File size: 13,275 Bytes
f123267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
"""Catalog fixture access and cart/favorite persistence for the Article clone.

The catalog is a read-only fixture derived from source-observed evidence.
Mutable state (cart, favorites, orders) lives in this site's bound SQLite
database, opened only through the generated backend integration seam.
"""

from __future__ import annotations

import json
import pathlib
import time
from typing import Any

from backend.site_backend_integration import open_site_services

DATA = pathlib.Path(__file__).resolve().parent / "data"
_catalog: dict[str, Any] | None = None
_services: tuple[Any, Any] | None = None


def catalog() -> dict[str, Any]:
    global _catalog
    if _catalog is None:
        _catalog = json.loads((DATA / "catalog.json").read_text(encoding="utf-8"))
        _catalog["by_id"] = {p["product_id"]: p for p in _catalog["products"]}
        _catalog["by_slug"] = {p["slug"]: p for p in _catalog["products"]}
    return _catalog


def services() -> tuple[Any, Any]:
    """Open the bound backend once and make the synthetic demo account usable.

    Seeding is idempotent, so a reset database always comes back with the same
    deterministic reviewer credentials.
    """

    global _services
    if _services is None:
        _services = open_site_services()
        from site_schema import SYNTHETIC_ACCOUNTS

        for account in SYNTHETIC_ACCOUNTS:
            try:
                _services[1].seed_account(**account)
            except Exception:  # a pre-seeded database is not an error
                pass
    return _services


def backend():
    return services()[0]


def auth():
    return services()[1]


def connect():
    return auth().connect()


def product(product_id: str) -> dict[str, Any] | None:
    return catalog()["by_id"].get(product_id)


def collection(collection_id: str) -> list[dict[str, Any]]:
    ids = catalog()["collections"].get(collection_id, [])
    return [catalog()["by_id"][i] for i in ids if i in catalog()["by_id"]]


_subcategories: dict[str, Any] | None = None


def subcategories(browse_id: str) -> list[dict[str, Any]]:
    """Source-observed subcategory tiles, narrowed to products this clone holds."""

    global _subcategories
    if _subcategories is None:
        path = DATA / "subcategories.json"
        _subcategories = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    entries = []
    for entry in _subcategories.get(browse_id, []):
        local = [pid for pid in entry["member_product_ids"] if pid in catalog()["by_id"]]
        if not local:
            continue  # never render a tile that would open an empty result
        entries.append({**entry, "local_product_ids": local})
    return entries


_content: dict[str, Any] | None = None


def _content_pages() -> dict[str, Any]:
    global _content
    if _content is None:
        path = DATA / "content.json"
        _content = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    return _content


def content_routes() -> list[str]:
    return sorted(_content_pages())


def content_page(route: str) -> dict[str, Any] | None:
    return _content_pages().get(route)


def cart_recommendations(limit: int = 6) -> list[dict[str, Any]]:
    """The order the source's empty cart renders under Browse popular products."""

    path = DATA / "cart-recommendations.json"
    ids = json.loads(path.read_text(encoding="utf-8"))["product_ids"] if path.exists() else []
    picked = [product(i) for i in ids]
    picked = [p for p in picked if p]
    if len(picked) < limit:
        for extra in collection("living-furniture"):
            if extra not in picked:
                picked.append(extra)
            if len(picked) >= limit:
                break
    return picked[:limit]


_menu_routes: dict[str, Any] | None = None


def menu_routes() -> dict[str, Any]:
    global _menu_routes
    if _menu_routes is None:
        path = DATA / "menu-routes.json"
        _menu_routes = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    return _menu_routes


def menu_route(path: str) -> dict[str, Any] | None:
    """A mega-menu destination with its source-observed membership narrowed to
    the products this clone holds."""

    entry = menu_routes().get(path)
    if entry is None:
        return None
    products = [catalog()["by_id"][i] for i in entry["product_ids"]
                if i in catalog()["by_id"]]
    return {**entry, "products": products}


_megamenu: dict[str, Any] | None = None


def mega_menu(label: str) -> dict[str, Any] | None:
    """The captured dropdown for one nav item, narrowed to destinations this
    clone serves so a menu control never opens a dead route."""

    global _megamenu
    if _megamenu is None:
        path = DATA / "megamenu.json"
        _megamenu = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    return _megamenu.get(label)


