import { nanoid } from 'nanoid' import * as Runtime from '../../../test/runtime.js' import * as Db from '../Db.js' import * as Organizations from './organizations.js' import * as RoutesSubsidies from './routesSubsidies.js' const create = () => Db.postgres({ connectionString: Runtime.postgresUrl, schema: `t_${nanoid()}` }) describe('getOrganization', () => { test('behavior: reads an enabled policy', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) await RoutesSubsidies.upsertOrganization(db, { frequency: 'tx', maxAmount: '5', orgId: 'org_1', }) expect(await RoutesSubsidies.getOrganization(db, 'org_1')).toMatchObject({ enabled: true, frequency: 'tx', maxAmount: '5', orgId: 'org_1', }) await db.close() }) }) describe('upsertOrganization', () => { test('behavior: creates and replaces the organization policy', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) vi.useFakeTimers() try { vi.setSystemTime(new Date('2026-09-01T00:00:00.000Z')) const created = await RoutesSubsidies.upsertOrganization(db, { frequency: 'tx', maxAmount: '5', orgId: 'org_1', }) vi.setSystemTime(new Date('2026-09-02T00:00:00.000Z')) const updated = await RoutesSubsidies.upsertOrganization(db, { frequency: 'tx', maxAmount: '25.50', orgId: 'org_1', }) expect({ created: created.maxAmount, createdAt: updated.createdAt, frequency: updated.frequency, updated: updated.maxAmount, updatedAt: updated.updatedAt, }).toMatchInlineSnapshot(` { "created": "5", "createdAt": "2026-09-01T00:00:00.000Z", "frequency": "tx", "updated": "25.50", "updatedAt": "2026-09-02T00:00:00.000Z", } `) } finally { vi.useRealTimers() await db.close() } }) }) describe('removeOrganization', () => { test('behavior: removes an enabled policy', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) await RoutesSubsidies.upsertOrganization(db, { frequency: 'tx', maxAmount: '5', orgId: 'org_1', }) expect(await RoutesSubsidies.removeOrganization(db, 'org_1')).toBe(true) expect(await RoutesSubsidies.getOrganization(db, 'org_1')).toBeUndefined() await db.close() }) }) describe('policy storage', () => { test('behavior: rejects inconsistent or invalid amounts', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) const now = new Date().toISOString() try { for (const policy of [ { enabled: false, maxAmount: '5' }, { enabled: true, maxAmount: null }, { enabled: true, maxAmount: '0' }, { enabled: true, maxAmount: '1.0000001' }, ]) await expect( db.kysely .insertInto('routes_subsidies') .values({ createdAt: now, enabled: policy.enabled, frequency: 'tx', maxAmount: policy.maxAmount, orgId: 'org_1', updatedAt: now, }) .execute(), ).rejects.toThrow() } finally { await db.close() } }) })