import { nanoid } from 'nanoid' import * as Runtime from '../../../test/runtime.js' import * as Webhooks from '../../internal/Webhooks.js' import * as Viem from '../../internal/Viem.js' import * as Db from '../Db.js' import * as EnabledBillingSources from './enabledBillingSources.js' import * as Memberships from './memberships.js' import * as Organizations from './organizations.js' import * as SponsoredTransactions from './sponsoredTransactions.js' import * as StripeCustomers from './stripeCustomers.js' const create = () => Db.postgres({ connectionString: Runtime.postgresUrl, schema: `t_${nanoid()}` }) /** Redacts nondeterministic row fields (generated nanoid ids, timestamps). */ function redact(record: Organizations.Record) { return { ...record, createdAt: '', id: /^org_[0-9A-Za-z]{24}$/.test(record.id) ? 'org_' : record.id, updatedAt: '', } } describe('create', () => { test('behavior: inserts with a generated id and defaults', async () => { const db = create() await db.migrate() const record = await Organizations.create(db, { name: 'Acme, Inc.' }) expect(record.id).toMatch(/^org_/) expect(redact(record)).toMatchInlineSnapshot(` { "createdAt": "", "createdBy": null, "id": "org_", "name": "Acme, Inc.", "sponsorshipSubsidyDurationDays": null, "sponsorshipSubsidyProjectSpendLimit": null, "updatedAt": "", "userId": null, } `) await db.close() }) test('behavior: preserves an explicit id and createdBy', async () => { const db = create() await db.migrate() const record = await Organizations.create(db, { createdBy: 'admin@tempo.xyz', id: 'org_explicit', name: 'Explicit', }) expect(redact(record)).toMatchInlineSnapshot(` { "createdAt": "", "createdBy": "admin@tempo.xyz", "id": "org_explicit", "name": "Explicit", "sponsorshipSubsidyDurationDays": null, "sponsorshipSubsidyProjectSpendLimit": null, "updatedAt": "", "userId": null, } `) await db.close() }) }) describe('createOwned', () => { test('behavior: creates the organization, owner, and enabled sources atomically', async () => { const db = create() await db.migrate() const record = await Organizations.createOwned(db, { enabledBillingSources: ['stripe'], name: 'Acme, Inc.', userId: 'usr_owner', }) expect( (await Memberships.listByOrg(db, record.id)).map(({ role, userId }) => ({ role, userId })), ).toMatchInlineSnapshot(` [ { "role": "owner", "userId": "usr_owner", }, ] `) expect( (await EnabledBillingSources.listByOrg(db, record.id)).map(({ createdBy, source }) => ({ createdBy, source, })), ).toMatchInlineSnapshot(` [ { "createdBy": "usr_owner", "source": "stripe", }, ] `) await db.close() }) test('behavior: rolls back all rows when initial source insertion fails', async () => { const db = create() await db.migrate() await expect( Organizations.createOwned(db, { enabledBillingSources: ['stripe', 'stripe'], name: 'Acme, Inc.', userId: 'usr_owner', }), ).rejects.toThrow() expect(await Organizations.listByUser(db, 'usr_owner')).toEqual([]) expect(await db.kysely.selectFrom('enabled_billing_sources').selectAll().execute()).toEqual([]) expect( await db.kysely .selectFrom('memberships') .selectAll() .where('userId', '=', 'usr_owner') .execute(), ).toEqual([]) await db.close() }) }) describe('get', () => { test('behavior: returns undefined when absent', async () => { const db = create() await db.migrate() expect(await Organizations.get(db, 'org_missing')).toBeUndefined() await db.close() }) }) describe('list', () => { test('behavior: lists newest first', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_a', name: 'A' }) // Distinct createdAt for a deterministic order. await new Promise((resolve) => setTimeout(resolve, 5)) await Organizations.create(db, { id: 'org_b', name: 'B' }) expect((await Organizations.list(db)).map((record) => record.id)).toMatchInlineSnapshot(` [ "org_b", "org_a", ] `) await db.close() }) }) describe('update', () => { test('behavior: renames and bumps updatedAt', async () => { const db = create() await db.migrate() const created = await Organizations.create(db, { id: 'org_1', name: 'Before' }) await new Promise((resolve) => setTimeout(resolve, 5)) const updated = await Organizations.update(db, 'org_1', { name: 'After' }) expect(updated?.name).toMatchInlineSnapshot(`"After"`) expect(updated && updated.updatedAt > created.updatedAt).toBe(true) await db.close() }) test('behavior: returns undefined when absent', async () => { const db = create() await db.migrate() expect(await Organizations.update(db, 'org_missing', { name: 'X' })).toBeUndefined() await db.close() }) }) describe('setSponsorshipSubsidy', () => { test('behavior: replaces and disables the organization policy', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) const enabled = await Organizations.setSponsorshipSubsidy(db, 'org_1', { durationDays: 90, projectSpendLimit: '100.00', }) expect({ durationDays: enabled?.sponsorshipSubsidyDurationDays, projectSpendLimit: enabled?.sponsorshipSubsidyProjectSpendLimit, }).toMatchInlineSnapshot(` { "durationDays": 90, "projectSpendLimit": "100.00", } `) const disabled = await Organizations.setSponsorshipSubsidy(db, 'org_1', { durationDays: null, projectSpendLimit: null, }) expect({ durationDays: disabled?.sponsorshipSubsidyDurationDays, projectSpendLimit: disabled?.sponsorshipSubsidyProjectSpendLimit, }).toMatchInlineSnapshot(` { "durationDays": null, "projectSpendLimit": null, } `) await db.close() }) }) describe('upsert', () => { test('behavior: inserts when absent, defaulting name to the id', async () => { const db = create() await db.migrate() await Organizations.upsert(db, { id: 'key_fallback' }) expect((await Organizations.get(db, 'key_fallback'))?.name).toMatchInlineSnapshot( `"key_fallback"`, ) await db.close() }) test('behavior: leaves an existing row untouched', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'Original' }) await Organizations.upsert(db, { id: 'org_1', name: 'Clobbered' }) expect((await Organizations.get(db, 'org_1'))?.name).toMatchInlineSnapshot(`"Original"`) await db.close() }) }) describe('deleteOrganization', () => { test('behavior: preserves an org with unreported billable sponsorships', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) await StripeCustomers.create(db, { orgId: 'org_1', stripeCustomerId: 'cus_org_1', }) await EnabledBillingSources.add(db, { createdBy: 'admin@tempo.xyz', orgId: 'org_1', source: 'stripe', }) await SponsoredTransactions.upsert(db, { apiKeyId: 'key_1', billable: true, chainId: 4217, environment: 'production', orgId: 'org_1', projectId: 'prj_1', signPayload: `0x${'bb'.repeat(32)}`, transaction: `0x76${'cc'.repeat(16)}`, transactionHash: `0x${'aa'.repeat(32)}`, }) expect(await Organizations.hasUnreportedSponsorships(db, 'org_1')).toBe(true) await expect(Organizations.deleteOrganization(db, 'org_1')).rejects.toThrow( Organizations.UnreportedSponsorshipsError, ) expect(await Organizations.get(db, 'org_1')).toBeDefined() expect(await EnabledBillingSources.isEnabled(db, { orgId: 'org_1', source: 'stripe' })).toBe( true, ) expect(await StripeCustomers.get(db, 'org_1')).toBeDefined() await db.close() }) test('behavior: deletes an org with only failed or non-mainnet sponsorships', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) const failed = await SponsoredTransactions.upsert(db, { apiKeyId: 'key_1', billable: true, chainId: Viem.chainId.mainnet, environment: 'production', orgId: 'org_1', projectId: 'prj_1', signPayload: `0x${'bb'.repeat(32)}`, transaction: `0x76${'cc'.repeat(16)}`, transactionHash: `0x${'aa'.repeat(32)}`, }) await SponsoredTransactions.fail(db, failed.id, '2026-01-01T00:00:00.000Z') const testnet = await SponsoredTransactions.upsert(db, { apiKeyId: 'key_1', billable: true, chainId: Viem.chainId.testnet, environment: 'production', orgId: 'org_1', projectId: 'prj_1', signPayload: `0x${'dd'.repeat(32)}`, transaction: `0x76${'ee'.repeat(16)}`, transactionHash: `0x${'ff'.repeat(32)}`, }) await SponsoredTransactions.finalize(db, testnet.id, { feeAmount: '100', finalizedAt: '2026-01-01T00:00:00.000Z', }) expect(await Organizations.hasUnreportedSponsorships(db, 'org_1')).toBe(false) expect(await Organizations.deleteOrganization(db, 'org_1')).toBe(true) await db.close() }) test('behavior: preserves an org with a recoverable failed fill intent', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) const failed = await SponsoredTransactions.upsert(db, { apiKeyId: 'key_1', billable: true, chainId: Viem.chainId.mainnet, environment: 'production', orgId: 'org_1', projectId: 'prj_1', signPayload: `0x${'bb'.repeat(32)}`, transaction: `0x76${'cc'.repeat(16)}`, }) await SponsoredTransactions.fail(db, failed.id, new Date().toISOString()) expect(await Organizations.hasUnreportedSponsorships(db, 'org_1')).toBe(true) await expect(Organizations.deleteOrganization(db, 'org_1')).rejects.toThrow( Organizations.UnreportedSponsorshipsError, ) expect(await Organizations.get(db, 'org_1')).toBeDefined() await db.close() }) test('behavior: deletes an org with only expired failed fill intents', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) const failed = await SponsoredTransactions.upsert(db, { apiKeyId: 'key_1', billable: true, chainId: Viem.chainId.mainnet, environment: 'production', orgId: 'org_1', projectId: 'prj_1', signPayload: `0x${'bb'.repeat(32)}`, transaction: `0x76${'cc'.repeat(16)}`, }) await SponsoredTransactions.fail( db, failed.id, new Date(Date.now() - SponsoredTransactions.failedIntentRecoveryTtlMs - 1).toISOString(), ) expect(await Organizations.hasUnreportedSponsorships(db, 'org_1')).toBe(false) expect(await Organizations.deleteOrganization(db, 'org_1')).toBe(true) await db.close() }) test('behavior: deletes enabled billing sources', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) await Organizations.create(db, { id: 'org_2', name: 'Two' }) await EnabledBillingSources.add(db, { createdBy: 'admin@tempo.xyz', orgId: 'org_1', source: 'stripe', }) await EnabledBillingSources.add(db, { createdBy: 'admin@tempo.xyz', orgId: 'org_1', source: 'tempo', }) await EnabledBillingSources.add(db, { createdBy: 'admin@tempo.xyz', orgId: 'org_2', source: 'stripe', }) expect(await Organizations.deleteOrganization(db, 'org_1')).toBe(true) expect(await EnabledBillingSources.listByOrg(db, 'org_1')).toEqual([]) expect((await EnabledBillingSources.listByOrg(db, 'org_2')).map((record) => record.source)) .toMatchInlineSnapshot(` [ "stripe", ] `) await db.close() }) test('behavior: deletes api-key-owned webhook subscriptions', async () => { const db = create() await db.migrate() await Organizations.create(db, { id: 'org_1', name: 'One' }) await Organizations.create(db, { id: 'org_2', name: 'Two' }) const deletedOrg = { orgId: 'org_1', type: 'api_key' } as const const keptOrg = { orgId: 'org_2', type: 'api_key' } as const const keptMpp = { payer: 'did:pkh:eip155:1:0xabc', type: 'mpp' } as const await Webhooks.createSubscription(db, subscription(deletedOrg)) const keptApiKey = await Webhooks.createSubscription(db, subscription(keptOrg)) const keptMppSubscription = await Webhooks.createSubscription(db, subscription(keptMpp)) expect(await Organizations.deleteOrganization(db, 'org_1')).toBe(true) expect(await Webhooks.listSubscriptions(db, deletedOrg)).toEqual([]) const active = await Webhooks.listActiveForChain(db, { chainId: 4217, eventTypes: ['token:transfer'], }) expect(active.map(({ subscription }) => subscription.id).sort()).toEqual( [keptApiKey.id, keptMppSubscription.id].sort(), ) await db.close() }) }) function subscription(owner: Webhooks.Owner): Webhooks.CreateInput { return { chainId: 4217, destination: { type: 'url', url: 'https://hooks.example.com/endpoint' }, eventType: 'token:transfer', owner, } }