@davoodmehraban89 / Factor-easy / commits / c2bf031
Fork 0

سامانه صدور فاکتور و حسابداری

feat: add read-only historical journal identity preflight (#216)

davoodmehraban89 committed Nov 18, 2026 at 09:15 UTC c2bf031346c4e5360d9cea7b8671fa09da8a2ad0
1 file changed +30
supabase/preflight/0216_document_identity_inventory.sql new
+30
@@ -0,0 +1,30 @@
1 +-- Read-only preflight for ADR 0216. Run on a disposable restored database first.
2 +-- No production mutations; aggregate output only.
3 +BEGIN TRANSACTION READ ONLY;
4 +SELECT organization_id, data->>'companyId' AS company_id,
5 + coalesce(data->>'status','missing') AS status,
6 + coalesce(data->>'sourceType','manual') AS source_type,
7 + count(*) AS vouchers,
8 + count(*) FILTER (WHERE nullif(btrim(data->>'attachmentNumber'),'') IS NULL) AS missing_attachment,
9 + count(*) FILTER (WHERE nullif(btrim(data->>'companyId'),'') IS NULL) AS missing_company
10 +FROM public.records WHERE collection='journalVouchers'
11 +GROUP BY 1,2,3,4 ORDER BY 1,2,3,4;
12 +
13 +-- Duplicate existing attachment identities, including across fiscal years.
14 +SELECT organization_id, data->>'companyId' AS company_id,
15 + btrim(data->>'attachmentNumber') AS attachment_number, count(*) AS duplicates
16 +FROM public.records WHERE collection='journalVouchers'
17 +AND nullif(btrim(data->>'attachmentNumber'),'') IS NOT NULL
18 +GROUP BY 1,2,3 HAVING count(*)>1;
19 +
20 +-- Source-linked journals and missing source identity (sale/purchase only).
21 +SELECT v.organization_id,v.data->>'companyId' AS company_id,
22 + v.data->>'sourceType' AS source_type,count(*) AS broken_links
23 +FROM public.records v
24 +WHERE v.collection='journalVouchers' AND v.data->>'sourceType' IN ('sale','purchase')
25 +AND NOT EXISTS (
26 + SELECT 1 FROM public.records s WHERE s.organization_id=v.organization_id
27 + AND s.collection=CASE v.data->>'sourceType' WHEN 'sale' THEN 'invoices' ELSE 'purchases' END
28 + AND s.id=v.data->>'sourceId' AND s.data->>'companyId'=v.data->>'companyId')
29 +GROUP BY 1,2,3;
30 +ROLLBACK;