سامانه صدور فاکتور و حسابداری
feat/document-lifecycle-temp-permanent-atef
audit-remediation-wave3-4-20261002
audit-remediation-wave3-verify-20261002
audit-remediation-wave4-20261002
audit-remediation-wave4b-20261002
audit-remediation-wave5a-identity-20261002
audit-remediation-wave5b-offboarding-20261002
audit-remediation-wave5c-authorization-20261002
audit-security-intent-review-20261002
audit/finora-financial-core-20261115
audit/finora-master-prompt-phase0-20261016
audit/finora-stage3-legacy-source-readonly-20261023
audit/full-controls-20261030
audit/owner-live-state-reconcile-20261012
audit/owner-review-20261007
audit/phase1-live-permissions-readonly-20261013
audit/reconcile-live-state-20261006
audit/reconcile-state-20261002
audit/wp0-hardening-baseline-20261102
branding-login-favicon-20261002
c8-workflow-task1
c8-workflow-task2
c8-workflow-task3
chore/wave0-pages-gate-closeout
claude-code-plugins-setup
design/finora-c01-authoritative-source-draft-20261124
docs-wave4b-verified-20261002
docs/active-company-invoice-release-evidence-20261014
docs/agent-operating-model-20261114
docs/chart-taxpayer-release-evidence-20261004
docs/cloud-only-agent-orchestration-20261115
docs/confirm-finora-product-charter-20261115
docs/continuation-20261030
docs/d4a-verified
docs/external-work-review-20261121
docs/finora-audit-continuity-20261014
docs/finora-backup-merge-evidence-20261014
docs/finora-ci-reconciliation-20261122
docs/finora-codex-master-prompt
docs/finora-eight-phase-plan-20261011
docs/finora-f002-live-buyer-filter-verified-20261015
docs/finora-license-race-release-evidence-20261014
docs/finora-license-rollout-acceptance-20261015
docs/finora-phase0-repeat-and-pages-nav-verified-20261015
docs/finora-phase0-repeat-evidence-20261015
docs/finora-selectors-release-and-fixture-qa-20261015
docs/finora-stagea-pr240-ci-triage-20261123
docs/finora-test-license-live-pass-20261015
docs/finora-v2-m01-coverage-20261124
docs/handoff-charter-v2-20261124
docs/invoice-product-search-release-20261011
docs/invoice-workspace-release-20261007
docs/phase-status-20261031
docs/phase0-acceptance-release-evidence-20261012
docs/phase0-admin-provision-release-evidence-20261012
docs/phase0-core-bundle-owner-login-open-20261013
docs/phase0-duplicate-js-release-20261016
docs/phase0-f001-auth-rest-shared-timeout-20261013
docs/phase0-f001-owner-login-observed-20261013
docs/phase0-f001-second-device-fail-40s-20261013
docs/phase0-f003-release-verification-20261011
docs/phase0-f004-print-release-evidence-20261012
docs/phase0-f004-watermark-release-evidence-20261012
docs/phase0-f005-large-selector-release-20261012
docs/phase0-f005-release-evidence-20261012
docs/phase0-f006-dark-release-evidence-20261012
docs/phase0-f008-final-pr-closure-evidence-20261012
docs/phase0-f008-reconcile-stale-prs-20261012
docs/phase0-f107-production-evidence-20261012
docs/phase0-kavenegar-otp-preflight-release-20261012
docs/phase0-login-release-evidence-20261012
docs/phase0-login-rest-bootstrap-stage-release-20261012
docs/phase0-owner-app-assets-bundle-release-20261013
docs/phase0-owner-login-csp-release-20261012
docs/phase0-reconcile-postmerge-evidence-20261012
docs/phase0-site-probe-release-evidence-20261012
docs/phase0-startup-release-evidence-20261012
docs/phase3-treasury-release-evidence-20261014
docs/pilot-posted-correction-release-evidence-20261014
docs/pilot-purchase-correction-release-evidence-20261014
docs/print-persian-release-verification-20261011
docs/qa-ci-triage-218-20261122
docs/real-account-qa-20261030
docs/release-state-20261007
docs/seamless-amendment-release-20261014
docs/seamless-document-correction-release-20261014
docs/settings-login-release-20261025
docs/stripe-qa-deployment-evidence-20261011
docs/ux-f2-release-evidence-20261011
docs/ux-f2-release-verification-20261011
docs/wave0-closeout
docs/wave2-closeout
exec-phase1-architecture
exec-phase1-implementation
exec-phase1-qa
exec-phase1-security-release
exec-phase1-ux
feat/accounting-document-draft-approval-20261011
feat/accounting-document-release-candidate-20261011
feat/active-company-strict-isolation-20261014
feat/admin-provisioning-reconciled-20261011
feat/admin-secure-user-provisioning-20261011
feat/admin-user-provisioning-merged-20261011
feat/d4a-request-work-queue
feat/document-lifecycle-atf-20261118
feat/document-lifecycle-temp-permanent-atef
feat/draft-first-attachment-lifecycle-216
feat/finora-offline-encrypted-backup-20261014
feat/finora-phase-a-navigation-20261023
feat/finora-stripe-sandbox-edge-gate
feat/immutable-attachment-temporary-vouchers
feat/iran-accounting-design-audit
feat/journal-document-lifecycle-20261118
feat/journal-rpc-repository-adapter-20261117
feat/office-c7-fulltext-ocr-provenance
feat/password-recovery-admin-reset-20261025
feat/pilot-expense-income-inplace-amendment-20261014
feat/pilot-journal-invoice-correction-20261014
feat/pilot-purchase-correction-20261014
feat/pilot-treasury-unallocated-correction-20261014
feat/retain-document-editor-after-save-20261014
feat/seamless-financial-document-correction-20261014
feat/slice-b-tenant-rbac
feat/stripe-sandbox-invoice-probe
feature/accounting-core-p0
feature/accounting-product-guidance
feature/admin-identity-phone-auth
feature/commercial-rnd
feature/finora-phase1a-supabase-cli-20261016
feature/finora-stage2-manual-canary-20261017
feature/finora-stage3-commercial-payload-20261023
feature/finora-stage3-enforce-invoice-rpc-20261023
feature/finora-stage3-enforce-purchase-red-20261023
feature/invoice-workspace-cleanup
feature/phase0-kavenegar-otp-preflight-20261012
feature/ux-commerce-settings-r2
fix-shell-scroll-live-cache-20261002
fix-shell-scrollbar-explicit-ownership-20261002
fix-shell-scrollbar-ownership-20261002
fix-shell-scrollbar-right-edge-20261002
fix/about-bug-report-20261114
fix/active-company-invoice-scope-20261014
fix/active-company-isolation-reconcile-20261014
fix/admin-central-password-reset-20261028
fix/auth-network-diagnostics
fix/chart-taxpayer-reference-20261003
fix/combobox-enter-reliability
fix/combobox-live-search
fix/combobox-production-cache
fix/combobox-release-asset-v2
fix/company-edit-action-20261028
fix/company-edit-pilot-delete-20261014
fix/company-form-action-state-20261014
fix/company-form-action-state-rebased-20261014
fix/contact-operational-balance-20261111
fix/dark-theme-contrast
fix/financial-lifecycle-recovery-20261124
fix/finora-accounting-test-organization-readiness-20261015
fix/finora-b01-safe-org-switch-20261124
fix/finora-b02-sync-recovery-20261124
fix/finora-b03-conflict-review-20261124
fix/finora-org-license-bootstrap-race-20261014
fix/finora-stage3-posted-source-immutable-20261023
fix/finora-v2-b03-r2-qa-20261124
fix/finora-v2-b03-r3-readonly-20261124
fix/g01-asof-financial-position-20261128
fix/invoice-product-search-rehydrate-20261011
fix/invoice-search-cache-bust
fix/issue229-linked-draft-status-20261122
fix/login-assets-retry-20261014
fix/login-inert-startup-20261110
fix/login-member-access-20261101
fix/login-resilience-20261017
fix/login-short-viewport-20261028
fix/login-startup-readiness-20261024
fix/navigation-utilities-placement-20261105
fix/office-c7-source-ref-binding
fix/office-c7-source-ref-binding-v2
fix/owner-login-network-20261026
fix/password-recovery-invalid-cancel-20261026
fix/payment-amount-format-20261111
fix/phase0-admin-provision-seat-bootstrap-20261012
fix/phase0-auth-bundled-assets-for-unstable-isp-20261013
fix/phase0-auth-handler-binding-stalled-session-20261012
fix/phase0-login-context-stage-visibility-20261012
fix/phase0-login-single-local-bundle-20261013
fix/phase0-login-site-probe-clarity-20261012
fix/phase0-login-ui-ready-20261012
fix/phase0-modal-dashboard-drill-20261011
fix/phase0-pages-blocking-core-bundles-20261013
fix/phase0-print-no-draft-watermark-20261012
fix/phase0-startup-parallel-asset-load-20261012
fix/phase3-behavioral-verification
fix/preserve-pending-edits-20261121
fix/print-persian-digit-consistency-20261011
fix/recovery-login-startup-20261027
fix/report-opening-balance-release-20261130
fix/settings-checkbox-persistence-20261024
fix/taxpayer-arithmetic-20261004
fix/ux-keyboard-search-f2-20261011
fix/wave2-request-input-integrity
hardening/c01-source-draft-20261129
hardening/global-draft-conversion-20261113
hardening/wp1-ledger-integrity-20261102
integration/finora-execution-20261124
integration/issue229-ui-qa-20261122
integration/wp1-ledger-core-20261115
integration/wp2-manual-journal-rpc-20261116
main
ops-heartbeat-v2-20261002
ops-progress-heartbeat-rule-20261002
ops/wave4-production-20261003
plan/financial-core-phase1-approval-20261016
qa/attachment-allocator-two-session-20261122
qa/draft-first-save-red-evidence-20261122
qa/finora-autopost-retry-identity-red-20261122
qa/finora-identity-rpc-security-tripwire-20261122
qa/finora-issue223-manual-kardex-browser-red-20261123
qa/finora-issue223-stock-real-jwt-20261123
qa/finora-issue238-inventory-count-browser-red-20261123
qa/finora-issue238-save-browser-red-20261122
qa/finora-login-cors-header-preflight-20261025
qa/finora-phase0-saved-session-repeat-20261015
qa/finora-phase5-posted-insert-jwt-red-20261123
qa/finora-stage3-ui-jwt-autopost-20261023
qa/finora-v2-g01-report-reconciliation-20261125
qa/free-supabase-local-wp2-20261116
qa/issue229-approval-boundary-jwt-20261122
qa/issue229-sale-save-linked-draft-red-20261122
qa/phase0-acceptance-start-20261012
qa/phase0-f005-account-project-contract-stress-20261012
qa/phase0-f005-selector-stress-20261012
qa/phase0-f006-dark-contrast-20261012
qa/post-wave4-verification-20261003
qa/posted-source-immutable-jwt-20261122
qa/pr219-wp1-disposable-dburl-proof-20261123
qa/purchase-source-jwt-20261122
qa/real-settings-acceptance-20261025
qa/recovery-mail-acceptance-20261026
qa/source-autopost-jwt-atomicity-20261122
qa/wave0-negative-gate-proof
qa/wp2-auth-tenant-e2e-20261117
qa/wp2-authorized-journal-write-20261122
qa/wp2-financial-paths-reconciliation-20261122
qa/wp3-financial-tenant-isolation-20261117
remediation/wave0-liveqa-wave1
remediation/wave2-request-integrity
staging/finora-stage22-free-20261022
state-scroll-verified-20261002
state-wave4b-production-20261002
state-wave5a-production-20261002
test/finora-accounting-boot-readiness-20261015
test/finora-f0-02-production-selectors-20261015
test/finora-pages-commerce-event-wiring-20261015
test/finora-pages-invoice-selectors-readonly-20261015
test/finora-stage3-jwt-source-post-20261023
test/phase0-invoice-fixture-bootstrap-20261016
test/phase0-invoice-persistence-20261011
test/phase0-pages-delayed-dispatcher-20261016
ux-scroll-ownership-20261002
work/finora-stage3-enforce-purchase-green-20261023
work/finora-stage3-enforce-sale-green-20261023
work/finora-stage3-payload-green-20261023
| 1 | -- Wave 4b: explicit SLA scheduler policy and durable outbox delivery state machine. |
| 2 | -- D4c destination consumers remain disabled; this migration only establishes the server-side contract. |
| 3 | |
| 4 | create table if not exists private.request_scheduler_runs( |
| 5 | id uuid primary key default gen_random_uuid(), |
| 6 | organization_id uuid not null references public.organizations(id) on delete cascade, |
| 7 | job_key text not null check(job_key in ('request_sla_escalation')), |
| 8 | run_key text not null check(char_length(trim(run_key)) between 8 and 200), |
| 9 | schedule_slot timestamptz not null, |
| 10 | server_clock timestamptz not null, |
| 11 | batch_limit integer not null check(batch_limit between 1 and 200), |
| 12 | processed_count integer not null default 0 check(processed_count between 0 and 200), |
| 13 | status text not null default 'running' check(status in ('running','completed')), |
| 14 | created_at timestamptz not null default now(), |
| 15 | completed_at timestamptz, |
| 16 | unique(organization_id,job_key,run_key), |
| 17 | unique(organization_id,job_key,schedule_slot) |
| 18 | ); |
| 19 | create table if not exists private.request_scheduler_run_items( |
| 20 | id uuid primary key default gen_random_uuid(), |
| 21 | scheduler_run_id uuid not null references private.request_scheduler_runs(id) on delete cascade, |
| 22 | organization_id uuid not null references public.organizations(id) on delete cascade, |
| 23 | request_instance_id uuid not null references public.request_instances(id) on delete cascade, |
| 24 | step_instance_id uuid not null references private.request_step_instances(id) on delete cascade, |
| 25 | due_at timestamptz not null, |
| 26 | claimed_at timestamptz not null, |
| 27 | outcome text not null check(outcome='escalated'), |
| 28 | created_at timestamptz not null default now(), |
| 29 | unique(step_instance_id) |
| 30 | ); |
| 31 | create index if not exists request_scheduler_runs_org_created_idx on private.request_scheduler_runs(organization_id,created_at desc); |
| 32 | create index if not exists request_scheduler_items_run_idx on private.request_scheduler_run_items(scheduler_run_id,created_at); |
| 33 | revoke all on private.request_scheduler_runs,private.request_scheduler_run_items from public,anon,authenticated; |
| 34 | |
| 35 | alter table private.request_outbox add column if not exists claim_token uuid; |
| 36 | alter table private.request_outbox add column if not exists claimed_at timestamptz; |
| 37 | alter table private.request_outbox add column if not exists last_attempt_at timestamptz; |
| 38 | alter table private.request_outbox add column if not exists last_worker_id text; |
| 39 | alter table private.request_outbox add column if not exists dead_lettered_at timestamptz; |
| 40 | alter table private.request_outbox add column if not exists replay_count integer not null default 0 check(replay_count between 0 and 100); |
| 41 | alter table private.request_outbox add column if not exists last_replay_key text; |
| 42 | alter table private.request_outbox add column if not exists destination_command_key text; |
| 43 | alter table private.request_outbox add column if not exists destination_receipt text; |
| 44 | update private.request_outbox set destination_command_key='request-outbox:'||id::text where destination_command_key is null; |
| 45 | alter table private.request_outbox alter column destination_command_key set not null; |
| 46 | create unique index if not exists request_outbox_destination_command_uidx on private.request_outbox(destination_command_key); |
| 47 | alter table private.request_outbox drop constraint if exists request_outbox_status_check; |
| 48 | alter table private.request_outbox add constraint request_outbox_status_check check(status in ('pending','processing','dispatched','failed','dead_letter')); |
| 49 | alter table private.request_outbox drop constraint if exists request_outbox_last_worker_id_check; |
| 50 | alter table private.request_outbox add constraint request_outbox_last_worker_id_check check(last_worker_id is null or char_length(trim(last_worker_id)) between 3 and 120); |
| 51 | alter table private.request_outbox drop constraint if exists request_outbox_last_replay_key_check; |
| 52 | alter table private.request_outbox add constraint request_outbox_last_replay_key_check check(last_replay_key is null or char_length(trim(last_replay_key)) between 8 and 200); |
| 53 | |
| 54 | create or replace function private.enqueue_request_outbox(p_request_instance_id uuid,p_workflow_schema jsonb,p_revision bigint) |
| 55 | returns integer language plpgsql security definer set search_path='' |
| 56 | as $$ |
| 57 | declare v_action jsonb;v_org uuid;v_count integer:=0;v_id uuid; |
| 58 | begin |
| 59 | select organization_id into v_org from public.request_instances where id=p_request_instance_id; |
| 60 | if v_org is null then raise exception 'request instance not found';end if; |
| 61 | if jsonb_typeof(p_workflow_schema->'onApproved')<>'array' then return 0;end if; |
| 62 | for v_action in select value from jsonb_array_elements(p_workflow_schema->'onApproved') loop |
| 63 | v_id:=gen_random_uuid(); |
| 64 | insert into private.request_outbox(id,organization_id,request_instance_id,event_key,target_module,action_key,payload,destination_command_key) |
| 65 | values(v_id,v_org,p_request_instance_id,'approved:'||p_revision::text,lower(trim(v_action->>'targetModule')),lower(trim(v_action->>'actionKey')),jsonb_build_object('requestInstanceId',p_request_instance_id,'requestRevision',p_revision,'config',coalesce(v_action->'payload','{}'::jsonb)),'request-outbox:'||v_id::text) |
| 66 | on conflict(request_instance_id,event_key,target_module,action_key) do nothing; |
| 67 | if found then v_count:=v_count+1;end if; |
| 68 | end loop; |
| 69 | return v_count; |
| 70 | end $$; |
| 71 | revoke all on function private.enqueue_request_outbox(uuid,jsonb,bigint) from public,anon,authenticated; |
| 72 | |
| 73 | create or replace function private.request_run_sla_scheduler(p_organization_id uuid,p_run_key text,p_schedule_slot timestamptz,p_limit integer default 100) |
| 74 | returns table(run_id uuid,processed_count integer,server_clock timestamptz,replayed boolean) |
| 75 | language plpgsql security definer set search_path='' |
| 76 | as $$ |
| 77 | declare v_clock timestamptz:=statement_timestamp();v_run private.request_scheduler_runs%rowtype;v_step private.request_step_instances%rowtype;v_count integer:=0; |
| 78 | begin |
| 79 | if char_length(trim(coalesce(p_run_key,''))) not between 8 and 200 then raise exception 'scheduler run_key must be between 8 and 200 characters';end if; |
| 80 | if p_limit is null or p_limit<1 or p_limit>200 then raise exception 'scheduler batch limit must be between 1 and 200';end if; |
| 81 | if p_schedule_slot is null or mod(extract(epoch from p_schedule_slot)::bigint,300)<>0 then raise exception 'scheduler slot must align to a 5-minute UTC boundary';end if; |
| 82 | if p_schedule_slot>v_clock+interval '30 seconds' or p_schedule_slot<v_clock-interval '1 hour' then raise exception 'scheduler slot is outside the accepted server-clock window';end if; |
| 83 | select * into v_run from private.request_scheduler_runs r where r.organization_id=p_organization_id and r.job_key='request_sla_escalation' and r.run_key=trim(p_run_key); |
| 84 | if found then |
| 85 | if v_run.schedule_slot<>p_schedule_slot or v_run.batch_limit<>p_limit then raise exception 'scheduler run_key is already bound to a different command' using errcode='23505';end if; |
| 86 | return query select v_run.id,v_run.processed_count,v_run.server_clock,true;return; |
| 87 | end if; |
| 88 | if exists(select 1 from private.request_scheduler_runs r where r.organization_id=p_organization_id and r.job_key='request_sla_escalation' and r.schedule_slot=p_schedule_slot) then raise exception 'scheduler slot is already claimed' using errcode='23505';end if; |
| 89 | insert into private.request_scheduler_runs(organization_id,job_key,run_key,schedule_slot,server_clock,batch_limit) |
| 90 | values(p_organization_id,'request_sla_escalation',trim(p_run_key),p_schedule_slot,v_clock,p_limit) returning * into v_run; |
| 91 | for v_step in |
| 92 | select * from private.request_step_instances s |
| 93 | where s.organization_id=p_organization_id and s.state='active' and s.due_at is not null and s.due_at<=v_clock and s.escalated_at is null |
| 94 | order by s.due_at,s.id for update skip locked limit p_limit |
| 95 | loop |
| 96 | update private.request_step_instances set escalated_at=v_clock,escalation_level=escalation_level+1 where id=v_step.id and escalated_at is null; |
| 97 | if found then |
| 98 | insert into private.request_scheduler_run_items(scheduler_run_id,organization_id,request_instance_id,step_instance_id,due_at,claimed_at,outcome) |
| 99 | values(v_run.id,p_organization_id,v_step.request_instance_id,v_step.id,v_step.due_at,v_clock,'escalated'); |
| 100 | insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,after_data) |
| 101 | values(p_organization_id,null,'request_step_sla_escalated_system','request_step_instance',v_step.id::text, |
| 102 | jsonb_build_object('requestInstanceId',v_step.request_instance_id,'stepKey',v_step.step_key,'dueAt',v_step.due_at,'serverClock',v_clock,'schedulerRunId',v_run.id)); |
| 103 | v_count:=v_count+1; |
| 104 | end if; |
| 105 | end loop; |
| 106 | update private.request_scheduler_runs set processed_count=v_count,status='completed',completed_at=statement_timestamp() where id=v_run.id returning * into v_run; |
| 107 | return query select v_run.id,v_run.processed_count,v_run.server_clock,false; |
| 108 | end $$; |
| 109 | revoke all on function private.request_run_sla_scheduler(uuid,text,timestamptz,integer) from public,anon,authenticated; |
| 110 | |
| 111 | create or replace function public.request_run_sla_scheduler(p_organization_id uuid,p_run_key text,p_schedule_slot timestamptz,p_limit integer default 100) |
| 112 | returns table(run_id uuid,processed_count integer,server_clock timestamptz,replayed boolean) |
| 113 | language sql security definer set search_path='' |
| 114 | as $$ select * from private.request_run_sla_scheduler(p_organization_id,p_run_key,p_schedule_slot,p_limit) $$; |
| 115 | revoke all on function public.request_run_sla_scheduler(uuid,text,timestamptz,integer) from public,anon,authenticated; |
| 116 | do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_run_sla_scheduler(uuid,text,timestamptz,integer) to service_role';end if;end $$; |
| 117 | |
| 118 | create or replace function private.request_claim_outbox(p_worker_id text,p_limit integer default 25) |
| 119 | returns table(outbox_id uuid,organization_id uuid,request_instance_id uuid,target_module text,action_key text,payload jsonb,destination_command_key text,claim_token uuid,attempts integer,server_clock timestamptz) |
| 120 | language plpgsql security definer set search_path='' |
| 121 | as $$ |
| 122 | declare v_clock timestamptz:=statement_timestamp(); |
| 123 | begin |
| 124 | if char_length(trim(coalesce(p_worker_id,''))) not between 3 and 120 then raise exception 'worker_id must be between 3 and 120 characters';end if; |
| 125 | if p_limit is null or p_limit<1 or p_limit>100 then raise exception 'outbox claim limit must be between 1 and 100';end if; |
| 126 | update private.request_outbox o set status='dead_letter',dead_lettered_at=v_clock,claim_token=null,claimed_at=null,last_error=coalesce(o.last_error,'claim lease expired after maximum attempts') |
| 127 | where o.status='processing' and o.claimed_at<v_clock-interval '10 minutes' and o.attempts>=5; |
| 128 | return query |
| 129 | with candidates as ( |
| 130 | select o.id from private.request_outbox o |
| 131 | where ((o.status in('pending','failed') and o.available_at<=v_clock) or (o.status='processing' and o.claimed_at<v_clock-interval '10 minutes')) |
| 132 | and o.attempts<5 |
| 133 | order by o.available_at,o.created_at,o.id |
| 134 | for update skip locked limit p_limit |
| 135 | ), claimed as ( |
| 136 | update private.request_outbox o set status='processing',claim_token=gen_random_uuid(),claimed_at=v_clock,last_attempt_at=v_clock,last_worker_id=trim(p_worker_id),attempts=o.attempts+1,last_error=case when o.status='processing' then coalesce(o.last_error,'stale claim recovered') else o.last_error end |
| 137 | from candidates c where o.id=c.id |
| 138 | returning o.id,o.organization_id,o.request_instance_id,o.target_module,o.action_key,o.payload,o.destination_command_key,o.claim_token,o.attempts |
| 139 | ) |
| 140 | select c.id,c.organization_id,c.request_instance_id,c.target_module,c.action_key,c.payload,c.destination_command_key,c.claim_token,c.attempts,v_clock from claimed c; |
| 141 | end $$; |
| 142 | revoke all on function private.request_claim_outbox(text,integer) from public,anon,authenticated; |
| 143 | |
| 144 | create or replace function public.request_claim_outbox(p_worker_id text,p_limit integer default 25) |
| 145 | returns table(outbox_id uuid,organization_id uuid,request_instance_id uuid,target_module text,action_key text,payload jsonb,destination_command_key text,claim_token uuid,attempts integer,server_clock timestamptz) |
| 146 | language sql security definer set search_path='' |
| 147 | as $$ select * from private.request_claim_outbox(p_worker_id,p_limit) $$; |
| 148 | revoke all on function public.request_claim_outbox(text,integer) from public,anon,authenticated; |
| 149 | do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_claim_outbox(text,integer) to service_role';end if;end $$; |
| 150 | |
| 151 | create or replace function private.request_complete_outbox(p_outbox_id uuid,p_claim_token uuid,p_destination_receipt text default null) |
| 152 | returns boolean language plpgsql security definer set search_path='' |
| 153 | as $$ |
| 154 | declare v_org uuid;v_clock timestamptz:=statement_timestamp();v_key text; |
| 155 | begin |
| 156 | if p_claim_token is null then raise exception 'claim token is required';end if; |
| 157 | update private.request_outbox o set status='dispatched',dispatched_at=v_clock,destination_receipt=nullif(left(trim(coalesce(p_destination_receipt,'')),500),''),claim_token=null,claimed_at=null,last_error=null |
| 158 | where o.id=p_outbox_id and o.status='processing' and o.claim_token=p_claim_token |
| 159 | returning o.organization_id,o.destination_command_key into v_org,v_key; |
| 160 | if not found then raise exception 'outbox claim is stale or invalid' using errcode='40001';end if; |
| 161 | insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,after_data) |
| 162 | values(v_org,null,'request_outbox_dispatched','request_outbox',p_outbox_id::text,jsonb_build_object('destinationCommandKey',v_key,'serverClock',v_clock)); |
| 163 | return true; |
| 164 | end $$; |
| 165 | revoke all on function private.request_complete_outbox(uuid,uuid,text) from public,anon,authenticated; |
| 166 | create or replace function public.request_complete_outbox(p_outbox_id uuid,p_claim_token uuid,p_destination_receipt text default null) |
| 167 | returns boolean language sql security definer set search_path='' as $$ select private.request_complete_outbox(p_outbox_id,p_claim_token,p_destination_receipt) $$; |
| 168 | revoke all on function public.request_complete_outbox(uuid,uuid,text) from public,anon,authenticated; |
| 169 | do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_complete_outbox(uuid,uuid,text) to service_role';end if;end $$; |
| 170 | |
| 171 | create or replace function private.request_fail_outbox(p_outbox_id uuid,p_claim_token uuid,p_error text) |
| 172 | returns text language plpgsql security definer set search_path='' |
| 173 | as $$ |
| 174 | declare v_row private.request_outbox%rowtype;v_clock timestamptz:=statement_timestamp();v_next text;v_delay interval; |
| 175 | begin |
| 176 | if p_claim_token is null then raise exception 'claim token is required';end if; |
| 177 | select * into v_row from private.request_outbox o where o.id=p_outbox_id and o.status='processing' and o.claim_token=p_claim_token for update; |
| 178 | if not found then raise exception 'outbox claim is stale or invalid' using errcode='40001';end if; |
| 179 | if v_row.attempts>=5 then v_next:='dead_letter';v_delay:=interval '0';else v_next:='failed';v_delay:=make_interval(secs=>least(3600,60*(2^greatest(v_row.attempts-1,0))::integer));end if; |
| 180 | update private.request_outbox set status=v_next,available_at=v_clock+v_delay,last_error=left(coalesce(nullif(trim(p_error),''),'delivery failed'),1000),dead_lettered_at=case when v_next='dead_letter' then v_clock else null end,claim_token=null,claimed_at=null where id=p_outbox_id; |
| 181 | insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,after_data) |
| 182 | values(v_row.organization_id,null,case when v_next='dead_letter' then 'request_outbox_dead_lettered' else 'request_outbox_retry_scheduled' end,'request_outbox',p_outbox_id::text, |
| 183 | jsonb_build_object('destinationCommandKey',v_row.destination_command_key,'attempts',v_row.attempts,'nextState',v_next,'availableAt',v_clock+v_delay,'serverClock',v_clock)); |
| 184 | return v_next; |
| 185 | end $$; |
| 186 | revoke all on function private.request_fail_outbox(uuid,uuid,text) from public,anon,authenticated; |
| 187 | create or replace function public.request_fail_outbox(p_outbox_id uuid,p_claim_token uuid,p_error text) |
| 188 | returns text language sql security definer set search_path='' as $$ select private.request_fail_outbox(p_outbox_id,p_claim_token,p_error) $$; |
| 189 | revoke all on function public.request_fail_outbox(uuid,uuid,text) from public,anon,authenticated; |
| 190 | do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_fail_outbox(uuid,uuid,text) to service_role';end if;end $$; |
| 191 | |
| 192 | create or replace function private.request_replay_dead_letter(p_organization_id uuid,p_outbox_id uuid,p_idempotency_key text,p_reason text) |
| 193 | returns boolean language plpgsql security definer set search_path='' |
| 194 | as $$ |
| 195 | declare v_row private.request_outbox%rowtype;v_clock timestamptz:=statement_timestamp();v_before integer; |
| 196 | begin |
| 197 | if auth.uid() is null then raise exception 'authentication required' using errcode='28000';end if; |
| 198 | if p_organization_id not in(select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501';end if; |
| 199 | if not private.has_org_capability(p_organization_id,'requests_workflow','configure') then raise exception 'requests_workflow configure capability required' using errcode='42501';end if; |
| 200 | if char_length(trim(coalesce(p_idempotency_key,''))) not between 8 and 200 then raise exception 'replay idempotency_key must be between 8 and 200 characters';end if; |
| 201 | select * into v_row from private.request_outbox o where o.id=p_outbox_id and o.organization_id=p_organization_id for update; |
| 202 | if not found then raise exception 'outbox item not found';end if; |
| 203 | if v_row.last_replay_key=trim(p_idempotency_key) then return true;end if; |
| 204 | if v_row.status<>'dead_letter' then raise exception 'only dead-letter outbox items can be replayed';end if; |
| 205 | v_before:=v_row.attempts; |
| 206 | update private.request_outbox set status='pending',attempts=0,available_at=v_clock,last_error=null,dead_lettered_at=null,claim_token=null,claimed_at=null,replay_count=replay_count+1,last_replay_key=trim(p_idempotency_key) where id=p_outbox_id; |
| 207 | insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data) |
| 208 | values(p_organization_id,auth.uid(),'request_outbox_replayed','request_outbox',p_outbox_id::text,jsonb_build_object('status','dead_letter','attempts',v_before), |
| 209 | jsonb_build_object('status','pending','destinationCommandKey',v_row.destination_command_key,'reason',left(coalesce(p_reason,''),500),'serverClock',v_clock,'idempotencyKey',trim(p_idempotency_key))); |
| 210 | return true; |
| 211 | end $$; |
| 212 | revoke all on function private.request_replay_dead_letter(uuid,uuid,text,text) from public,anon; |
| 213 | grant execute on function private.request_replay_dead_letter(uuid,uuid,text,text) to authenticated; |
| 214 | create or replace function public.request_replay_dead_letter(p_organization_id uuid,p_outbox_id uuid,p_idempotency_key text,p_reason text default null) |
| 215 | returns boolean language sql security invoker set search_path='' as $$ select private.request_replay_dead_letter(p_organization_id,p_outbox_id,p_idempotency_key,p_reason) $$; |
| 216 | revoke all on function public.request_replay_dead_letter(uuid,uuid,text,text) from public,anon; |
| 217 | grant execute on function public.request_replay_dead_letter(uuid,uuid,text,text) to authenticated; |