New customers report with order counts
Database · PostgreSQL · beginner · modification
Adds the endpoint behind the growth team's new-customers report. `queries/new_customers.sql` (new) selects the customers who signed up in the last 30 days with their number of orders, newest signup first. `app/customers.py` maps `GET /new` on the existing admin customers router, above the `/{customer_id}` route so `new` is never read as a customer id, and returns the rows. `tests/test_new_customers.py` (new) checks the counts, the order and the 30-day window.
Shop backend on PostgreSQL 16 and Python 3.12 (FastAPI 0.115, psycopg 3.2 with dict rows, plain SQL, no ORM). Existing and unchanged: `customers` (`id bigserial` primary key, `email text NOT NULL UNIQUE`, `name text NOT NULL`, `created_at timestamptz NOT NULL DEFAULT now()`, indexed) holds about 200,000 customers; `orders` (`id bigserial` primary key, `customer_id bigint NOT NULL` referencing `customers`, indexed, `total_cents bigint NOT NULL`, `created_at timestamptz NOT NULL DEFAULT now()`) holds about 1.5 million orders. `app.db.get_conn` yields a connection from the app's pool for the request. `app.queries.q(name)` returns the text of `queries/<name>.sql`, read once and cached; queries use psycopg named placeholders, so values are always sent as parameters. `app.auth.require_admin` answers 401 or 403 itself unless the signed-in user is an admin. `queries/customer_by_id.sql` selects one customer by `id`. Tests run with pytest against a fresh test database built from `migrations/`; `tests/conftest.py` provides `db` (a connection to that database, `orders` and `customers` emptied before each test) and `admin_client` (a FastAPI `TestClient` signed in as an admin). The report page (web app) ships separately and only reads this endpoint.
Requirements
- New endpoint `GET /api/admin/customers/new` lists the customers who signed up in the last 30 days (`created_at >= now() - interval '30 days'`), for the growth team.
- Each item is `{ "id", "email", "name", "created_at", "order_count" }`, where `order_count` is the number of orders the customer has placed. A customer who has not placed an order yet shows `order_count: 0`: the growth team sends those customers a first-order reminder.
- Items are ordered by `created_at`, newest first, ties broken by `id`, higher first. All matching customers are returned (about 2,000 signups a month). No signups in the window gives `[]`.
- The query lives in `queries/new_customers.sql` and is loaded with `q()`, like the app's other queries.
- Unchanged: the admin customers router's `require_admin` dependency answers 401 or 403 unless the caller is a signed-in admin, and `GET /api/admin/customers/{customer_id}` works as before.
Files touched
- queries/new_customers.sql
- app/customers.py
- tests/test_new_customers.py