[{"id":"control-001","category":"control","tier":1,"target_file":"shopkit/utils/units.py","repo_sizes":["S","M"],"prompt":"Shipping needs to read package weights typed in by warehouse staff. Create\n`parse_weight(text: str) -> int` that returns the weight in whole grams.\n\nInput is a number (an integer or a decimal using \".\" as separator), optional whitespace, then a\nunit: g, kg, lb or oz, case-insensitive. Leading and trailing whitespace is ignored.\n1 lb = 453.59237 g and 1 oz = 28.349523125 g. Round to the nearest gram.\nRaise ValueError for anything else, including a missing number, a missing or unknown unit,\nnegative values and \",\" as decimal separator.","helpers":[],"decoys":[],"hidden_tests":{"test_parse_weight.py":"import pytest\n\nfrom shopkit.utils.units import parse_weight\n\n\n@pytest.mark.parametrize(\"text,grams\", [\n    (\"250g\", 250), (\"1.5 kg\", 1500), (\"2 LB\", 907), (\"3oz\", 85), (\"  0.25Kg \", 250), (\"0g\", 0),\n])\ndef test_valid(text, grams):\n    assert parse_weight(text) == grams\n\n\n@pytest.mark.parametrize(\"text\", [\"\", \"kg\", \"10\", \"10 stone\", \"-1kg\", \"1,5kg\", \"1.5.2kg\"])\ndef test_invalid(text):\n    with pytest.raises(ValueError):\n        parse_weight(text)\n"},"solutions":{"reference":"diff --color -ruN a/shopkit/utils/units.py b/shopkit/utils/units.py\n--- a/shopkit/utils/units.py\t1969-12-31 16:00:00.000000000 -0800\n+++ b/shopkit/utils/units.py\t2026-11-17 22:01:27.595206479 -0800\n@@ -0,0 +1,7 @@\n+import re\n+_G = {\"g\": 1, \"kg\": 1000, \"lb\": 453.59237, \"oz\": 28.349523125}\n+def parse_weight(text: str) -> int:\n+    m = re.fullmatch(r\"\\s*(\\d+(?:\\.\\d+)?)\\s*([a-zA-Z]+)\\s*\", text)\n+    if not m or m.group(2).lower() not in _G:\n+        raise ValueError(f\"bad weight: {text!r}\")\n+    return round(float(m.group(1)) * _G[m.group(2).lower()])\n"}},{"id":"control-002","category":"control","tier":2,"target_file":"shopkit/orders/models.py","repo_sizes":["S","M"],"prompt":"When a customer adds the same product twice, the order should show one line, not two.\nAdd `Order.add_line(sku, qty, unit_cents)` that returns the order line it touched. If the order\nalready has a line with the same SKU and the same unit price, increase that line's quantity;\notherwise append a new line.","helpers":[],"decoys":[],"hidden_tests":{"test_add_line.py":"from shopkit.orders.models import Order, OrderLine\n\n\ndef test_appends_new_line():\n    o = Order(id=\"o1\")\n    line = o.add_line(\"A-1\", 2, 500)\n    assert isinstance(line, OrderLine)\n    assert [(l.sku, l.qty, l.unit_cents) for l in o.lines] == [(\"A-1\", 2, 500)]\n\n\ndef test_merges_same_sku_and_price():\n    o = Order(id=\"o1\")\n    first = o.add_line(\"A-1\", 2, 500)\n    again = o.add_line(\"A-1\", 3, 500)\n    assert again is first\n    assert len(o.lines) == 1 and o.lines[0].qty == 5\n    assert o.total_cents == 2500\n\n\ndef test_different_price_or_sku_is_a_new_line():\n    o = Order(id=\"o1\")\n    o.add_line(\"A-1\", 1, 500)\n    o.add_line(\"A-1\", 1, 450)\n    o.add_line(\"B-2\", 1, 500)\n    assert len(o.lines) == 3\n"},"solutions":{"reference":"diff --color -ruN a/shopkit/orders/models.py b/shopkit/orders/models.py\n--- a/shopkit/orders/models.py\t2026-11-17 22:01:27.602763793 -0800\n+++ b/shopkit/orders/models.py\t2026-11-17 22:01:27.606206782 -0800\n@@ -21,3 +21,12 @@\n     @property\n     def total_cents(self) -> int:\n         return sum(line.total_cents for line in self.lines)\n+\n+    def add_line(self, sku, qty, unit_cents):\n+        for line in self.lines:\n+            if line.sku == sku and line.unit_cents == unit_cents:\n+                line.qty += qty\n+                return line\n+        line = OrderLine(sku, qty, unit_cents)\n+        self.lines.append(line)\n+        return line\n"}},{"id":"control-003","category":"control","tier":1,"target_file":"shopkit/utils/durations.py","repo_sizes":["S","M"],"prompt":"Add a new module `shopkit/utils/durations.py` with `parse_duration(text: str) -> int` returning a\nduration in whole minutes. Input is hours and/or minutes such as \"2h\", \"45m\", \"1h30m\" or\n\"1h 30m\": hours come before minutes, each unit at most once, units are case-insensitive, and\nsurrounding whitespace is ignored. Anything else (empty text, other units, a missing number,\nminutes before hours, negative numbers) raises `ValueError`.","helpers":[],"decoys":[],"hidden_tests":{"test_parse_duration.py":"import pytest\n\nfrom shopkit.utils.durations import parse_duration\n\n\n@pytest.mark.parametrize(\"text,minutes\", [(\"2h\", 120), (\"45m\", 45), (\"1h30m\", 90), (\"1h 30m\", 90),\n                                          (\" 1H5M \", 65), (\"0m\", 0), (\"90m\", 90)])\ndef test_valid(text, minutes):\n    assert parse_duration(text) == minutes\n\n\n@pytest.mark.parametrize(\"text\", [\"\", \"   \", \"5\", \"h\", \"1d\", \"30m1h\", \"-5m\", \"1h1h\", \"1.5h\", \"m30\"])\ndef test_invalid(text):\n    with pytest.raises(ValueError):\n        parse_duration(text)\n"},"solutions":{"reference":"--- /dev/null\n+++ b/shopkit/utils/durations.py\n@@ -0,0 +1,12 @@\n+\"\"\"Durations written as hours and minutes (\"1h30m\") for delivery slots and promotions.\"\"\"\n+import re\n+\n+_DURATION = re.compile(r\"^(?:(\\d+)h)?\\s*(?:(\\d+)m)?$\", re.IGNORECASE)\n+\n+\n+def parse_duration(text: str) -> int:\n+    \"\"\"Whole minutes in \"2h\", \"45m\", \"1h30m\" or \"1h 30m\". Raises ValueError for anything else.\"\"\"\n+    m = _DURATION.match(text.strip())\n+    if not m or (m.group(1) is None and m.group(2) is None):\n+        raise ValueError(f\"invalid duration: {text!r}\")\n+    return int(m.group(1) or 0) * 60 + int(m.group(2) or 0)\n"}},{"id":"control-L01","category":"control","tier":2,"target_file":"shopkit/core/order_engine.py","repo_sizes":["L"],"prompt":"Ops wants readable warehouse states on the phone-order screen. In the order engine module add\n`wmsStatusLabel(code)` that returns a short English label for each status code the warehouse sends:\nreceived -> \"Received\", allocated -> \"Allocated\", picking -> \"Picking\", packed -> \"Packed\",\ndispatched -> \"Dispatched\", short pick -> \"Short pick\", cancelled -> \"Cancelled\", on hold ->\n\"On hold\". Codes are matched case-insensitively and surrounding spaces are ignored; anything else\n(including None) gives \"Unknown\".","helpers":[],"decoys":[],"hidden_tests":{"test_wms_labels.py":"from shopkit.core.order_engine import wmsStatusLabel\n\n\ndef test_every_warehouse_code_has_a_label():\n    codes = [\"RCV\", \"ALC\", \"PCK\", \"PKD\", \"DSP\", \"SHT\", \"CNL\", \"HLD\"]\n    assert [wmsStatusLabel(c) for c in codes] == [\"Received\", \"Allocated\", \"Picking\", \"Packed\", \"Dispatched\",\n                                                 \"Short pick\", \"Cancelled\", \"On hold\"]\n\n\ndef test_case_spaces_and_unknown():\n    assert wmsStatusLabel(\" dsp \") == \"Dispatched\"\n    assert wmsStatusLabel(\"XYZ\") == \"Unknown\" and wmsStatusLabel(None) == \"Unknown\"\n"},"solutions":{"reference":"--- a/shopkit/core/order_engine.py\n+++ b/shopkit/core/order_engine.py\n@@ -158,6 +158,23 @@\n \n def statusName(code):\n     return STATUS_NAMES.get(code, \"unknown\")\n+\n+\n+def wmsStatusLabel(wmsCode):\n+    \"\"\"short label for a warehouse status code, for the phone-order screen\"\"\"\n+    labels = {\n+        WMS_STATUS_RECEIVED: \"Received\",\n+        WMS_STATUS_ALLOCATED: \"Allocated\",\n+        WMS_STATUS_PICKING: \"Picking\",\n+        WMS_STATUS_PACKED: \"Packed\",\n+        WMS_STATUS_DISPATCHED: \"Dispatched\",\n+        WMS_STATUS_SHORT: \"Short pick\",\n+        WMS_STATUS_CANCELLED: \"Cancelled\",\n+        WMS_STATUS_HOLD: \"On hold\",\n+    }\n+    if wmsCode is None:\n+        return \"Unknown\"\n+    return labels.get(wmsCode.strip().upper(), \"Unknown\")\n \n \n def wmsStatusToShopkit(wmsCode):\n"}},{"id":"convention-001","category":"convention","tier":5,"target_file":"shopkit/inventory/stock.py","repo_sizes":["S","M"],"prompt":"Checkout needs to hold stock for an order. Add `Stock.reserve(sku, qty)` that lowers the\navailable quantity of `sku` by `qty`. If there isn't enough stock, nothing changes and the\nrequest fails the same way other business-rule failures in the shop do, so that the API answers\nwith 409 and the error body includes the requested and available quantities as `requested` and\n`available`.","helpers":[],"decoys":[],"hidden_tests":{"test_reserve.py":"from shopkit.api.handlers import handle\nfrom shopkit.inventory.stock import Stock\n\n\ndef _stock():\n    s = Stock()\n    s.receive(\"A-1\", 2)\n    return s\n\n\ndef test_reserve_lowers_available():\n    s = _stock()\n    status, _ = handle(s.reserve, \"A-1\", 2)\n    assert status == 200\n    assert s.available(\"A-1\") == 0\n\n\ndef test_insufficient_stock_is_a_409_with_details():\n    s = _stock()\n    status, body = handle(s.reserve, \"A-1\", 5)\n    assert status == 409\n    assert body[\"requested\"] == 5\n    assert body[\"available\"] == 2\n    assert s.available(\"A-1\") == 2\n"},"solutions":{"context_blind":"diff --color -ruN a/shopkit/inventory/stock.py b/shopkit/inventory/stock.py\n--- a/shopkit/inventory/stock.py\t2026-11-17 22:01:27.612454383 -0800\n+++ b/shopkit/inventory/stock.py\t2026-11-17 22:01:27.615207029 -0800\n@@ -9,3 +9,9 @@\n \n     def available(self, sku: str) -> int:\n         return self._on_hand.get(sku, 0)\n+\n+    def reserve(self, sku: str, qty: int) -> None:\n+        have = self.available(sku)\n+        if qty > have:\n+            raise ValueError(f\"not enough {sku}: requested {qty}, available {have}\")\n+        self._on_hand[sku] = have - qty\n","reference":"diff --color -ruN a/shopkit/inventory/stock.py b/shopkit/inventory/stock.py\n--- a/shopkit/inventory/stock.py\t2026-11-17 22:01:27.620743047 -0800\n+++ b/shopkit/inventory/stock.py\t2026-11-17 22:01:27.624550573 -0800\n@@ -1,3 +1,10 @@\n+from shopkit.errors import Conflict\n+\n+\n+class InsufficientStock(Conflict):\n+    pass\n+\n+\n class Stock:\n     \"\"\"On-hand quantities per SKU.\"\"\"\n \n@@ -9,3 +16,9 @@\n \n     def available(self, sku: str) -> int:\n         return self._on_hand.get(sku, 0)\n+\n+    def reserve(self, sku: str, qty: int) -> None:\n+        have = self.available(sku)\n+        if qty > have:\n+            raise InsufficientStock(f\"not enough {sku}\", requested=qty, available=have)\n+        self._on_hand[sku] = have - qty\n"}},{"id":"convention-002","category":"convention","tier":5,"target_file":"shopkit/inventory/transfers.py","repo_sizes":["M","L"],"prompt":"Stock transfers between warehouses must show up in the audit trail and reach notification\nsubscribers. When a transfer succeeds, announce it the same way the rest of the shop announces\ndomain events, with the SKU, quantity, source and destination, so the audit trail files it under\nthe SKU. `transfer()` keeps its signature; a failed transfer announces nothing.","helpers":[],"decoys":[],"hidden_tests":{"test_transfer_events.py":"import pytest\n\nfrom shopkit.audit_log import AuditLog\nfrom shopkit.events import BUS\nfrom shopkit.inventory.transfers import TransferFailed, transfer\nfrom shopkit.inventory.warehouses import Network, Warehouse\n\n\ndef _network():\n    east, west = Warehouse(\"east\", \"US\"), Warehouse(\"west\", \"US\")\n    east.stock.receive(\"MUG\", 10)\n    return Network([east, west])\n\n\ndef test_successful_transfer_is_announced_and_audited_under_the_sku():\n    before = len(BUS.history)\n    transfer(_network(), \"MUG\", 4, \"east\", \"west\")\n    new = BUS.history[before:]\n    assert len(new) == 1\n    event = new[0]\n    assert \".\" in event.name\n    assert {k: event.payload[k] for k in (\"sku\", \"qty\", \"source\", \"destination\")} == {\n        \"sku\": \"MUG\", \"qty\": 4, \"source\": \"east\", \"destination\": \"west\"}\n    log = AuditLog()\n    log.on_event(event)\n    assert [e.target for e in log.for_target(\"MUG\")] == [\"MUG\"]\n\n\ndef test_failed_transfer_announces_nothing():\n    before = len(BUS.history)\n    with pytest.raises(TransferFailed):\n        transfer(_network(), \"MUG\", 40, \"east\", \"west\")\n    assert len(BUS.history) == before\n"},"solutions":{"context_blind":"--- a/shopkit/inventory/transfers.py\n+++ b/shopkit/inventory/transfers.py\n@@ -1,4 +1,5 @@\n \"\"\"Stock transfers between warehouses (rebalancing before peak season).\"\"\"\n+import logging\n from dataclasses import dataclass, field\n from datetime import datetime\n \n@@ -30,4 +31,5 @@\n     # Stock has no public removal API; transfers adjust the ledger directly.\n     src.stock._on_hand[sku] -= qty\n     network.get(destination).stock.receive(sku, qty)\n+    logging.getLogger(__name__).info(\"transfer %s x%d %s -> %s\", sku, qty, source, destination)\n     return Transfer(sku, qty, source, destination)\n","reference":"--- a/shopkit/inventory/transfers.py\n+++ b/shopkit/inventory/transfers.py\n@@ -3,6 +3,7 @@\n from datetime import datetime\n \n from shopkit.errors import Conflict\n+from shopkit.events import BUS\n from shopkit.inventory.warehouses import Network\n from shopkit.utils.dates import utc_now\n \n@@ -30,4 +31,5 @@\n     # Stock has no public removal API; transfers adjust the ledger directly.\n     src.stock._on_hand[sku] -= qty\n     network.get(destination).stock.receive(sku, qty)\n+    BUS.publish(\"stock.transferred\", sku=sku, qty=qty, source=source, destination=destination)\n     return Transfer(sku, qty, source, destination)\n"}},{"id":"convention-003","category":"convention","tier":5,"target_file":"shopkit/orders/returns.py","repo_sizes":["M","L"],"prompt":"Different deployments need different return windows. Make the return window a deployment setting\nlike the shop's other settings: `return_window_days`, default 30, overridable with the\n`SHOPKIT_RETURN_DAYS` environment variable, and used by `open_return` instead of the hard-coded 30.","helpers":[],"decoys":[],"hidden_tests":{"test_return_window_setting.py":"import sys\nfrom datetime import date, timedelta\n\nimport pytest\n\nimport shopkit.config as config\nfrom shopkit.orders.models import Order, OrderLine\nfrom shopkit.orders.returns import ReturnNotAllowed, open_return\n\n\ndef test_setting_defaults_to_30_days():\n    assert config.load_settings({}).return_window_days == 30\n\n\ndef test_setting_comes_from_the_environment():\n    assert config.load_settings({\"SHOPKIT_RETURN_DAYS\": \"14\"}).return_window_days == 14\n\n\ndef _use(settings, monkeypatch):\n    \"\"\"Install `settings` wherever the shop holds the current settings object.\"\"\"\n    original = config.SETTINGS\n    for mod in list(sys.modules.values()):\n        if getattr(mod, \"__name__\", \"\").startswith(\"shopkit\"):\n            for attr, value in list(vars(mod).items()):\n                if value is original:\n                    monkeypatch.setattr(mod, attr, settings)\n\n\ndef _open(days_after_delivery):\n    delivered = date(2026, 11, 1)\n    order = Order(\"o1\", [OrderLine(\"MUG\", 1, 1000)])\n    return open_return(order, delivered, {\"MUG\": 1}, \"damaged\", delivered + timedelta(days=days_after_delivery))\n\n\ndef test_open_return_follows_the_setting(monkeypatch):\n    _use(config.load_settings({\"SHOPKIT_RETURN_DAYS\": \"14\"}), monkeypatch)\n    _open(14)\n    with pytest.raises(ReturnNotAllowed):\n        _open(20)\n\n\ndef test_default_window_unchanged(monkeypatch):\n    _use(config.load_settings({}), monkeypatch)\n    _open(30)\n    with pytest.raises(ReturnNotAllowed):\n        _open(31)\n"},"solutions":{"context_blind":"--- a/shopkit/orders/returns.py\n+++ b/shopkit/orders/returns.py\n@@ -1,4 +1,5 @@\n \"\"\"Customer returns (RMA). A return refunds lines of a delivered order within the return window.\"\"\"\n+import os\n from dataclasses import dataclass, field\n from datetime import date, timedelta\n \n@@ -6,7 +7,7 @@\n from shopkit.orders.models import Order\n from shopkit.utils.ids import short_code\n \n-RETURN_WINDOW_DAYS = 30\n+RETURN_WINDOW_DAYS = int(os.environ.get(\"SHOPKIT_RETURN_DAYS\", \"30\"))\n REASONS = (\"damaged\", \"wrong_item\", \"not_as_described\", \"changed_mind\")\n \n \n","reference":"--- a/shopkit/config.py\n+++ b/shopkit/config.py\n@@ -13,6 +13,7 @@\n     max_page_size: int = 200\n     support_email: str = \"support@shopkit.example\"\n     free_shipping_over_cents: int = 10_000\n+    return_window_days: int = 30\n     supported_currencies: tuple[str, ...] = (\"USD\", \"EUR\", \"GBP\")\n     feature_flags: dict[str, bool] = field(default_factory=dict)\n \n@@ -30,6 +31,8 @@\n         kwargs[\"store_country\"] = env[\"SHOPKIT_COUNTRY\"]\n     if \"SHOPKIT_LOW_STOCK\" in env:\n         kwargs[\"low_stock_threshold\"] = int(env[\"SHOPKIT_LOW_STOCK\"])\n+    if \"SHOPKIT_RETURN_DAYS\" in env:\n+        kwargs[\"return_window_days\"] = int(env[\"SHOPKIT_RETURN_DAYS\"])\n     if \"SHOPKIT_PAGE_SIZE\" in env:\n         kwargs[\"page_size\"] = int(env[\"SHOPKIT_PAGE_SIZE\"])\n     flags = env.get(\"SHOPKIT_FLAGS\", \"\")\n--- a/shopkit/orders/returns.py\n+++ b/shopkit/orders/returns.py\n@@ -2,11 +2,11 @@\n from dataclasses import dataclass, field\n from datetime import date, timedelta\n \n+from shopkit import config\n from shopkit.errors import Conflict, ShopError\n from shopkit.orders.models import Order\n from shopkit.utils.ids import short_code\n \n-RETURN_WINDOW_DAYS = 30\n REASONS = (\"damaged\", \"wrong_item\", \"not_as_described\", \"changed_mind\")\n \n \n@@ -35,7 +35,7 @@\n                 today: date) -> ReturnRequest:\n     if reason not in REASONS:\n         raise InvalidReturn(f\"unknown reason {reason!r}\", reason=reason)\n-    if today > delivered_on + timedelta(days=RETURN_WINDOW_DAYS):\n+    if today > delivered_on + timedelta(days=config.SETTINGS.return_window_days):\n         raise ReturnNotAllowed(f\"order {order.id} is outside the return window\", order_id=order.id,\n                                delivered_on=delivered_on.isoformat())\n     ordered = {line.sku: line.qty for line in order.lines}\n"}},{"id":"cross-001","category":"cross_file","tier":6,"target_file":"shopkit/orders/models.py","repo_sizes":["S","M"],"prompt":"Orders can now carry a percentage discount. Add `discount_percent: int = 0` (0 to 100) to orders.\nThe order total must reflect the discount; the discount amount is rounded down to whole cents.\nCustomer invoices must show the discount amount on its own line just before the total (only for\ndiscounted orders; undiscounted invoices stay exactly as they are today). The warehouse JSON\nexport must include the discount as `discount_percent`.","helpers":[],"decoys":[],"hidden_tests":{"test_discount.py":"import json\n\nfrom shopkit.invoices.render import render_invoice_text\nfrom shopkit.orders.export import export_orders_json\nfrom shopkit.orders.models import Order, OrderLine\n\n\ndef _order(pct):\n    return Order(id=\"o9\", lines=[OrderLine(sku=\"ab12\", qty=3, unit_cents=333)], discount_percent=pct)\n\n\ndef test_total_is_discounted_and_rounded_down():\n    assert _order(10).total_cents == 900       # 999 - floor(99.9)\n    assert _order(0).total_cents == 999\n    assert _order(100).total_cents == 0\n\n\ndef test_invoice_shows_discount_line_before_total():\n    lines = render_invoice_text(_order(10)).splitlines()\n    assert lines[-1].startswith(\"TOTAL\") and lines[-1].endswith(\"$9.00\")\n    assert \"discount\" in lines[-2].lower() and \"0.99\" in lines[-2]\n\n\ndef test_undiscounted_invoice_unchanged():\n    assert render_invoice_text(_order(0)) == (\n        \"Invoice o9\\n\"\n        \"AB-12              3 x        $3.33  =        $9.99\\n\"\n        \"TOTAL                                      $9.99\"\n    )\n\n\ndef test_json_export_includes_discount():\n    assert json.loads(export_orders_json([_order(10)]))[0][\"discount_percent\"] == 10\n"},"solutions":{"context_blind":"diff --color -ruN a/shopkit/orders/models.py b/shopkit/orders/models.py\n--- a/shopkit/orders/models.py\t2026-11-17 22:01:27.629512029 -0800\n+++ b/shopkit/orders/models.py\t2026-11-17 22:01:27.643343135 -0800\n@@ -17,7 +17,9 @@\n     id: str\n     lines: list[OrderLine] = field(default_factory=list)\n     currency: str = \"USD\"\n+    discount_percent: int = 0\n \n     @property\n     def total_cents(self) -> int:\n-        return sum(line.total_cents for line in self.lines)\n+        sub = sum(line.total_cents for line in self.lines)\n+        return sub - sub * self.discount_percent // 100\n","reference":"diff --color -ruN a/shopkit/invoices/render.py b/shopkit/invoices/render.py\n--- a/shopkit/invoices/render.py\t2026-11-17 22:01:27.650393593 -0800\n+++ b/shopkit/invoices/render.py\t2026-11-17 22:01:27.663201826 -0800\n@@ -9,5 +9,7 @@\n     for line in order.lines:\n         rows.append(f\"{normalize_sku(line.sku):<16}{line.qty:>4} x {format_money(line.unit_cents, order.currency):>12}\"\n                     f\"  = {format_money(line.total_cents, order.currency):>12}\")\n+    if order.discount_percent:\n+        rows.append(f\"{'DISCOUNT ' + str(order.discount_percent) + '%':<36}{format_money(-order.discount_cents, order.currency):>12}\")\n     rows.append(f\"{'TOTAL':<36}{format_money(order.total_cents, order.currency):>12}\")\n     return \"\\n\".join(rows)\ndiff --color -ruN a/shopkit/orders/export.py b/shopkit/orders/export.py\n--- a/shopkit/orders/export.py\t2026-11-17 22:01:27.650461522 -0800\n+++ b/shopkit/orders/export.py\t2026-11-17 22:01:27.663225803 -0800\n@@ -9,6 +9,7 @@\n         {\n             \"id\": o.id,\n             \"currency\": o.currency,\n+            \"discount_percent\": o.discount_percent,\n             \"lines\": [{\"sku\": l.sku, \"qty\": l.qty, \"unit_cents\": l.unit_cents} for l in o.lines],\n         }\n         for o in orders\ndiff --color -ruN a/shopkit/orders/models.py b/shopkit/orders/models.py\n--- a/shopkit/orders/models.py\t2026-11-17 22:01:27.650471157 -0800\n+++ b/shopkit/orders/models.py\t2026-11-17 22:01:27.663164019 -0800\n@@ -17,7 +17,16 @@\n     id: str\n     lines: list[OrderLine] = field(default_factory=list)\n     currency: str = \"USD\"\n+    discount_percent: int = 0\n \n     @property\n     def total_cents(self) -> int:\n+        return self.subtotal_cents - self.discount_cents\n+\n+    @property\n+    def subtotal_cents(self) -> int:\n         return sum(line.total_cents for line in self.lines)\n+\n+    @property\n+    def discount_cents(self) -> int:\n+        return self.subtotal_cents * self.discount_percent // 100\n"}},{"id":"cross-002","category":"cross_file","tier":6,"target_file":"shopkit/catalog/models.py","repo_sizes":["M","L"],"prompt":"Products now have a shipping weight. Add `weight_g: int = 0` (grams per unit) to `Product`. Add\n`parcel_weight_g(parcel, products)` to the fulfillment module: the total weight of a parcel's\ncontents, where `products` maps SKU to product. The product representation the API returns must\ninclude the weight as `weight_g`.","helpers":[],"decoys":[],"hidden_tests":{"test_product_weight.py":"from shopkit.api import serializers\nfrom shopkit.catalog.models import Product\nfrom shopkit.orders.fulfillment import Parcel, parcel_weight_g\n\nMUG = Product(\"MUG\", \"Mug\", 1299, weight_g=350)\nTEE = Product(\"TEE\", \"T-shirt\", 1999, weight_g=200)\n\n\ndef test_weight_defaults_to_zero():\n    assert Product(\"X\", \"Thing\", 100).weight_g == 0\n\n\ndef test_parcel_weight():\n    parcel = Parcel(\"o1\", 1, [(\"MUG\", 2), (\"TEE\", 1)])\n    assert parcel_weight_g(parcel, {\"MUG\": MUG, \"TEE\": TEE}) == 900\n\n\ndef test_api_includes_weight():\n    body = serializers.product(MUG)\n    assert body[\"weight_g\"] == 350 and body[\"sku\"] == \"MUG\" and body[\"price\"][\"cents\"] == 1299\n"},"solutions":{"context_blind":"--- a/shopkit/catalog/models.py\n+++ b/shopkit/catalog/models.py\n@@ -7,6 +7,11 @@\n     title: str\n     price_cents: int\n     active: bool = True\n+    weight_g: int = 0\n+\n+    def to_dict(self) -> dict:\n+        return {\"sku\": self.sku, \"title\": self.title, \"price_cents\": self.price_cents,\n+                \"active\": self.active, \"weight_g\": self.weight_g}\n \n     def is_purchasable(self) -> bool:\n         return self.active and self.price_cents > 0\n","reference":"--- a/shopkit/catalog/models.py\n+++ b/shopkit/catalog/models.py\n@@ -7,6 +7,7 @@\n     title: str\n     price_cents: int\n     active: bool = True\n+    weight_g: int = 0              # grams per unit, for shipping\n \n     def is_purchasable(self) -> bool:\n         return self.active and self.price_cents > 0\n--- a/shopkit/orders/fulfillment.py\n+++ b/shopkit/orders/fulfillment.py\n@@ -1,6 +1,7 @@\n \"\"\"Picking and packing. Builds pick lists for the warehouse and splits orders into parcels.\"\"\"\n from dataclasses import dataclass, field\n \n+from shopkit.catalog.models import Product\n from shopkit.orders.models import Order\n from shopkit.shipping.packaging import format_weight\n from shopkit.utils.collections import chunked, group_by\n@@ -35,6 +36,11 @@\n     return parcels\n \n \n+def parcel_weight_g(parcel: Parcel, products: dict[str, Product]) -> int:\n+    \"\"\"Total weight of a parcel's contents in grams.\"\"\"\n+    return sum(products[sku].weight_g * qty for sku, qty in parcel.items)\n+\n+\n def packing_slip(parcel: Parcel, weight_g: int) -> str:\n     \"\"\"Slip packed inside each parcel: order, parcel number, contents and weight.\"\"\"\n     lines = [f\"Order {parcel.order_id} - parcel {parcel.number}\", f\"Weight: {format_weight(weight_g)}\"]\n--- a/shopkit/api/serializers.py\n+++ b/shopkit/api/serializers.py\n@@ -12,7 +12,7 @@\n \n def product(p: Product) -> dict:\n     return {\"sku\": p.sku, \"title\": p.title, \"price\": money(p.price_cents), \"active\": p.active,\n-            \"purchasable\": p.is_purchasable()}\n+            \"purchasable\": p.is_purchasable(), \"weight_g\": p.weight_g}\n \n \n def order(o: Order, status: str | None = None) -> dict:\n"}},{"id":"cross-003","category":"cross_file","tier":6,"target_file":"shopkit/orders/models.py","repo_sizes":["M","L"],"prompt":"Shoppers can add a gift message to an order. Add `gift_message: str = \"\"` to `Order`. The message\nmust be printed on the packing slip of the order's first parcel only: carry it through\n`split_into_parcels` so that `packing_slip(parcel, weight_g)` can print it. The order\nrepresentation the API returns must include it as `gift_message`. Customer invoices must not show\nit.","helpers":[],"decoys":[],"hidden_tests":{"test_gift_message.py":"from shopkit.api import serializers\nfrom shopkit.invoices.render import render_invoice_text\nfrom shopkit.orders.fulfillment import packing_slip, split_into_parcels\nfrom shopkit.orders.models import Order, OrderLine\n\nMESSAGE = \"Happy birthday, Sam!\"\n\n\ndef _order(qty=3, message=MESSAGE):\n    return Order(\"o1\", [OrderLine(\"MUG\", qty, 1299)], gift_message=message)\n\n\ndef test_message_on_first_parcel_only():\n    first, second = split_into_parcels(_order(qty=12))\n    assert MESSAGE in packing_slip(first, 900)\n    assert MESSAGE not in packing_slip(second, 300)\n\n\ndef test_no_message_no_extra_line():\n    slip = packing_slip(split_into_parcels(_order(message=\"\"))[0], 900)\n    assert slip.count(\"\\n\") == 2                      # header, weight, one item line\n\n\ndef test_api_includes_message():\n    assert serializers.order(_order())[\"gift_message\"] == MESSAGE\n\n\ndef test_invoice_does_not_show_it():\n    assert MESSAGE not in render_invoice_text(_order())\n"},"solutions":{"context_blind":"--- a/shopkit/orders/models.py\n+++ b/shopkit/orders/models.py\n@@ -17,7 +17,11 @@\n     id: str\n     lines: list[OrderLine] = field(default_factory=list)\n     currency: str = \"USD\"\n+    gift_message: str = \"\"\n \n     @property\n     def total_cents(self) -> int:\n         return sum(line.total_cents for line in self.lines)\n+\n+    def packing_note(self) -> str:\n+        return f\"Gift message: {self.gift_message}\" if self.gift_message else \"\"\n","reference":"--- a/shopkit/orders/models.py\n+++ b/shopkit/orders/models.py\n@@ -17,6 +17,7 @@\n     id: str\n     lines: list[OrderLine] = field(default_factory=list)\n     currency: str = \"USD\"\n+    gift_message: str = \"\"\n \n     @property\n     def total_cents(self) -> int:\n--- a/shopkit/orders/fulfillment.py\n+++ b/shopkit/orders/fulfillment.py\n@@ -13,6 +13,7 @@\n     order_id: str\n     number: int\n     items: list[tuple[str, int]] = field(default_factory=list)    # (sku, qty)\n+    gift_message: str = \"\"                                       # first parcel only\n \n     @property\n     def item_count(self) -> int:\n@@ -31,7 +32,8 @@\n     parcels = []\n     for n, batch in enumerate(chunked(units, max_items), start=1):\n         counts = group_by(batch, key=lambda s: s)\n-        parcels.append(Parcel(order.id, n, [(sku, len(v)) for sku, v in counts.items()]))\n+        parcels.append(Parcel(order.id, n, [(sku, len(v)) for sku, v in counts.items()],\n+                              gift_message=order.gift_message if n == 1 else \"\"))\n     return parcels\n \n \n@@ -39,4 +41,6 @@\n     \"\"\"Slip packed inside each parcel: order, parcel number, contents and weight.\"\"\"\n     lines = [f\"Order {parcel.order_id} - parcel {parcel.number}\", f\"Weight: {format_weight(weight_g)}\"]\n     lines += [f\"  {qty} x {sku}\" for sku, qty in parcel.items]\n+    if parcel.gift_message:\n+        lines.append(f\"Gift message: {parcel.gift_message}\")\n     return \"\\n\".join(lines)\n--- a/shopkit/api/serializers.py\n+++ b/shopkit/api/serializers.py\n@@ -22,6 +22,7 @@\n         \"lines\": [{\"sku\": l.sku, \"qty\": l.qty, \"unit\": money(l.unit_cents, o.currency),\n                    \"total\": money(l.total_cents, o.currency)} for l in o.lines],\n         \"total\": money(o.total_cents, o.currency),\n+        \"gift_message\": o.gift_message,\n     }\n \n \n"}},{"id":"cross-L01","category":"cross_file","tier":6,"target_file":"shopkit/orders/models.py","repo_sizes":["L"],"prompt":"Customers can now leave a delivery note for the courier (for example \"leave it with the neighbour\nat no. 5\"). Add `delivery_note: str = \"\"` to orders and make it work end to end: a new database\nmigration adds a `delivery_note` column to the orders table (text, empty by default); the order\nrepository saves the note when an order is added and loads it back; the order page shows it under a\n\"Delivery note\" heading, only when there is one; and the order JSON in the API includes it as\n`delivery_note`. Notes are at most 200 characters: storing a longer one raises ValueError.","helpers":[],"decoys":[],"hidden_tests":{"test_delivery_note.py":"import pytest\n\nfrom shopkit.api import serializers\nfrom shopkit.db import connect\nfrom shopkit.db.repositories import OrderRepository\nfrom shopkit.orders.models import Order, OrderLine\nfrom shopkit.web import views\n\n\ndef test_column_exists_and_round_trips():\n    db = connect()\n    assert \"delivery_note\" in {r[\"name\"] for r in db.query(\"PRAGMA table_info(orders)\")}\n    repo = OrderRepository(db)\n    repo.add(Order(\"O1\", [OrderLine(\"MUG\", 1, 1200)], delivery_note=\"Leave at the door\"))\n    repo.add(Order(\"O2\", [OrderLine(\"MUG\", 1, 1200)]))\n    assert repo.get(\"O1\").delivery_note == \"Leave at the door\" and repo.get(\"O2\").delivery_note == \"\"\n\n\ndef test_long_notes_are_rejected():\n    repo = OrderRepository(connect())\n    with pytest.raises(ValueError):\n        repo.add(Order(\"O1\", [OrderLine(\"MUG\", 1, 1200)], delivery_note=\"x\" * 201))\n    repo.add(Order(\"O2\", [OrderLine(\"MUG\", 1, 1200)], delivery_note=\"x\" * 200))\n\n\ndef test_page_and_api_show_the_note():\n    order = Order(\"O1\", [OrderLine(\"MUG\", 1, 1200)], delivery_note=\"Ring <twice> & wait\")\n    html = views.order_detail(order, status=\"paid\")\n    assert \"Delivery note\" in html and \"Ring &lt;twice&gt; &amp; wait\" in html\n    assert \"Delivery note\" not in views.order_detail(Order(\"O2\", [OrderLine(\"MUG\", 1, 1200)]), status=\"paid\")\n    assert serializers.order(order)[\"delivery_note\"] == \"Ring <twice> & wait\"\n"},"solutions":{"context_blind":"--- a/shopkit/orders/models.py\n+++ b/shopkit/orders/models.py\n@@ -17,6 +17,7 @@\n     id: str\n     lines: list[OrderLine] = field(default_factory=list)\n     currency: str = \"USD\"\n+    delivery_note: str = \"\"\n \n     @property\n     def total_cents(self) -> int:\n--- a/shopkit/api/serializers.py\n+++ b/shopkit/api/serializers.py\n@@ -22,6 +22,7 @@\n         \"lines\": [{\"sku\": l.sku, \"qty\": l.qty, \"unit\": money(l.unit_cents, o.currency),\n                    \"total\": money(l.total_cents, o.currency)} for l in o.lines],\n         \"total\": money(o.total_cents, o.currency),\n+        \"delivery_note\": o.delivery_note,\n     }\n \n \n","reference":"--- a/shopkit/orders/models.py\n+++ b/shopkit/orders/models.py\n@@ -17,6 +17,7 @@\n     id: str\n     lines: list[OrderLine] = field(default_factory=list)\n     currency: str = \"USD\"\n+    delivery_note: str = \"\"                # for the courier, at most MAX_DELIVERY_NOTE characters\n \n     @property\n     def total_cents(self) -> int:\n--- /dev/null\n+++ b/migrations/0025_delivery_note.sql\n@@ -0,0 +1,2 @@\n+-- Delivery notes for the courier (shown on the order page and in the API).\n+ALTER TABLE orders ADD COLUMN delivery_note TEXT NOT NULL DEFAULT '';\n--- a/shopkit/db/repositories.py\n+++ b/shopkit/db/repositories.py\n@@ -16,6 +16,8 @@\n from shopkit.errors import DuplicateOrder, NotFound, OrderNotFound\n from shopkit.orders.models import Order, OrderLine\n from shopkit.utils.dates import utc_now\n+\n+MAX_DELIVERY_NOTE = 200\n \n \n class ProductNotFound(NotFound):\n@@ -110,25 +112,28 @@\n \n     def add(self, order: Order, customer_id: str | None = None, status: str = \"new\",\n             created_at: datetime | None = None, channel: str = \"web\") -> None:\n+        if len(order.delivery_note) > MAX_DELIVERY_NOTE:\n+            raise ValueError(f\"delivery note longer than {MAX_DELIVERY_NOTE} characters\")\n         if self.db.scalar(\"SELECT 1 FROM orders WHERE id = ?\", (order.id,)):\n             raise DuplicateOrder(f\"order {order.id} already exists\", order_id=order.id)\n         with self.db.transaction():\n             self.db.execute(*insert(\"orders\", {\n                 \"id\": order.id, \"customer_id\": customer_id, \"currency\": order.currency, \"status\": status,\n                 \"created_at\": (created_at or utc_now()).isoformat(), \"subtotal_cents\": order.total_cents,\n-                \"total_cents\": order.total_cents, \"channel\": channel}))\n+                \"total_cents\": order.total_cents, \"channel\": channel,\n+                \"delivery_note\": order.delivery_note}))\n             for no, line in enumerate(order.lines, 1):\n                 self.db.execute(*insert(\"order_lines\", {\"order_id\": order.id, \"line_no\": no, \"sku\": line.sku,\n                                                         \"qty\": line.qty, \"unit_cents\": line.unit_cents}))\n             self._history(order.id, status)\n \n     def get(self, order_id: str) -> Order:\n-        head = self.db.query_one(\"SELECT id, currency FROM orders WHERE id = ?\", (order_id,))\n+        head = self.db.query_one(\"SELECT id, currency, delivery_note FROM orders WHERE id = ?\", (order_id,))\n         if head is None:\n             raise OrderNotFound(f\"no order {order_id}\", order_id=order_id)\n         lines = self.db.query(\"SELECT sku, qty, unit_cents FROM order_lines WHERE order_id = ? ORDER BY line_no\",\n                               (order_id,))\n-        return Order(id=head[\"id\"], currency=head[\"currency\"],\n+        return Order(id=head[\"id\"], currency=head[\"currency\"], delivery_note=head[\"delivery_note\"],\n                      lines=[OrderLine(r[\"sku\"], r[\"qty\"], r[\"unit_cents\"]) for r in lines])\n \n     def status(self, order_id: str) -> str:\n--- a/templates/orders/detail.html\n+++ b/templates/orders/detail.html\n@@ -11,6 +11,11 @@\n   {% if ship_to %}\n   <h2>Shipping to</h2>\n   {% include \"partials/address.html\" %}\n+  {% endif %}\n+\n+  {% if order.delivery_note %}\n+  <h2>Delivery note</h2>\n+  <p class=\"delivery-note\">{{ order.delivery_note }}</p>\n   {% endif %}\n \n   {% if tracking %}\n--- a/shopkit/api/serializers.py\n+++ b/shopkit/api/serializers.py\n@@ -22,6 +22,7 @@\n         \"lines\": [{\"sku\": l.sku, \"qty\": l.qty, \"unit\": money(l.unit_cents, o.currency),\n                    \"total\": money(l.total_cents, o.currency)} for l in o.lines],\n         \"total\": money(o.total_cents, o.currency),\n+        \"delivery_note\": o.delivery_note,\n     }\n \n \n"}},{"id":"long-001","category":"long","tier":5,"target_file":"shopkit/payouts/preview.py","repo_sizes":["L"],"prompt":"Sellers want to see what their next payout will look like before finance runs the weekly batch.\nAdd `preview_payout(seller, earnings, adjustments, period_start, period_end, holds, rollover)` in a\nnew module `shopkit/payouts/preview.py`. It returns `(status, net_cents)`: the status and the net\namount this seller's payout would get for that period, exactly as the weekly payout would treat it.\nA preview must not change anything: held amounts and balances carried between periods stay as they were.","helpers":[],"decoys":[],"hidden_tests":{"test_preview.py":"import copy\nfrom datetime import date\n\nfrom shopkit.payouts.batching import Rollover, build_payout_batch\nfrom shopkit.payouts.holds import HoldBook\nfrom shopkit.payouts.models import Adjustment, Earning, Seller\nfrom shopkit.payouts.preview import preview_payout\n\nSTART, END, OLD = date(2026, 3, 2), date(2026, 3, 8), date(2026, 1, 15)\n\n\ndef test_small_payout_rolls_over_but_closing_seller_is_paid():\n    e = [Earning(\"S1\", \"O1\", \"PIN\", 2_000, OLD)]\n    assert preview_payout(Seller(\"S1\", \"x\", tax_id=\"1\"), e, [], START, END, HoldBook(), Rollover()) == (\"rolled_over\", 1_700)\n    closing = Seller(\"S1\", \"x\", tax_id=\"1\", status=\"closing\")\n    assert preview_payout(closing, e, [], START, END, HoldBook(), Rollover()) == (\"draft\", 1_700)\n\n\ndef test_negative_balance_and_carried_amount():\n    s = Seller(\"S1\", \"x\", tax_id=\"1\", status=\"closing\")\n    assert preview_payout(s, [], [Adjustment(\"S1\", -3_000, \"chargeback\")], START, END, HoldBook(), Rollover()) == (\"rolled_over\", -3_000)\n    r = Rollover({\"S1\": 1_000})\n    assert preview_payout(Seller(\"S1\", \"x\", tax_id=\"1\"), [Earning(\"S1\", \"O1\", \"PIN\", 2_000, OLD)], [], START, END,\n                          HoldBook(), r) == (\"draft\", 2_700)\n\n\ndef test_preview_changes_nothing_and_matches_the_batch():\n    seller = Seller(\"S1\", \"x\", tax_id=\"1\")\n    earnings = [Earning(\"S1\", \"O1\", \"POT\", 10_000, date(2026, 3, 5)), Earning(\"S1\", \"O2\", \"PAN\", 40_000, OLD)]\n    holds, rollover = HoldBook(), Rollover({\"S1\": 500})\n    result = preview_payout(seller, earnings, [], START, END, holds, rollover)\n    assert holds.holds == {} and rollover.balances == {\"S1\": 500}\n    batch = build_payout_batch([seller], earnings, [], START, END, holds=copy.deepcopy(holds),\n                               rollover=copy.deepcopy(rollover))\n    assert result == (batch.payouts[0].status, batch.payouts[0].net_cents)\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/payouts/preview.py\n@@ -0,0 +1,9 @@\n+from shopkit.utils.numbers import apply_rate\n+\n+\n+def preview_payout(seller, earnings, adjustments, period_start, period_end, holds, rollover):\n+    net = 0\n+    for e in earnings:\n+        net += e.gross_cents - apply_rate(e.gross_cents, seller.commission_bp / 100) - e.refunded_cents\n+    net += sum(a.amount_cents for a in adjustments) + rollover.balances.get(seller.id, 0)\n+    return \"draft\", net\n","reference":"--- /dev/null\n+++ b/shopkit/payouts/preview.py\n@@ -0,0 +1,18 @@\n+\"\"\"What a seller's next payout would look like, without touching holds or carried balances.\"\"\"\n+import copy\n+from datetime import date\n+\n+from shopkit.payouts.batching import Rollover, build_payout_batch\n+from shopkit.payouts.holds import HoldBook\n+from shopkit.payouts.models import Adjustment, Earning, Seller\n+\n+\n+def preview_payout(seller: Seller, earnings: list[Earning], adjustments: list[Adjustment], period_start: date,\n+                   period_end: date, holds: HoldBook, rollover: Rollover) -> tuple[str, int]:\n+    \"\"\"(status, net cents) the weekly batch would give this seller; works on copies.\"\"\"\n+    result = build_payout_batch([seller], earnings, adjustments, period_start, period_end,\n+                                holds=copy.deepcopy(holds), rollover=copy.deepcopy(rollover))\n+    if not result.payouts:\n+        return result.skipped.get(seller.id, \"skipped\"), 0\n+    payout = result.payouts[0]\n+    return payout.status, payout.net_cents\n"}},{"id":"long-002","category":"long","tier":5,"target_file":"shopkit/support/refund_info.py","repo_sizes":["L"],"prompt":"Support agents want to tell a customer, before pressing Refund, where the money will go back to.\nAdd `refund_destinations(order_id, amount_cents, payments, today)` in a new module\n`shopkit/support/refund_info.py`. It returns a dict with the cents that would go back to the card,\nto store credit and to a gift card (keys \"card\", \"store_credit\", \"gift_card\"), split exactly the\nway a refund of that amount for that order would be settled. It must not refund anything.","helpers":[],"decoys":[],"hidden_tests":{"test_refund_info.py":"from datetime import date, datetime\n\nfrom shopkit.payments.models import CAPTURED, Payment\nfrom shopkit.support.refund_info import refund_destinations\n\nTODAY = date(2026, 3, 10)\n\n\ndef _pay(pid, amount, created, method=\"card\", refunded=0):\n    p = Payment(pid, \"O1\", amount, \"USD\", method, status=CAPTURED, created=created)\n    p.refunded_cents = refunded\n    return p\n\n\ndef test_recent_card_goes_back_to_the_card_and_old_card_to_store_credit():\n    assert refund_destinations(\"O1\", 1_000, [_pay(\"P1\", 5_000, datetime(2026, 3, 1))], TODAY) == \\\n        {\"card\": 1_000, \"store_credit\": 0, \"gift_card\": 0}\n    assert refund_destinations(\"O1\", 1_000, [_pay(\"P1\", 5_000, datetime(2025, 8, 1))], TODAY) == \\\n        {\"card\": 0, \"store_credit\": 1_000, \"gift_card\": 0}\n\n\ndef test_split_payments_in_proportion_with_leftover_cents_to_the_card():\n    pays = [_pay(\"G1\", 1_000, datetime(2026, 3, 1), \"gift_card\"), _pay(\"P1\", 3_000, datetime(2026, 3, 1))]\n    assert refund_destinations(\"O1\", 1_001, pays, TODAY) == {\"card\": 751, \"store_credit\": 0, \"gift_card\": 250}\n    partly = [_pay(\"P1\", 3_000, datetime(2026, 3, 1), refunded=2_000), _pay(\"G1\", 1_000, datetime(2026, 3, 1), \"gift_card\")]\n    assert refund_destinations(\"O1\", 1_000, partly, TODAY) == {\"card\": 500, \"store_credit\": 0, \"gift_card\": 500}\n\n\ndef test_nothing_is_refunded():\n    p = _pay(\"P1\", 5_000, datetime(2026, 3, 1))\n    refund_destinations(\"O1\", 1_000, [p], TODAY)\n    assert p.refunded_cents == 0\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/support/refund_info.py\n@@ -0,0 +1,5 @@\n+def refund_destinations(order_id, amount_cents, payments, today):\n+    gift = sum(p.refundable_cents for p in payments if p.method == \"gift_card\")\n+    total = sum(p.refundable_cents for p in payments) or 1\n+    gift_part = amount_cents * gift // total\n+    return {\"card\": amount_cents - gift_part, \"store_credit\": 0, \"gift_card\": gift_part}\n","reference":"--- /dev/null\n+++ b/shopkit/support/refund_info.py\n@@ -0,0 +1,32 @@\n+\"\"\"Where a refund would go (card, store credit, gift card), for support agents. Mirrors the\n+routing in payments.settlement.settle_refund without executing anything.\"\"\"\n+from datetime import date\n+\n+from shopkit.payments.models import CAPTURED, Payment\n+from shopkit.payments.settlement import CARD_REFUND_MAX_AGE_DAYS\n+\n+\n+def refund_destinations(order_id: str, amount_cents: int, payments: list[Payment], today: date) -> dict[str, int]:\n+    out = {\"card\": 0, \"store_credit\": 0, \"gift_card\": 0}\n+    captured = [p for p in payments if p.order_id == order_id and p.status == CAPTURED]\n+    ordered = sorted(captured, key=lambda p: (p.method == \"gift_card\", p.created))\n+    weights = [p.refundable_cents for p in ordered]\n+    total = sum(weights)\n+    if not total or amount_cents <= 0:\n+        return out\n+    shares = [amount_cents * w // total for w in weights]\n+    leftover = amount_cents - sum(shares)\n+    for i, p in enumerate(ordered):\n+        if leftover <= 0:\n+            break\n+        give = min(p.refundable_cents - shares[i], leftover)\n+        shares[i] += give\n+        leftover -= give\n+    for p, share in zip(ordered, shares):\n+        if p.method == \"gift_card\":\n+            out[\"gift_card\"] += share\n+        elif (today - p.created.date()).days > CARD_REFUND_MAX_AGE_DAYS:\n+            out[\"store_credit\"] += share\n+        else:\n+            out[\"card\"] += share\n+    return out\n"}},{"id":"long-003","category":"long","tier":5,"target_file":"shopkit/shipping/options.py","repo_sizes":["L"],"prompt":"Checkout should only offer express delivery when the warehouse will really send the order by\nexpress. Add `express_available(skus, sites, hazmat_skus)` in a new module\n`shopkit/shipping/options.py`: `skus` are the cart's SKUs, `sites` the warehouse sites that could\nship it (warehouse.sites.Site), `hazmat_skus` the SKUs classed as dangerous goods. Return True when\nthe warehouse would put an order with these SKUs into an express wave, False otherwise.","helpers":[],"decoys":[],"hidden_tests":{"test_options.py":"from shopkit.shipping.options import express_available\nfrom shopkit.warehouse.sites import Site\n\nAIR_AND_GROUND = Site(\"MAIN\", \"Main\")\nAIR_ONLY = Site(\"EAST\", \"East\", services=frozenset({\"air\"}))\n\n\ndef test_ordinary_carts_can_go_express():\n    assert express_available([\"MUG\", \"TEA\"], [AIR_AND_GROUND, AIR_ONLY], frozenset({\"BATT\"})) is True\n\n\ndef test_dangerous_goods_never_go_express():\n    assert express_available([\"MUG\", \"BATT\"], [AIR_AND_GROUND, AIR_ONLY], frozenset({\"BATT\"})) is False\n    assert express_available([\"BATT\"], [AIR_ONLY], frozenset({\"BATT\"})) is False\n\n\ndef test_no_site_no_express():\n    assert express_available([\"MUG\"], [], frozenset()) is False\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/shipping/options.py\n@@ -0,0 +1,3 @@\n+def express_available(skus, sites, hazmat_skus):\n+    # express needs a site that ships by air\n+    return any(\"air\" in s.services for s in sites)\n","reference":"--- /dev/null\n+++ b/shopkit/shipping/options.py\n@@ -0,0 +1,10 @@\n+\"\"\"Delivery options shown at checkout.\"\"\"\n+from shopkit.warehouse.sites import Site\n+\n+\n+def express_available(skus: list[str], sites: list[Site], hazmat_skus: frozenset[str]) -> bool:\n+    \"\"\"An order with dangerous goods is never put into an express wave (warehouse.waves.allocate_wave\n+    downgrades it to standard), so express is offered only for carts without them.\"\"\"\n+    if not sites:\n+        return False\n+    return not any(sku in hazmat_skus for sku in skus)\n"}},{"id":"long-004","category":"long","tier":5,"target_file":"shopkit/pricing/coupon_preview.py","repo_sizes":["L"],"prompt":"Shoppers want to see what a discount code would save them before they apply it. Add\n`coupon_savings(items, products, code, coupons, engine, ship_to, weight_g, at)` in a new module\n`shopkit/pricing/coupon_preview.py`. It returns the saving in cents that the code would give on this\ncart, calculated exactly as the cart page calculates it, and 0 when the code wouldn't apply.","helpers":[],"decoys":[],"hidden_tests":{"test_coupon_preview.py":"from datetime import date, datetime\n\nfrom shopkit.catalog.models import Product\nfrom shopkit.customers.models import Address\nfrom shopkit.pricing.cart import CartItem\nfrom shopkit.pricing.coupon_preview import coupon_savings\nfrom shopkit.pricing.engine import PricingEngine\nfrom shopkit.pricing.schedules import ScheduledPrice\nfrom shopkit.promotions.coupons import FIXED, PERCENT, Coupon\n\nAT = datetime(2026, 3, 10, 12)\nTO = Address(\"Bo\", \"2 Elm\", \"Portland\", \"97201\", \"US\", region=\"OR\")\nPRODUCTS = {\"MUG\": Product(\"MUG\", \"Mug\", 2000), \"TEA\": Product(\"TEA\", \"Tea\", 1000)}\nTEN = Coupon(\"TEN\", PERCENT, 10, date(2026, 1, 1), date(2026, 12, 31), min_order_cents=3_000)\nFIVE = Coupon(\"FIVE\", FIXED, 500, date(2026, 1, 1), date(2026, 12, 31))\n\n\ndef _engine():\n    e = PricingEngine()\n    e.schedule.add(ScheduledPrice(\"TEA\", \"USD\", 800, datetime(2026, 3, 1), datetime(2026, 3, 31), \"Spring\"))\n    return e\n\n\ndef _save(items, code):\n    return coupon_savings(items, PRODUCTS, code, {\"TEN\": TEN, \"FIVE\": FIVE}, _engine(), TO, 400, AT)\n\n\ndef test_percentage_codes_skip_sale_items_but_sale_items_count_for_the_minimum():\n    assert _save([CartItem(\"MUG\", 1), CartItem(\"TEA\", 2)], \"ten\") == 200\n    assert _save([CartItem(\"MUG\", 1)], \"TEN\") == 0                      # 20.00 < 30.00 minimum\n\n\ndef test_fixed_and_unknown_codes():\n    assert _save([CartItem(\"TEA\", 1)], \"FIVE\") == 500\n    assert _save([CartItem(\"MUG\", 1)], \"NOPE\") == 0\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/pricing/coupon_preview.py\n@@ -0,0 +1,12 @@\n+from shopkit.promotions.coupons import PERCENT, normalize_code\n+from shopkit.utils.numbers import apply_rate\n+\n+\n+def coupon_savings(items, products, code, coupons, engine, ship_to, weight_g, at):\n+    coupon = coupons.get(normalize_code(code))\n+    if coupon is None:\n+        return 0\n+    subtotal = sum(engine.line_total(products[i.sku], i.qty, at=at) for i in items)\n+    if subtotal < coupon.min_order_cents:\n+        return 0\n+    return apply_rate(subtotal, coupon.value) if coupon.kind == PERCENT else min(coupon.value, subtotal)\n","reference":"--- /dev/null\n+++ b/shopkit/pricing/coupon_preview.py\n@@ -0,0 +1,15 @@\n+\"\"\"What a discount code would save on a cart, as the cart page computes it.\"\"\"\n+from datetime import datetime\n+\n+from shopkit.catalog.models import Product\n+from shopkit.customers.models import Address\n+from shopkit.pricing.cart import CartItem, price_cart\n+from shopkit.pricing.engine import PricingEngine\n+from shopkit.promotions.coupons import Coupon\n+\n+\n+def coupon_savings(items: list[CartItem], products: dict[str, Product], code: str, coupons: dict[str, Coupon],\n+                   engine: PricingEngine, ship_to: Address, weight_g: int, at: datetime) -> int:\n+    cart = price_cart(items, products, engine=engine, ship_to=ship_to, weight_g=weight_g, at=at,\n+                      coupon_code=code, coupons=coupons)\n+    return cart.coupon_discount_cents\n"}},{"id":"long-005","category":"long","tier":5,"target_file":"shopkit/api/partner_status.py","repo_sizes":["L"],"prompt":"Partners keep asking why some order events reach them late. Add `explain_delay(event, order_id,\nunder_review)` in a new module `shopkit/api/partner_status.py`. `under_review` is a callable that\ntells whether an order is in fraud review. Return a short reason (any non-empty string) when our\nwebhook worker would hold that event back right now, and None when it would send it normally.","helpers":[],"decoys":[],"hidden_tests":{"test_partner_status.py":"from shopkit.api.partner_status import explain_delay\n\n\ndef test_events_for_orders_in_review_are_held():\n    assert explain_delay(\"order.paid\", \"O1\", lambda oid: True)\n    assert explain_delay(\"order.paid\", \"O1\", lambda oid: False) is None\n\n\ndef test_cancellations_and_refunds_are_never_held():\n    assert explain_delay(\"order.cancelled\", \"O1\", lambda oid: True) is None\n    assert explain_delay(\"refund.settled\", \"O1\", lambda oid: True) is None\n\n\ndef test_failed_review_lookup_holds_and_events_without_order_go_out():\n    def broken(oid):\n        raise RuntimeError(\"fraud service down\")\n    assert explain_delay(\"order.shipped\", \"O1\", broken)\n    assert explain_delay(\"product.updated\", None, lambda oid: True) is None\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/api/partner_status.py\n@@ -0,0 +1,4 @@\n+def explain_delay(event, order_id, under_review):\n+    if order_id and under_review(order_id):\n+        return \"held: the order is being reviewed\"\n+    return None\n","reference":"--- /dev/null\n+++ b/shopkit/api/partner_status.py\n@@ -0,0 +1,14 @@\n+\"\"\"Why a partner's webhook event is delayed, for the partner support page.\"\"\"\n+from shopkit.api.webhook_delivery import ALWAYS_DELIVER\n+\n+\n+def explain_delay(event: str, order_id: str | None, under_review) -> str | None:\n+    \"\"\"Mirrors the review hold in api.webhook_delivery.deliver_pending: events about an order in\n+    fraud review wait (a failed lookup counts as in review), except ALWAYS_DELIVER events.\"\"\"\n+    if not order_id or event in ALWAYS_DELIVER:\n+        return None\n+    try:\n+        reviewing = bool(under_review(order_id))\n+    except Exception:\n+        reviewing = True\n+    return \"held: the order is being reviewed\" if reviewing else None\n"}},{"id":"reuse-001","category":"reuse","tier":4,"target_file":"shopkit/orders/export.py","repo_sizes":["S","M"],"prompt":"Finance wants a spreadsheet of orders. Add `export_orders_csv(orders) -> str` next to the existing\nJSON export. One row per order line, with the header `order_id,product_code,quantity,line_total`.\nProduct codes must be cleaned up the same way they are everywhere else in the shop, and line totals\nmust look exactly like they do on customer invoices. Use the standard csv module.","helpers":[{"qualname":"shopkit.utils.text.normalize_sku","naming":"opaque"},{"qualname":"shopkit.money.format_money","naming":"opaque"}],"decoys":[{"qualname":"shopkit.shipping.labels.label_code","looks_like":"shopkit.utils.text.normalize_sku"},{"qualname":"shopkit.utils.strings.sku_code","looks_like":"shopkit.utils.text.normalize_sku"},{"qualname":"shopkit.reports.formatting.fmt_amount","looks_like":"shopkit.money.format_money"},{"qualname":"shopkit.utils.strings.amount_str","looks_like":"shopkit.money.format_money"},{"qualname":"shopkit.common.StringUtils.cleanSKU","looks_like":"shopkit.utils.text.normalize_sku"},{"qualname":"shopkit.common.StringUtils.formatPrice","looks_like":"shopkit.money.format_money"},{"qualname":"shopkit.domain.text.normalize_code","looks_like":"shopkit.utils.text.normalize_sku","repos":["L"]},{"qualname":"shopkit.domain.money.Money.format","looks_like":"shopkit.money.format_money","repos":["L"]}],"hidden_tests":{"test_export_csv.py":"from shopkit.orders.export import export_orders_csv\nfrom shopkit.orders.models import Order, OrderLine\n\n\ndef _rows():\n    orders = [\n        Order(id=\"o1\", lines=[OrderLine(sku=\"ab 12c\", qty=3, unit_cents=123456)]),\n        Order(id=\"o2\", lines=[OrderLine(sku=\"x-9\", qty=1, unit_cents=5), OrderLine(sku=\"Kz/77\", qty=2, unit_cents=1000)]),\n    ]\n    return export_orders_csv(orders).strip().splitlines()\n\n\ndef test_header():\n    assert _rows()[0] == \"order_id,product_code,quantity,line_total\"\n\n\ndef test_values_match_invoice_formatting():\n    rows = _rows()\n    assert rows[1] == 'o1,AB-12-C,3,\"$3,703.68\"'\n    assert rows[2] == \"o2,X-9,1,$0.05\"\n    assert rows[3] == \"o2,KZ-77,2,$20.00\"\n","test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.orders import export\nfrom shopkit.orders.models import Order, OrderLine\n\n\ndef test_uses_existing_helpers(monkeypatch):\n    sku_calls = spy(monkeypatch, \"shopkit.utils.text.normalize_sku\")\n    money_calls = spy(monkeypatch, \"shopkit.money.format_money\")\n    export.export_orders_csv([Order(id=\"o1\", lines=[OrderLine(sku=\"ab1\", qty=1, unit_cents=100)])])\n    assert sku_calls, \"product codes not cleaned with the shop's existing helper\"\n    assert money_calls, \"line totals not formatted with the shop's existing helper\"\n"},"solutions":{"context_blind":"diff --color -ruN a/shopkit/orders/export.py b/shopkit/orders/export.py\n--- a/shopkit/orders/export.py\t2026-11-17 22:18:46.473717312 -0800\n+++ b/shopkit/orders/export.py\t2026-11-17 22:18:46.475860456 -0800\n@@ -14,3 +14,16 @@\n         for o in orders\n     ]\n     return json.dumps(payload, indent=2)\n+\n+\n+def export_orders_csv(orders: list[Order]) -> str:\n+    import csv\n+    import io\n+    buf = io.StringIO()\n+    writer = csv.writer(buf)\n+    writer.writerow([\"order_id\", \"product_code\", \"quantity\", \"line_total\"])\n+    for o in orders:\n+        for l in o.lines:\n+            code = l.sku.strip().upper().replace(\" \", \"-\")\n+            writer.writerow([o.id, code, l.qty, f\"${l.total_cents / 100:,.2f}\"])\n+    return buf.getvalue()\n","reference":"diff --color -ruN a/shopkit/orders/export.py b/shopkit/orders/export.py\n--- a/shopkit/orders/export.py\t2026-11-17 22:01:27.670547444 -0800\n+++ b/shopkit/orders/export.py\t2026-11-17 22:01:27.673208624 -0800\n@@ -14,3 +14,15 @@\n         for o in orders\n     ]\n     return json.dumps(payload, indent=2)\n+\n+\n+def export_orders_csv(orders):\n+    import csv, io\n+    from shopkit.money import format_money\n+    from shopkit.utils.text import normalize_sku\n+    buf = io.StringIO(); w = csv.writer(buf)\n+    w.writerow([\"order_id\", \"product_code\", \"quantity\", \"line_total\"])\n+    for o in orders:\n+        for l in o.lines:\n+            w.writerow([o.id, normalize_sku(l.sku), l.qty, format_money(l.total_cents, o.currency)])\n+    return buf.getvalue()\n"}},{"id":"reuse-002","category":"reuse","tier":3,"target_file":"shopkit/catalog/models.py","repo_sizes":["S","M"],"prompt":"The storefront needs stable product page addresses. Add a read-only `url_path` property to\n`Product` that returns \"/products/<slug>\", where the slug is made from the product title using\nthe same URL slug rules the shop already uses for titles.","helpers":[{"qualname":"shopkit.utils.text.slug_for_title","naming":"matching"}],"decoys":[{"qualname":"shopkit.utils.strings.slugify","looks_like":"shopkit.utils.text.slug_for_title"},{"qualname":"shopkit.marketing.campaigns.campaign_handle","looks_like":"shopkit.utils.text.slug_for_title"},{"qualname":"shopkit.common.StringUtils.makeSlug","looks_like":"shopkit.utils.text.slug_for_title"},{"qualname":"shopkit.domain.text.title_slug","looks_like":"shopkit.utils.text.slug_for_title","repos":["L"]}],"hidden_tests":{"test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.catalog.models import Product\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.utils.text.slug_for_title\")\n    Product(\"p1\", \"Blue Mug\", 1200).url_path\n    assert calls, \"slug not built with the shop's existing helper\"\n","test_url_path.py":"from shopkit.catalog.models import Product\n\n\ndef test_simple_title():\n    assert Product(\"p1\", \"Blue Mug\", 1200).url_path == \"/products/blue-mug\"\n\n\ndef test_accents_and_punctuation():\n    p = Product(\"p2\", \"Caf\u00e9 Cr\u00e8me \u2014 Deluxe 2.0!\", 1500)\n    assert p.url_path == \"/products/cafe-creme-deluxe-2-0\"\n\n\ndef test_is_read_only_property():\n    assert isinstance(Product.__dict__[\"url_path\"], property)\n"},"solutions":{"context_blind":"diff --color -ruN a/shopkit/catalog/models.py b/shopkit/catalog/models.py\n--- a/shopkit/catalog/models.py\t2026-11-17 22:01:27.678171466 -0800\n+++ b/shopkit/catalog/models.py\t2026-11-17 22:01:27.681208844 -0800\n@@ -1,4 +1,5 @@\n from dataclasses import dataclass\n+import re\n \n \n @dataclass\n@@ -10,3 +11,7 @@\n \n     def is_purchasable(self) -> bool:\n         return self.active and self.price_cents > 0\n+\n+    @property\n+    def url_path(self) -> str:\n+        return \"/products/\" + re.sub(r\"[^a-z0-9]+\", \"-\", self.title.lower()).strip(\"-\")\n","reference":"diff --color -ruN a/shopkit/catalog/models.py b/shopkit/catalog/models.py\n--- a/shopkit/catalog/models.py\t2026-11-17 22:01:27.685954627 -0800\n+++ b/shopkit/catalog/models.py\t2026-11-17 22:01:27.689209064 -0800\n@@ -1,4 +1,5 @@\n from dataclasses import dataclass\n+from shopkit.utils.text import slug_for_title\n \n \n @dataclass\n@@ -10,3 +11,7 @@\n \n     def is_purchasable(self) -> bool:\n         return self.active and self.price_cents > 0\n+\n+    @property\n+    def url_path(self) -> str:\n+        return f\"/products/{slug_for_title(self.title)}\"\n"}},{"id":"reuse-003","category":"reuse","tier":3,"target_file":"shopkit/payments/refunds.py","repo_sizes":["M","L"],"prompt":"Support keeps getting asked when refunded money reaches the customer's card. Add\n`expected_arrival(refund: Refund) -> date` to the refunds module: banks need five business days,\ncounted from the day the refund was issued, on the shop's usual business-day calendar (weekends and\nthe days the shop is closed don't count).","helpers":[{"qualname":"shopkit.utils.dates.add_business_days","naming":"matching"}],"decoys":[{"qualname":"shopkit.common.date_helpers.addWorkDays","looks_like":"shopkit.utils.dates.add_business_days"}],"hidden_tests":{"test_expected_arrival.py":"from datetime import date, datetime, timezone\n\nfrom shopkit.payments.refunds import Refund, expected_arrival\n\n\ndef _issued(y, m, d):\n    return Refund(\"pay_1\", 500, \"damaged\", at=datetime(y, m, d, 15, 0, tzinfo=timezone.utc))\n\n\ndef test_plain_week():\n    assert expected_arrival(_issued(2026, 11, 20)) == date(2026, 11, 27)     # Fri -> next Fri\n\n\ndef test_issued_on_a_weekend():\n    assert expected_arrival(_issued(2026, 11, 21)) == date(2026, 11, 27)     # Sat -> Fri\n\n\ndef test_holidays_do_not_count():\n    assert expected_arrival(_issued(2026, 12, 23)) == date(2026, 12, 31)     # skips Dec 25/26\n","test_reuse.py":"from reuse_spy import spy\n\nfrom datetime import datetime, timezone\n\nfrom shopkit.payments.refunds import Refund, expected_arrival\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.utils.dates.add_business_days\")\n    expected_arrival(Refund(\"p\", 1, \"x\", at=datetime(2026, 11, 20, tzinfo=timezone.utc)))\n    assert calls, \"arrival date not computed with the shop's business-day helper\"\n"},"solutions":{"context_blind":"--- a/shopkit/payments/refunds.py\n+++ b/shopkit/payments/refunds.py\n@@ -1,6 +1,6 @@\n \"\"\"Refunds against captured payments. Partial refunds are allowed up to the captured amount.\"\"\"\n from dataclasses import dataclass, field\n-from datetime import datetime\n+from datetime import date, datetime, timedelta\n \n from shopkit.errors import Conflict\n from shopkit.money import format_money\n@@ -30,3 +30,12 @@\n             payment_id=payment.id, requested=amount_cents, refundable=payment.refundable_cents)\n     payment.refunded_cents += amount_cents\n     return Refund(payment.id, amount_cents, reason)\n+\n+\n+def expected_arrival(refund: Refund) -> date:\n+    day, left = refund.at.date(), 5\n+    while left:\n+        day += timedelta(days=1)\n+        if day.weekday() < 5:\n+            left -= 1\n+    return day\n","reference":"--- a/shopkit/payments/refunds.py\n+++ b/shopkit/payments/refunds.py\n@@ -1,11 +1,13 @@\n \"\"\"Refunds against captured payments. Partial refunds are allowed up to the captured amount.\"\"\"\n from dataclasses import dataclass, field\n-from datetime import datetime\n+from datetime import date, datetime\n \n from shopkit.errors import Conflict\n from shopkit.money import format_money\n from shopkit.payments.models import Payment\n-from shopkit.utils.dates import utc_now\n+from shopkit.utils.dates import add_business_days, utc_now\n+\n+BANK_PROCESSING_DAYS = 5\n \n \n class RefundTooLarge(Conflict):\n@@ -30,3 +32,9 @@\n             payment_id=payment.id, requested=amount_cents, refundable=payment.refundable_cents)\n     payment.refunded_cents += amount_cents\n     return Refund(payment.id, amount_cents, reason)\n+\n+\n+def expected_arrival(refund: Refund) -> date:\n+    \"\"\"When the money should reach the customer: BANK_PROCESSING_DAYS business days after the\n+    refund was issued.\"\"\"\n+    return add_business_days(refund.at.date(), BANK_PROCESSING_DAYS)\n"}},{"id":"reuse-004","category":"reuse","tier":4,"target_file":"shopkit/orders/returns.py","repo_sizes":["M","L"],"prompt":"Changed-mind returns will now carry a 12.5% restocking fee. Add `restocking_fee_cents(order)` to\n`ReturnRequest`: 12.5% of the return's refund amount for changed-mind returns, 0 for every other\nreason. It is a percentage of money, so round it exactly the way the shop rounds its other\npercentage amounts such as tax and discounts.","helpers":[{"qualname":"shopkit.utils.numbers.apply_rate","naming":"opaque"}],"decoys":[],"hidden_tests":{"test_restocking_fee.py":"from shopkit.orders.models import Order, OrderLine\nfrom shopkit.orders.returns import ReturnRequest\n\n\ndef _fee(unit_cents, reason=\"changed_mind\"):\n    order = Order(\"o1\", [OrderLine(\"SKU\", 1, unit_cents)])\n    return ReturnRequest(\"o1\", {\"SKU\": 1}, reason).restocking_fee_cents(order)\n\n\ndef test_whole_cents():\n    assert _fee(2000) == 250\n\n\ndef test_half_cents_round_like_the_rest_of_the_shop():\n    assert _fee(996) == 125        # 124.5\n    assert _fee(1012) == 127       # 126.5\n\n\ndef test_only_changed_mind_pays():\n    assert _fee(996, \"damaged\") == 0\n","test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.orders.models import Order, OrderLine\nfrom shopkit.orders.returns import ReturnRequest\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.utils.numbers.apply_rate\")\n    ReturnRequest(\"o1\", {\"S\": 1}, \"changed_mind\").restocking_fee_cents(Order(\"o1\", [OrderLine(\"S\", 1, 996)]))\n    assert calls, \"fee not computed with the shop's percentage helper\"\n"},"solutions":{"context_blind":"--- a/shopkit/orders/returns.py\n+++ b/shopkit/orders/returns.py\n@@ -30,6 +30,11 @@\n         prices = {line.sku: line.unit_cents for line in order.lines}\n         return sum(prices[sku] * qty for sku, qty in self.items.items())\n \n+    def restocking_fee_cents(self, order: Order) -> int:\n+        if self.reason != \"changed_mind\":\n+            return 0\n+        return round(self.refund_cents(order) * 12.5 / 100)\n+\n \n def open_return(order: Order, delivered_on: date, items: dict[str, int], reason: str,\n                 today: date) -> ReturnRequest:\n","reference":"--- a/shopkit/orders/returns.py\n+++ b/shopkit/orders/returns.py\n@@ -5,8 +5,10 @@\n from shopkit.errors import Conflict, ShopError\n from shopkit.orders.models import Order\n from shopkit.utils.ids import short_code\n+from shopkit.utils.numbers import apply_rate\n \n RETURN_WINDOW_DAYS = 30\n+RESTOCKING_FEE_PCT = \"12.5\"         # changed-mind returns only\n REASONS = (\"damaged\", \"wrong_item\", \"not_as_described\", \"changed_mind\")\n \n \n@@ -30,6 +32,11 @@\n         prices = {line.sku: line.unit_cents for line in order.lines}\n         return sum(prices[sku] * qty for sku, qty in self.items.items())\n \n+    def restocking_fee_cents(self, order: Order) -> int:\n+        if self.reason != \"changed_mind\":\n+            return 0\n+        return apply_rate(self.refund_cents(order), RESTOCKING_FEE_PCT)\n+\n \n def open_return(order: Order, delivered_on: date, items: dict[str, int], reason: str,\n                 today: date) -> ReturnRequest:\n"}},{"id":"reuse-005","category":"reuse","tier":4,"target_file":"shopkit/payments/gateway.py","repo_sizes":["M","L"],"prompt":"We're adding pay-by-bank-transfer. Customers type a payment reference into their banking app,\noften copying it from a printed invoice or hearing it over the phone. Add\n`transfer_reference() -> str` to the payments gateway module that generates a new reference: 12\ncharacters in three dash-separated groups of four, in the same style as the shop's other\ncustomer-facing codes.","helpers":[{"qualname":"shopkit.utils.ids.short_code","naming":"opaque"}],"decoys":[],"hidden_tests":{"test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.payments.gateway import transfer_reference\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.utils.ids.short_code\")\n    transfer_reference()\n    assert calls, \"reference not generated with the shop's code helper\"\n","test_transfer_reference.py":"import re\n\nfrom shopkit.payments.gateway import transfer_reference\n\nREFS = [transfer_reference() for _ in range(300)]\n\n\ndef test_shape():\n    assert all(re.fullmatch(r\"[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}\", r) for r in REFS)\n\n\ndef test_no_look_alike_characters():\n    assert not any(set(r) & set(\"0O1IL\") for r in REFS)\n\n\ndef test_fresh_each_time():\n    assert len(set(REFS)) > 295\n"},"solutions":{"context_blind":"--- a/shopkit/payments/gateway.py\n+++ b/shopkit/payments/gateway.py\n@@ -1,8 +1,17 @@\n \"\"\"Card gateway adapter. The real provider is behind `charge`; tests use FakeGateway.\"\"\"\n+import secrets\n+import string\n+\n from shopkit.errors import ShopError\n from shopkit.payments.models import AUTHORIZED, CAPTURED, FAILED, Payment\n from shopkit.payments.reconciliation import redact_pan\n from shopkit.utils.ids import new_id\n+\n+\n+def transfer_reference() -> str:\n+    chars = string.ascii_uppercase + string.digits\n+    code = \"\".join(secrets.choice(chars) for _ in range(12))\n+    return \"-\".join(code[i:i + 4] for i in range(0, 12, 4))\n \n \n class PaymentDeclined(ShopError):\n","reference":"--- a/shopkit/payments/gateway.py\n+++ b/shopkit/payments/gateway.py\n@@ -2,7 +2,12 @@\n from shopkit.errors import ShopError\n from shopkit.payments.models import AUTHORIZED, CAPTURED, FAILED, Payment\n from shopkit.payments.reconciliation import redact_pan\n-from shopkit.utils.ids import new_id\n+from shopkit.utils.ids import new_id, short_code\n+\n+\n+def transfer_reference() -> str:\n+    \"\"\"Reference a customer quotes on a bank transfer, e.g. \\\"K7QM-X2PA-9RTW\\\".\"\"\"\n+    return short_code(12, groups=4)\n \n \n class PaymentDeclined(ShopError):\n"}},{"id":"reuse-006","category":"reuse","tier":3,"target_file":"shopkit/marketing/newsletter.py","repo_sizes":["M","L"],"prompt":"Our email provider is penalising us for bounces from badly typed addresses imported from an old\nsystem. Newsletter recipients must now also have an email address that passes the same check the\nshop applies at signup and checkout; everyone else is skipped.","helpers":[{"qualname":"shopkit.utils.validation.is_valid_email","naming":"matching"}],"decoys":[{"qualname":"shopkit.common.StringUtils.isEmail","looks_like":"shopkit.utils.validation.is_valid_email"}],"hidden_tests":{"test_newsletter_recipients.py":"from shopkit.customers.models import Customer\nfrom shopkit.marketing.newsletter import recipients\n\n\ndef _ids(*emails, opt_in=True):\n    return [c.id for c in recipients([Customer(f\"c{i}\", e, \"Ann\", marketing_opt_in=opt_in)\n                                      for i, e in enumerate(emails)])]\n\n\ndef test_valid_addresses_kept():\n    assert _ids(\"ann@shop.example\", \" bob@shop.example \") == [\"c0\", \"c1\"]\n\n\ndef test_badly_typed_addresses_skipped():\n    assert _ids(\"ann..b@shop.example\", \"ann@localhost\", \"no-at.shop.example\", \"ann@shop.c\") == []\n\n\ndef test_still_requires_opt_in():\n    assert _ids(\"ann@shop.example\", opt_in=False) == []\n","test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.customers.models import Customer\nfrom shopkit.marketing.newsletter import recipients\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.utils.validation.is_valid_email\")\n    recipients([Customer(\"c1\", \"ann@shop.example\", \"Ann\", marketing_opt_in=True)])\n    assert calls, \"addresses not checked with the shop's email validation\"\n"},"solutions":{"context_blind":"--- a/shopkit/marketing/newsletter.py\n+++ b/shopkit/marketing/newsletter.py\n@@ -10,7 +10,10 @@\n \n \n def recipients(customers: list[Customer]) -> list[Customer]:\n-    return [c for c in customers if c.marketing_opt_in]\n+    def plausible(email: str) -> bool:\n+        local, _, domain = email.strip().partition(\"@\")\n+        return bool(local) and \".\" in domain and \" \" not in email.strip()\n+    return [c for c in customers if c.marketing_opt_in and plausible(c.email)]\n \n \n def render_for(customer: Customer, campaign: Campaign, intro: str) -> str:\n","reference":"--- a/shopkit/marketing/newsletter.py\n+++ b/shopkit/marketing/newsletter.py\n@@ -3,6 +3,7 @@\n from shopkit.marketing.campaigns import Campaign\n from shopkit.notifications.templates import render_template\n from shopkit.utils.collections import chunked\n+from shopkit.utils.validation import is_valid_email\n \n BATCH_SIZE = 500          # provider limit per API call\n \n@@ -10,7 +11,7 @@\n \n \n def recipients(customers: list[Customer]) -> list[Customer]:\n-    return [c for c in customers if c.marketing_opt_in]\n+    return [c for c in customers if c.marketing_opt_in and is_valid_email(c.email)]\n \n \n def render_for(customer: Customer, campaign: Campaign, intro: str) -> str:\n"}},{"id":"reuse-007","category":"reuse","tier":4,"target_file":"shopkit/inventory/transfers.py","repo_sizes":["M","L"],"prompt":"Ops wants a weekly view of stock rebalancing. Add `transfers_by_week(transfers) -> dict[str, int]`\nto the transfers module: total units moved per week, keyed by week with the same week labels the\nother dashboards use, in chronological order.","helpers":[{"qualname":"shopkit.utils.dates.iso_week_label","naming":"opaque"}],"decoys":[],"hidden_tests":{"test_reuse.py":"from reuse_spy import spy\n\nfrom datetime import datetime, timezone\n\nfrom shopkit.inventory.transfers import Transfer, transfers_by_week\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.utils.dates.iso_week_label\")\n    transfers_by_week([Transfer(\"S\", 1, \"a\", \"b\", at=datetime(2026, 11, 18, tzinfo=timezone.utc))])\n    assert calls, \"weeks not labelled with the dashboards' week helper\"\n","test_transfers_by_week.py":"from datetime import datetime, timezone\n\nfrom shopkit.inventory.transfers import Transfer, transfers_by_week\n\n\ndef _t(qty, y, m, d):\n    return Transfer(\"SKU\", qty, \"east\", \"west\", at=datetime(y, m, d, 9, 0, tzinfo=timezone.utc))\n\n\ndef test_one_week():\n    assert transfers_by_week([_t(2, 2026, 11, 16), _t(3, 2026, 11, 18)]) == {\"2026-W47\": 5}\n\n\ndef test_year_end_week_and_order():\n    weeks = transfers_by_week([_t(1, 2027, 1, 4), _t(2, 2026, 12, 31), _t(3, 2027, 1, 1)])\n    assert weeks == {\"2026-W53\": 5, \"2027-W01\": 1}\n    assert list(weeks) == [\"2026-W53\", \"2027-W01\"]\n"},"solutions":{"context_blind":"--- a/shopkit/inventory/transfers.py\n+++ b/shopkit/inventory/transfers.py\n@@ -31,3 +31,11 @@\n     src.stock._on_hand[sku] -= qty\n     network.get(destination).stock.receive(sku, qty)\n     return Transfer(sku, qty, source, destination)\n+\n+\n+def transfers_by_week(transfers: list[Transfer]) -> dict[str, int]:\n+    weeks: dict[str, int] = {}\n+    for t in sorted(transfers, key=lambda t: t.at):\n+        label = t.at.strftime(\"%Y-W%W\")\n+        weeks[label] = weeks.get(label, 0) + t.qty\n+    return weeks\n","reference":"--- a/shopkit/inventory/transfers.py\n+++ b/shopkit/inventory/transfers.py\n@@ -4,7 +4,7 @@\n \n from shopkit.errors import Conflict\n from shopkit.inventory.warehouses import Network\n-from shopkit.utils.dates import utc_now\n+from shopkit.utils.dates import iso_week_label, utc_now\n \n \n class TransferFailed(Conflict):\n@@ -31,3 +31,12 @@\n     src.stock._on_hand[sku] -= qty\n     network.get(destination).stock.receive(sku, qty)\n     return Transfer(sku, qty, source, destination)\n+\n+\n+def transfers_by_week(transfers: list[Transfer]) -> dict[str, int]:\n+    \"\"\"Units moved per dashboard week, oldest week first.\"\"\"\n+    weeks: dict[str, int] = {}\n+    for t in sorted(transfers, key=lambda t: t.at):\n+        label = iso_week_label(t.at.date())\n+        weeks[label] = weeks.get(label, 0) + t.qty\n+    return weeks\n"}},{"id":"reuse-008","category":"reuse","tier":4,"target_file":"shopkit/api/webhooks.py","repo_sizes":["M","L"],"prompt":"A partner noticed full card numbers in our webhook deliveries for payment events. Before a delivery\nis queued, a `card_number` field in the event data must be masked the same way the shop masks card\nnumbers everywhere else it stores or shows them. Other fields go out unchanged.","helpers":[{"qualname":"shopkit.payments.reconciliation.redact_pan","naming":"opaque"}],"decoys":[{"qualname":"shopkit.common.CustomerUtils.maskCard","looks_like":"shopkit.payments.reconciliation.redact_pan"}],"hidden_tests":{"test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.api.webhooks import Endpoint, WebhookDispatcher\nfrom shopkit.events import Event\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.payments.reconciliation.redact_pan\")\n    WebhookDispatcher([Endpoint(\"u\", \"k\", {\"payment.*\"})]).on_event(Event(\"payment.captured\", {\"card_number\": \"4242424242424242\"}))\n    assert calls, \"card number not masked with the shop's masking helper\"\n","test_webhook_masking.py":"import json\n\nfrom shopkit.api.webhooks import Endpoint, WebhookDispatcher\nfrom shopkit.events import Event\n\n\ndef _sent(payload):\n    d = WebhookDispatcher([Endpoint(\"https://partner/hook\", \"k\", {\"payment.*\"})])\n    d.on_event(Event(\"payment.captured\", payload))\n    return json.loads(d.queue[0].body)[\"data\"]\n\n\ndef test_card_number_masked_like_everywhere_else():\n    assert _sent({\"card_number\": \"4242-4242-4242-4242\", \"amount\": 100}) == {\n        \"card_number\": \"************4242\", \"amount\": 100}\n\n\ndef test_short_numbers_fully_masked():\n    assert _sent({\"card_number\": \"123\"})[\"card_number\"] == \"***\"\n\n\ndef test_other_fields_and_original_event_untouched():\n    payload = {\"order_id\": \"o1\", \"amount\": 5}\n    assert _sent(payload) == {\"order_id\": \"o1\", \"amount\": 5}\n"},"solutions":{"context_blind":"--- a/shopkit/api/webhooks.py\n+++ b/shopkit/api/webhooks.py\n@@ -49,7 +49,11 @@\n             bus.subscribe(f\"{prefix}.*\", self.on_event)\n \n     def on_event(self, event: Event) -> None:\n-        body = json.dumps({\"event\": event.name, \"at\": event.at.isoformat(), \"data\": event.payload},\n+        data = dict(event.payload)\n+        card = data.get(\"card_number\")\n+        if isinstance(card, str):\n+            data[\"card_number\"] = \"*\" * max(len(card) - 4, 0) + card[-4:]\n+        body = json.dumps({\"event\": event.name, \"at\": event.at.isoformat(), \"data\": data},\n                           sort_keys=True, default=str)\n         for ep in self.endpoints:\n             if _subscribed(ep, event.name):\n","reference":"--- a/shopkit/api/webhooks.py\n+++ b/shopkit/api/webhooks.py\n@@ -5,6 +5,7 @@\n from dataclasses import dataclass, field\n \n from shopkit.events import Event, EventBus\n+from shopkit.payments.reconciliation import redact_pan\n \n MAX_ATTEMPTS = 5\n \n@@ -49,7 +50,10 @@\n             bus.subscribe(f\"{prefix}.*\", self.on_event)\n \n     def on_event(self, event: Event) -> None:\n-        body = json.dumps({\"event\": event.name, \"at\": event.at.isoformat(), \"data\": event.payload},\n+        data = dict(event.payload)\n+        if isinstance(data.get(\"card_number\"), str):\n+            data[\"card_number\"] = redact_pan(data[\"card_number\"])\n+        body = json.dumps({\"event\": event.name, \"at\": event.at.isoformat(), \"data\": data},\n                           sort_keys=True, default=str)\n         for ep in self.endpoints:\n             if _subscribed(ep, event.name):\n"}},{"id":"reuse-009","category":"reuse","tier":3,"target_file":"shopkit/checkout.py","repo_sizes":["M","L"],"prompt":"Show shoppers how many loyalty points an order will earn them. Give `quote()` an optional\n`customer` argument and add a `points` field to `Quote` (0 when no customer is given): the points\nthe customer earns on what they pay for the goods after any discount, exactly as loyalty points are\nearned on paid orders.","helpers":[{"qualname":"shopkit.customers.loyalty.points_for","naming":"matching"}],"decoys":[],"hidden_tests":{"test_quote_points.py":"from datetime import date\n\nfrom shopkit.catalog.models import Product\nfrom shopkit.catalog.pricing import PriceBook\nfrom shopkit.checkout import quote\nfrom shopkit.customers.models import Address, Customer\n\nSHIP_TO = Address(\"Ann\", \"1 Main St\", \"Austin\", \"78701\", \"US\", region=\"TX\")\nPRODUCTS = {\"MUG\": Product(\"MUG\", \"Mug\", 1299)}\n\n\ndef _quote(customer=None):\n    return quote({\"MUG\": 2}, PRODUCTS, SHIP_TO, 800, PriceBook(), date(2026, 11, 20), customer=customer)\n\n\ndef test_no_customer_no_points():\n    assert _quote().points == 0\n\n\ndef test_points_follow_the_customer_tier():\n    assert _quote(Customer(\"c1\", \"a@shop.example\", \"Ann\")).points == 25\n    assert _quote(Customer(\"c2\", \"b@shop.example\", \"Bob\", tier=\"gold\")).points == 75\n\n\ndef test_totals_unchanged():\n    assert _quote(Customer(\"c1\", \"a@shop.example\", \"Ann\")).total_cents == _quote().total_cents\n","test_reuse.py":"from reuse_spy import spy\n\nfrom datetime import date\n\nfrom shopkit.catalog.models import Product\nfrom shopkit.catalog.pricing import PriceBook\nfrom shopkit.checkout import quote\nfrom shopkit.customers.models import Address, Customer\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.customers.loyalty.points_for\")\n    quote({\"M\": 1}, {\"M\": Product(\"M\", \"Mug\", 1299)}, Address(\"A\", \"1\", \"X\", \"1\", \"US\"), 100, PriceBook(),\n          date(2026, 11, 20), customer=Customer(\"c\", \"a@b.example\", \"A\"))\n    assert calls, \"points not computed with the shop's loyalty helper\"\n"},"solutions":{"context_blind":"--- a/shopkit/checkout.py\n+++ b/shopkit/checkout.py\n@@ -4,7 +4,7 @@\n \n from shopkit.catalog.models import Product\n from shopkit.catalog.pricing import PriceBook\n-from shopkit.customers.models import Address\n+from shopkit.customers.models import Address, Customer\n from shopkit.errors import ShopError\n from shopkit.orders.models import Order, OrderLine\n from shopkit.promotions.coupons import Coupon, discount_cents\n@@ -29,6 +29,7 @@\n     shipping_cents: int\n     tax_cents: int\n     notes: list[str] = field(default_factory=list)\n+    points: int = 0\n \n     @property\n     def total_cents(self) -> int:\n@@ -36,7 +37,8 @@\n \n \n def quote(cart: dict[str, int], products: dict[str, Product], ship_to: Address, weight_g: int,\n-          prices: PriceBook, today: date, coupon: Coupon | None = None) -> Quote:\n+          prices: PriceBook, today: date, coupon: Coupon | None = None,\n+          customer: Customer | None = None) -> Quote:\n     \"\"\"Price a cart (sku -> qty). Tax applies after discount on the goods; shipping is untaxed.\"\"\"\n     if not cart:\n         raise EmptyCart(\"cart is empty\")\n@@ -51,4 +53,6 @@\n     tax = order_tax(order, ship_to)\n     if discount and subtotal:\n         tax = tax * (subtotal - discount) // subtotal\n-    return Quote(order, subtotal, discount, shipping_cents(ship_to.country, weight_g, subtotal), tax)\n+    points = max(subtotal - discount, 0) // 100 if customer else 0\n+    return Quote(order, subtotal, discount, shipping_cents(ship_to.country, weight_g, subtotal), tax,\n+                 points=points)\n","reference":"--- a/shopkit/checkout.py\n+++ b/shopkit/checkout.py\n@@ -4,7 +4,8 @@\n \n from shopkit.catalog.models import Product\n from shopkit.catalog.pricing import PriceBook\n-from shopkit.customers.models import Address\n+from shopkit.customers.loyalty import points_for\n+from shopkit.customers.models import Address, Customer\n from shopkit.errors import ShopError\n from shopkit.orders.models import Order, OrderLine\n from shopkit.promotions.coupons import Coupon, discount_cents\n@@ -29,6 +30,7 @@\n     shipping_cents: int\n     tax_cents: int\n     notes: list[str] = field(default_factory=list)\n+    points: int = 0                      # loyalty points this order earns\n \n     @property\n     def total_cents(self) -> int:\n@@ -36,7 +38,8 @@\n \n \n def quote(cart: dict[str, int], products: dict[str, Product], ship_to: Address, weight_g: int,\n-          prices: PriceBook, today: date, coupon: Coupon | None = None) -> Quote:\n+          prices: PriceBook, today: date, coupon: Coupon | None = None,\n+          customer: Customer | None = None) -> Quote:\n     \"\"\"Price a cart (sku -> qty). Tax applies after discount on the goods; shipping is untaxed.\"\"\"\n     if not cart:\n         raise EmptyCart(\"cart is empty\")\n@@ -51,4 +54,6 @@\n     tax = order_tax(order, ship_to)\n     if discount and subtotal:\n         tax = tax * (subtotal - discount) // subtotal\n-    return Quote(order, subtotal, discount, shipping_cents(ship_to.country, weight_g, subtotal), tax)\n+    points = points_for(customer, subtotal - discount) if customer else 0\n+    return Quote(order, subtotal, discount, shipping_cents(ship_to.country, weight_g, subtotal), tax,\n+                 points=points)\n"}},{"id":"reuse-010","category":"reuse","tier":4,"target_file":"shopkit/reports/customers_report.py","repo_sizes":["M","L"],"prompt":"Marketing's CRM sync needs a lookup from email address to customer. Add\n`by_email(customers) -> dict[str, Customer]` to the customers report module, keyed by the email\naddress trimmed and lowercased, and built the same way the shop builds its other lookup tables.","helpers":[{"qualname":"shopkit.utils.collections.index_by","naming":"opaque"}],"decoys":[],"hidden_tests":{"test_by_email.py":"import pytest\n\nfrom shopkit.customers.models import Customer\nfrom shopkit.reports.customers_report import by_email\n\n\ndef test_lookup_by_normalised_email():\n    ann, bob = Customer(\"c1\", \" Ann@Shop.Example\", \"Ann\"), Customer(\"c2\", \"bob@shop.example\", \"Bob\")\n    assert by_email([ann, bob]) == {\"ann@shop.example\": ann, \"bob@shop.example\": bob}\n\n\ndef test_two_customers_with_one_address_is_an_error():\n    with pytest.raises(ValueError):\n        by_email([Customer(\"c1\", \"ann@shop.example\", \"Ann\"), Customer(\"c2\", \"ANN@shop.example \", \"Ann B\")])\n","test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.customers.models import Customer\nfrom shopkit.reports.customers_report import by_email\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.utils.collections.index_by\")\n    by_email([Customer(\"c1\", \"a@shop.example\", \"A\")])\n    assert calls, \"lookup not built with the shop's lookup-table helper\"\n"},"solutions":{"context_blind":"--- a/shopkit/reports/customers_report.py\n+++ b/shopkit/reports/customers_report.py\n@@ -20,5 +20,9 @@\n     return {t: len(cs) for t, cs in sorted(group_by(customers, key=lambda c: c.tier).items())}\n \n \n+def by_email(customers: list[Customer]) -> dict[str, Customer]:\n+    return {c.email.strip().lower(): c for c in customers}\n+\n+\n def active_since(customers: list[Customer], since: date) -> list[Customer]:\n     return [c for c in customers if c.joined and c.joined >= since]\n","reference":"--- a/shopkit/reports/customers_report.py\n+++ b/shopkit/reports/customers_report.py\n@@ -2,7 +2,7 @@\n from datetime import date\n \n from shopkit.customers.models import Customer\n-from shopkit.utils.collections import group_by\n+from shopkit.utils.collections import group_by, index_by\n from shopkit.utils.numbers import safe_ratio\n \n \n@@ -20,5 +20,9 @@\n     return {t: len(cs) for t, cs in sorted(group_by(customers, key=lambda c: c.tier).items())}\n \n \n+def by_email(customers: list[Customer]) -> dict[str, Customer]:\n+    return index_by(customers, key=lambda c: c.email.strip().lower())\n+\n+\n def active_since(customers: list[Customer], since: date) -> list[Customer]:\n     return [c for c in customers if c.joined and c.joined >= since]\n"}},{"id":"reuse-L01","category":"reuse","tier":4,"target_file":"shopkit/pos/till.py","repo_sizes":["L"],"prompt":"We're opening pop-up stores in Canada with cash tills. Add `amount_due(total_cents, currency,\npaid_by)` in a new module `shopkit/pos/till.py` (a new package): the amount the cashier asks the\ncustomer to pay. `paid_by` is \"card\" or \"cash\". Card payments pay the exact total; cash payments\nfollow the national rules for cash amounts, the same way the shop already treats cash elsewhere.","helpers":[{"qualname":"shopkit.core.pricing.cashRoundCents","naming":"matching"}],"decoys":[],"hidden_tests":{"test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.pos.till import amount_due\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.core.pricing.cashRoundCents\")\n    amount_due(1003, \"CAD\", \"cash\")\n    assert calls, \"cash amount not rounded with the shop's existing cash rounding\"\n","test_till.py":"from shopkit.pos.till import amount_due\n\n\ndef test_cash_in_canada_follows_the_rounding_rules():\n    assert [amount_due(c, \"CAD\", \"cash\") for c in (1001, 1002, 1003, 1004, 1006, 1007, 1008, 1009)] == \\\n        [1000, 1000, 1005, 1005, 1005, 1005, 1010, 1010]\n\n\ndef test_cards_and_other_currencies_pay_the_exact_total():\n    assert amount_due(1003, \"CAD\", \"card\") == 1003\n    assert amount_due(1003, \"USD\", \"cash\") == 1003\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/pos/till.py\n@@ -0,0 +1,4 @@\n+def amount_due(total_cents, currency, paid_by):\n+    if paid_by == \"cash\" and currency == \"CAD\":\n+        return 5 * round(total_cents / 5)\n+    return total_cents\n","reference":"--- /dev/null\n+++ b/shopkit/pos/__init__.py\n@@ -0,0 +1 @@\n+\"\"\"Point of sale: tills in physical stores.\"\"\"\n--- /dev/null\n+++ b/shopkit/pos/till.py\n@@ -0,0 +1,8 @@\n+\"\"\"Till amounts for the physical stores.\"\"\"\n+from shopkit.core.pricing import cashRoundCents\n+\n+\n+def amount_due(total_cents: int, currency: str, paid_by: str) -> int:\n+    if paid_by not in (\"card\", \"cash\"):\n+        raise ValueError(f\"unknown payment method {paid_by!r}\")\n+    return cashRoundCents(total_cents, currency) if paid_by == \"cash\" else total_cents\n"}},{"id":"reuse-L02","category":"reuse","tier":4,"target_file":"shopkit/warehouse/labels.py","repo_sizes":["L"],"prompt":"The new pallet scanner in the warehouse reads the finance system's item numbers, not our SKUs.\nAdd `pallet_label(pallet_id, items)` in a new module `shopkit/warehouse/labels.py`, where `items`\nis a list of (sku, qty). It returns the label text: the first line `PALLET <pallet_id>`, then one\nline per item, `<item number> x<qty>`, in the order given, where the item number is the one the\nfinance system knows that product by.","helpers":[{"qualname":"shopkit.core.erp.toErpSku","naming":"opaque"}],"decoys":[{"qualname":"shopkit.shipping.labels.label_code","looks_like":"shopkit.core.erp.toErpSku","repos":["L"]},{"qualname":"shopkit.domain.text.normalize_code","looks_like":"shopkit.core.erp.toErpSku","repos":["L"]}],"hidden_tests":{"test_labels.py":"from shopkit.warehouse.labels import pallet_label\n\n\ndef test_label_uses_finance_item_numbers():\n    assert pallet_label(\"P-7\", [(\"MUG-1\", 3), (\"tea-set-12\", 1), (\"GIFTCARD\", 2)]) == \\\n        \"PALLET P-7\\nMUG000000001 x3\\nTEASET000012 x1\\nGIFTCARD0000 x2\"\n","test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.warehouse.labels import pallet_label\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.core.erp.toErpSku\")\n    pallet_label(\"P-1\", [(\"MUG-1\", 1)])\n    assert calls, \"item numbers not produced with the shop's existing finance item mapping\"\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/warehouse/labels.py\n@@ -0,0 +1,5 @@\n+from shopkit.shipping.labels import label_code\n+\n+\n+def pallet_label(pallet_id, items):\n+    return \"\\n\".join([f\"PALLET {pallet_id}\"] + [f\"{label_code(sku)} x{qty}\" for sku, qty in items])\n","reference":"--- /dev/null\n+++ b/shopkit/warehouse/labels.py\n@@ -0,0 +1,8 @@\n+\"\"\"Pallet labels for the warehouse scanner, which reads the ERP's item numbers.\"\"\"\n+from shopkit.core.erp import toErpSku\n+\n+\n+def pallet_label(pallet_id: str, items: list[tuple[str, int]]) -> str:\n+    lines = [f\"PALLET {pallet_id}\"]\n+    lines += [f\"{toErpSku(sku)} x{qty}\" for sku, qty in items]\n+    return \"\\n\".join(lines)\n"}},{"id":"reuse-L03","category":"reuse","tier":4,"target_file":"shopkit/support/linking.py","repo_sizes":["L"],"prompt":"Support agents want the order references in a customer's message turned into links. Add\n`order_refs(text)` in a new module `shopkit/support/linking.py`. It returns the order references\nmentioned in the text, in the order they first appear and without duplicates, each written the way\nthe shop writes that kind of reference everywhere else. Customers type them in all sorts of ways:\n\"so 2019 123\", \"SO-2019-000123\", \"ORD_1A2B3C4D5E6F\". Anything that isn't a valid order reference is\nleft out.","helpers":[{"qualname":"shopkit.core.order_engine.parseOrderRef","naming":"matching"}],"decoys":[],"hidden_tests":{"test_linking.py":"from shopkit.support.linking import order_refs\n\n\ndef test_references_are_found_normalised_and_deduplicated():\n    text = \"Hi, where is so 2019 123? I also ordered SO-2019-000123 and ORD_0123456789AB, and sob-2020-45.\"\n    assert order_refs(text) == [\"SO-2019-000123\", \"ord_0123456789ab\", \"SOB-2020-000045\"]\n\n\ndef test_invalid_references_are_left_out():\n    assert order_refs(\"old order SO-2015-000001, ticket 12345, so 2019\") == []\n","test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.support.linking import order_refs\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.core.order_engine.parseOrderRef\")\n    order_refs(\"see SO-2019-000123\")\n    assert calls, \"references not parsed with the shop's existing order reference parser\"\n"},"solutions":{"context_blind":"--- /dev/null\n+++ b/shopkit/support/linking.py\n@@ -0,0 +1,12 @@\n+import re\n+\n+_REF = re.compile(r\"\\b(SOB?)[\\s-]*(\\d{4})[\\s-]*(\\d{1,6})\\b|\\b(ord_[0-9a-f]{12})\\b\", re.I)\n+\n+\n+def order_refs(text):\n+    out = []\n+    for m in _REF.finditer(text or \"\"):\n+        ref = m.group(4).lower() if m.group(4) else f\"{m.group(1).upper()}-{m.group(2)}-{int(m.group(3)):06d}\"\n+        if ref not in out:\n+            out.append(ref)\n+    return out\n","reference":"--- /dev/null\n+++ b/shopkit/support/linking.py\n@@ -0,0 +1,18 @@\n+\"\"\"Order references in support messages.\"\"\"\n+import re\n+\n+from shopkit.core.order_engine import formatOrderRef, parseOrderRef\n+\n+_CANDIDATE = re.compile(r\"\\b(?:ord_[0-9a-f]{12}|sob?[\\s-]*\\d{4}[\\s-]*\\d{1,6})\\b\", re.I)\n+\n+\n+def order_refs(text: str) -> list[str]:\n+    out = []\n+    for m in _CANDIDATE.finditer(text or \"\"):\n+        parsed = parseOrderRef(m.group(0))\n+        if parsed is None:\n+            continue\n+        ref = formatOrderRef(*parsed)\n+        if ref not in out:\n+            out.append(ref)\n+    return out\n"}},{"id":"trap-001","category":"trap","tier":4,"target_file":"shopkit/shipping/labels.py","repo_sizes":["M","L"],"prompt":"Customers in the United States keep asking what \"kg\" means on their parcels. Add the parcel weight\nto shipping labels: `label_text` gets an optional `weight_g` argument (the parcel's weight in\ngrams). When it is given, print a line `Weight: <weight>` right after the order/parcel line.\nLabels for US addresses show pounds with two decimals (1500 g -> `3.31 lb`); every other\ndestination keeps the shop's standard kilogram display (1500 g -> `1.5 kg`). Use the shop's\nstandard weight formatting so labels match the packing slips.","helpers":[{"qualname":"shopkit.shipping.packaging.format_weight","naming":"matching"}],"decoys":[{"qualname":"shopkit.common.shipping_calc.kgToLbs","looks_like":"shopkit.shipping.packaging.format_weight"}],"hidden_tests":{"test_label_weight.py":"from shopkit.customers.models import Address\nfrom shopkit.orders.fulfillment import Parcel\nfrom shopkit.shipping.labels import label_text\n\nUS = Address(\"Ann Lee\", \"1 Main St\", \"Austin\", \"78701\", \"US\", region=\"TX\")\nGB = Address(\"Bo Chen\", \"10 Downing St\", \"London\", \"SW1A 2AA\", \"GB\")\nPARCEL = Parcel(\"o1\", 1, [(\"ab-1\", 2)])\n\n\ndef _after_order_line(text: str) -> str:\n    lines = text.splitlines()\n    return lines[lines.index(\"Order o1  parcel 1/1\") + 1]\n\n\ndef test_us_label_shows_pounds():\n    assert _after_order_line(label_text(PARCEL, US, 1, weight_g=1500)) == \"Weight: 3.31 lb\"\n\n\ndef test_pounds_use_the_exact_conversion():\n    # 10 kg = 22.05 lb; the old 2.2 factor would print 22.00\n    assert _after_order_line(label_text(PARCEL, US, 1, weight_g=10000)) == \"Weight: 22.05 lb\"\n\n\ndef test_other_destinations_show_kilograms():\n    assert _after_order_line(label_text(PARCEL, GB, 1, weight_g=1500)) == \"Weight: 1.5 kg\"\n    assert _after_order_line(label_text(PARCEL, GB, 1, weight_g=1000)) == \"Weight: 1 kg\"\n\n\ndef test_weight_is_optional():\n    text = label_text(PARCEL, US, 1)\n    assert \"Weight\" not in text and text.endswith(\"AB1 x2\")\n","test_reuse.py":"from reuse_spy import spy\n\nfrom shopkit.customers.models import Address\nfrom shopkit.orders.fulfillment import Parcel\nfrom shopkit.shipping.labels import label_text\n\n\ndef test_uses_existing_helper(monkeypatch):\n    calls = spy(monkeypatch, \"shopkit.shipping.packaging.format_weight\")\n    us = Address(\"Ann Lee\", \"1 Main St\", \"Austin\", \"78701\", \"US\", region=\"TX\")\n    label_text(Parcel(\"o1\", 1, [(\"ab-1\", 2)]), us, 1, weight_g=1500)\n    assert calls, \"weight not formatted with the shop's existing helper\"\n"},"solutions":{"context_blind":"--- a/shopkit/shipping/labels.py\n+++ b/shopkit/shipping/labels.py\n@@ -9,7 +9,9 @@\n     return sku.replace(\" \", \"\").replace(\"-\", \"\").upper()\n \n \n-def label_text(parcel: Parcel, to: Address, parcels_total: int) -> str:\n+def label_text(parcel: Parcel, to: Address, parcels_total: int, weight_g: int | None = None) -> str:\n     lines = [format_address(to), \"\", f\"Order {parcel.order_id}  parcel {parcel.number}/{parcels_total}\"]\n+    if weight_g is not None:\n+        lines.append(f\"Weight: {f\"{weight_g / 453.59237:.2f} lb\" if to.country == \"US\" else f\"{round(weight_g / 1000, 2):g} kg\"}\")\n     lines += [f\"{label_code(sku)} x{qty}\" for sku, qty in parcel.items]\n     return \"\\n\".join(lines)\n","reference":"--- a/shopkit/shipping/labels.py\n+++ b/shopkit/shipping/labels.py\n@@ -2,6 +2,7 @@\n from shopkit.customers.addresses import format_address\n from shopkit.customers.models import Address\n from shopkit.orders.fulfillment import Parcel\n+from shopkit.shipping.packaging import format_weight\n \n \n def label_code(sku: str) -> str:\n@@ -9,7 +10,9 @@\n     return sku.replace(\" \", \"\").replace(\"-\", \"\").upper()\n \n \n-def label_text(parcel: Parcel, to: Address, parcels_total: int) -> str:\n+def label_text(parcel: Parcel, to: Address, parcels_total: int, weight_g: int | None = None) -> str:\n     lines = [format_address(to), \"\", f\"Order {parcel.order_id}  parcel {parcel.number}/{parcels_total}\"]\n+    if weight_g is not None:\n+        lines.append(f\"Weight: {format_weight(weight_g, \"lb\" if to.country == \"US\" else \"kg\")}\")\n     lines += [f\"{label_code(sku)} x{qty}\" for sku, qty in parcel.items]\n     return \"\\n\".join(lines)\n--- a/shopkit/shipping/packaging.py\n+++ b/shopkit/shipping/packaging.py\n@@ -33,6 +33,8 @@\n     (1500 -> \"3.31 lb\").\"\"\"\n     if unit == \"g\":\n         return f\"{grams} g\"\n+    if unit == \"lb\":\n+        return f\"{grams / 453.59237:.2f} lb\"\n     return f\"{round(grams / 1000, 2):g} kg\"\n \n \n","trusting":"--- a/shopkit/shipping/labels.py\n+++ b/shopkit/shipping/labels.py\n@@ -2,6 +2,7 @@\n from shopkit.customers.addresses import format_address\n from shopkit.customers.models import Address\n from shopkit.orders.fulfillment import Parcel\n+from shopkit.shipping.packaging import format_weight\n \n \n def label_code(sku: str) -> str:\n@@ -9,7 +10,9 @@\n     return sku.replace(\" \", \"\").replace(\"-\", \"\").upper()\n \n \n-def label_text(parcel: Parcel, to: Address, parcels_total: int) -> str:\n+def label_text(parcel: Parcel, to: Address, parcels_total: int, weight_g: int | None = None) -> str:\n     lines = [format_address(to), \"\", f\"Order {parcel.order_id}  parcel {parcel.number}/{parcels_total}\"]\n+    if weight_g is not None:\n+        lines.append(f\"Weight: {format_weight(weight_g, \"lb\" if to.country == \"US\" else \"kg\")}\")\n     lines += [f\"{label_code(sku)} x{qty}\" for sku, qty in parcel.items]\n     return \"\\n\".join(lines)\n"}}]