سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 17:00 UTC
feat: add D3b visual workflow conditions and timeline
davoodmehraban89 committed
Oct 1, 2026 at 23:04 UTC
175c00529e4005c15cea352f7c5e9fb11867e96e
3 files changed
+163
-1
js/bootstrap.js
+1
-1
@@ -1,2 +1,2 @@
1
function finoraLoadScript(src){return new Promise((resolve,reject)=>{const s=document.createElement('script');s.src=src;s.onload=resolve;s.onerror=()=>reject(new Error('Failed to load '+src));document.head.appendChild(s)})}
2
-window.addEventListener('DOMContentLoaded',async()=>{try{await finoraLoadScript('js/organization-rbac.js?v=20260930-slice-b-v1');await finoraLoadScript('js/organization-invitations.js?v=20260930-eli3-v1');await finoraLoadScript('js/organization-enterprise-ux.js?v=20260930-eli4-v1');await finoraLoadScript('js/platform-modules.js?v=20261001-platform-c6-v1');await finoraLoadScript('js/office-automation.js?v=20260930-c4-v1');await finoraLoadScript('js/request-workflow-d2.js?v=20261001-d2-v1');await finoraLoadScript('js/office-rbac.js?v=20260930-slice-b-v1');await finoraLoadScript('js/office-mature.js?v=20261001-c7-v2');await finoraLoadScript('js/office-workflow.js?v=20261001-c8-task3-v3');await finoraLoadScript('js/organization-shell.js?v=20260930-eli4-v1');await finoraLoadScript('js/taxpayer-print.js?v=20261001-official-v1')}catch(e){console.error('Finora platform extension load failed',e)}if(!currentUser)initAuthSystem();});
2
+window.addEventListener('DOMContentLoaded',async()=>{try{await finoraLoadScript('js/organization-rbac.js?v=20260930-slice-b-v1');await finoraLoadScript('js/organization-invitations.js?v=20260930-eli3-v1');await finoraLoadScript('js/organization-enterprise-ux.js?v=20260930-eli4-v1');await finoraLoadScript('js/platform-modules.js?v=20261001-platform-c6-v1');await finoraLoadScript('js/office-automation.js?v=20260930-c4-v1');await finoraLoadScript('js/request-workflow-d2.js?v=20261001-d2-v1');await finoraLoadScript('js/request-workflow-d3b.js?v=20261001-d3b-v1');await finoraLoadScript('js/office-rbac.js?v=20260930-slice-b-v1');await finoraLoadScript('js/office-mature.js?v=20261001-c7-v2');await finoraLoadScript('js/office-workflow.js?v=20261001-c8-task3-v3');await finoraLoadScript('js/organization-shell.js?v=20260930-eli4-v1');await finoraLoadScript('js/taxpayer-print.js?v=20261001-official-v1')}catch(e){console.error('Finora platform extension load failed',e)}if(!currentUser)initAuthSystem();});
js/request-workflow-d3b.js
new
+35
@@ -0,0 +1,35 @@
1
+/* Finora Requests D3b: visual workflow editor, bounded conditions and read-only runtime timeline. */
2
+(function(){
3
+const D={selectedDefinitionId:'',steps:[],instances:[],loadingWorkflow:false};
4
+const esc3=v=>typeof esc==='function'?esc(v):String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
5
+const orgId=()=>currentUser?.organizationId||'';
6
+const canConfigure=()=>!!currentUser&&(currentUser.isOrganizationOwner||typeof finoraCanConfigureModule==='function'&&finoraCanConfigureModule('requests_workflow'));
7
+const faNum=n=>Number(n||0).toLocaleString('fa-IR');
8
+const defaultStep=()=>({key:'approval',title:'تأیید',mode:'sequential',requiredApprovals:1,requiredCapability:'approve'});
9
+function normalizeStep(s,i){const x={key:String(s?.key||('step_'+(i+1))),title:String(s?.title||('مرحله '+(i+1))),mode:s?.mode==='parallel'?'parallel':'sequential',requiredApprovals:Number(s?.requiredApprovals||1),requiredCapability:['approve','edit','configure'].includes(s?.requiredCapability)?s.requiredCapability:'approve'};if(s?.condition&&typeof s.condition==='object')x.condition={field:String(s.condition.field||''),op:String(s.condition.op||'eq'),...(['exists','not_exists'].includes(String(s.condition.op||''))?{}:{value:s.condition.value})};return x}
10
+async function rows(table,columns,order){const q=sb.from(table).select(columns).eq('organization_id',orgId());const r=order?await q.order(order,{ascending:false}):await q;if(r.error)throw r.error;return r.data||[]}
11
+async function loadWorkflow(definitionId){
12
+ D.loadingWorkflow=true;
13
+ try{const versions=await rows('request_type_versions','id,request_type_id,version_no,form_schema,published_at','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){D.steps=[defaultStep()];return}const workflows=await rows('request_workflow_versions','id,request_type_version_id,workflow_schema,published_at','published_at');const wf=workflows.find(w=>w.request_type_version_id===latest.id);const schema=wf?.workflow_schema||{};D.steps=Number(schema.schemaVersion)===2&&Array.isArray(schema.steps)&&schema.steps.length?schema.steps.map(normalizeStep):[defaultStep()]}finally{D.loadingWorkflow=false}
14
+}
15
+function conditionValue(v){const s=String(v??'').trim();if(/^-?(?:\d+\.?\d*|\.\d+)$/.test(s))return Number(s);if(s==='true')return true;if(s==='false')return false;return s}
16
+function buildSchema(){return {schemaVersion:2,steps:D.steps.map((s,i)=>{const x=normalizeStep(s,i),field=String(x.condition?.field||'').trim(),op=String(x.condition?.op||'eq');const out={key:String(x.key||'').trim().toLowerCase(),title:String(x.title||'').trim(),mode:x.mode,requiredApprovals:x.mode==='parallel'?Math.max(2,Number(x.requiredApprovals||2)):1,requiredCapability:x.requiredCapability};if(field)out.condition={field,op,...(['exists','not_exists'].includes(op)?{}:{value:conditionValue(x.condition?.value)})};return out})}}
17
+function markDirty(){if(typeof requestD2MarkDirty==='function')requestD2MarkDirty()}
18
+function stepCard(s,i){const c=s.condition||{},mode=s.mode==='parallel'?'parallel':'sequential';return '<div class="request-d3b-step" data-index="'+i+'" style="border:1px solid #dbe5ef;border-radius:12px;padding:14px;background:#fbfdff;min-width:250px;flex:1"><div style="display:flex;justify-content:space-between;align-items:center;gap:8px"><strong>مرحله '+faNum(i+1)+' →</strong><div style="display:flex;gap:6px"><button class="btn btn-secondary btn-inline" style="min-height:32px;padding:4px 9px" onclick="requestD3bMoveStep('+i+',-1)">↑</button><button class="btn btn-secondary btn-inline" style="min-height:32px;padding:4px 9px" onclick="requestD3bMoveStep('+i+',1)">↓</button><button class="btn btn-danger btn-inline" style="min-height:32px;padding:4px 9px" onclick="requestD3bRemoveStep('+i+')">حذف</button></div></div><div class="form-row" style="margin-top:10px"><div class="form-group"><label>کلید فنی</label><input data-d3b="key" class="form-control" value="'+esc3(s.key)+'" oninput="requestD3bStepChange('+i+',\'key\',this.value)"></div><div class="form-group"><label>عنوان مرحله</label><input data-d3b="title" class="form-control" value="'+esc3(s.title)+'" oninput="requestD3bStepChange('+i+',\'title\',this.value)"></div><div class="form-group"><label>نوع تأیید</label><select data-d3b="mode" class="form-control" onchange="requestD3bStepChange('+i+',\'mode\',this.value)"><option value="sequential" '+(mode==='sequential'?'selected':'')+'>ترتیبی</option><option value="parallel" '+(mode==='parallel'?'selected':'')+'>موازی / حدنصاب</option></select></div><div class="form-group"><label>حدنصاب تأیید</label><input data-d3b="approvals" type="number" min="1" max="20" class="form-control" value="'+Number(s.requiredApprovals||1)+'" '+(mode==='sequential'?'disabled':'')+' oninput="requestD3bStepChange('+i+',\'requiredApprovals\',this.value)"></div><div class="form-group"><label>مجوز لازم</label><select data-d3b="capability" class="form-control" onchange="requestD3bStepChange('+i+',\'requiredCapability\',this.value)">'+[['approve','تأیید'],['edit','ویرایش'],['configure','پیکربندی']].map(x=>'<option value="'+x[0]+'" '+(s.requiredCapability===x[0]?'selected':'')+'>'+x[1]+'</option>').join('')+'</select></div></div><div style="border-top:1px dashed #dbe5ef;padding-top:10px"><strong style="font-size:12px">شرط اجرای مرحله (اختیاری و امن)</strong><div class="form-row" style="margin-top:8px"><div class="form-group"><label>کلید فیلد</label><input data-d3b="condition-field" class="form-control" value="'+esc3(c.field||'')+'" placeholder="مثلاً f1" oninput="requestD3bConditionChange('+i+',\'field\',this.value)"></div><div class="form-group"><label>عملگر</label><select data-d3b="condition-op" class="form-control" onchange="requestD3bConditionChange('+i+',\'op\',this.value)">'+[['eq','برابر'],['neq','نابرابر'],['gt','بزرگتر'],['gte','بزرگتر یا برابر'],['lt','کوچکتر'],['lte','کوچکتر یا برابر'],['exists','وجود دارد'],['not_exists','وجود ندارد']].map(x=>'<option value="'+x[0]+'" '+((c.op||'eq')===x[0]?'selected':'')+'>'+x[1]+'</option>').join('')+'</select></div><div class="form-group"><label>مقدار مقایسه</label><input data-d3b="condition-value" class="form-control" value="'+esc3(c.value??'')+'" placeholder="1000" oninput="requestD3bConditionChange('+i+',\'value\',this.value)"></div></div><small style="color:var(--text-muted)">شرط فقط روی داده همان درخواست ارزیابی میشود؛ اجرای SQL یا JavaScript مجاز نیست.</small></div></div>'}
19
+function renderSteps(){const box=document.getElementById('request-d3b-steps');if(box)box.innerHTML=D.steps.map(stepCard).join('')||'<div class="af-empty">حداقل یک مرحله لازم است.</div>'}
20
+function mountEditor(){if(!canConfigure())return;const root=document.getElementById('view-requests'),publish=document.getElementById('request-d2-publish');if(!root||!publish)return;let box=document.getElementById('request-d3b-editor');if(!box){box=document.createElement('div');box.id='request-d3b-editor';box.className='card';publish.closest('.card')?.after(box)}box.innerHTML='<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:10px;flex-wrap:wrap"><div><h3 style="font-size:16px">طراح بصری گردشکار</h3><p class="af-hint">مراحل بهترتیب اجرا میشوند؛ مرحله موازی با رسیدن به حدنصاب تأیید تکمیل میشود.</p></div><button class="btn btn-secondary btn-inline" onclick="requestD3bAddStep()">+ افزودن مرحله</button></div><div id="request-d3b-steps" style="display:flex;gap:10px;align-items:stretch;overflow-x:auto;padding:10px 0"></div>';publish.setAttribute('onclick','requestD3bPublishCombined()');renderSteps()}
21
+window.requestD3bAddStep=function(){D.steps.push({key:'step_'+(D.steps.length+1),title:'مرحله '+(D.steps.length+1),mode:'sequential',requiredApprovals:1,requiredCapability:'approve'});markDirty();renderSteps()};
22
+window.requestD3bRemoveStep=function(i){if(D.steps.length<=1)return alert('گردشکار باید حداقل یک مرحله داشته باشد.');D.steps.splice(i,1);markDirty();renderSteps()};
23
+window.requestD3bMoveStep=function(i,delta){const j=i+delta;if(j<0||j>=D.steps.length)return;[D.steps[i],D.steps[j]]=[D.steps[j],D.steps[i]];markDirty();renderSteps()};
24
+window.requestD3bStepChange=function(i,key,value){const s=D.steps[i];if(!s)return;if(key==='requiredApprovals')s[key]=Math.max(1,Math.min(20,Number(value||1)));else{s[key]=value;if(key==='mode'&&value==='sequential')s.requiredApprovals=1}markDirty();if(key==='mode')renderSteps()};
25
+window.requestD3bConditionChange=function(i,key,value){const s=D.steps[i];if(!s)return;s.condition=s.condition||{field:'',op:'eq',value:''};s.condition[key]=value;markDirty()};
26
+const basePublish=window.requestD2PublishType;
27
+window.requestD3bPublishCombined=async function(){if(!D.steps.length)return alert('حداقل یک مرحله گردشکار تعریف کنید.');const schema=buildSchema(),rpc=sb.rpc.bind(sb);sb.rpc=async(name,args)=>name==='request_publish_type_version'?rpc(name,{...args,p_workflow_schema:schema}):rpc(name,args);try{return await basePublish()}finally{sb.rpc=rpc}}
28
+function statusLabel(s){return ({pending:'در انتظار',active:'فعال',completed:'تکمیلشده',rejected:'ردشده',skipped:'رد شده توسط شرط'})[s]||s||'—'}
29
+async function mountRuntime(){const root=document.getElementById('view-requests');if(!root)return;try{D.instances=await rows('request_instances','id,request_type_version_id,status,revision,created_at,updated_at','updated_at')}catch(e){console.error('D3b runtime load',e);D.instances=[]}let box=document.getElementById('request-d3b-runtime');if(!box){box=document.createElement('div');box.id='request-d3b-runtime';box.className='card';root.appendChild(box)}box.innerHTML='<h3 style="font-size:15px;margin-bottom:10px">گردشکار و تاریخچه اجرا</h3><div class="table-responsive"><table><thead><tr><th>درخواست</th><th>وضعیت</th><th>Revision</th><th></th></tr></thead><tbody>'+((D.instances||[]).map(r=>'<tr><td><code>'+esc3(String(r.id).slice(0,8))+'</code></td><td>'+esc3(r.status)+'</td><td>'+faNum(r.revision)+'</td><td><button class="btn btn-secondary btn-inline" onclick="requestD3bOpenTimeline(\''+esc3(r.id)+'\')">مشاهده مسیر</button></td></tr>').join('')||'<tr><td colspan="4" class="af-empty">درخواستی برای نمایش مسیر وجود ندارد.</td></tr>')+'</tbody></table></div><div id="request-d3b-timeline" style="margin-top:12px"></div>'}
30
+window.requestD3bOpenTimeline=async function(id){const box=document.getElementById('request-d3b-timeline');if(!box)return;box.innerHTML='<div class="af-empty">در حال دریافت تاریخچه امن…</div>';const {data,error}=await sb.rpc('request_workflow_timeline',{p_request_instance_id:id});if(error){box.innerHTML='<div class="af-empty" style="color:#b91c1c">'+esc3(error.message||error)+'</div>';return}const t=data||{},steps=Array.isArray(t.steps)?t.steps:[];box.innerHTML='<div style="display:flex;gap:10px;overflow-x:auto;padding:8px 0">'+steps.map((s,i)=>'<div style="min-width:210px;border:1px solid #dbe5ef;border-radius:12px;padding:12px;background:'+(s.state==='active'?'#eff6ff':'#fff')+'"><small>مرحله '+faNum(i+1)+'</small><strong style="display:block;margin:4px 0">'+esc3(s.title||s.key)+'</strong><span class="badge '+(s.state==='completed'?'badge-success':s.state==='active'?'badge-info':s.state==='rejected'?'badge-danger':'badge-warning')+'">'+statusLabel(s.state)+'</span><div class="af-hint">تأییدها: '+faNum(s.approvalsReceived)+' از '+faNum(s.requiredApprovals)+'</div>'+(s.conditionMatched===false?'<div class="af-hint" style="color:#92400e">شرط مرحله برقرار نشد.</div>':'')+'</div>').join('')+'</div>'+(Array.isArray(t.events)&&t.events.length?'<div style="margin-top:12px"><strong>رویدادهای ثبتشده</strong>'+t.events.map(e=>'<div class="af-hint">'+esc3(e.action)+' · '+esc3(e.toStatus||'')+' · rev '+faNum(e.revision)+'</div>').join('')+'</div>':'')};
31
+const baseRender=window.requestsRender,baseEdit=window.requestD2EditType,baseNew=window.requestD2NewType;
32
+window.requestsRender=async function(task='mine'){const r=await baseRender(task);if(task==='types'){if(!D.selectedDefinitionId&&D.steps.length===0)D.steps=[defaultStep()];mountEditor()}else if(task==='mine')await mountRuntime();return r};
33
+window.requestD2EditType=async function(id){baseEdit(id);D.selectedDefinitionId=id;try{await loadWorkflow(id)}catch(e){console.error('D3b workflow load',e);D.steps=[defaultStep()]}mountEditor()};
34
+window.requestD2NewType=function(){baseNew();D.selectedDefinitionId='';D.steps=[defaultStep()];mountEditor()};
35
+})();
supabase/migrations/20261001233000_request_workflow_d3b_conditions_timeline.sql
new
+127
@@ -0,0 +1,127 @@
1
+-- Slice D3b: bounded condition DSL, skipped-step evidence and authorized read-only runtime timeline.
2
+
3
+alter table private.request_step_instances add column if not exists condition_json jsonb;
4
+alter table private.request_step_instances add column if not exists condition_matched boolean not null default true;
5
+alter table private.request_step_instances drop constraint if exists request_step_instances_state_check;
6
+alter table private.request_step_instances add constraint request_step_instances_state_check check(state in ('pending','active','completed','rejected','skipped'));
7
+
8
+create or replace function private.validate_request_condition(p_condition jsonb)
9
+returns void language plpgsql security invoker set search_path=''
10
+as $$
11
+declare v_field text; v_op text; v_type text;
12
+begin
13
+ if p_condition is null or p_condition='null'::jsonb then return; end if;
14
+ if jsonb_typeof(p_condition)<>'object' then raise exception 'condition must be an object'; end if;
15
+ if exists(select 1 from jsonb_object_keys(p_condition) as k(key) where key not in ('field','op','value')) then raise exception 'condition contains unsupported keys'; end if;
16
+ v_field:=lower(trim(coalesce(p_condition->>'field','')));
17
+ if v_field='' or v_field!~'^[a-z][a-z0-9_]{0,63}$' then raise exception 'condition field is invalid'; end if;
18
+ v_op:=lower(trim(coalesce(p_condition->>'op','')));
19
+ if v_op not in ('eq','neq','gt','gte','lt','lte','exists','not_exists') then raise exception 'condition operator is not allowed'; end if;
20
+ if v_op not in ('exists','not_exists') and not (p_condition ? 'value') then raise exception 'condition value is required'; end if;
21
+ if v_op not in ('exists','not_exists') then
22
+ v_type:=jsonb_typeof(p_condition->'value');
23
+ if v_type not in ('string','number','boolean','null') then raise exception 'condition value must be scalar'; end if;
24
+ end if;
25
+end $$;
26
+revoke all on function private.validate_request_condition(jsonb) from public,anon,authenticated;
27
+
28
+create or replace function private.evaluate_request_condition(p_condition jsonb,p_values jsonb)
29
+returns boolean language plpgsql immutable security invoker set search_path=''
30
+as $$
31
+declare v_field text; v_op text; v_actual jsonb; v_expected jsonb; a text; b text;
32
+begin
33
+ if p_condition is null or p_condition='null'::jsonb then return true; end if;
34
+ perform private.validate_request_condition(p_condition);
35
+ v_field:=lower(trim(p_condition->>'field'));v_op:=lower(trim(p_condition->>'op'));
36
+ if v_op='exists' then return coalesce(p_values,'{}'::jsonb) ? v_field and coalesce(p_values->v_field,'null'::jsonb)<>'null'::jsonb; end if;
37
+ if v_op='not_exists' then return not (coalesce(p_values,'{}'::jsonb) ? v_field) or coalesce(p_values->v_field,'null'::jsonb)='null'::jsonb; end if;
38
+ if not (coalesce(p_values,'{}'::jsonb) ? v_field) then return false; end if;
39
+ v_actual:=p_values->v_field;v_expected:=p_condition->'value';a:=v_actual#>>'{}';b:=v_expected#>>'{}';
40
+ if v_op='eq' then return a is not distinct from b; end if;
41
+ if v_op='neq' then return a is distinct from b; end if;
42
+ if a is null or b is null or a!~'^[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$' or b!~'^[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$' then return false; end if;
43
+ if v_op='gt' then return a::numeric>b::numeric; elsif v_op='gte' then return a::numeric>=b::numeric; elsif v_op='lt' then return a::numeric<b::numeric; elsif v_op='lte' then return a::numeric<=b::numeric; end if;
44
+ return false;
45
+end $$;
46
+revoke all on function private.evaluate_request_condition(jsonb,jsonb) from public,anon,authenticated;
47
+
48
+create or replace function private.validate_request_workflow_schema(p_schema jsonb)
49
+returns void language plpgsql security invoker set search_path=''
50
+as $$
51
+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[];
52
+begin
53
+ if jsonb_typeof(coalesce(p_schema,'{}'::jsonb))<>'object' then raise exception 'workflow schema must be a JSON object'; end if;
54
+ begin v_version:=coalesce((p_schema->>'schemaVersion')::integer,1); exception when others then raise exception 'workflow schema version must be an integer'; end;
55
+ if v_version=1 then return; end if;
56
+ if v_version<>2 then raise exception 'unsupported request workflow schema version'; end if;
57
+ v_steps:=p_schema->'steps';
58
+ 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;
59
+ for v_step in select value from jsonb_array_elements(v_steps) loop
60
+ if jsonb_typeof(v_step)<>'object' then raise exception 'workflow step must be an object'; end if;
61
+ 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);
62
+ if nullif(trim(v_step->>'title'),'') is null then raise exception 'workflow step title is required'; end if;
63
+ 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;
64
+ 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;
65
+ 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;
66
+ if v_step ? 'condition' then perform private.validate_request_condition(v_step->'condition'); end if;
67
+ end loop;
68
+end $$;
69
+revoke all on function private.validate_request_workflow_schema(jsonb) from public,anon,authenticated;
70
+
71
+create or replace function private.request_create_instance(p_organization_id uuid,p_request_type_version_id uuid,p_values jsonb,p_idempotency_key text)
72
+returns uuid language plpgsql security definer set search_path=''
73
+as $$
74
+declare v_existing uuid;v_workflow uuid;v_id uuid;v_schema jsonb;v_step jsonb;v_ord bigint;v_match boolean;v_activated integer;
75
+begin
76
+ if auth.uid() is null then raise exception 'authentication required' using errcode='28000'; end if;
77
+ if p_organization_id not in (select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501'; end if;
78
+ 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;
79
+ if not private.has_org_capability(p_organization_id,'requests_workflow','create') then raise exception 'requests_workflow create capability required' using errcode='42501'; end if;
80
+ if char_length(trim(coalesce(p_idempotency_key,'')))<8 then raise exception 'idempotency_key is required'; end if;
81
+ select id into v_existing from public.request_instances where organization_id=p_organization_id and idempotency_key=p_idempotency_key;if found then return v_existing;end if;
82
+ select w.id,w.workflow_schema into v_workflow,v_schema from public.request_workflow_versions w join public.request_type_versions v on v.id=w.request_type_version_id where w.organization_id=p_organization_id and v.organization_id=p_organization_id and v.id=p_request_type_version_id;if v_workflow is null then raise exception 'published request type version not found';end if;
83
+ perform private.validate_request_workflow_schema(coalesce(v_schema,'{}'::jsonb));
84
+ insert into public.request_instances(organization_id,request_type_version_id,workflow_version_id,requester_user_id,values_json,status,revision,idempotency_key) values(p_organization_id,p_request_type_version_id,v_workflow,auth.uid(),coalesce(p_values,'{}'::jsonb),'submitted',1,p_idempotency_key) returning id into v_id;
85
+ insert into public.request_instance_events(organization_id,request_instance_id,actor_user_id,action,from_status,to_status,revision,idempotency_key) values(p_organization_id,v_id,auth.uid(),'create',null,'submitted',1,'create:'||p_idempotency_key);
86
+ if coalesce((v_schema->>'schemaVersion')::integer,1)=2 then
87
+ for v_step,v_ord in select value,ordinality from jsonb_array_elements(v_schema->'steps') with ordinality loop
88
+ v_match:=private.evaluate_request_condition(v_step->'condition',coalesce(p_values,'{}'::jsonb));
89
+ insert into private.request_step_instances(organization_id,request_instance_id,workflow_version_id,step_key,step_title,step_index,mode,required_approvals,required_capability,state,activated_at,condition_json,condition_matched)
90
+ values(p_organization_id,v_id,v_workflow,lower(trim(v_step->>'key')),trim(v_step->>'title'),v_ord::integer,lower(trim(coalesce(v_step->>'mode','sequential'))),coalesce((v_step->>'requiredApprovals')::integer,1),lower(trim(coalesce(v_step->>'requiredCapability','approve'))),case when v_match then 'pending' else 'skipped' end,null,v_step->'condition',v_match);
91
+ end loop;
92
+ with first_pending as (select id from private.request_step_instances where request_instance_id=v_id and state='pending' order by step_index limit 1) update private.request_step_instances s set state='active',activated_at=now() from first_pending f where s.id=f.id;
93
+ get diagnostics v_activated=row_count;
94
+ if v_activated=0 then
95
+ update public.request_instances set status='approved',revision=2,updated_at=now() where id=v_id;
96
+ insert into public.request_instance_events(organization_id,request_instance_id,actor_user_id,action,from_status,to_status,revision,idempotency_key) values(p_organization_id,v_id,auth.uid(),'workflow_auto_complete','submitted','approved',2,'auto:'||p_idempotency_key);
97
+ end if;
98
+ end if;
99
+ return v_id;
100
+exception when unique_violation then
101
+ select id into v_existing from public.request_instances where organization_id=p_organization_id and idempotency_key=p_idempotency_key;if v_existing is not null then return v_existing;end if;raise;
102
+end $$;
103
+revoke all on function private.request_create_instance(uuid,uuid,jsonb,text) from public,anon;
104
+grant execute on function private.request_create_instance(uuid,uuid,jsonb,text) to authenticated;
105
+
106
+create or replace function private.request_workflow_timeline(p_request_instance_id uuid)
107
+returns jsonb language plpgsql security definer set search_path=''
108
+as $$
109
+declare v_row public.request_instances%rowtype;v_steps jsonb;v_events jsonb;
110
+begin
111
+ if auth.uid() is null then raise exception 'authentication required' using errcode='28000'; end if;
112
+ select * into v_row from public.request_instances r where r.id=p_request_instance_id;if not found then raise exception 'request instance not found';end if;
113
+ if v_row.organization_id not in (select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501'; end if;
114
+ if not private.organization_has_module_entitlement(v_row.organization_id,'requests_workflow',false) then raise exception 'requests_workflow entitlement required' using errcode='42501'; end if;
115
+ if v_row.requester_user_id<>auth.uid() and not private.has_org_capability(v_row.organization_id,'requests_workflow','approve') and not private.has_org_capability(v_row.organization_id,'requests_workflow','edit') then raise exception 'request timeline access denied' using errcode='42501'; end if;
116
+ select coalesce(jsonb_agg(jsonb_build_object('key',s.step_key,'title',s.step_title,'index',s.step_index,'mode',s.mode,'state',s.state,'requiredApprovals',s.required_approvals,'approvalsReceived',(select count(*) from private.request_step_votes v where v.step_instance_id=s.id and v.decision='approve'),'requiredCapability',s.required_capability,'condition',s.condition_json,'conditionMatched',s.condition_matched,'activatedAt',s.activated_at,'completedAt',s.completed_at) order by s.step_index),'[]'::jsonb) into v_steps from private.request_step_instances s where s.request_instance_id=v_row.id;
117
+ select coalesce(jsonb_agg(jsonb_build_object('action',e.action,'fromStatus',e.from_status,'toStatus',e.to_status,'revision',e.revision,'note',e.note,'createdAt',e.created_at) order by e.revision,e.created_at),'[]'::jsonb) into v_events from public.request_instance_events e where e.request_instance_id=v_row.id and e.organization_id=v_row.organization_id;
118
+ return jsonb_build_object('request',jsonb_build_object('id',v_row.id,'status',v_row.status,'revision',v_row.revision,'createdAt',v_row.created_at,'updatedAt',v_row.updated_at),'steps',v_steps,'events',v_events);
119
+end $$;
120
+revoke all on function private.request_workflow_timeline(uuid) from public,anon;
121
+grant execute on function private.request_workflow_timeline(uuid) to authenticated;
122
+
123
+create or replace function public.request_workflow_timeline(p_request_instance_id uuid)
124
+returns jsonb language sql security invoker set search_path=''
125
+as $$ select private.request_workflow_timeline(p_request_instance_id) $$;
126
+revoke all on function public.request_workflow_timeline(uuid) from public,anon;
127
+grant execute on function public.request_workflow_timeline(uuid) to authenticated;