File size: 5,784 Bytes
a976fe6 | 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 | """Deterministic local store state: carts, orders and the sandbox payment ledger.
State lives in the site-bound SQLite database opened by the generated backend
integration seam; no state is kept in process memory.
"""
from __future__ import annotations
import json
import sqlite3
import time
import uuid
SCHEMA = """
CREATE TABLE IF NOT EXISTS clone_cart_item (
session_token TEXT NOT NULL,
variant_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
added_at REAL NOT NULL,
PRIMARY KEY (session_token, variant_id)
);
CREATE TABLE IF NOT EXISTS clone_order (
id TEXT PRIMARY KEY,
number TEXT NOT NULL UNIQUE,
account_email TEXT,
session_token TEXT,
placed_at REAL NOT NULL,
status TEXT NOT NULL,
subtotal REAL NOT NULL,
lines_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS clone_payment_ledger (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL REFERENCES clone_order(id),
scenario TEXT NOT NULL,
outcome TEXT NOT NULL,
amount REAL NOT NULL,
recorded_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS clone_outbox (
id TEXT PRIMARY KEY,
recipient TEXT NOT NULL,
subject TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL,
created_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS clone_newsletter (
email TEXT PRIMARY KEY,
created_at REAL NOT NULL
);
"""
def ensure_schema(conn: sqlite3.Connection) -> None:
conn.executescript(SCHEMA)
conn.commit()
# ---------------------------------------------------------------- cart
def cart_rows(conn, session_token: str):
return conn.execute(
"SELECT variant_id, quantity FROM clone_cart_item WHERE session_token = ? ORDER BY added_at",
(session_token,),
).fetchall()
def cart_add(conn, session_token: str, variant_id: int, quantity: int = 1) -> None:
conn.execute(
"INSERT INTO clone_cart_item (session_token, variant_id, quantity, added_at) VALUES (?,?,?,?)"
" ON CONFLICT(session_token, variant_id) DO UPDATE SET quantity = quantity + excluded.quantity",
(session_token, variant_id, quantity, time.time()),
)
conn.commit()
def cart_set(conn, session_token: str, variant_id: int, quantity: int) -> None:
if quantity <= 0:
cart_remove(conn, session_token, variant_id)
return
conn.execute(
"UPDATE clone_cart_item SET quantity = ? WHERE session_token = ? AND variant_id = ?",
(quantity, session_token, variant_id),
)
conn.commit()
def cart_remove(conn, session_token: str, variant_id: int) -> None:
conn.execute(
"DELETE FROM clone_cart_item WHERE session_token = ? AND variant_id = ?",
(session_token, variant_id),
)
conn.commit()
def cart_clear(conn, session_token: str) -> None:
conn.execute("DELETE FROM clone_cart_item WHERE session_token = ?", (session_token,))
conn.commit()
def cart_merge(conn, from_token: str, to_token: str) -> None:
for variant_id, quantity in cart_rows(conn, from_token):
cart_add(conn, to_token, variant_id, quantity)
cart_clear(conn, from_token)
# ---------------------------------------------------------------- orders
def create_order(conn, *, session_token, account_email, subtotal, lines, scenario="sandbox-approved"):
order_id = uuid.uuid4().hex
seq = conn.execute("SELECT COUNT(*) FROM clone_order").fetchone()[0] + 1
number = f"#BK{10000 + seq}"
outcome = {"sandbox-approved": "approved", "sandbox-declined": "declined",
"sandbox-retry": "retryable"}.get(scenario, "approved")
status = "Paid" if outcome == "approved" else outcome.capitalize()
now = time.time()
conn.execute(
"INSERT INTO clone_order (id, number, account_email, session_token, placed_at, status, subtotal, lines_json)"
" VALUES (?,?,?,?,?,?,?,?)",
(order_id, number, account_email, session_token, now, status, subtotal, json.dumps(lines)),
)
conn.execute(
"INSERT INTO clone_payment_ledger (id, order_id, scenario, outcome, amount, recorded_at) VALUES (?,?,?,?,?,?)",
(uuid.uuid4().hex, order_id, scenario, outcome, subtotal, now),
)
conn.commit()
return {"id": order_id, "number": number, "status": status, "outcome": outcome}
def orders_for(conn, account_email: str):
rows = conn.execute(
"SELECT number, placed_at, status, subtotal, lines_json FROM clone_order"
" WHERE account_email = ? ORDER BY placed_at DESC",
(account_email,),
).fetchall()
out = []
for number, placed_at, status, subtotal, lines_json in rows:
lines = json.loads(lines_json)
out.append({"number": number, "placed_at": time.strftime("%b %d, %Y", time.localtime(placed_at)),
"status": status, "total": subtotal,
"item_count": sum(line["quantity"] for line in lines)})
return out
# ---------------------------------------------------------------- outbox
def outbox_add(conn, recipient: str, subject: str, body: str) -> None:
conn.execute(
"INSERT INTO clone_outbox (id, recipient, subject, body, status, created_at) VALUES (?,?,?,?,?,?)",
(uuid.uuid4().hex, recipient, subject, body, "LOCAL_ONLY", time.time()),
)
conn.commit()
def outbox_all(conn):
return [
{"to": r[0], "subject": r[1], "body": r[2], "status": r[3]}
for r in conn.execute(
"SELECT recipient, subject, body, status FROM clone_outbox ORDER BY created_at DESC LIMIT 100"
).fetchall()
]
def newsletter_add(conn, email: str) -> None:
conn.execute("INSERT OR IGNORE INTO clone_newsletter (email, created_at) VALUES (?,?)", (email, time.time()))
conn.commit()
|