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,52 @@
|
|
|
1
|
+
"""Weekly grocery norm dataset: per-person quantities by basket type
|
|
2
|
+
(basic/eco/premium), ported from the household-basket research (see
|
|
3
|
+
.scratch/smart-cart/issues/01-norm-dataset.md). Pure data, no network calls
|
|
4
|
+
-- same shape as order_aggregator.py's TypicalItem/derive_typical_items.
|
|
5
|
+
Seasonality (in-season months, price multipliers) from the research is
|
|
6
|
+
deliberately not carried over -- out of scope for this feature.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class NormItem:
|
|
14
|
+
category: str
|
|
15
|
+
name_ua: str
|
|
16
|
+
quantity_per_person: float
|
|
17
|
+
unit: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_NORMS: dict[str, list[NormItem]] = {
|
|
21
|
+
"basic": [
|
|
22
|
+
NormItem("vegetables", "Картопля", 0.5, "kg"),
|
|
23
|
+
NormItem("fruits", "Яблука", 0.4, "kg"),
|
|
24
|
+
NormItem("protein", "Куряче філе", 0.25, "kg"),
|
|
25
|
+
NormItem("dairy", "Молоко", 0.5, "l"),
|
|
26
|
+
NormItem("grains", "Гречка", 0.1, "kg"),
|
|
27
|
+
NormItem("pantry", "Олія соняшникова", 0.03, "l"),
|
|
28
|
+
],
|
|
29
|
+
"eco": [
|
|
30
|
+
NormItem("vegetables", "Картопля", 0.5, "kg"),
|
|
31
|
+
NormItem("fruits", "Яблука", 0.5, "kg"),
|
|
32
|
+
NormItem("protein", "Куряче філе", 0.3, "kg"),
|
|
33
|
+
NormItem("dairy", "Молоко", 0.6, "l"),
|
|
34
|
+
NormItem("grains", "Гречка", 0.12, "kg"),
|
|
35
|
+
NormItem("pantry", "Олія соняшникова", 0.03, "l"),
|
|
36
|
+
],
|
|
37
|
+
"premium": [
|
|
38
|
+
NormItem("vegetables", "Картопля", 0.5, "kg"),
|
|
39
|
+
NormItem("fruits", "Яблука", 0.6, "kg"),
|
|
40
|
+
NormItem("fruits", "Сезонні ягоди", 0.3, "kg"),
|
|
41
|
+
NormItem("protein", "Куряче філе", 0.4, "kg"),
|
|
42
|
+
NormItem("dairy", "Молоко", 0.7, "l"),
|
|
43
|
+
NormItem("grains", "Гречка", 0.15, "kg"),
|
|
44
|
+
NormItem("pantry", "Олія соняшникова", 0.03, "l"),
|
|
45
|
+
],
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def get_norms(basket_type: str) -> list[NormItem]:
|
|
50
|
+
if basket_type not in _NORMS:
|
|
51
|
+
raise ValueError(f"unknown basket_type {basket_type!r}, expected one of {sorted(_NORMS)}")
|
|
52
|
+
return _NORMS[basket_type]
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Norm Top-Up (ticket 04, part of the smart-cart feature): after typical
|
|
2
|
+
items and favorites-deals are assembled, checks each category in the norm
|
|
3
|
+
dataset (norm_dataset.py, scaled by --people/--basket-type) against what's
|
|
4
|
+
already going into the cart, and proposes an addition for any category with
|
|
5
|
+
no real product-id overlap.
|
|
6
|
+
|
|
7
|
+
Coverage is a real id intersection, not "did we search for the same
|
|
8
|
+
product": resolve the category's real product list (`promo_scanner.
|
|
9
|
+
resolve_category` + `silpo_get_products(category=slug)`, the same pattern
|
|
10
|
+
`deals --category` already uses) and check whether any id already going
|
|
11
|
+
into the cart (typical items union favorites-deals, passed in by the
|
|
12
|
+
caller) belongs to it. Presence-only "did we search for the same id" was
|
|
13
|
+
explicitly rejected in the ticket -- it produces near-permanent false
|
|
14
|
+
negatives (a user's usual potato SKU will essentially never equal an
|
|
15
|
+
explicit search result's SKU).
|
|
16
|
+
|
|
17
|
+
`NormItem.category` is an internal English tag (vegetables/fruits/protein/
|
|
18
|
+
dairy/grains/pantry, see norm_dataset.py), not a real Silpo category title
|
|
19
|
+
-- `_CATEGORY_SEARCH_QUERY` below maps each tag to a Ukrainian query fed to
|
|
20
|
+
`resolve_category`'s exact-then-shortest-substring matching. Live-verified
|
|
21
|
+
2026-08-06 against a real authenticated session via `silpo-agent deals
|
|
22
|
+
--list-categories`: 5 of the 6 (vegetables/fruits/protein/grains/pantry) are
|
|
23
|
+
exact matches in the real category tree. "dairy" has no exact match --
|
|
24
|
+
"Молочні продукти" is a substring of two real titles, "Молочні продукти та
|
|
25
|
+
яйця" and "Молочні продукти для дітей" -- confirmed live that
|
|
26
|
+
`resolve_category`'s shortest-title-wins fallback picks the former, the
|
|
27
|
+
correct general dairy+eggs category, not a wrong one; the guess was updated
|
|
28
|
+
to that exact title so all 6 now resolve via exact match. A category tag
|
|
29
|
+
whose guess nonetheless fails to match anything real (e.g. the live
|
|
30
|
+
category tree changes) resolves to `None` and is conservatively treated as
|
|
31
|
+
uncovered (see `find_uncovered_categories`) rather than silently skipped.
|
|
32
|
+
|
|
33
|
+
Norm items found uncovered are searched for by product name (`name_ua`) via
|
|
34
|
+
a batched `silpo_find_products_batch` call -- the exact pattern
|
|
35
|
+
`substitution_resolver._check_availability` already uses for typical items
|
|
36
|
+
(same endpoint, same chunking limit, same {"queries": [{"query",
|
|
37
|
+
"totalFound", "products"}]} response shape). Norm items deliberately do NOT
|
|
38
|
+
route through `resolve_substitutions`/`silpo_get_replacements`: per ticket
|
|
39
|
+
03's review, that machinery's `_to_item`/remembered-substitution branch
|
|
40
|
+
silently drops `quantity` (and `company_id`/`branch_id`/`name`) when
|
|
41
|
+
constructing a replacement `TypicalItem`, and isn't designed for a one-off
|
|
42
|
+
speculative add in the first place. Availability (top result's `available`/
|
|
43
|
+
`stock`) is therefore checked right here instead.
|
|
44
|
+
|
|
45
|
+
Product record shape (docs/mcp_schema.md's "Product search / replacement
|
|
46
|
+
tools" section, same shape for `silpo_get_products`/`silpo_find_products_
|
|
47
|
+
batch`/`silpo_get_similar_products`): `{"id", "name", "slug", "price",
|
|
48
|
+
"oldPrice", "stock", "available", "weighted", "step", ...}` -- the step
|
|
49
|
+
field for a *search-result* product record is `step`, not `addToBasketStep`
|
|
50
|
+
(that spelling only appears in `silpo_get_shopping_cart_by_id`'s own
|
|
51
|
+
already-in-cart product record, a different endpoint). Read `step` first,
|
|
52
|
+
falling back to `addToBasketStep` defensively in case a given category ever
|
|
53
|
+
returns the other shape.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
from dataclasses import dataclass
|
|
57
|
+
|
|
58
|
+
from silpo_agent.cart_context import CartContext
|
|
59
|
+
from silpo_agent.cart_writer import round_to_step
|
|
60
|
+
from silpo_agent.norm_dataset import NormItem
|
|
61
|
+
from silpo_agent.order_aggregator import TypicalItem
|
|
62
|
+
from silpo_agent.promo_scanner import _fetch_all_categories, resolve_category_from_list
|
|
63
|
+
|
|
64
|
+
_FIND_PRODUCTS_BATCH_MAX = 30
|
|
65
|
+
|
|
66
|
+
# silpo_get_products's `limit` hard-rejects anything over 100 (confirmed
|
|
67
|
+
# live: "Too big: expected number to be <=100"). Some categories list
|
|
68
|
+
# thousands of products (promo_scanner.py's DEFAULT_CATEGORY_CAP docstring),
|
|
69
|
+
# so a coverage check against only the first 100 can still miss a real match
|
|
70
|
+
# -- same accepted tradeoff promo_scanner.py's own category cap already
|
|
71
|
+
# makes, not new risk introduced here.
|
|
72
|
+
_CATEGORY_PRODUCTS_CAP = 100
|
|
73
|
+
|
|
74
|
+
# Ukrainian query per norm_dataset.py category tag, fed through
|
|
75
|
+
# resolve_category's exact-then-shortest-substring matching. Live-verified
|
|
76
|
+
# 2026-08-06 -- see module docstring.
|
|
77
|
+
_CATEGORY_SEARCH_QUERY = {
|
|
78
|
+
"vegetables": "Овочі",
|
|
79
|
+
"fruits": "Фрукти",
|
|
80
|
+
"protein": "М'ясо",
|
|
81
|
+
"dairy": "Молочні продукти та яйця",
|
|
82
|
+
"grains": "Крупи",
|
|
83
|
+
"pantry": "Бакалія",
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def find_uncovered_categories(
|
|
88
|
+
client,
|
|
89
|
+
cart_context: CartContext,
|
|
90
|
+
norms: list[NormItem],
|
|
91
|
+
existing_product_ids: set[str],
|
|
92
|
+
*,
|
|
93
|
+
cap: int = _CATEGORY_PRODUCTS_CAP,
|
|
94
|
+
print_fn=None,
|
|
95
|
+
) -> list[NormItem]:
|
|
96
|
+
"""Norm items whose category has no real id overlap with
|
|
97
|
+
`existing_product_ids` (typical items union favorites-deals). A category
|
|
98
|
+
tag that fails to resolve to a real category (see `_CATEGORY_SEARCH_QUERY`
|
|
99
|
+
-- live-verified 2026-08-06, but the live category tree can still change)
|
|
100
|
+
is treated as uncovered -- we have no real product list to check
|
|
101
|
+
coverage against, so err on proposing rather than silently dropping it
|
|
102
|
+
-- and a warning is printed so a future mismatch doesn't fail silently on
|
|
103
|
+
every single run.
|
|
104
|
+
|
|
105
|
+
Fetches the (paginated) category tree once via `_fetch_all_categories`
|
|
106
|
+
and matches all of `norms`'s distinct category tags against that one
|
|
107
|
+
in-memory list (`promo_scanner.resolve_category_from_list`), rather than
|
|
108
|
+
re-fetching the whole tree per category tag -- up to 6x fewer round
|
|
109
|
+
trips per smart-cart run.
|
|
110
|
+
"""
|
|
111
|
+
print_fn = print_fn or print
|
|
112
|
+
categories = sorted({item.category for item in norms})
|
|
113
|
+
all_categories = _fetch_all_categories(client, cart_context)
|
|
114
|
+
uncovered: set[str] = set()
|
|
115
|
+
|
|
116
|
+
for category in categories:
|
|
117
|
+
query = _CATEGORY_SEARCH_QUERY.get(category, category)
|
|
118
|
+
match = resolve_category_from_list(all_categories, query)
|
|
119
|
+
if match is None:
|
|
120
|
+
print_fn(
|
|
121
|
+
f"norm top-up: could not resolve category {category!r} (guessed {query!r}); "
|
|
122
|
+
"treating as uncovered."
|
|
123
|
+
)
|
|
124
|
+
uncovered.add(category)
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
response = (
|
|
128
|
+
client.call(
|
|
129
|
+
"silpo_get_products",
|
|
130
|
+
{
|
|
131
|
+
"branchId": cart_context.branch_id,
|
|
132
|
+
"deliveryType": cart_context.delivery_type,
|
|
133
|
+
"timeslotStart": cart_context.timeslot_start,
|
|
134
|
+
"timeslotEnd": cart_context.timeslot_end,
|
|
135
|
+
"category": match.slug,
|
|
136
|
+
"limit": cap,
|
|
137
|
+
},
|
|
138
|
+
)
|
|
139
|
+
or {}
|
|
140
|
+
)
|
|
141
|
+
category_ids = {p.get("id") for p in response.get("products") or []}
|
|
142
|
+
if category_ids.isdisjoint(existing_product_ids):
|
|
143
|
+
uncovered.add(category)
|
|
144
|
+
|
|
145
|
+
return [item for item in norms if item.category in uncovered]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass(frozen=True)
|
|
149
|
+
class NormTopUpResult:
|
|
150
|
+
items: list[TypicalItem]
|
|
151
|
+
skipped: list[str] # name_ua of norm items skipped (no/unavailable result)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def resolve_norm_top_up_items(
|
|
155
|
+
client,
|
|
156
|
+
cart_context: CartContext,
|
|
157
|
+
norm_items: list[NormItem],
|
|
158
|
+
people: int,
|
|
159
|
+
*,
|
|
160
|
+
print_fn=None,
|
|
161
|
+
) -> NormTopUpResult:
|
|
162
|
+
"""Searches each uncovered norm item by name (batched), skips anything
|
|
163
|
+
with zero results or an unavailable top result, and computes the cart
|
|
164
|
+
quantity (`quantity_per_person * people`, rounded to a valid step) for
|
|
165
|
+
the rest."""
|
|
166
|
+
print_fn = print_fn or print
|
|
167
|
+
|
|
168
|
+
if not norm_items:
|
|
169
|
+
return NormTopUpResult(items=[], skipped=[])
|
|
170
|
+
|
|
171
|
+
query_names = list({item.name_ua for item in norm_items})
|
|
172
|
+
top_by_query: dict[str, dict | None] = {}
|
|
173
|
+
for i in range(0, len(query_names), _FIND_PRODUCTS_BATCH_MAX):
|
|
174
|
+
chunk = query_names[i : i + _FIND_PRODUCTS_BATCH_MAX]
|
|
175
|
+
response = (
|
|
176
|
+
client.call(
|
|
177
|
+
"silpo_find_products_batch",
|
|
178
|
+
{
|
|
179
|
+
"branchId": cart_context.branch_id,
|
|
180
|
+
"deliveryType": cart_context.delivery_type,
|
|
181
|
+
"timeslotStart": cart_context.timeslot_start,
|
|
182
|
+
"timeslotEnd": cart_context.timeslot_end,
|
|
183
|
+
"products": chunk,
|
|
184
|
+
"limit": 1,
|
|
185
|
+
},
|
|
186
|
+
)
|
|
187
|
+
or {}
|
|
188
|
+
)
|
|
189
|
+
for query_result in response.get("queries") or []:
|
|
190
|
+
products = query_result.get("products") or []
|
|
191
|
+
top_by_query[query_result.get("query")] = products[0] if products else None
|
|
192
|
+
|
|
193
|
+
items: list[TypicalItem] = []
|
|
194
|
+
skipped: list[str] = []
|
|
195
|
+
for norm_item in norm_items:
|
|
196
|
+
product = top_by_query.get(norm_item.name_ua)
|
|
197
|
+
is_available = bool(product and product.get("available") and (product.get("stock") or 0) > 0)
|
|
198
|
+
if not is_available:
|
|
199
|
+
print_fn(f"norm top-up: no available product found for {norm_item.name_ua!r}; skipping.")
|
|
200
|
+
skipped.append(norm_item.name_ua)
|
|
201
|
+
continue
|
|
202
|
+
|
|
203
|
+
raw_quantity = norm_item.quantity_per_person * people
|
|
204
|
+
step = product.get("step")
|
|
205
|
+
if step is None:
|
|
206
|
+
step = product.get("addToBasketStep")
|
|
207
|
+
quantity = round_to_step(raw_quantity, weighted=bool(product.get("weighted")), step=step)
|
|
208
|
+
|
|
209
|
+
items.append(
|
|
210
|
+
TypicalItem(
|
|
211
|
+
product_id=product.get("id"),
|
|
212
|
+
frequency=0.0,
|
|
213
|
+
last_known_price=product.get("price"),
|
|
214
|
+
company_id=product.get("companyId"),
|
|
215
|
+
branch_id=product.get("branchId"),
|
|
216
|
+
name=product.get("name"),
|
|
217
|
+
quantity=quantity,
|
|
218
|
+
)
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
return NormTopUpResult(items=items, skipped=skipped)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Order Aggregator: pure function that derives Typical Items from raw online
|
|
2
|
+
orders. No network calls, no side effects, fully unit-testable against
|
|
3
|
+
fixture order data.
|
|
4
|
+
|
|
5
|
+
Input order shape (live-verified against `silpo_get_my_online_orders`, see
|
|
6
|
+
../../docs/mcp_schema.md's "Order history tools" section): each order is a
|
|
7
|
+
dict with a "products" list, each line item a dict with "id", "name",
|
|
8
|
+
"price", "companyId", "branchId", and a "removed" bool ("removed": true
|
|
9
|
+
means the item was pulled from the order after ordering but before
|
|
10
|
+
delivery, though it's still listed with its original price/subtotal --
|
|
11
|
+
these are skipped when counting frequency and determining last known
|
|
12
|
+
price/company/branch/name). `name` is carried through so downstream
|
|
13
|
+
consumers (Cart Writer's plastic-bag filter, issue #19) can match on it.
|
|
14
|
+
Orders are returned newest-first by `silpo_get_my_online_orders` (confirmed
|
|
15
|
+
live), and are assumed to already be confirmed/paid orders (the tool's own
|
|
16
|
+
semantics, per CONTEXT.md's Reorder log entry) -- this function does not
|
|
17
|
+
filter on a paid/confirmed status field.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class InsufficientOrderHistoryError(Exception):
|
|
24
|
+
"""Raised when fewer than `last` orders exist (including zero)."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class TypicalItem:
|
|
29
|
+
product_id: str
|
|
30
|
+
frequency: float
|
|
31
|
+
last_known_price: float
|
|
32
|
+
company_id: str | None = None
|
|
33
|
+
branch_id: str | None = None
|
|
34
|
+
name: str | None = None
|
|
35
|
+
quantity: float = 1.0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def derive_typical_items(orders: list[dict], last: int, threshold: float) -> list[TypicalItem]:
|
|
39
|
+
if len(orders) < last:
|
|
40
|
+
raise InsufficientOrderHistoryError(
|
|
41
|
+
f"need at least {last} past orders to determine typical items, found {len(orders)}"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
considered = orders[:last]
|
|
45
|
+
|
|
46
|
+
counts: dict[str, int] = {}
|
|
47
|
+
last_known_price: dict[str, float] = {}
|
|
48
|
+
last_known_context: dict[str, tuple[str | None, str | None, str | None]] = {}
|
|
49
|
+
for order in considered:
|
|
50
|
+
active_lines = [line for line in order.get("products", []) if not line.get("removed", False)]
|
|
51
|
+
for product_id in {line["id"] for line in active_lines}:
|
|
52
|
+
counts[product_id] = counts.get(product_id, 0) + 1
|
|
53
|
+
for line in active_lines:
|
|
54
|
+
product_id = line["id"]
|
|
55
|
+
last_known_price.setdefault(product_id, line["price"])
|
|
56
|
+
last_known_context.setdefault(
|
|
57
|
+
product_id, (line.get("companyId"), line.get("branchId"), line.get("name"))
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
typical = [
|
|
61
|
+
TypicalItem(
|
|
62
|
+
product_id=product_id,
|
|
63
|
+
frequency=count / len(considered),
|
|
64
|
+
last_known_price=last_known_price[product_id],
|
|
65
|
+
company_id=last_known_context[product_id][0],
|
|
66
|
+
branch_id=last_known_context[product_id][1],
|
|
67
|
+
name=last_known_context[product_id][2],
|
|
68
|
+
)
|
|
69
|
+
for product_id, count in counts.items()
|
|
70
|
+
if count / len(considered) >= threshold
|
|
71
|
+
]
|
|
72
|
+
typical.sort(key=lambda item: (-item.frequency, item.product_id))
|
|
73
|
+
return typical
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Similar-Products Promo Finder (issue #28, shared by `cart promos` and,
|
|
2
|
+
per issue #31, `cart edit`'s promo-browse replacement path).
|
|
3
|
+
|
|
4
|
+
Given a product's `slug` (cart items already carry their own `slug` -- see
|
|
5
|
+
`cart.shipments[0].products[].slug` in docs/mcp_schema.md's "Cart tools"
|
|
6
|
+
section), calls `silpo_get_similar_products` and filters the results to
|
|
7
|
+
candidates that are genuinely discounted right now (`oldPrice` present and
|
|
8
|
+
strictly greater than `price`), ranked by discount size (`oldPrice - price`,
|
|
9
|
+
descending).
|
|
10
|
+
|
|
11
|
+
Deliberately NOT category-based or keyword/text-matching: confirmed live
|
|
12
|
+
that no product record anywhere in this API carries a category id (see
|
|
13
|
+
docs/mcp_schema.md's "Product search / replacement tools" section), so
|
|
14
|
+
Silpo's own similarity engine (`silpo_get_similar_products`) is used as the
|
|
15
|
+
real signal instead, same design decision already made for
|
|
16
|
+
`promo_optimizer.py` (issue #20) and `coupons_lister.py` (issue #36).
|
|
17
|
+
|
|
18
|
+
Real schema (live-verified, docs/mcp_schema.md's "Product search /
|
|
19
|
+
replacement tools" section):
|
|
20
|
+
- `silpo_get_similar_products({"branchId", "slug", "deliveryType", "limit",
|
|
21
|
+
"offset"})` -> `{"success", "summary", "products": [...], "meta":
|
|
22
|
+
{"total"}}`, `products[]` using the general product-record shape
|
|
23
|
+
(`"id"`, `"name"`, `"slug"`, `"price"`, `"oldPrice"`, `"companyId"`,
|
|
24
|
+
`"branchId"`, ...).
|
|
25
|
+
|
|
26
|
+
Plastic-bag-style candidates (e.g. "пакет майка") are filtered out before
|
|
27
|
+
ranking, same convention as `cart_writer.py`'s `_is_plastic_bag` (matched
|
|
28
|
+
case-insensitively on the candidate's `name` containing "пакет") -- bags are
|
|
29
|
+
added automatically at order fulfillment and should never surface as a
|
|
30
|
+
promo alternative (docs/mcp_schema.md / issue #26 PRD).
|
|
31
|
+
|
|
32
|
+
Public interface: `find_promo_alternatives(client, cart_context, slug,
|
|
33
|
+
*, limit=10) -> list[PromoCandidate]`. Takes a plain `client` +
|
|
34
|
+
`CartContext` (for `branchId`/`deliveryType`) + `slug`, not anything
|
|
35
|
+
CLI-specific, so issue #31's `cart edit` promo-browse path can call it
|
|
36
|
+
as-is with no duplicated similarity/discount-filtering logic.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from dataclasses import dataclass
|
|
40
|
+
|
|
41
|
+
from silpo_agent.cart_context import CartContext
|
|
42
|
+
|
|
43
|
+
_PLASTIC_BAG_KEYWORD = "пакет"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class PromoCandidate:
|
|
48
|
+
product_id: str | None
|
|
49
|
+
name: str
|
|
50
|
+
slug: str | None
|
|
51
|
+
price: float
|
|
52
|
+
old_price: float
|
|
53
|
+
discount: float
|
|
54
|
+
company_id: str | None
|
|
55
|
+
branch_id: str | None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _is_plastic_bag(name: str) -> bool:
|
|
59
|
+
return bool(name) and _PLASTIC_BAG_KEYWORD in name.lower()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _is_discounted(product: dict) -> bool:
|
|
63
|
+
price = product.get("price")
|
|
64
|
+
old_price = product.get("oldPrice")
|
|
65
|
+
return price is not None and old_price is not None and old_price > price
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def find_promo_alternatives(
|
|
69
|
+
client, cart_context: CartContext, slug: str, *, limit: int = 10
|
|
70
|
+
) -> list[PromoCandidate]:
|
|
71
|
+
response = (
|
|
72
|
+
client.call(
|
|
73
|
+
"silpo_get_similar_products",
|
|
74
|
+
{
|
|
75
|
+
"branchId": cart_context.branch_id,
|
|
76
|
+
"slug": slug,
|
|
77
|
+
"deliveryType": cart_context.delivery_type,
|
|
78
|
+
"limit": limit,
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
or {}
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
products = response.get("products") or []
|
|
85
|
+
candidates = [
|
|
86
|
+
PromoCandidate(
|
|
87
|
+
product_id=product.get("id"),
|
|
88
|
+
name=product.get("name") or "",
|
|
89
|
+
slug=product.get("slug"),
|
|
90
|
+
price=product["price"],
|
|
91
|
+
old_price=product["oldPrice"],
|
|
92
|
+
discount=product["oldPrice"] - product["price"],
|
|
93
|
+
company_id=product.get("companyId"),
|
|
94
|
+
branch_id=product.get("branchId"),
|
|
95
|
+
)
|
|
96
|
+
for product in products
|
|
97
|
+
if isinstance(product, dict) and _is_discounted(product) and not _is_plastic_bag(product.get("name") or "")
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
candidates.sort(key=lambda c: c.discount, reverse=True)
|
|
101
|
+
return candidates
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Promo Optimizer: opt-in module (`--optimize promos`, see cli.py), invoked
|
|
2
|
+
only when the flag is passed. Runs on the Substitution Resolver's resolved
|
|
3
|
+
item set, between it and the Cart Writer.
|
|
4
|
+
|
|
5
|
+
Scope decision (issue #20 -- see docs/mcp_schema.md's "Promo / loyalty
|
|
6
|
+
tools" section for the full live-verified schema this is built against):
|
|
7
|
+
|
|
8
|
+
Narrowed to bonus application only. The original design assumed two tools
|
|
9
|
+
that don't exist on the real MCP server (`silpo_get_promo_equivalent`,
|
|
10
|
+
`silpo_get_available_bonuses`). The real promo-swap mechanism --
|
|
11
|
+
`silpo_get_products({"mustHavePromotion": true, "promotionCode": ...})` --
|
|
12
|
+
is a category/text browse, not a per-product lookup: there's no verified
|
|
13
|
+
free-text search parameter on that tool (only `category`/`mustHavePromotion`/
|
|
14
|
+
`promotionCode`/`set` filters are documented), so matching a Typical Item to
|
|
15
|
+
"its" promo equivalent would mean guessing an unconfirmed filter and/or
|
|
16
|
+
scanning entire promo categories by name -- exactly the unreliable heuristic
|
|
17
|
+
issue #20 explicitly permits dropping. Bonus application, by contrast, is a
|
|
18
|
+
single well-specified field on `silpo_update_shopping_cart` fed by a value
|
|
19
|
+
(`bonus_available`) already returned by the same `silpo_get_shopping_cart_by_id`
|
|
20
|
+
call the Cart Context Resolver (#17) makes -- no new lookup, no matching
|
|
21
|
+
heuristic, nothing speculative. `promoCode` is left `null`:
|
|
22
|
+
`silpo_get_promo_codes()` returned empty for the live test account
|
|
23
|
+
(unverified case, not worth building against per the issue).
|
|
24
|
+
|
|
25
|
+
Real schema (live-verified, see ../../docs/mcp_schema.md):
|
|
26
|
+
- `silpo_update_shopping_cart` is the real "apply bonuses" call --
|
|
27
|
+
`bonusRequested` (number) and `promoCode` (string or null) are two more
|
|
28
|
+
fields on it, alongside `shipments`/`address`/`timeslot`/`deliveryType`,
|
|
29
|
+
which per the tool's own description must be copied from
|
|
30
|
+
`silpo_get_shopping_cart_by_id`'s response as-is, not constructed. Those
|
|
31
|
+
raw values are carried by `CartContext` (extended in cart_context.py for
|
|
32
|
+
this ticket: `.timeslot`/`.address`/`.shipments`/`.bonus_available`).
|
|
33
|
+
|
|
34
|
+
Off by default: `cli.py` only imports/calls this module when
|
|
35
|
+
`--optimize promos` is passed, so a plain `reorder` makes zero calls here
|
|
36
|
+
(verified in test_cli.py's flag-off test).
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from dataclasses import dataclass
|
|
40
|
+
|
|
41
|
+
from silpo_agent.cart_context import CartContext
|
|
42
|
+
from silpo_agent.order_aggregator import TypicalItem
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class PromoResult:
|
|
47
|
+
items: list[TypicalItem]
|
|
48
|
+
bonus_applied: float | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def optimize_promos(client, items: list[TypicalItem], cart_context: CartContext) -> PromoResult:
|
|
52
|
+
bonus = cart_context.bonus_available
|
|
53
|
+
# silpo_update_shopping_cart requires shoppingCartId/deliveryType/timeslot/
|
|
54
|
+
# address/shipments all present (the last four copied from
|
|
55
|
+
# silpo_get_shopping_cart_by_id verbatim, per that tool's own
|
|
56
|
+
# description) -- a resolved-but-incomplete CartContext (e.g. no
|
|
57
|
+
# shipments recorded yet) must skip the call rather than send nulls
|
|
58
|
+
# into required fields, same guard style as substitution_resolver.py's
|
|
59
|
+
# no-cart-context skip (issue #18).
|
|
60
|
+
has_required_context = (
|
|
61
|
+
cart_context.shopping_cart_id
|
|
62
|
+
and cart_context.delivery_type
|
|
63
|
+
and cart_context.timeslot
|
|
64
|
+
and cart_context.address
|
|
65
|
+
and cart_context.shipments
|
|
66
|
+
)
|
|
67
|
+
if not bonus or not has_required_context:
|
|
68
|
+
return PromoResult(items=items)
|
|
69
|
+
|
|
70
|
+
response = (
|
|
71
|
+
client.call(
|
|
72
|
+
"silpo_update_shopping_cart",
|
|
73
|
+
{
|
|
74
|
+
"shoppingCartId": cart_context.shopping_cart_id,
|
|
75
|
+
"deliveryType": cart_context.delivery_type,
|
|
76
|
+
"timeslot": cart_context.timeslot,
|
|
77
|
+
"address": cart_context.address,
|
|
78
|
+
"shipments": cart_context.shipments,
|
|
79
|
+
"bonusRequested": bonus,
|
|
80
|
+
"promoCode": None,
|
|
81
|
+
},
|
|
82
|
+
)
|
|
83
|
+
or {}
|
|
84
|
+
)
|
|
85
|
+
# Mutating call -- don't claim the bonus was applied unless the response
|
|
86
|
+
# says so (every real response in this MCP server is enveloped in
|
|
87
|
+
# {"success": bool, ...}, per docs/mcp_schema.md).
|
|
88
|
+
if not response.get("success"):
|
|
89
|
+
return PromoResult(items=items)
|
|
90
|
+
|
|
91
|
+
return PromoResult(items=items, bonus_applied=bonus)
|