_facets: dict[str, Any] | None = None


def facet_groups(browse_id: str) -> list[dict[str, Any]]:
    """Source-observed filter groups for a collection, with each option's count
    recomputed against the products this clone actually holds."""

    global _facets
    if _facets is None:
        path = DATA / "facets.json"
        _facets = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    entry = _facets.get(browse_id)
    return entry["groups"] if entry else []


def facet_local_count(products: list[dict[str, Any]], label: str) -> int:
    """How many of these products the option's label matches by name."""

    needle = label.lower()
    return sum(1 for p in products if needle in p["name"].lower())


_room_tiles: list[dict[str, Any]] | None = None

# Display titles as the source renders them beneath each All Rooms tile; the CMS
# alt text ("Shop By Bedroom") differs from the visible label.
ROOM_TITLES = {
    "/browse/224/living-furniture": "Living Room",
    "/browse/222/dining-furniture": "Dining Room & Kitchen",
    "/browse/225/bedroom-furniture": "Bedroom",
    "/browse/223/home-office-furniture": "Home Office",
    "/browse/58/outdoor": "Outdoor",
    "/browse/345/entryway-furniture": "Entryway",
}


def room_tiles() -> list[dict[str, Any]]:
    """Only tiles whose destination this clone actually serves are rendered."""

    global _room_tiles
    if _room_tiles is None:
        path = DATA / "room-tiles.json"
        raw = json.loads(path.read_text(encoding="utf-8")) if path.exists() else []
        _room_tiles = [
            {**t, "title": ROOM_TITLES[t["href"]]}
            for t in raw if t.get("href") in ROOM_TITLES and t.get("image")
        ]
    return _room_tiles


def subcategory_by_tc(browse_id: str, tc: str) -> dict[str, Any] | None:
    for entry in subcategories(browse_id):
        if entry["tc"] == tc:
            return entry
    return None


def variants_for(prod: dict[str, Any]) -> list[dict[str, Any]]:
    """Colour siblings this clone actually serves; a dropped product must never
    remain linked from a swatch."""

    return [v for v in (prod.get("variants") or []) if v["product_id"] in catalog()["by_id"]]


def all_products() -> list[dict[str, Any]]:
    return catalog()["products"]


COLLECTION_ROUTES = {
    "living-furniture": ("/browse/224/living-furniture", "Living Room"),
    "dining-furniture": ("/browse/222/dining-furniture", "Dining & Kitchen"),
    "bedroom-furniture": ("/browse/225/bedroom-furniture", "All Bedroom"),
    "outdoor": ("/browse/58/outdoor", "Outdoor"),
    "decor": ("/browse/48/decor", "Accessories & Decor"),
    "home-office": ("/browse/223/home-office-furniture", "Home Office"),
    "entryway": ("/browse/345/entryway-furniture", "Entryway"),
    "new-arrivals": ("/browse/100/new", "New Arrivals"),
    "all-rooms": ("/c/all-rooms", "All Rooms"),
}


def primary_collection(product_id: str) -> tuple[str, str]:
    """The collection whose breadcrumb the source shows for this product."""

    for name in COLLECTION_ROUTES:
        if product_id in catalog()["collections"].get(name, []):
            return name, COLLECTION_ROUTES[name][1]
    return "all-rooms", COLLECTION_ROUTES["all-rooms"][1]


def collection_href(name: str) -> str:
    return COLLECTION_ROUTES.get(name, COLLECTION_ROUTES["all-rooms"])[0]


def search(query: str) -> list[dict[str, Any]]:
    q = query.strip().lower()
    if not q:
        return []
    return [p for p in all_products() if q in p["name"].lower()]


# --- mutable state -------------------------------------------------------

def owner_key(session_token: str, session: dict[str, Any]) -> str:
    """Scope cart state to the account when signed in, else to the session."""

    account = session.get("account") if session else None
    if account:
        return f"account:{account['account_id']}"
    return f"session:{auth().session_owner_digest(session_token)}"


