AgPerry's picture
Add files using upload-large-folder tool
187ef74 verified
Raw History Blame Contribute Delete
19.1 kB
"""Site-owned donation, favorite, and recurring-plan semantics for ioby.
The live site was observed in its archival/closed state, so none of its
production donation or account endpoints were mutated. These tables model the
frozen WebsiteBench journeys locally. Payment outcomes come only from the
generated ``websitebench.site_backend`` local sandbox; this module never
accepts card data and never contacts ioby or a payment provider.
"""
from __future__ import annotations
import sqlite3
import uuid
from datetime import UTC, datetime
from typing import Any, Mapping
PROJECT_SLUG = "make-block-bloom"
PROJECT_TITLE = "Make the Block Bloom"
SCHEMA = """
CREATE TABLE IF NOT EXISTS ioby_schema_migrations (
version TEXT PRIMARY KEY,
applied_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS ioby_donations (
id TEXT PRIMARY KEY,
owner_key TEXT NOT NULL,
account_id TEXT,
project_slug TEXT NOT NULL,
project_title TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('draft','confirmed','canceled')),
cadence TEXT NOT NULL CHECK(cadence IN ('one-time','monthly')),
amount_cents INTEGER NOT NULL CHECK(amount_cents BETWEEN 100 AND 10000000),
tip_cents INTEGER NOT NULL DEFAULT 0 CHECK(tip_cents BETWEEN 0 AND 10000000),
donor_name TEXT,
donor_email TEXT,
recognition TEXT NOT NULL DEFAULT 'public'
CHECK(recognition IN ('public','anonymous')),
dedication TEXT,
payment_snapshot_token TEXT NOT NULL UNIQUE,
payment_flow_id TEXT,
payment_attempt_id TEXT,
receipt_number TEXT UNIQUE,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
confirmed_at TEXT
);
CREATE INDEX IF NOT EXISTS ioby_donations_owner_idx
ON ioby_donations(owner_key, created_at DESC);
CREATE INDEX IF NOT EXISTS ioby_donations_account_idx
ON ioby_donations(account_id, created_at DESC);
CREATE TABLE IF NOT EXISTS ioby_recurring_plans (
id TEXT PRIMARY KEY,
donation_id TEXT NOT NULL UNIQUE
REFERENCES ioby_donations(id) ON DELETE CASCADE,
account_id TEXT,
owner_key TEXT NOT NULL,
project_slug TEXT NOT NULL,
amount_cents INTEGER NOT NULL,
status TEXT NOT NULL CHECK(status IN ('active','canceled')),
next_local_run TEXT,
canceled_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS ioby_favorites (
account_id TEXT NOT NULL,
project_slug TEXT NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY(account_id, project_slug)
);
CREATE TABLE IF NOT EXISTS ioby_receipts (
receipt_number TEXT PRIMARY KEY,
donation_id TEXT NOT NULL UNIQUE
REFERENCES ioby_donations(id) ON DELETE CASCADE,
owner_key TEXT NOT NULL,
account_id TEXT,
project_slug TEXT NOT NULL,
amount_cents INTEGER NOT NULL,
cadence TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS ioby_project_totals (
project_slug TEXT PRIMARY KEY,
confirmed_amount_cents INTEGER NOT NULL DEFAULT 0,
confirmed_donation_count INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
);
"""
def now() -> str:
return datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _id(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex}"
def _opaque_snapshot_token() -> str:
"""Return an opaque 256-bit token without adding a hash mechanism."""
return uuid.uuid4().hex + uuid.uuid4().hex
def migrate(connection: sqlite3.Connection) -> None:
connection.executescript(SCHEMA)
columns = {
str(row[1])
for row in connection.execute("PRAGMA table_info(ioby_donations)").fetchall()
}
if "payment_snapshot_token" not in columns:
connection.execute(
"ALTER TABLE ioby_donations ADD COLUMN payment_snapshot_token TEXT"
)
missing = connection.execute(
"SELECT id FROM ioby_donations WHERE payment_snapshot_token IS NULL"
).fetchall()
for row in missing:
connection.execute(
"UPDATE ioby_donations SET payment_snapshot_token=? WHERE id=?",
(_opaque_snapshot_token(), row[0]),
)
connection.execute(
"INSERT OR IGNORE INTO ioby_schema_migrations(version,applied_at) VALUES (?,?)",
("001-local-community-donations", now()),
)
connection.execute(
"INSERT OR IGNORE INTO ioby_schema_migrations(version,applied_at) VALUES (?,?)",
("002-atomic-receipts-and-opaque-payment-snapshots", now()),
)
connection.execute(
"""INSERT OR IGNORE INTO ioby_receipts(
receipt_number,donation_id,owner_key,account_id,project_slug,
amount_cents,cadence,created_at
)
SELECT receipt_number,id,owner_key,account_id,project_slug,
amount_cents + tip_cents,cadence,COALESCE(confirmed_at,updated_at)
FROM ioby_donations
WHERE status='confirmed' AND receipt_number IS NOT NULL"""
)
def _public(row: sqlite3.Row | None) -> dict[str, Any] | None:
return dict(row) if row is not None else None
def seed_demo(connection: sqlite3.Connection, account_id: str) -> None:
"""Install deterministic offline history for the seeded local donor."""
connection.execute(
"""INSERT OR IGNORE INTO ioby_donations(
id,owner_key,account_id,project_slug,project_title,status,cadence,
amount_cents,tip_cents,donor_name,donor_email,recognition,dedication,
payment_snapshot_token,receipt_number,created_at,updated_at,confirmed_at
) VALUES (?,?,?,?,?,'confirmed','one-time',2500,0,?,?,?,?, ?,?,?,?,?)""",
(
"donation_seed_history",
"seed:ioby-demo-donor",
account_id,
PROJECT_SLUG,
PROJECT_TITLE,
"Morgan Neighbor",
"demo@ioby.local",
"public",
"For greener blocks.",
"0000000000000000000000000000000000000000000000000000000000000001",
"IOBY-LOCAL-SEED-001",
"2026-01-15T15:00:00Z",
"2026-01-15T15:00:00Z",
"2026-01-15T15:00:00Z",
),
)
connection.execute(
"""INSERT OR IGNORE INTO ioby_donations(
id,owner_key,account_id,project_slug,project_title,status,cadence,
amount_cents,tip_cents,donor_name,donor_email,recognition,
payment_snapshot_token,receipt_number,created_at,updated_at,confirmed_at
) VALUES (?,?,?,?,?,'confirmed','monthly',1000,0,?,?,?, ?,?,?,?,?)""",
(
"donation_seed_recurring",
"seed:ioby-demo-donor",
account_id,
PROJECT_SLUG,
PROJECT_TITLE,
"Morgan Neighbor",
"demo@ioby.local",
"anonymous",
"0000000000000000000000000000000000000000000000000000000000000002",
"IOBY-LOCAL-SEED-002",
"2026-02-01T15:00:00Z",
"2026-02-01T15:00:00Z",
"2026-02-01T15:00:00Z",
),
)
connection.execute(
"""INSERT OR IGNORE INTO ioby_recurring_plans(
id,donation_id,account_id,owner_key,project_slug,amount_cents,status,
next_local_run,created_at,updated_at
) VALUES (?,?,?,?,?,1000,'active',?,?,?)""",
(
"recurring_seed_plan",
"donation_seed_recurring",
account_id,
"seed:ioby-demo-donor",
PROJECT_SLUG,
"2026-09-01T15:00:00Z",
"2026-02-01T15:00:00Z",
"2026-02-01T15:00:00Z",
),
)
connection.execute(
"""INSERT INTO ioby_project_totals(
project_slug,confirmed_amount_cents,confirmed_donation_count,updated_at
) VALUES (?,?,?,?)
ON CONFLICT(project_slug) DO UPDATE SET
confirmed_amount_cents=(
SELECT COALESCE(SUM(amount_cents + tip_cents),0)
FROM ioby_donations
WHERE project_slug=excluded.project_slug AND status='confirmed'
),
confirmed_donation_count=(
SELECT COUNT(*) FROM ioby_donations
WHERE project_slug=excluded.project_slug AND status='confirmed'
),
-- Seeding replays on every start. Stamping a new time when the
-- recomputed totals are unchanged would rewrite durable state on a
-- restart that changed no business row, so only a real change to
-- the totals moves the timestamp.
updated_at=CASE
WHEN confirmed_amount_cents=(
SELECT COALESCE(SUM(amount_cents + tip_cents),0)
FROM ioby_donations
WHERE project_slug=excluded.project_slug
AND status='confirmed'
)
AND confirmed_donation_count=(
SELECT COUNT(*) FROM ioby_donations
WHERE project_slug=excluded.project_slug
AND status='confirmed'
)
THEN updated_at
ELSE excluded.updated_at
END""",
(PROJECT_SLUG, 3500, 2, now()),
)
def create_draft(
connection: sqlite3.Connection,
*,
owner_key: str,
account_id: str | None,
project_slug: str,
amount_cents: int,
cadence: str,
) -> dict[str, Any]:
donation_id = _id("donation")
timestamp = now()
connection.execute(
"""INSERT INTO ioby_donations(
id,owner_key,account_id,project_slug,project_title,status,cadence,
amount_cents,payment_snapshot_token,created_at,updated_at
) VALUES (?,?,?,?,?,'draft',?,?,?,?,?)""",
(
donation_id,
owner_key,
account_id,
project_slug,
PROJECT_TITLE,
cadence,
amount_cents,
_opaque_snapshot_token(),
timestamp,
timestamp,
),
)
return get_donation(
connection,
donation_id,
owner_key=owner_key,
account_id=account_id,
) # type: ignore[return-value]
def get_donation(
connection: sqlite3.Connection,
donation_id: str,
*,
owner_key: str | None,
account_id: str | None,
) -> dict[str, Any] | None:
row = connection.execute(
"SELECT * FROM ioby_donations WHERE id=?", (donation_id,)
).fetchone()
if row is None:
return None
if row["owner_key"] != owner_key and not (
account_id and row["account_id"] == account_id
):
return None
return _public(row)
def update_details(
connection: sqlite3.Connection,
donation_id: str,
values: Mapping[str, Any],
*,
owner_key: str,
account_id: str | None,
) -> dict[str, Any] | None:
existing = get_donation(
connection, donation_id, owner_key=owner_key, account_id=account_id
)
if existing is None or existing["status"] != "draft":
return None
allowed = {"donor_name", "donor_email", "recognition", "dedication", "tip_cents"}
clean = {key: value for key, value in values.items() if key in allowed}
if clean:
assignments = ",".join(f"{key}=?" for key in clean)
connection.execute(
f"""UPDATE ioby_donations
SET {assignments},payment_snapshot_token=?,updated_at=?
WHERE id=?""",
(*clean.values(), _opaque_snapshot_token(), now(), donation_id),
)
return get_donation(
connection, donation_id, owner_key=owner_key, account_id=account_id
)
def payment_facts(donation: Mapping[str, Any]) -> dict[str, Any]:
"""Return immutable sandbox facts without inventing a site-side hash."""
return {
"owner": str(donation["owner_key"]),
"amount_minor": int(donation["amount_cents"]) + int(donation["tip_cents"]),
"currency": "USD",
"fingerprint": str(donation["payment_snapshot_token"]),
}
def record_payment_approval(
connection: sqlite3.Connection,
donation_id: str,
*,
owner_key: str,
account_id: str | None,
payment_flow_id: str,
payment_attempt_id: str,
) -> dict[str, Any] | None:
donation = get_donation(
connection, donation_id, owner_key=owner_key, account_id=account_id
)
if donation is None or donation["status"] != "draft":
return None
connection.execute(
"""UPDATE ioby_donations
SET payment_flow_id=?,payment_attempt_id=?,updated_at=?
WHERE id=? AND status='draft'""",
(payment_flow_id, payment_attempt_id, now(), donation_id),
)
return get_donation(
connection, donation_id, owner_key=owner_key, account_id=account_id
)
def confirm_donation(
connection: sqlite3.Connection,
*,
donation_id: str,
owner_key: str,
account_id: str | None,
payment_flow_id: str,
payment_attempt_id: str,
) -> dict[str, Any] | None:
donation = get_donation(
connection, donation_id, owner_key=owner_key, account_id=account_id
)
if donation is None:
return None
if donation["status"] == "confirmed":
return donation
if donation["status"] != "draft":
return None
timestamp = now()
receipt = f"IOBY-LOCAL-{uuid.uuid4().hex[:12].upper()}"
changed = connection.execute(
"""UPDATE ioby_donations
SET status='confirmed',account_id=COALESCE(account_id,?),
payment_flow_id=?,payment_attempt_id=?,receipt_number=?,
confirmed_at=?,updated_at=?
WHERE id=? AND status='draft'""",
(
account_id,
payment_flow_id,
payment_attempt_id,
receipt,
timestamp,
timestamp,
donation_id,
),
).rowcount
if changed != 1:
return get_donation(
connection, donation_id, owner_key=owner_key, account_id=account_id
)
connection.execute(
"""INSERT INTO ioby_receipts(
receipt_number,donation_id,owner_key,account_id,project_slug,
amount_cents,cadence,created_at
) VALUES (?,?,?,?,?,?,?,?)""",
(
receipt,
donation_id,
owner_key,
account_id,
donation["project_slug"],
int(donation["amount_cents"]) + int(donation["tip_cents"]),
donation["cadence"],
timestamp,
),
)
connection.execute(
"""INSERT INTO ioby_project_totals(
project_slug,confirmed_amount_cents,confirmed_donation_count,updated_at
) VALUES (?,?,1,?)
ON CONFLICT(project_slug) DO UPDATE SET
confirmed_amount_cents=confirmed_amount_cents+excluded.confirmed_amount_cents,
confirmed_donation_count=confirmed_donation_count+1,
updated_at=excluded.updated_at""",
(
donation["project_slug"],
int(donation["amount_cents"]) + int(donation["tip_cents"]),
timestamp,
),
)
if donation["cadence"] == "monthly":
connection.execute(
"""INSERT INTO ioby_recurring_plans(
id,donation_id,account_id,owner_key,project_slug,amount_cents,
status,next_local_run,created_at,updated_at
) VALUES (?,?,?,?,?,?,'active',?,?,?)""",
(
_id("recurring"),
donation_id,
account_id,
owner_key,
donation["project_slug"],
donation["amount_cents"],
"next local monthly cycle",
timestamp,
timestamp,
),
)
return get_donation(
connection, donation_id, owner_key=owner_key, account_id=account_id
)
def claim_donations(
connection: sqlite3.Connection, *, owner_key: str, account_id: str
) -> None:
connection.execute(
"UPDATE ioby_donations SET account_id=? WHERE owner_key=? AND account_id IS NULL",
(account_id, owner_key),
)
connection.execute(
"UPDATE ioby_recurring_plans SET account_id=? WHERE owner_key=? AND account_id IS NULL",
(account_id, owner_key),
)
def list_donations(connection: sqlite3.Connection, account_id: str) -> list[dict[str, Any]]:
return [
dict(row)
for row in connection.execute(
"""SELECT * FROM ioby_donations
WHERE account_id=? AND status='confirmed'
ORDER BY confirmed_at DESC, created_at DESC""",
(account_id,),
)
]
def list_recurring(connection: sqlite3.Connection, account_id: str) -> list[dict[str, Any]]:
return [
dict(row)
for row in connection.execute(
"""SELECT r.*,d.project_title FROM ioby_recurring_plans r
JOIN ioby_donations d ON d.id=r.donation_id
WHERE r.account_id=? ORDER BY r.created_at DESC""",
(account_id,),
)
]
def cancel_recurring(
connection: sqlite3.Connection, plan_id: str, account_id: str
) -> dict[str, Any] | None:
row = connection.execute(
"SELECT * FROM ioby_recurring_plans WHERE id=? AND account_id=?",
(plan_id, account_id),
).fetchone()
if row is None:
return None
if row["status"] == "active":
timestamp = now()
connection.execute(
"""UPDATE ioby_recurring_plans
SET status='canceled',canceled_at=?,updated_at=?
WHERE id=? AND account_id=? AND status='active'""",
(timestamp, timestamp, plan_id, account_id),
)
return _public(
connection.execute(
"SELECT * FROM ioby_recurring_plans WHERE id=? AND account_id=?",
(plan_id, account_id),
).fetchone()
)
def is_favorite(connection: sqlite3.Connection, account_id: str, project_slug: str) -> bool:
return connection.execute(
"SELECT 1 FROM ioby_favorites WHERE account_id=? AND project_slug=?",
(account_id, project_slug),
).fetchone() is not None
def set_favorite(
connection: sqlite3.Connection,
account_id: str,
project_slug: str,
*,
saved: bool,
) -> bool:
"""Set a server-known project's saved state idempotently.
A target state is used instead of a toggle so a retried POST cannot undo
the user's first successful request. The public app supplies the account
from the authenticated session and this function rejects project names
outside the frozen local inventory.
"""
if project_slug != PROJECT_SLUG:
raise ValueError("unknown local project")
if saved:
connection.execute(
"INSERT OR IGNORE INTO ioby_favorites("
"account_id,project_slug,created_at) VALUES (?,?,?)",
(account_id, project_slug, now()),
)
else:
connection.execute(
"DELETE FROM ioby_favorites WHERE account_id=? AND project_slug=?",
(account_id, project_slug),
)
return saved