c187fabf92
* feat(shopify): Shopify order/refund feed into the transactions inbox
New extensions/general/shopify feed extension, modeled on the WooCommerce
feed: connect a Shopify store with Dev Dashboard custom-app client
credentials (client credentials grant, ~24h tokens, never stored), then a
nightly cron + manual sync imports paid orders and refunds via the GraphQL
Admin API (pinned 2026-07) into the transactions inbox on clearing account
1584. Feed-only: nothing auto-books. Zero PII fields are queried, keeping
the app outside Shopify's protected customer data program.
- shopify_connections migration (RLS, revoke-never-delete, encrypted
client id/secret) + shopify_sync capability and bank_sync-mirrored
backfill
- frozen external_id scheme shopify_{shop_domain}_order|refund_{id},
scoped on the shop domain so reconnects never re-import
- cursor sync on updated_at windows with 24h overlap, lock-date drop at
map time, ingest-failure cursor floor, deadline stop-and-resume,
revoked-credential flip
- /import card + settings panel, sv/en i18n, cron 03:15 in vercel.json +
regenerated Docker crontabs, logo, events, panel registry
- 65 unit tests + pg-real RLS test; extensions.schema.json enum also
gains the missing stripe entry (pre-existing drift)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(shopify): review findings from PR 1474
- token exchange: a 429 that survives every retry is throttling, not a
credential failure; stop remapping retryable 4xx to 401 so sustained
throttling can no longer flip the connection to revoked and delete the
stored credentials (CodeRabbit critical)
- order sync: advance a scanned-through watermark (run start, capped by
the failure floor) after a fully-listed window, so empty first runs and
quiet stores rotate to the back of the cron's oldest-first selection
instead of permanently occupying the 50-connection batch (CodeRabbit
major, starvation)
- add handler-level tests for the orders cron route (auth 401, disabled
503, unconfigured no-op, query failure, capability skip, happy path,
per-connection failure isolation, revoked marking)
- add 401 tests for /sync, /transaction-sync and /disconnect; pin the
cursor floor rule with a two-order page; stub the encryption key via
vi.stubEnv
- note in the panel description (sv/en) that orders can mix VAT rates and
must be split at booking (Swedish review advisory)
- DECISIONS.md: wrap underscore identifiers in backticks (MD037)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
138 lines
5.1 KiB
TypeScript
138 lines
5.1 KiB
TypeScript
import { describe, it, expect, afterEach, vi } from 'vitest'
|
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import type Stripe from 'stripe'
|
|
import {
|
|
statusGrantsAccess,
|
|
subscriptionToState,
|
|
applySubscriptionState,
|
|
} from '../subscription-sync'
|
|
|
|
afterEach(() => vi.unstubAllEnvs())
|
|
|
|
// Recording mock: captures the from()/upsert()/delete()/eq() operations so we
|
|
// can assert what applySubscriptionState wrote, without a real DB.
|
|
interface RecordedOp {
|
|
table: string
|
|
op: 'upsert' | 'delete' | null
|
|
payload: unknown
|
|
conflict: string | undefined
|
|
filters: Array<[string, unknown]>
|
|
}
|
|
function recordingSupabase() {
|
|
const calls: RecordedOp[] = []
|
|
const supabase = {
|
|
from(table: string) {
|
|
const ctx: RecordedOp = { table, op: null, payload: null, conflict: undefined, filters: [] }
|
|
const chain = {
|
|
upsert(payload: unknown, opts?: { onConflict?: string }) {
|
|
ctx.op = 'upsert'
|
|
ctx.payload = payload
|
|
ctx.conflict = opts?.onConflict
|
|
calls.push(ctx)
|
|
return chain
|
|
},
|
|
delete() {
|
|
ctx.op = 'delete'
|
|
calls.push(ctx)
|
|
return chain
|
|
},
|
|
eq(col: string, val: unknown) {
|
|
ctx.filters.push([col, val])
|
|
return chain
|
|
},
|
|
then(resolve: (v: { data: null; error: null }) => void) {
|
|
resolve({ data: null, error: null })
|
|
},
|
|
}
|
|
return chain
|
|
},
|
|
}
|
|
return { supabase: supabase as unknown as SupabaseClient, calls }
|
|
}
|
|
|
|
function fakeSub(over: Partial<{ status: string; priceId: string; interval: string; periodEnd: number; customer: string }> = {}): Stripe.Subscription {
|
|
return {
|
|
id: 'sub_123',
|
|
customer: over.customer ?? 'cus_123',
|
|
status: over.status ?? 'active',
|
|
metadata: {},
|
|
items: {
|
|
data: [
|
|
{
|
|
price: { id: over.priceId ?? 'price_x', recurring: { interval: over.interval ?? 'month' } },
|
|
current_period_end: over.periodEnd ?? Math.floor(Date.now() / 1000) + 30 * 86400,
|
|
},
|
|
],
|
|
},
|
|
} as unknown as Stripe.Subscription
|
|
}
|
|
|
|
describe('statusGrantsAccess', () => {
|
|
it('grants for active/trialing/past_due, denies otherwise', () => {
|
|
expect(statusGrantsAccess('active')).toBe(true)
|
|
expect(statusGrantsAccess('trialing')).toBe(true)
|
|
expect(statusGrantsAccess('past_due')).toBe(true)
|
|
expect(statusGrantsAccess('canceled')).toBe(false)
|
|
expect(statusGrantsAccess('unpaid')).toBe(false)
|
|
expect(statusGrantsAccess(null)).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('subscriptionToState', () => {
|
|
it('maps status, customer, id, and period end', () => {
|
|
const end = Math.floor(Date.now() / 1000) + 1000
|
|
const state = subscriptionToState(fakeSub({ status: 'active', periodEnd: end }), 'co_1')
|
|
expect(state.companyId).toBe('co_1')
|
|
expect(state.stripeCustomerId).toBe('cus_123')
|
|
expect(state.stripeSubscriptionId).toBe('sub_123')
|
|
expect(state.status).toBe('active')
|
|
expect(state.currentPeriodEnd).toBe(new Date(end * 1000).toISOString())
|
|
})
|
|
|
|
it('derives plan from the env price id, falling back to interval', () => {
|
|
vi.stubEnv('STRIPE_PRICE_YEARLY', 'price_year')
|
|
vi.stubEnv('STRIPE_PRICE_MONTHLY', 'price_month')
|
|
expect(subscriptionToState(fakeSub({ priceId: 'price_year' }), 'co').plan).toBe('yearly')
|
|
expect(subscriptionToState(fakeSub({ priceId: 'price_month' }), 'co').plan).toBe('monthly')
|
|
// unknown price id -> interval fallback
|
|
expect(subscriptionToState(fakeSub({ priceId: 'price_other', interval: 'year' }), 'co').plan).toBe('yearly')
|
|
})
|
|
})
|
|
|
|
describe('applySubscriptionState', () => {
|
|
it('grants the PAID keys when the subscription is active', async () => {
|
|
const { supabase, calls } = recordingSupabase()
|
|
await applySubscriptionState(supabase, {
|
|
companyId: 'co_1',
|
|
stripeCustomerId: 'cus_1',
|
|
stripeSubscriptionId: 'sub_1',
|
|
status: 'active',
|
|
plan: 'yearly',
|
|
currentPeriodEnd: new Date().toISOString(),
|
|
})
|
|
const subUpsert = calls.find((c) => c.table === 'company_subscriptions')
|
|
expect(subUpsert?.op).toBe('upsert')
|
|
const grantUpsert = calls.find((c) => c.table === 'capability_grants')
|
|
expect(grantUpsert?.op).toBe('upsert')
|
|
const rows = grantUpsert?.payload as Array<{ capability_key: string; source: string }>
|
|
expect(rows.map((r) => r.capability_key).sort()).toEqual(['ai', 'bank_sync', 'email_send', 'shopify_sync', 'skatteverket', 'stripe_payments', 'woocommerce_sync'])
|
|
expect(rows.every((r) => r.source === 'stripe')).toBe(true)
|
|
})
|
|
|
|
it('removes only the stripe grants when canceled (freeze-and-retain)', async () => {
|
|
const { supabase, calls } = recordingSupabase()
|
|
await applySubscriptionState(supabase, {
|
|
companyId: 'co_1',
|
|
stripeCustomerId: 'cus_1',
|
|
stripeSubscriptionId: 'sub_1',
|
|
status: 'canceled',
|
|
plan: null,
|
|
currentPeriodEnd: null,
|
|
})
|
|
const grantOp = calls.find((c) => c.table === 'capability_grants')
|
|
expect(grantOp?.op).toBe('delete')
|
|
expect(grantOp?.filters).toContainEqual(['company_id', 'co_1'])
|
|
expect(grantOp?.filters).toContainEqual(['source', 'stripe'])
|
|
})
|
|
})
|