def cart_items(owner: str) -> list[dict[str, Any]]:
    with connect() as connection:
        rows = connection.execute(
            "SELECT product_id, quantity FROM article_cart_items"
            " WHERE owner_key=? ORDER BY cart_item_id",
            (owner,),
        ).fetchall()
    items = []
    for row in rows:
        prod = product(str(row["product_id"]))
        if prod is None:
            continue
        items.append({
            "product": prod,
            "quantity": int(row["quantity"]),
            "line_cents": prod["price_cents"] * int(row["quantity"]),
        })
    return items


def cart_count(owner: str) -> int:
    with connect() as connection:
        row = connection.execute(
            "SELECT COALESCE(SUM(quantity), 0) AS n FROM article_cart_items WHERE owner_key=?",
            (owner,),
        ).fetchone()
    return int(row["n"]) if row else 0


def cart_subtotal(owner: str) -> int:
    return sum(i["line_cents"] for i in cart_items(owner))


# Deterministic local checkout arithmetic. The source's USD shipping and tax
# figures were not captured (the checkout capture ran on a CAD-region egress),
# so these are this clone's own fixed sandbox rules, not source-observed values.
SHIPPING_FLAT_CENTS = 4900
FREE_SHIPPING_THRESHOLD_CENTS = 99900
TAX_RATE_BASIS_POINTS = 875  # 8.75%


def shipping_cents(subtotal: int) -> int:
    if subtotal == 0 or subtotal >= FREE_SHIPPING_THRESHOLD_CENTS:
        return 0
    return SHIPPING_FLAT_CENTS


def tax_cents(subtotal: int) -> int:
    return (subtotal * TAX_RATE_BASIS_POINTS + 5000) // 10000


def add_to_cart(owner: str, product_id: str, quantity: int = 1) -> None:
    if product(product_id) is None:
        raise KeyError(product_id)
    now = int(time.time())
    with connect() as connection:
        connection.execute(
            "INSERT INTO article_cart_items(owner_key, product_id, quantity, created_at)"
            " VALUES (?,?,?,?)"
            " ON CONFLICT(owner_key, product_id)"
            " DO UPDATE SET quantity = quantity + excluded.quantity",
            (owner, product_id, quantity, now),
        )
        connection.commit()


def set_quantity(owner: str, product_id: str, quantity: int) -> None:
    with connect() as connection:
        if quantity <= 0:
            connection.execute(
                "DELETE FROM article_cart_items WHERE owner_key=? AND product_id=?",
                (owner, product_id),
            )
        else:
            connection.execute(
                "UPDATE article_cart_items SET quantity=? WHERE owner_key=? AND product_id=?",
                (quantity, owner, product_id),
            )
        connection.commit()


def remove_from_cart(owner: str, product_id: str) -> None:
    set_quantity(owner, product_id, 0)


def favorites(owner: str) -> list[dict[str, Any]]:
    with connect() as connection:
        rows = connection.execute(
            "SELECT product_id FROM article_favorites WHERE owner_key=? ORDER BY favorite_id",
            (owner,),
        ).fetchall()
    return [p for p in (product(str(r["product_id"])) for r in rows) if p]


def toggle_favorite(owner: str, product_id: str) -> bool:
    """Return True when the product ends up favorited."""

    now = int(time.time())
    with connect() as connection:
        existing = connection.execute(
            "SELECT 1 FROM article_favorites WHERE owner_key=? AND product_id=?",
            (owner, product_id),
        ).fetchone()
        if existing:
            connection.execute(
                "DELETE FROM article_favorites WHERE owner_key=? AND product_id=?",
                (owner, product_id),
            )
            connection.commit()
            return False
        connection.execute(
            "INSERT INTO article_favorites(owner_key, product_id, created_at) VALUES (?,?,?)",
            (owner, product_id, now),
        )
        connection.commit()
        return True


def migrate_owner(old_owner: str, new_owner: str) -> None:
    """Carry an anonymous cart across a sign-in session rotation."""

    if old_owner == new_owner:
        return
    with connect() as connection:
        connection.execute(
            "UPDATE OR IGNORE article_cart_items SET owner_key=? WHERE owner_key=?",
            (new_owner, old_owner),
        )
        connection.execute("DELETE FROM article_cart_items WHERE owner_key=?", (old_owner,))
        connection.commit()