Nightly revenue per store for the finance dashboard

Database · PostgreSQL · intermediate · modification

Finance wants daily revenue per store on their dashboard without querying `orders` live. `app/jobs/revenue_report.py` (new) builds one UTC day from the paid orders into `daily_store_revenue`, replacing that day's rows in one transaction. All three worker pods run every scheduled job, so the job takes a Postgres advisory lock first and a pod that cannot get it skips; a `finally` calls `pg_advisory_unlock` once the build is done to release it. Migration `0063_daily_store_revenue.sql` adds the table, `app/worker.py` schedules the job for 02:00, and `tests/test_revenue_report.py` (new) covers the job.

Shop backend: Python 3.12, psycopg 3.2 (plain SQL), PostgreSQL 16, one primary, default isolation (READ COMMITTED). `app/db.py` (existing) defines `make_pool()`, which returns `psycopg_pool.ConnectionPool(DATABASE_URL, min_size=4, max_size=4, open=False)` (psycopg-pool 3.2, every other setting at its default, so `max_lifetime` is one hour, no `reset` or `check` callback; connections are not in autocommit, and leaving a `with pool.connection()` block commits, or rolls back on an exception), and the module-level `pool = make_pool()`; code reads it as `db.pool` at call time. The worker deployment runs three pods; each opens `db.pool` at start-up and closes it at shutdown. The existing in-house scheduler (`app/scheduler.py`) fires every `Job` in `app/worker.py` at its cron time (UTC) on every worker pod and logs any exception the job raises; `app/jobs/` is an existing package. Tables: `stores` (`id bigint` identity primary key, `name text NOT NULL`), about 40 rows; `orders` (`id bigint` identity primary key, `store_id bigint NOT NULL REFERENCES stores`, `status text NOT NULL` CHECK in `pending`, `paid`, `refunded`, `total_cents bigint NOT NULL` CHECK `>= 0` and at most 10,000,000, `created_at timestamptz NOT NULL DEFAULT now()`), about 3 million rows with an index on `created_at`; a store takes at most a few thousand orders a day. Schema changes are plain SQL files in `migrations/`, applied in name order by the existing runner at the start of every deploy, each file in one transaction. The test suite (`tests/conftest.py`, existing) builds a fresh test database from all migrations, truncates every table before each test, gives each test a fresh `db.pool` opened for that test and closed after it, and provides `sql` (an autocommit connection), `insert_store(name)` and `insert_order(store_id, created_at, status="paid", total_cents=1000)`.

Requirements

Files touched

Review this PR

Database practice