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.
- silpo_agent/__init__.py +0 -0
- silpo_agent/address_resolver.py +141 -0
- silpo_agent/auth.py +266 -0
- silpo_agent/cart_context.py +197 -0
- silpo_agent/cart_editor.py +325 -0
- silpo_agent/cart_viewer.py +97 -0
- silpo_agent/cart_writer.py +203 -0
- silpo_agent/cli.py +1117 -0
- silpo_agent/coupons_lister.py +66 -0
- silpo_agent/delivery_settings.py +417 -0
- silpo_agent/favorites_deals.py +92 -0
- silpo_agent/log_store.py +77 -0
- silpo_agent/norm_dataset.py +52 -0
- silpo_agent/norm_top_up.py +221 -0
- silpo_agent/order_aggregator.py +73 -0
- silpo_agent/promo_finder.py +101 -0
- silpo_agent/promo_optimizer.py +91 -0
- silpo_agent/promo_scanner.py +255 -0
- silpo_agent/substitution_resolver.py +251 -0
- silpo_agent/timeslot_format.py +28 -0
- silpo_agent_cli-0.2.0.dist-info/METADATA +271 -0
- silpo_agent_cli-0.2.0.dist-info/RECORD +25 -0
- silpo_agent_cli-0.2.0.dist-info/WHEEL +4 -0
- silpo_agent_cli-0.2.0.dist-info/entry_points.txt +2 -0
- silpo_agent_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Promo Scanner: powers the read-only `deals` subcommand (issue #32, part
|
|
2
|
+
of #26's cart_and_deals PRD). Independent of the user's cart -- discovers
|
|
3
|
+
store-wide discounts rather than starting from a specific item (that's the
|
|
4
|
+
Similar-Products Promo Finder's job, per `cart edit`/`cart promos`, not this
|
|
5
|
+
module's).
|
|
6
|
+
|
|
7
|
+
Real schema (see ../../docs/mcp_schema.md's "Promo / loyalty tools" and
|
|
8
|
+
"Product search / replacement tools" sections, live-verified):
|
|
9
|
+
- `silpo_get_promotions({"branchId", "deliveryType", "timeslotStart",
|
|
10
|
+
"timeslotEnd"})` -> `{"success", "summary", "promotions": [{"code",
|
|
11
|
+
"title", "productCount", "url"}]}` -- branch-wide promotion *categories*,
|
|
12
|
+
not per-product results.
|
|
13
|
+
- `silpo_get_products({"branchId", "deliveryType", "timeslotStart",
|
|
14
|
+
"timeslotEnd", "mustHavePromotion": true, "promotionCode": "<code>"})` is
|
|
15
|
+
the only real way to list a category's actual promo products. Confirmed
|
|
16
|
+
live that some categories list thousands of products (one had 3517), so
|
|
17
|
+
every category response is capped locally to `cap_per_category` (~20)
|
|
18
|
+
before merging -- this cap is applied defensively regardless of whether
|
|
19
|
+
the live server actually honors the `limit` param passed alongside the
|
|
20
|
+
other filters, since that hasn't been confirmed.
|
|
21
|
+
- Product record shape is the same one documented for `silpo_get_products` /
|
|
22
|
+
`silpo_find_products_batch` / `silpo_get_similar_products`: `{"id",
|
|
23
|
+
"name", ..., "price", "oldPrice", ...}`. A product only counts as a real
|
|
24
|
+
deal when `oldPrice` is a genuinely higher number than `price` -- same
|
|
25
|
+
discount signal the PRD's Similar-Products Promo Finder uses.
|
|
26
|
+
|
|
27
|
+
Plastic-bag-style items (пакет / пакет з пакетів / пакет-майка) are never a
|
|
28
|
+
"deal" a user would search for -- filtered with the same
|
|
29
|
+
`cart_writer.py`'s `_is_plastic_bag` substring-on-name heuristic, duplicated
|
|
30
|
+
here since it operates on raw product dicts (from `silpo_get_products`), not
|
|
31
|
+
a `TypicalItem`.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
|
|
36
|
+
from silpo_agent.cart_context import CartContext
|
|
37
|
+
|
|
38
|
+
_PLASTIC_BAG_KEYWORD = "пакет"
|
|
39
|
+
DEFAULT_CATEGORY_CAP = 20
|
|
40
|
+
_CATEGORY_PAGE_SIZE = 1000
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CategoryNotFoundError(Exception):
|
|
44
|
+
"""Raised by `resolve_category_slug` when --category's free-text query
|
|
45
|
+
(e.g. "овочі") doesn't match any real category title, so `scan_deals`
|
|
46
|
+
never sends a bogus category slug to `silpo_get_products` (a slug that
|
|
47
|
+
doesn't exist there just silently returns zero products, indistinguishable
|
|
48
|
+
from "no deals right now" -- this needs to be a clear, distinct error)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Deal:
|
|
53
|
+
product_id: str
|
|
54
|
+
name: str
|
|
55
|
+
# Issue #50: the product record's own slug, carried through untouched --
|
|
56
|
+
# it's this CLI's public product identifier (what `cart edit --replace`
|
|
57
|
+
# takes) and the only one `silpo_get_product_details` can resolve.
|
|
58
|
+
slug: str | None
|
|
59
|
+
price: float
|
|
60
|
+
old_price: float
|
|
61
|
+
discount_pct: float
|
|
62
|
+
company_id: str | None
|
|
63
|
+
branch_id: str | None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _is_plastic_bag(product: dict) -> bool:
|
|
67
|
+
name = product.get("name")
|
|
68
|
+
return bool(name) and _PLASTIC_BAG_KEYWORD in name.lower()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _discount_pct(price, old_price) -> float | None:
|
|
72
|
+
"""None (not a real deal) unless both are numbers and old_price is
|
|
73
|
+
genuinely higher than price -- same signal the PRD's Similar-Products
|
|
74
|
+
Promo Finder uses (`oldPrice` present and higher than `price`)."""
|
|
75
|
+
if not isinstance(price, (int, float)) or not isinstance(old_price, (int, float)):
|
|
76
|
+
return None
|
|
77
|
+
if old_price <= price:
|
|
78
|
+
return None
|
|
79
|
+
return (old_price - price) / old_price * 100
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _deals_from_products(products: list[dict], cap: int) -> list[Deal]:
|
|
83
|
+
deals: list[Deal] = []
|
|
84
|
+
for product in products[:cap]:
|
|
85
|
+
if _is_plastic_bag(product):
|
|
86
|
+
continue
|
|
87
|
+
pct = _discount_pct(product.get("price"), product.get("oldPrice"))
|
|
88
|
+
if pct is None:
|
|
89
|
+
continue
|
|
90
|
+
deals.append(
|
|
91
|
+
Deal(
|
|
92
|
+
product_id=product.get("id"),
|
|
93
|
+
name=product.get("name") or "",
|
|
94
|
+
slug=product.get("slug"),
|
|
95
|
+
price=product.get("price"),
|
|
96
|
+
old_price=product.get("oldPrice"),
|
|
97
|
+
discount_pct=pct,
|
|
98
|
+
company_id=product.get("companyId"),
|
|
99
|
+
branch_id=product.get("branchId"),
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
return deals
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _fetch_all_categories(client, cart_context: CartContext) -> list[dict]:
|
|
106
|
+
"""`silpo_get_categories` is a flat, paginated list (1000+ categories
|
|
107
|
+
real-world) unlike `silpo_get_categories_tree`'s nested-but-nameless
|
|
108
|
+
nodes (its entries carry only slug/children/total, no title) -- this is
|
|
109
|
+
the only listing call that pairs a human title with a real slug."""
|
|
110
|
+
categories: list[dict] = []
|
|
111
|
+
offset = 0
|
|
112
|
+
while True:
|
|
113
|
+
response = (
|
|
114
|
+
client.call(
|
|
115
|
+
"silpo_get_categories",
|
|
116
|
+
{"branchId": cart_context.branch_id, "limit": _CATEGORY_PAGE_SIZE, "offset": offset},
|
|
117
|
+
)
|
|
118
|
+
or {}
|
|
119
|
+
)
|
|
120
|
+
page = response.get("categories") or []
|
|
121
|
+
categories.extend(page)
|
|
122
|
+
total = (response.get("meta") or {}).get("total", len(categories))
|
|
123
|
+
offset += _CATEGORY_PAGE_SIZE
|
|
124
|
+
if not page or offset >= total:
|
|
125
|
+
break
|
|
126
|
+
return categories
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass(frozen=True)
|
|
130
|
+
class CategoryMatch:
|
|
131
|
+
slug: str
|
|
132
|
+
title: str
|
|
133
|
+
exact: bool
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def resolve_category_from_list(categories: list[dict], query: str) -> CategoryMatch | None:
|
|
137
|
+
"""Same matching logic as `resolve_category`, against an already-fetched
|
|
138
|
+
category list -- lets a caller that needs to match several queries
|
|
139
|
+
(norm_top_up.py's per-norm-category-tag lookup) fetch the paginated
|
|
140
|
+
category tree once and reuse it, instead of `resolve_category` calling
|
|
141
|
+
`_fetch_all_categories` fresh on every single query."""
|
|
142
|
+
query_lower = query.strip().lower()
|
|
143
|
+
if not query_lower:
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
exact = [c for c in categories if (c.get("title") or "").strip().lower() == query_lower]
|
|
147
|
+
if exact:
|
|
148
|
+
return CategoryMatch(slug=exact[0].get("slug"), title=exact[0].get("title"), exact=True)
|
|
149
|
+
|
|
150
|
+
partial = [c for c in categories if query_lower in (c.get("title") or "").lower()]
|
|
151
|
+
if not partial:
|
|
152
|
+
return None
|
|
153
|
+
partial.sort(key=lambda c: len(c.get("title") or ""))
|
|
154
|
+
best = partial[0]
|
|
155
|
+
return CategoryMatch(slug=best.get("slug"), title=best.get("title"), exact=False)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def resolve_category(client, cart_context: CartContext, query: str) -> CategoryMatch | None:
|
|
159
|
+
"""Free-text category name (e.g. "Овочі") -> matched real category, plus
|
|
160
|
+
whether the match was exact. `silpo_get_products`'s own `category` filter
|
|
161
|
+
takes a slug, not a name -- a free-text name there silently matches
|
|
162
|
+
nothing (live-verified). Exact (case-insensitive) title match wins;
|
|
163
|
+
otherwise the shortest title containing the query, on the theory that a
|
|
164
|
+
shorter title is the more specific category (e.g. "Овочі" over "Фрукти,
|
|
165
|
+
овочі"). Issue #05: `exact=False` signals the CLI should warn the user
|
|
166
|
+
which real category it fell back to, since a query like "Вино" can
|
|
167
|
+
otherwise silently match "Виноград" instead."""
|
|
168
|
+
categories = _fetch_all_categories(client, cart_context)
|
|
169
|
+
return resolve_category_from_list(categories, query)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def list_category_titles(client, cart_context: CartContext) -> list[str]:
|
|
173
|
+
"""Every real category title currently available, alphabetically --
|
|
174
|
+
powers `deals --list-categories` (issue #05) so a user can see what to
|
|
175
|
+
type for `--category` instead of guessing. Read-only: reuses the same
|
|
176
|
+
`_fetch_all_categories` listing `resolve_category` matches against,
|
|
177
|
+
fetches no deals."""
|
|
178
|
+
categories = _fetch_all_categories(client, cart_context)
|
|
179
|
+
return sorted(title for c in categories if (title := c.get("title")))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def resolve_category_slug(client, cart_context: CartContext, query: str) -> str | None:
|
|
183
|
+
"""Thin wrapper over `resolve_category` for callers that only need the
|
|
184
|
+
slug (e.g. `scan_deals`'s category filter)."""
|
|
185
|
+
match = resolve_category(client, cart_context, query)
|
|
186
|
+
return match.slug if match else None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def scan_deals(
|
|
190
|
+
client,
|
|
191
|
+
cart_context: CartContext,
|
|
192
|
+
*,
|
|
193
|
+
limit: int = 10,
|
|
194
|
+
cap_per_category: int = DEFAULT_CATEGORY_CAP,
|
|
195
|
+
category: str | None = None,
|
|
196
|
+
) -> list[Deal]:
|
|
197
|
+
if category is not None:
|
|
198
|
+
slug = resolve_category_slug(client, cart_context, category)
|
|
199
|
+
if slug is None:
|
|
200
|
+
raise CategoryNotFoundError(category)
|
|
201
|
+
|
|
202
|
+
products_response = (
|
|
203
|
+
client.call(
|
|
204
|
+
"silpo_get_products",
|
|
205
|
+
{
|
|
206
|
+
"branchId": cart_context.branch_id,
|
|
207
|
+
"deliveryType": cart_context.delivery_type,
|
|
208
|
+
"timeslotStart": cart_context.timeslot_start,
|
|
209
|
+
"timeslotEnd": cart_context.timeslot_end,
|
|
210
|
+
"category": slug,
|
|
211
|
+
"mustHavePromotion": True,
|
|
212
|
+
"sortBy": "promotion",
|
|
213
|
+
"sortDirection": "desc",
|
|
214
|
+
"limit": max(limit, cap_per_category),
|
|
215
|
+
},
|
|
216
|
+
)
|
|
217
|
+
or {}
|
|
218
|
+
)
|
|
219
|
+
deals = _deals_from_products(products_response.get("products") or [], cap_per_category)
|
|
220
|
+
deals.sort(key=lambda deal: deal.discount_pct, reverse=True)
|
|
221
|
+
return deals[:limit]
|
|
222
|
+
|
|
223
|
+
promos_response = client.call(
|
|
224
|
+
"silpo_get_promotions",
|
|
225
|
+
{
|
|
226
|
+
"branchId": cart_context.branch_id,
|
|
227
|
+
"deliveryType": cart_context.delivery_type,
|
|
228
|
+
"timeslotStart": cart_context.timeslot_start,
|
|
229
|
+
"timeslotEnd": cart_context.timeslot_end,
|
|
230
|
+
},
|
|
231
|
+
) or {}
|
|
232
|
+
promotions = promos_response.get("promotions") or []
|
|
233
|
+
|
|
234
|
+
deals: list[Deal] = []
|
|
235
|
+
for promo in promotions:
|
|
236
|
+
code = promo.get("code")
|
|
237
|
+
if not code:
|
|
238
|
+
continue
|
|
239
|
+
|
|
240
|
+
products_response = client.call(
|
|
241
|
+
"silpo_get_products",
|
|
242
|
+
{
|
|
243
|
+
"branchId": cart_context.branch_id,
|
|
244
|
+
"deliveryType": cart_context.delivery_type,
|
|
245
|
+
"timeslotStart": cart_context.timeslot_start,
|
|
246
|
+
"timeslotEnd": cart_context.timeslot_end,
|
|
247
|
+
"mustHavePromotion": True,
|
|
248
|
+
"promotionCode": code,
|
|
249
|
+
"limit": cap_per_category,
|
|
250
|
+
},
|
|
251
|
+
) or {}
|
|
252
|
+
deals.extend(_deals_from_products(products_response.get("products") or [], cap_per_category))
|
|
253
|
+
|
|
254
|
+
deals.sort(key=lambda deal: deal.discount_pct, reverse=True)
|
|
255
|
+
return deals[:limit]
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Substitution Resolver: for each Typical Item, checks current availability
|
|
2
|
+
and, if unavailable, resolves a replacement via `silpo_get_replacements`
|
|
3
|
+
(see prd_reorder_optimizer.md's Substitution Resolver section and
|
|
4
|
+
CONTEXT.md's "Substitution decision" / "Substitution memory" entries).
|
|
5
|
+
|
|
6
|
+
Rules:
|
|
7
|
+
- Zero replacement candidates: item is reported unavailable, not added to
|
|
8
|
+
the cart, and the run does not crash.
|
|
9
|
+
- Exactly one candidate: auto-applied, no prompt.
|
|
10
|
+
- More than one candidate: Substitution Memory (`ReorderLogStore.get_substitution`)
|
|
11
|
+
is consulted first for a prior choice; if one exists it's auto-applied
|
|
12
|
+
without asking. Otherwise the user is asked to pick, and the answer is
|
|
13
|
+
persisted via `ReorderLogStore.set_substitution` for future runs.
|
|
14
|
+
|
|
15
|
+
Runs on the Order Aggregator's output, before the Cart Writer (PRD pipeline:
|
|
16
|
+
Address Resolver -> Cart Context Resolver -> Order Aggregator ->
|
|
17
|
+
Substitution Resolver -> Cart Writer). Needs the `CartContext` resolved by
|
|
18
|
+
#17 (`cart_context.py`) for `branchId`/`companyId`/`deliveryType`/timeslot,
|
|
19
|
+
which every product-facing MCP tool below requires.
|
|
20
|
+
|
|
21
|
+
Real schema (live-verified, see ../../docs/mcp_schema.md's "Product search /
|
|
22
|
+
replacement tools" section):
|
|
23
|
+
- No `silpo_check_availability` tool exists. Availability is checked via
|
|
24
|
+
`silpo_find_products_batch({"branchId", "deliveryType", "timeslotStart",
|
|
25
|
+
"timeslotEnd", "products": [...], "limit"})` (NOTE: no `companyId` in this
|
|
26
|
+
tool's schema), one batched call across all typical items, using each
|
|
27
|
+
item's `name` as the search query where available (falling back to
|
|
28
|
+
`product_id` for items without one, e.g. substitution/promo results --
|
|
29
|
+
see `_search_query`; `TypicalItem.name` was added in issue #19). Response:
|
|
30
|
+
`{"queries": [{"query", "totalFound", "products": [...]}]}`; a product is
|
|
31
|
+
considered available if the top result for its query has `available: True`
|
|
32
|
+
and `stock > 0` (the real product-record shape:
|
|
33
|
+
`{"id", "name", "slug", "price", "oldPrice", "stock", "available", ...}`).
|
|
34
|
+
- `silpo_get_replacements({"branchId", "companyId", "productIds": [...],
|
|
35
|
+
"deliveryType"})` is a genuine BATCH call, one call for all unavailable
|
|
36
|
+
items rather than one per item. Response: `{"success", "summary",
|
|
37
|
+
"items": [...]}`. Tested live against real out-of-stock items and got an
|
|
38
|
+
empty `items` array ("Found replacements for 0 products") -- the populated
|
|
39
|
+
shape of entries inside `items[]` is UNCONFIRMED. This module assumes each
|
|
40
|
+
entry looks like `{"productId": <original id>, "replacements": [<product
|
|
41
|
+
record>, ...]}`, normalizing a single dict to a one-item list the same way
|
|
42
|
+
`address_resolver.py` handles `silpo_find_address`. This is a documented
|
|
43
|
+
guess, not a verified shape -- see docs/mcp_schema.md. Candidate id lookups
|
|
44
|
+
read `"id"` first, falling back to `"productId"`, for the same reason.
|
|
45
|
+
|
|
46
|
+
If `cart_context.branch_id` is `None` (no cart resolved yet --
|
|
47
|
+
`resolve_cart_context` returns an all-None `CartContext` on a first-ever run
|
|
48
|
+
or cleared cart, see cart_context.py), both MCP calls are skipped entirely
|
|
49
|
+
and every item is reported unavailable rather than sending `None` fields to
|
|
50
|
+
the real API. If `branch_id` is present but `company_id` is not (the
|
|
51
|
+
address-resolver fallback, issue #29, never has a `company_id` to give --
|
|
52
|
+
see cart_context.py), availability checking still runs (`silpo_find_products_batch`
|
|
53
|
+
doesn't take a `companyId` at all), but `silpo_get_replacements` is skipped
|
|
54
|
+
since it requires one -- unavailable items in that case are reported with no
|
|
55
|
+
replacement candidates found, rather than sending `None` as `companyId`.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
from dataclasses import dataclass
|
|
59
|
+
|
|
60
|
+
from silpo_agent.cart_context import CartContext
|
|
61
|
+
from silpo_agent.order_aggregator import TypicalItem
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class SubstitutionResult:
|
|
66
|
+
items: list[TypicalItem]
|
|
67
|
+
substitutions: list[tuple[str, str]]
|
|
68
|
+
unavailable: list[str]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _candidate_id(candidate: dict) -> str | None:
|
|
72
|
+
# "id" matches the general product-record shape used elsewhere; "productId"
|
|
73
|
+
# is a defensive fallback since the populated silpo_get_replacements item
|
|
74
|
+
# shape is still unconfirmed live (see module docstring).
|
|
75
|
+
return candidate.get("id") or candidate.get("productId")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _to_item(candidate: dict, frequency: float, fallback_price: float) -> TypicalItem:
|
|
79
|
+
return TypicalItem(
|
|
80
|
+
product_id=_candidate_id(candidate),
|
|
81
|
+
frequency=frequency,
|
|
82
|
+
last_known_price=candidate.get("price", fallback_price),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _search_query(item: TypicalItem) -> str:
|
|
87
|
+
# A real product name (carried by TypicalItem as of issue #19) is a far
|
|
88
|
+
# better free-text search query than a raw product_id/UUID; fall back to
|
|
89
|
+
# product_id for items that don't have one (e.g. substitution/promo
|
|
90
|
+
# results, which don't carry a name through).
|
|
91
|
+
return item.name or item.product_id
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_FIND_PRODUCTS_BATCH_MAX = 30
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _check_availability(client, items: list[TypicalItem], cart_context: CartContext) -> dict[str, bool]:
|
|
98
|
+
"""Batched `silpo_get_replacements`-adjacent availability lookup via
|
|
99
|
+
`silpo_find_products_batch`, keyed by each item's search query (see
|
|
100
|
+
`_search_query`). Returns {product_id: is_available}.
|
|
101
|
+
|
|
102
|
+
`silpo_find_products_batch` rejects more than 30 products per call
|
|
103
|
+
(real, live-observed limit -- a wide typical-item net, e.g. a low
|
|
104
|
+
--threshold or high --last, can easily exceed it), so queries are
|
|
105
|
+
chunked."""
|
|
106
|
+
if not items:
|
|
107
|
+
return {}
|
|
108
|
+
|
|
109
|
+
query_to_ids: dict[str, list[str]] = {}
|
|
110
|
+
for item in items:
|
|
111
|
+
query_to_ids.setdefault(_search_query(item), []).append(item.product_id)
|
|
112
|
+
|
|
113
|
+
queries = list(query_to_ids)
|
|
114
|
+
availability: dict[str, bool] = {}
|
|
115
|
+
for i in range(0, len(queries), _FIND_PRODUCTS_BATCH_MAX):
|
|
116
|
+
chunk = queries[i : i + _FIND_PRODUCTS_BATCH_MAX]
|
|
117
|
+
response = (
|
|
118
|
+
client.call(
|
|
119
|
+
"silpo_find_products_batch",
|
|
120
|
+
{
|
|
121
|
+
"branchId": cart_context.branch_id,
|
|
122
|
+
"deliveryType": cart_context.delivery_type,
|
|
123
|
+
"timeslotStart": cart_context.timeslot_start,
|
|
124
|
+
"timeslotEnd": cart_context.timeslot_end,
|
|
125
|
+
"products": chunk,
|
|
126
|
+
"limit": 1,
|
|
127
|
+
},
|
|
128
|
+
)
|
|
129
|
+
or {}
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
for query_result in response.get("queries") or []:
|
|
133
|
+
query = query_result.get("query")
|
|
134
|
+
products = query_result.get("products") or []
|
|
135
|
+
top = products[0] if products else None
|
|
136
|
+
is_available = bool(top and top.get("available") and (top.get("stock") or 0) > 0)
|
|
137
|
+
for product_id in query_to_ids.get(query, []):
|
|
138
|
+
availability[product_id] = is_available
|
|
139
|
+
return availability
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _fetch_replacements(client, items: list[TypicalItem], cart_context: CartContext) -> dict[str, list[dict]]:
|
|
143
|
+
"""One batched `silpo_get_replacements` call for all unavailable items.
|
|
144
|
+
Returns {original_product_id: [candidate_product_record, ...]}."""
|
|
145
|
+
if not items:
|
|
146
|
+
return {}
|
|
147
|
+
|
|
148
|
+
response = (
|
|
149
|
+
client.call(
|
|
150
|
+
"silpo_get_replacements",
|
|
151
|
+
{
|
|
152
|
+
"branchId": cart_context.branch_id,
|
|
153
|
+
"companyId": cart_context.company_id,
|
|
154
|
+
"productIds": [item.product_id for item in items],
|
|
155
|
+
"deliveryType": cart_context.delivery_type,
|
|
156
|
+
},
|
|
157
|
+
)
|
|
158
|
+
or {}
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
replacements: dict[str, list[dict]] = {}
|
|
162
|
+
for entry in response.get("items") or []:
|
|
163
|
+
product_id = entry.get("productId")
|
|
164
|
+
candidates = entry.get("replacements") or []
|
|
165
|
+
if isinstance(candidates, dict):
|
|
166
|
+
candidates = [candidates]
|
|
167
|
+
replacements[product_id] = candidates
|
|
168
|
+
return replacements
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _resolve_one(
|
|
172
|
+
item: TypicalItem, candidates: list[dict], log_store, input_fn, print_fn
|
|
173
|
+
) -> tuple[TypicalItem | None, str | None]:
|
|
174
|
+
"""Returns (resolved_item_or_None, substituted_from_product_id_or_None)."""
|
|
175
|
+
if not candidates:
|
|
176
|
+
return None, None
|
|
177
|
+
|
|
178
|
+
if len(candidates) == 1:
|
|
179
|
+
return _to_item(candidates[0], item.frequency, item.last_known_price), item.product_id
|
|
180
|
+
|
|
181
|
+
remembered_id = log_store.get_substitution(item.product_id)
|
|
182
|
+
if remembered_id is not None:
|
|
183
|
+
match = next((c for c in candidates if _candidate_id(c) == remembered_id), None)
|
|
184
|
+
price = match.get("price", item.last_known_price) if match else item.last_known_price
|
|
185
|
+
return TypicalItem(product_id=remembered_id, frequency=item.frequency, last_known_price=price), item.product_id
|
|
186
|
+
|
|
187
|
+
print_fn(f"{item.product_id} is unavailable. Choose a replacement:")
|
|
188
|
+
for i, candidate in enumerate(candidates, start=1):
|
|
189
|
+
print_fn(f"{i}. {_candidate_id(candidate)}")
|
|
190
|
+
choice = input_fn("Pick a number: ").strip()
|
|
191
|
+
idx = int(choice) if choice.isdigit() else None
|
|
192
|
+
if not idx or not (1 <= idx <= len(candidates)):
|
|
193
|
+
print_fn(f"No candidate numbered {choice!r}.")
|
|
194
|
+
return None, None
|
|
195
|
+
|
|
196
|
+
chosen = candidates[idx - 1]
|
|
197
|
+
log_store.set_substitution(item.product_id, _candidate_id(chosen))
|
|
198
|
+
return _to_item(chosen, item.frequency, item.last_known_price), item.product_id
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def resolve_substitutions(
|
|
202
|
+
client,
|
|
203
|
+
log_store,
|
|
204
|
+
typical_items: list[TypicalItem],
|
|
205
|
+
cart_context: CartContext,
|
|
206
|
+
*,
|
|
207
|
+
input_fn=None,
|
|
208
|
+
print_fn=None,
|
|
209
|
+
) -> SubstitutionResult:
|
|
210
|
+
input_fn = input_fn or input
|
|
211
|
+
print_fn = print_fn or print
|
|
212
|
+
|
|
213
|
+
if not cart_context.branch_id:
|
|
214
|
+
# No cart context resolved yet (first-ever run, or a cleared cart --
|
|
215
|
+
# resolve_cart_context returns an all-None CartContext in that case,
|
|
216
|
+
# see cart_context.py). silpo_find_products_batch requires branchId;
|
|
217
|
+
# sending None would fail against the real API. Skip both lookups and
|
|
218
|
+
# report every item unavailable rather than crashing.
|
|
219
|
+
return SubstitutionResult(
|
|
220
|
+
items=[], substitutions=[], unavailable=[item.product_id for item in typical_items]
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
availability = _check_availability(client, typical_items, cart_context)
|
|
224
|
+
unavailable_items = [item for item in typical_items if not availability.get(item.product_id)]
|
|
225
|
+
# silpo_get_replacements requires companyId, unlike silpo_find_products_batch
|
|
226
|
+
# above -- the address-resolver fallback (issue #29) can legitimately
|
|
227
|
+
# produce a branch_id with no company_id (the real
|
|
228
|
+
# silpo_get_available_delivery_types response never carries one), so this
|
|
229
|
+
# lookup is skipped in that case rather than sending a None companyId;
|
|
230
|
+
# affected items simply have no replacement candidates found.
|
|
231
|
+
replacements = _fetch_replacements(client, unavailable_items, cart_context) if cart_context.company_id else {}
|
|
232
|
+
|
|
233
|
+
items: list[TypicalItem] = []
|
|
234
|
+
substitutions: list[tuple[str, str]] = []
|
|
235
|
+
unavailable: list[str] = []
|
|
236
|
+
|
|
237
|
+
for item in typical_items:
|
|
238
|
+
if availability.get(item.product_id):
|
|
239
|
+
items.append(item)
|
|
240
|
+
continue
|
|
241
|
+
|
|
242
|
+
resolved, original_id = _resolve_one(
|
|
243
|
+
item, replacements.get(item.product_id, []), log_store, input_fn, print_fn
|
|
244
|
+
)
|
|
245
|
+
if resolved is None:
|
|
246
|
+
unavailable.append(item.product_id)
|
|
247
|
+
else:
|
|
248
|
+
items.append(resolved)
|
|
249
|
+
substitutions.append((original_id, resolved.product_id))
|
|
250
|
+
|
|
251
|
+
return SubstitutionResult(items=items, substitutions=substitutions, unavailable=unavailable)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Formats a raw UTC timeslot (start/end ISO8601 strings from the MCP API)
|
|
2
|
+
into the local timezone with "Today"/"Tomorrow" wording -- the raw strings
|
|
3
|
+
are always UTC (+00:00), which reads as a foreign, hard-to-place time
|
|
4
|
+
without doing the tz math in your head first.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from datetime import date, datetime, timedelta
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def format_timeslot(start: str | None, end: str | None) -> str:
|
|
11
|
+
if not start or not end:
|
|
12
|
+
return f"{start} - {end}"
|
|
13
|
+
try:
|
|
14
|
+
local_start = datetime.fromisoformat(start).astimezone()
|
|
15
|
+
local_end = datetime.fromisoformat(end).astimezone()
|
|
16
|
+
except ValueError:
|
|
17
|
+
return f"{start} - {end}"
|
|
18
|
+
|
|
19
|
+
today = date.today()
|
|
20
|
+
slot_date = local_start.date()
|
|
21
|
+
if slot_date == today:
|
|
22
|
+
day = "Today"
|
|
23
|
+
elif slot_date == today + timedelta(days=1):
|
|
24
|
+
day = "Tomorrow"
|
|
25
|
+
else:
|
|
26
|
+
day = local_start.strftime("%d.%m")
|
|
27
|
+
|
|
28
|
+
return f"{day}, {local_start:%H:%M}-{local_end:%H:%M}"
|