Files
accounted/supabase/migrations/20260421160500_opening_balances_rpc.sql
T
MattssonandClaude Opus 4.7 02f94ef631 Fix/critical issues (#351)
* fix: add 15s timeout to accounting provider HTTP clients

Node's built-in fetch has no default timeout, so a stalled provider
could hold a serverless worker open for many minutes — worse with
withRetry (6x on Fortnox, 3x on others) and getPaginated stacking
across pages.

Wrap each fetch() in the Fortnox, Visma, Bokio, Briox, and Björn
Lundén clients with signal: AbortSignal.timeout(15_000), and treat
TimeoutError/AbortError as retryable so a single stalled attempt
retries cleanly instead of hanging the request.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: add timeouts to OAuth token endpoints

Wrap every OAuth2 token exchange, refresh, and revoke POST in an
AbortController via a new fetchWithTimeout helper. Without this, a
hung provider endpoint holds the request thread indefinitely — worst
case being Skatteverket, where refreshAccessToken sits on the hot
path of every bookkeeping action and exchangeCodeForTokens races the
5-minute BankID auth-code TTL.

On timeout, the Skatteverket OAuth callback now redirects to
/reports?tab=vat-declaration with a Swedish retry message instead
of leaving the user stranded on the callback URL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: close RLS escalation on membership and settings tables

Any authenticated user who was a member (including viewer) could issue a
direct PostgREST PATCH against company_members and promote themselves to
owner, bypassing the app-layer requireWritePermission guard entirely.
Reproduced on prod, then verified the fix on staging.

Tighten INSERT/UPDATE/DELETE policies on company_members, team_members,
api_keys, company_invitations, team_invitations, companies, teams, and
company_settings to require the caller to hold role IN ('owner','admin')
in the target company/team. Role check is wrapped in SECURITY DEFINER
helpers (user_is_company_admin, user_is_team_admin, user_role_in_company)
to avoid RLS recursion when a policy on company_members references
company_members in its subquery.

Add a BEFORE UPDATE trigger on company_members that rejects any role
change unless the caller already holds role='owner', so admins cannot
mint further owners even though they can otherwise write.

Legitimate write paths are unaffected: company creation goes through the
create_company_with_owner SECURITY DEFINER RPC, invite acceptance uses
the service role, and team->company membership syncs via SECURITY
DEFINER triggers. All bypass RLS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(migrations): resolve duplicate schema_migrations version 20260421160000

Two migration files shared timestamp 20260421160000 on main
(booking_template_usage.sql and opening_balances_rpc.sql), causing
supabase_migrations.schema_migrations PK collisions on any fresh CI run:

  duplicate key value violates unique constraint "schema_migrations_pkey"
  Key (version)=(20260421160000) already exists.

Bump opening_balances_rpc.sql to 20260421160500. booking_template_usage
keeps 20260421160000 because its table already exists on prod; the
renamed file has an idempotent CREATE OR REPLACE FUNCTION body and has
not yet been deployed to prod, so moving its version is free.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(migrations): make booking_template_usage migration idempotent

The table already exists on prod (applied out-of-band) but prod's
schema_migrations does not track version 20260421160000, so the next
PR-driven deploy would re-run this migration and fail on
`CREATE TABLE public.booking_template_usage` with a duplicate-relation
error.

Add IF NOT EXISTS to CREATE TABLE and CREATE INDEX, and DROP POLICY
IF EXISTS before each CREATE POLICY. No functional change on fresh
databases; prod just silently no-ops the table/index creates and
re-declares policies without dropping-then-missing them.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: implement isTimeoutError utility and enforce role restrictions on company_members insert

* fix: implement fallback for user_id in commit_journal_entry function when auth.uid() is NULL

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 18:14:01 +02:00

94 lines
3.7 KiB
PL/PgSQL

-- compute_prior_opening_balances(company_id, period_start)
--
-- Server-side aggregate for the opening-balances fallback used when a fiscal
-- period has no opening_balance_entry_id set (i.e. year-end closing never ran
-- for the prior period). Returns one row per balance-sheet account
-- (class 1-2) with the summed debit and credit of every posted/reversed
-- journal line dated before the period start.
--
-- Replaces a paginated PostgREST scan that fetched every prior line via
-- journal_entry_lines with an !inner join on journal_entries. At ~8k lines
-- that scan would tip over the 8s statement_timeout on the authenticated
-- role because the RLS EXISTS subquery on journal_entry_lines re-evaluates
-- user_company_ids() per row on every .range() page. This RPC pushes the
-- filter + SUM into the planner and returns ~50 rows in a single round trip.
--
-- Class 3-8 accounts are intentionally excluded: their balances reset at
-- each year transition and are absorbed into equity via the closing entry;
-- carrying them forward as IB would violate BFNAR 2013:2.
--
-- Duplicate-IB guard: multi-year SIE imports create one opening_balance
-- journal entry per imported year (the #IB records from each SIE file).
-- Each year N+1's IB equals year N's UB, which is already the sum of
-- year N's journal lines — so blindly summing every prior IB double-counts
-- by one year's worth of movements per duplicate. Only the earliest IB per
-- account is kept (pre-system starting capital); later IBs are excluded.
CREATE OR REPLACE FUNCTION compute_prior_opening_balances(
p_company_id uuid,
p_period_start date
)
RETURNS TABLE (account_number text, debit numeric, credit numeric)
LANGUAGE sql
STABLE
SECURITY INVOKER
SET search_path = public
AS $$
-- Dedup is per-account, not per-entry. If the same account appears in multiple
-- IB entries (duplicate opening balances from multi-year imports), we keep only
-- the earliest line for that account. Accounts that appear only in a later IB
-- (e.g. a new account introduced in year N with no prior-year IB) are still
-- included — they represent a genuine pre-system starting balance for that
-- account, not a duplicate.
WITH ib_lines_ranked AS (
SELECT
jel.account_number,
jel.debit_amount,
jel.credit_amount,
ROW_NUMBER() OVER (
PARTITION BY jel.account_number
ORDER BY je.entry_date ASC, je.created_at ASC, je.id ASC
) AS rn
FROM journal_entry_lines jel
JOIN journal_entries je ON je.id = jel.journal_entry_id
WHERE je.company_id = p_company_id
AND je.status IN ('posted', 'reversed')
AND je.entry_date < p_period_start
AND je.source_type = 'opening_balance'
AND substr(jel.account_number, 1, 1) BETWEEN '1' AND '2'
),
earliest_ib AS (
SELECT account_number, debit_amount, credit_amount
FROM ib_lines_ranked
WHERE rn = 1
),
non_ib_lines AS (
SELECT
jel.account_number,
jel.debit_amount,
jel.credit_amount
FROM journal_entry_lines jel
JOIN journal_entries je ON je.id = jel.journal_entry_id
WHERE je.company_id = p_company_id
AND je.status IN ('posted', 'reversed')
AND je.entry_date < p_period_start
AND je.source_type IS DISTINCT FROM 'opening_balance'
AND substr(jel.account_number, 1, 1) BETWEEN '1' AND '2'
),
all_lines AS (
SELECT account_number, debit_amount, credit_amount FROM earliest_ib
UNION ALL
SELECT account_number, debit_amount, credit_amount FROM non_ib_lines
)
SELECT
account_number,
SUM(debit_amount)::numeric AS debit,
SUM(credit_amount)::numeric AS credit
FROM all_lines
GROUP BY account_number;
$$;
GRANT EXECUTE ON FUNCTION compute_prior_opening_balances(uuid, date) TO authenticated;
NOTIFY pgrst, 'reload schema';