Skip to content

Commit be390f7

Browse files
committed
feat(rest, client): a tenant-admin REST door for the record-currency code backfill
POST /meta/_migrate-record-currency-codes runs backfillRecordCurrencyCodes for the caller's current organization only, gated on setup.write and mounted behind metadata.endpoints.maintenance; preview unless apply is true. Adds the SDK method, the REST route-ledger row, the objectql barrel re-export of the two organization report types, the 409 remedy naming the door, and a truncated walk that no longer claims every row was examined. Claude-Session: https://claude.ai/code/session_016WV4cyrhYJgbkZHbbqud3F Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1371b9d commit be390f7

13 files changed

Lines changed: 690 additions & 5 deletions

‎packages/cli/src/commands/migrate/record-currency-codes.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,13 @@ export default class MigrateRecordCurrencyCodes extends Command {
304304

305305
if (report.failures.length > 0) {
306306
printError(`${report.failures.length} row(s) could not be written — re-run to finish them.`);
307+
} else if (report.truncated) {
308+
// The cap cut the walk short: neither "done" nor "nothing to do" is known.
309+
printWarning(
310+
`Walk incomplete — ${report.scannedRecords} row(s) examined, ${report.codeless} codeless` +
311+
(apply ? `, ${report.written} written` : '') +
312+
'. Re-run without --max-records (or with a higher one) to finish.',
313+
);
307314
} else if (apply && report.written > 0) {
308315
printSuccess(
309316
`Wrote ${report.code} on ${report.written} row(s). ` +

‎packages/client/src/index.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2201,6 +2201,9 @@ export class ObjectStackClient {
22012201
* which is not a dependency of this package, and a second declaration in
22022202
* spec would drift against the CLI that renders the same report. Its two
22032203
* ledger rows carry the same note. ⛔ Do not re-declare it here.
2204+
* `migrateRecordCurrencyCodes`, added after the ruling, stays unbound for
2205+
* the same reason (its report type lives in `@objectstack/objectql`) and
2206+
* answers `unknown`, which the caller narrows.
22042207
*/
22052208

22062209
/**
@@ -2270,6 +2273,50 @@ export class ObjectStackClient {
22702273
return this.unwrapResponse<any>(res);
22712274
},
22722275

2276+
/**
2277+
* ADR-0144: write a currency code into the rows of a `record`-mode amount
2278+
* that hold an amount beside a blank code — the rows stored before the
2279+
* field was switched to `currencyMode: 'record'`. The server-side form of
2280+
* `os migrate record-currency-codes`, for an organization admin with no
2281+
* shell on the deployment's database.
2282+
*
2283+
* **Your current organization only.** The server fills the rows of the
2284+
* caller's current organization and no other; there is no
2285+
* environment-wide form and no organization parameter (each organization
2286+
* has its own home currency). `code` is the one you give, never derived.
2287+
*
2288+
* **Preview by default.** Without `apply: true` it reports what it would
2289+
* write and writes nothing; the report is the one the CLI's `--json`
2290+
* prints (`@objectstack/objectql`'s `RecordCurrencyBackfillReport`:
2291+
* `scannedRecords` / `codeless` / `written` / the two skip counts,
2292+
* `sampleRecordIds`, `applied`, `truncated`, `failures`, `organizations`).
2293+
* `truncated: true` means the walk stopped at its row cap and some rows
2294+
* were not examined.
2295+
*
2296+
* Requires `setup.write` in the current organization (403 otherwise).
2297+
*
2298+
* Unbound for the reason `migrateStored` above is (ruling 2C): the
2299+
* report's named type lives in `@objectstack/objectql`, which this
2300+
* package does not depend on. ⛔ Do not re-declare it here. Answered as
2301+
* `unknown`, not `any`: a new `any` return is refused by
2302+
* `check:exported-any-returns` (`exported-any-returns.json` is
2303+
* shrink-only), and `unknown` makes the caller narrow, as `getPublished`
2304+
* does under ruling 1C.
2305+
*/
2306+
migrateRecordCurrencyCodes: async (opts: { object: string; field: string; code: string; apply?: boolean }) => {
2307+
const route = this.getRoute('metadata');
2308+
const res = await this.fetch(`${this.baseUrl}${route}/_migrate-record-currency-codes`, {
2309+
method: 'POST',
2310+
body: JSON.stringify({
2311+
object: opts.object,
2312+
field: opts.field,
2313+
code: opts.code,
2314+
...(opts.apply === true ? { apply: true } : {}),
2315+
}),
2316+
});
2317+
return this.unwrapResponse<unknown>(res);
2318+
},
2319+
22732320
/**
22742321
* ADR-0020 D3.3 FSM introspection: the legal next states for `field`
22752322
* from state `from`, per the object's `state_machine` validation rule.

‎packages/client/src/meta-automation-descriptors.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,27 @@ describe('client.automation descriptors (#3563 PR-5)', () => {
110110
expect(out.flows[0].bound).toBe(true);
111111
});
112112
});
113+
114+
describe('client.meta.migrateRecordCurrencyCodes (ADR-0144 record-currency code backfill)', () => {
115+
it('POSTs the three names to the backfill door, a preview unless apply is true', async () => {
116+
const report = { object: 'deal', organizationId: 'org_a', codeless: 2, written: 0, applied: false, truncated: false };
117+
const { client, fetchMock } = createMockClient(report);
118+
const out = await client.meta.migrateRecordCurrencyCodes({ object: 'deal', field: 'amount', code: 'USD' });
119+
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/v1/meta/_migrate-record-currency-codes');
120+
expect(fetchMock.mock.calls[0][1]?.method).toBe('POST');
121+
expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({ object: 'deal', field: 'amount', code: 'USD' });
122+
// The REST door answers the report BARE; it reaches the caller as it was sent.
123+
expect(out).toEqual(report);
124+
});
125+
126+
it('sends apply only when it is true, and never an organization', async () => {
127+
const { client, fetchMock } = createMockClient({ applied: true });
128+
await client.meta.migrateRecordCurrencyCodes({ object: 'deal', field: 'amount', code: 'USD', apply: true });
129+
await client.meta.migrateRecordCurrencyCodes({ object: 'deal', field: 'amount', code: 'USD', apply: false });
130+
const bodies = fetchMock.mock.calls.map((c: unknown[]) => JSON.parse(String((c[1] as { body?: unknown })?.body)));
131+
expect(bodies).toEqual([
132+
{ object: 'deal', field: 'amount', code: 'USD', apply: true },
133+
{ object: 'deal', field: 'amount', code: 'USD' },
134+
]);
135+
});
136+
});

‎packages/client/src/return-type-precision.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,10 @@ export async function returnTypePrecisionPins12038(): Promise<void> {
428428
// which this package does not depend on. Pinned so a well-meaning sweep
429429
// does not "fix" it against the ruling.
430430
expectTypeOf(await client.meta.migrateStored()).toBeAny();
431+
// `migrateRecordCurrencyCodes` is unbound for the same reason (its report
432+
// type lives in `@objectstack/objectql`), but answers `unknown`, not `any`:
433+
// the caller narrows, and `exported-any-returns.json` stays shrink-only.
434+
expectTypeOf(await client.meta.migrateRecordCurrencyCodes({ object: 'deal', field: 'amount', code: 'USD' })).toEqualTypeOf<unknown>();
431435

432436
// ── the packages.* eight ──────────────────────────────────────────────
433437
expectTypeOf(await client.packages.publish('com.acme.crm')).toEqualTypeOf<PackagePublishResult>();

‎packages/metadata-protocol/src/protocol-write-face.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,9 @@ function detectDestructiveObjectChanges(prev: any, next: any): Array<{
253253
+ 'display as a plain number, fall into the null group of a grouped aggregate, and sit outside every '
254254
+ 'currency-paired filter until they hold a code; once saved, write it with '
255255
+ `\`os migrate record-currency-codes --object ${objectName} --field ${fname} --code <ISO 4217 code>\``
256-
+ ' (a dry run; add --apply to write).',
256+
+ ' (a dry run; add --apply to write), or, with no shell, as an organization admin with '
257+
+ `\`POST /api/v1/meta/_migrate-record-currency-codes\` and the body \`{ "object": "${objectName}", "field": "${fname}", "code": "<ISO 4217 code>" }\``
258+
+ ' (a preview of your current organization\'s rows; add "apply": true to write).',
257259
});
258260
}
259261
}

‎packages/objectql/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,8 @@ export type {
565565
RecordCurrencyBackfillEngine,
566566
RecordCurrencyBackfillLogger,
567567
RecordCurrencyBackfillOptions,
568+
RecordCurrencyBackfillOrganization,
569+
RecordCurrencyBackfillOrganizationsRefusal,
568570
} from './record-currency-backfill.js';
569571
// [ADR-0144 D5, D7 parameter 1, Open item 8] The explicit recompute of stored
570572
// home amounts behind `os migrate recompute-home-amounts`: the write's own

‎packages/objectql/src/record-currency-backfill.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,12 @@ export function formatRecordCurrencyBackfillReport(report: RecordCurrencyBackfil
462462
}
463463
}
464464
if (report.codeless === 0) {
465-
lines.push(`✓ Every ${pair} amount already has its currency code — nothing to backfill.`);
465+
// A walk the cap cut short saw only some rows, so it cannot say "every".
466+
lines.push(
467+
report.truncated
468+
? `No codeless ${pair} amount among the ${report.scannedRecords} row(s) examined.`
469+
: `✓ Every ${pair} amount already has its currency code — nothing to backfill.`,
470+
);
466471
} else {
467472
lines.push(
468473
report.applied
@@ -485,6 +490,14 @@ export function formatRecordCurrencyBackfillReport(report: RecordCurrencyBackfil
485490
}
486491
if (report.truncated) {
487492
lines.push('⚠ Walk incomplete — some rows were not examined; re-run without the cap to finish.');
493+
// An unscoped run judged "one organization" from the rows it examined: the
494+
// rows past the cap were never checked for another organization's.
495+
if (report.organizationId === null && !report.allOrganizations) {
496+
lines.push(
497+
' The organization check saw only the rows examined: rows past the cap may belong to another ' +
498+
'organization, so name the organization (one run per organization) before writing.',
499+
);
500+
}
488501
}
489502
// Claims no row or table, never that nothing was written: the command that
490503
// prints it boots through the driver's connect, which can switch a SQLite

0 commit comments

Comments
 (0)