silpo-agent-cli 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,325 @@
1
+ """Cart Editor: manually swap one cart item for another (see prd_reorder_
2
+ optimizer.md's Cart Editor section / issue #30). The only capability in this
3
+ project besides `reorder` itself that mutates the real cart outside the
4
+ reorder pipeline.
5
+
6
+ Real schema (see docs/mcp_schema.md's "Cart tools" section, live-verified):
7
+ - `silpo_remove_cart_products({"shoppingCartId", "products": [{"productId"}]})`
8
+ - `silpo_add_or_update_cart_products` -- same real payload shape
9
+ `cart_writer.py` already established: `{"shoppingCartId", "products":
10
+ [{"productId", "companyId", "branchId", "quantity", "addQuantity",
11
+ "comment"}]}`. There is no separate "swap this line for a different
12
+ product" call -- remove-then-add is the only way to do that (see
13
+ `swap_cart_item`). Changing an *existing* line's quantity in place doesn't
14
+ need a remove at all, though: `cart_writer.py`'s own doc note says
15
+ `addQuantity: True` "adds to, rather than overwrites, any existing
16
+ quantity" -- the corollary, confirmed by `set_cart_item_quantity` below, is
17
+ that `addQuantity: False` with the line's own `productId` overwrites it,
18
+ i.e. sets the absolute quantity.
19
+
20
+ Products are addressed by **slug**, not by product id (issue #50) -- see
21
+ `resolve_product_by_slug` below and docs/mcp_schema.md's issue #50 section.
22
+ Two resolution paths exist, for two different situations:
23
+
24
+ - `--replace <old-slug> <new-slug>` resolves the new product with
25
+ `silpo_get_product_details`, a real per-slug lookup. Deterministic, and it
26
+ returns `companyId`/`branchId` on the record itself.
27
+ - the interactive flow's free-text search still goes through
28
+ `silpo_find_products_batch` (same pattern `substitution_resolver.py`
29
+ uses), because there the user types words, not a slug. Plastic-bag
30
+ candidates (`cart_writer.py`'s `_is_plastic_bag` heuristic) are filtered
31
+ out of those results before they're ever shown.
32
+
33
+ No-partial-mutation guarantee: `swap_cart_item` validates the old slug is
34
+ actually a line in the cart (via `CartContext.products`, no extra network
35
+ call needed -- same pattern the Cart Writer's non-empty-cart guard uses) and
36
+ that the resolved new product record actually has an id, before either the
37
+ remove or the add call is made. An old slug not in the cart, or a new product
38
+ record with no id, raises `CartEditError` and makes zero MCP calls.
39
+
40
+ Failure *between* the two calls (remove succeeds, add doesn't) is a second,
41
+ distinct risk the above guarantee doesn't cover -- a bare remove-then-add
42
+ with no error handling would silently drop the old item on the floor if the
43
+ add call blows up. `auth.py`'s `MCPClient.call()` signals a failed tool call
44
+ by raising `MCPError` (or, for a lower-level transport problem, some other
45
+ exception) rather than returning an error payload -- see `auth.py`'s
46
+ `call_tool_http`/`_unwrap_tool_result`. `swap_cart_item` catches exactly
47
+ that: if the add call raises anything, it attempts one best-effort re-add of
48
+ the old item (same productId/companyId/branchId/quantity just removed) as a
49
+ rollback, then always raises `CartEditError` either way -- worded
50
+ differently depending on whether the rollback itself worked -- rather than
51
+ ever returning normally with the cart left in a state the caller doesn't
52
+ know about.
53
+ """
54
+
55
+ from dataclasses import dataclass
56
+
57
+ from silpo_agent.cart_context import CartContext
58
+
59
+ _PLASTIC_BAG_KEYWORD = "пакет"
60
+
61
+
62
+ class CartEditError(Exception):
63
+ """A user-facing cart-edit failure (old id not in cart, unresolvable
64
+ replacement). Raised before any mutating MCP call is made."""
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class CartEditResult:
69
+ # Issue #50: reported in slugs, not UUIDs -- slug is what this CLI
70
+ # publishes and what `--replace` takes, so it's what the user sees back.
71
+ # removed_slug is None for a pure add (--add): nothing was removed.
72
+ removed_slug: str | None
73
+ added_slug: str | None
74
+ added_price: float
75
+ # Only set by set_cart_item_quantity (--qty); every other constructor
76
+ # leaves these at their default, so existing call sites are unaffected.
77
+ old_quantity: float | None = None
78
+ new_quantity: float | None = None
79
+ # Only set by remove_cart_item (a pure delete has no added_price to
80
+ # report); defaults to 0.0 so swap/add's existing keyword-only
81
+ # construction sites are unaffected.
82
+ removed_price: float = 0.0
83
+
84
+
85
+ def _is_plastic_bag(product: dict) -> bool:
86
+ name = product.get("name") or ""
87
+ return _PLASTIC_BAG_KEYWORD in name.lower()
88
+
89
+
90
+ def _find_cart_product(cart_context: CartContext, slug: str) -> dict | None:
91
+ """Cart lines are addressed by slug (issue #50). Matched locally against
92
+ `CartContext.products` -- no network call, same as when this matched on
93
+ `productId`."""
94
+ return next((p for p in cart_context.products if p.get("slug") == slug), None)
95
+
96
+
97
+ def search_replacement_candidates(client, cart_context: CartContext, query: str) -> list[dict]:
98
+ """Free-text product search via `silpo_find_products_batch` (same real
99
+ call shape `substitution_resolver.py`'s `_check_availability` already
100
+ uses), plastic-bag candidates filtered out before returning."""
101
+ response = (
102
+ client.call(
103
+ "silpo_find_products_batch",
104
+ {
105
+ "branchId": cart_context.branch_id,
106
+ "deliveryType": cart_context.delivery_type,
107
+ "timeslotStart": cart_context.timeslot_start,
108
+ "timeslotEnd": cart_context.timeslot_end,
109
+ "products": [query],
110
+ "limit": 10,
111
+ },
112
+ )
113
+ or {}
114
+ )
115
+ queries = response.get("queries") or []
116
+ query_result = next((q for q in queries if q.get("query") == query), queries[0] if queries else {})
117
+ candidates = query_result.get("products") or []
118
+ return [candidate for candidate in candidates if not _is_plastic_bag(candidate)]
119
+
120
+
121
+ def resolve_product_by_slug(client, cart_context: CartContext, slug: str) -> dict | None:
122
+ """Resolves a slug to a full product record via `silpo_get_product_details`
123
+ (issue #50). Returns None if the slug doesn't resolve.
124
+
125
+ Real live-verified request/response (docs/mcp_schema.md): the call takes
126
+ `{branchId, slug, deliveryType, timeslotStart, timeslotEnd}` and answers
127
+ `{"success", "product": {"id", "name", "slug", "price", "oldPrice",
128
+ "stock", "available", "companyId", "branchId", ...}}` -- note the
129
+ `"product"` wrapper, and that `companyId`/`branchId` come back on the
130
+ record itself. That last part matters: it means the replacement path
131
+ never has to fall back to `CartContext.company_id`, which is `None` on
132
+ the issue #29 no-shipments path.
133
+
134
+ This replaces the previous resolution path, which used a product id as a
135
+ free-text `silpo_find_products_batch` query and matched a candidate by
136
+ exact id -- indirect, and unreliable for exactly the reason issue #18
137
+ documents (a raw UUID as search text usually returns nothing)."""
138
+ response = (
139
+ client.call(
140
+ "silpo_get_product_details",
141
+ {
142
+ "branchId": cart_context.branch_id,
143
+ "slug": slug,
144
+ "deliveryType": cart_context.delivery_type,
145
+ "timeslotStart": cart_context.timeslot_start,
146
+ "timeslotEnd": cart_context.timeslot_end,
147
+ },
148
+ )
149
+ or {}
150
+ )
151
+ return response.get("product") or None
152
+
153
+
154
+ def _add_call(client, cart_context: CartContext, product_id: str, company_id, branch_id, quantity, add_quantity: bool = True):
155
+ return client.call(
156
+ "silpo_add_or_update_cart_products",
157
+ {
158
+ "shoppingCartId": cart_context.shopping_cart_id,
159
+ "products": [
160
+ {
161
+ "productId": product_id,
162
+ "companyId": company_id,
163
+ "branchId": branch_id,
164
+ "quantity": quantity,
165
+ "addQuantity": add_quantity,
166
+ }
167
+ ],
168
+ },
169
+ )
170
+
171
+
172
+ def swap_cart_item(client, cart_context: CartContext, old_slug: str, new_product: dict) -> CartEditResult:
173
+ """Removes the cart line whose slug is `old_slug` and adds `new_product`
174
+ (a full resolved product record -- id/companyId/branchId/price, e.g.
175
+ from `resolve_product_by_slug`). Preserves the old line's quantity.
176
+ Raises `CartEditError` -- making zero MCP calls -- if `old_slug` isn't
177
+ actually in the cart or `new_product` has no id.
178
+
179
+ Slugs in, slugs out (issue #50): the product UUIDs the MCP calls need are
180
+ read off the matched cart line and off `new_product`, never asked of the
181
+ caller.
182
+
183
+ If the add call fails after the remove already succeeded, attempts a
184
+ best-effort rollback (re-adding the old item) and always raises
185
+ `CartEditError` describing what happened -- see module docstring."""
186
+ # A missing slug must never reach the match: `_find_cart_product`
187
+ # compares `p.get("slug") == slug`, so `None` would match the first
188
+ # slug-less cart line and silently swap the wrong item. Guarded here
189
+ # rather than in each caller -- both the interactive flow and
190
+ # `--replace` route through this function.
191
+ if not old_slug:
192
+ raise CartEditError("That cart item has no slug, so it can't be addressed for replacement.")
193
+
194
+ old_item = _find_cart_product(cart_context, old_slug)
195
+ if old_item is None:
196
+ raise CartEditError(f"{old_slug!r} is not in your cart.")
197
+
198
+ old_product_id = old_item.get("productId")
199
+ new_id = new_product.get("id") or new_product.get("productId")
200
+ if not new_id:
201
+ raise CartEditError("Replacement product has no id; cannot add to cart.")
202
+
203
+ new_company_id = new_product.get("companyId") or cart_context.company_id
204
+ new_branch_id = new_product.get("branchId") or cart_context.branch_id
205
+ old_company_id = old_item.get("companyId") or cart_context.company_id
206
+ old_branch_id = old_item.get("branchId") or cart_context.branch_id
207
+ quantity = old_item.get("quantity") or 1
208
+
209
+ client.call(
210
+ "silpo_remove_cart_products",
211
+ {"shoppingCartId": cart_context.shopping_cart_id, "products": [{"productId": old_product_id}]},
212
+ )
213
+
214
+ try:
215
+ _add_call(client, cart_context, new_id, new_company_id, new_branch_id, quantity)
216
+ except Exception as add_exc: # noqa: BLE001 -- deliberately broad: a raw
217
+ # transport failure (network error) surfaces as a plain exception
218
+ # from client.call(), not just MCPError (see auth.py's call_tool_http
219
+ # -- _post_json isn't wrapped), and both must trigger the rollback.
220
+ _attempt_rollback_and_raise(
221
+ client, cart_context, old_slug, old_product_id, old_company_id, old_branch_id, quantity, new_id, add_exc
222
+ )
223
+
224
+ return CartEditResult(
225
+ removed_slug=old_slug,
226
+ added_slug=new_product.get("slug"),
227
+ added_price=new_product.get("price", 0.0),
228
+ )
229
+
230
+
231
+ def add_cart_item(client, cart_context: CartContext, new_product: dict, quantity: int = 1) -> CartEditResult:
232
+ """Adds `new_product` (a full resolved product record, e.g. from
233
+ `resolve_product_by_slug`) as a brand-new cart line. No removal
234
+ involved, so unlike `swap_cart_item` there's no partial-mutation
235
+ rollback case to handle.
236
+
237
+ Raises `CartEditError` -- making zero MCP calls -- if the product has no
238
+ id, or if its productId already matches a line already in the cart:
239
+ reorder's `addQuantity=True` blindly re-adding an already-present item
240
+ silently doubled its quantity (see cart_writer.py's dedupe fix), and
241
+ --add must not repeat that mistake. Point the user at --replace or
242
+ reorder instead, rather than guessing whether they wanted +N."""
243
+ new_id = new_product.get("id") or new_product.get("productId")
244
+ if not new_id:
245
+ raise CartEditError("Product has no id; cannot add to cart.")
246
+
247
+ if any(p.get("productId") == new_id for p in cart_context.products):
248
+ label = new_product.get("slug") or new_id
249
+ raise CartEditError(
250
+ f"{label!r} is already in your cart; use `cart edit --replace` to swap it "
251
+ "or `reorder` to restock it, rather than adding a second line."
252
+ )
253
+
254
+ new_company_id = new_product.get("companyId") or cart_context.company_id
255
+ new_branch_id = new_product.get("branchId") or cart_context.branch_id
256
+
257
+ _add_call(client, cart_context, new_id, new_company_id, new_branch_id, quantity)
258
+
259
+ return CartEditResult(
260
+ removed_slug=None,
261
+ added_slug=new_product.get("slug"),
262
+ added_price=new_product.get("price", 0.0),
263
+ )
264
+
265
+
266
+ def set_cart_item_quantity(client, cart_context: CartContext, slug: str, quantity: float) -> CartEditResult:
267
+ """Sets an existing cart line's quantity to the absolute value `quantity`
268
+ (a set, not a delta). Raises `CartEditError` -- making zero MCP calls --
269
+ if `slug` isn't a line in the cart."""
270
+ item = _find_cart_product(cart_context, slug)
271
+ if item is None:
272
+ raise CartEditError(f"{slug!r} is not in your cart.")
273
+
274
+ old_quantity = item.get("quantity") or 0
275
+ company_id = item.get("companyId") or cart_context.company_id
276
+ branch_id = item.get("branchId") or cart_context.branch_id
277
+
278
+ _add_call(client, cart_context, item.get("productId"), company_id, branch_id, quantity, add_quantity=False)
279
+
280
+ return CartEditResult(
281
+ removed_slug=None,
282
+ added_slug=slug,
283
+ added_price=item.get("price", 0.0),
284
+ old_quantity=old_quantity,
285
+ new_quantity=quantity,
286
+ )
287
+
288
+
289
+ def remove_cart_item(client, cart_context: CartContext, slug: str) -> CartEditResult:
290
+ """Removes the cart line whose slug is `slug`, adding nothing back --
291
+ the delete-only counterpart to `swap_cart_item`. Raises `CartEditError`
292
+ -- making zero MCP calls -- if `slug` isn't actually a line in the cart,
293
+ same guard `swap_cart_item` applies to its old-slug argument."""
294
+ item = _find_cart_product(cart_context, slug)
295
+ if item is None:
296
+ raise CartEditError(f"{slug!r} is not in your cart.")
297
+
298
+ client.call(
299
+ "silpo_remove_cart_products",
300
+ {"shoppingCartId": cart_context.shopping_cart_id, "products": [{"productId": item.get("productId")}]},
301
+ )
302
+
303
+ return CartEditResult(
304
+ removed_slug=slug, added_slug=None, added_price=0.0, removed_price=item.get("price", 0.0)
305
+ )
306
+
307
+
308
+ def _attempt_rollback_and_raise(
309
+ client, cart_context, old_slug, old_product_id, old_company_id, old_branch_id, quantity, new_id, add_exc
310
+ ):
311
+ """Removed the `old_slug` line but the add of `new_id` blew up
312
+ (`add_exc`). Best-effort re-add of the old item, then always raise -- the
313
+ caller must never see a normal return with the cart silently missing an
314
+ item. Messages name the slug, the identifier the user actually holds."""
315
+ try:
316
+ _add_call(client, cart_context, old_product_id, old_company_id, old_branch_id, quantity)
317
+ except Exception: # noqa: BLE001 -- same broad-catch reasoning as above
318
+ raise CartEditError(
319
+ f"Removed {old_slug!r}, failed to add {new_id!r} ({add_exc}), and failed to restore "
320
+ f"{old_slug!r} -- your cart may be missing an item, please check manually."
321
+ ) from add_exc
322
+
323
+ raise CartEditError(
324
+ f"Removed {old_slug!r} but failed to add {new_id!r} ({add_exc}); restored {old_slug!r} to your cart."
325
+ ) from add_exc
@@ -0,0 +1,97 @@
1
+ """Cart Viewer: read-only `cart` subcommand (issue #27, part of #26). Formats
2
+ an already-resolved `CartContext` (see cart_context.py) into a human-readable
3
+ report -- no MCP calls of its own, no new schema assumptions.
4
+
5
+ Real schema (docs/mcp_schema.md's "Cart tools" section): each cart product
6
+ (`CartContext.products`, from `cart.shipments[0].products[]`) carries
7
+ `name`/`quantity`/`price`/`stock`. The amount actually payable is
8
+ `cart.calculation.totalAfterDiscounts`, never the pre-discount `total` --
9
+ `CartContext.total_after_discounts` carries this through (added for this
10
+ ticket; CartContext previously exposed no total at all).
11
+ """
12
+
13
+ from silpo_agent.address_resolver import _build_label
14
+ from silpo_agent.cart_context import CartContext
15
+ from silpo_agent.timeslot_format import format_timeslot
16
+
17
+
18
+ def _or_unknown(value):
19
+ """"?" for a missing/None field instead of rendering the literal string
20
+ "None" -- a real response with a gap in one field shouldn't make the
21
+ whole line look broken."""
22
+ return "?" if value is None else value
23
+
24
+
25
+ def format_cart(context: CartContext) -> list[str]:
26
+ lines: list[str] = []
27
+
28
+ if context.address:
29
+ lines.append(f"Delivering to: {_build_label(context.address)}")
30
+ if context.delivery_type:
31
+ lines.append(f"Delivery type: {context.delivery_type}")
32
+ if context.timeslot_start:
33
+ lines.append(f"Timeslot: {format_timeslot(context.timeslot_start, context.timeslot_end)}")
34
+ else:
35
+ lines.append("Timeslot: not set yet -- run 'silpo-agent delivery' to choose one")
36
+
37
+ # A cart with only zero-quantity line items (if the live API ever
38
+ # returns that) is treated as non-empty here -- context.products is
39
+ # non-empty, so it's listed with "x0" rather than folded into the
40
+ # "empty cart" message. Not special-cased: an edge case that hasn't
41
+ # been observed live, and "x0" is still an accurate, non-crashing render.
42
+ if not context.products:
43
+ lines.append("Your cart is empty.")
44
+ else:
45
+ lines.append(f"Cart ({len(context.products)} item(s)):")
46
+ for product in context.products:
47
+ name = product.get("name") or product.get("productId") or "?"
48
+ quantity = _or_unknown(product.get("quantity"))
49
+ price = _or_unknown(product.get("price"))
50
+ stock = _or_unknown(product.get("stock"))
51
+ # Issue #6: a weighted cart line's `quantity` is already the real
52
+ # kg amount (docs/mcp_schema.md's order-history section confirms
53
+ # fractional kg quantities like 1.232 for weighted goods) -- the
54
+ # line's own `ratio` field (e.g. "100г") is unreliable for a
55
+ # weighted item priced per kg, so it's ignored in favor of a
56
+ # hardcoded "кг" unit. Driven by this cart line's own `weighted`
57
+ # flag only, not a cross-call reconciliation with
58
+ # resolve_product_by_slug's separate `ratio`.
59
+ if product.get("weighted") and isinstance(quantity, (int, float)):
60
+ qty_display = f"{float(quantity)} кг"
61
+ else:
62
+ qty_display = f"x{quantity}"
63
+ line = f" - {name} {qty_display} @ {price} (stock: {stock})"
64
+ # Issue #50: the slug is this CLI's public product identifier --
65
+ # `cart edit --replace` takes slugs, and this is the only command
66
+ # that lists what's currently in the cart, so without it the
67
+ # read/act loop can't be closed. Omitted entirely when absent:
68
+ # a "?" would be an identifier that's guaranteed to fail.
69
+ slug = product.get("slug")
70
+ if slug:
71
+ line += f" {slug}"
72
+ lines.append(line)
73
+
74
+ if context.validations:
75
+ lines.append("Validations:")
76
+ products_by_id = {p.get("productId"): p for p in context.products}
77
+ for validation in context.validations:
78
+ level = _or_unknown(validation.get("level"))
79
+ message = _or_unknown(validation.get("message"))
80
+ line = f" [{level}] {message}"
81
+ # Issue #04: resolve a product-scoped validation's opaque
82
+ # productId to the cart's own name/slug so the user knows which
83
+ # line item tripped it -- unresolvable context (no dict, no
84
+ # match) falls back to the raw line unchanged.
85
+ if validation.get("type") == "product" and isinstance(validation.get("context"), dict):
86
+ product = products_by_id.get(validation["context"].get("productId"))
87
+ if product:
88
+ line += f" — {product.get('name')} ({product.get('slug')})"
89
+ lines.append(line)
90
+
91
+ if context.total_after_discounts is not None:
92
+ lines.append(f"Payable total: {context.total_after_discounts:.2f}")
93
+
94
+ if context.bonus_available is not None:
95
+ lines.append(f"Bonus available: {context.bonus_available:.2f}")
96
+
97
+ return lines
@@ -0,0 +1,203 @@
1
+ """Cart Writer (see prd_reorder_optimizer.md's Cart Writer section). Before
2
+ adding anything, reads the current cart's real contents from the caller's
3
+ already-resolved `CartContext` (issue #17's `resolve_cart_context`) and
4
+ warns the user if it already has items from a prior session (CONTEXT.md's
5
+ "Non-empty cart guard" -- warn-and-proceed-or-abort, never auto-clear or
6
+ silently merge). Applies the optional `--budget` cap by trimming the
7
+ lowest-priority Typical Items (by frequency) until the existing cart's own
8
+ payable total (`CartContext.total_after_discounts`) plus the new items fits,
9
+ if set -- otherwise just totals and reports. A reorder onto a non-empty
10
+ cart counts what's already there against the budget, rather than treating
11
+ `--budget` as a cap on the new items alone. Adds the (possibly trimmed) items via
12
+ `silpo_add_or_update_cart_products` and reports what was added, trimmed, and
13
+ the total. Cart-only: never calls checkout/payment (CONTEXT.md's "Reorder
14
+ flow -- cart-only scope").
15
+
16
+ Real schema (see ../../docs/mcp_schema.md's "Cart tools" section,
17
+ live-verified):
18
+ - `silpo_get_my_shopping_cart` returns only `{"success", "shoppingCartId"}`
19
+ -- no cart contents, so it is not read here at all. The non-empty-cart
20
+ guard instead reads `CartContext.products` (issue #17's resolver, which
21
+ already made the `silpo_get_my_shopping_cart` -> `silpo_get_shopping_cart_by_id`
22
+ round trip and carries `cart.shipments[0].products`), avoiding a
23
+ duplicate network call.
24
+ - `silpo_add_or_update_cart_products` takes `{"shoppingCartId", "products":
25
+ [{"productId", "companyId", "branchId", "quantity", "addQuantity", "comment"}]}`.
26
+ `companyId`/`branchId` come from the Typical Item (Order Aggregator, #16)
27
+ or a substitution/promo-resolved item; if either is missing (e.g. a
28
+ substituted item that didn't carry it through) this falls back to the
29
+ CartContext's own branch/company, since a cart's items all live under one
30
+ branch/company already. Each Typical Item is added at `item.quantity`
31
+ (defaults to 1) with `addQuantity=True` (adds to, rather than overwrites,
32
+ any existing quantity) -- most sources still leave this at the default 1,
33
+ but norm top-up items (see norm_top_up.py) carry a real computed quantity,
34
+ rounded via `round_to_step` for weighted goods.
35
+ `comment` is always null; nothing upstream produces one.
36
+ - Plastic-bag-style items (пакет / пакет з пакетів / пакет-майка) are
37
+ always skipped before the add call, per the tool's own guidance -- see
38
+ `_is_plastic_bag`. Matched case-insensitively on the item's `name`
39
+ containing "пакет"; this is a heuristic (Ukrainian-only, substring match)
40
+ -- good enough for the known plastic-bag SKUs in order history, but an
41
+ item that lost its `name` during substitution (issue #18's territory)
42
+ won't be caught. ponytail: substring-on-name heuristic, revisit with a
43
+ dedicated category/tag from the product record if false negatives show up.
44
+
45
+ The report's total is still computed locally from each item's last known
46
+ price rather than trusting a total in the add call's response, since that
47
+ response shape remains unverified (mutating tool, not exercised live).
48
+ """
49
+
50
+ import math
51
+ from dataclasses import dataclass, field
52
+
53
+ from silpo_agent.cart_context import CartContext
54
+ from silpo_agent.order_aggregator import TypicalItem
55
+
56
+ _PLASTIC_BAG_KEYWORD = "пакет"
57
+
58
+
59
+ def round_to_step(raw_quantity: float, *, weighted: bool, step: float | None) -> float:
60
+ """Rounds a raw desired quantity to a value the cart will accept.
61
+ Weighted goods must be added as a multiple of the product's own
62
+ `addToBasketStep` (docs/mcp_schema.md's cart-tools note, e.g. 0.35 for
63
+ loose cucumbers); other goods round up to the next whole unit.
64
+ """
65
+ if weighted and step:
66
+ return round(round(raw_quantity / step) * step, 6)
67
+ return math.ceil(raw_quantity)
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class CartReport:
72
+ items_added: list[tuple[str, float]]
73
+ total: float
74
+ trimmed: list[tuple[str, float]] = field(default_factory=list)
75
+ aborted: bool = False
76
+
77
+
78
+ def _is_plastic_bag(item: TypicalItem) -> bool:
79
+ return bool(item.name) and _PLASTIC_BAG_KEYWORD in item.name.lower()
80
+
81
+
82
+ def _trim_to_budget(
83
+ items: list[TypicalItem], budget: float, already_spent: float = 0.0
84
+ ) -> tuple[list[TypicalItem], list[TypicalItem]]:
85
+ """Drops lowest-priority (lowest frequency) items first until
86
+ `already_spent` (the existing cart's own payable total, for a reorder
87
+ onto a non-empty cart) plus the new items' total fits under `budget`.
88
+ Returns (kept, trimmed), both in original order.
89
+ """
90
+ total = already_spent + sum(item.last_known_price for item in items)
91
+ if total <= budget:
92
+ return items, []
93
+
94
+ drop_order = sorted(items, key=lambda item: (item.frequency, item.product_id))
95
+ dropped_ids: set[str] = set()
96
+ for item in drop_order:
97
+ if total <= budget:
98
+ break
99
+ dropped_ids.add(item.product_id)
100
+ total -= item.last_known_price
101
+
102
+ kept = [item for item in items if item.product_id not in dropped_ids]
103
+ trimmed = [item for item in items if item.product_id in dropped_ids]
104
+ return kept, trimmed
105
+
106
+
107
+ def trim_by_source_priority(
108
+ source_groups: list[tuple[str, list[TypicalItem]]], budget: float, already_spent: float = 0.0
109
+ ) -> tuple[list[TypicalItem], list[tuple[str, str, float]]]:
110
+ """Cascading budget trim across ordered item sources (smart-cart's
111
+ `--budget`, ticket 05). `source_groups` is `[(label, items), ...]`
112
+ listed drop-first-to-drop-last (e.g. norm items before favorites-deals
113
+ before typical items): an earlier source is trimmed down to nothing
114
+ before a single item from a later source is touched. Each source's own
115
+ trim reuses `_trim_to_budget`'s existing lowest-frequency-then-
116
+ product_id tie-break, threading the running spent-so-far through as its
117
+ `already_spent` -- so the last group gets exactly the same trim
118
+ `write_cart`'s single-source `budget=` path already gives `reorder`.
119
+ Returns `(kept_items, trimmed)` where `trimmed` is
120
+ `[(source_label, product_id, price), ...]`, so the report can say which
121
+ source each dropped item came from.
122
+
123
+ Each group's own budget must reserve room for every *later* (higher-
124
+ priority) group's full total, otherwise a naive forward pass would fill
125
+ the budget with the first (lowest-priority) group and starve the last
126
+ one -- so this trims each group against `budget - sum(later groups'
127
+ totals)`, computed as a suffix sum, not against the raw `budget`.
128
+ """
129
+ group_totals = [sum(item.last_known_price for item in items) for _, items in source_groups]
130
+ later_totals = [0.0] * len(source_groups)
131
+ running = 0.0
132
+ for i in range(len(source_groups) - 1, -1, -1):
133
+ later_totals[i] = running
134
+ running += group_totals[i]
135
+
136
+ kept: list[TypicalItem] = []
137
+ trimmed: list[tuple[str, str, float]] = []
138
+ spent = already_spent
139
+ for i, (label, items) in enumerate(source_groups):
140
+ group_kept, group_trimmed = _trim_to_budget(items, budget - later_totals[i], spent)
141
+ kept.extend(group_kept)
142
+ trimmed.extend((label, item.product_id, item.last_known_price) for item in group_trimmed)
143
+ spent += sum(item.last_known_price for item in group_kept)
144
+ return kept, trimmed
145
+
146
+
147
+ def write_cart(
148
+ client,
149
+ typical_items: list[TypicalItem],
150
+ cart_context: CartContext,
151
+ *,
152
+ budget: float | None = None,
153
+ input_fn=None,
154
+ print_fn=None,
155
+ ) -> CartReport:
156
+ input_fn = input_fn or input
157
+ print_fn = print_fn or print
158
+
159
+ if not typical_items:
160
+ return CartReport(items_added=[], total=0.0)
161
+
162
+ purchasable_items = [item for item in typical_items if not _is_plastic_bag(item)]
163
+
164
+ if cart_context.products:
165
+ print_fn("Warning: your cart already has items from a previous session.")
166
+ answer = input_fn("Add to the existing cart anyway? [y/N] ").strip().lower()
167
+ if answer not in ("y", "yes"):
168
+ print_fn("Aborted: cart left unchanged.")
169
+ return CartReport(items_added=[], total=0.0, aborted=True)
170
+
171
+ existing_ids = {p.get("productId") for p in cart_context.products}
172
+ purchasable_items = [item for item in purchasable_items if item.product_id not in existing_ids]
173
+
174
+ items_to_add = purchasable_items
175
+ trimmed_items: list[TypicalItem] = []
176
+ if budget is not None:
177
+ already_spent = cart_context.total_after_discounts or 0.0
178
+ items_to_add, trimmed_items = _trim_to_budget(purchasable_items, budget, already_spent)
179
+ trimmed = [(item.product_id, item.last_known_price) for item in trimmed_items]
180
+
181
+ if not items_to_add:
182
+ return CartReport(items_added=[], total=0.0, trimmed=trimmed)
183
+
184
+ client.call(
185
+ "silpo_add_or_update_cart_products",
186
+ {
187
+ "shoppingCartId": cart_context.shopping_cart_id,
188
+ "products": [
189
+ {
190
+ "productId": item.product_id,
191
+ "companyId": item.company_id or cart_context.company_id,
192
+ "branchId": item.branch_id or cart_context.branch_id,
193
+ "quantity": item.quantity,
194
+ "addQuantity": True,
195
+ }
196
+ for item in items_to_add
197
+ ],
198
+ },
199
+ )
200
+
201
+ items_added = [(item.product_id, item.last_known_price) for item in items_to_add]
202
+ total = sum(price for _, price in items_added)
203
+ return CartReport(items_added=items_added, total=total, trimmed=trimmed)