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

Requests: remediate Wave 4 operational integrity

* Requests: remediate Wave 4 operational integrity * Tests: use idempotent delegation contract in D4a * State: reconcile environment handoff and live targets

davoodmehraban89 committed Oct 2, 2026 at 10:15 UTC 7571e1851768d38a2d199490564a7feddfad6e0e
8 files changed +140 -13
.github/workflows/quality.yml
+4
@@ -208,6 +208,10 @@ jobs:
208 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002071000_request_wave3_decision_idempotency.sql
209 - name: Execute Wave 3 replay authorization and stability assertions
210 run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_wave3_decision_idempotency.sql
211 + - name: Apply Wave 4 operational integrity hardening
212 + run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002072000_request_wave4_operational_integrity.sql
213 + - name: Execute Wave 4 outbox/SLA/delegation assertions
214 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_wave4_operational_integrity.sql
215 - name: Apply D4a authorized work queue
216 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002033000_request_workflow_d4a_work_queue.sql
217 - name: Execute D4a work queue assertions
PROJECT_STATE.md
+2
@@ -14,6 +14,8 @@ This is high-assurance accounting/ERP software. Posted financial history, tenant
14 ## Current change ledger
15 | Date | Request / decision | Status | Evidence / next action |
16 |---|---|---|---|
17 +| 2026-10-02 | Owner supplied environment/connection handoff and directed it to be enforced while continuing work. | **LIVE RECONCILED / ACTIVE OPERATING CONTEXT** | Verified GitHub target `davoodmehraban89/Factor-easy` with admin/read-write access, canonical `main`, and Supabase target `hcsixhqbyuhpshfwqpjx` = Finora / `ACTIVE_HEALTHY`. GitHub + Supabase remain source of truth; Gmail/Notion are optional support only, and Railway/Render are not deployment truth unless a later explicit project decision makes them so. Detected concurrent branch advancement during Wave 4 and refused a non-fast-forward overwrite; re-read the newer head before continuing. |
18 +| 2026-10-02 | Wave 4 remediation F-420/F-421/F-422 from canonical audit register. | **IMPLEMENTED ON BRANCH / NOT YET VERIFIED** | F-420 rejects duplicate normalized `onApproved` target/action identities; F-421 binds SLA editor values to logical step keys across reorder/remove/key-edit; F-422 adds actor-scoped delegation idempotency, explicit overlap rejection and revoke retry audit dedupe. Disposable-DB + Real-DOM gates added. CI/merge/production remain NOT VERIFIED at this checkpoint. |
19 | 2026-10-02 | Owner supplied the current remediation/audit package plus manual GitHub QA workflow and directed continuation of both roadmap execution and defect remediation. | **F-412 + WAVE 3 F-415/F-416 VERIFIED / PRODUCTION RECONCILED** | PR #23 merged as `d13498f3af03f544c05168727b440f053de1d733`. Main Quality `36973781026` SUCCESS including disposable D1 DB adversarial tests; Security `36973781055` SUCCESS (Release/QA safety + CodeQL; PR Dependency Review remains externally blocked by disabled Dependency Graph); Release gate `36973927530` SUCCESS; gated Pages `36973959986` SUCCESS. Production migrations `20261002063121 request_wave2_duplicate_code_guard` and `20261002063123 request_wave3_decision_idempotency` applied. Read-only production reconciliation: duplicate legacy code groups=0; replay actor binding, reauthorization and immutable event-outcome reconstruction are present. Next: Wave 4 F-420/F-421/F-422; D4c consumers remain disabled. |
20 | 2026-10-02 | Owner directed immediate continuation after observing execution delay. | **D4A IMPLEMENTED / PRODUCTION + DISPOSABLE-DB + REAL-DOM + ACCOUNTING + SECURITY VERIFIED** | PR #21 merged as `4583703396a7ddb00bdad76b52c22932d634cbef`. Main Quality `36961361891` SUCCESS (38/38 real-DOM, accounting phases 2–6 + Golden, D1/C8 DB); Security `36961361897` SUCCESS; Release gate `36961459328` SUCCESS; gated Pages `36961492170` SUCCESS. Production migration `20261002034311 request_workflow_d4a_work_queue` reconciled. Evidence: `docs/REQUEST_WORKFLOW_D4A_VERIFICATION.md`. |\n| 2026-10-02 | Owner switched GitHub Pages source to **GitHub Actions** after the gated Pages workflow was installed. | **WAVE 0 COMPLETED / POSITIVE + NEGATIVE CONTROLS VERIFIED** | Negative control: failing SHA `03561a3369130a7aaba689474d92aa3e93137404` on PR #15 failed required `static-quality`, could not merge, and produced no Release gate / gated Pages deployment. Positive control: protected-main SHA `150ff54d938a45b9a9b476f3a4a8fdabbb45d065` passed Quality `36932956964`, Security `36932956877`, exact-SHA Release gate `36933115365`, then gated Pages deploy `36933151878`; no legacy dynamic branch Pages deployment appeared. F-402/F-403/F-406/F-407/F-423/F-424 are closed at the verified GitHub/repository boundary. |
21 | 2026-10-02 | Wave 2 request integrity remediation F-411/F-413/F-414/F-417/F-418. | **IMPLEMENTED / PRODUCTION + DISPOSABLE-DB + REAL-DOM + ACCOUNTING + SECURITY VERIFIED** | Squash merge `7346910638b6ef9555d4adb5952dd62c8f4c130d` from PR #19. PR Quality `36937247798`: DB jobs SUCCESS and 37/37 real-DOM tests passed; accounting phases + Golden journey passed. PR Security `36937247803`: required Release/QA invariants + CodeQL SUCCESS (Dependency review remains the documented external graph boundary). Main Quality `36937448157` SUCCESS; Security `36937448101` SUCCESS; exact-SHA Release gate `36937598497` SUCCESS; gated Pages `36937616201` SUCCESS. Production migration recorded as `20261001225044 request_wave2_integrity_hardening`; live validator negative controls and function-contract checks passed. |
js/request-workflow-d3c.js
+9 -8
@@ -1,33 +1,34 @@
1 /* Finora Requests D3c: SLA evidence, explicit delegation and transactional outbox UX. */
2 (function(){
3 -const O={sla:[],actions:[],members:[],delegations:[]};
3 +const O={slaByKey:{},actions:[],members:[],delegations:[],delegationCommand:null};
4 const org=()=>currentUser?.organizationId||'';
5 const e=v=>typeof esc==='function'?esc(v):String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
6 const canConfig=()=>!!currentUser&&(currentUser.isOrganizationOwner||typeof finoraCanConfigureModule==='function'&&finoraCanConfigureModule('requests_workflow'));
7 const fa=n=>Number(n||0).toLocaleString('fa-IR');
8 async function tableRows(table,columns,order='created_at'){const q=sb.from(table).select(columns).eq('organization_id',org());const r=await q.order(order,{ascending:false});if(r.error)throw r.error;return r.data||[]}
9 -async function loadConfig(definitionId){const versions=await tableRows('request_type_versions','id,request_type_id,version_no','version_no');const latest=versions.filter(v=>v.request_type_id===definitionId).sort((a,b)=>Number(b.version_no)-Number(a.version_no))[0];if(!latest){O.sla=[];O.actions=[];return}const workflows=await tableRows('request_workflow_versions','id,request_type_version_id,workflow_schema,published_at','published_at');const schema=(workflows.find(w=>w.request_type_version_id===latest.id)||{}).workflow_schema||{};O.sla=(Array.isArray(schema.steps)?schema.steps:[]).map(s=>Number(s.slaHours||0));O.actions=(Array.isArray(schema.onApproved)?schema.onApproved:[]).map(a=>({targetModule:String(a.targetModule||'commerce'),actionKey:String(a.actionKey||''),payload:a.payload&&typeof a.payload==='object'?a.payload:{}}))}
9 +async function loadConfig(definitionId){const versions=await tableRows('request_type_versions','id,request_type_id,version_no','version_no');const latest=versions.filter(v=>v.request_type_id===definitionId).sort((a,b)=>Number(b.version_no)-Number(a.version_no))[0];if(!latest){O.slaByKey={};O.actions=[];return}const workflows=await tableRows('request_workflow_versions','id,request_type_version_id,workflow_schema,published_at','published_at');const schema=(workflows.find(w=>w.request_type_version_id===latest.id)||{}).workflow_schema||{};O.slaByKey=Object.fromEntries((Array.isArray(schema.steps)?schema.steps:[]).map(s=>[String(s.key||'').trim().toLowerCase(),Number(s.slaHours||0)]));O.actions=(Array.isArray(schema.onApproved)?schema.onApproved:[]).map(a=>({targetModule:String(a.targetModule||'commerce'),actionKey:String(a.actionKey||''),payload:a.payload&&typeof a.payload==='object'?a.payload:{}}))}
10 function outboxActionRow(a,i){const modules=[['commerce','بازرگانی'],['accounting','حسابداری'],['treasury','خزانه'],['inventory','انبار'],['assets','دارایی'],['hr_payroll','حقوق و دستمزد'],['office_automation','اتوماسیون اداری'],['crm','CRM'],['contracting','پیمانکاری'],['transport','حمل‌ونقل'],['manufacturing','تولید'],['maintenance','نگهداری'],['analytics','تحلیل']];return '<div class="request-d3c-outbox-action" style="display:flex;gap:8px;align-items:end;flex-wrap:wrap;margin:8px 0"><div class="form-group" style="min-width:150px"><label>ماژول مقصد</label><select class="form-control" onchange="requestD3cActionChange('+i+',\'targetModule\',this.value)">'+modules.map(x=>'<option value="'+x[0]+'" '+(a.targetModule===x[0]?'selected':'')+'>'+x[1]+'</option>').join('')+'</select></div><div class="form-group" style="flex:1;min-width:210px"><label>کلید عملیات</label><input class="form-control" value="'+e(a.actionKey)+'" placeholder="create_purchase_draft" oninput="requestD3cActionChange('+i+',\'actionKey\',this.value)"></div><button class="btn btn-danger btn-inline" onclick="requestD3cRemoveOutboxAction('+i+')">حذف</button></div>'}
11 function renderOutboxConfig(){const box=document.getElementById('request-d3c-outbox-config');if(!box)return;box.innerHTML='<div style="display:flex;justify-content:space-between;gap:8px;align-items:flex-start;flex-wrap:wrap"><div><h3 style="font-size:15px">اقدامات پس از تأیید</h3><p class="af-hint">فقط پیام تراکنشی Outbox ثبت می‌شود؛ هیچ ماژول مقصدی مستقیماً از گردش‌کار تغییر نمی‌کند.</p></div><button class="btn btn-secondary btn-inline" onclick="requestD3cAddOutboxAction()">+ افزودن اقدام</button></div>'+(O.actions.map(outboxActionRow).join('')||'<div class="af-empty">اقدام بین‌ماژولی تعریف نشده است.</div>')}
12 -function decorateEditor(){const editor=document.getElementById('request-d3b-editor');if(!editor)return;document.querySelectorAll('.request-d3b-step').forEach((card,i)=>{if(card.querySelector('[data-d3c-sla]'))return;const wrap=document.createElement('div');wrap.className='request-d3c-sla-wrap';wrap.style.cssText='border-top:1px dashed #dbe5ef;padding-top:10px;margin-top:10px';wrap.innerHTML='<div class="form-group"><label>SLA مرحله (ساعت)</label><input data-d3c-sla type="number" min="1" max="8760" class="form-control" value="'+(O.sla[i]||'')+'" placeholder="اختیاری؛ مثلاً 24"><small class="af-hint">مهلت از لحظه فعال‌شدن مرحله محاسبه می‌شود.</small></div>';card.appendChild(wrap)});let box=document.getElementById('request-d3c-outbox-config');if(!box){box=document.createElement('div');box.id='request-d3c-outbox-config';box.className='card';editor.after(box)}renderOutboxConfig()}
12 +function captureSla(){document.querySelectorAll('.request-d3b-step').forEach(card=>{const input=card.querySelector('[data-d3c-sla]');if(!input)return;const key=String(input.dataset.d3cStepKey||card.querySelector('[data-d3b="key"]')?.value||'').trim().toLowerCase();if(key)O.slaByKey[key]=Number(input.value||0)})}
13 +function decorateEditor(){const editor=document.getElementById('request-d3b-editor');if(!editor)return;document.querySelectorAll('.request-d3b-step').forEach(card=>{const key=String(card.querySelector('[data-d3b="key"]')?.value||'').trim().toLowerCase();let input=card.querySelector('[data-d3c-sla]');if(input){input.dataset.d3cStepKey=key;input.value=O.slaByKey[key]||'';return}const wrap=document.createElement('div');wrap.className='request-d3c-sla-wrap';wrap.style.cssText='border-top:1px dashed #dbe5ef;padding-top:10px;margin-top:10px';wrap.innerHTML='<div class="form-group"><label>SLA مرحله (ساعت)</label><input data-d3c-sla data-d3c-step-key="'+e(key)+'" type="number" min="1" max="8760" class="form-control" value="'+(O.slaByKey[key]||'')+'" placeholder="اختیاری؛ مثلاً 24"><small class="af-hint">مهلت از لحظه فعال‌شدن مرحله محاسبه می‌شود.</small></div>';card.appendChild(wrap)});let box=document.getElementById('request-d3c-outbox-config');if(!box){box=document.createElement('div');box.id='request-d3c-outbox-config';box.className='card';editor.after(box)}renderOutboxConfig()}
14 window.requestD3cAddOutboxAction=function(){if(O.actions.length>=10)return alert('حداکثر ۱۰ اقدام پس از تأیید مجاز است.');O.actions.push({targetModule:'commerce',actionKey:'',payload:{}});renderOutboxConfig()};
15 window.requestD3cRemoveOutboxAction=function(i){O.actions.splice(i,1);renderOutboxConfig()};
16 window.requestD3cActionChange=function(i,key,value){if(O.actions[i])O.actions[i][key]=value};
17 const d3bPublish=window.requestD3bPublishCombined;
17 -window.requestD3bPublishCombined=async function(){const sla=[...document.querySelectorAll('[data-d3c-sla]')].map(x=>Number(x.value||0)),actions=O.actions.map(a=>({targetModule:a.targetModule,actionKey:String(a.actionKey||'').trim().toLowerCase(),payload:a.payload||{}})),rpc=sb.rpc.bind(sb);sb.rpc=async(name,args)=>{if(name!=='request_publish_type_version')return rpc(name,args);const schema=JSON.parse(JSON.stringify(args?.p_workflow_schema||{}));schema.steps=(schema.steps||[]).map((s,i)=>{if(sla[i]>0)s.slaHours=sla[i];return s});if(actions.length)schema.onApproved=actions;else delete schema.onApproved;return rpc(name,{...args,p_workflow_schema:schema})};try{return await d3bPublish()}finally{sb.rpc=rpc;O.sla=sla;decorateEditor()}}
18 +window.requestD3bPublishCombined=async function(){captureSla();const actions=O.actions.map(a=>({targetModule:a.targetModule,actionKey:String(a.actionKey||'').trim().toLowerCase(),payload:a.payload||{}})),rpc=sb.rpc.bind(sb);sb.rpc=async(name,args)=>{if(name!=='request_publish_type_version')return rpc(name,args);const schema=JSON.parse(JSON.stringify(args?.p_workflow_schema||{}));schema.steps=(schema.steps||[]).map(s=>{const key=String(s.key||'').trim().toLowerCase(),sla=Number(O.slaByKey[key]||0);if(sla>0)s.slaHours=sla;else delete s.slaHours;return s});if(actions.length)schema.onApproved=actions;else delete schema.onApproved;return rpc(name,{...args,p_workflow_schema:schema})};try{return await d3bPublish()}finally{sb.rpc=rpc;decorateEditor()}}
19 async function loadOps(){try{O.members=await tableRows('organization_members','id,user_id,status,is_owner,position_title,created_at','created_at')}catch(_){O.members=[]}try{const r=await sb.rpc('request_list_delegations',{p_organization_id:org()});O.delegations=r.error?[]:(r.data||[])}catch(_){O.delegations=[]}}
20 function defaultUntil(){const d=new Date(Date.now()+7*86400000);const z=n=>String(n).padStart(2,'0');return d.getFullYear()+'-'+z(d.getMonth()+1)+'-'+z(d.getDate())+'T'+z(d.getHours())+':'+z(d.getMinutes())}
21 function renderOps(){const root=document.getElementById('view-requests');if(!root)return;let box=document.getElementById('request-d3c-ops');if(!box){box=document.createElement('div');box.id='request-d3c-ops';box.className='card';root.appendChild(box)}const others=O.members.filter(m=>m.status==='active'&&m.user_id!==currentUser?.id);box.innerHTML='<div style="display:flex;justify-content:space-between;gap:8px;align-items:center;flex-wrap:wrap"><div><h3 style="font-size:15px">عملیات گردش‌کار</h3><p class="af-hint">SLA، جانشینی زمان‌دار و وضعیت پیام‌های بین‌ماژولی با سابقه قابل ردگیری.</p></div>'+(canConfig()?'<button class="btn btn-secondary btn-inline" onclick="requestD3cEscalateOverdue()">بررسی SLAهای سررسیدشده</button>':'')+'</div><div style="margin-top:12px;border-top:1px solid #edf2f7;padding-top:12px"><strong>واگذاری موقت اختیار</strong><div class="form-row" style="margin-top:8px"><div class="form-group"><label>جانشین</label><select id="request-d3c-delegate-user" class="form-control"><option value="">انتخاب عضو</option>'+others.map(m=>'<option value="'+e(m.user_id)+'">'+e(m.position_title||String(m.user_id).slice(0,8))+'</option>').join('')+'</select></div><div class="form-group"><label>اختیار</label><select id="request-d3c-delegate-cap" class="form-control"><option value="approve">تأیید</option><option value="edit">ویرایش</option><option value="configure">پیکربندی مرحله</option></select></div><div class="form-group"><label>تا تاریخ</label><input id="request-d3c-delegate-until" type="datetime-local" class="form-control" value="'+defaultUntil()+'"></div><div class="form-group"><label>علت</label><input id="request-d3c-delegate-reason" class="form-control" placeholder="مثلاً مرخصی"></div></div><button class="btn btn-primary btn-inline" onclick="requestD3cCreateDelegation()">ثبت جانشینی</button><div style="margin-top:10px">'+(O.delegations.map(d=>'<div class="af-hint" style="padding:6px 0">'+e(d.capability)+' → '+e(String(d.toUserId||'').slice(0,8))+' · '+(d.active?'فعال':'غیرفعال')+(d.fromUserId===currentUser?.id&&d.active?' <button class="btn btn-danger btn-inline" onclick="requestD3cRevokeDelegation(\''+e(d.id)+'\')">لغو</button>':'')+'</div>').join('')||'<div class="af-empty">جانشینی ثبت نشده است.</div>')+'</div></div>'}
22 async function mountOps(){await loadOps();renderOps()}
22 -window.requestD3cCreateDelegation=async function(){const to=document.getElementById('request-d3c-delegate-user')?.value,cap=document.getElementById('request-d3c-delegate-cap')?.value,until=document.getElementById('request-d3c-delegate-until')?.value,reason=document.getElementById('request-d3c-delegate-reason')?.value;if(!to||!until)return alert('جانشین و تاریخ پایان را مشخص کنید.');const r=await sb.rpc('request_create_delegation',{p_organization_id:org(),p_to_user_id:to,p_capability:cap,p_valid_from:new Date().toISOString(),p_valid_to:new Date(until).toISOString(),p_reason:reason||null});if(r.error)return alert(r.error.message||r.error);await mountOps()};
23 +window.requestD3cCreateDelegation=async function(){const to=document.getElementById('request-d3c-delegate-user')?.value,cap=document.getElementById('request-d3c-delegate-cap')?.value,until=document.getElementById('request-d3c-delegate-until')?.value,reason=document.getElementById('request-d3c-delegate-reason')?.value;if(!to||!until)return alert('جانشین و تاریخ پایان را مشخص کنید.');const signature=[org(),to,cap,until,reason||''].join('|');if(!O.delegationCommand||O.delegationCommand.signature!==signature)O.delegationCommand={signature,key:'delegation-'+(globalThis.crypto?.randomUUID?.()||Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)),validFrom:new Date().toISOString()};const r=await sb.rpc('request_create_delegation',{p_organization_id:org(),p_to_user_id:to,p_capability:cap,p_valid_from:O.delegationCommand.validFrom,p_valid_to:new Date(until).toISOString(),p_reason:reason||null,p_idempotency_key:O.delegationCommand.key});if(r.error)return alert(r.error.message||r.error);O.delegationCommand=null;await mountOps()};
24 window.requestD3cRevokeDelegation=async function(id){const r=await sb.rpc('request_revoke_delegation',{p_organization_id:org(),p_delegation_id:id});if(r.error)return alert(r.error.message||r.error);await mountOps()};
25 window.requestD3cEscalateOverdue=async function(){const r=await sb.rpc('request_escalate_overdue',{p_organization_id:org()});if(r.error)return alert(r.error.message||r.error);alert(fa(r.data||0)+' مرحله سررسیدشده ثبت شد.');await requestsRender('mine')};
26 function outboxStatus(s){return ({pending:'در انتظار ارسال',processing:'در حال ارسال',dispatched:'ارسال‌شده',failed:'ناموفق'})[s]||s}
27 const d3bOpen=window.requestD3bOpenTimeline;
28 window.requestD3bOpenTimeline=async function(id){let timeline=null;const rpc=sb.rpc.bind(sb);sb.rpc=async(name,args)=>{const r=await rpc(name,args);if(name==='request_workflow_timeline'&&!r.error)timeline=r.data;return r};try{await d3bOpen(id)}finally{sb.rpc=rpc}const out=await sb.rpc('request_outbox_status',{p_request_instance_id:id});const box=document.getElementById('request-d3b-timeline');if(!box)return;const steps=Array.isArray(timeline?.steps)?timeline.steps:[],items=out.error?[]:(out.data||[]);const ev=document.createElement('div');ev.id='request-d3c-runtime-evidence';ev.style.cssText='margin-top:12px;border-top:1px solid #edf2f7;padding-top:12px';ev.innerHTML='<strong>SLA و عملیات بین‌ماژولی</strong>'+steps.map(s=>'<div class="af-hint">'+e(s.title||s.key)+' · SLA: '+(s.slaHours?fa(s.slaHours)+' ساعت':'—')+' · سررسید: '+(s.dueAt?new Date(s.dueAt).toLocaleString('fa-IR'):'—')+(s.escalatedAt?' · تشدید سطح '+fa(s.escalationLevel):'')+'</div>').join('')+(items.length?'<div style="margin-top:8px">'+items.map(x=>'<div class="af-hint">'+e(x.targetModule)+' / '+e(x.actionKey)+' · '+e(outboxStatus(x.status))+' · تلاش '+fa(x.attempts)+'</div>').join('')+'</div>':'<div class="af-hint">پیام Outbox ثبت نشده است.</div>');box.appendChild(ev)};
29 const baseEdit=window.requestD2EditType,baseNew=window.requestD2NewType,baseRender=window.requestsRender;
29 -window.requestD2EditType=async function(id){await baseEdit(id);try{await loadConfig(id)}catch(err){console.error('D3c config load',err);O.sla=[];O.actions=[]}decorateEditor()};
30 -window.requestD2NewType=function(){baseNew();O.sla=[];O.actions=[];decorateEditor()};
30 +window.requestD2EditType=async function(id){await baseEdit(id);try{await loadConfig(id)}catch(err){console.error('D3c config load',err);O.slaByKey={};O.actions=[]}decorateEditor()};
31 +window.requestD2NewType=function(){baseNew();O.slaByKey={};O.actions=[];decorateEditor()};
32 window.requestsRender=async function(task='mine'){const r=await baseRender(task);if(task==='types')decorateEditor();if(task==='mine')await mountOps();return r};
32 -['requestD3bAddStep','requestD3bRemoveStep','requestD3bMoveStep'].forEach(name=>{const base=window[name];if(typeof base==='function')window[name]=function(...args){const r=base(...args);setTimeout(decorateEditor,0);return r}});
33 +['requestD3bAddStep','requestD3bRemoveStep','requestD3bMoveStep'].forEach(name=>{const base=window[name];if(typeof base==='function')window[name]=function(...args){captureSla();const r=base(...args);setTimeout(decorateEditor,0);return r}});const baseStepChange=window.requestD3bStepChange;if(typeof baseStepChange==='function')window.requestD3bStepChange=function(i,key,value){if(key!=='key')return baseStepChange(i,key,value);const card=document.querySelector('.request-d3b-step[data-index="'+i+'"]'),sla=card?.querySelector('[data-d3c-sla]'),oldKey=String(sla?.dataset.d3cStepKey||'').trim().toLowerCase();if(oldKey&&sla)O.slaByKey[oldKey]=Number(sla.value||0);const r=baseStepChange(i,key,value),newKey=String(value||'').trim().toLowerCase();if(oldKey&&newKey&&oldKey!==newKey){O.slaByKey[newKey]=O.slaByKey[oldKey];delete O.slaByKey[oldKey]}if(sla)sla.dataset.d3cStepKey=newKey;return r};
34 })();
scripts/request-workflow-d3c-check.mjs
+6
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2 import assert from 'node:assert/strict';
3 const js=fs.readFileSync('js/request-workflow-d3c.js','utf8');
4 const migration=fs.readFileSync('supabase/migrations/20261001235500_request_workflow_d3c_operations.sql','utf8');
5 +const wave4=fs.readFileSync('supabase/migrations/20261002072000_request_wave4_operational_integrity.sql','utf8');
6 const bootstrap=fs.readFileSync('js/bootstrap.js','utf8');
7 assert.match(js,/requestD3cCreateDelegation/,'D3c must expose explicit delegation management');
8 assert.match(js,/requestD3cEscalateOverdue/,'D3c must expose controlled SLA escalation');
@@ -13,5 +14,10 @@ assert.match(migration,/request_outbox/,'D3c must use a transactional outbox');
14 assert.match(migration,/request_escalate_overdue/,'D3c must expose server-authorized escalation');
15 assert.match(migration,/sla_hours/,'D3c must persist SLA configuration on runtime steps');
16 assert.match(migration,/request_step_decide/,'D3c must integrate delegation and outbox with the authoritative decision transaction');
17 +assert.match(js,/slaByKey/,'F-421 SLA editor state must bind to logical step keys');
18 +assert.match(js,/p_idempotency_key/,'F-422 client must send a delegation retry key');
19 +assert.match(wave4,/duplicate outbox target\/action intent/,'F-420 must reject duplicate outbox intent identity');
20 +assert.match(wave4,/overlapping active delegation/,'F-422 must define an overlap policy');
21 +assert.match(wave4,/idempotency_key/,'F-422 delegation create must be retry-safe');
22 assert.match(bootstrap,/request-workflow-d3b\.js[\s\S]*request-workflow-d3c\.js/,'D3c must load after D3b');
23 console.log('Request Workflow D3c invariants: OK');
scripts/request-workflow-d3c.spec.js
+13 -4
@@ -8,7 +8,7 @@ test('D3c adds SLA configuration and surfaces outbox/runtime operations',async({
8 currentUser={id:'11111111-1111-1111-1111-111111111111',email:'owner@example.test',organizationId:'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',organizationName:'D3c Org',isOrganizationOwner:true,commercialModules:['requests_workflow'],modulePermissions:[{module_key:'requests_workflow',capabilities:['read','configure','create','edit','approve']}],modules:['requests_workflow'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
9 const defs=[{id:'d1111111-1111-1111-1111-111111111111',organization_id:currentUser.organizationId,code:'OPS',title:'عملیات',category:'Workflow',revision:2,active:true}];
10 const versions=[{id:'v1111111-1111-1111-1111-111111111111',organization_id:currentUser.organizationId,request_type_id:defs[0].id,version_no:2,title:'عملیات',category:'Workflow',form_schema:{schemaVersion:1,fields:[{key:'f1',label:'مبلغ',type:'number',required:true}]},published_at:'2026-10-01T00:00:00Z'}];
11 - const workflows=[{id:'w1111111-1111-1111-1111-111111111111',organization_id:currentUser.organizationId,request_type_version_id:versions[0].id,workflow_schema:{schemaVersion:2,steps:[{key:'approve',title:'تأیید',mode:'sequential',requiredApprovals:1,requiredCapability:'approve',slaHours:4}],onApproved:[{targetModule:'commerce',actionKey:'create_purchase_draft',payload:{}}]},published_at:'2026-10-01T00:00:00Z'}];
11 + const workflows=[{id:'w1111111-1111-1111-1111-111111111111',organization_id:currentUser.organizationId,request_type_version_id:versions[0].id,workflow_schema:{schemaVersion:2,steps:[{key:'approve',title:'تأیید',mode:'sequential',requiredApprovals:1,requiredCapability:'approve',slaHours:4},{key:'finance',title:'مالی',mode:'sequential',requiredApprovals:1,requiredCapability:'approve',slaHours:12}],onApproved:[{targetModule:'commerce',actionKey:'create_purchase_draft',payload:{}}]},published_at:'2026-10-01T00:00:00Z'}];
12 const instances=[{id:'r1111111-1111-1111-1111-111111111111',organization_id:currentUser.organizationId,request_type_version_id:versions[0].id,requester_user_id:currentUser.id,status:'approved',revision:2,updated_at:'2026-10-01T00:00:00Z'}];
13 const members=[{id:'m1',organization_id:currentUser.organizationId,user_id:currentUser.id,status:'active',is_owner:true},{id:'m2',organization_id:currentUser.organizationId,user_id:'55555555-5555-5555-5555-555555555555',status:'active',is_owner:false}];
14 sb.from=(table)=>({select:()=>({eq:()=>({order:()=>Promise.resolve({data:table==='request_type_definitions'?defs:table==='request_type_versions'?versions:table==='request_workflow_versions'?workflows:table==='organization_members'?members:instances,error:null})})})});
@@ -16,13 +16,22 @@ test('D3c adds SLA configuration and surfaces outbox/runtime operations',async({
16 switchView('view-requests');
17 });
18 await page.evaluate(async()=>{await requestsRender('types');await requestD2EditType('d1111111-1111-1111-1111-111111111111')});
19 - await expect(page.locator('[data-d3c-sla]')).toHaveValue('4');
20 - await page.fill('[data-d3c-sla]','8');
19 + await expect(page.locator('[data-d3c-sla]').nth(0)).toHaveValue('4');
20 + await expect(page.locator('[data-d3c-sla]').nth(1)).toHaveValue('12');
21 + await page.fill('[data-d3c-sla][data-d3c-step-key="approve"]','8');
22 + await page.evaluate(()=>requestD3bMoveStep(0,1));
23 + await expect(page.locator('[data-d3c-sla][data-d3c-step-key="approve"]')).toHaveValue('8');
24 + await expect(page.locator('[data-d3c-sla][data-d3c-step-key="finance"]')).toHaveValue('12');
25 await page.evaluate(()=>requestD3bPublishCombined());
26 const call=await page.evaluate(()=>window.__d3c.rpc.find(x=>x.name==='request_publish_type_version'));
23 - expect(call.args.p_workflow_schema.steps[0].slaHours).toBe(8);
27 + expect(call.args.p_workflow_schema.steps.find(x=>x.key==='approve').slaHours).toBe(8);
28 + expect(call.args.p_workflow_schema.steps.find(x=>x.key==='finance').slaHours).toBe(12);
29 await page.evaluate(()=>requestsRender('mine'));
30 await expect(page.locator('#request-d3c-ops')).toBeVisible();
31 + await page.selectOption('#request-d3c-delegate-user','55555555-5555-5555-5555-555555555555');
32 + await page.evaluate(()=>requestD3cCreateDelegation());
33 + const delegationCall=await page.evaluate(()=>window.__d3c.rpc.find(x=>x.name==='request_create_delegation'));
34 + expect(delegationCall.args.p_idempotency_key).toMatch(/^delegation-/);
35 await page.evaluate(()=>requestD3bOpenTimeline('r1111111-1111-1111-1111-111111111111'));
36 await expect(page.locator('#request-d3c-runtime-evidence')).toContainText('SLA');
37 await expect(page.locator('#request-d3c-runtime-evidence')).toContainText('در انتظار ارسال');
supabase/migrations/20261002072000_request_wave4_operational_integrity.sql new
+63
@@ -0,0 +1,63 @@
1 +-- Wave 4 remediation: F-420 outbox intent uniqueness, F-422 delegation idempotency/overlap/revoke retry.
2 +-- F-421 is a client binding fix archived in js/request-workflow-d3c.js.
3 +alter table private.request_delegations add column if not exists idempotency_key text;
4 +alter table private.request_delegations drop constraint if exists request_delegations_idempotency_key_check;
5 +alter table private.request_delegations add constraint request_delegations_idempotency_key_check check(idempotency_key is null or char_length(idempotency_key) between 8 and 200);
6 +create unique index if not exists request_delegations_actor_idempotency_uidx on private.request_delegations(organization_id,from_user_id,idempotency_key) where idempotency_key is not null;
7 +
8 +create or replace function private.validate_request_workflow_schema(p_schema jsonb)
9 +returns void language plpgsql security invoker set search_path=''
10 +as $$
11 +declare v_version integer;v_steps jsonb;v_step jsonb;v_key text;v_mode text;v_required integer;v_cap text;v_seen text[]:=array[]::text[];v_sla integer;v_actions jsonb;v_action jsonb;v_target text;v_action_key text;v_action_identity text;v_action_seen text[]:=array[]::text[];
12 +begin
13 + if jsonb_typeof(coalesce(p_schema,'{}'::jsonb))<>'object' then raise exception 'workflow schema must be a JSON object';end if;
14 + begin v_version:=coalesce((p_schema->>'schemaVersion')::integer,1);exception when others then raise exception 'workflow schema version must be an integer';end;
15 + if v_version=1 then return;end if;if v_version<>2 then raise exception 'unsupported request workflow schema version';end if;
16 + v_steps:=p_schema->'steps';if jsonb_typeof(v_steps)<>'array' or jsonb_array_length(v_steps)<1 or jsonb_array_length(v_steps)>50 then raise exception 'D3 workflow requires between 1 and 50 steps';end if;
17 + for v_step in select value from jsonb_array_elements(v_steps) loop
18 + if jsonb_typeof(v_step)<>'object' then raise exception 'workflow step must be an object';end if;v_key:=lower(trim(coalesce(v_step->>'key','')));if v_key='' or v_key!~'^[a-z][a-z0-9_]{0,63}$' then raise exception 'workflow step key is invalid';end if;if v_key=any(v_seen) then raise exception 'workflow step keys must be unique';end if;v_seen:=array_append(v_seen,v_key);if nullif(trim(v_step->>'title'),'') is null then raise exception 'workflow step title is required';end if;
19 + v_mode:=lower(trim(coalesce(v_step->>'mode','sequential')));if v_mode not in('sequential','parallel') then raise exception 'workflow step mode must be sequential or parallel';end if;begin v_required:=coalesce((v_step->>'requiredApprovals')::integer,1);exception when others then raise exception 'requiredApprovals must be an integer';end;if v_required<1 or v_required>20 then raise exception 'requiredApprovals must be between 1 and 20';end if;if v_mode='sequential' and v_required<>1 then raise exception 'sequential step requires exactly one approval';end if;if v_mode='parallel' and v_required<2 then raise exception 'parallel step requires at least two approvals';end if;
20 + v_cap:=lower(trim(coalesce(v_step->>'requiredCapability','approve')));if v_cap not in('approve','edit','configure') then raise exception 'workflow step capability is not allowed';end if;if v_step?'condition' then perform private.validate_request_condition(v_step->'condition');end if;if v_step?'slaHours' then begin v_sla:=(v_step->>'slaHours')::integer;exception when others then raise exception 'slaHours must be an integer';end;if v_sla<1 or v_sla>8760 then raise exception 'slaHours must be between 1 and 8760';end if;end if;
21 + end loop;
22 + if p_schema?'onApproved' then
23 + v_actions:=p_schema->'onApproved';if jsonb_typeof(v_actions)<>'array' or jsonb_array_length(v_actions)>10 then raise exception 'onApproved must be an array with at most 10 actions';end if;
24 + for v_action in select value from jsonb_array_elements(v_actions) loop
25 + if jsonb_typeof(v_action)<>'object' then raise exception 'outbox action must be an object';end if;if exists(select 1 from jsonb_object_keys(v_action) as k(key) where key not in('targetModule','actionKey','payload')) then raise exception 'outbox action contains unsupported keys';end if;
26 + v_target:=lower(trim(coalesce(v_action->>'targetModule','')));if v_target not in('accounting','commerce','treasury','contracting','inventory','assets','hr_payroll','office_automation','crm','transport','manufacturing','maintenance','group_consolidation','analytics') then raise exception 'outbox targetModule is not allowed';end if;
27 + v_action_key:=lower(trim(coalesce(v_action->>'actionKey','')));if v_action_key!~'^[a-z][a-z0-9_]{1,63}$' then raise exception 'outbox actionKey is invalid';end if;v_action_identity:=v_target||':'||v_action_key;if v_action_identity=any(v_action_seen) then raise exception 'duplicate outbox target/action intent is not allowed';end if;v_action_seen:=array_append(v_action_seen,v_action_identity);
28 + if v_action?'payload' and jsonb_typeof(v_action->'payload')<>'object' then raise exception 'outbox payload must be an object';end if;if octet_length(coalesce((v_action->'payload')::text,'{}'))>8192 then raise exception 'outbox payload is too large';end if;
29 + end loop;
30 + end if;
31 +end $$;
32 +revoke all on function private.validate_request_workflow_schema(jsonb) from public,anon,authenticated;
33 +
34 +create or replace function private.request_create_delegation(p_organization_id uuid,p_to_user_id uuid,p_capability text,p_valid_from timestamptz,p_valid_to timestamptz,p_reason text,p_idempotency_key text)
35 +returns uuid language plpgsql security definer set search_path=''
36 +as $$
37 +declare v_id uuid;v_cap text;v_reason text;v_existing private.request_delegations%rowtype;
38 +begin
39 + if auth.uid() is null then raise exception 'authentication required' using errcode='28000';end if;if p_organization_id not in(select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501';end if;if not private.organization_has_module_entitlement(p_organization_id,'requests_workflow',true) then raise exception 'active requests_workflow entitlement required' using errcode='42501';end if;
40 + v_cap:=lower(trim(coalesce(p_capability,'')));v_reason:=nullif(trim(p_reason),'');if v_cap not in('approve','edit','configure') then raise exception 'delegation capability is not allowed';end if;if not private.has_org_capability(p_organization_id,'requests_workflow',v_cap) then raise exception 'cannot delegate a capability you do not hold' using errcode='42501';end if;if p_to_user_id=auth.uid() then raise exception 'cannot delegate to self';end if;if not exists(select 1 from public.organization_members m where m.organization_id=p_organization_id and m.user_id=p_to_user_id and m.status='active') then raise exception 'delegate target must be an active organization member';end if;if p_valid_from is null or p_valid_to is null or p_valid_to<=p_valid_from or p_valid_to>p_valid_from+interval '90 days' then raise exception 'delegation window must be positive and no longer than 90 days';end if;if char_length(trim(coalesce(p_idempotency_key,'')))<8 or char_length(trim(p_idempotency_key))>200 then raise exception 'delegation idempotency_key must be between 8 and 200 characters';end if;
41 + select * into v_existing from private.request_delegations d where d.organization_id=p_organization_id and d.from_user_id=auth.uid() and d.idempotency_key=trim(p_idempotency_key);
42 + if found then if v_existing.to_user_id<>p_to_user_id or v_existing.capability<>v_cap or v_existing.valid_from<>p_valid_from or v_existing.valid_to<>p_valid_to or coalesce(v_existing.reason,'')<>coalesce(v_reason,'') then raise exception 'delegation idempotency key is already bound to a different command' using errcode='23505';end if;return v_existing.id;end if;
43 + if exists(select 1 from private.request_delegations d where d.organization_id=p_organization_id and d.from_user_id=auth.uid() and d.capability=v_cap and d.revoked_at is null and tstzrange(d.valid_from,d.valid_to,'[)') && tstzrange(p_valid_from,p_valid_to,'[)')) then raise exception 'overlapping active delegation for this capability is not allowed' using errcode='23P01';end if;
44 + insert into private.request_delegations(organization_id,from_user_id,to_user_id,capability,valid_from,valid_to,reason,created_by,idempotency_key) values(p_organization_id,auth.uid(),p_to_user_id,v_cap,p_valid_from,p_valid_to,v_reason,auth.uid(),trim(p_idempotency_key)) returning id into v_id;
45 + insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,after_data) values(p_organization_id,auth.uid(),'request_delegation_created','request_delegation',v_id::text,jsonb_build_object('toUserId',p_to_user_id,'capability',v_cap,'validFrom',p_valid_from,'validTo',p_valid_to,'idempotencyKey',trim(p_idempotency_key)));return v_id;
46 +end $$;
47 +revoke all on function private.request_create_delegation(uuid,uuid,text,timestamptz,timestamptz,text,text) from public,anon;grant execute on function private.request_create_delegation(uuid,uuid,text,timestamptz,timestamptz,text,text) to authenticated;
48 +create or replace function public.request_create_delegation(p_organization_id uuid,p_to_user_id uuid,p_capability text,p_valid_from timestamptz,p_valid_to timestamptz,p_reason text,p_idempotency_key text)
49 +returns uuid language sql security invoker set search_path='' as $$ select private.request_create_delegation(p_organization_id,p_to_user_id,p_capability,p_valid_from,p_valid_to,p_reason,p_idempotency_key) $$;
50 +revoke all on function public.request_create_delegation(uuid,uuid,text,timestamptz,timestamptz,text,text) from public,anon;grant execute on function public.request_create_delegation(uuid,uuid,text,timestamptz,timestamptz,text,text) to authenticated;
51 +revoke execute on function public.request_create_delegation(uuid,uuid,text,timestamptz,timestamptz,text) from authenticated;
52 +revoke execute on function private.request_create_delegation(uuid,uuid,text,timestamptz,timestamptz,text) from authenticated;
53 +
54 +create or replace function private.request_revoke_delegation(p_organization_id uuid,p_delegation_id uuid)
55 +returns boolean language plpgsql security definer set search_path=''
56 +as $$
57 +declare v_from uuid;v_changed uuid;
58 +begin
59 + if auth.uid() is null then raise exception 'authentication required' using errcode='28000';end if;if p_organization_id not in(select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501';end if;select from_user_id into v_from from private.request_delegations where id=p_delegation_id and organization_id=p_organization_id for update;if not found then raise exception 'delegation not found';end if;if v_from<>auth.uid() and not private.has_org_capability(p_organization_id,'requests_workflow','configure') then raise exception 'delegation revoke denied' using errcode='42501';end if;
60 + update private.request_delegations set revoked_at=now() where id=p_delegation_id and organization_id=p_organization_id and revoked_at is null returning id into v_changed;
61 + if v_changed is not null then insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id) values(p_organization_id,auth.uid(),'request_delegation_revoked','request_delegation',p_delegation_id::text);end if;return true;
62 +end $$;
63 +revoke all on function private.request_revoke_delegation(uuid,uuid) from public,anon;grant execute on function private.request_revoke_delegation(uuid,uuid) to authenticated;
supabase/tests/request_d4a_work_queue.sql
+1 -1
@@ -38,7 +38,7 @@ insert into d4a_ids values('delegated',public.request_create_instance(
38 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from d4a_ids where k='type'),'{"subject":"delegated"}'::jsonb,'d4a-create-delegated-01'
39 ));
40 insert into d4a_ids values('delegation',public.request_create_delegation(
41 - 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','55555555-5555-5555-5555-555555555555','approve',now(),now()+interval '1 day','coverage'
41 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','55555555-5555-5555-5555-555555555555','approve',now(),now()+interval '1 day','coverage','d4a-coverage-delegation-0001'
42 ));
43
44 select set_config('request.jwt.claim.sub','55555555-5555-5555-5555-555555555555',false);
supabase/tests/request_wave4_operational_integrity.sql new
+42
@@ -0,0 +1,42 @@
1 +\set ON_ERROR_STOP on
2 +insert into public.profiles(id) values ('88888888-8888-8888-8888-888888888888'),('99999999-9999-9999-9999-999999999999') on conflict do nothing;
3 +insert into public.organization_members(organization_id,user_id,status,is_owner,position_title) values
4 + ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','88888888-8888-8888-8888-888888888888','active',false,'Wave4 delegate A'),
5 + ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','99999999-9999-9999-9999-999999999999','active',false,'Wave4 delegate B')
6 +on conflict(organization_id,user_id) do update set status='active';
7 +set role authenticated;
8 +select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
9 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
10 +select set_config('request.jwt.claim.member_active','true',false);
11 +select set_config('request.jwt.claim.entitled','true',false);
12 +select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
13 +do $$ begin begin
14 + perform * from public.request_publish_type_version('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','W4_DUP_OUTBOX','duplicate outbox',null,
15 + '{"schemaVersion":1,"fields":[{"key":"subject","label":"Subject","type":"text","required":true}]}'::jsonb,
16 + '{"schemaVersion":2,"steps":[{"key":"approve","title":"Approve","mode":"sequential","requiredApprovals":1,"requiredCapability":"approve"}],"onApproved":[{"targetModule":"commerce","actionKey":"create_purchase_draft","payload":{"slot":1}},{"targetModule":"COMMERCE","actionKey":"CREATE_PURCHASE_DRAFT","payload":{"slot":2}}]}'::jsonb,0);
17 + raise exception 'F-420 duplicate outbox identity unexpectedly published';
18 +exception when others then if position('duplicate outbox target/action intent' in sqlerrm)=0 then raise;end if;end;end $$;
19 +create temporary table wave4_ids(k text primary key,v uuid);
20 +insert into wave4_ids values('delegation',public.request_create_delegation(
21 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','88888888-8888-8888-8888-888888888888','approve',
22 + '2026-10-03T08:00:00Z','2026-10-03T18:00:00Z','wave4 test','wave4-delegation-0001'));
23 +do $$ declare a uuid;b uuid;begin
24 + a=(select v from wave4_ids where k='delegation');
25 + b=public.request_create_delegation('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','88888888-8888-8888-8888-888888888888','approve','2026-10-03T08:00:00Z','2026-10-03T18:00:00Z','wave4 test','wave4-delegation-0001');
26 + if a<>b then raise exception 'F-422 idempotent create returned a different delegation';end if;
27 + if (select count(*) from public.organization_audit where action='request_delegation_created' and entity_id=a::text)<>1 then raise exception 'F-422 idempotent create duplicated audit evidence';end if;
28 +end $$;
29 +do $$ begin begin
30 + perform public.request_create_delegation('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','99999999-9999-9999-9999-999999999999','approve','2026-10-03T08:00:00Z','2026-10-03T18:00:00Z','different command','wave4-delegation-0001');
31 + raise exception 'F-422 idempotency key accepted a different command';
32 +exception when unique_violation then null;end;end $$;
33 +do $$ begin begin
34 + perform public.request_create_delegation('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','99999999-9999-9999-9999-999999999999','approve','2026-10-03T12:00:00Z','2026-10-03T20:00:00Z','overlap','wave4-delegation-0002');
35 + raise exception 'F-422 overlapping delegation unexpectedly succeeded';
36 +exception when exclusion_violation then null;end;end $$;
37 +select public.request_revoke_delegation('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from wave4_ids where k='delegation'));
38 +select public.request_revoke_delegation('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from wave4_ids where k='delegation'));
39 +do $$ declare d uuid;begin d=(select v from wave4_ids where k='delegation');
40 + if (select count(*) from public.organization_audit where action='request_delegation_revoked' and entity_id=d::text)<>1 then raise exception 'F-422 revoke retry duplicated semantic audit evidence';end if;
41 +end $$;
42 +reset role;