Files
member-console/internal/billing/queries/invoices.sql
T
cgalo5758 dd3962990b Adopt entity keys and add invoice numbers
Replace the entity slugs on organizations, workspaces, resource pools,
and
plan ladders with nullable `key` columns and add keys to products,
prices,
and entitlement sets. Rename `providers.slug` to `provider` and add
partial
unique indexes for system and org role names.

Assign invoice numbers per billing account from a gapless transactional
counter; Stripe's number moves to the invoice mapping as an external
reference.

Seeds, fixtures, and the operator lookup address rows by key, and the
returning-login resync no longer blanks a display name when the IdP
sends
no `name` claim.
2026-08-29 20:12:04 -05:00

144 lines
5.5 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).
-- 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))
ORDER BY i.created_at DESC
LIMIT sqlc.arg(page_limit)::int OFFSET sqlc.arg(page_offset)::int;
-- 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: 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;