Files
member-console/internal/billing/queries/invoices.sql
T

196 lines
8.1 KiB
SQL

-- name: CreateInvoice :one
-- invoice_number is the platform-assigned reference number (invoice-numbers
-- D1-D3): the caller assigns it via AssignNextInvoiceNumber (billing_accounts.sql)
-- in the same transaction, inside the invoice.finalized projection, and
-- passes the formatted result here. Drafts pass NULL/invalid
-- (chk_invoices_issued_have_number allows a NULL number only when status is
-- 'draft').
INSERT INTO core.invoices (
billing_account_id, subscription_id, status,
amount_due, amount_paid, currency,
period_start, period_end, due_date, invoice_number
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING *;
-- name: GetInvoiceByID :one
SELECT * FROM core.invoices
WHERE invoice_id = $1;
-- name: GetInvoicesByBillingAccountID :many
SELECT * FROM core.invoices
WHERE billing_account_id = $1
ORDER BY created_at DESC;
-- name: UpdateInvoiceStatus :one
UPDATE core.invoices
SET status = $2
WHERE invoice_id = $1
RETURNING *;
-- name: UpdateInvoicePaid :one
UPDATE core.invoices
SET status = 'paid',
amount_paid = $2,
paid_at = $3
WHERE invoice_id = $1
RETURNING *;
-- name: UpdateInvoiceVoided :one
UPDATE core.invoices
SET status = 'void',
voided_at = $2
WHERE invoice_id = $1
RETURNING *;
-- name: ListInvoicesPage :many
-- Operator invoices view, paged/searched/filtered (operator-list-scale
-- UX-4; operator-billing-views D5/D8). Carries ba.org_id so the handler can
-- resolve and link the organization without a cross-module join (see
-- billing_accounts.sql's ListBillingAccountsPage comment for why).
--
-- sqlc.narg(q): NULL matches every row; set, a case-insensitive substring
-- match against the billing account's name (the view's leading identifier
-- pre-reorder), the invoice's own invoice_number (invoice-numbers D3/D4 --
-- matches both the platform form and a grandfathered Stripe-format string,
-- since both live in this column), or its organization via
-- sqlc.narg(org_ids), pre-resolved in Go (operator_billing.go:
-- matchingOrgIDs). sqlc.narg(invoice_ids): a search also matches an
-- invoice whose stripe.invoice_mappings row carries a matching
-- stripe_invoice_number (design D6) -- internal/billing has no query that
-- joins the stripe schema (mirrors the org-name pattern above: no existing
-- query crosses that module boundary either), so operator_billing.go
-- resolves the matching invoice ids there
-- (matchingInvoiceIDsByStripeNumber) and passes them in pre-resolved, the
-- same shape as org_ids.
-- sqlc.narg(status): NULL matches every status. The stored status
-- vocabulary (design/data-model.md: draft, open, paid, void,
-- uncollectible, refunded -- core.invoices carries no CHECK constraint,
-- this is the documented closed set) matches exactly; the sentinel value
-- 'overdue' instead selects the derived predicate design D5 defines --
-- status = 'open' AND due_date IS NOT NULL AND due_date < now() -- so the
-- Overdue filter's total is computed in SQL, never after LIMIT (the same
-- predicate operator_billing.go's invoiceIsOverdue applies in Go for
-- per-row presentation; a test pins their agreement).
-- sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is
-- in the array are left out of the page AND out of count(*) OVER(), so the
-- pager's total counts only what renders. The operator billing views hand
-- it the ids whose stripe mapping records the environment the API key is
-- not in (stripe-environment-stamp D7), resolved in the stripe store the
-- same way org_ids and invoice_ids are resolved in Go, because no query
-- here crosses that module boundary.
-- count(*) OVER() carries the true total for the filtered set (design D2).
SELECT
i.invoice_id,
i.billing_account_id,
ba.org_id,
i.subscription_id,
i.status,
i.amount_due,
i.amount_paid,
i.currency,
i.period_start,
i.period_end,
i.due_date,
i.paid_at,
i.voided_at,
i.invoice_number,
i.created_at,
i.updated_at,
ba.name as billing_account_name,
count(*) OVER() AS total_count
FROM core.invoices i
JOIN core.accounts ba ON i.billing_account_id = ba.billing_account_id
WHERE (sqlc.narg(q)::text IS NULL
OR ba.name ILIKE '%' || sqlc.narg(q)::text || '%'
OR i.invoice_number ILIKE '%' || sqlc.narg(q)::text || '%'
OR ba.org_id = ANY(sqlc.narg(org_ids)::uuid[])
OR i.invoice_id = ANY(sqlc.narg(invoice_ids)::uuid[]))
AND (sqlc.narg(status)::text IS NULL
OR (sqlc.narg(status)::text = 'overdue'
AND i.status = 'open' AND i.due_date IS NOT NULL AND i.due_date < now())
OR (sqlc.narg(status)::text <> 'overdue' AND i.status = sqlc.narg(status)::text))
AND (sqlc.narg(exclude_ids)::uuid[] IS NULL
OR i.invoice_id <> ALL(sqlc.narg(exclude_ids)::uuid[]))
ORDER BY i.created_at DESC
LIMIT sqlc.arg(page_limit)::int OFFSET sqlc.arg(page_offset)::int;
-- name: CountInvoicesPage :one
-- The same predicates as ListInvoicesPage, without paging: the caller runs it twice,
-- once with sqlc.narg(exclude_ids) and once without, and the difference is
-- how many rows the environment filter holds back from the view the
-- operator is looking at. The billing views' absence line reports that
-- number under the search and the facet in force
-- (stripe-environment-stamp D7), which the page query's count(*) OVER()
-- cannot give, because it counts the rows that were shown.
SELECT count(*)::bigint AS total_count
FROM core.invoices i
JOIN core.accounts ba ON i.billing_account_id = ba.billing_account_id
WHERE (sqlc.narg(q)::text IS NULL
OR ba.name ILIKE '%' || sqlc.narg(q)::text || '%'
OR i.invoice_number ILIKE '%' || sqlc.narg(q)::text || '%'
OR ba.org_id = ANY(sqlc.narg(org_ids)::uuid[])
OR i.invoice_id = ANY(sqlc.narg(invoice_ids)::uuid[]))
AND (sqlc.narg(status)::text IS NULL
OR (sqlc.narg(status)::text = 'overdue'
AND i.status = 'open' AND i.due_date IS NOT NULL AND i.due_date < now())
OR (sqlc.narg(status)::text <> 'overdue' AND i.status = sqlc.narg(status)::text))
AND (sqlc.narg(exclude_ids)::uuid[] IS NULL
OR i.invoice_id <> ALL(sqlc.narg(exclude_ids)::uuid[]));
-- name: ListRecentInvoices :many
-- Recent invoices for the operator landing activity timeline. Joins to
-- core.accounts to resolve the org_id (same schema, safe for sqlc).
SELECT
i.invoice_id,
i.billing_account_id,
ba.org_id,
i.amount_due,
i.amount_paid,
i.currency,
i.status,
i.created_at
FROM core.invoices i
JOIN core.accounts ba ON ba.billing_account_id = i.billing_account_id
ORDER BY i.created_at DESC
LIMIT $1;
-- name: GetInvoicesByNumber :many
-- The operator landing-surface lookup's invoice-number resolver
-- (operator-panel-navigation design D4: exact key -> exact invoice number ->
-- persons -> organizations). invoice_number is unique per billing account
-- only (uq_invoices_account_invoice_number), never globally, so an exact
-- number can legitimately match several invoices across different
-- organizations' accounts; the caller renders a disambiguation row per
-- match (number, organization resolved Go-side via OrgQ, issued date).
-- Newest first, matching every other recent-first list on this surface.
SELECT
i.invoice_id,
i.billing_account_id,
ba.org_id,
i.invoice_number,
i.created_at
FROM core.invoices i
JOIN core.accounts ba ON ba.billing_account_id = i.billing_account_id
WHERE i.invoice_number = $1
ORDER BY i.created_at DESC;
-- name: CountOpenInvoices :one
-- Receivables headline for the operator landing surface. `open` is the only
-- actionable non-terminal invoice status (design/billing/model.md): draft is
-- not yet issued, and paid/void/uncollectible/refunded are settled or written
-- off. A count, not a balance sum — currency is per-row, and a cross-currency
-- sum would be a number the tile could not stand behind.
SELECT COUNT(*) FROM core.invoices
WHERE status = 'open';
-- name: SumOpenInvoiceBalanceByCurrency :many
-- Outstanding receivables for the Open invoices caption, per currency —
-- the caller applies the same largest-bucket display rule as the Monthly
-- recurring headline.
SELECT currency, SUM(amount_due - amount_paid)::bigint AS outstanding_cents
FROM core.invoices
WHERE status = 'open'
GROUP BY currency
ORDER BY outstanding_cents DESC;