Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions apps/backend/prisma/generated/prisma/internal/class.ts

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -3042,6 +3042,7 @@ export const PaymentMethodScalarFieldEnum = {
color: 'color',
initialBalance: 'initialBalance',
currentBalance: 'currentBalance',
currency: 'currency',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
Expand Down Expand Up @@ -3074,6 +3075,7 @@ export const UserScalarFieldEnum = {
lastName: 'lastName',
image: 'image',
emailVerified: 'emailVerified',
reportingCurrency: 'reportingCurrency',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
Expand Down Expand Up @@ -3192,6 +3194,9 @@ export const TransactionScalarFieldEnum = {
type: 'type',
status: 'status',
value: 'value',
currency: 'currency',
exchangeRate: 'exchangeRate',
settledValue: 'settledValue',
rejectionReason: 'rejectionReason',
recordedAt: 'recordedAt',
deletedAt: 'deletedAt',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,7 @@ export const PaymentMethodScalarFieldEnum = {
color: 'color',
initialBalance: 'initialBalance',
currentBalance: 'currentBalance',
currency: 'currency',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
Expand Down Expand Up @@ -407,6 +408,7 @@ export const UserScalarFieldEnum = {
lastName: 'lastName',
image: 'image',
emailVerified: 'emailVerified',
reportingCurrency: 'reportingCurrency',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
Expand Down Expand Up @@ -525,6 +527,9 @@ export const TransactionScalarFieldEnum = {
type: 'type',
status: 'status',
value: 'value',
currency: 'currency',
exchangeRate: 'exchangeRate',
settledValue: 'settledValue',
rejectionReason: 'rejectionReason',
recordedAt: 'recordedAt',
deletedAt: 'deletedAt',
Expand Down
41 changes: 40 additions & 1 deletion apps/backend/prisma/generated/prisma/models/PaymentMethod.ts

Large diffs are not rendered by default.

191 changes: 190 additions & 1 deletion apps/backend/prisma/generated/prisma/models/Transaction.ts

Large diffs are not rendered by default.

110 changes: 109 additions & 1 deletion apps/backend/prisma/generated/prisma/models/User.ts

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
-- Multi-currency columns. Columns and backfill only: nothing in the application
-- reads or writes these yet. All behaviour -- rate lookup, normalisation on the
-- write path, mixed-currency aggregates -- lands in a later change.
--
-- A receipt's currency and the currency the payment settled in can differ (a USD
-- receipt paid with a EUR card), so the dashboard needs a single normalisation
-- target per user.
--
-- EXCHANGE RATE DIRECTION, fixed here so it can never be guessed at later:
-- "transaction"."exchange_rate" is units of the SETTLEMENT currency
-- (the owning "payment_method"."currency") per ONE unit of
-- "transaction"."currency", such that
--
-- settled_value = value * exchange_rate
--
-- NULL PAYMENT METHOD: "transaction"."payment_method_id" is nullable and nulls
-- out on payment-method deletion, so a transaction can have no settlement
-- currency. When "payment_method_id" IS NULL the settlement currency IS the
-- transaction currency, therefore "exchange_rate" = 1 and
-- "settled_value" = "value". The same rule applies whenever the two currencies
-- are equal. The write path must never leave "exchange_rate" NULL on a row it
-- touched: NULL means only "this row pre-dates multi-currency".
--
-- "settled_value" is stored, never recomputed, so historical totals do not drift
-- when rates move and survive the deletion of the payment method.
--
-- Columns 2-5 land NULLABLE on purpose. This is the expand step; the contract
-- step that makes them NOT NULL belongs in a later migration, once the write
-- path always populates them.

-- ---------------------------------------------------------------------------
-- Deploy-time parameter. THIS IS THE ONLY PLACE THE CURRENCY IS NAMED.
-- Change this one literal to deploy into a market that is not the euro area.
-- ---------------------------------------------------------------------------

CREATE TABLE "_currency_backfill_parameter" (
"reporting_currency" CHAR(3) NOT NULL
);

INSERT INTO "_currency_backfill_parameter" ("reporting_currency") VALUES ('EUR');

-- ---------------------------------------------------------------------------
-- 1. users.reporting_currency -- from the deploy-time parameter.
-- NOT NULL with deliberately NO schema default: a default would silently
-- re-introduce a hardcoded currency and let the registration flow forget to
-- choose one. Added nullable, backfilled, then constrained.
-- ---------------------------------------------------------------------------

ALTER TABLE "users" ADD COLUMN "reporting_currency" CHAR(3);

UPDATE "users"
SET "reporting_currency" = (SELECT "reporting_currency" FROM "_currency_backfill_parameter");

ALTER TABLE "users" ALTER COLUMN "reporting_currency" SET NOT NULL;

-- ---------------------------------------------------------------------------
-- 2. payment_method.currency -- the settlement currency of the instrument.
-- Read from the value written in step 1, not from the parameter, so a later
-- correction to one user's reporting currency has a single source.
-- ---------------------------------------------------------------------------

ALTER TABLE "payment_method" ADD COLUMN "currency" CHAR(3);

UPDATE "payment_method" pm
SET "currency" = u."reporting_currency"
FROM "users" u
WHERE u."id" = pm."user_id";

-- ---------------------------------------------------------------------------
-- 3. transaction.currency -- the currency the amount was recorded or receipted
-- in. NOT the settlement currency. Also read from step 1's value.
-- ---------------------------------------------------------------------------

ALTER TABLE "transaction" ADD COLUMN "currency" CHAR(3);

UPDATE "transaction" t
SET "currency" = u."reporting_currency"
FROM "users" u
WHERE u."id" = t."user_id";

-- ---------------------------------------------------------------------------
-- 4. transaction.exchange_rate -- exactly 1 for every existing row: after
-- steps 2 and 3 the transaction currency and the settlement currency are
-- equal by construction, and rows with no payment method follow the same
-- rule.
-- ---------------------------------------------------------------------------

ALTER TABLE "transaction" ADD COLUMN "exchange_rate" DECIMAL(18,8);

UPDATE "transaction" SET "exchange_rate" = 1;

-- ---------------------------------------------------------------------------
-- 5. transaction.settled_value -- equal to value for every existing row, which
-- is what settled_value = value * exchange_rate yields at a rate of 1.
-- ---------------------------------------------------------------------------

ALTER TABLE "transaction" ADD COLUMN "settled_value" DECIMAL(12,2);

UPDATE "transaction" SET "settled_value" = "value";

-- ---------------------------------------------------------------------------
-- Assert the backfill was total. Every payment_method and every transaction has
-- a NOT NULL user_id behind a foreign key, so there is no row the joins above
-- could legitimately have missed.
-- ---------------------------------------------------------------------------

DO $$
DECLARE
"missing" BIGINT;
BEGIN
SELECT COUNT(*) INTO "missing" FROM "payment_method" WHERE "currency" IS NULL;
IF "missing" > 0 THEN
RAISE EXCEPTION 'currency backfill: % payment methods have no currency', "missing";
END IF;

SELECT COUNT(*) INTO "missing" FROM "transaction" WHERE "currency" IS NULL;
IF "missing" > 0 THEN
RAISE EXCEPTION 'currency backfill: % transactions have no currency', "missing";
END IF;

SELECT COUNT(*) INTO "missing" FROM "transaction" WHERE "exchange_rate" IS NULL;
IF "missing" > 0 THEN
RAISE EXCEPTION 'currency backfill: % transactions have no exchange rate', "missing";
END IF;

SELECT COUNT(*) INTO "missing" FROM "transaction" WHERE "settled_value" IS NULL;
IF "missing" > 0 THEN
RAISE EXCEPTION 'currency backfill: % transactions have no settled value', "missing";
END IF;

SELECT COUNT(*) INTO "missing"
FROM "transaction"
WHERE "settled_value" <> "value" * "exchange_rate";
IF "missing" > 0 THEN
RAISE EXCEPTION 'currency backfill: % transactions break settled_value = value * exchange_rate', "missing";
END IF;
END $$;

-- ---------------------------------------------------------------------------
-- ISO 4217 shape. Prisma cannot express these, so they live only here.
-- CHAR(3) is blank-padded, and the regex operator strips the padding, so a
-- two-letter code fails as surely as a lowercase one.
-- ---------------------------------------------------------------------------

ALTER TABLE "users" ADD CONSTRAINT "users_reporting_currency_check"
CHECK ("reporting_currency" ~ '^[A-Z]{3}$');

ALTER TABLE "payment_method" ADD CONSTRAINT "payment_method_currency_check"
CHECK ("currency" ~ '^[A-Z]{3}$');

ALTER TABLE "transaction" ADD CONSTRAINT "transaction_currency_check"
CHECK ("currency" ~ '^[A-Z]{3}$');

DROP TABLE "_currency_backfill_parameter";
1 change: 1 addition & 0 deletions apps/backend/prisma/schema/payment-method.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ model PaymentMethod {
color String @default("#6366F1")
initialBalance Decimal @default(0) @map("initial_balance") @db.Decimal(12, 2)
currentBalance Decimal @default(0) @map("current_balance") @db.Decimal(12, 2)
currency String? @db.Char(3)

user User @relation(fields: [userId], references: [id], onDelete: Cascade)
transactions Transaction[]
Expand Down
2 changes: 2 additions & 0 deletions apps/backend/prisma/schema/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ model User {

emailVerified Boolean @default(false) @map("email_verified")

reportingCurrency String @map("reporting_currency") @db.Char(3)

transactions Transaction[]
accounts Account[]
sessions Session[]
Expand Down
3 changes: 3 additions & 0 deletions apps/backend/prisma/schema/transaction.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ model Transaction {
type TransactionType
status TransactionStatus @default(CONFIRMED) @map("status")
value Decimal @db.Decimal(12, 2)
currency String? @db.Char(3)
exchangeRate Decimal? @map("exchange_rate") @db.Decimal(18, 8)
settledValue Decimal? @map("settled_value") @db.Decimal(12, 2)
rejectionReason String? @map("rejection_reason")

recordedAt DateTime @default(now()) @map("recorded_at")
Expand Down
113 changes: 113 additions & 0 deletions apps/backend/src/common/prisma/prisma-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ function migrationNames(): string[] {
.sort();
}

function migrationSql(name: string): string {
return readFileSync(join(MIGRATIONS_DIR, name, 'migration.sql'), 'utf8');
}

function allMigrationSql(): string {
return readdirSync(MIGRATIONS_DIR)
.filter((entry) => entry !== 'migration_lock.toml')
Expand Down Expand Up @@ -213,4 +217,113 @@ describe('prisma schema', () => {
expect(audit).toContain('actor User @relation');
});
});

describe('multi-currency columns', () => {
const CURRENCY_MIGRATION = '20260909037000_add_currency_columns';

it('gives a user a reporting currency that is required and undefaulted', () => {
const user = schema('schema.prisma').split('model User {')[1];
expect(user).toMatch(
/reportingCurrency String @map\("reporting_currency"\) @db\.Char\(3\)/,
);
expect(user).not.toMatch(/reportingCurrency[^\n]*@default/);
});

const nullableCurrencies: [string, RegExp][] = [
['payment-method.prisma', /currency\s+String\?\s+@db\.Char\(3\)/],
['transaction.prisma', /currency\s+String\?\s+@db\.Char\(3\)/],
];

it.each(nullableCurrencies)(
'leaves %s currency nullable',
(file, pattern) => {
expect(schema(file)).toMatch(pattern);
},
);

it('stores the rate at eight decimals and the settled value at two', () => {
const transaction = schema('transaction.prisma');
expect(transaction).toMatch(
/exchangeRate\s+Decimal\?\s+@map\("exchange_rate"\) @db\.Decimal\(18, 8\)/,
);
expect(transaction).toMatch(
/settledValue\s+Decimal\?\s+@map\("settled_value"\) @db\.Decimal\(12, 2\)/,
);
});

it('lands between the category re-ownership and the income store drop', () => {
const names = migrationNames();
expect(names.indexOf(CURRENCY_MIGRATION)).toBeGreaterThan(
names.indexOf('20260909036000_own_categories_and_items'),
);
expect(names.indexOf(CURRENCY_MIGRATION)).toBeLessThan(
names.indexOf('20260909040000_drop_income_store_id'),
);
});

it('names the deploy-time currency exactly once', () => {
expect(migrationSql(CURRENCY_MIGRATION).match(/'EUR'/g)).toHaveLength(1);
});

it('backfills in the order the rollout depends on', () => {
const sql = migrationSql(CURRENCY_MIGRATION);
const steps = [
'SET "reporting_currency" = (SELECT "reporting_currency" FROM "_currency_backfill_parameter")',
'UPDATE "payment_method" pm',
'UPDATE "transaction" t',
'UPDATE "transaction" SET "exchange_rate" = 1;',
'UPDATE "transaction" SET "settled_value" = "value";',
].map((step) => sql.indexOf(step));

expect(steps).not.toContain(-1);
expect([...steps].sort((a, b) => a - b)).toEqual(steps);
});

it('derives the dependent currencies from the user row, not the parameter', () => {
const sql = migrationSql(CURRENCY_MIGRATION);
const derived = sql.match(/SET "currency" = u\."reporting_currency"/g);

expect(derived).toHaveLength(2);
expect(sql.match(/FROM "_currency_backfill_parameter"/g)).toHaveLength(1);
});

it('requires the user reporting currency after the backfill', () => {
expect(migrationSql(CURRENCY_MIGRATION)).toContain(
'ALTER TABLE "users" ALTER COLUMN "reporting_currency" SET NOT NULL',
);
});

const currencyChecks: [string, string][] = [
['users_reporting_currency_check', 'reporting_currency'],
['payment_method_currency_check', 'currency'],
['transaction_currency_check', 'currency'],
];

it.each(currencyChecks)(
'constrains %s to an ISO 4217 shape',
(name, column) => {
const sql = migrationSql(CURRENCY_MIGRATION);
expect(sql).toContain(`CONSTRAINT "${name}"`);
expect(sql).toContain(`CHECK ("${column}" ~ '^[A-Z]{3}$')`);
},
);

it('pins the exchange rate direction in the migration itself', () => {
expect(migrationSql(CURRENCY_MIGRATION)).toContain(
'settled_value = value * exchange_rate',
);
});

it('states the rule for a transaction with no payment method', () => {
const sql = migrationSql(CURRENCY_MIGRATION);
expect(sql).toContain('NULL PAYMENT METHOD');
expect(sql).toContain('the settlement currency IS the');
});

it('adds no index on any currency column', () => {
expect(migrationSql(CURRENCY_MIGRATION)).not.toMatch(
/CREATE\s+(UNIQUE\s+)?INDEX[^;]*currency/i,
);
});
});
});
13 changes: 7 additions & 6 deletions plans/phase-3a-schema-rollout.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ That makes the drop pure cleanup, safe to run after the new code is live.
### The combined sequence, across all phase 3 branches

A deployer runs these as one set, so this is the whole order, not just this
branch's. Two of them are authored on `review/phase-3b-category-ownership` and
are listed here for ordering only — their content, backfills and rollback are
that branch's to document.
branch's. Two of them are authored on other branches and are listed here for
ordering only — their content, backfills and rollback are those branches' to
document: `20260909036000` in `plans/phase-3b-category-ownership-rollout.md`,
and `20260909037000` in `plans/phase-3c-currency-rollout.md`.

| Migration | Branch | When |
|---|---|---|
Expand All @@ -61,7 +62,7 @@ that branch's to document.
| `20260909034000_fix_basket_uniqueness` | 3a (this one) | **before** deploy |
| `20260909035000_add_soft_delete_and_audit_log` | 3a (this one) | **before** deploy |
| `20260909036000_own_categories_and_items` | 3b — category re-ownership | **before** deploy |
| `20260909037000_add_currency_columns` | reserved, not yet authored | **before** deploy |
| `20260909037000_add_currency_columns` | 3c — multi-currency columns | **before** deploy |
| `20260909040000_drop_income_store_id` | 3a (this one) | **AFTER** deploy |

The gap between `037000` and `040000` is deliberate: it is a visible break
Expand Down Expand Up @@ -213,8 +214,8 @@ code depends on. It does not stop `migrate deploy` from running it in the same
pass — see "Keeping the drop out of the pre-deploy run" above for that.

This table covers this branch's six migrations. `20260909036000_own_categories_and_items`
and the reserved `20260909037000` come from other branches and slot in between
groups 2 and 3; see the combined sequence above.
and `20260909037000_add_currency_columns` come from other branches and slot in
between groups 2 and 3; see the combined sequence above.

| # | Migration | Group | Rewrites a table? | Lock | Reversible? |
|---|---|---|---|---|---|
Expand Down
Loading