diff --git a/backend/src/gateways/README.md b/backend/src/gateways/README.md index 388f8fb5..1df963e9 100644 --- a/backend/src/gateways/README.md +++ b/backend/src/gateways/README.md @@ -48,3 +48,48 @@ const charge = await adapter.charge({ 3. Register the protocol in `PROTOCOLS` and add a test using a fake transport. No call site should ever import a provider module directly. + +## Provider modules beyond charge/refund + +Subscription lifecycle and webhook-driven providers live in their own modules. +They reuse `BillingAdapterError`, `BillingTelemetry` and `withIdempotentRetry` +from `billingAdapter.ts`, so failures and metrics look the same everywhere. + +### Stripe subscriptions — [`stripe.ts`](./stripe.ts) + +`createStripeSubscriptionAdapter({ transport })` exposes `createSubscription`, +`changePlan`, `previewPlanChange`, `cancelSubscription` and `fetchSubscription`. + +- `calculateProration` is a pure, integer-only preview: credit for the unused + part of the old plan, charge for the remaining part of the new one, rounded + half-up per leg. `changePlan` sends the same `proration_date` to Stripe, so + the preview matches the invoice. +- Mutating calls carry the caller's idempotency key. 429, 5xx and transport + errors are retried with exponential backoff and the **same key**; 4xx are not. + +### Shopify billing — [`shopify.ts`](./shopify.ts) + +`createShopifyBillingAdapter({ transport })` wraps `appSubscriptionCreate`, +`appSubscriptionCancel` and a subscription lookup over the Admin GraphQL API. +Shopify has no idempotency header, so one result is kept per caller key: +concurrent and repeated calls share a single request. Failures are not cached, +so the caller can retry with the same key. `THROTTLED`, 429 and 5xx are retried +with backoff; `userErrors` are non-retryable rejections. + +### Circle USDC — [`circle.ts`](./circle.ts) + +- `createCircleAdapter` creates and fetches payments. Amounts are integer + micro-USDC (6 decimals) internally and decimal strings on the wire. +- `verifyCircleWebhook` checks the ECDSA-SHA256 signature (`X-Circle-Signature`) + with the key named by `X-Circle-Key-Id`. +- `applyCircleEvent` applies a webhook to a `CircleLedger` idempotently by + notification id. Statuses only move forward (`pending` → `confirmed` → + `paid`/`failed`); stale, duplicate and out-of-order events are ignored, and an + amount that differs from what was expected is flagged, never applied. +- `reconcileCirclePayments` polls Circle for payments still unsettled after + `staleAfterMs` (lost or delayed webhooks) and returns + `{ checked, updated, mismatched, errors }`. One failing lookup never aborts + the sweep. Run it on a schedule. + +`InMemoryCircleLedger` is provided for tests; production code supplies its own +`CircleLedger` backed by the database. diff --git a/backend/src/gateways/__tests__/circle.test.ts b/backend/src/gateways/__tests__/circle.test.ts new file mode 100644 index 00000000..433be348 --- /dev/null +++ b/backend/src/gateways/__tests__/circle.test.ts @@ -0,0 +1,233 @@ +import crypto from 'crypto'; +import type { BillingTransport } from '../billingAdapter'; +import { + InMemoryCircleLedger, + applyCircleEvent, + createCircleAdapter, + decimalStringToMicro, + microToDecimalString, + normaliseCircleStatus, + reconcileCirclePayments, + verifyCircleWebhook, + type CirclePayment, +} from '../circle'; + +type Reply = { status: number; body: Record } | Error; + +function fake(replies: Reply[]) { + const calls: any[] = []; + const transport: BillingTransport = { + async request(req) { + calls.push(req); + const next = replies.shift(); + if (!next) throw new Error('unexpected request'); + if (next instanceof Error) throw next; + return next; + }, + }; + return { transport, calls }; +} +const retry = { sleep: async () => undefined, baseDelayMs: 0 }; +const wire = (id: string, status: string, amount: string) => ({ + status: 200, + body: { data: { id, status, amount: { amount, currency: 'USD' }, createDate: '2026-01-01T00:00:00Z' } }, +}); +const payment = (id: string, status: CirclePayment['status'], amountMicro: number): CirclePayment => ({ + paymentId: id, status, amountMicro, createdAt: '2026-01-01T00:00:00Z', +}); + +describe('amount conversion', () => { + it.each([ + [1_500_000, '1.500000'], + [1, '0.000001'], + [10_000_000, '10.000000'], + ])('micro %i -> %s', (micro, text) => { + expect(microToDecimalString(micro)).toBe(text); + expect(decimalStringToMicro(text)).toBe(micro); + }); + it('parses short decimals and rejects junk', () => { + expect(decimalStringToMicro('1.5')).toBe(1_500_000); + expect(decimalStringToMicro('7')).toBe(7_000_000); + for (const bad of ['1.1234567', '-1', 'abc', '', undefined, 5]) { + expect(() => decimalStringToMicro(bad)).toThrow(/invalid USDC amount/); + } + }); + it('maps provider statuses', () => { + expect(normaliseCircleStatus('complete')).toBe('paid'); + expect(normaliseCircleStatus('cancelled')).toBe('failed'); + expect(normaliseCircleStatus('confirmed')).toBe('confirmed'); + expect(normaliseCircleStatus('whatever')).toBe('pending'); + }); +}); + +describe('createCircleAdapter', () => { + it('creates a payment with the idempotency key and decimal amount', async () => { + const { transport, calls } = fake([wire('pay_1', 'pending', '2.500000')]); + const adapter = createCircleAdapter({ transport, retry }); + const result = await adapter.createPayment({ idempotencyKey: 'k1', amountMicro: 2_500_000, sourceId: 'w1', metadata: { sub: 's1' } }); + expect(result).toEqual(payment('pay_1', 'pending', 2_500_000)); + expect(calls[0]).toMatchObject({ + method: 'POST', path: '/v1/payments', idempotencyKey: 'k1', + body: { amount: { amount: '2.500000', currency: 'USD' }, source: { id: 'w1', type: 'wallet' }, metadata: { sub: 's1' } }, + }); + }); + + it('retries 429/5xx/transport errors with the same key; not 4xx', async () => { + const { transport, calls } = fake([ + { status: 429, body: {} }, new Error('ECONNRESET'), { status: 503, body: {} }, wire('pay_1', 'pending', '1'), + ]); + const adapter = createCircleAdapter({ transport, retry: { ...retry, maxAttempts: 4 } }); + await adapter.createPayment({ idempotencyKey: 'same', amountMicro: 1_000_000, sourceId: 'w1' }); + expect(calls.map((c) => c.idempotencyKey)).toEqual(['same', 'same', 'same', 'same']); + + const rejected = fake([{ status: 400, body: { message: 'bad source' } }]); + await expect( + createCircleAdapter({ transport: rejected.transport, retry }).createPayment({ idempotencyKey: 'k', amountMicro: 1, sourceId: 'x' }), + ).rejects.toMatchObject({ code: 'PROVIDER_REJECTED', message: 'bad source', provider: 'circle' }); + expect(rejected.calls).toHaveLength(1); + }); + + it('validates input and responses', async () => { + const { transport, calls } = fake([{ status: 200, body: { data: { status: 'pending' } } }]); + const adapter = createCircleAdapter({ transport, retry }); + for (const bad of [ + { idempotencyKey: '', amountMicro: 1, sourceId: 's' }, + { idempotencyKey: 'k', amountMicro: 0, sourceId: 's' }, + { idempotencyKey: 'k', amountMicro: 1.5, sourceId: 's' }, + { idempotencyKey: 'k', amountMicro: 1, sourceId: '' }, + ]) { + await expect(adapter.createPayment(bad)).rejects.toMatchObject({ code: 'INVALID_REQUEST' }); + } + expect(calls).toHaveLength(0); + await expect(adapter.fetchPayment('pay_x')).rejects.toMatchObject({ code: 'INVALID_RESPONSE' }); + }); + + it('records telemetry', async () => { + const events: any[] = []; + const { transport } = fake([wire('p', 'paid', '1'), { status: 404, body: {} }]); + const adapter = createCircleAdapter({ transport, retry, telemetry: { record: (e) => events.push(e) } }); + await adapter.fetchPayment('p'); + await expect(adapter.fetchPayment('nope')).rejects.toMatchObject({ code: 'UNKNOWN' }); + expect(events.map((e) => [e.operation, e.provider, e.outcome, e.errorCode])).toEqual([ + ['fetch', 'circle', 'success', undefined], + ['fetch', 'circle', 'failure', 'UNKNOWN'], + ]); + }); +}); + +describe('verifyCircleWebhook', () => { + const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }); + const pem = publicKey.export({ type: 'spki', format: 'pem' }) as string; + const body = JSON.stringify({ notificationId: 'n1' }); + const sign = (b: string, key = privateKey) => crypto.sign('sha256', Buffer.from(b), key).toString('base64'); + const resolve = (id: string) => (id === 'key-1' ? pem : undefined); + + it('accepts a valid signature (string or Buffer body)', () => { + const headers = { 'x-circle-signature': sign(body), 'x-circle-key-id': 'key-1' }; + expect(verifyCircleWebhook(body, headers, resolve)).toEqual({ valid: true, keyId: 'key-1' }); + expect(verifyCircleWebhook(Buffer.from(body), headers, resolve).valid).toBe(true); + }); + + it('rejects tampering, wrong key, unknown key id and missing/garbage headers', () => { + const good = { 'x-circle-signature': sign(body), 'x-circle-key-id': 'key-1' }; + expect(verifyCircleWebhook(body + ' ', good, resolve).valid).toBe(false); + const other = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey; + expect(verifyCircleWebhook(body, { ...good, 'x-circle-signature': sign(body, other) }, resolve).valid).toBe(false); + expect(verifyCircleWebhook(body, { ...good, 'x-circle-key-id': 'key-2' }, resolve).error).toMatch(/Unknown signing key/); + expect(verifyCircleWebhook(body, { 'x-circle-key-id': 'key-1' }, resolve).error).toMatch(/Missing x-circle-signature/); + expect(verifyCircleWebhook(body, { 'x-circle-signature': 'x' }, resolve).error).toMatch(/Missing x-circle-key-id/); + expect(verifyCircleWebhook(body, { ...good, 'x-circle-signature': '!!!' }, resolve).valid).toBe(false); + expect(verifyCircleWebhook(body, { ...good, 'x-circle-signature': [good['x-circle-signature']] }, resolve).valid).toBe(true); + }); +}); + +describe('applyCircleEvent', () => { + async function seeded() { + const ledger = new InMemoryCircleLedger(); + await ledger.put({ paymentId: 'p1', status: 'pending', expectedAmountMicro: 5_000_000, updatedAt: '2026-01-01T00:00:00.000Z' }); + return ledger; + } + const logger = () => ({ info: jest.fn(), warn: jest.fn() }); + + it('moves a payment forward and logs it', async () => { + const ledger = await seeded(); + const log = logger(); + expect(await applyCircleEvent(ledger, { notificationId: 'n1', payment: payment('p1', 'paid', 5_000_000) }, log, () => 'T')).toBe('applied'); + expect(await ledger.get('p1')).toMatchObject({ status: 'paid', updatedAt: 'T' }); + expect(log.info).toHaveBeenCalledWith('[circle] payment updated', { paymentId: 'p1', from: 'pending', to: 'paid' }); + }); + + it('is idempotent per notification id', async () => { + const ledger = await seeded(); + const event = { notificationId: 'n1', payment: payment('p1', 'confirmed', 5_000_000) }; + expect(await applyCircleEvent(ledger, event)).toBe('applied'); + expect(await applyCircleEvent(ledger, event)).toBe('duplicate'); + }); + + it('ignores out-of-order and post-terminal events', async () => { + const ledger = await seeded(); + await applyCircleEvent(ledger, { notificationId: 'a', payment: payment('p1', 'paid', 5_000_000) }); + expect(await applyCircleEvent(ledger, { notificationId: 'b', payment: payment('p1', 'confirmed', 5_000_000) })).toBe('ignored_stale'); + expect(await applyCircleEvent(ledger, { notificationId: 'c', payment: payment('p1', 'failed', 5_000_000) })).toBe('ignored_stale'); + expect((await ledger.get('p1'))!.status).toBe('paid'); + }); + + it('flags amount mismatches and unknown payments without changing the ledger', async () => { + const ledger = await seeded(); + const log = logger(); + expect(await applyCircleEvent(ledger, { notificationId: 'm', payment: payment('p1', 'paid', 1) }, log)).toBe('amount_mismatch'); + expect(await applyCircleEvent(ledger, { notificationId: 'u', payment: payment('nope', 'paid', 1) }, log)).toBe('unknown_payment'); + expect((await ledger.get('p1'))!.status).toBe('pending'); + expect(log.warn).toHaveBeenCalledTimes(2); + }); + + it('requires a notification id', async () => { + await expect(applyCircleEvent(await seeded(), { notificationId: '', payment: payment('p1', 'paid', 1) })).rejects.toMatchObject({ code: 'INVALID_REQUEST' }); + }); +}); + +describe('reconcileCirclePayments', () => { + const NOW = Date.parse('2026-01-02T00:00:00.000Z'); + + it('updates stale unsettled payments, reports mismatches and isolates errors', async () => { + const ledger = new InMemoryCircleLedger(); + const old = '2026-01-01T00:00:00.000Z'; + for (const id of ['ok', 'mismatch', 'boom', 'unchanged']) { + await ledger.put({ paymentId: id, status: 'pending', expectedAmountMicro: 1_000_000, updatedAt: old }); + } + await ledger.put({ paymentId: 'fresh', status: 'pending', expectedAmountMicro: 1_000_000, updatedAt: '2026-01-01T23:59:59.000Z' }); + await ledger.put({ paymentId: 'done', status: 'paid', expectedAmountMicro: 1_000_000, updatedAt: old }); + + const fetched: string[] = []; + const adapter = { + createPayment: jest.fn(), + fetchPayment: jest.fn(async (id: string) => { + fetched.push(id); + if (id === 'boom') throw new Error('circle down'); + if (id === 'mismatch') return payment(id, 'paid', 2_000_000); + if (id === 'unchanged') return payment(id, 'pending', 1_000_000); + return payment(id, 'paid', 1_000_000); + }), + }; + const log = { info: jest.fn(), warn: jest.fn() }; + const report = await reconcileCirclePayments({ ledger, adapter, staleAfterMs: 60_000, nowMs: NOW, logger: log }); + + expect(fetched.sort()).toEqual(['boom', 'mismatch', 'ok', 'unchanged']); + expect(report).toEqual({ + checked: 4, + updated: ['ok'], + mismatched: ['mismatch'], + errors: [{ paymentId: 'boom', error: 'circle down' }], + }); + expect((await ledger.get('ok'))!.status).toBe('paid'); + expect((await ledger.get('mismatch'))!.status).toBe('pending'); + expect(log.info).toHaveBeenCalledWith('[circle] reconciliation complete', { checked: 4, updated: 1, mismatched: 1, errors: 1 }); + }); + + it('is a no-op when nothing is unsettled', async () => { + const adapter = { createPayment: jest.fn(), fetchPayment: jest.fn() }; + const report = await reconcileCirclePayments({ ledger: new InMemoryCircleLedger(), adapter, staleAfterMs: 1 }); + expect(report).toEqual({ checked: 0, updated: [], mismatched: [], errors: [] }); + expect(adapter.fetchPayment).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/gateways/__tests__/shopifyBilling.test.ts b/backend/src/gateways/__tests__/shopifyBilling.test.ts new file mode 100644 index 00000000..14d112c0 --- /dev/null +++ b/backend/src/gateways/__tests__/shopifyBilling.test.ts @@ -0,0 +1,155 @@ +import { createShopifyBillingAdapter, minorToDecimalString, type ShopifyGraphqlTransport } from '../shopify'; + +type Reply = { status: number; body: Record } | Error; + +function fake(replies: Reply[]) { + const calls: Array<{ query: string; variables: Record }> = []; + const transport: ShopifyGraphqlTransport = { + async query(query, variables) { + calls.push({ query, variables }); + const next = replies.shift(); + if (!next) throw new Error('unexpected request'); + if (next instanceof Error) throw next; + return next; + }, + }; + return { transport, calls }; +} + +const retry = { sleep: async () => undefined, baseDelayMs: 0 }; +const created = { + status: 200, + body: { + data: { + appSubscriptionCreate: { + appSubscription: { id: 'gid://shopify/AppSubscription/1', status: 'PENDING' }, + confirmationUrl: 'https://shop.example/confirm', + userErrors: [], + }, + }, + }, +}; +const request = { + idempotencyKey: 'k1', + name: 'Pro', + returnUrl: 'https://app.example/return', + price: { amountMinor: 1999, currency: 'USD' }, +}; + +describe('minorToDecimalString', () => { + it.each([ + [1999, '19.99'], + [5, '0.05'], + [100, '1.00'], + [123456, '1234.56'], + ])('%i -> %s', (minor, text) => expect(minorToDecimalString(minor)).toBe(text)); +}); + +describe('createShopifyBillingAdapter', () => { + it('creates a subscription and returns the confirmation url', async () => { + const { transport, calls } = fake([created]); + const adapter = createShopifyBillingAdapter({ transport, retry }); + const result = await adapter.createSubscription({ ...request, trialDays: 7, test: true }); + expect(result).toEqual({ + subscriptionId: 'gid://shopify/AppSubscription/1', + status: 'PENDING', + confirmationUrl: 'https://shop.example/confirm', + }); + expect(calls[0].variables).toMatchObject({ name: 'Pro', trialDays: 7, test: true }); + expect(calls[0].variables.lineItems[0].plan.appRecurringPricingDetails).toEqual({ + interval: 'EVERY_30_DAYS', + price: { amount: '19.99', currencyCode: 'USD' }, + }); + }); + + it('is idempotent: same key sends one request, concurrently and afterwards', async () => { + const { transport, calls } = fake([created, created]); + const adapter = createShopifyBillingAdapter({ transport, retry }); + const [a, b] = await Promise.all([adapter.createSubscription(request), adapter.createSubscription(request)]); + const c = await adapter.createSubscription(request); + expect(a).toEqual(b); + expect(c).toEqual(a); + expect(calls).toHaveLength(1); + await adapter.createSubscription({ ...request, idempotencyKey: 'k2' }); + expect(calls).toHaveLength(2); + }); + + it('retries throttling and 5xx with one logical create, then succeeds', async () => { + const { transport, calls } = fake([ + { status: 200, body: { errors: [{ message: 'Throttled', extensions: { code: 'THROTTLED' } }] } }, + { status: 502, body: {} }, + created, + ]); + const retries: number[] = []; + const adapter = createShopifyBillingAdapter({ + transport, + retry: { ...retry, maxAttempts: 3, onRetry: (i) => retries.push(i.attempt) }, + }); + await expect(adapter.createSubscription(request)).resolves.toMatchObject({ status: 'PENDING' }); + expect(calls).toHaveLength(3); + expect(retries).toEqual([1, 2]); + }); + + it('does not cache failures: the same key can be retried by the caller', async () => { + const { transport, calls } = fake([{ status: 500, body: {} }, created]); + const adapter = createShopifyBillingAdapter({ transport, retry: { ...retry, maxAttempts: 1 } }); + await expect(adapter.createSubscription(request)).rejects.toMatchObject({ code: 'PROVIDER_UNAVAILABLE', provider: 'shopify' }); + await expect(adapter.createSubscription(request)).resolves.toMatchObject({ status: 'PENDING' }); + expect(calls).toHaveLength(2); + }); + + it('surfaces userErrors as a non-retryable rejection', async () => { + const { transport, calls } = fake([ + { status: 200, body: { data: { appSubscriptionCreate: { appSubscription: null, userErrors: [{ message: 'Invalid return URL' }] } } } }, + ]); + const adapter = createShopifyBillingAdapter({ transport, retry }); + await expect(adapter.createSubscription(request)).rejects.toMatchObject({ + code: 'PROVIDER_REJECTED', message: 'Invalid return URL', retryable: false, + }); + expect(calls).toHaveLength(1); + }); + + it('retries transport errors', async () => { + const { transport, calls } = fake([new Error('ECONNRESET'), created]); + const adapter = createShopifyBillingAdapter({ transport, retry }); + await adapter.createSubscription(request); + expect(calls).toHaveLength(2); + }); + + it.each([ + ['missing key', { ...request, idempotencyKey: ' ' }], + ['missing name', { ...request, name: '' }], + ['float price', { ...request, price: { amountMinor: 19.99, currency: 'USD' } }], + ['zero price', { ...request, price: { amountMinor: 0, currency: 'USD' } }], + ['bad currency', { ...request, price: { amountMinor: 100, currency: 'usd' } }], + ])('rejects %s without calling Shopify', async (_l, bad) => { + const { transport, calls } = fake([]); + const adapter = createShopifyBillingAdapter({ transport, retry }); + await expect(adapter.createSubscription(bad)).rejects.toMatchObject({ code: 'INVALID_REQUEST' }); + expect(calls).toHaveLength(0); + }); + + it('cancels and fetches subscriptions', async () => { + const { transport } = fake([ + { status: 200, body: { data: { appSubscriptionCancel: { appSubscription: { id: 'gid://1', status: 'CANCELLED' }, userErrors: [] } } } }, + { status: 200, body: { data: { node: { id: 'gid://1', status: 'ACTIVE' } } } }, + { status: 200, body: { data: { node: null } } }, + ]); + const adapter = createShopifyBillingAdapter({ transport, retry }); + expect((await adapter.cancelSubscription({ idempotencyKey: 'c', subscriptionId: 'gid://1' })).status).toBe('CANCELLED'); + expect((await adapter.fetchSubscription('gid://1')).status).toBe('ACTIVE'); + await expect(adapter.fetchSubscription('gid://missing')).rejects.toMatchObject({ code: 'INVALID_RESPONSE' }); + }); + + it('emits telemetry for success and failure', async () => { + const events: any[] = []; + const { transport } = fake([created, { status: 400, body: { errors: [{ message: 'bad' }] } }]); + const adapter = createShopifyBillingAdapter({ transport, retry, telemetry: { record: (e) => events.push(e) } }); + await adapter.createSubscription(request); + await expect(adapter.fetchSubscription('x')).rejects.toThrow(); + expect(events.map((e) => [e.operation, e.provider, e.outcome, e.errorCode])).toEqual([ + ['charge', 'shopify', 'success', undefined], + ['fetch', 'shopify', 'failure', 'PROVIDER_REJECTED'], + ]); + }); +}); diff --git a/backend/src/gateways/__tests__/stripe.test.ts b/backend/src/gateways/__tests__/stripe.test.ts new file mode 100644 index 00000000..bf7d95eb --- /dev/null +++ b/backend/src/gateways/__tests__/stripe.test.ts @@ -0,0 +1,261 @@ +import { BillingAdapterError, withIdempotentRetry, type BillingTransport } from '../billingAdapter'; +import { calculateProration, createStripeSubscriptionAdapter } from '../stripe'; + +const PERIOD_START = 1_700_000_000; +const PERIOD_END = PERIOD_START + 30 * 86400; +const MID = PERIOD_START + 15 * 86400; + +function subscription(priceId: string, unit: number, extra: Record = {}) { + return { + id: 'sub_1', + status: 'active', + current_period_start: PERIOD_START, + current_period_end: PERIOD_END, + cancel_at_period_end: false, + items: { data: [{ id: 'si_1', quantity: 1, price: { id: priceId, unit_amount: unit } }] }, + ...extra, + }; +} + +type Reply = { status: number; body: Record } | Error; + +function fakeTransport(replies: Reply[]) { + const calls: Array<{ method: string; path: string; body?: Record; idempotencyKey?: string }> = []; + const transport: BillingTransport = { + async request(req) { + calls.push(req); + const next = replies.shift(); + if (!next) throw new Error('unexpected request'); + if (next instanceof Error) throw next; + return next; + }, + }; + return { transport, calls }; +} + +const fastRetry = { sleep: async () => undefined, baseDelayMs: 0 }; + +describe('calculateProration', () => { + const base = { + currentPlan: { priceId: 'basic', amountMinor: 1000 }, + newPlan: { priceId: 'pro', amountMinor: 3000 }, + periodStart: PERIOD_START, + periodEnd: PERIOD_END, + }; + + it('prorates an upgrade half-way through the period', () => { + expect(calculateProration({ ...base, changeAt: MID })).toEqual({ + creditMinor: 500, + chargeMinor: 1500, + netMinor: 1000, + remainingSeconds: 15 * 86400, + totalSeconds: 30 * 86400, + }); + }); + + it('produces a negative net (credit) on a downgrade', () => { + const p = calculateProration({ + ...base, + currentPlan: base.newPlan, + newPlan: base.currentPlan, + changeAt: MID, + }); + expect(p.netMinor).toBe(-1000); + }); + + it('is a full swap at period start and a no-op at period end', () => { + expect(calculateProration({ ...base, changeAt: PERIOD_START })).toMatchObject({ creditMinor: 1000, chargeMinor: 3000 }); + expect(calculateProration({ ...base, changeAt: PERIOD_END })).toMatchObject({ creditMinor: 0, chargeMinor: 0, netMinor: 0 }); + }); + + it('rounds half-up to whole minor units and scales with quantity', () => { + const third = PERIOD_START + 2 * 86400; // 28/30 remaining + expect(calculateProration({ ...base, changeAt: third }).creditMinor).toBe(933); // 933.33 + expect(calculateProration({ ...base, changeAt: third, quantity: 3 }).creditMinor).toBe(2800); + expect(Number.isInteger(calculateProration({ ...base, changeAt: MID + 1 }).chargeMinor)).toBe(true); + }); + + it.each([ + ['changeAt before period', { changeAt: PERIOD_START - 1 }], + ['changeAt after period', { changeAt: PERIOD_END + 1 }], + ['empty period', { periodEnd: PERIOD_START, changeAt: PERIOD_START }], + ['float price', { currentPlan: { priceId: 'x', amountMinor: 9.5 }, changeAt: MID }], + ['bad quantity', { quantity: 0, changeAt: MID }], + ])('rejects %s', (_label, patch) => { + expect(() => calculateProration({ ...base, ...patch })).toThrow(BillingAdapterError); + }); +}); + +describe('withIdempotentRetry', () => { + it('retries retryable errors with exponential backoff and stops on non-retryable', async () => { + const delays: number[] = []; + let n = 0; + const result = await withIdempotentRetry( + async () => { + if (++n < 3) throw new BillingAdapterError('RATE_LIMITED', 'stripe', 'slow down', true); + return 'ok'; + }, + { maxAttempts: 3, baseDelayMs: 100, sleep: async (ms) => void delays.push(ms) }, + ); + expect(result).toBe('ok'); + expect(delays).toEqual([100, 200]); + + let m = 0; + await expect( + withIdempotentRetry(async () => { + m++; + throw new BillingAdapterError('PROVIDER_REJECTED', 'stripe', 'no', false); + }, fastRetry), + ).rejects.toThrow('no'); + expect(m).toBe(1); + }); + + it('gives up after maxAttempts and does not retry unknown errors', async () => { + let n = 0; + await expect( + withIdempotentRetry(async () => { + n++; + throw new BillingAdapterError('PROVIDER_UNAVAILABLE', 'stripe', 'down', true); + }, { ...fastRetry, maxAttempts: 2 }), + ).rejects.toThrow('down'); + expect(n).toBe(2); + await expect(withIdempotentRetry(async () => { throw new Error('boom'); }, fastRetry)).rejects.toThrow('boom'); + }); +}); + +describe('createStripeSubscriptionAdapter', () => { + it('creates a subscription with the idempotency key', async () => { + const { transport, calls } = fakeTransport([{ status: 200, body: subscription('price_basic', 1000) }]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + const result = await adapter.createSubscription({ idempotencyKey: 'k1', customerId: 'cus_1', priceId: 'price_basic' }); + expect(result).toMatchObject({ subscriptionId: 'sub_1', priceId: 'price_basic', itemId: 'si_1', status: 'active' }); + expect(calls[0]).toMatchObject({ + method: 'POST', + path: '/v1/subscriptions', + idempotencyKey: 'k1', + body: { customer: 'cus_1', items: [{ price: 'price_basic', quantity: 1 }] }, + }); + }); + + it('changes plan with proration and returns the computed proration', async () => { + const updated = subscription('price_pro', 3000); + const { transport, calls } = fakeTransport([ + { status: 200, body: subscription('price_basic', 1000) }, + { status: 200, body: updated }, + ]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + const result = await adapter.changePlan({ + idempotencyKey: 'chg-1', + subscriptionId: 'sub_1', + newPriceId: 'price_pro', + prorationDate: MID, + }); + expect(calls[1]).toMatchObject({ + method: 'POST', + path: '/v1/subscriptions/sub_1', + idempotencyKey: 'chg-1', + body: { items: [{ id: 'si_1', price: 'price_pro' }], proration_behavior: 'create_prorations', proration_date: MID }, + }); + expect(result.priceId).toBe('price_pro'); + expect(result.proration).toMatchObject({ creditMinor: 500, chargeMinor: 1500, netMinor: 1000 }); + }); + + it('skips proration output when behavior is none', async () => { + const { transport, calls } = fakeTransport([ + { status: 200, body: subscription('price_basic', 1000) }, + { status: 200, body: subscription('price_pro', 3000) }, + ]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + const result = await adapter.changePlan({ + idempotencyKey: 'c', subscriptionId: 'sub_1', newPriceId: 'price_pro', prorationBehavior: 'none', + }); + expect(result.proration).toBeUndefined(); + expect(calls[1].body).toMatchObject({ proration_behavior: 'none' }); + }); + + it('retries a 5xx plan change using the SAME idempotency key', async () => { + const replies = [ + { status: 200, body: subscription('price_basic', 1000) }, + { status: 429, body: { error: { message: 'slow' } } }, + { status: 200, body: subscription('price_pro', 3000) }, + ]; + const t2 = fakeTransport(replies); + const adapter = createStripeSubscriptionAdapter({ transport: t2.transport, retry: fastRetry }); + await adapter.changePlan({ idempotencyKey: 'same', subscriptionId: 'sub_1', newPriceId: 'price_pro', prorationDate: MID }); + const posts = t2.calls.filter((c) => c.method === 'POST'); + expect(posts).toHaveLength(2); + expect(posts.map((p) => p.idempotencyKey)).toEqual(['same', 'same']); + }); + + it('retries transport failures and surfaces PROVIDER_UNAVAILABLE when exhausted', async () => { + const { transport, calls } = fakeTransport([new Error('ECONNRESET'), new Error('ECONNRESET'), new Error('ECONNRESET')]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + await expect(adapter.fetchSubscription('sub_1')).rejects.toMatchObject({ code: 'PROVIDER_UNAVAILABLE', retryable: true }); + expect(calls).toHaveLength(3); + }); + + it('does not retry 4xx rejections', async () => { + const { transport, calls } = fakeTransport([{ status: 402, body: { error: { message: 'card declined' } } }]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + await expect(adapter.fetchSubscription('sub_1')).rejects.toMatchObject({ + code: 'PROVIDER_REJECTED', message: 'card declined', retryable: false, + }); + expect(calls).toHaveLength(1); + }); + + it('refuses a no-op plan change and invalid input before changing anything', async () => { + const { transport, calls } = fakeTransport([{ status: 200, body: subscription('price_pro', 3000) }]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + await expect( + adapter.changePlan({ idempotencyKey: 'k', subscriptionId: 'sub_1', newPriceId: 'price_pro' }), + ).rejects.toMatchObject({ code: 'INVALID_REQUEST' }); + expect(calls.filter((c) => c.method === 'POST')).toHaveLength(0); + await expect( + adapter.changePlan({ idempotencyKey: ' ', subscriptionId: 'sub_1', newPriceId: 'x' }), + ).rejects.toMatchObject({ code: 'INVALID_REQUEST' }); + await expect(adapter.createSubscription({ idempotencyKey: 'k', customerId: '', priceId: 'p' })).rejects.toMatchObject({ + code: 'INVALID_REQUEST', + }); + }); + + it('previews proration without mutating', async () => { + const { transport, calls } = fakeTransport([{ status: 200, body: subscription('price_basic', 1000) }]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry, now: () => MID * 1000 }); + const preview = await adapter.previewPlanChange('sub_1', { priceId: 'price_pro', amountMinor: 3000 }); + expect(preview.netMinor).toBe(1000); + expect(calls.every((c) => c.method === 'GET')).toBe(true); + }); + + it('cancels immediately or at period end', async () => { + const { transport, calls } = fakeTransport([ + { status: 200, body: subscription('p', 1, { status: 'canceled' }) }, + { status: 200, body: subscription('p', 1, { cancel_at_period_end: true }) }, + ]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + expect((await adapter.cancelSubscription({ idempotencyKey: 'a', subscriptionId: 'sub_1' })).status).toBe('canceled'); + expect((await adapter.cancelSubscription({ idempotencyKey: 'b', subscriptionId: 'sub_1', atPeriodEnd: true })).cancelAtPeriodEnd).toBe(true); + expect(calls[0].path).toBe('/v1/subscriptions/sub_1/cancel'); + expect(calls[1].body).toEqual({ cancel_at_period_end: true }); + }); + + it('rejects malformed provider responses', async () => { + const { transport } = fakeTransport([{ status: 200, body: { id: 'sub_1', status: 'active' } }]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry }); + await expect(adapter.fetchSubscription('sub_1')).rejects.toMatchObject({ code: 'INVALID_RESPONSE' }); + }); + + it('emits success and failure telemetry', async () => { + const events: any[] = []; + const { transport } = fakeTransport([ + { status: 200, body: subscription('p', 1) }, + { status: 400, body: { error: 'bad' } }, + ]); + const adapter = createStripeSubscriptionAdapter({ transport, retry: fastRetry, telemetry: { record: (e) => events.push(e) } }); + await adapter.fetchSubscription('sub_1'); + await expect(adapter.fetchSubscription('sub_1')).rejects.toThrow(); + expect(events.map((e) => [e.operation, e.provider, e.outcome, e.errorCode])).toEqual([ + ['fetch', 'stripe', 'success', undefined], + ['fetch', 'stripe', 'failure', 'PROVIDER_REJECTED'], + ]); + }); +}); diff --git a/backend/src/gateways/billingAdapter.ts b/backend/src/gateways/billingAdapter.ts index 538ffbf3..de1bd96a 100644 --- a/backend/src/gateways/billingAdapter.ts +++ b/backend/src/gateways/billingAdapter.ts @@ -22,7 +22,10 @@ export type BillingProvider = 'stripe' | 'paypal' | 'paddle'; -export type BillingOperation = 'charge' | 'refund' | 'fetch'; +/** Providers that have a gateway module, including those outside the charge/refund registry. */ +export type GatewayProvider = BillingProvider | 'shopify' | 'circle'; + +export type BillingOperation = 'charge' | 'refund' | 'fetch' | 'cancel'; export interface BillingMoney { /** Integer minor units (cents, paise, …). Never a float. */ @@ -83,7 +86,7 @@ export type BillingErrorCode = export class BillingAdapterError extends Error { constructor( public readonly code: BillingErrorCode, - public readonly provider: BillingProvider, + public readonly provider: GatewayProvider, message: string, public readonly retryable = false, public readonly cause?: unknown, @@ -112,7 +115,7 @@ export interface BillingTransportResponse { export interface BillingTelemetryEvent { operation: BillingOperation; - provider: BillingProvider; + provider: GatewayProvider; outcome: 'success' | 'failure'; durationMs: number; errorCode?: BillingErrorCode; @@ -650,3 +653,42 @@ export function createBillingAdapter( export function listBillingAdapters(): BillingProvider[] { return Object.keys(PROTOCOLS) as BillingProvider[]; } + +// ── Shared retry helper ─────────────────────────────────────────────────────── + +export interface RetryPolicy { + /** Total attempts including the first. Defaults to 3. */ + maxAttempts?: number; + /** Delay before the second attempt; doubles each retry. Defaults to 200 ms. */ + baseDelayMs?: number; + /** Injectable sleep, so tests never wait on real timers. */ + sleep?: (ms: number) => Promise; + /** Called before each retry (for logs/metrics). */ + onRetry?: (info: { attempt: number; delayMs: number; error: BillingAdapterError }) => void; +} + +/** + * Run `fn`, retrying only `BillingAdapterError`s flagged `retryable`. + * Callers must pass the SAME idempotency key on every attempt, which is why + * the key is fixed by the caller and never regenerated here. + */ +export async function withIdempotentRetry( + fn: (attempt: number) => Promise, + policy: RetryPolicy = {}, +): Promise { + const maxAttempts = Math.max(1, policy.maxAttempts ?? 3); + const baseDelayMs = policy.baseDelayMs ?? 200; + const sleep = policy.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); + for (let attempt = 1; ; attempt++) { + try { + return await fn(attempt); + } catch (error) { + if (!(error instanceof BillingAdapterError) || !error.retryable || attempt >= maxAttempts) { + throw error; + } + const delayMs = baseDelayMs * 2 ** (attempt - 1); + policy.onRetry?.({ attempt, delayMs, error }); + await sleep(delayMs); + } + } +} diff --git a/backend/src/gateways/circle.ts b/backend/src/gateways/circle.ts new file mode 100644 index 00000000..c29cef32 --- /dev/null +++ b/backend/src/gateways/circle.ts @@ -0,0 +1,403 @@ +/** + * backend/src/gateways/circle.ts + * + * Circle USDC billing adapter with webhook reconciliation. + * + * - `createCircleAdapter` creates and fetches USDC payments. Amounts are + * integer micro-USDC (6 decimals) inside SubTrackr and decimal strings on + * the wire; no floats cross the boundary. Creates are retried with the + * SAME idempotency key on 429/5xx/transport errors. + * - `verifyCircleWebhook` checks Circle's ECDSA-SHA256 signature over the raw + * body against the public key identified by `X-Circle-Key-Id`. + * - `applyCircleEvent` folds a webhook into a `CircleLedger` idempotently + * (by notification id) and only ever moves a payment forward. + * - `reconcileCirclePayments` polls Circle for payments whose webhook never + * arrived and reports amount mismatches instead of silently overwriting. + */ + +import crypto from 'crypto'; +import { + BillingAdapterError, + noopBillingTelemetry, + withIdempotentRetry, + type BillingOperation, + type BillingTelemetry, + type BillingTransport, + type BillingTransportResponse, + type RetryPolicy, +} from './billingAdapter'; + +// ── Types ───────────────────────────────────────────────────────────────────── + +export const USDC_DECIMALS = 6; +export const CIRCLE_SIGNATURE_HEADER = 'x-circle-signature'; +export const CIRCLE_KEY_ID_HEADER = 'x-circle-key-id'; + +export type CirclePaymentStatus = 'pending' | 'confirmed' | 'paid' | 'failed'; + +export interface CirclePayment { + paymentId: string; + status: CirclePaymentStatus; + /** Integer micro-USDC (1 USDC = 1_000_000). */ + amountMicro: number; + createdAt: string; +} + +export interface CircleCreatePaymentRequest { + idempotencyKey: string; + /** Integer micro-USDC, > 0. */ + amountMicro: number; + /** Circle source (wallet/card) id. */ + sourceId: string; + sourceType?: 'wallet' | 'card'; + metadata?: Record; +} + +export interface CircleAdapter { + createPayment(request: CircleCreatePaymentRequest): Promise; + fetchPayment(paymentId: string): Promise; +} + +export interface CircleAdapterOptions { + transport: BillingTransport; + telemetry?: BillingTelemetry; + retry?: RetryPolicy; + now?: () => number; +} + +// ── Amount conversion ───────────────────────────────────────────────────────── + +/** 1_500_000 → "1.500000". Integer math only. */ +export function microToDecimalString(amountMicro: number): string { + const whole = Math.trunc(amountMicro / 10 ** USDC_DECIMALS); + const frac = String(amountMicro % 10 ** USDC_DECIMALS).padStart(USDC_DECIMALS, '0'); + return `${whole}.${frac}`; +} + +/** "1.5" → 1_500_000. Rejects anything with more than 6 decimals or non-numeric text. */ +export function decimalStringToMicro(value: unknown): number { + const match = typeof value === 'string' ? /^(\d+)(?:\.(\d{1,6}))?$/.exec(value) : null; + if (!match) { + throw new BillingAdapterError('INVALID_RESPONSE', 'circle', 'Circle returned an invalid USDC amount'); + } + const micro = Number(match[1]) * 10 ** USDC_DECIMALS + Number((match[2] ?? '').padEnd(USDC_DECIMALS, '0')); + if (!Number.isSafeInteger(micro)) { + throw new BillingAdapterError('INVALID_RESPONSE', 'circle', 'Circle returned an out-of-range USDC amount'); + } + return micro; +} + +// ── Payment parsing ─────────────────────────────────────────────────────────── + +export function normaliseCircleStatus(status: unknown): CirclePaymentStatus { + switch (status) { + case 'paid': + case 'complete': + case 'completed': + return 'paid'; + case 'confirmed': + return 'confirmed'; + case 'failed': + case 'canceled': + case 'cancelled': + return 'failed'; + default: + return 'pending'; + } +} + +function parsePayment(raw: unknown): CirclePayment { + const body = ((raw as Record | undefined)?.data ?? raw) as Record | undefined; + const amount = body?.amount as Record | undefined; + if (!body || typeof body.id !== 'string' || body.id === '') { + throw new BillingAdapterError('INVALID_RESPONSE', 'circle', 'Circle response is missing the payment id'); + } + if (typeof body.createdAt !== 'string' && typeof body.createDate !== 'string') { + throw new BillingAdapterError('INVALID_RESPONSE', 'circle', 'Circle response is missing the creation time'); + } + return { + paymentId: body.id, + status: normaliseCircleStatus(body.status), + amountMicro: decimalStringToMicro(amount?.amount), + createdAt: (body.createdAt ?? body.createDate) as string, + }; +} + +// ── Adapter ─────────────────────────────────────────────────────────────────── + +export function createCircleAdapter(options: CircleAdapterOptions): CircleAdapter { + const telemetry = options.telemetry ?? noopBillingTelemetry; + const now = options.now ?? (() => Date.now()); + + const send = ( + method: 'GET' | 'POST', + path: string, + body?: Record, + ): Promise> => + withIdempotentRetry(async () => { + let response: BillingTransportResponse; + try { + response = await options.transport.request({ + method, + path, + body, + idempotencyKey: body?.idempotencyKey as string | undefined, + }); + } catch (error) { + throw new BillingAdapterError('PROVIDER_UNAVAILABLE', 'circle', 'Circle transport failed', true, error); + } + if (response.status >= 200 && response.status < 300) return response.body; + const message = + typeof response.body?.message === 'string' ? response.body.message : 'Circle rejected the request'; + if (response.status === 429) throw new BillingAdapterError('RATE_LIMITED', 'circle', message, true); + if (response.status >= 500) throw new BillingAdapterError('PROVIDER_UNAVAILABLE', 'circle', message, true); + throw new BillingAdapterError(response.status === 404 ? 'UNKNOWN' : 'PROVIDER_REJECTED', 'circle', message); + }, options.retry); + + const observe = async (operation: BillingOperation, fn: () => Promise): Promise => { + const started = now(); + try { + const result = await fn(); + telemetry.record({ operation, provider: 'circle', outcome: 'success', durationMs: now() - started }); + return result; + } catch (error) { + telemetry.record({ + operation, + provider: 'circle', + outcome: 'failure', + durationMs: now() - started, + errorCode: error instanceof BillingAdapterError ? error.code : 'UNKNOWN', + }); + throw error; + } + }; + + return { + createPayment: (request) => + observe('charge', async () => { + if (typeof request.idempotencyKey !== 'string' || request.idempotencyKey.trim() === '') { + throw new BillingAdapterError('INVALID_REQUEST', 'circle', 'idempotencyKey is required'); + } + if (!Number.isSafeInteger(request.amountMicro) || request.amountMicro <= 0) { + throw new BillingAdapterError('INVALID_REQUEST', 'circle', 'amountMicro must be a positive integer'); + } + if (!request.sourceId) { + throw new BillingAdapterError('INVALID_REQUEST', 'circle', 'sourceId is required'); + } + return parsePayment( + await send('POST', '/v1/payments', { + idempotencyKey: request.idempotencyKey, + amount: { amount: microToDecimalString(request.amountMicro), currency: 'USD' }, + source: { id: request.sourceId, type: request.sourceType ?? 'wallet' }, + metadata: request.metadata, + }), + ); + }), + + fetchPayment: (paymentId) => + observe('fetch', async () => { + if (!paymentId) throw new BillingAdapterError('INVALID_REQUEST', 'circle', 'paymentId is required'); + return parsePayment(await send('GET', `/v1/payments/${encodeURIComponent(paymentId)}`)); + }), + }; +} + +// ── Webhook verification ────────────────────────────────────────────────────── + +export interface CircleWebhookVerifyResult { + valid: boolean; + error?: string; + keyId?: string; +} + +/** + * Verify a Circle webhook. `resolvePublicKey` maps `X-Circle-Key-Id` to a PEM + * (or SPKI) public key; return undefined for unknown ids, which are rejected. + */ +export function verifyCircleWebhook( + rawBody: Buffer | string, + headers: Record, + resolvePublicKey: (keyId: string) => string | undefined, +): CircleWebhookVerifyResult { + const pick = (name: string) => { + const value = headers[name]; + return Array.isArray(value) ? value[0] : value; + }; + const signature = pick(CIRCLE_SIGNATURE_HEADER); + const keyId = pick(CIRCLE_KEY_ID_HEADER); + if (!signature) return { valid: false, error: `Missing ${CIRCLE_SIGNATURE_HEADER} header` }; + if (!keyId) return { valid: false, error: `Missing ${CIRCLE_KEY_ID_HEADER} header` }; + const publicKey = resolvePublicKey(keyId); + if (!publicKey) return { valid: false, error: 'Unknown signing key id', keyId }; + try { + const ok = crypto.verify( + 'sha256', + Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, 'utf8'), + publicKey, + Buffer.from(signature, 'base64'), + ); + return ok ? { valid: true, keyId } : { valid: false, error: 'Signature verification failed', keyId }; + } catch { + return { valid: false, error: 'Signature verification failed', keyId }; + } +} + +// ── Ledger + webhook application ────────────────────────────────────────────── + +export interface CircleLedgerEntry { + paymentId: string; + status: CirclePaymentStatus; + /** What SubTrackr expects to receive, integer micro-USDC. */ + expectedAmountMicro: number; + /** ISO time the entry was created or last changed. */ + updatedAt: string; +} + +export interface CircleLedger { + get(paymentId: string): Promise; + put(entry: CircleLedgerEntry): Promise; + /** Entries still `pending`/`confirmed` and not updated since `before` (ISO). */ + listUnsettled(before: string): Promise; + /** Returns true the first time a notification id is seen. */ + markNotification(notificationId: string): Promise; +} + +export class InMemoryCircleLedger implements CircleLedger { + private readonly entries = new Map(); + private readonly seen = new Set(); + + async get(paymentId: string) { + return this.entries.get(paymentId); + } + async put(entry: CircleLedgerEntry) { + this.entries.set(entry.paymentId, { ...entry }); + } + async listUnsettled(before: string) { + return [...this.entries.values()].filter( + (e) => (e.status === 'pending' || e.status === 'confirmed') && e.updatedAt <= before, + ); + } + async markNotification(notificationId: string) { + if (this.seen.has(notificationId)) return false; + this.seen.add(notificationId); + return true; + } +} + +export interface CircleWebhookEvent { + notificationId: string; + payment: CirclePayment; +} + +export type CircleApplyOutcome = + | 'applied' + | 'duplicate' + | 'ignored_stale' + | 'unknown_payment' + | 'amount_mismatch'; + +export interface CircleReconcileLogger { + info(message: string, meta?: Record): void; + warn(message: string, meta?: Record): void; +} + +const noopLogger: CircleReconcileLogger = { info: () => undefined, warn: () => undefined }; + +const RANK: Record = { pending: 0, confirmed: 1, paid: 2, failed: 2 }; + +/** + * Apply one webhook event. Safe to call repeatedly with the same event, and + * with events delivered out of order: statuses only move forward and terminal + * statuses (`paid`/`failed`) are never overwritten. + */ +export async function applyCircleEvent( + ledger: CircleLedger, + event: CircleWebhookEvent, + logger: CircleReconcileLogger = noopLogger, + now: () => string = () => new Date().toISOString(), +): Promise { + if (!event.notificationId) { + throw new BillingAdapterError('INVALID_REQUEST', 'circle', 'notificationId is required'); + } + if (!(await ledger.markNotification(event.notificationId))) return 'duplicate'; + + const entry = await ledger.get(event.payment.paymentId); + if (!entry) { + logger.warn('[circle] webhook for unknown payment', { paymentId: event.payment.paymentId }); + return 'unknown_payment'; + } + if (entry.expectedAmountMicro !== event.payment.amountMicro) { + logger.warn('[circle] amount mismatch', { + paymentId: entry.paymentId, + expected: entry.expectedAmountMicro, + received: event.payment.amountMicro, + }); + return 'amount_mismatch'; + } + if (RANK[event.payment.status] <= RANK[entry.status]) return 'ignored_stale'; + + await ledger.put({ ...entry, status: event.payment.status, updatedAt: now() }); + logger.info('[circle] payment updated', { + paymentId: entry.paymentId, + from: entry.status, + to: event.payment.status, + }); + return 'applied'; +} + +// ── Reconciliation ──────────────────────────────────────────────────────────── + +export interface CircleReconcileReport { + checked: number; + updated: string[]; + mismatched: string[]; + errors: Array<{ paymentId: string; error: string }>; +} + +/** + * Poll Circle for payments that are still unsettled after `staleAfterMs` + * (their webhook was lost or delayed) and bring the ledger up to date. + * One failing lookup never aborts the sweep. + */ +export async function reconcileCirclePayments(options: { + ledger: CircleLedger; + adapter: CircleAdapter; + staleAfterMs: number; + nowMs?: number; + logger?: CircleReconcileLogger; +}): Promise { + const logger = options.logger ?? noopLogger; + const nowMs = options.nowMs ?? Date.now(); + const unsettled = await options.ledger.listUnsettled(new Date(nowMs - options.staleAfterMs).toISOString()); + const report: CircleReconcileReport = { checked: unsettled.length, updated: [], mismatched: [], errors: [] }; + + for (const entry of unsettled) { + try { + const payment = await options.adapter.fetchPayment(entry.paymentId); + if (payment.amountMicro !== entry.expectedAmountMicro) { + report.mismatched.push(entry.paymentId); + logger.warn('[circle] reconciliation amount mismatch', { + paymentId: entry.paymentId, + expected: entry.expectedAmountMicro, + received: payment.amountMicro, + }); + continue; + } + if (RANK[payment.status] > RANK[entry.status]) { + await options.ledger.put({ ...entry, status: payment.status, updatedAt: new Date(nowMs).toISOString() }); + report.updated.push(entry.paymentId); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + report.errors.push({ paymentId: entry.paymentId, error: message }); + logger.warn('[circle] reconciliation lookup failed', { paymentId: entry.paymentId, error: message }); + } + } + logger.info('[circle] reconciliation complete', { + checked: report.checked, + updated: report.updated.length, + mismatched: report.mismatched.length, + errors: report.errors.length, + }); + return report; +} diff --git a/backend/src/gateways/shopify.ts b/backend/src/gateways/shopify.ts index 0451ff10..a184e00a 100644 --- a/backend/src/gateways/shopify.ts +++ b/backend/src/gateways/shopify.ts @@ -13,12 +13,24 @@ * 3. Exposes an Express middleware (`shopifyWebhookMiddleware`) that * requires the raw body buffer (use `express.raw()` on the route). * + * The second half of the module is the Shopify App Subscription billing + * adapter (`createShopifyBillingAdapter`) with idempotent retries. + * * References: * https://shopify.dev/docs/apps/build/webhooks/secure/validate-webhooks */ import crypto from 'crypto'; import type { Request, Response, NextFunction } from 'express'; +import { + BillingAdapterError, + noopBillingTelemetry, + withIdempotentRetry, + type BillingMoney, + type BillingOperation, + type BillingTelemetry, + type RetryPolicy, +} from './billingAdapter'; // ── Constants ───────────────────────────────────────────────────────────────── @@ -207,3 +219,224 @@ function getHeader( if (Array.isArray(val)) return val[0]; return val; } + +// ── Billing adapter (Shopify App Subscriptions, Admin GraphQL API) ──────────── +// +// Shopify's appSubscriptionCreate has no server-side idempotency header, so +// idempotency is enforced here: one in-flight/settled result per caller key, +// shared across concurrent callers and across retries. Throttling (HTTP 429, +// THROTTLED GraphQL errors) and 5xx are retried with backoff using the same key. + +/** Narrow GraphQL transport. Inject the Admin API client. */ +export interface ShopifyGraphqlTransport { + query( + query: string, + variables: Record, + ): Promise<{ status: number; body: Record }>; +} + +export type ShopifyInterval = 'EVERY_30_DAYS' | 'ANNUAL'; + +export interface ShopifyCreateSubscriptionRequest { + idempotencyKey: string; + name: string; + returnUrl: string; + /** Integer minor units; converted to the decimal string Shopify expects. */ + price: BillingMoney; + interval?: ShopifyInterval; + trialDays?: number; + /** Creates a test charge that is never billed. */ + test?: boolean; +} + +export interface ShopifySubscriptionResult { + subscriptionId: string; + status: string; + /** Merchant must open this URL to approve the charge. Absent on cancel/fetch. */ + confirmationUrl?: string; +} + +export interface ShopifyBillingAdapter { + createSubscription(request: ShopifyCreateSubscriptionRequest): Promise; + cancelSubscription(request: { idempotencyKey: string; subscriptionId: string }): Promise; + fetchSubscription(subscriptionId: string): Promise; +} + +export interface ShopifyBillingAdapterOptions { + transport: ShopifyGraphqlTransport; + telemetry?: BillingTelemetry; + retry?: RetryPolicy; + now?: () => number; +} + +const CREATE_MUTATION = `mutation($name: String!, $returnUrl: URL!, $trialDays: Int, $test: Boolean, $lineItems: [AppSubscriptionLineItemInput!]!) { + appSubscriptionCreate(name: $name, returnUrl: $returnUrl, trialDays: $trialDays, test: $test, lineItems: $lineItems) { + appSubscription { id status } + confirmationUrl + userErrors { field message } + } +}`; +const CANCEL_MUTATION = `mutation($id: ID!) { + appSubscriptionCancel(id: $id) { + appSubscription { id status } + userErrors { field message } + } +}`; +const FETCH_QUERY = `query($id: ID!) { node(id: $id) { ... on AppSubscription { id status } } }`; + +/** Integer minor units → "19.99" without floating-point arithmetic. */ +export function minorToDecimalString(amountMinor: number): string { + const whole = Math.trunc(amountMinor / 100); + const cents = String(amountMinor % 100).padStart(2, '0'); + return `${whole}.${cents}`; +} + +export function createShopifyBillingAdapter(options: ShopifyBillingAdapterOptions): ShopifyBillingAdapter { + const telemetry = options.telemetry ?? noopBillingTelemetry; + const now = options.now ?? (() => Date.now()); + const settled = new Map>(); + + const reject = (code: 'INVALID_REQUEST' | 'INVALID_RESPONSE', message: string) => + new BillingAdapterError(code, 'shopify', message); + + const run = async ( + query: string, + variables: Record, + ): Promise> => + withIdempotentRetry(async () => { + let response: { status: number; body: Record }; + try { + response = await options.transport.query(query, variables); + } catch (error) { + throw new BillingAdapterError('PROVIDER_UNAVAILABLE', 'shopify', 'Shopify transport failed', true, error); + } + const errors = response.body?.errors as Array<{ message?: string; extensions?: { code?: string } }> | undefined; + const throttled = response.status === 429 || errors?.some((e) => e.extensions?.code === 'THROTTLED'); + if (throttled) throw new BillingAdapterError('RATE_LIMITED', 'shopify', 'Shopify throttled the request', true); + if (response.status >= 500) { + throw new BillingAdapterError('PROVIDER_UNAVAILABLE', 'shopify', `Shopify returned ${response.status}`, true); + } + if (response.status < 200 || response.status >= 300 || (errors && errors.length > 0)) { + throw new BillingAdapterError( + 'PROVIDER_REJECTED', + 'shopify', + errors?.[0]?.message ?? `Shopify returned ${response.status}`, + ); + } + return (response.body.data ?? {}) as Record; + }, options.retry); + + const observe = async (operation: BillingOperation, fn: () => Promise): Promise => { + const started = now(); + try { + const result = await fn(); + telemetry.record({ operation, provider: 'shopify', outcome: 'success', durationMs: now() - started }); + return result; + } catch (error) { + telemetry.record({ + operation, + provider: 'shopify', + outcome: 'failure', + durationMs: now() - started, + errorCode: error instanceof BillingAdapterError ? error.code : 'UNKNOWN', + }); + throw error; + } + }; + + /** Run `fn` at most once per key; concurrent and later callers share the result. */ + const once = (scope: string, key: string, fn: () => Promise): Promise => { + if (typeof key !== 'string' || key.trim() === '') { + return Promise.reject(reject('INVALID_REQUEST', 'idempotencyKey is required')); + } + const id = `${scope}:${key}`; + const existing = settled.get(id); + if (existing) return existing as Promise; + const promise = fn().catch((error) => { + settled.delete(id); // failures are not cached: the caller may retry the same key + throw error; + }); + settled.set(id, promise); + return promise; + }; + + const parse = (node: unknown, confirmationUrl?: unknown): ShopifySubscriptionResult => { + const sub = node as { id?: unknown; status?: unknown } | null; + if (!sub || typeof sub.id !== 'string' || typeof sub.status !== 'string') { + throw reject('INVALID_RESPONSE', 'Shopify response is missing the app subscription'); + } + return { + subscriptionId: sub.id, + status: sub.status, + ...(typeof confirmationUrl === 'string' ? { confirmationUrl } : {}), + }; + }; + + const userErrors = (payload: Record | undefined): void => { + const list = payload?.userErrors as Array<{ message?: string }> | undefined; + if (list && list.length > 0) { + throw new BillingAdapterError( + 'PROVIDER_REJECTED', + 'shopify', + list.map((e) => e.message ?? 'Unknown error').join('; '), + ); + } + }; + + return { + createSubscription: (request) => + once('create', request.idempotencyKey, () => + observe('charge', async () => { + if (!request.name || !request.returnUrl) { + throw reject('INVALID_REQUEST', 'name and returnUrl are required'); + } + if (!Number.isSafeInteger(request.price.amountMinor) || request.price.amountMinor <= 0) { + throw reject('INVALID_REQUEST', 'price.amountMinor must be a positive integer'); + } + if (!/^[A-Z]{3}$/.test(request.price.currency)) { + throw reject('INVALID_REQUEST', 'price.currency must be a three-letter upper-case ISO code'); + } + const data = await run(CREATE_MUTATION, { + name: request.name, + returnUrl: request.returnUrl, + trialDays: request.trialDays, + test: request.test ?? false, + lineItems: [ + { + plan: { + appRecurringPricingDetails: { + interval: request.interval ?? 'EVERY_30_DAYS', + price: { + amount: minorToDecimalString(request.price.amountMinor), + currencyCode: request.price.currency, + }, + }, + }, + }, + ], + }); + const payload = data.appSubscriptionCreate as Record | undefined; + userErrors(payload); + return parse(payload?.appSubscription, payload?.confirmationUrl); + }), + ), + + cancelSubscription: (request) => + once('cancel', `${request.idempotencyKey}:${request.subscriptionId}`, () => + observe('cancel', async () => { + if (!request.subscriptionId) throw reject('INVALID_REQUEST', 'subscriptionId is required'); + const data = await run(CANCEL_MUTATION, { id: request.subscriptionId }); + const payload = data.appSubscriptionCancel as Record | undefined; + userErrors(payload); + return parse(payload?.appSubscription); + }), + ), + + fetchSubscription: (subscriptionId) => + observe('fetch', async () => { + if (!subscriptionId) throw reject('INVALID_REQUEST', 'subscriptionId is required'); + const data = await run(FETCH_QUERY, { id: subscriptionId }); + return parse(data.node); + }), + }; +} diff --git a/backend/src/gateways/stripe.ts b/backend/src/gateways/stripe.ts new file mode 100644 index 00000000..2ad07e20 --- /dev/null +++ b/backend/src/gateways/stripe.ts @@ -0,0 +1,363 @@ +/** + * backend/src/gateways/stripe.ts + * + * Stripe subscription adapter with proration on plan change. + * + * Sits beside the generic charge/refund adapter in `billingAdapter.ts` and + * covers the subscription lifecycle: create, change plan, cancel and fetch. + * + * - `calculateProration` is a pure, integer-only preview of what a mid-cycle + * plan change costs (unused credit on the old plan, remaining charge on the + * new one). The same `prorationDate` is sent to Stripe, so the preview and + * the invoice Stripe generates agree. + * - Every mutating call carries the caller's idempotency key and is retried + * (429/5xx/transport errors) with the SAME key, so a retry can never + * double-apply a plan change. + * - Each call emits a telemetry event (duration, outcome, error code). + */ + +import { + BillingAdapterError, + noopBillingTelemetry, + withIdempotentRetry, + type BillingOperation, + type BillingTelemetry, + type BillingTransport, + type BillingTransportResponse, + type RetryPolicy, +} from './billingAdapter'; + +// ── Types ───────────────────────────────────────────────────────────────────── + +export type StripeProrationBehavior = 'create_prorations' | 'none' | 'always_invoice'; + +export interface StripePlan { + priceId: string; + /** Price per billing period, integer minor units. */ + amountMinor: number; +} + +export interface StripeProrationInput { + currentPlan: StripePlan; + newPlan: StripePlan; + /** Current billing period, epoch seconds. */ + periodStart: number; + periodEnd: number; + /** Moment of the change, epoch seconds. Must fall inside the period. */ + changeAt: number; + quantity?: number; +} + +export interface StripeProration { + /** Credit for the unused part of the old plan (>= 0). */ + creditMinor: number; + /** Charge for the remaining part of the new plan (>= 0). */ + chargeMinor: number; + /** charge - credit. Negative means the customer is owed a credit. */ + netMinor: number; + /** Fraction of the period left, as remainingSeconds / totalSeconds. */ + remainingSeconds: number; + totalSeconds: number; +} + +export interface StripeSubscriptionResult { + subscriptionId: string; + status: string; + priceId: string; + itemId: string; + currentPeriodStart: number; + currentPeriodEnd: number; + cancelAtPeriodEnd: boolean; +} + +export interface StripeCreateSubscriptionRequest { + idempotencyKey: string; + customerId: string; + priceId: string; + quantity?: number; +} + +export interface StripeChangePlanRequest { + idempotencyKey: string; + subscriptionId: string; + newPriceId: string; + /** Defaults to `create_prorations`. */ + prorationBehavior?: StripeProrationBehavior; + /** Epoch seconds the proration is computed at. Defaults to adapter clock. */ + prorationDate?: number; +} + +export interface StripeCancelRequest { + idempotencyKey: string; + subscriptionId: string; + atPeriodEnd?: boolean; +} + +export interface StripeSubscriptionAdapter { + createSubscription(request: StripeCreateSubscriptionRequest): Promise; + /** Preview the proration without changing anything. */ + previewPlanChange(subscriptionId: string, newPlan: StripePlan, quantity?: number): Promise; + changePlan( + request: StripeChangePlanRequest, + ): Promise; + cancelSubscription(request: StripeCancelRequest): Promise; + fetchSubscription(subscriptionId: string): Promise; +} + +export interface StripeSubscriptionAdapterOptions { + transport: BillingTransport; + telemetry?: BillingTelemetry; + retry?: RetryPolicy; + /** Epoch ms clock. */ + now?: () => number; +} + +// ── Proration ───────────────────────────────────────────────────────────────── + +/** + * Time-based proration in integer minor units. Amounts are rounded half-up per + * leg, so credit and charge are each whole minor units and `net` is exact. + */ +export function calculateProration(input: StripeProrationInput): StripeProration { + const { currentPlan, newPlan, periodStart, periodEnd, changeAt } = input; + const quantity = input.quantity ?? 1; + for (const [label, value] of [ + ['currentPlan.amountMinor', currentPlan.amountMinor], + ['newPlan.amountMinor', newPlan.amountMinor], + ] as const) { + if (!Number.isSafeInteger(value) || value < 0) { + throw new BillingAdapterError('INVALID_REQUEST', 'stripe', `${label} must be a non-negative integer`); + } + } + if (!Number.isSafeInteger(quantity) || quantity <= 0) { + throw new BillingAdapterError('INVALID_REQUEST', 'stripe', 'quantity must be a positive integer'); + } + const totalSeconds = periodEnd - periodStart; + if (!(totalSeconds > 0)) { + throw new BillingAdapterError('INVALID_REQUEST', 'stripe', 'periodEnd must be after periodStart'); + } + if (changeAt < periodStart || changeAt > periodEnd) { + throw new BillingAdapterError('INVALID_REQUEST', 'stripe', 'changeAt must fall inside the billing period'); + } + const remainingSeconds = periodEnd - changeAt; + const prorate = (amountMinor: number) => + Math.floor((amountMinor * quantity * remainingSeconds * 2 + totalSeconds) / (totalSeconds * 2)); + const creditMinor = prorate(currentPlan.amountMinor); + const chargeMinor = prorate(newPlan.amountMinor); + return { creditMinor, chargeMinor, netMinor: chargeMinor - creditMinor, remainingSeconds, totalSeconds }; +} + +// ── Response parsing ────────────────────────────────────────────────────────── + +function str(value: unknown, label: string): string { + if (typeof value !== 'string' || value.length === 0) { + throw new BillingAdapterError('INVALID_RESPONSE', 'stripe', `Stripe response is missing "${label}"`); + } + return value; +} + +function num(value: unknown, label: string): number { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new BillingAdapterError('INVALID_RESPONSE', 'stripe', `Stripe response is missing numeric "${label}"`); + } + return value; +} + +interface ParsedItem { + itemId: string; + priceId: string; + amountMinor: number; + quantity: number; +} + +function firstItem(body: Record): ParsedItem { + const items = (body.items as { data?: Array> } | undefined)?.data; + const item = items?.[0]; + if (!item) { + throw new BillingAdapterError('INVALID_RESPONSE', 'stripe', 'Stripe subscription has no items'); + } + const price = (item.price ?? {}) as Record; + return { + itemId: str(item.id, 'items.data[0].id'), + priceId: str(price.id, 'items.data[0].price.id'), + amountMinor: num(price.unit_amount, 'items.data[0].price.unit_amount'), + quantity: typeof item.quantity === 'number' ? item.quantity : 1, + }; +} + +function parseSubscription(body: Record): StripeSubscriptionResult { + const item = firstItem(body); + return { + subscriptionId: str(body.id, 'id'), + status: str(body.status, 'status'), + priceId: item.priceId, + itemId: item.itemId, + currentPeriodStart: num(body.current_period_start, 'current_period_start'), + currentPeriodEnd: num(body.current_period_end, 'current_period_end'), + cancelAtPeriodEnd: body.cancel_at_period_end === true, + }; +} + +function errorMessage(body: Record): string { + const error = body?.error as Record | string | undefined; + if (typeof error === 'string') return error; + if (error && typeof error.message === 'string') return error.message; + return 'Stripe rejected the request'; +} + +// ── Adapter ─────────────────────────────────────────────────────────────────── + +export function createStripeSubscriptionAdapter( + options: StripeSubscriptionAdapterOptions, +): StripeSubscriptionAdapter { + const telemetry = options.telemetry ?? noopBillingTelemetry; + const now = options.now ?? (() => Date.now()); + + const send = async ( + method: 'GET' | 'POST', + path: string, + body?: Record, + idempotencyKey?: string, + ): Promise> => + withIdempotentRetry(async () => { + let response: BillingTransportResponse; + try { + response = await options.transport.request({ method, path, body, idempotencyKey }); + } catch (error) { + throw new BillingAdapterError('PROVIDER_UNAVAILABLE', 'stripe', 'Stripe transport failed', true, error); + } + if (response.status >= 200 && response.status < 300) return response.body; + const message = errorMessage(response.body ?? {}); + if (response.status === 429) throw new BillingAdapterError('RATE_LIMITED', 'stripe', message, true, response); + if (response.status >= 500) { + throw new BillingAdapterError('PROVIDER_UNAVAILABLE', 'stripe', message, true, response); + } + throw new BillingAdapterError( + response.status === 404 ? 'UNKNOWN' : 'PROVIDER_REJECTED', + 'stripe', + message, + false, + response, + ); + }, options.retry); + + const observe = async (operation: BillingOperation, fn: () => Promise): Promise => { + const started = now(); + try { + const result = await fn(); + telemetry.record({ operation, provider: 'stripe', outcome: 'success', durationMs: now() - started }); + return result; + } catch (error) { + telemetry.record({ + operation, + provider: 'stripe', + outcome: 'failure', + durationMs: now() - started, + errorCode: error instanceof BillingAdapterError ? error.code : 'UNKNOWN', + }); + throw error; + } + }; + + const requireKey = (key: string) => { + if (typeof key !== 'string' || key.trim() === '') { + throw new BillingAdapterError('INVALID_REQUEST', 'stripe', 'idempotencyKey is required'); + } + }; + const requireId = (value: string, label: string) => { + if (typeof value !== 'string' || value.trim() === '') { + throw new BillingAdapterError('INVALID_REQUEST', 'stripe', `${label} is required`); + } + }; + const subPath = (id: string) => `/v1/subscriptions/${encodeURIComponent(id)}`; + + const adapter: StripeSubscriptionAdapter = { + createSubscription: (request) => + observe('charge', async () => { + requireKey(request.idempotencyKey); + requireId(request.customerId, 'customerId'); + requireId(request.priceId, 'priceId'); + const body = await send( + 'POST', + '/v1/subscriptions', + { + customer: request.customerId, + items: [{ price: request.priceId, quantity: request.quantity ?? 1 }], + }, + request.idempotencyKey, + ); + return parseSubscription(body); + }), + + fetchSubscription: (subscriptionId) => + observe('fetch', async () => { + requireId(subscriptionId, 'subscriptionId'); + return parseSubscription(await send('GET', subPath(subscriptionId))); + }), + + previewPlanChange: (subscriptionId, newPlan, quantity) => + observe('fetch', async () => { + requireId(subscriptionId, 'subscriptionId'); + const body = await send('GET', subPath(subscriptionId)); + const sub = parseSubscription(body); + const item = firstItem(body); + return calculateProration({ + currentPlan: { priceId: item.priceId, amountMinor: item.amountMinor }, + newPlan, + periodStart: sub.currentPeriodStart, + periodEnd: sub.currentPeriodEnd, + changeAt: Math.floor(now() / 1000), + quantity: quantity ?? item.quantity, + }); + }), + + changePlan: (request) => + observe('charge', async () => { + requireKey(request.idempotencyKey); + requireId(request.subscriptionId, 'subscriptionId'); + requireId(request.newPriceId, 'newPriceId'); + const current = await send('GET', subPath(request.subscriptionId)); + const item = firstItem(current); + if (item.priceId === request.newPriceId) { + throw new BillingAdapterError('INVALID_REQUEST', 'stripe', 'Subscription is already on that price'); + } + const behavior = request.prorationBehavior ?? 'create_prorations'; + const prorationDate = request.prorationDate ?? Math.floor(now() / 1000); + const updated = await send( + 'POST', + subPath(request.subscriptionId), + { + items: [{ id: item.itemId, price: request.newPriceId }], + proration_behavior: behavior, + proration_date: prorationDate, + }, + request.idempotencyKey, + ); + const result = parseSubscription(updated); + if (behavior === 'none') return result; + const newItem = firstItem(updated); + return { + ...result, + proration: calculateProration({ + currentPlan: { priceId: item.priceId, amountMinor: item.amountMinor }, + newPlan: { priceId: newItem.priceId, amountMinor: newItem.amountMinor }, + periodStart: result.currentPeriodStart, + periodEnd: result.currentPeriodEnd, + changeAt: Math.min(Math.max(prorationDate, result.currentPeriodStart), result.currentPeriodEnd), + quantity: item.quantity, + }), + }; + }), + + cancelSubscription: (request) => + observe('cancel', async () => { + requireKey(request.idempotencyKey); + requireId(request.subscriptionId, 'subscriptionId'); + const body = request.atPeriodEnd + ? await send('POST', subPath(request.subscriptionId), { cancel_at_period_end: true }, request.idempotencyKey) + : await send('POST', `${subPath(request.subscriptionId)}/cancel`, {}, request.idempotencyKey); + return parseSubscription(body); + }), + }; + return adapter; +} diff --git a/backend/src/services/__tests__/import.test.ts b/backend/src/services/__tests__/import.test.ts new file mode 100644 index 00000000..30bff0f5 --- /dev/null +++ b/backend/src/services/__tests__/import.test.ts @@ -0,0 +1,205 @@ +import { + importSubscriptions, + parseCsv, + parsePriceMinor, + duplicateKey, + ImportError, + type ImportSubscriptionInput, +} from '../import'; + +const HEADER = 'name,price,currency,billing_cycle,next_billing_date,category'; + +function deps(existing: Array<{ name: string; currency: string; billingCycle: string }> = []) { + const created: ImportSubscriptionInput[] = []; + const logger = { info: jest.fn(), warn: jest.fn() }; + return { + created, + logger, + deps: { + existing, + logger, + create: jest.fn(async (input: ImportSubscriptionInput) => { + created.push(input); + return { id: `sub_${created.length}` }; + }), + }, + }; +} + +describe('parseCsv', () => { + it('handles quotes, escaped quotes, embedded commas/newlines, CRLF and BOM', () => { + const rows = parseCsv('a,b\r\n"x, y","say ""hi"""\r\n"multi\nline",z\n'); + expect(rows).toEqual([ + ['a', 'b'], + ['x, y', 'say "hi"'], + ['multi\nline', 'z'], + ]); + }); + + it('rejects an unterminated quote', () => { + expect(() => parseCsv('a,"oops')).toThrow(ImportError); + }); +}); + +describe('parsePriceMinor', () => { + it.each([ + ['9.99', 999], + ['10', 1000], + ['0.5', 50], + ])('parses %s', (raw, minor) => expect(parsePriceMinor(raw)).toBe(minor)); + + it.each(['0', '-1', '1.234', 'abc', '', '1e3'])('rejects %p', (raw) => + expect(parsePriceMinor(raw)).toBeUndefined(), + ); +}); + +describe('importSubscriptions', () => { + it('creates valid rows and normalises values', async () => { + const { deps: d, created } = deps(); + const summary = await importSubscriptions( + `${HEADER}\nNetflix,15.49,usd,Monthly,2026-12-01,Streaming\n`, + d, + ); + expect(summary).toMatchObject({ total: 1, created: 1, duplicates: 0, failed: 0, dryRun: false }); + expect(created[0]).toEqual({ + name: 'Netflix', + priceMinor: 1549, + currency: 'USD', + billingCycle: 'monthly', + nextBillingDate: '2026-12-01', + category: 'Streaming', + }); + expect(summary.rows[0]).toMatchObject({ line: 2, status: 'created', id: 'sub_1' }); + }); + + it('accepts columns in any order and ignores unknown ones with a warning', async () => { + const { deps: d, created, logger } = deps(); + await importSubscriptions('billing_cycle,currency,price,name,color\nyearly,eur,99,Spotify,green\n', d); + expect(created[0]).toMatchObject({ name: 'Spotify', priceMinor: 9900, currency: 'EUR' }); + expect(logger.warn).toHaveBeenCalledWith('[import] ignoring unknown columns', { columns: ['color'] }); + }); + + it('reports per-row errors without blocking valid rows', async () => { + const { deps: d } = deps(); + const summary = await importSubscriptions( + [ + HEADER, + 'Good,5,USD,monthly,,', + ',5,USD,monthly,,', + 'BadPrice,-3,USD,monthly,,', + 'BadCycle,5,USD,fortnightly,,', + 'BadCur,5,DOLLARS,monthly,,', + 'BadDate,5,USD,monthly,2026-02-31,', + 'AlsoGood,7,USD,weekly,,', + ].join('\n'), + d, + ); + expect(summary.created).toBe(2); + expect(summary.failed).toBe(5); + const byLine = Object.fromEntries(summary.rows.map((r) => [r.line, r])); + expect(byLine[3].errors.map((e) => e.field)).toEqual(['name']); + expect(byLine[4].errors.map((e) => e.field)).toEqual(['price']); + expect(byLine[5].errors.map((e) => e.field)).toEqual(['billing_cycle']); + expect(byLine[6].errors.map((e) => e.field)).toEqual(['currency']); + expect(byLine[7].errors.map((e) => e.field)).toEqual(['next_billing_date']); + expect(byLine[8].status).toBe('created'); + }); + + it('collects every error on a row', async () => { + const { deps: d } = deps(); + const summary = await importSubscriptions(`${HEADER}\n,0,X,never,nope,\n`, d); + expect(summary.rows[0].errors.map((e) => e.field)).toEqual([ + 'name', + 'price', + 'currency', + 'billing_cycle', + 'next_billing_date', + ]); + }); + + it('detects duplicates against existing subscriptions (case/space-insensitive)', async () => { + const { deps: d, created } = deps([{ name: 'netflix', currency: 'USD', billingCycle: 'monthly' }]); + const summary = await importSubscriptions(`${HEADER}\n NETFLIX ,15,usd,monthly,,\n`, d); + expect(created).toHaveLength(0); + expect(summary.duplicates).toBe(1); + expect(summary.rows[0]).toMatchObject({ status: 'duplicate', duplicateOf: 'existing' }); + }); + + it('detects duplicates within the same file and points at the first occurrence', async () => { + const { deps: d, created } = deps(); + const summary = await importSubscriptions( + `${HEADER}\nHulu,8,USD,monthly,,\nHulu,9,USD,monthly,,\nHulu,8,USD,yearly,,\n`, + d, + ); + expect(created.map((c) => c.billingCycle)).toEqual(['monthly', 'yearly']); + expect(summary.rows[1]).toMatchObject({ status: 'duplicate', duplicateOf: { line: 2 } }); + }); + + it('turns a create() failure into a row error and lets a later identical row retry', async () => { + const d = deps(); + d.deps.create.mockRejectedValueOnce(new Error('db down')); + const summary = await importSubscriptions(`${HEADER}\nHulu,8,USD,monthly,,\nHulu,8,USD,monthly,,\n`, d.deps); + expect(summary.rows[0]).toMatchObject({ status: 'error', errors: [{ field: '*', message: 'db down' }] }); + expect(summary.rows[1].status).toBe('created'); + }); + + it('dry run validates and dedupes but never calls create', async () => { + const d = deps(); + const summary = await importSubscriptions(`${HEADER}\nA,1,USD,monthly,,\nA,1,USD,monthly,,\n,1,USD,monthly,,\n`, d.deps, { + dryRun: true, + }); + expect(d.deps.create).not.toHaveBeenCalled(); + expect(summary).toMatchObject({ dryRun: true, created: 1, duplicates: 1, failed: 1 }); + expect(summary.rows[0].status).toBe('would_create'); + }); + + it('keeps source line numbers across blank lines', async () => { + const d = deps(); + const summary = await importSubscriptions(`${HEADER}\n\nA,1,USD,monthly,,\n\n,1,USD,monthly,,\n`, d.deps); + expect(summary.rows.map((r) => r.line)).toEqual([3, 5]); + }); + + it('flags rows with extra populated columns', async () => { + const d = deps(); + const summary = await importSubscriptions('name,price,currency,billing_cycle\nA,1,USD,monthly,surprise\n', d.deps); + expect(summary.rows[0].errors[0].message).toMatch(/5 columns but the header has 4/); + }); + + it('rejects structurally bad files with typed errors', async () => { + const d = deps(); + await expect(importSubscriptions('', d.deps)).rejects.toMatchObject({ code: 'EMPTY_FILE' }); + await expect(importSubscriptions('name,price\nA,1\n', d.deps)).rejects.toMatchObject({ + code: 'MISSING_COLUMNS', + message: expect.stringContaining('currency, billing_cycle'), + }); + await expect( + importSubscriptions(`${HEADER}\nA,1,USD,monthly,,\nB,1,USD,monthly,,\n`, d.deps, { maxRows: 1 }), + ).rejects.toMatchObject({ code: 'TOO_MANY_ROWS' }); + }); + + it('logs a summary for observability', async () => { + const d = deps(); + await importSubscriptions(`${HEADER}\nA,1,USD,monthly,,\n`, d.deps); + expect(d.logger.info).toHaveBeenCalledWith( + '[import] subscription import finished', + expect.objectContaining({ total: 1, created: 1, failed: 0 }), + ); + }); + + it('re-running the same file creates nothing new', async () => { + const d = deps(); + const csv = `${HEADER}\nA,1,USD,monthly,,\nB,2,USD,yearly,,\n`; + await importSubscriptions(csv, d.deps); + const second = await importSubscriptions( + csv, + { ...d.deps, existing: d.created.map((c) => ({ name: c.name, currency: c.currency, billingCycle: c.billingCycle })) }, + ); + expect(second).toMatchObject({ created: 0, duplicates: 2 }); + }); +}); + +describe('duplicateKey', () => { + it('collapses whitespace and case', () => { + expect(duplicateKey(' My App ', 'usd', 'Monthly')).toBe('my app|USD|monthly'); + }); +}); diff --git a/backend/src/services/__tests__/importCli.test.ts b/backend/src/services/__tests__/importCli.test.ts new file mode 100644 index 00000000..b728a16d --- /dev/null +++ b/backend/src/services/__tests__/importCli.test.ts @@ -0,0 +1,122 @@ +/** End-to-end test of `subtrackr subscriptions import` against a local fake API. */ +import { spawn } from 'child_process'; +import fs from 'fs'; +import http from 'http'; +import os from 'os'; +import path from 'path'; + +const CLI = path.resolve(__dirname, '../../../../bin/subtrackr.js'); + +interface Fake { + url: string; + posted: Array>; + close(): Promise; +} + +async function startFakeApi(existing: unknown[], rejectName?: string): Promise { + const posted: Array> = []; + const server = http.createServer((req, res) => { + let raw = ''; + req.on('data', (d) => (raw += d)); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + if (req.method === 'GET') return res.end(JSON.stringify({ data: existing })); + const body = JSON.parse(raw); + if (body.name === rejectName) { + res.statusCode = 422; + return res.end(JSON.stringify({ error: 'rejected by server' })); + } + posted.push(body); + res.statusCode = 201; + res.end(JSON.stringify({ id: posted.length })); + }); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}`, + posted, + close: () => new Promise((r) => server.close(() => r())), + }; +} + +function runCli(args: string[], baseUrl: string): Promise<{ code: number | null; stdout: string; stderr: string }> { + return new Promise((resolve) => { + const child = spawn( + process.execPath, + [CLI, ...args, '--api-key', 'sk_test', '--base-url', baseUrl, '--no-summary', '--format', 'json'], + { env: { ...process.env, HOME: os.tmpdir(), NO_COLOR: '1' } }, + ); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (d) => (stdout += d)); + child.stderr.on('data', (d) => (stderr += d)); + child.on('close', (code) => resolve({ code, stdout, stderr })); + }); +} + +function csvFile(content: string): string { + const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'import-')), 'subs.csv'); + fs.writeFileSync(file, content); + return file; +} + +const CSV = [ + 'name,price,currency,billing_cycle', + 'Netflix,15.49,USD,monthly', + 'Existing,5,USD,monthly', + 'Netflix,15.49,usd,monthly', + 'Broken,abc,USD,monthly', + 'ServerNo,3,USD,monthly', +].join('\n'); + +describe('subtrackr subscriptions import', () => { + it('imports, skips duplicates, reports per-row errors and exits non-zero on failures', async () => { + const api = await startFakeApi([{ name: 'Existing', currency: 'USD', billing_cycle: 'monthly' }], 'ServerNo'); + try { + const { code, stdout } = await runCli(['subscriptions', 'import', csvFile(CSV)], api.url); + const summary = JSON.parse(stdout); + expect(code).toBe(1); + expect(summary).toMatchObject({ total: 5, created: 1, duplicates: 2, failed: 2, dryRun: false }); + expect(api.posted).toHaveLength(1); + expect(api.posted[0]).toMatchObject({ name: 'Netflix', price: 15.49, currency: 'USD', billing_cycle: 'monthly' }); + expect(summary.rows[3].errors[0]).toMatch(/price/); + expect(summary.rows[4].errors[0]).toMatch(/422/); + } finally { + await api.close(); + } + }); + + it('--dry-run (before or after the file) posts nothing', async () => { + const api = await startFakeApi([]); + try { + const file = csvFile('name,price,currency,billing_cycle\nA,1,USD,monthly\nB,2,USD,yearly\n'); + for (const args of [ + ['subscriptions', 'import', '--dry-run', file], + ['subscriptions', 'import', file, '--dry-run'], + ]) { + const { code, stdout } = await runCli(args, api.url); + expect(code).toBe(0); + expect(JSON.parse(stdout)).toMatchObject({ dryRun: true, created: 2, failed: 0 }); + } + expect(api.posted).toHaveLength(0); + } finally { + await api.close(); + } + }); + + it('fails fast on missing columns and unreadable files', async () => { + const api = await startFakeApi([]); + try { + const bad = await runCli(['subscriptions', 'import', csvFile('name,price\nA,1\n')], api.url); + expect(bad.code).toBe(1); + expect(bad.stderr).toMatch(/Missing required column/); + const none = await runCli(['subscriptions', 'import', '/nonexistent/file.csv'], api.url); + expect(none.code).toBe(1); + expect(none.stderr).toMatch(/Cannot read/); + expect(api.posted).toHaveLength(0); + } finally { + await api.close(); + } + }); +}); diff --git a/backend/src/services/import.ts b/backend/src/services/import.ts new file mode 100644 index 00000000..dc79851b --- /dev/null +++ b/backend/src/services/import.ts @@ -0,0 +1,301 @@ +/** + * backend/src/services/import.ts + * + * Bulk subscription import with duplicate detection and per-row errors. + * + * Takes CSV text, validates every row independently, detects duplicates + * (against subscriptions that already exist AND earlier rows in the same + * file), and creates the rest. One bad row never blocks the others: every row + * gets its own outcome with the line number and field-level errors, so users + * can fix just the failing lines and re-run (re-runs are safe because rows + * created last time now show up as duplicates). + * + * Expected header (case-insensitive, any column order): + * name, price, currency, billing_cycle, next_billing_date, category + * Only `name`, `price`, `currency` and `billing_cycle` are required. + * + * Storage and observability are injected so the module stays framework-free. + */ + +export const IMPORT_MAX_ROWS = 1000; + +export const BILLING_CYCLES = ['weekly', 'monthly', 'quarterly', 'yearly'] as const; +export type BillingCycle = (typeof BILLING_CYCLES)[number]; + +export interface ImportSubscriptionInput { + name: string; + /** Integer minor units (cents). */ + priceMinor: number; + currency: string; + billingCycle: BillingCycle; + nextBillingDate?: string; + category?: string; +} + +export interface ExistingSubscription { + name: string; + currency: string; + billingCycle: string; +} + +export interface ImportRowError { + field: string; + message: string; +} + +export type ImportRowStatus = 'created' | 'duplicate' | 'error' | 'would_create'; + +export interface ImportRowResult { + /** 1-based CSV record number (the header is record 1). */ + line: number; + status: ImportRowStatus; + name?: string; + id?: string; + errors: ImportRowError[]; + /** For duplicates: where the original is. */ + duplicateOf?: 'existing' | { line: number }; +} + +export interface ImportSummary { + total: number; + created: number; + duplicates: number; + failed: number; + dryRun: boolean; + rows: ImportRowResult[]; +} + +export interface ImportLogger { + info(message: string, meta?: Record): void; + warn(message: string, meta?: Record): void; +} + +export interface ImportDeps { + existing: ExistingSubscription[]; + /** Persist one subscription and return its id. A throw becomes a row error. */ + create(input: ImportSubscriptionInput): Promise<{ id: string }>; + logger?: ImportLogger; +} + +export interface ImportOptions { + /** Validate and detect duplicates without creating anything. */ + dryRun?: boolean; + maxRows?: number; +} + +export class ImportError extends Error { + constructor( + public readonly code: 'EMPTY_FILE' | 'MISSING_COLUMNS' | 'TOO_MANY_ROWS' | 'MALFORMED_CSV', + message: string, + ) { + super(message); + this.name = 'ImportError'; + } +} + +// ── CSV parsing (RFC 4180: quotes, escaped quotes, embedded newlines) ───────── + +export function parseCsv(text: string): string[][] { + const rows: string[][] = []; + let row: string[] = []; + let field = ''; + let inQuotes = false; + const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text; + + for (let i = 0; i < src.length; i++) { + const ch = src[i]; + if (inQuotes) { + if (ch === '"') { + if (src[i + 1] === '"') { + field += '"'; + i++; + } else { + inQuotes = false; + } + } else { + field += ch; + } + } else if (ch === '"' && field === '') { + inQuotes = true; + } else if (ch === ',') { + row.push(field); + field = ''; + } else if (ch === '\n' || ch === '\r') { + if (ch === '\r' && src[i + 1] === '\n') i++; + row.push(field); + rows.push(row); + row = []; + field = ''; + } else { + field += ch; + } + } + if (inQuotes) throw new ImportError('MALFORMED_CSV', 'Unterminated quoted field'); + if (field !== '' || row.length > 0) { + row.push(field); + rows.push(row); + } + return rows; +} + +// ── Row validation ──────────────────────────────────────────────────────────── + +const REQUIRED_COLUMNS = ['name', 'price', 'currency', 'billing_cycle'] as const; +const KNOWN_COLUMNS = [...REQUIRED_COLUMNS, 'next_billing_date', 'category']; + +/** "9.99" → 999. Rejects negatives, zero, and more than two decimals. */ +export function parsePriceMinor(raw: string): number | undefined { + const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(raw.trim()); + if (!match) return undefined; + const minor = Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0')); + return Number.isSafeInteger(minor) && minor > 0 ? minor : undefined; +} + +function isRealDate(value: string): boolean { + if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false; + const d = new Date(`${value}T00:00:00Z`); + return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === value; +} + +export function validateRow( + cells: Record, +): { input: ImportSubscriptionInput } | { errors: ImportRowError[] } { + const errors: ImportRowError[] = []; + const name = (cells.name ?? '').trim(); + if (!name) errors.push({ field: 'name', message: 'name is required' }); + else if (name.length > 120) errors.push({ field: 'name', message: 'name must be 120 characters or fewer' }); + + const priceMinor = parsePriceMinor(cells.price ?? ''); + if (priceMinor === undefined) { + errors.push({ field: 'price', message: 'price must be a positive number with at most 2 decimals' }); + } + + const currency = (cells.currency ?? '').trim().toUpperCase(); + if (!/^[A-Z]{3}$/.test(currency)) { + errors.push({ field: 'currency', message: 'currency must be a 3-letter ISO code' }); + } + + const cycle = (cells.billing_cycle ?? '').trim().toLowerCase(); + if (!(BILLING_CYCLES as readonly string[]).includes(cycle)) { + errors.push({ field: 'billing_cycle', message: `billing_cycle must be one of ${BILLING_CYCLES.join(', ')}` }); + } + + const next = (cells.next_billing_date ?? '').trim(); + if (next && !isRealDate(next)) { + errors.push({ field: 'next_billing_date', message: 'next_billing_date must be a real date as YYYY-MM-DD' }); + } + + if (errors.length > 0) return { errors }; + return { + input: { + name, + priceMinor: priceMinor as number, + currency, + billingCycle: cycle as BillingCycle, + ...(next ? { nextBillingDate: next } : {}), + ...((cells.category ?? '').trim() ? { category: cells.category.trim() } : {}), + }, + }; +} + +/** Same subscription = same name (case/space-insensitive), currency and cycle. */ +export function duplicateKey(name: string, currency: string, cycle: string): string { + return [name.trim().replace(/\s+/g, ' ').toLowerCase(), currency.trim().toUpperCase(), cycle.trim().toLowerCase()].join('|'); +} + +// ── Import ──────────────────────────────────────────────────────────────────── + +export async function importSubscriptions( + csv: string, + deps: ImportDeps, + options: ImportOptions = {}, +): Promise { + const dryRun = options.dryRun ?? false; + const maxRows = options.maxRows ?? IMPORT_MAX_ROWS; + const log: ImportLogger = deps.logger ?? { info: () => undefined, warn: () => undefined }; + + // `line` is the 1-based CSV record number, so blank lines still count. + const table = parseCsv(csv) + .map((cells, i) => ({ cells, line: i + 1 })) + .filter((r) => r.cells.some((c) => c.trim() !== '')); + if (table.length === 0) throw new ImportError('EMPTY_FILE', 'The file is empty'); + + const header = table[0].cells.map((h) => h.trim().toLowerCase()); + const missing = REQUIRED_COLUMNS.filter((c) => !header.includes(c)); + if (missing.length > 0) { + throw new ImportError('MISSING_COLUMNS', `Missing required column(s): ${missing.join(', ')}`); + } + const dataRows = table.slice(1); + if (dataRows.length > maxRows) { + throw new ImportError('TOO_MANY_ROWS', `Import is limited to ${maxRows} rows (got ${dataRows.length})`); + } + const unknown = header.filter((h) => !KNOWN_COLUMNS.includes(h)); + if (unknown.length > 0) log.warn('[import] ignoring unknown columns', { columns: unknown }); + + const seen = new Map(); + for (const e of deps.existing) seen.set(duplicateKey(e.name, e.currency, e.billingCycle), 'existing'); + + const results: ImportRowResult[] = []; + for (const { cells, line } of dataRows) { + const record: Record = {}; + header.forEach((h, i) => (record[h] = cells[i] ?? '')); + + if (cells.length > header.length && cells.slice(header.length).some((c) => c.trim() !== '')) { + results.push({ + line, + status: 'error', + name: record.name, + errors: [{ field: '*', message: `row has ${cells.length} columns but the header has ${header.length}` }], + }); + continue; + } + + const validated = validateRow(record); + if ('errors' in validated) { + results.push({ line, status: 'error', name: record.name?.trim() || undefined, errors: validated.errors }); + continue; + } + const { input } = validated; + const key = duplicateKey(input.name, input.currency, input.billingCycle); + const original = seen.get(key); + if (original) { + results.push({ line, status: 'duplicate', name: input.name, errors: [], duplicateOf: original }); + continue; + } + seen.set(key, { line }); + + if (dryRun) { + results.push({ line, status: 'would_create', name: input.name, errors: [] }); + continue; + } + try { + const { id } = await deps.create(input); + results.push({ line, status: 'created', name: input.name, id, errors: [] }); + } catch (error) { + seen.delete(key); + results.push({ + line, + status: 'error', + name: input.name, + errors: [{ field: '*', message: error instanceof Error ? error.message : String(error) }], + }); + } + } + + const summary: ImportSummary = { + total: results.length, + created: results.filter((r) => r.status === 'created' || r.status === 'would_create').length, + duplicates: results.filter((r) => r.status === 'duplicate').length, + failed: results.filter((r) => r.status === 'error').length, + dryRun, + rows: results, + }; + log.info('[import] subscription import finished', { + total: summary.total, + created: summary.created, + duplicates: summary.duplicates, + failed: summary.failed, + dryRun, + }); + return summary; +} diff --git a/bin/subtrackr.js b/bin/subtrackr.js index 96bc0a56..1dcd8a9f 100644 --- a/bin/subtrackr.js +++ b/bin/subtrackr.js @@ -234,6 +234,7 @@ ${c.bold('Commands:')} pause Pause a subscription resume Resume a paused subscription charge Manually trigger a charge cycle + import Bulk-import from CSV (--dry-run to preview) ${c.cyan('plans')} Manage subscription plans list List available plans @@ -817,6 +818,225 @@ async function cmdWebhookDelete(args, cfg) { ok(`Webhook ${c.cyan(id)} deleted.`); } +// ── Bulk import ─────────────────────────────────────────────────────────────── +// CSV columns: name, price, currency, billing_cycle (required); +// next_billing_date, category (optional). Rules mirror +// backend/src/services/import.ts, which is the authoritative validator. + +const IMPORT_REQUIRED = ['name', 'price', 'currency', 'billing_cycle']; +const IMPORT_CYCLES = ['weekly', 'monthly', 'quarterly', 'yearly']; +const IMPORT_MAX_ROWS = 1000; + +function parseCsv(text) { + const rows = []; + let row = []; + let field = ''; + let inQuotes = false; + const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text; + for (let i = 0; i < src.length; i++) { + const ch = src[i]; + if (inQuotes) { + if (ch === '"') { + if (src[i + 1] === '"') { + field += '"'; + i++; + } else inQuotes = false; + } else field += ch; + } else if (ch === '"' && field === '') inQuotes = true; + else if (ch === ',') { + row.push(field); + field = ''; + } else if (ch === '\n' || ch === '\r') { + if (ch === '\r' && src[i + 1] === '\n') i++; + row.push(field); + rows.push(row); + row = []; + field = ''; + } else field += ch; + } + if (inQuotes) throw new Error('Unterminated quoted field in CSV'); + if (field !== '' || row.length > 0) { + row.push(field); + rows.push(row); + } + return rows; +} + +function importRowErrors(rec) { + const errors = []; + if (!(rec.name || '').trim()) errors.push('name is required'); + if (!/^\d+(\.\d{1,2})?$/.test((rec.price || '').trim()) || Number(rec.price) <= 0) { + errors.push('price must be a positive number with at most 2 decimals'); + } + if (!/^[A-Za-z]{3}$/.test((rec.currency || '').trim())) + errors.push('currency must be a 3-letter code'); + if (!IMPORT_CYCLES.includes((rec.billing_cycle || '').trim().toLowerCase())) { + errors.push(`billing_cycle must be one of ${IMPORT_CYCLES.join(', ')}`); + } + const next = (rec.next_billing_date || '').trim(); + if (next && !(/^\d{4}-\d{2}-\d{2}$/.test(next) && !isNaN(Date.parse(next)))) { + errors.push('next_billing_date must be YYYY-MM-DD'); + } + return errors; +} + +function importKey(rec) { + return [ + (rec.name || '').trim().replace(/\s+/g, ' ').toLowerCase(), + (rec.currency || '').trim().toUpperCase(), + (rec.billing_cycle || '').trim().toLowerCase(), + ].join('|'); +} + +async function cmdSubImport(args, cfg) { + requireAuth(cfg); + // `--dry-run file.csv` makes the arg parser treat the file as the flag's value. + const dryRunOpt = args.options['dry-run']; + const file = args._[0] || dryRunOpt; + if (!file) { + fail('Usage: subtrackr subscriptions import [--dry-run]'); + process.exit(1); + } + let text; + try { + text = fs.readFileSync(file, 'utf8'); + } catch (e) { + fail(`Cannot read ${file}: ${e.message}`); + process.exit(1); + } + + let table; + try { + table = parseCsv(text) + .map((cells, i) => ({ cells, line: i + 1 })) + .filter((r) => r.cells.some((x) => x.trim() !== '')); + } catch (e) { + fail(e.message); + process.exit(1); + } + if (table.length === 0) { + fail('The file is empty.'); + process.exit(1); + } + const header = table[0].cells.map((h) => h.trim().toLowerCase()); + const missing = IMPORT_REQUIRED.filter((col) => !header.includes(col)); + if (missing.length) { + fail(`Missing required column(s): ${missing.join(', ')}`); + process.exit(1); + } + const dataRows = table.slice(1); + if (dataRows.length > IMPORT_MAX_ROWS) { + fail(`Import is limited to ${IMPORT_MAX_ROWS} rows (got ${dataRows.length}).`); + process.exit(1); + } + + const dryRun = Boolean(args.flags['dry-run']) || dryRunOpt !== undefined; + const existingRes = await apiRequest(cfg.baseUrl, '/v1/subscriptions', 'GET', null, cfg.apiKey); + if (existingRes.status !== 200) { + fail(`API error ${existingRes.status}: ${JSON.stringify(existingRes.body)}`); + process.exit(1); + } + const existing = Array.isArray(existingRes.body) + ? existingRes.body + : existingRes.body && existingRes.body.data + ? existingRes.body.data + : []; + const seen = new Map(); + for (const e of existing) { + seen.set( + importKey({ name: e.name, currency: e.currency, billing_cycle: e.billing_cycle }), + 'existing' + ); + } + + const results = []; + for (const { cells, line } of dataRows) { + const rec = {}; + header.forEach((h, i) => (rec[h] = cells[i] || '')); + const errors = importRowErrors(rec); + if (errors.length) { + results.push({ line, name: rec.name, status: 'error', errors }); + continue; + } + const key = importKey(rec); + if (seen.has(key)) { + const orig = seen.get(key); + results.push({ + line, + name: rec.name, + status: 'duplicate', + errors: [], + duplicateOf: orig === 'existing' ? 'existing subscription' : `line ${orig}`, + }); + continue; + } + seen.set(key, line); + if (dryRun) { + results.push({ line, name: rec.name, status: 'would_create', errors: [] }); + continue; + } + const body = { + name: rec.name.trim(), + price: parseFloat(rec.price), + currency: rec.currency.trim().toUpperCase(), + billing_cycle: rec.billing_cycle.trim().toLowerCase(), + ...(rec.next_billing_date && rec.next_billing_date.trim() + ? { next_billing_date: rec.next_billing_date.trim() } + : {}), + ...(rec.category && rec.category.trim() ? { category: rec.category.trim() } : {}), + }; + try { + const res = await apiRequest(cfg.baseUrl, '/v1/subscriptions', 'POST', body, cfg.apiKey); + if (res.status === 200 || res.status === 201) { + results.push({ + line, + name: rec.name, + status: 'created', + id: res.body && res.body.id, + errors: [], + }); + } else { + seen.delete(key); + results.push({ + line, + name: rec.name, + status: 'error', + errors: [`API error ${res.status}: ${JSON.stringify(res.body)}`], + }); + } + } catch (e) { + seen.delete(key); + results.push({ line, name: rec.name, status: 'error', errors: [e.message] }); + } + } + + const summary = { + total: results.length, + created: results.filter((r) => r.status === 'created' || r.status === 'would_create').length, + duplicates: results.filter((r) => r.status === 'duplicate').length, + failed: results.filter((r) => r.status === 'error').length, + dryRun, + rows: results, + }; + + const format = args.options['format'] || args.options['f']; + if (format === 'json') { + printOutput(summary, 'json'); + } else { + for (const r of results) { + if (r.status === 'error') + warn(`line ${r.line} (${r.name || 'unnamed'}): ${r.errors.join('; ')}`); + else if (r.status === 'duplicate') + info(`line ${r.line} (${r.name}): duplicate of ${r.duplicateOf}, skipped`); + } + const verb = dryRun ? 'Would create' : 'Created'; + ok( + `${verb} ${summary.created}, skipped ${summary.duplicates} duplicate(s), ${summary.failed} failed (of ${summary.total}).` + ); + } + if (summary.failed > 0) process.exitCode = 1; +} + // ── Sub-command dispatcher ──────────────────────────────────────────────────── async function dispatchSubscriptions(subArgs, cfg) { @@ -838,6 +1058,8 @@ async function dispatchSubscriptions(subArgs, cfg) { return cmdSubResume(args, cfg); case 'charge': return cmdSubCharge(args, cfg); + case 'import': + return cmdSubImport(args, cfg); default: console.log(`${c.bold('subtrackr subscriptions')} — manage subscriptions\n`); console.log(' list List all subscriptions'); @@ -863,6 +1085,12 @@ async function dispatchSubscriptions(subArgs, cfg) { console.log(' resume Resume a paused subscription'); console.log(' charge Manually trigger a charge cycle'); console.log(''); + console.log(' import Bulk-import subscriptions from CSV'); + console.log(' --dry-run Validate and detect duplicates only'); + console.log( + ' columns: name, price, currency, billing_cycle [, next_billing_date, category]' + ); + console.log(''); console.log(`${c.dim('Global: --format json | --api-key | --base-url ')}`); console.log(''); } diff --git a/docs/bulk-import.md b/docs/bulk-import.md new file mode 100644 index 00000000..4afe3c58 --- /dev/null +++ b/docs/bulk-import.md @@ -0,0 +1,53 @@ +# Bulk subscription import + +Import many subscriptions from a CSV file, with duplicate detection and a +result for every row. + +## CLI + +```bash +subtrackr subscriptions import subscriptions.csv --dry-run # validate only +subtrackr subscriptions import subscriptions.csv # import +subtrackr subscriptions import subscriptions.csv --format json +``` + +The exit code is `1` when any row failed, `0` otherwise (duplicates are not +failures). + +## CSV format + +| Column | Required | Rules | +| ------------------- | -------- | ---------------------------------------------- | +| `name` | yes | 1–120 characters | +| `price` | yes | Positive number, at most 2 decimals | +| `currency` | yes | 3-letter ISO code (case-insensitive) | +| `billing_cycle` | yes | `weekly`, `monthly`, `quarterly` or `yearly` | +| `next_billing_date` | no | Real calendar date, `YYYY-MM-DD` | +| `category` | no | Free text | + +Columns can be in any order; unknown columns are ignored. Quoted fields, +escaped quotes (`""`), embedded commas/newlines, CRLF and a UTF-8 BOM are +supported. A file is limited to 1000 rows. + +## Duplicates + +Two rows are the same subscription when **name** (case and spacing ignored), +**currency** and **billing cycle** match. A row is skipped as a duplicate of an +existing subscription or of an earlier row in the same file (the report names +which). Re-running the same file is therefore safe: rows created last time show +up as duplicates. + +## Per-row results + +Every row ends as `created`, `would_create` (dry run), `duplicate` or `error`. +An error lists each failing field. One bad row never blocks the others. +Line numbers are CSV record numbers; the header is line 1. + +## Backend service + +`backend/src/services/import.ts` is the authoritative implementation: +`importSubscriptions(csv, { existing, create, logger }, { dryRun, maxRows })`. +Storage and logging are injected. It logs one structured summary line +(`total`, `created`, `duplicates`, `failed`, `dryRun`) per import and a warning +for ignored columns. The CLI applies the same rules client-side and reports +server rejections per row.