Files
accounted/tests/pg/shopify-connections.pg.test.ts
Mattsson c187fabf92 feat(shopify): Shopify order/refund feed into the transactions inbox (#1474)
* 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>
2026-08-09 12:44:08 +02:00

131 lines
5.1 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { randomUUID } from 'crypto'
import { seedCompany } from './fixtures'
// Committed (pool) inserts persist across pg-real runs, and the shop_domain
// partial unique index is global: fixed domains would collide with rows left
// by a previous run before the assertion under test is ever reached.
const uniqueShop = (label: string) => label + '-' + randomUUID() + '.myshopify.com'
/**
* Covers migration 20260808150000_shopify_connections:
* 1. RLS: members insert and read their own company's connection,
* non-members see nothing and cannot insert for a foreign company.
* 2. One ACTIVE connection per company (partial unique index).
* 3. One store actively connected to at most one company.
* 4. No DELETE policy: a member DELETE silently affects zero rows.
*/
describe('shopify_connections RLS', () => {
it('a member can insert and read their company connection', async () => {
const { userId, companyId } = await seedCompany()
const shop = uniqueShop('member')
await withUserContext(userId, async (client) => {
const inserted = await client.query(
`INSERT INTO public.shopify_connections
(company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'active')
RETURNING id`,
[companyId, userId, shop],
)
expect(inserted.rows).toHaveLength(1)
const read = await client.query(
`SELECT status, shop_domain FROM public.shopify_connections WHERE company_id = $1`,
[companyId],
)
expect(read.rows).toEqual([{ status: 'active', shop_domain: shop }])
})
})
it('a non-member sees nothing and cannot insert for a foreign company', async () => {
const { userId: ownerId, companyId } = await seedCompany()
await getPool().query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'active')`,
[companyId, ownerId, uniqueShop('foreign')],
)
const { userId: outsiderId } = await seedCompany() // member of a DIFFERENT company
await withUserContext(outsiderId, async (client) => {
const read = await client.query(
`SELECT id FROM public.shopify_connections WHERE company_id = $1`,
[companyId],
)
expect(read.rows).toHaveLength(0)
await expect(
client.query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'pending')`,
[companyId, outsiderId, uniqueShop('intruder')],
),
).rejects.toThrow(/row-level security/i)
})
})
it('only one ACTIVE connection per company is allowed', async () => {
const { userId, companyId } = await seedCompany()
await getPool().query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'active')`,
[companyId, userId, uniqueShop('shop-one')],
)
await expect(
getPool().query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'active')`,
[companyId, userId, uniqueShop('shop-two')],
),
).rejects.toMatchObject({ code: '23505' }) // unique_violation
})
it('a store may be actively connected to at most one company', async () => {
const { userId: userA, companyId: companyA } = await seedCompany()
const { userId: userB, companyId: companyB } = await seedCompany()
const sharedShop = uniqueShop('shared')
await getPool().query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'active')`,
[companyA, userA, sharedShop],
)
await expect(
getPool().query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'active')`,
[companyB, userB, sharedShop],
),
).rejects.toMatchObject({ code: '23505' })
// A revoked row for the same store is fine (history is kept).
const revoked = await getPool().query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'revoked') RETURNING id`,
[companyB, userB, sharedShop],
)
expect(revoked.rows).toHaveLength(1)
})
it('members cannot DELETE (no DELETE policy; revoke is a status flip)', async () => {
const { userId, companyId } = await seedCompany()
const { rows } = await getPool().query(
`INSERT INTO public.shopify_connections (company_id, user_id, shop_domain, status)
VALUES ($1, $2, $3, 'active') RETURNING id`,
[companyId, userId, uniqueShop('keep')],
)
await withUserContext(userId, async (client) => {
const del = await client.query(
`DELETE FROM public.shopify_connections WHERE id = $1`,
[rows[0].id],
)
expect(del.rowCount).toBe(0)
})
const still = await getPool().query(
`SELECT id FROM public.shopify_connections WHERE id = $1`,
[rows[0].id],
)
expect(still.rows).toHaveLength(1)
})
})