feat(zettle): sync paid purchases into webshop_orders (#2445)
Community PR #2416 by @olofpinzke, adopted and finished by maintainers (rebased so every commit is signed). Why the problem occurred: no Zettle integration; POS sales only reached the books as bank descriptors while Woo/Shopify already had order underlag via webshop_orders. The contributor's version also failed at the database (platform CHECKs listed only woocommerce/shopify), which the mocked unit tests never saw. What was simplified: reused the Orders/book/invoice path instead of a new inbox; Finance API payouts/fees deferred. Sales the one-account, revenue-per-rate model cannot book (split tender, gift cards, tips) import unbookable with a "bokför manuellt" title instead of guessing accounts. Reset parity uses the rename-and-wrap pattern instead of re-issuing the reset body. Why this solution: per-purchase rows give the radunderlag BFL verifikat need and the bulk-book path exists; daily kassarapport aggregation and Finance API fees/payouts are the follow-up (DECISIONS.md). Skeptic-refuted paths fixed before merge: concurrent refresh-token rotation (sync claim), cron offset paging (candidate snapshot), platform CHECKs, writer-role gate, migration-reset parity, white-label return origin re-validated at callback, VAT net from product rows. Not live until ZETTLE_CLIENT_ID / ZETTLE_CLIENT_SECRET / ZETTLE_CREDENTIALS_ENCRYPTION_KEY are set on Vercel and a Zettle developer app is registered with the callback redirect URI. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WtYqzKPoTSRHskYYdf7MwB
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
500806f001
commit
6ea92f3152
@@ -73,6 +73,8 @@ describe('company migration reset RPCs (pg)', () => {
|
||||
legacy_snapshot_224000_authenticated: boolean
|
||||
legacy_snapshot_231500_authenticated: boolean
|
||||
legacy_snapshot_20260826150000_authenticated: boolean
|
||||
legacy_snapshot_20260909100400_authenticated: boolean
|
||||
legacy_reset_20260909100400_authenticated: boolean
|
||||
}>(`
|
||||
SELECT
|
||||
has_function_privilege(
|
||||
@@ -124,7 +126,17 @@ describe('company migration reset RPCs (pg)', () => {
|
||||
'authenticated',
|
||||
'public.company_migration_reset_snapshot_before_20260826150000(uuid)',
|
||||
'EXECUTE'
|
||||
) AS legacy_snapshot_20260826150000_authenticated
|
||||
) AS legacy_snapshot_20260826150000_authenticated,
|
||||
has_function_privilege(
|
||||
'authenticated',
|
||||
'public.company_migration_reset_snapshot_before_20260909100400(uuid)',
|
||||
'EXECUTE'
|
||||
) AS legacy_snapshot_20260909100400_authenticated,
|
||||
has_function_privilege(
|
||||
'authenticated',
|
||||
'public.reset_company_for_migration_before_20260909100400(uuid,text,text,boolean,boolean)',
|
||||
'EXECUTE'
|
||||
) AS legacy_reset_20260909100400_authenticated
|
||||
`)
|
||||
|
||||
expect(rows[0]).toEqual({
|
||||
@@ -138,6 +150,8 @@ describe('company migration reset RPCs (pg)', () => {
|
||||
legacy_snapshot_224000_authenticated: false,
|
||||
legacy_snapshot_231500_authenticated: false,
|
||||
legacy_snapshot_20260826150000_authenticated: false,
|
||||
legacy_snapshot_20260909100400_authenticated: false,
|
||||
legacy_reset_20260909100400_authenticated: false,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -318,6 +332,20 @@ describe('company migration reset RPCs (pg)', () => {
|
||||
count: 1,
|
||||
})
|
||||
|
||||
// A pending Zettle connection is an integration too (20260909100400 wraps
|
||||
// the snapshot instead of re-issuing its body).
|
||||
const pos = await seedCompany()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, status)
|
||||
VALUES ($1, $2, 'pending')`,
|
||||
[pos.companyId, pos.userId],
|
||||
)
|
||||
const posPreview = await preview(pos.userId, pos.companyId)
|
||||
expect(posPreview.eligibility?.blockers).toContainEqual({
|
||||
code: 'active_integrations_or_schedules',
|
||||
count: 1,
|
||||
})
|
||||
|
||||
const busy = await seedCompany()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.operations (company_id, user_id, operation_type, status)
|
||||
|
||||
@@ -2,8 +2,8 @@ import { describe, it, expect } from 'vitest'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import { insertAuthUser, insertCompany, insertCompanyMember, seedCompany } from './fixtures'
|
||||
|
||||
// Validates migration 20260826120000_get_dashboard_nav_flags:
|
||||
// 1. has_webshop flips on an ACTIVE WooCommerce or Shopify connection
|
||||
// Validates migration 20260826120000_get_dashboard_nav_flags (plus zettle):
|
||||
// 1. has_webshop flips on an ACTIVE WooCommerce, Shopify, or Zettle connection
|
||||
// (a pending/revoked one does not count) and has_mileage_trips on any
|
||||
// mileage_trips row.
|
||||
// 2. SECURITY INVOKER: a member of ANOTHER company sees (false, false)
|
||||
@@ -64,6 +64,16 @@ describe('get_dashboard_nav_flags()', () => {
|
||||
expect((await flagsAs(userId, companyId)).has_webshop).toBe(true)
|
||||
})
|
||||
|
||||
it('flips has_webshop on an active Zettle connection', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyId, userId, `nav-flags-zettle-${companyId}`],
|
||||
)
|
||||
expect((await flagsAs(userId, companyId)).has_webshop).toBe(true)
|
||||
})
|
||||
|
||||
it('flips has_mileage_trips on any mileage trip', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await getPool().query(
|
||||
|
||||
@@ -61,10 +61,11 @@ async function trialGrantKeys(companyId: string): Promise<string[]> {
|
||||
}
|
||||
|
||||
describe('trial suppression for byrå-team companies', () => {
|
||||
it('the trial seed covers the full eight-key PAID set', () => {
|
||||
it('the trial seed covers the full nine-key PAID set', () => {
|
||||
// Guard against the seed list drifting from lib/entitlements/keys.ts:
|
||||
// if PAID_CAPABILITIES grows, the migration VALUES list (and this test)
|
||||
// must grow with it. multi_user joined at 20260901081417.
|
||||
// must grow with it. multi_user joined at 20260901081417; zettle_sync
|
||||
// at 20260909100300.
|
||||
expect(TRIAL_KEYS).toEqual(
|
||||
[
|
||||
'ai',
|
||||
@@ -75,6 +76,7 @@ describe('trial suppression for byrå-team companies', () => {
|
||||
'skatteverket',
|
||||
'stripe_payments',
|
||||
'woocommerce_sync',
|
||||
'zettle_sync',
|
||||
],
|
||||
)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { insertAuthUser, insertCompanyMember, seedCompany } from './fixtures'
|
||||
|
||||
const uniqueOrg = (label: string) => label + '-' + randomUUID()
|
||||
|
||||
/**
|
||||
* Covers migration 20260909100000_zettle_connections:
|
||||
* 1. RLS: members insert and read their own company's connection.
|
||||
* 2. One ACTIVE connection per company.
|
||||
* 3. One organization actively connected to at most one company.
|
||||
* 4. No DELETE policy.
|
||||
*/
|
||||
|
||||
describe('zettle_connections RLS', () => {
|
||||
it('a member can insert and read their company connection', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const org = uniqueOrg('member')
|
||||
await withUserContext(userId, async (client) => {
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO public.zettle_connections
|
||||
(company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active')
|
||||
RETURNING id`,
|
||||
[companyId, userId, org],
|
||||
)
|
||||
expect(inserted.rows).toHaveLength(1)
|
||||
|
||||
const read = await client.query(
|
||||
`SELECT status, organization_uuid FROM public.zettle_connections WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(read.rows).toEqual([{ status: 'active', organization_uuid: org }])
|
||||
})
|
||||
})
|
||||
|
||||
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.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyId, ownerId, uniqueOrg('foreign')],
|
||||
)
|
||||
const { userId: outsiderId } = await seedCompany()
|
||||
|
||||
await withUserContext(outsiderId, async (client) => {
|
||||
const read = await client.query(
|
||||
`SELECT id FROM public.zettle_connections WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(read.rows).toHaveLength(0)
|
||||
|
||||
await expect(
|
||||
client.query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'pending')`,
|
||||
[companyId, outsiderId, uniqueOrg('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.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyId, userId, uniqueOrg('org-one')],
|
||||
)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyId, userId, uniqueOrg('org-two')],
|
||||
),
|
||||
).rejects.toMatchObject({ code: '23505' })
|
||||
})
|
||||
|
||||
it('an organization 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 sharedOrg = uniqueOrg('shared')
|
||||
await getPool().query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyA, userA, sharedOrg],
|
||||
)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyB, userB, sharedOrg],
|
||||
),
|
||||
).rejects.toMatchObject({ code: '23505' })
|
||||
})
|
||||
|
||||
it('members cannot DELETE a connection (revoke-only)', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const inserted = await getPool().query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'active') RETURNING id`,
|
||||
[companyId, userId, uniqueOrg('nodelete')],
|
||||
)
|
||||
const id = inserted.rows[0].id as string
|
||||
await withUserContext(userId, async (client) => {
|
||||
const deleted = await client.query(
|
||||
`DELETE FROM public.zettle_connections WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
expect(deleted.rowCount).toBe(0)
|
||||
})
|
||||
const still = await getPool().query(
|
||||
`SELECT status FROM public.zettle_connections WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
expect(still.rows[0].status).toBe('active')
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Covers migration 20260909100400_zettle_platform_parity:
|
||||
* 1. webshop_orders / webshop_store_settings accept platform = 'zettle'.
|
||||
* 2. The writer-role gate (20260902093000) is attached: a viewer cannot
|
||||
* connect a Zettle account even though RLS membership would let them.
|
||||
*/
|
||||
describe('zettle platform parity', () => {
|
||||
it('lets webshop rows carry platform = zettle', async () => {
|
||||
const { rows } = await getPool().query<{ conname: string; def: string }>(
|
||||
`SELECT conname, pg_get_constraintdef(oid) AS def
|
||||
FROM pg_constraint
|
||||
WHERE conname IN ('webshop_orders_platform_check', 'webshop_store_settings_platform_check')
|
||||
ORDER BY conname`,
|
||||
)
|
||||
expect(rows.map((r) => r.conname)).toEqual([
|
||||
'webshop_orders_platform_check',
|
||||
'webshop_store_settings_platform_check',
|
||||
])
|
||||
for (const row of rows) {
|
||||
expect(row.def).toContain("'zettle'")
|
||||
expect(row.def).toContain("'shopify'")
|
||||
expect(row.def).toContain("'woocommerce'")
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses a viewer who tries to connect', async () => {
|
||||
const { companyId } = await seedCompany()
|
||||
const viewerId = await insertAuthUser()
|
||||
await insertCompanyMember({ companyId, userId: viewerId, role: 'viewer' })
|
||||
|
||||
await withUserContext(viewerId, async (client) => {
|
||||
await expect(
|
||||
client.query(
|
||||
`INSERT INTO public.zettle_connections (company_id, user_id, organization_uuid, status)
|
||||
VALUES ($1, $2, $3, 'pending')`,
|
||||
[companyId, viewerId, uniqueOrg('viewer')],
|
||||
),
|
||||
).rejects.toThrow(/no write access to company/i)
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user