ソースを参照

Slicer: list presets when a cloud preset type is empty (#3593)

- Bambu Cloud sends null for a preset type, or for its private or
  public list, when the account has nothing there. The Slice dialog,
  the Profiles page's cloud list and the filament-id map read it as
  nested dicts and failed, so the Slice dialog offered no presets.
- get_slicer_settings now returns every type as a dict whose private
  and public are lists of presets.
- Tests through the Slice dialog and Profiles page paths with null
  types and lists.

Tests: a missing maintenance log value is left to the csv writer

- _spreadsheet_text passes non-text values through since the
  spreadsheet export hardening, and the csv writer writes None as an
  empty cell. The merge of #3569 kept the old expectation.
maziggy 3 日 前
親
コミット
7e6e1e7980

+ 1 - 0
CHANGELOG.md

@@ -15,6 +15,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
 
 ### Fixed
+- **The Slice dialog lists presets when a Bambu Cloud account has none of one type (#3593, reported by @KevinMidboe)** — Bambu Cloud answers "nothing here" for a preset type with an empty value instead of an empty list, for example on an account with no filament presets of its own. Bambuddy did not handle that, so with a Bambu Cloud sign-in on the Profiles page the Slice dialog showed "Failed to load presets" and offered no presets at all, local ones included, and the Profiles page's cloud list failed the same way. Such a type now reads as empty, and the presets the account does have are listed.
 - **Monitor-only MQTT plugs are no longer switched by automation (#3583, reported by @paulleonartcalvo)** — Bambuddy only listens to an MQTT plug, so it cannot turn one on or off, but its Auto On and Auto Off were on by default, hidden in the plug's settings, and every automation tried anyway. With an MQTT plug for metering and a switchable plug on the same printer, the queue could pick the MQTT plug to power the printer on, fail, and hold the job with "the smart plug could not power it on". A printer whose only plug was an MQTT plug counted as one the queue could switch on, so its job said "Offline" instead of that it has no Auto On plug. Auto-off at print end, "auto off after this job", auto-off after drying, plug schedules and the AI failure detection's power-off all logged a failed turn-off for it. All of them now leave MQTT plugs alone, and an auto-off still pending on one from an earlier version is cleared at startup. Home Assistant scripts linked to a printer still run at print start as before.
 - **An MQTT plug keeps a print's energy across midnight (#3582, reported by @paulleonartcalvo)** — A print's energy is what the plug's counter went up by between its start and its end, and an MQTT plug had one energy value that Bambuddy used as both today's and the lifetime counter. Many devices publish a daily counter there (Tasmota's `ENERGY.Today`), which drops back to zero at midnight: a print that ran past midnight came out negative and got no energy or energy cost, or ended above its start and silently lost everything before midnight. MQTT plugs now have an **Energy JSON Path (lifetime)** and its own multiplier, read from the energy topic, for the counter that never resets (Tasmota's `ENERGY.Total`, in the same message). With it set, per-print energy and cost use the lifetime counter, the plug feeds the hourly snapshots behind the Statistics date filters and the all-time total, and the energy summary under Settings > Smart Plugs counts it in the lifetime total. A topic with only the lifetime counter still gets a Today, worked out from the snapshots. Without it, a plug reads its one energy value as before, so nothing changes for a topic that already carries a lifetime counter. Translated in all locales; wiki updated. Covered by backend and frontend tests.
 - **A first Git backup to an empty GitHub repository works (#3565, reported by @pike00)** — GitHub answers a repository with no commits with HTTP 409 "Git Repository is empty", and Bambuddy stopped there with "Failed to get branch ref", although Test Connection passed. Its fallback for an empty repository could not have helped either: it builds the first commit from blobs and trees, and GitHub refuses those too until the repository has a commit. The first backup now makes that commit through GitHub's Contents API, which writes one file, and pushes the rest on top, so no README or placeholder file is needed. Any other 409 is still reported as an error. Wiki updated.

+ 25 - 1
backend/app/services/bambu_cloud.py

@@ -272,6 +272,30 @@ def _cloud_json(response: httpx.Response):
         ) from None
 
 
+# The preset types in the cloud's listing, under the names it uses for them.
+_SLICER_SETTING_TYPES = ("filament", "printer", "print")
+
+
+def _slicer_settings_listing(data: object) -> dict:
+    """The cloud's preset listing with every type a dict and its ``private``
+    and ``public`` lists always lists of dicts (#3593).
+
+    The cloud sends ``null`` for a type, or for one of its lists, when the
+    account has nothing there. Every caller reads the listing as nested dicts,
+    so a null here took down the Slice dialog's preset list for an account
+    with no presets of one type.
+    """
+    listing = dict(data) if isinstance(data, dict) else {}
+    for key in _SLICER_SETTING_TYPES:
+        section = listing.get(key)
+        section = dict(section) if isinstance(section, dict) else {}
+        for tier in ("private", "public"):
+            entries = section.get(tier)
+            section[tier] = [e for e in entries if isinstance(e, dict)] if isinstance(entries, list) else []
+        listing[key] = section
+    return listing
+
+
 _shared_http_client: httpx.AsyncClient | None = None
 
 
@@ -836,7 +860,7 @@ class BambuCloudService:
             if await self._note_response(response):
                 raise BambuCloudAuthError("Bambu Cloud session expired")
             if response.status_code == 200:
-                return data
+                return _slicer_settings_listing(data)
 
             raise BambuCloudError(f"Failed to get settings: {response.status_code}")
 

+ 97 - 0
backend/tests/unit/test_cloud_preset_listing_nulls_3593.py

@@ -0,0 +1,97 @@
+"""A Bambu Cloud preset listing with null types or lists still lists presets (#3593).
+
+The cloud sends ``null`` for a preset type, or for its private or public list,
+when the account has nothing there. The Slice dialog's preset list and the
+Profiles page's cloud list read the listing as nested dicts and failed on it,
+so one empty type cost every preset, local ones included.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.app.api.routes import cloud as cloud_routes, slicer_presets as sp
+from backend.app.services.bambu_cloud import BambuCloudService, _slicer_settings_listing
+
+# Shaped like an account with no filament presets, only stock printers and one
+# process preset of its own.
+LISTING = {
+    "filament": None,
+    "printer": {"private": None, "public": [{"setting_id": "GP1", "name": "Bambu Lab X1C 0.4 nozzle"}]},
+    "print": {"private": [{"setting_id": "PP1", "name": "My 0.2mm"}], "public": None},
+}
+
+
+def _cloud_answering(body) -> BambuCloudService:
+    service = BambuCloudService()
+    service.access_token = "test-token"
+    response = MagicMock()
+    response.status_code = 200
+    response.json.return_value = body
+    service._client = MagicMock()
+    service._client.get = AsyncMock(return_value=response)
+    service.close = AsyncMock()
+    return service
+
+
+def _user() -> MagicMock:
+    user = MagicMock(id=1)
+    user.has_permission = MagicMock(return_value=True)
+    return user
+
+
+async def test_the_slice_dialog_lists_the_presets_the_account_has():
+    sp._cloud_cache.clear()
+    with (
+        patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
+        patch.object(sp, "BambuCloudService", return_value=_cloud_answering(LISTING)),
+    ):
+        slots, status = await sp._fetch_cloud_presets(MagicMock(), _user())
+    sp._cloud_cache.clear()
+
+    assert status == "ok"
+    assert [p.name for p in slots["printer"]] == ["Bambu Lab X1C 0.4 nozzle"]
+    assert [p.name for p in slots["process"]] == ["My 0.2mm"]
+    assert slots["filament"] == []
+
+
+async def test_the_profiles_page_lists_the_presets_the_account_has():
+    service = _cloud_answering(LISTING)
+    with patch.object(cloud_routes, "build_authenticated_cloud", AsyncMock(return_value=service)):
+        result = await cloud_routes.get_slicer_settings(db=MagicMock(), current_user=None)
+
+    assert [s.name for s in result.printer] == ["Bambu Lab X1C 0.4 nozzle"]
+    assert [s.name for s in result.process] == ["My 0.2mm"]
+    assert result.filament == []
+
+
+@pytest.mark.parametrize(
+    ("body", "expected_printer_private"),
+    [
+        (None, []),
+        ([], []),
+        ({"printer": "unexpected"}, []),
+        ({"printer": {"private": "unexpected"}}, []),
+        ({"printer": {"private": [None, "x", {"setting_id": "P1"}]}}, [{"setting_id": "P1"}]),
+    ],
+)
+def test_every_type_reads_as_lists_of_presets(body, expected_printer_private):
+    listing = _slicer_settings_listing(body)
+
+    for key in ("filament", "printer", "print"):
+        assert isinstance(listing[key]["private"], list)
+        assert isinstance(listing[key]["public"], list)
+    assert listing["printer"]["private"] == expected_printer_private
+
+
+def test_a_full_listing_is_kept_as_it_is():
+    body = {
+        "filament": {"private": [{"setting_id": "F1"}], "public": [{"setting_id": "F2"}]},
+        "printer": {"private": [], "public": []},
+        "print": {"private": [], "public": []},
+        "message": "success",
+    }
+
+    assert _slicer_settings_listing(body) == body