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:
Mattsson
2026-09-09 11:19:39 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 500806f001
commit 6ea92f3152
58 changed files with 4069 additions and 18 deletions
@@ -0,0 +1,80 @@
-- Zettle merchant connections: per-company OAuth refresh tokens for the
-- paid-purchase feed (extensions/general/zettle).
--
-- Partner-hosted authorization code grant: the deployment holds
-- ZETTLE_CLIENT_ID / ZETTLE_CLIENT_SECRET; each merchant authorises READ:PURCHASE
-- + READ:USERINFO. Only the rotating refresh token is stored, AES-256-GCM
-- encrypted with ZETTLE_CREDENTIALS_ENCRYPTION_KEY (same layout as Shopify /
-- WooCommerce credential stores). Access tokens are ephemeral (~2h) and
-- never persisted. organization_uuid from users/self is the store identity
-- frozen into webshop_orders.external_id.
--
-- Modeled on shopify_connections: same status lifecycle, same member-scoped
-- RLS, no DELETE policy (connections are revoked, never deleted). No
-- write_audit_log trigger: connection state carrying encrypted credentials
-- must not flood audit_log.
create table public.zettle_connections (
id uuid primary key default gen_random_uuid(),
company_id uuid not null references public.companies(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
-- Merchant organization UUID; null while pending OAuth.
organization_uuid text,
organization_name text,
-- AES-256-GCM encrypted OAuth refresh token.
refresh_token_encrypted text,
oauth_state text,
-- Validated origin the connect flow started on (app origin or a brand
-- domain from the brands table); the callback returns the browser there.
return_origin text,
-- Sync claim: set by the run that holds the connection (cron or manual
-- sync), so two runs never refresh the rotating token concurrently (a
-- reused refresh token comes back 400 and would flip the row to revoked).
sync_lock_until timestamptz not null default 'epoch',
status text not null default 'pending'
check (status in ('pending', 'active', 'revoked', 'error')),
currency text,
transaction_sync_enabled boolean not null default false,
last_order_synced_at timestamptz,
error_message text,
connected_at timestamptz,
disconnected_at timestamptz,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create unique index zettle_connections_one_active_per_company
on public.zettle_connections (company_id) where (status = 'active');
create unique index zettle_connections_org_active_uniq
on public.zettle_connections (organization_uuid) where (status = 'active');
create index idx_zettle_connections_company_id
on public.zettle_connections (company_id);
alter table public.zettle_connections enable row level security;
create policy "members read zettle_connections"
on public.zettle_connections for select
using (company_id in (select public.user_company_ids()));
create policy "members insert zettle_connections"
on public.zettle_connections for insert
with check (
company_id in (select public.user_company_ids())
and user_id = auth.uid()
);
create policy "members update zettle_connections"
on public.zettle_connections for update
using (company_id in (select public.user_company_ids()))
with check (company_id in (select public.user_company_ids()));
create trigger set_updated_at_zettle_connections
before update on public.zettle_connections
for each row execute function public.update_updated_at_column();
comment on table public.zettle_connections is
'Zettle merchant connections per company. Refresh token stored AES-256-GCM encrypted; decryption requires ZETTLE_CREDENTIALS_ENCRYPTION_KEY.';
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,22 @@
-- Backfill capability_grants for the new 'zettle_sync' capability.
--
-- zettle_sync joins PAID_CAPABILITIES; existing companies' grants were written
-- before this key existed. Mirror each existing bank_sync grant (same sibling
-- used by stripe_payments / woocommerce_sync / shopify_sync backfills).
insert into public.capability_grants
(company_id, team_id, capability_key, source, granted_at, expires_at, metadata)
select
g.company_id,
g.team_id,
'zettle_sync',
g.source,
g.granted_at,
g.expires_at,
jsonb_build_object(
'backfilled_from', 'bank_sync',
'backfill_migration', '20260909100100'
)
from public.capability_grants g
where g.capability_key = 'bank_sync'
on conflict (company_id, team_id, capability_key, source) do nothing;
@@ -0,0 +1,40 @@
-- Include active zettle_connections in get_dashboard_nav_flags.has_webshop
-- so the Orders nav row appears after a Zettle connect (parity with
-- WooCommerce / Shopify probes in 20260826120000).
CREATE OR REPLACE FUNCTION public.get_dashboard_nav_flags(p_company_id uuid)
RETURNS TABLE(has_webshop boolean, has_mileage_trips boolean)
LANGUAGE sql
STABLE
SECURITY INVOKER
SET search_path TO 'public'
AS $$
SELECT
(
EXISTS (
SELECT 1 FROM public.woocommerce_connections w
WHERE w.company_id = p_company_id AND w.status = 'active'
)
OR EXISTS (
SELECT 1 FROM public.shopify_connections s
WHERE s.company_id = p_company_id AND s.status = 'active'
)
OR EXISTS (
SELECT 1 FROM public.zettle_connections z
WHERE z.company_id = p_company_id AND z.status = 'active'
)
OR EXISTS (
SELECT 1 FROM public.webshop_orders o
WHERE o.company_id = p_company_id
)
) AS has_webshop,
EXISTS (
SELECT 1 FROM public.mileage_trips m
WHERE m.company_id = p_company_id
) AS has_mileage_trips;
$$;
COMMENT ON FUNCTION public.get_dashboard_nav_flags(uuid) IS
'Dashboard nav visibility flags (webshop, mileage) for one company in one round trip. SECURITY INVOKER: RLS applies.';
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,39 @@
-- REPLACE seed_trial_capability_grants to add zettle_sync while keeping the
-- byrå suppression from 20260826130300 / 20260901081417.
CREATE OR REPLACE FUNCTION public.seed_trial_capability_grants()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
-- Byrå-team companies are covered by the team's agreement (WL-10):
-- no company-scoped trial, so no trial-expiry noise toward byrå clients.
IF NEW.team_id IS NOT NULL AND EXISTS (
SELECT 1 FROM public.teams t
WHERE t.id = NEW.team_id
AND t.kind = 'byra'
) THEN
RETURN NEW;
END IF;
-- Full PAID set as of 20260909100300; keep this VALUES list in step with
-- lib/entitlements/keys.ts PAID_CAPABILITIES whenever a key is added.
INSERT INTO public.capability_grants (company_id, capability_key, source, expires_at)
SELECT NEW.id, k.key, 'trial', NEW.created_at + interval '30 days'
FROM (VALUES
('ai'),
('bank_sync'),
('skatteverket'),
('email_send'),
('stripe_payments'),
('woocommerce_sync'),
('shopify_sync'),
('zettle_sync'),
('multi_user')
) AS k(key)
ON CONFLICT (company_id, team_id, capability_key, source) DO NOTHING;
RETURN NEW;
END;
$$;
@@ -0,0 +1,162 @@
-- Zettle parity for every site that enumerates the webshop platforms or the
-- integration connection tables. The zettle extension (20260909100000) adds
-- zettle_connections and writes platform = 'zettle' into webshop_orders, but:
--
-- 1. webshop_orders.platform and webshop_store_settings.platform still
-- CHECK (platform in ('woocommerce', 'shopify')), so every Zettle upsert
-- would have been refused at the database (the unit tests mock Supabase
-- and never saw it).
-- 2. The writer-role gate trigger (20260902093000) was attached to the
-- shopify/woocommerce connection tables by name; zettle_connections had
-- no aa_enforce_company_writer_role, so a viewer could connect a POS.
-- 3. The migration-reset snapshot counts pending/active integrations as a
-- blocker and the reset locks those tables FOR UPDATE (20260818084050);
-- both enumerate stripe/woocommerce/shopify and missed zettle.
--
-- 3 follows the wrapper pattern of 20260826150000 (rename, wrap, revoke)
-- instead of re-issuing the 400-line reset body for one PERFORM line.
-- 1. Platform CHECK constraints -------------------------------------------
ALTER TABLE public.webshop_orders
DROP CONSTRAINT IF EXISTS webshop_orders_platform_check;
ALTER TABLE public.webshop_orders
ADD CONSTRAINT webshop_orders_platform_check
CHECK (platform IN ('woocommerce', 'shopify', 'zettle'));
ALTER TABLE public.webshop_store_settings
DROP CONSTRAINT IF EXISTS webshop_store_settings_platform_check;
ALTER TABLE public.webshop_store_settings
ADD CONSTRAINT webshop_store_settings_platform_check
CHECK (platform IN ('woocommerce', 'shopify', 'zettle'));
-- 2. Writer-role gate ------------------------------------------------------
DROP TRIGGER IF EXISTS aa_enforce_company_writer_role ON public.zettle_connections;
CREATE TRIGGER aa_enforce_company_writer_role
BEFORE INSERT OR UPDATE OR DELETE ON public.zettle_connections
FOR EACH ROW EXECUTE FUNCTION public.enforce_company_writer_role();
-- 3a. Reset snapshot: a pending/active Zettle connection blocks the reset ---
ALTER FUNCTION public.company_migration_reset_snapshot(uuid)
RENAME TO company_migration_reset_snapshot_before_20260909100400;
CREATE OR REPLACE FUNCTION public.company_migration_reset_snapshot(p_company_id uuid)
RETURNS jsonb
LANGUAGE plpgsql
STABLE
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_snapshot jsonb;
v_blockers jsonb;
v_zettle integer;
BEGIN
v_snapshot := public.company_migration_reset_snapshot_before_20260909100400(
p_company_id
);
IF v_snapshot ->> 'code' = 'COMPANY_RESET_NOT_FOUND' THEN
RETURN v_snapshot;
END IF;
SELECT count(*) INTO v_zettle
FROM public.zettle_connections
WHERE company_id = p_company_id AND status IN ('pending', 'active');
IF v_zettle = 0 THEN
RETURN v_snapshot;
END IF;
-- Fold into the existing active_integrations_or_schedules blocker when the
-- inner snapshot already raised one; otherwise append it.
SELECT COALESCE(jsonb_agg(
CASE
WHEN existing.blocker ->> 'code' = 'active_integrations_or_schedules'
THEN existing.blocker || jsonb_build_object(
'count', COALESCE((existing.blocker ->> 'count')::integer, 0) + v_zettle
)
ELSE existing.blocker
END
ORDER BY existing.position
), '[]'::jsonb)
INTO v_blockers
FROM jsonb_array_elements(v_snapshot -> 'blockers')
WITH ORDINALITY AS existing(blocker, position);
IF NOT EXISTS (
SELECT 1 FROM jsonb_array_elements(v_blockers) AS b
WHERE b ->> 'code' = 'active_integrations_or_schedules'
) THEN
v_blockers := v_blockers || jsonb_build_array(jsonb_build_object(
'code', 'active_integrations_or_schedules',
'count', v_zettle
));
END IF;
RETURN v_snapshot || jsonb_build_object(
'eligible', false,
'blockers', v_blockers
);
END;
$$;
COMMENT ON FUNCTION public.company_migration_reset_snapshot(uuid) IS
'Internal fail-closed reset snapshot. Journal entries, voucher sequences, and invoices are retained data, not blockers; lock, filing, sync, import, integration (incl. Zettle), and worker state still block.';
REVOKE ALL ON FUNCTION public.company_migration_reset_snapshot_before_20260909100400(uuid)
FROM PUBLIC, anon, authenticated;
REVOKE ALL ON FUNCTION public.company_migration_reset_snapshot(uuid)
FROM PUBLIC, anon, authenticated;
-- 3b. Reset execution: lock zettle_connections with the other integrations --
ALTER FUNCTION public.reset_company_for_migration(uuid, text, text, boolean, boolean)
RENAME TO reset_company_for_migration_before_20260909100400;
CREATE OR REPLACE FUNCTION public.reset_company_for_migration(
p_company_id uuid,
p_confirmed_name text,
p_reason text,
p_confirm_no_filed_declarations boolean,
p_confirm_retained_archive boolean
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
-- Only an owner reaches the lock: outsiders and non-owner members fall
-- through to the inner function's own fast-fail so they cannot hold row
-- locks on a foreign company while it rejects them.
IF EXISTS (
SELECT 1 FROM public.company_members cm
WHERE cm.company_id = p_company_id
AND cm.user_id = auth.uid()
AND cm.role = 'owner'
) THEN
PERFORM 1 FROM public.zettle_connections
WHERE company_id = p_company_id FOR UPDATE;
END IF;
RETURN public.reset_company_for_migration_before_20260909100400(
p_company_id,
p_confirmed_name,
p_reason,
p_confirm_no_filed_declarations,
p_confirm_retained_archive
);
END;
$$;
REVOKE ALL ON FUNCTION public.reset_company_for_migration_before_20260909100400(uuid, text, text, boolean, boolean)
FROM PUBLIC, anon, authenticated;
REVOKE ALL ON FUNCTION public.reset_company_for_migration(uuid, text, text, boolean, boolean)
FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.reset_company_for_migration(uuid, text, text, boolean, boolean)
TO authenticated;
NOTIFY pgrst, 'reload schema';