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,66 @@
1
+ """Coupons Lister: read-only `coupons` subcommand (issue #36, part of #34).
2
+ Lists the user's active loyalty coupons with their buying condition,
3
+ validity dates, and reward. Informational only -- makes no mutating MCP
4
+ calls.
5
+
6
+ Real schema (live-verified, see ../../docs/mcp_schema.md's "Promo / loyalty
7
+ tools" section):
8
+ - `silpo_get_my_coupons()` -> `{"success", "summary", "coupons": [{"id",
9
+ "active", "useWay", "beginDate", "endDate", "description", "limitText",
10
+ "warningText", "image"}]}`.
11
+ - `silpo_get_coupon_details({"businessCouponId": id})` -> `{"success",
12
+ "coupon": {"id", "active", "state", "useWay", "beginDate", "endDate",
13
+ "usedCount", "description", "limitText", "warningText", "rewardText",
14
+ "rewardValue", "image"}}`, keyed off `coupons[].id`.
15
+
16
+ Scope decision: only active coupons get a details lookup -- an inactive
17
+ coupon's reward isn't actionable, same scope-narrowing style as
18
+ promo_optimizer.py (issue #20).
19
+
20
+ Explicitly does NOT attempt to match a coupon's free-text `description`
21
+ (the buying condition, e.g. "за купівлю вершкового масла") against cart
22
+ contents, search results, or promo alternatives. No coupon exposes a linked
23
+ product id, only descriptive text -- this exact heuristic was already
24
+ rejected for promo alternatives (see docs/mcp_schema.md's "Promo / loyalty
25
+ tools" section and promo_optimizer.py's module docstring).
26
+ """
27
+
28
+ from dataclasses import dataclass
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class CouponLine:
33
+ description: str
34
+ begin_date: str | None
35
+ end_date: str | None
36
+ reward_text: str | None
37
+ reward_value: float | None
38
+
39
+ def format(self) -> str:
40
+ dates = f"{self.begin_date or '?'} - {self.end_date or '?'}"
41
+ reward = self.reward_text or (None if self.reward_value is None else str(self.reward_value))
42
+ line = f"{self.description} ({dates})"
43
+ if reward:
44
+ line += f" -- reward: {reward}"
45
+ return line
46
+
47
+
48
+ def list_coupons(client) -> list[CouponLine]:
49
+ response = client.call("silpo_get_my_coupons") or {}
50
+ coupons = response.get("coupons") or []
51
+ active = [c for c in coupons if c.get("active")]
52
+
53
+ lines = []
54
+ for coupon in active:
55
+ details_response = client.call("silpo_get_coupon_details", {"businessCouponId": coupon["id"]}) or {}
56
+ detail = details_response.get("coupon") or {}
57
+ lines.append(
58
+ CouponLine(
59
+ description=coupon.get("description") or "",
60
+ begin_date=coupon.get("beginDate"),
61
+ end_date=coupon.get("endDate"),
62
+ reward_text=detail.get("rewardText"),
63
+ reward_value=detail.get("rewardValue"),
64
+ )
65
+ )
66
+ return lines
@@ -0,0 +1,417 @@
1
+ """Delivery Settings: interactive `delivery` command (issue #37, part of the
2
+ #34 PRD -- prd_delivery_context_coupons.md) that lets the user explicitly set
3
+ their delivery address, delivery type, and timeslot together in one real
4
+ `silpo_update_shopping_cart` call. Issue #37 covered `DeliveryHome` only;
5
+ issue #38 (this revision) adds `SelfPickup` and `NovaPoshta` -- each needs a
6
+ differently-shaped `address` object, per `silpo_update_shopping_cart`'s own
7
+ tool description (see docs/mcp_schema.md).
8
+
9
+ Flow:
10
+ 1. Resolve/confirm a delivery address -- reuses `address_resolver.py`'s
11
+ `resolve_address()` as-is (no duplicated confirm/pick/new-address logic;
12
+ the same resolver issue #29 wires into `CartContext`'s fallback path).
13
+ `resolve_address()` itself makes one `silpo_get_available_delivery_types`
14
+ call for the resolved address's coordinates and keeps the raw response on
15
+ `ResolvedAddress.delivery_types` (added in issue #29 for exactly this
16
+ kind of reuse) -- this module reads that field directly rather than
17
+ making its own, second, identical call.
18
+ 2. Resolve the current `CartContext` (needed as the address/shipments
19
+ template below), passing the already-resolved address through as
20
+ `resolved_address=` so the no-shipments fallback (issue #29) reuses it
21
+ instead of prompting the user a second time. Fails fast if the resolved
22
+ context has no address/shipments -- see "Real DeliveryHome
23
+ address/shipments construction" below for why a template is required.
24
+ 3. Pick a delivery type from `resolved_address.delivery_types`'s real
25
+ response shape, live-verified 2026-08-05 -- see docs/mcp_schema.md --
26
+ `{"success", "summary", "options": [{"deliveryType", "branchId",
27
+ "description"}]}`, NOT `"deliveryTypes"` as the PRD/pre-ticket docs
28
+ assumed. `DeliveryHome`/`SelfPickup`/`NovaPoshta` are supported; anything
29
+ else stops the flow with a clear message.
30
+ - `DeliveryHome`: `branchId` comes straight from this option.
31
+ - `SelfPickup`/`NovaPoshta`: this option's `branchId` is `null` (per the
32
+ tool's own "NEXT STEPS BY TYPE" description) -- resolved in the
33
+ type-specific branch below instead.
34
+ 4. Type-specific branch/address construction (`_pick_self_pickup_branch` /
35
+ `_pick_nova_poshta_*`, live-verified 2026-08-05 against the real MCP
36
+ server -- see docs/mcp_schema.md's "Live-verified: SelfPickup / Nova
37
+ Poshta address construction" section for the corrections this made to
38
+ the tool description's field names):
39
+ - `SelfPickup`: `silpo_list_branches(hasPickup=true)`, nearest
40
+ `_NEAREST_PICKUP_BRANCHES` branches to the resolved address sorted by
41
+ plain lat/lon distance (good enough for "nearest of this page"; not a
42
+ true nearest-of-all-311 search -- see docs/mcp_schema.md), user picks
43
+ one. Address built from that branch's real fields (`city`/`address`/
44
+ `latitude`/`longitude` -- the tool description's `cityFull`/
45
+ `addressFull` names don't actually exist on the live record).
46
+ - `NovaPoshta`: `silpo_find_nova_poshta_settlements` (search by name) ->
47
+ user picks a settlement -> `silpo_find_nova_poshta_offices` -> user
48
+ picks an office -> `silpo_list_branches(hasNP=true)` for the
49
+ NP-servicing branch (live-verified: exactly one branch nationwide has
50
+ `hasNP=true`, so no picking needed there).
51
+ - Both override `shipments[].companyId` AND `.branchId` with the chosen
52
+ branch's own values (per the tool description's "Set shipments with
53
+ the branch companyId + branchId") -- unlike `DeliveryHome` below, which
54
+ keeps the existing cart shipment's `companyId`.
55
+ 5. List real timeslots at that branch/type (`silpo_get_time_slots`),
56
+ filtered to `available: true` (the tool's own description: "Only pick
57
+ slots where available=true"), and let the user pick one.
58
+ 6. Apply all three in ONE `silpo_update_shopping_cart` call.
59
+
60
+ Real DeliveryHome address/shipments construction (`silpo_update_shopping_cart`'s
61
+ own live tool description): for anything other than
62
+ `DeliveryExpressByPromise`/`NovaPoshta`/`SelfPickup`, "the address object
63
+ MUST be passed exactly as received from `silpo_get_shopping_cart_by_id` ...
64
+ Do NOT construct the address manually -- always copy it from the cart
65
+ response. The shipments array must also come from the cart response."
66
+ `address_resolver.py`'s `ResolvedAddress` only carries `id`/`label`/
67
+ `latitude`/`longitude` (a display/confirmation type, not a full postal
68
+ record) and is reused as-is per this ticket's instructions, so this module
69
+ cannot -- and per the tool's own instruction, should not -- hand-build a
70
+ brand-new postal address from it. So: `address` is copied verbatim from
71
+ `CartContext.address` (same pass-through precedent as `promo_optimizer.py`'s
72
+ issue #20 call), with only `latitude`/`longitude` overridden to the
73
+ newly-resolved address's coordinates (the one part of "a new address"
74
+ `ResolvedAddress` actually gives us, and the field that determines which
75
+ branch/company can serve the order). `shipments` is copied from
76
+ `CartContext.shipments` with each entry's `branchId` overridden to the
77
+ chosen delivery type's `branchId` (a real value returned by
78
+ `silpo_get_available_delivery_types`, not invented); `companyId` is kept
79
+ from the existing cart shipment -- an assumption (one company serves all
80
+ branches for a given account), documented in docs/mcp_schema.md's
81
+ "Assumptions made in issue #37" section, matching every live-observed
82
+ cart/product record in this project sharing one `companyId`.
83
+
84
+ A cart context with no existing `address`/`shipments` (e.g. a brand-new,
85
+ never-delivered-to account) has no template to copy from -- `delivery`
86
+ fails clearly in that case rather than guessing a full postal address from
87
+ scratch, per the same "narrow scope over an unreliable guess" precedent
88
+ issue #20 established for the promo-swap feature.
89
+
90
+ Post-apply availability report: re-resolves cart context after the update
91
+ and cross-references its `calculation.validations[]` product-level entries
92
+ (`type == "product"`, carrying `context.productId` per docs/mcp_schema.md's
93
+ live-verified validation shape) against the pre-update cart's products, by
94
+ `productId`, to report which previously-in-cart items are now flagged.
95
+ Purely informational -- print only; nothing here mutates the cart, and the
96
+ update call itself already happened before this check runs.
97
+ """
98
+
99
+ from dataclasses import dataclass, field
100
+
101
+ from silpo_agent.address_resolver import resolve_address
102
+ from silpo_agent.cart_context import resolve_cart_context
103
+ from silpo_agent.timeslot_format import format_timeslot
104
+
105
+ _TARGET_DELIVERY_TYPE = "DeliveryHome"
106
+ _SUPPORTED_DELIVERY_TYPES = ("DeliveryHome", "SelfPickup", "NovaPoshta")
107
+ _NEAREST_PICKUP_BRANCHES = 5
108
+ _NP_OFFICE_TYPE_LABELS = {"office": "Відділення", "parcelLocker": "Поштомат"}
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class DeliveryResult:
113
+ applied: bool
114
+ delivery_type: str | None = None
115
+ newly_unavailable: list[dict] = field(default_factory=list)
116
+
117
+
118
+ def _pick_delivery_type(resolved_address, input_fn, print_fn) -> dict | None:
119
+ # resolved_address.delivery_types is the raw silpo_get_available_delivery_types
120
+ # response resolve_address() already fetched for these exact coordinates
121
+ # (issue #29) -- reuse it instead of making a second, identical call.
122
+ response = resolved_address.delivery_types or {}
123
+ options = response.get("options") or []
124
+ if not options:
125
+ print_fn("No delivery types available at this address.")
126
+ return None
127
+
128
+ for i, option in enumerate(options, start=1):
129
+ print_fn(f"{i}. {option.get('deliveryType')} -- {option.get('description')}")
130
+ choice = input_fn("Pick a delivery type by number: ").strip()
131
+ idx = int(choice) if choice.isdigit() else None
132
+ if not idx or not (1 <= idx <= len(options)):
133
+ print_fn(f"No delivery type numbered {choice!r}.")
134
+ return None
135
+
136
+ chosen = options[idx - 1]
137
+ delivery_type = chosen.get("deliveryType")
138
+ if delivery_type not in _SUPPORTED_DELIVERY_TYPES:
139
+ print_fn(
140
+ f"{delivery_type} isn't supported by `delivery` yet -- only "
141
+ f"{', '.join(_SUPPORTED_DELIVERY_TYPES)} are."
142
+ )
143
+ return None
144
+ # Only DeliveryHome's branchId comes from this option -- SelfPickup/
145
+ # NovaPoshta legitimately have branchId=null here (per the tool's own
146
+ # "NEXT STEPS BY TYPE" description) and are resolved separately below.
147
+ if delivery_type == _TARGET_DELIVERY_TYPE and not chosen.get("branchId"):
148
+ print_fn(f"{_TARGET_DELIVERY_TYPE} has no branch at this address.")
149
+ return None
150
+ return chosen
151
+
152
+
153
+ def _distance_sq(lat1, lon1, lat2, lon2) -> float:
154
+ return (lat1 - lat2) ** 2 + (lon1 - lon2) ** 2
155
+
156
+
157
+ def _to_float(value) -> float | None:
158
+ try:
159
+ return float(value)
160
+ except (TypeError, ValueError):
161
+ return None
162
+
163
+
164
+ def _pick_self_pickup_branch(client, resolved_address, input_fn, print_fn) -> dict | None:
165
+ """SelfPickup branch pick (issue #38): silpo_list_branches(hasPickup=true)
166
+ per its own tool description ("show 5 nearest branches to their location
167
+ and let them choose"). Sorts the fetched page by plain lat/lon distance
168
+ to the resolved address -- not a true nearest-of-all-311 search across
169
+ every page (see docs/mcp_schema.md), good enough for picking among a
170
+ default-sized page of real branch data. Closed (`open: false`) branches
171
+ and branches missing coordinates (can't be meaningfully distance-ranked,
172
+ and defaulting to (0, 0) would rank them as falsely "nearest") are
173
+ excluded before sorting."""
174
+ response = client.call("silpo_list_branches", {"hasPickup": True}) or {}
175
+ branches = [b for b in (response.get("branches") or []) if b.get("open")]
176
+ if not branches:
177
+ print_fn("No self-pickup branches available.")
178
+ return None
179
+
180
+ locatable = [b for b in branches if _to_float(b.get("latitude")) is not None and _to_float(b.get("longitude")) is not None]
181
+ if not locatable:
182
+ print_fn("No self-pickup branches available.")
183
+ return None
184
+
185
+ nearest = sorted(
186
+ locatable,
187
+ key=lambda b: _distance_sq(
188
+ resolved_address.latitude,
189
+ resolved_address.longitude,
190
+ _to_float(b.get("latitude")),
191
+ _to_float(b.get("longitude")),
192
+ ),
193
+ )[:_NEAREST_PICKUP_BRANCHES]
194
+
195
+ for i, branch in enumerate(nearest, start=1):
196
+ print_fn(f"{i}. {branch.get('city')} -- {branch.get('address')}")
197
+ choice = input_fn("Pick a pickup branch by number: ").strip()
198
+ idx = int(choice) if choice.isdigit() else None
199
+ if not idx or not (1 <= idx <= len(nearest)):
200
+ print_fn(f"No branch numbered {choice!r}.")
201
+ return None
202
+ return nearest[idx - 1]
203
+
204
+
205
+ def _self_pickup_address(branch: dict) -> dict:
206
+ """Real SelfPickup address shape, live-verified 2026-08-05 against
207
+ silpo_list_branches(hasPickup=true): the branch record's real field
208
+ names are `city`/`address`, NOT `cityFull`/`addressFull` as the
209
+ silpo_update_shopping_cart tool description's own text says -- those
210
+ fields don't exist on the live record. See docs/mcp_schema.md."""
211
+ return {
212
+ "addressType": "self-pickup",
213
+ "city": branch.get("city"),
214
+ "locality": branch.get("address"),
215
+ "street": branch.get("address"),
216
+ "latitude": branch.get("latitude"),
217
+ "longitude": branch.get("longitude"),
218
+ }
219
+
220
+
221
+ def _pick_nova_poshta_settlement(client, input_fn, print_fn) -> dict | None:
222
+ query = input_fn("City/settlement to search for Nova Poshta delivery: ").strip()
223
+ if not query:
224
+ print_fn("No settlement search entered.")
225
+ return None
226
+ response = client.call("silpo_find_nova_poshta_settlements", {"title": query}) or {}
227
+ settlements = response.get("settlements") or []
228
+ if not settlements:
229
+ print_fn(f"No Nova Poshta settlements found for {query!r}.")
230
+ return None
231
+
232
+ for i, settlement in enumerate(settlements, start=1):
233
+ print_fn(f"{i}. {settlement.get('title')} ({settlement.get('area')})")
234
+ choice = input_fn("Pick a settlement by number: ").strip()
235
+ idx = int(choice) if choice.isdigit() else None
236
+ if not idx or not (1 <= idx <= len(settlements)):
237
+ print_fn(f"No settlement numbered {choice!r}.")
238
+ return None
239
+ return settlements[idx - 1]
240
+
241
+
242
+ def _pick_nova_poshta_office(client, settlement, input_fn, print_fn) -> dict | None:
243
+ response = client.call("silpo_find_nova_poshta_offices", {"settlementId": settlement.get("id")}) or {}
244
+ offices = response.get("offices") or []
245
+ if not offices:
246
+ print_fn("No Nova Poshta offices found in that settlement.")
247
+ return None
248
+
249
+ for i, office in enumerate(offices, start=1):
250
+ print_fn(f"{i}. {office.get('title')}")
251
+ choice = input_fn("Pick an office by number: ").strip()
252
+ idx = int(choice) if choice.isdigit() else None
253
+ if not idx or not (1 <= idx <= len(offices)):
254
+ print_fn(f"No office numbered {choice!r}.")
255
+ return None
256
+ return offices[idx - 1]
257
+
258
+
259
+ def _nova_poshta_address(settlement: dict, office: dict) -> dict:
260
+ """Real NovaPoshta address shape, per silpo_update_shopping_cart's own
261
+ tool description, live-verified 2026-08-05 against
262
+ silpo_find_nova_poshta_settlements/offices: settlement.title/area and
263
+ office.id/latitude/longitude/type/number all match the tool
264
+ description's field names as-is (unlike SelfPickup's branch fields)."""
265
+ label = _NP_OFFICE_TYPE_LABELS.get(office.get("type"), office.get("type"))
266
+ return {
267
+ "addressType": "nova-poshta",
268
+ "city": settlement.get("title"),
269
+ "region": settlement.get("area"),
270
+ "latitude": str(office.get("latitude")),
271
+ "longitude": str(office.get("longitude")),
272
+ "officeId": office.get("id"),
273
+ "street": f"{label} #{office.get('number')}",
274
+ }
275
+
276
+
277
+ def _pick_nova_poshta_branch(client, print_fn) -> dict | None:
278
+ """silpo_list_branches(hasNP=true) for the branchId/companyId to ship
279
+ through -- live-verified 2026-08-05: exactly one branch nationwide has
280
+ hasNP=true, so this is a lookup, not a user pick. That's an
281
+ observation about this account, not a guarantee -- if a future account
282
+ or a different API state ever returns more than one, don't silently
283
+ pick the first with no trace of it: say so, so it's visible rather than
284
+ an invisible wrong guess."""
285
+ response = client.call("silpo_list_branches", {"hasNP": True}) or {}
286
+ branches = response.get("branches") or []
287
+ if not branches:
288
+ print_fn("No Nova Poshta-servicing branch found.")
289
+ return None
290
+ if len(branches) > 1:
291
+ print_fn(f"{len(branches)} Nova Poshta-servicing branches found; using {branches[0].get('city')}.")
292
+ return branches[0]
293
+
294
+
295
+ def _pick_timeslot(client, branch_id, delivery_type, input_fn, print_fn) -> dict | None:
296
+ response = (
297
+ client.call("silpo_get_time_slots", {"branchId": branch_id, "deliveryTypes": [delivery_type]}) or {}
298
+ )
299
+ slots = [slot for slot in (response.get("slots") or []) if slot.get("available")]
300
+ if not slots:
301
+ print_fn("No available timeslots.")
302
+ return None
303
+
304
+ for i, slot in enumerate(slots, start=1):
305
+ print_fn(f"{i}. {format_timeslot(slot.get('start'), slot.get('end'))}")
306
+ choice = input_fn("Pick a timeslot by number: ").strip()
307
+ idx = int(choice) if choice.isdigit() else None
308
+ if not idx or not (1 <= idx <= len(slots)):
309
+ print_fn(f"No timeslot numbered {choice!r}.")
310
+ return None
311
+ return slots[idx - 1]
312
+
313
+
314
+ def _newly_unavailable(pre_products: list[dict], validations: list[dict]) -> list[dict]:
315
+ flagged_ids = {
316
+ validation["context"]["productId"]
317
+ for validation in validations
318
+ if validation.get("type") == "product"
319
+ and isinstance(validation.get("context"), dict)
320
+ and validation["context"].get("productId")
321
+ }
322
+ return [product for product in pre_products if product.get("productId") in flagged_ids]
323
+
324
+
325
+ def run_delivery_settings(client, log_store, *, input_fn=None, print_fn=None):
326
+ input_fn = input_fn or input
327
+ print_fn = print_fn or print
328
+
329
+ resolved_address = resolve_address(client, log_store, input_fn=input_fn, print_fn=print_fn)
330
+ if resolved_address is None:
331
+ print_fn("delivery: no delivery address resolved; aborting.")
332
+ return DeliveryResult(applied=False)
333
+ if resolved_address.latitude is None or resolved_address.longitude is None:
334
+ print_fn("delivery: resolved address has no coordinates; aborting.")
335
+ return DeliveryResult(applied=False)
336
+
337
+ # Pass the address we already resolved through so the no-shipments
338
+ # fallback (issue #29) reuses it instead of prompting a second time.
339
+ cart_context = resolve_cart_context(client, resolved_address=resolved_address, print_fn=print_fn)
340
+ if not (cart_context.shopping_cart_id and cart_context.address and cart_context.shipments):
341
+ print_fn("delivery: no existing cart address/shipments to update from; aborting.")
342
+ return DeliveryResult(applied=False)
343
+
344
+ chosen_type = _pick_delivery_type(resolved_address, input_fn, print_fn)
345
+ if chosen_type is None:
346
+ return DeliveryResult(applied=False)
347
+ delivery_type = chosen_type["deliveryType"]
348
+
349
+ if delivery_type == _TARGET_DELIVERY_TYPE:
350
+ branch_id = chosen_type["branchId"]
351
+ address = dict(cart_context.address)
352
+ address["latitude"] = str(resolved_address.latitude)
353
+ address["longitude"] = str(resolved_address.longitude)
354
+ shipments = [{**shipment, "branchId": branch_id} for shipment in cart_context.shipments]
355
+ elif delivery_type == "SelfPickup":
356
+ branch = _pick_self_pickup_branch(client, resolved_address, input_fn, print_fn)
357
+ if branch is None:
358
+ return DeliveryResult(applied=False)
359
+ branch_id = branch.get("branchId")
360
+ address = _self_pickup_address(branch)
361
+ shipments = [
362
+ {**shipment, "companyId": branch.get("companyId"), "branchId": branch_id}
363
+ for shipment in cart_context.shipments
364
+ ]
365
+ else: # NovaPoshta
366
+ settlement = _pick_nova_poshta_settlement(client, input_fn, print_fn)
367
+ if settlement is None:
368
+ return DeliveryResult(applied=False)
369
+ office = _pick_nova_poshta_office(client, settlement, input_fn, print_fn)
370
+ if office is None:
371
+ return DeliveryResult(applied=False)
372
+ np_branch = _pick_nova_poshta_branch(client, print_fn)
373
+ if np_branch is None:
374
+ return DeliveryResult(applied=False)
375
+ branch_id = np_branch.get("branchId")
376
+ address = _nova_poshta_address(settlement, office)
377
+ shipments = [
378
+ {**shipment, "companyId": np_branch.get("companyId"), "branchId": branch_id}
379
+ for shipment in cart_context.shipments
380
+ ]
381
+
382
+ chosen_slot = _pick_timeslot(client, branch_id, delivery_type, input_fn, print_fn)
383
+ if chosen_slot is None:
384
+ return DeliveryResult(applied=False)
385
+ if not chosen_slot.get("start") or not chosen_slot.get("end"):
386
+ print_fn("delivery: chosen timeslot is missing start/end; aborting.")
387
+ return DeliveryResult(applied=False)
388
+
389
+ timeslot = {"start": chosen_slot.get("start"), "end": chosen_slot.get("end")}
390
+
391
+ response = (
392
+ client.call(
393
+ "silpo_update_shopping_cart",
394
+ {
395
+ "shoppingCartId": cart_context.shopping_cart_id,
396
+ "deliveryType": delivery_type,
397
+ "timeslot": timeslot,
398
+ "address": address,
399
+ "shipments": shipments,
400
+ },
401
+ )
402
+ or {}
403
+ )
404
+ if not response.get("success"):
405
+ print_fn("delivery: failed to update delivery settings.")
406
+ return DeliveryResult(applied=False)
407
+
408
+ print_fn(f"Delivery settings updated: {delivery_type}, {format_timeslot(timeslot['start'], timeslot['end'])}.")
409
+
410
+ new_context = resolve_cart_context(client, resolved_address=resolved_address, print_fn=print_fn)
411
+ newly_unavailable = _newly_unavailable(cart_context.products, new_context.validations)
412
+ if newly_unavailable:
413
+ print_fn(f"Now unavailable ({len(newly_unavailable)}):")
414
+ for product in newly_unavailable:
415
+ print_fn(f" - {product.get('name') or product.get('productId')}")
416
+
417
+ return DeliveryResult(applied=True, delivery_type=delivery_type, newly_unavailable=newly_unavailable)
@@ -0,0 +1,92 @@
1
+ """Favorites Deals: read-only `favorites-deals` subcommand (issue #33, part
2
+ of #26). Checks the user's own favorites list for items currently
3
+ discounted -- no matching/heuristic needed, it's already the user's own
4
+ explicit list, unlike Substitution Resolver's stock-availability matching.
5
+
6
+ Real schema (see ../../docs/mcp_schema.md's "Profile / account tools"
7
+ section): `silpo_get_my_favorites({"branchId", "deliveryType",
8
+ "timeslotStart", "limit", "offset"})` -- not live-verified at implementation
9
+ time, but per its tool description returns products in the same shape as
10
+ `silpo_get_products` (`silpo_get_similar_products`'s confirmed live shape is
11
+ `{"success", "summary", "products": [...], "meta": {"total"}}`, the closest
12
+ verified analogue) -- so this module reads the `"products"` key, same
13
+ defensive `.get(...) or []` pattern used everywhere else in this codebase.
14
+ Each product record's `price`/`oldPrice` fields are the same ones
15
+ live-verified on cart/order product records elsewhere in this project.
16
+
17
+ Branch/delivery/timeslot context comes from `cart_context.resolve_cart_context`
18
+ (issue #17, with the issue #29 no-shipments address-resolver fallback) --
19
+ this module is one of the "future callers" #29's docstring named as calling
20
+ `resolve_cart_context` directly with no address of its own, so the
21
+ interactive confirm/pick/new-address flow runs automatically on a
22
+ fresh/cleared-cart account.
23
+ """
24
+
25
+ from dataclasses import dataclass
26
+
27
+ from silpo_agent.cart_context import resolve_cart_context
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class FavoriteDeal:
32
+ name: str
33
+ price: float
34
+ old_price: float
35
+ # Issue #50: the product record's own slug -- this CLI's public product
36
+ # identifier, what `cart edit --replace` takes. Omitted from the
37
+ # formatted line when absent rather than rendered as a placeholder: an
38
+ # identifier that can't be resolved is worse than no identifier.
39
+ slug: str | None = None
40
+ # Ticket 02 (smart-cart): the real product id, same id space as
41
+ # TypicalItem.product_id / order history's "id" -- needed so smart-cart
42
+ # can dedupe a favorited-and-discounted product against typical items and
43
+ # add it via silpo_add_or_update_cart_products. Not shown in format(),
44
+ # which stays slug-based for cart edit --replace.
45
+ product_id: str | None = None
46
+
47
+ def format(self) -> str:
48
+ line = f"{self.name}: {self.price:.2f} (was {self.old_price:.2f})"
49
+ if self.slug:
50
+ line += f" {self.slug}"
51
+ return line
52
+
53
+
54
+ def list_favorites_deals(client, log_store=None, *, input_fn=None, print_fn=None, cart_context=None) -> list[FavoriteDeal]:
55
+ # Ticket 02 (smart-cart): a caller that already resolved a CartContext of
56
+ # its own (same pattern as resolve_cart_context's own `resolved_address`,
57
+ # cart_context.py:44-49) passes it here to skip this redundant
58
+ # silpo_get_my_shopping_cart/silpo_get_shopping_cart_by_id round trip --
59
+ # and, on a fresh/cleared cart, avoid re-prompting for address
60
+ # confirmation a second time. The standalone `favorites-deals` command has
61
+ # no context of its own, so it omits this and resolves one here as before.
62
+ if cart_context is None:
63
+ cart_context = resolve_cart_context(client, log_store=log_store, input_fn=input_fn, print_fn=print_fn)
64
+
65
+ response = (
66
+ client.call(
67
+ "silpo_get_my_favorites",
68
+ {
69
+ "branchId": cart_context.branch_id,
70
+ "deliveryType": cart_context.delivery_type,
71
+ "timeslotStart": cart_context.timeslot_start,
72
+ },
73
+ )
74
+ or {}
75
+ )
76
+ products = response.get("products") or []
77
+
78
+ deals = []
79
+ for product in products:
80
+ price = product.get("price")
81
+ old_price = product.get("oldPrice")
82
+ if price is not None and old_price is not None and old_price > price:
83
+ deals.append(
84
+ FavoriteDeal(
85
+ name=product.get("name") or "",
86
+ price=price,
87
+ old_price=old_price,
88
+ slug=product.get("slug"),
89
+ product_id=product.get("id"),
90
+ )
91
+ )
92
+ return deals
@@ -0,0 +1,77 @@
1
+ """Reorder Log Store: local append-only audit trail of past Reorder flow runs,
2
+ plus Substitution Memory (item -> chosen replacement). Read/write only, no
3
+ business logic.
4
+ """
5
+
6
+ import fcntl
7
+ import json
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+
11
+ DEFAULT_PATH = Path.home() / ".silpo-agent" / "reorder_log.json"
12
+
13
+ _EMPTY = {"runs": [], "substitutions": {}}
14
+
15
+
16
+ class ReorderLogStore:
17
+ def __init__(self, path: Path | None = None):
18
+ self.path = path or DEFAULT_PATH
19
+
20
+ @contextmanager
21
+ def _locked(self):
22
+ # ponytail: advisory file lock (fcntl, POSIX-only) around each
23
+ # load-mutate-save, not a cross-platform lock library — fine for
24
+ # this single-machine personal CLI. A single `reorder` run can now
25
+ # call append_run (address audit) and set_substitution (once per
26
+ # freshly-chosen replacement) multiple times; the lock serializes
27
+ # each call's load+save into one critical section so a later call
28
+ # can never load a stale copy and clobber an earlier call's save.
29
+ # Swap for `filelock` (already-installed-dependency rung) if this
30
+ # ever needs to run on Windows.
31
+ self.path.parent.mkdir(parents=True, exist_ok=True)
32
+ lock_path = self.path.with_suffix(self.path.suffix + ".lock")
33
+ with open(lock_path, "w") as fh:
34
+ fcntl.flock(fh, fcntl.LOCK_EX)
35
+ try:
36
+ yield
37
+ finally:
38
+ fcntl.flock(fh, fcntl.LOCK_UN)
39
+
40
+ def _load(self) -> dict:
41
+ try:
42
+ raw = self.path.read_text()
43
+ except OSError:
44
+ return dict(_EMPTY, runs=[], substitutions={})
45
+ try:
46
+ data = json.loads(raw)
47
+ except json.JSONDecodeError:
48
+ return dict(_EMPTY, runs=[], substitutions={})
49
+ if not isinstance(data, dict) or "runs" not in data or "substitutions" not in data:
50
+ return dict(_EMPTY, runs=[], substitutions={})
51
+ return data
52
+
53
+ def _save(self, data: dict) -> None:
54
+ self.path.parent.mkdir(parents=True, exist_ok=True)
55
+ self.path.write_text(json.dumps(data, indent=2))
56
+
57
+ def append_run(self, run: dict) -> None:
58
+ with self._locked():
59
+ data = self._load()
60
+ data["runs"].append(run)
61
+ self._save(data)
62
+
63
+ def read_history(self) -> list[dict]:
64
+ return self._load()["runs"]
65
+
66
+ def set_substitution(self, item_id: str, replacement_id: str) -> None:
67
+ with self._locked():
68
+ data = self._load()
69
+ data["substitutions"][item_id] = replacement_id
70
+ self._save(data)
71
+
72
+ def get_substitution(self, item_id: str) -> str | None:
73
+ return self._load()["substitutions"].get(item_id)
74
+
75
+ def clear(self) -> None:
76
+ with self._locked():
77
+ self._save({"runs": [], "substitutions": {}})