File size: 22,300 Bytes
3ba647a | 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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 | """Server-side catalogue, bag, saved items, orders and payment for the clone.
Every read and write goes through the site-bound SQLite connection opened by
:mod:`backend.site_backend_integration`. Nothing here talks to the source site,
and no card data is ever accepted or stored: the payment surface takes an
opaque sandbox scenario id and a fingerprint only.
"""
from __future__ import annotations
import hashlib
import secrets
import sqlite3
from dataclasses import dataclass, field
PER_PAGE = 30
TAX_RATE = 0.0725
SHIPPING_CENTS = 0
SORTS = {
"featured": ("pc.listing_page, pc.listing_rank", "Featured"),
"price-low": ("p.price_cents ASC, p.name", "Price: Low to High"),
"price-high": ("p.price_cents DESC, p.name", "Price: High to Low"),
"name": ("p.name ASC", "Name"),
}
FACETS = [
("type", "accessory_type", "Accessory Type"),
("brand", "brand", "Brand"),
("color", "color", "Color"),
("material", "material", "Material"),
]
DELIVERY_METHODS = {
"standard": ("Free Standard Delivery", 0),
"express": ("Express Delivery", 900),
"pickup": ("Pick up at an Apple Store", 0),
}
def money(cents: int) -> str:
return f"${cents / 100:,.2f}"
@dataclass
class Product:
sku: str
slug: str
name: str
price_cents: int
image: str
description: str
brand: str
accessory_type: str
color: str | None
material: str | None
availability: str
only_at_apple: bool
compatibility: list[str] = field(default_factory=list)
categories: list[dict] = field(default_factory=list)
@property
def href(self) -> str:
return f"/shop/product/{self.sku}/a/{self.slug}"
@property
def price_display(self) -> str:
return money(self.price_cents)
@property
def monthly_display(self) -> str:
return money(round(self.price_cents / 12))
@property
def in_stock(self) -> bool:
return self.availability == "InStock"
def _product(row: sqlite3.Row) -> Product:
return Product(
sku=row["sku"],
slug=row["slug"],
name=row["name"],
price_cents=row["price_cents"],
image=row["image"],
description=row["description"],
brand=row["brand"],
accessory_type=row["accessory_type"],
color=row["color"],
material=row["material"],
availability=row["availability"],
only_at_apple=bool(row["only_at_apple"]),
)
class Catalog:
"""Read model over the seeded catalogue."""
def __init__(self, connect) -> None:
self._connect = connect
def _query(self, sql: str, params: tuple = ()) -> list[sqlite3.Row]:
with self._connect() as connection:
connection.row_factory = sqlite3.Row
return connection.execute(sql, params).fetchall()
# -- categories -------------------------------------------------------
def categories(self) -> list[dict]:
return [
dict(row)
for row in self._query(
"SELECT c.id, c.name, c.parent, c.per_page,"
" (SELECT COUNT(*) FROM product_category pc"
" WHERE pc.category_id = c.id) AS total"
" FROM category c ORDER BY c.position"
)
]
def category(self, category_id: str) -> dict | None:
rows = self._query(
"SELECT c.id, c.name, c.parent, c.per_page,"
" (SELECT COUNT(*) FROM product_category pc"
" WHERE pc.category_id = c.id) AS total"
" FROM category c WHERE c.id = ?",
(category_id,),
)
return dict(rows[0]) if rows else None
def facet_values(self, category_id: str, column: str) -> list[str]:
rows = self._query(
f"SELECT DISTINCT p.{column} AS value FROM product p"
" JOIN product_category pc ON pc.sku = p.sku"
f" WHERE pc.category_id = ? AND p.{column} IS NOT NULL"
f" AND p.{column} != '' ORDER BY value",
(category_id,),
)
return [row["value"] for row in rows]
def list_products(
self,
category_id: str,
*,
page: int = 1,
sort: str = "featured",
filters: dict[str, str] | None = None,
) -> tuple[list[Product], int]:
clauses = ["pc.category_id = ?"]
params: list[object] = [category_id]
for key, column, _label in FACETS:
value = (filters or {}).get(key)
if value:
clauses.append(f"p.{column} = ?")
params.append(value)
where = " AND ".join(clauses)
order = SORTS.get(sort, SORTS["featured"])[0]
total = self._query(
"SELECT COUNT(*) AS n FROM product p"
f" JOIN product_category pc ON pc.sku = p.sku WHERE {where}",
tuple(params),
)[0]["n"]
rows = self._query(
"SELECT p.* FROM product p JOIN product_category pc ON pc.sku = p.sku"
f" WHERE {where} ORDER BY {order} LIMIT ? OFFSET ?",
tuple(params) + (PER_PAGE, (page - 1) * PER_PAGE),
)
return [_product(row) for row in rows], total
# -- products ---------------------------------------------------------
def product(self, sku: str) -> Product | None:
rows = self._query("SELECT * FROM product WHERE sku = ?", (sku,))
if not rows:
return None
product = _product(rows[0])
product.compatibility = [
row["model"]
for row in self._query(
"SELECT model FROM product_compatibility WHERE sku = ? ORDER BY model",
(sku,),
)
]
product.categories = [
dict(row)
for row in self._query(
"SELECT c.id, c.name FROM product_category pc"
" JOIN category c ON c.id = pc.category_id"
" WHERE pc.sku = ? ORDER BY c.position",
(sku,),
)
]
return product
def variants(self, product: Product) -> dict[str, list[dict]]:
"""Siblings that share a product family, split into size and colour.
The source names a variant ``<model> <family> – <Colour>``; the same
decomposition is applied locally.
"""
family = product.name.split(" – ")[0]
base = family
models = (
"iPhone 17 Pro Max",
"iPhone 17 Pro",
"iPhone 17e",
"iPhone 17",
"iPhone Air",
"iPhone 16 Pro Max",
"iPhone 16 Pro",
"iPhone 16",
"iPad Pro 13-inch",
"iPad Pro 11-inch",
"iPad Air 13-inch",
"iPad Air 11-inch",
)
for model in models:
if family.startswith(model + " "):
base = family[len(model) + 1 :]
break
rows = self._query(
"SELECT * FROM product WHERE name LIKE ? ORDER BY name",
(f"%{base}%",),
)
sizes: list[dict] = []
colors: list[dict] = []
seen: set[str] = set()
for row in rows:
sibling = _product(row)
sibling_family = sibling.name.split(" – ")[0]
if not sibling_family.endswith(base):
continue
size = sibling_family[: len(sibling_family) - len(base)].strip()
if size and size not in seen:
seen.add(size)
sizes.append(
{
"label": size,
"href": sibling.href,
"current": sibling_family == family,
}
)
if sibling_family == family and sibling.color:
colors.append(
{
"label": sibling.color,
"href": sibling.href,
"current": sibling.sku == product.sku,
}
)
return {"sizes": sizes if len(sizes) > 1 else [], "colors": colors}
def related(self, product: Product, limit: int = 3) -> list[Product]:
rows = self._query(
"SELECT p.* FROM product p JOIN product_category pc ON pc.sku = p.sku"
" WHERE pc.category_id = (SELECT category_id FROM product_category"
" WHERE sku = ? LIMIT 1)"
" AND p.sku != ? AND p.accessory_type = ?"
" ORDER BY pc.listing_page, pc.listing_rank LIMIT ?",
(product.sku, product.sku, product.accessory_type, limit),
)
return [_product(row) for row in rows]
def search(self, query: str, limit: int = 60) -> list[Product]:
like = f"%{query.strip()}%"
rows = self._query(
"SELECT DISTINCT p.* FROM product p"
" WHERE p.name LIKE ? OR p.brand LIKE ? OR p.accessory_type LIKE ?"
" OR p.description LIKE ?"
" ORDER BY p.name LIMIT ?",
(like, like, like, like, limit),
)
return [_product(row) for row in rows]
def by_skus(self, skus: list[str]) -> list[Product]:
if not skus:
return []
marks = ",".join("?" for _ in skus)
rows = self._query(
f"SELECT * FROM product WHERE sku IN ({marks}) ORDER BY name",
tuple(skus),
)
return [_product(row) for row in rows]
class Bag:
"""Server-authoritative bag. The cookie carries only an opaque bag id."""
def __init__(self, connect) -> None:
self._connect = connect
def create(self) -> str:
bag_id = secrets.token_urlsafe(18)
with self._connect() as connection:
connection.execute("INSERT INTO bag (id) VALUES (?)", (bag_id,))
return bag_id
def exists(self, bag_id: str) -> bool:
with self._connect() as connection:
return (
connection.execute(
"SELECT 1 FROM bag WHERE id = ?", (bag_id,)
).fetchone()
is not None
)
def attach(self, bag_id: str, subject_id: str) -> None:
with self._connect() as connection:
connection.execute(
"UPDATE bag SET subject_id = ? WHERE id = ?", (subject_id, bag_id)
)
def add(self, bag_id: str, sku: str, quantity: int = 1) -> None:
with self._connect() as connection:
if (
connection.execute(
"SELECT 1 FROM product WHERE sku = ?", (sku,)
).fetchone()
is None
):
raise KeyError(sku)
connection.execute(
"INSERT INTO bag_item (bag_id, sku, quantity) VALUES (?, ?, ?)"
" ON CONFLICT(bag_id, sku) DO UPDATE SET"
" quantity = min(99, quantity + excluded.quantity)",
(bag_id, sku, quantity),
)
def set_quantity(self, bag_id: str, sku: str, quantity: int) -> None:
with self._connect() as connection:
if quantity <= 0:
connection.execute(
"DELETE FROM bag_item WHERE bag_id = ? AND sku = ?",
(bag_id, sku),
)
else:
connection.execute(
"UPDATE bag_item SET quantity = ? WHERE bag_id = ? AND sku = ?",
(min(99, quantity), bag_id, sku),
)
def clear(self, bag_id: str) -> None:
with self._connect() as connection:
connection.execute("DELETE FROM bag_item WHERE bag_id = ?", (bag_id,))
def lines(self, bag_id: str) -> list[dict]:
with self._connect() as connection:
connection.row_factory = sqlite3.Row
rows = connection.execute(
"SELECT b.sku, b.quantity, p.name, p.slug, p.image, p.price_cents"
" FROM bag_item b JOIN product p ON p.sku = b.sku"
" WHERE b.bag_id = ? ORDER BY b.id",
(bag_id,),
).fetchall()
lines = []
for row in rows:
total = row["price_cents"] * row["quantity"]
lines.append(
{
"sku": row["sku"],
"name": row["name"],
"image": row["image"],
"quantity": row["quantity"],
"href": f"/shop/product/{row['sku']}/a/{row['slug']}",
"unit_price_cents": row["price_cents"],
"unit_price_display": money(row["price_cents"]),
"line_total_cents": total,
"line_total_display": money(total),
}
)
return lines
def count(self, bag_id: str) -> int:
with self._connect() as connection:
row = connection.execute(
"SELECT COALESCE(SUM(quantity), 0) FROM bag_item WHERE bag_id = ?",
(bag_id,),
).fetchone()
return int(row[0])
@staticmethod
def totals(lines: list[dict], delivery: str = "standard") -> dict:
subtotal = sum(line["line_total_cents"] for line in lines)
shipping = DELIVERY_METHODS.get(delivery, DELIVERY_METHODS["standard"])[1]
tax = round(subtotal * TAX_RATE)
total = subtotal + shipping + tax
return {
"subtotal_cents": subtotal,
"shipping_cents": shipping,
"tax_cents": tax,
"total_cents": total,
"subtotal_display": money(subtotal),
"shipping_display": "FREE" if shipping == 0 else money(shipping),
"tax_display": money(tax),
"total_display": money(total),
}
class SavedItems:
"""Save for later, owned by a signed-in account."""
def __init__(self, connect) -> None:
self._connect = connect
def add(self, subject_id: str, sku: str) -> None:
with self._connect() as connection:
connection.execute(
"INSERT OR IGNORE INTO saved_item (subject_id, sku) VALUES (?, ?)",
(subject_id, sku),
)
def remove(self, subject_id: str, sku: str) -> None:
with self._connect() as connection:
connection.execute(
"DELETE FROM saved_item WHERE subject_id = ? AND sku = ?",
(subject_id, sku),
)
def skus(self, subject_id: str) -> list[str]:
with self._connect() as connection:
rows = connection.execute(
"SELECT sku FROM saved_item WHERE subject_id = ?"
" ORDER BY saved_at DESC",
(subject_id,),
).fetchall()
return [row[0] for row in rows]
def contains(self, subject_id: str, sku: str) -> bool:
with self._connect() as connection:
return (
connection.execute(
"SELECT 1 FROM saved_item WHERE subject_id = ? AND sku = ?",
(subject_id, sku),
).fetchone()
is not None
)
class PaymentDeclined(RuntimeError):
"""The sandbox adapter refused this authorisation."""
def __init__(self, outcome: str, message: str) -> None:
super().__init__(message)
self.outcome = outcome
class Orders:
"""Order placement against the local-sandbox payment adapter.
The adapter never sees a card. It receives an owner, an integer minor-unit
amount, a currency, a canonical fingerprint, an idempotency key and an
opaque scenario id, exactly as the backend mandate requires.
"""
def __init__(self, connect, scenarios: dict[str, str]) -> None:
self._connect = connect
self._scenarios = scenarios
@staticmethod
def fingerprint(lines: list[dict], totals: dict, email: str) -> str:
payload = "|".join(
f"{line['sku']}x{line['quantity']}@{line['unit_price_cents']}"
for line in lines
)
payload += f"|{totals['total_cents']}|{email.strip().lower()}"
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def place(
self,
*,
lines: list[dict],
totals: dict,
email: str,
subject_id: str | None,
shipping: dict,
delivery: str,
scenario_id: str,
idempotency_key: str,
) -> str:
if not lines:
raise ValueError("cannot place an order for an empty bag")
outcome = self._scenarios.get(scenario_id)
if outcome is None:
raise ValueError(f"unknown payment scenario: {scenario_id}")
fingerprint = self.fingerprint(lines, totals, email)
with self._connect() as connection:
connection.row_factory = sqlite3.Row
existing = connection.execute(
"SELECT order_id, outcome FROM payment_ledger"
" WHERE idempotency_key = ?",
(idempotency_key,),
).fetchone()
if existing is not None:
# Replaying the same authorisation must not charge or order twice.
if existing["outcome"] != "approved":
raise PaymentDeclined(
existing["outcome"], "This payment was not approved."
)
return existing["order_id"]
order_id = None
if outcome == "approved":
order_id = "W" + secrets.token_hex(5).upper()
connection.execute(
"INSERT INTO customer_order (id, subject_id, email, 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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
order_id,
subject_id,
email.strip().lower(),
"Processing",
shipping["name"],
shipping["line1"],
shipping["city"],
shipping["state"],
shipping["postal"],
delivery,
scenario_id,
outcome,
fingerprint,
totals["subtotal_cents"],
totals["shipping_cents"],
totals["tax_cents"],
totals["total_cents"],
),
)
for line in lines:
connection.execute(
"INSERT INTO order_item (order_id, sku, name, image,"
" unit_price_cents, quantity) VALUES (?,?,?,?,?,?)",
(
order_id,
line["sku"],
line["name"],
line["image"],
line["unit_price_cents"],
line["quantity"],
),
)
connection.execute(
"INSERT INTO payment_ledger (order_id, idempotency_key, owner,"
" amount_cents, currency, fingerprint, scenario_id, outcome)"
" VALUES (?,?,?,?,?,?,?,?)",
(
order_id,
idempotency_key,
subject_id or email.strip().lower(),
totals["total_cents"],
"USD",
fingerprint,
scenario_id,
outcome,
),
)
if outcome != "approved":
message = (
"Your payment was declined. Try a different payment method."
if outcome == "declined"
else "That payment could not be completed. Please try again."
)
raise PaymentDeclined(outcome, message)
return order_id
def _rows(self, sql: str, params: tuple) -> list[sqlite3.Row]:
with self._connect() as connection:
connection.row_factory = sqlite3.Row
return connection.execute(sql, params).fetchall()
def for_subject(self, subject_id: str) -> list[dict]:
return [
self._decorate(row)
for row in self._rows(
"SELECT * FROM customer_order WHERE subject_id = ?"
" ORDER BY placed_at DESC, rowid DESC",
(subject_id,),
)
]
def get(self, order_id: str, *, subject_id: str | None = None,
email: str | None = None) -> dict | None:
rows = self._rows(
"SELECT * FROM customer_order WHERE id = ?", (order_id.strip().upper(),)
)
if not rows:
return None
order = self._decorate(rows[0])
if subject_id is not None and order["subject_id"] == subject_id:
return order
if email is not None and order["email"] == email.strip().lower():
return order
if subject_id is None and email is None:
return order
return None
def _decorate(self, row: sqlite3.Row) -> dict:
order = dict(row)
order["items"] = [
dict(item, line_total_display=money(item["unit_price_cents"] * item["quantity"]))
for item in (
dict(entry)
for entry in self._rows(
"SELECT * FROM order_item WHERE order_id = ? ORDER BY id",
(row["id"],),
)
)
]
order["subtotal_display"] = money(row["subtotal_cents"])
order["shipping_display"] = (
"FREE" if row["shipping_cents"] == 0 else money(row["shipping_cents"])
)
order["tax_display"] = money(row["tax_cents"])
order["total_display"] = money(row["total_cents"])
order["delivery_label"] = DELIVERY_METHODS.get(
row["delivery_method"], ("Delivery", 0)
)[0]
return order
|