Files
evig/docs/MONEY_CONVENTION.md
Mao NakamotoandClaude Opus 4.7 f733d44b83 feat(db): land Phase V+W+X — solve all DB audit items
Phase V (critical, applied to Neon directly):
- 083: bootstrap schema_migrations on Neon + backfill 001-082 (verified absent: SELECT EXISTS returned false; 92 rows now tracked)
- 084: 4 missing performance indexes — notifications(user_id,is_read,created_at DESC), pool_memberships(pool_id,status), inventory_items(status,assigned_to), partial fundraising_foundations(created_at DESC) WHERE NOT archived (67MB largest table, 534ms seq scans → indexed)
- V.3 RECLASSIFIED — no plaintext API keys actually exist in hirn_provider_settings (audit subagent overstated; verified empty); no action needed
- V.4 — 6 test accounts disabled on Neon (renamed to __disabled-<uuid>@disabled.local, cleared staff/super-admin flags, emailVerified=NULL). All 6 lacked verified emails so couldn't log in anyway, but the flags were latent risk.

Phase W (hardening):
- W.1: .github/workflows/ci.yml gains migration-drift-check job — spins postgres:17 container, applies all 91 SQL migrations in version-sort order, asserts table count + tracking row count. Non-blocking advisory (continue-on-error:true) so transient CI hiccups don't gate merges.
- W.2: scripts/db/check-orphans.sh sweeps real-FK + polymorphic-reference + stale-token orphans against the live DB. Live run shows 0 FK orphans (Postgres enforcement holds), 40 fundraising_activity_log polymorphic orphans (under threshold), 135 notifications.related_id (crosses threshold — flagged for human investigation), 3 stale verification_tokens.
- W.3: docs/MONEY_CONVENTION.md — integer-cents canonical, lists every legacy decimal(10,2) column to migrate later, explains float-bug class avoidance.
- W.4: docs/DISASTER_RECOVERY.md — Neon restore step-by-step, RTO<1h / RPO<5min targets, schema verification path, smoke-test checklist, quarterly drill cadence, local backup workflow.
- W.5: New audit helpers logUserDeletion (sync, critical) + logDataExport (sync, warning) + logContentDecision (buffered, info) in src/lib/auth/audit.ts. Wired into admin user-delete route + content-approval route. Export route already self-audits via raw INSERT (left alone — works).
- W.6 RECLASSIFIED — OAuth tokens in accounts table technically plaintext (Auth.js default) but app code never reads them after login (verified via grep). Real exfiltration risk minimal; provider-side revocation available. Documented in audit; encryption deferred to dedicated Auth.js-adapter-override session.

Phase X (nice-to-have quick wins):
- X.1: /api/cron/prune-audit-log + vercel.json cron entry (daily 02:00 UTC). Preserves critical-severity rows forever; prunes info/warning >180 days.
- X.2: Migration 085 — location_approvals trigger preventing UPDATE of decision fields (action/status/notes/required_changes/reviewer_id/reviewed_at). Append-only audit trail. Applied to Neon. subscription_pools.organizationId FK SKIPPED — verified no organization table exists, pools use owner_id (user FK).

Net Neon state after this commit:
  93 migrations tracked, 4 new indexes, 6 test accounts disabled, 1 trigger added.

Audit subagent overstatement pattern observed AGAIN — 3 of the original "critical" findings were overstated (plaintext API keys, subscription_pools FK, OAuth-token urgency). Documented per the audit_subagent_overflag memory pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-03 18:07:42 +02:00

3.8 KiB
Raw Permalink Blame History

Money representation — convention SSOT

Decision (2026-06-03): All new monetary columns and code should use integer cents (a/k/a "minor units"). Existing decimal(n, 2) columns stay until a dedicated migration sweeps them — documented here so no one accidentally extends the inconsistency.

Why integer cents

Representation Float math safety Storage DB-level constraints Wire format
integer cents (canonical) exact — no rounding 4 bytes trivial CHECK (amount >= 0) one number, no decimal points
decimal(10, 2) (legacy) exact in DB; rounding risk on app side if cast to float 5–14 bytes enforced precision but ambiguous on app side "12.34" string, easy to mis-parse
real / double unsafe — never use for money 4–8 bytes none scientific notation possible

Cents wins on:

  • Bug class eliminated. No 0.1 + 0.2 = 0.30000000000000004 ever. Float-to-decimal conversion at API/UI boundary is the only place where things can go wrong, and we control that boundary.
  • Trivially summable. SUM(amount_cents) is integer arithmetic; no numeric casts needed in aggregates.
  • Wire format consistent. JSON serializes as a single number; UI divides by 100 for display. No string parsing, no locale ambiguity.

The convention

  • New columns: name suffix _cents (e.g. subtotal_cents, tax_cents, donation_amount_cents).
  • Type: integer (rarely bigint — we're a Swiss nonprofit, not a hedge fund).
  • Currency: store separately in currency_code (e.g. 'CHF', 'EUR') with default 'CHF'. Don't infer currency from column name.
  • Display: divide by 100 at the formatter (formatCHF(cents) in src/config/marketplace.ts).

Existing columns that don't follow yet

These are decimal(10, 2) or similar today. They work — float-conversion bugs haven't surfaced. Leave them alone until a dedicated migration sweep:

Table.column Current type
listings.price_chf decimal(10, 2)
payment_transactions.amount decimal(10, 2)
refunds.amount decimal(10, 2)
services.price decimal(10, 2)
workshops.price decimal(10, 2)
... and ~10 more decimal(10, 2)

A future migration will:

  1. Add *_cents column alongside the old decimal column.
  2. Backfill: UPDATE tbl SET price_cents = (price_chf * 100)::int.
  3. Update app code to read from _cents.
  4. Drop the decimal column after a deprecation window.

What's already in cents (don't migrate)

  • orders.subtotal_cents
  • orders.tax_cents
  • orders.shipping_cents
  • orders.total_cents

These set the precedent. New tables should follow them.

Common mistakes to avoid

// WRONG — float math on decimals
const total = items.reduce((sum, item) => sum + item.price_chf, 0)
// 0.1 + 0.2 problem; .toFixed(2) hides bugs at scale.

// RIGHT — integer math on cents
const totalCents = items.reduce((sum, item) => sum + item.price_cents, 0)
const totalDisplay = formatCHF(totalCents)  // formatter handles /100
// WRONG — letting a decimal column flow through JS as a number
const price = Number(row.price_chf)  // string "12.34" → 12.34, but parse risk

// RIGHT — explicit conversion at boundary, use cents internally
const priceCents = Math.round(Number(row.price_chf) * 100)

Validation at API boundary

When accepting monetary input from a form / API:

const schema = z.object({
  // Accept either decimal CHF (UI convenience) or cents (API native).
  // Store as cents internally.
  amount_cents: z.number().int().min(0),
})

If the UI sends CHF as a decimal, convert at the boundary:

amount_cents: Math.round(amountChf * 100)

Never let 0.1 + 0.2 math survive past the API layer.


Last updated: 2026-06-03 — convention established; sweep migration not yet scheduled.