File size: 8,591 Bytes
aa09365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Site business schema, migration and deterministic seed for the apple clone.

Opened only through the generated integration seam
(:mod:`backend.site_backend_integration`), which binds every connection to
``site_id = "apple"``. Accounts, verification mail and password recovery are
NOT implemented here: they belong to the vendored ``LocalAuthStore`` runtime.
This module owns only the catalogue, bag, saved items and orders.
"""

from __future__ import annotations

import json
import sqlite3
from pathlib import Path

SEED_PATH = Path(__file__).resolve().parents[1] / "data" / "seed_products.json"

SCHEMA = """
CREATE TABLE IF NOT EXISTS category (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    parent TEXT NOT NULL,
    per_page INTEGER NOT NULL,
    position INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS product (
    sku TEXT PRIMARY KEY,
    slug TEXT NOT NULL,
    name TEXT NOT NULL,
    price_cents INTEGER NOT NULL,
    image TEXT NOT NULL,
    description TEXT NOT NULL,
    brand TEXT NOT NULL,
    accessory_type TEXT NOT NULL,
    color TEXT,
    material TEXT,
    availability TEXT NOT NULL DEFAULT 'InStock',
    only_at_apple INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS product_category (
    sku TEXT NOT NULL REFERENCES product(sku),
    category_id TEXT NOT NULL REFERENCES category(id),
    listing_page INTEGER NOT NULL,
    listing_rank INTEGER NOT NULL,
    PRIMARY KEY (sku, category_id)
);
CREATE TABLE IF NOT EXISTS product_compatibility (
    sku TEXT NOT NULL REFERENCES product(sku),
    model TEXT NOT NULL,
    PRIMARY KEY (sku, model)
);
CREATE TABLE IF NOT EXISTS bag (
    id TEXT PRIMARY KEY,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    subject_id TEXT
);
CREATE TABLE IF NOT EXISTS bag_item (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    bag_id TEXT NOT NULL REFERENCES bag(id),
    sku TEXT NOT NULL REFERENCES product(sku),
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    added_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE (bag_id, sku)
);
CREATE TABLE IF NOT EXISTS saved_item (
    subject_id TEXT NOT NULL,
    sku TEXT NOT NULL REFERENCES product(sku),
    saved_at TEXT NOT NULL DEFAULT (datetime('now')),
    PRIMARY KEY (subject_id, sku)
);
CREATE TABLE IF NOT EXISTS customer_order (
    id TEXT PRIMARY KEY,
    subject_id TEXT,
    email TEXT NOT NULL,
    placed_at TEXT NOT NULL DEFAULT (datetime('now')),
    status TEXT NOT NULL,
    ship_name TEXT NOT NULL,
    ship_line1 TEXT NOT NULL,
    ship_city TEXT NOT NULL,
    ship_state TEXT NOT NULL,
    ship_postal TEXT NOT NULL,
    delivery_method TEXT NOT NULL,
    payment_scenario TEXT NOT NULL,
    payment_outcome TEXT NOT NULL,
    payment_fingerprint TEXT NOT NULL,
    subtotal_cents INTEGER NOT NULL,
    shipping_cents INTEGER NOT NULL,
    tax_cents INTEGER NOT NULL,
    total_cents INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS order_item (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id TEXT NOT NULL REFERENCES customer_order(id),
    sku TEXT NOT NULL,
    name TEXT NOT NULL,
    image TEXT NOT NULL,
    unit_price_cents INTEGER NOT NULL,
    quantity INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS payment_ledger (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id TEXT,
    idempotency_key TEXT NOT NULL UNIQUE,
    owner TEXT NOT NULL,
    amount_cents INTEGER NOT NULL,
    currency TEXT NOT NULL,
    fingerprint TEXT NOT NULL,
    scenario_id TEXT NOT NULL,
    outcome TEXT NOT NULL,
    recorded_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS product_category_page
    ON product_category(category_id, listing_page, listing_rank);
CREATE INDEX IF NOT EXISTS order_by_subject
    ON customer_order(subject_id, placed_at DESC);
CREATE INDEX IF NOT EXISTS order_by_email ON customer_order(email);
"""


def migrate(connection: sqlite3.Connection) -> None:
    """Create the site business schema. Safe to run repeatedly.

    Statements run individually: ``executescript`` would commit the transaction
    the site backend opened around the migration.
    """

    for statement in SCHEMA.split(";"):
        if statement.strip():
            connection.execute(statement)


def seed(connection: sqlite3.Connection) -> None:
    """Load the catalogue captured from the source listing pages."""

    payload = json.loads(SEED_PATH.read_text(encoding="utf-8"))

    for position, category in enumerate(payload["categories"]):
        connection.execute(
            "INSERT OR REPLACE INTO category (id, name, parent, per_page, position)"
            " VALUES (?, ?, ?, ?, ?)",
            (
                category["id"],
                category["name"],
                category["parent"],
                category["per_page"],
                position,
            ),
        )

    for product in payload["products"]:
        connection.execute(
            "INSERT OR REPLACE INTO product (sku, slug, name, price_cents, image,"
            " description, brand, accessory_type, color, material, availability,"
            " only_at_apple) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
            (
                product["sku"],
                product["slug"],
                product["name"],
                round(float(product["price"]) * 100),
                product["image"],
                product["description"],
                product["brand"],
                product["accessory_type"],
                product["color"],
                product["material"],
                product["availability"],
                1 if product["only_at_apple"] else 0,
            ),
        )
        connection.execute(
            "DELETE FROM product_compatibility WHERE sku = ?", (product["sku"],)
        )
        for model in product["compatibility"]:
            connection.execute(
                "INSERT OR IGNORE INTO product_compatibility (sku, model)"
                " VALUES (?, ?)",
                (product["sku"], model),
            )

    _seed_demo_order(connection, payload)

    rank: dict[tuple[str, int], int] = {}
    for membership in payload["memberships"]:
        key = (membership["category"], membership["page"])
        position = rank.get(key, 0)
        rank[key] = position + 1
        connection.execute(
            "INSERT OR REPLACE INTO product_category (sku, category_id,"
            " listing_page, listing_rank) VALUES (?, ?, ?, ?)",
            (
                membership["sku"],
                membership["category"],
                membership["page"],
                position,
            ),
        )


DEMO_ORDER_ID = "W1000000001"
DEMO_ORDER_EMAIL = "demo.shopper@example.test"


def _seed_demo_order(connection: sqlite3.Connection, payload: dict) -> None:
    """One deterministic guest order, so the confirmation and lookup routes
    have a populated state without anyone having to check out first."""

    existing = connection.execute(
        "SELECT 1 FROM customer_order WHERE id = ?", (DEMO_ORDER_ID,)
    ).fetchone()
    if existing is not None:
        return

    picks = payload["products"][:2]
    if not picks:
        return
    items = [(product, 1) for product in picks]
    subtotal = sum(round(float(p["price"]) * 100) * q for p, q in items)
    tax = round(subtotal * 0.0725)
    connection.execute(
        "INSERT INTO customer_order (id, subject_id, email, placed_at, status,"
        " ship_name, ship_line1, ship_city, ship_state, ship_postal,"
        " delivery_method, payment_scenario, payment_outcome,"
        " payment_fingerprint, subtotal_cents, shipping_cents, tax_cents,"
        " total_cents) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        (
            DEMO_ORDER_ID,
            None,
            DEMO_ORDER_EMAIL,
            "2026-08-29 10:00:00",
            "Delivered",
            "Demo Shopper",
            "1 Infinite Loop",
            "Cupertino",
            "CA",
            "95014",
            "standard",
            "sandbox-approved",
            "approved",
            "seeded-demo-order",
            subtotal,
            0,
            tax,
            subtotal + tax,
        ),
    )
    for product, quantity in items:
        connection.execute(
            "INSERT INTO order_item (order_id, sku, name, image,"
            " unit_price_cents, quantity) VALUES (?,?,?,?,?,?)",
            (
                DEMO_ORDER_ID,
                product["sku"],
                product["name"],
                product["image"],
                round(float(product["price"]) * 100),
                quantity,
            ),
        )