Files
accounted/supabase/migrations/20260723003500_backfill_final_closing_entry_links.sql
T
Mattsson 466e55a015 Fix/invoice delivery and payment accounts (#1116)
* fix: reconcile annual reports with final closing entries

* test: cover annual report depreciation and VAT balances

* Merge remote-tracking branch 'origin/main' into fix/usr-fdbck-ch

* fix: show exact invoice delivery details

* fix: use currency account in invoice emails

* fix: address invoice delivery review feedback

* fix: harden invoice delivery and payment accounts

* test: assert RLS-denied zero-row updates

* fix: close remaining invoice compliance gaps

* fix: harden invoice archive authorization

* fix: close invoice delivery review findings

* fix: verify delivery finalization results

* fix: cap combined invoice email recipients

* fix: close final invoice compliance findings

* fix: prevent stale payment account saves

* test: prove invoice delivery isolation

* fix: close invoice privacy review findings

* test: normalize delivery retention dates
2026-07-23 09:54:02 +02:00

26 lines
889 B
SQL

-- Repair only unambiguous final-closing links created by the canonical
-- year-end workflow. Other legacy closed periods remain unlinked so statutory
-- reporting fails explicitly instead of excluding unrelated year-end entries.
WITH exact_candidates AS (
SELECT
fp.id AS fiscal_period_id,
(array_agg(je.id))[1] AS closing_entry_id
FROM public.fiscal_periods fp
JOIN public.journal_entries je
ON je.company_id = fp.company_id
AND je.fiscal_period_id = fp.id
AND je.source_type = 'year_end'
AND je.status = 'posted'
AND je.description = 'Årsbokslut ' || fp.name
WHERE fp.is_closed = true
AND fp.closing_entry_id IS NULL
GROUP BY fp.id
HAVING count(*) = 1
)
UPDATE public.fiscal_periods fp
SET closing_entry_id = candidate.closing_entry_id
FROM exact_candidates candidate
WHERE fp.id = candidate.fiscal_period_id
AND fp.closing_entry_id IS NULL;