AgPerry's picture
Add files using upload-large-folder tool
9f517f2 verified
Raw History Blame Contribute Delete
22.6 kB
"""Etsy-specific checkout and order closure over the shared payment ledger.
The clone owns cart, checkout, address, and immutable order snapshots. The
vendored ``websitebench.site_backend`` runtime owns site binding and the
test-only payment state machine. A successful order always consumes the
matching approval inside the same SQLite transaction that creates the order.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import secrets
import sqlite3
from collections.abc import Mapping
from typing import Any
from websitebench.site_backend import (
PaymentConflict,
PaymentError,
PaymentRejected,
SiteBackend,
)
from backend import db
SITE_ID = "etsy"
CURRENCY = "USD"
SHIPPING_CENTS = 0
TAX_BASIS_POINTS = 825
PAYMENT_ADAPTER_ENV = "WEBSITEBENCH_PAYMENT_ADAPTER"
_POSTAL_RE = re.compile(r"^[0-9]{5}(?:-[0-9]{4})?$")
_STATE_RE = re.compile(r"^[A-Z]{2}$")
_SAFE_SCENARIO_LABELS = {
"approved": "Approve test payment",
"declined": "Decline test payment",
"retryable": "Ask to retry test payment",
}
class PurchaseError(RuntimeError):
"""The checkout is invalid, stale, foreign, or not payable."""
def _require_transaction(connection: sqlite3.Connection) -> None:
if not isinstance(connection, sqlite3.Connection) or not connection.in_transaction:
raise PurchaseError("purchase operation requires an active transaction")
def money(cents: int | str) -> str:
return f"${int(cents) / 100:.2f}"
def payment_owner(account_id: str) -> str:
return f"etsy-account:{account_id}"
def payment_adapter(backend: SiteBackend) -> str:
adapter = str(
os.environ.get(
PAYMENT_ADAPTER_ENV,
backend.config.payments["default_adapter"],
)
).strip()
if adapter not in {"local-sandbox", "stripe-test"}:
raise PurchaseError("the configured test payment adapter is invalid")
if adapter == "stripe-test" and backend.config.payments["stripe_test"] is None:
raise PurchaseError("Stripe test Checkout is not configured")
return adapter
def payment_scenarios(backend: SiteBackend) -> tuple[dict[str, str], ...]:
if payment_adapter(backend) != "local-sandbox":
return ()
return tuple(
{
"id": str(item["id"]),
"outcome": str(item["outcome"]),
"label": _SAFE_SCENARIO_LABELS[str(item["outcome"])],
}
for item in backend.config.payments["local_sandbox"]["scenarios"]
)
def validate_address(values: Mapping[str, str]) -> tuple[dict[str, str], list[str]]:
address = {
"name": str(values.get("name", "")).strip(),
"address1": str(values.get("address1", "")).strip(),
"address2": str(values.get("address2", "")).strip(),
"city": str(values.get("city", "")).strip(),
"state": str(values.get("state", "")).strip().upper(),
"postal_code": str(values.get("postal_code", "")).strip(),
"country": "US",
}
errors: list[str] = []
for field, label, maximum in (
("name", "Full name", 100),
("address1", "Street address", 160),
("city", "City", 100),
):
value = address[field]
if not value or len(value) > maximum or any(ord(char) < 32 for char in value):
errors.append(f"{label} is required and must be {maximum} characters or fewer.")
if len(address["address2"]) > 160 or any(
ord(char) < 32 for char in address["address2"]
):
errors.append("Apartment or suite must be 160 characters or fewer.")
if _STATE_RE.fullmatch(address["state"]) is None:
errors.append("State must be a two-letter US abbreviation.")
if _POSTAL_RE.fullmatch(address["postal_code"]) is None:
errors.append("ZIP code must be a valid five- or nine-digit US ZIP code.")
return address, errors
def _cart_rows(connection: sqlite3.Connection, owner_key: str) -> list[sqlite3.Row]:
return connection.execute(
"SELECT c.*,l.title,l.slug,l.image,l.stock_state,l.version AS current_version "
"FROM cart_lines c JOIN listings l ON l.listing_id=c.listing_id "
"WHERE c.owner_key=? ORDER BY c.rowid",
(owner_key,),
).fetchall()
def _cart_snapshot(
connection: sqlite3.Connection,
*,
account_id: str,
owner_key: str,
address: Mapping[str, str],
) -> dict[str, Any]:
rows = _cart_rows(connection, owner_key)
if not rows:
raise PurchaseError("Your cart is empty.")
lines: list[dict[str, Any]] = []
item_total = 0
for position, row in enumerate(rows):
if row["stock_state"] != "in-stock" or row["listing_version"] != row["current_version"]:
raise PurchaseError("Your cart changed. Refresh it before checkout.")
subtotal = int(row["unit_price_cents"]) * int(row["quantity"])
item_total += subtotal
lines.append(
{
"position": position,
"cart_line_token": str(row["line_token"]),
"listing_id": str(row["listing_id"]),
"listing_version": str(row["listing_version"]),
"title": str(row["title"]),
"slug": str(row["slug"]),
"image": str(row["image"]),
"variations_json": str(row["variations_json"]),
"personalization": str(row["personalization"]),
"quantity": int(row["quantity"]),
"unit_price_cents": int(row["unit_price_cents"]),
"subtotal_cents": subtotal,
}
)
tax = (item_total * TAX_BASIS_POINTS + 5_000) // 10_000
total = item_total + SHIPPING_CENTS + tax
canonical = {
"site_id": SITE_ID,
"account_id": account_id,
"currency": CURRENCY,
"address": dict(address),
"lines": lines,
"item_total_cents": item_total,
"shipping_cents": SHIPPING_CENTS,
"tax_cents": tax,
"total_cents": total,
}
fingerprint = hashlib.sha256(
json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
return {**canonical, "fingerprint": fingerprint}
def create_checkout(
connection: sqlite3.Connection,
backend: SiteBackend,
*,
account_id: str,
owner_key: str,
address: Mapping[str, str],
) -> dict[str, Any]:
_require_transaction(connection)
snapshot = _cart_snapshot(
connection,
account_id=account_id,
owner_key=owner_key,
address=address,
)
existing = connection.execute(
"SELECT * FROM checkouts WHERE account_id=? AND cart_fingerprint=?",
(account_id, snapshot["fingerprint"]),
).fetchone()
if existing is not None:
return dict(existing)
checkout_id = f"checkout_{secrets.token_urlsafe(18)}"
adapter = payment_adapter(backend)
try:
flow = backend.payments.create_intent(
owner=payment_owner(account_id),
amount_minor=int(snapshot["total_cents"]),
currency=CURRENCY,
fingerprint=str(snapshot["fingerprint"]),
idempotency_key=f"etsy-checkout:{snapshot['fingerprint'][:48]}",
adapter=adapter,
connection=connection,
)
except (PaymentConflict, PaymentError, PaymentRejected) as exc:
raise PurchaseError("The test payment flow could not be created.") from exc
address_json = json.dumps(dict(address), sort_keys=True, separators=(",", ":"))
connection.execute(
"INSERT INTO checkouts(checkout_id,account_id,status,currency,item_total_cents,"
"shipping_cents,tax_cents,total_cents,cart_fingerprint,address_json,"
"payment_flow_id,version,created_at,updated_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,1,?,?)",
(
checkout_id,
account_id,
"pending-payment",
CURRENCY,
snapshot["item_total_cents"],
snapshot["shipping_cents"],
snapshot["tax_cents"],
snapshot["total_cents"],
snapshot["fingerprint"],
address_json,
flow["flow_id"],
db.FROZEN_CLOCK,
db.FROZEN_CLOCK,
),
)
for line in snapshot["lines"]:
connection.execute(
"INSERT INTO checkout_lines(checkout_id,position,cart_line_token,listing_id,"
"listing_version,title,slug,image,variations_json,personalization,quantity,"
"unit_price_cents,subtotal_cents) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
checkout_id,
line["position"],
line["cart_line_token"],
line["listing_id"],
line["listing_version"],
line["title"],
line["slug"],
line["image"],
line["variations_json"],
line["personalization"],
line["quantity"],
line["unit_price_cents"],
line["subtotal_cents"],
),
)
return dict(
connection.execute(
"SELECT * FROM checkouts WHERE checkout_id=?", (checkout_id,)
).fetchone()
)
def checkout_for_owner(
connection: sqlite3.Connection, account_id: str, checkout_id: str
) -> dict[str, Any] | None:
row = connection.execute(
"SELECT * FROM checkouts WHERE checkout_id=? AND account_id=?",
(checkout_id, account_id),
).fetchone()
return dict(row) if row is not None else None
def checkout_lines(connection: sqlite3.Connection, checkout_id: str) -> list[dict[str, Any]]:
return [
dict(row)
for row in connection.execute(
"SELECT * FROM checkout_lines WHERE checkout_id=? ORDER BY position",
(checkout_id,),
)
]
def decorate_checkout(
connection: sqlite3.Connection, checkout: Mapping[str, Any]
) -> dict[str, Any]:
value = dict(checkout)
value["address"] = json.loads(str(value["address_json"]))
value["lines"] = checkout_lines(connection, str(value["checkout_id"]))
for line in value["lines"]:
line["summary"] = _line_summary(line)
line["unit_price"] = money(line["unit_price_cents"])
line["subtotal"] = money(line["subtotal_cents"])
for key in ("item_total", "shipping", "tax", "total"):
value[key] = money(value[f"{key}_cents"])
return value
def _line_summary(line: Mapping[str, Any]) -> str:
variations = json.loads(str(line["variations_json"]))
parts = [f"{label}: {value}" for label, value in variations.items()]
if line.get("personalization"):
parts.append(f"Personalization: {line['personalization']}")
return " · ".join(parts)
def _checkout_is_current(
connection: sqlite3.Connection,
checkout: Mapping[str, Any],
) -> bool:
expected = checkout_lines(connection, str(checkout["checkout_id"]))
owner_key = f"account:{checkout['account_id']}"
current = _cart_rows(connection, owner_key)
if len(current) != len(expected):
return False
for row, line in zip(current, expected, strict=True):
if (
str(row["line_token"]) != str(line["cart_line_token"])
or str(row["listing_id"]) != str(line["listing_id"])
or str(row["listing_version"]) != str(line["listing_version"])
or str(row["current_version"]) != str(line["listing_version"])
or str(row["stock_state"]) != "in-stock"
or str(row["variations_json"]) != str(line["variations_json"])
or str(row["personalization"]) != str(line["personalization"])
or int(row["quantity"]) != int(line["quantity"])
or int(row["unit_price_cents"]) != int(line["unit_price_cents"])
):
return False
return True
def _mark_nonapproved(
connection: sqlite3.Connection, checkout_id: str, outcome: str
) -> None:
status = "payment-declined" if outcome == "DECLINED" else "payment-retry"
connection.execute(
"UPDATE checkouts SET status=?,version=version+1,updated_at=? "
"WHERE checkout_id=? AND status!='completed'",
(status, db.FROZEN_CLOCK, checkout_id),
)
def _finalize_order(
connection: sqlite3.Connection,
backend: SiteBackend,
*,
checkout: Mapping[str, Any],
) -> dict[str, Any]:
_require_transaction(connection)
existing = connection.execute(
"SELECT * FROM orders WHERE checkout_id=? AND account_id=?",
(checkout["checkout_id"], checkout["account_id"]),
).fetchone()
if existing is not None:
return dict(existing)
if checkout["status"] == "completed" or not _checkout_is_current(connection, checkout):
raise PurchaseError("The checkout is stale or already completed.")
try:
payment = backend.payments.consume_approval(
connection,
flow_id=str(checkout["payment_flow_id"]),
owner=payment_owner(str(checkout["account_id"])),
amount_minor=int(checkout["total_cents"]),
currency=str(checkout["currency"]),
fingerprint=str(checkout["cart_fingerprint"]),
)
except (PaymentConflict, PaymentError, PaymentRejected) as exc:
raise PurchaseError("The test payment approval is missing or stale.") from exc
order_id = f"order_{secrets.token_urlsafe(18)}"
connection.execute(
"INSERT INTO orders(order_id,account_id,checkout_id,payment_flow_id,status,"
"currency,item_total_cents,shipping_cents,tax_cents,total_cents,address_json,placed_at) "
"VALUES (?,?,?,?, 'paid',?,?,?,?,?,?,?)",
(
order_id,
checkout["account_id"],
checkout["checkout_id"],
checkout["payment_flow_id"],
checkout["currency"],
checkout["item_total_cents"],
checkout["shipping_cents"],
checkout["tax_cents"],
checkout["total_cents"],
checkout["address_json"],
db.FROZEN_CLOCK,
),
)
lines = checkout_lines(connection, str(checkout["checkout_id"]))
for line in lines:
connection.execute(
"INSERT INTO order_lines(order_id,position,listing_id,listing_version,title,"
"slug,image,variations_json,personalization,quantity,unit_price_cents,"
"subtotal_cents) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
(
order_id,
line["position"],
line["listing_id"],
line["listing_version"],
line["title"],
line["slug"],
line["image"],
line["variations_json"],
line["personalization"],
line["quantity"],
line["unit_price_cents"],
line["subtotal_cents"],
),
)
connection.execute(
"DELETE FROM cart_lines WHERE line_token=? AND owner_key=?",
(line["cart_line_token"], f"account:{checkout['account_id']}"),
)
event_snapshot = {
"site_id": SITE_ID,
"order_id": order_id,
"checkout_id": checkout["checkout_id"],
"payment_flow_id": checkout["payment_flow_id"],
"payment_attempt_id": payment["attempt_id"],
"total_cents": int(checkout["total_cents"]),
"currency": CURRENCY,
"is_simulation": True,
}
connection.execute(
"INSERT INTO order_events(event_id,order_id,event_type,snapshot_json,created_at) "
"VALUES (?,?,'order-created',?,?)",
(
f"orderevt_{secrets.token_urlsafe(18)}",
order_id,
json.dumps(event_snapshot, sort_keys=True, separators=(",", ":")),
db.FROZEN_CLOCK,
),
)
connection.execute(
"UPDATE checkouts SET status='completed',version=version+1,updated_at=? "
"WHERE checkout_id=?",
(db.FROZEN_CLOCK, checkout["checkout_id"]),
)
return dict(
connection.execute("SELECT * FROM orders WHERE order_id=?", (order_id,)).fetchone()
)
def attempt_local_payment(
connection: sqlite3.Connection,
backend: SiteBackend,
*,
account_id: str,
checkout_id: str,
scenario_id: str,
) -> tuple[str, dict[str, Any] | None]:
_require_transaction(connection)
checkout = checkout_for_owner(connection, account_id, checkout_id)
if checkout is None:
raise PurchaseError("Checkout not found.")
existing = connection.execute(
"SELECT * FROM orders WHERE checkout_id=? AND account_id=?",
(checkout_id, account_id),
).fetchone()
if existing is not None:
return "APPROVED", dict(existing)
if payment_adapter(backend) != "local-sandbox":
raise PurchaseError("Local test payment is not enabled.")
if not _checkout_is_current(connection, checkout):
connection.execute(
"UPDATE checkouts SET status='stale',version=version+1,updated_at=? "
"WHERE checkout_id=? AND status!='completed'",
(db.FROZEN_CLOCK, checkout_id),
)
raise PurchaseError("Your cart changed. Start checkout again.")
allowed = {item["id"] for item in payment_scenarios(backend)}
if scenario_id not in allowed:
raise PurchaseError("Choose a valid test payment outcome.")
try:
attempt = backend.payments.attempt(
flow_id=str(checkout["payment_flow_id"]),
owner=payment_owner(account_id),
amount_minor=int(checkout["total_cents"]),
currency=CURRENCY,
fingerprint=str(checkout["cart_fingerprint"]),
scenario_id=scenario_id,
idempotency_key=f"etsy-attempt:{checkout_id}:{scenario_id}",
connection=connection,
)
except (PaymentConflict, PaymentError, PaymentRejected) as exc:
raise PurchaseError("The test payment attempt was rejected.") from exc
outcome = str(attempt["status"])
if outcome == "APPROVED":
return outcome, _finalize_order(connection, backend, checkout=checkout)
_mark_nonapproved(connection, checkout_id, outcome)
return outcome, None
def approve_verified_stripe(
connection: sqlite3.Connection,
backend: SiteBackend,
*,
checkout: Mapping[str, Any],
provider_session_id: str,
provider_snapshot: Mapping[str, Any],
) -> dict[str, Any]:
_require_transaction(connection)
account_id = str(checkout["account_id"])
existing = connection.execute(
"SELECT * FROM orders WHERE checkout_id=? AND account_id=?",
(checkout["checkout_id"], account_id),
).fetchone()
if existing is not None:
return dict(existing)
if payment_adapter(backend) != "stripe-test" or not _checkout_is_current(
connection, checkout
):
raise PurchaseError("Stripe test checkout is stale or unavailable.")
try:
attempt = backend.payments.attempt_verified_stripe(
flow_id=str(checkout["payment_flow_id"]),
owner=payment_owner(account_id),
amount_minor=int(checkout["total_cents"]),
currency=CURRENCY,
fingerprint=str(checkout["cart_fingerprint"]),
provider_session_id=provider_session_id,
idempotency_key=f"etsy-stripe:{checkout['checkout_id']}:{provider_session_id}",
provider_verifier=lambda _session_id: provider_snapshot,
connection=connection,
)
except (PaymentConflict, PaymentError, PaymentRejected) as exc:
raise PurchaseError("The Stripe test Session was rejected.") from exc
if str(attempt["status"]) != "APPROVED":
raise PurchaseError("The Stripe test Session was not paid.")
return _finalize_order(connection, backend, checkout=checkout)
def checkout_by_flow(
connection: sqlite3.Connection, flow_id: str
) -> dict[str, Any] | None:
row = connection.execute(
"SELECT * FROM checkouts WHERE payment_flow_id=?", (flow_id,)
).fetchone()
return dict(row) if row is not None else None
def payment_flow(
connection: sqlite3.Connection, checkout: Mapping[str, Any]
) -> dict[str, Any]:
"""Return the immutable public flow facts used by the Stripe gateway."""
row = connection.execute(
"SELECT flow_id,site_id,owner,amount_minor,currency,fingerprint,adapter,"
"status,is_simulation FROM websitebench_payment_flows "
"WHERE flow_id=? AND site_id=?",
(checkout["payment_flow_id"], SITE_ID),
).fetchone()
if row is None:
raise PurchaseError("The test payment flow is missing.")
value = dict(row)
value["is_simulation"] = bool(value["is_simulation"])
return value
def order_for_owner(
connection: sqlite3.Connection, account_id: str, order_id: str
) -> dict[str, Any] | None:
row = connection.execute(
"SELECT * FROM orders WHERE order_id=? AND account_id=?",
(order_id, account_id),
).fetchone()
if row is None:
return None
value = dict(row)
value["address"] = json.loads(str(value["address_json"]))
value["lines"] = [
dict(line)
for line in connection.execute(
"SELECT * FROM order_lines WHERE order_id=? ORDER BY position", (order_id,)
)
]
for line in value["lines"]:
line["summary"] = _line_summary(line)
line["unit_price"] = money(line["unit_price_cents"])
line["subtotal"] = money(line["subtotal_cents"])
for key in ("item_total", "shipping", "tax", "total"):
value[key] = money(value[f"{key}_cents"])
return value
def orders_for_owner(connection: sqlite3.Connection, account_id: str) -> list[dict[str, Any]]:
orders: list[dict[str, Any]] = []
for row in connection.execute(
"SELECT * FROM orders WHERE account_id=? ORDER BY placed_at DESC,order_id DESC",
(account_id,),
):
order = dict(row)
order["total"] = money(order["total_cents"])
order["line_count"] = int(
connection.execute(
"SELECT COUNT(*) FROM order_lines WHERE order_id=?", (order["order_id"],)
).fetchone()[0]
)
orders.append(order)
return orders
__all__ = [
"CURRENCY",
"PurchaseError",
"approve_verified_stripe",
"attempt_local_payment",
"checkout_by_flow",
"checkout_for_owner",
"checkout_lines",
"create_checkout",
"decorate_checkout",
"money",
"order_for_owner",
"orders_for_owner",
"payment_adapter",
"payment_flow",
"payment_owner",
"payment_scenarios",
"validate_address",
]