سامانه صدور فاکتور و حسابداری
fix(phase1a): make same client draft ID genuinely idempotent under concurrent INSERT race
davoodmehraban89 committed
Oct 16, 2026 at 16:55 UTC
3e204a67e1af76af64e965523050317cdd28b364
1 file changed
+14
-1
supabase/migrations/20261016101500_phase1a_journal_core.sql
+14
-1
@@ -182,7 +182,20 @@ BEGIN
182
'reversalReason',coalesce(p_header->>'reversalReason',''),
183
'reversalAllocations',coalesce(p_header->'reversalAllocations','null'::jsonb),
184
'status','draft','createdAt',clock_timestamp(),'createdBy',v_actor,
185
- 'requestFingerprint',v_fp));
185
+ 'requestFingerprint',v_fp))
186
+ ON CONFLICT (organization_id,collection,id) DO NOTHING;
187
+ -- Two simultaneous requests with the SAME client ID must both resolve to
188
+ -- the SAME draft, never leak a unique-key error or create duplicate lines.
189
+ IF NOT FOUND THEN
190
+ SELECT * INTO v_existing FROM public.records WHERE organization_id=p_org
191
+ AND collection='journalVouchers' AND id=p_id FOR UPDATE;
192
+ IF FOUND AND v_existing.data->>'requestFingerprint'=v_fp THEN
193
+ RETURN jsonb_build_object('voucher',
194
+ v_existing.data||jsonb_build_object('id',v_existing.id,'version',v_existing.version),
195
+ 'replayed',true);
196
+ END IF;
197
+ RAISE EXCEPTION 'FINORA_DRAFT_REQUEST_CONFLICT' USING ERRCODE='40001';
198
+ END IF;
199
PERFORM private.finora_phase1a_write_lines(p_org,v_actor,p_id,v_company,p_lines);
200
PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
201
PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'draft_created','',