/* =====================================================================
   NOWILLS SQC ERP — Module pack 4: Workflow Engine + Setup/Config
   ===================================================================== */
(function(){
'use strict';
const D=DATA,D2=DATA2,K=D.K,ts=D.ts,MON=D.MONTHS,C=Charts.palette;
const H=window.MH, S=H.S, ln=H.ln, ar=H.ar, br=H.br, hb=H.hb, dn=H.dn, pi=H.pi, gg=H.gg, hm=H.hm, item=H.item, fct=H.fct;
const DAYS30=H.DAYS30;
const KINDC={task:'#3b82f6',approval:'#f8c200',system:'#22c55e',decision:'#a855f7'};

/* ============================ 31. WORKFLOW ENGINE ============================ */
MODULES.wflow=function(M){
 const inst=window.WFI||D2.wfInstances(); const all=Object.values(D2.WF).flat();
 const stages=all.flatMap(p=>p.stages);
 const sysN=stages.filter(s=>s[1]==='system').length, apprN=stages.filter(s=>s[1]==='approval').length;
 const cards=[
  K('Process Definitions',all.length,{u:'#',d:0,neutral:1,info:'across all 30 modules'}),
  K('Workflow Stages',stages.length,{u:'#',d:0,neutral:1}),
  K('Approval Steps',apprN,{u:'#',d:0,neutral:1}),K('Automated Steps',sysN,{u:'#',d:0,neutral:1}),
  K('Automation Coverage',Math.round(sysN/stages.length*100),{u:'%',d:0,tgt:40}),
  K('Live Instances',inst.length,{u:'#',d:0,neutral:1}),
  K('Pending Approvals',inst.filter(i=>i.st!=='on track').length+18,{u:'#',good:'down',d:0}),
  K('SLA Breached',inst.filter(i=>i.st==='breached').length,{u:'#',good:'down',d:0,tgt:0}),
  K('At Risk (SLA)',inst.filter(i=>i.st==='at risk').length,{u:'#',good:'down',d:0}),
  K('Avg Cycle Time',31.6,{u:'h',good:'down',d:1,tgt:36}),
  K('On-time Completion',94.2,{u:'%',tgt:95,d:1}),
  K('Escalations (2 wks)',7,{u:'#',good:'down',d:0}),
  K('Auto-posted Today',3120,{u:'#'})];
 const secs=[
  {k:'html',id:'wfmap',ti:'Process Map — live stage diagram (click any stage)',cls:'wide',live:1,hint:'Designer: edit stages · simulate runs'},
  {k:'html',id:'wfcat',ti:'Workflow Catalogue — every module, every process',cls:'wide'},
  {k:'chart',id:'wfstage',ti:'In-flight Work by Stage Type',spec:dn([item('Waiting approval',24,C[0]),item('In task stage',31,C[1]),item('System processing',57,C[2]),item('At decision gates',6,C[3])],{fmt:'num',center:'WIP'})},
  {k:'chart',id:'wfcyc',ti:'Average Cycle Time by Week (h)',spec:ln(['W28','W29','W30','W31','W32'],[S('All workflows',ts(5,33,.06,-.02,'wfc'),C[0],{area:true}),S('Approvals only',ts(5,14,.1,0,'wfa'),C[4])],{fmt:'h',target:{value:36,label:'SLA cap'}})},
  {k:'chart',id:'wfsla',ti:'SLA Compliance',cls:'w4',spec:gg(94.2,{max:100,fmt:'pct',sub:'Target 95% · breached items auto-escalate',zones:[[0,80,'#ef4444'],[80,95,'#f59e0b'],[95,100,'#22c55e']]})},
  {k:'chart',id:'wfheat',ti:'Bottleneck Heatmap — avg stage wait (h)',cls:'w8',spec:hm(['Procurement P2P','IPC certification','Work orders','Payroll run','Blast authorization','Stock adjustments'],['Intake','Review','Approval','External','Post'],[[2,4,9,1,0],[6,4,8,71,0],[1,3,5,0,0],[0,2,3,0,0],[18,9,5,24,0],[0,7,4,0,1]],{dec:0})},
  {k:'table',id:'wfinst',ti:'Live Workflow Instances',cls:'wide',cfg:{id:'wfinst',page:10,search:1,cols:[{k:'id',l:'Instance'},{k:'mod',l:'Module'},{k:'process',l:'Process'},{k:'stageName',l:'Current stage'},{k:'owner',l:'Owner role'},{k:'by',l:'Started by'},{k:'age',l:'Age'},{k:'sla',l:'SLA'},{k:'st',l:'SLA status',y:'badge',badge:v=>v==='breached'?'red':v==='at risk'?'amber':'green'}],rows:inst.map(w=>Object.assign({},w,{st:w.st,stL:w.st.toUpperCase()})),bulk:[['Nudge owners','nudge'],['Escalate','esc'],['Reassign','reassign']], }}
 ];
 return {title:'wflow',sub:'Design · run · measure — every module\'s process with SLA & escalation',cards:cards,sections:secs};
};

/* ============================ 32. SETUP & CONFIGURATION ============================ */
MODULES.setup=function(M){
 const chg=(window.NWCHANGES||[]).filter(c=>c.stat==='pending').length;
 const settingsN=Object.values(D2.CFG).reduce((a,c)=>a+c.sections.reduce((x,s)=>x+s[1].length,0),0);
 const cards=[
  K('Modules Configured',30,{u:'#',d:0,neutral:1}),K('Governed Settings',settingsN,{u:'#',d:0,neutral:1}),
  K('Pending Changes',chg||2,{u:'#',good:'down',d:0}),K('Published (30d)',11,{u:'#',d:0}),
  K('Environments',3,{u:'#',d:0,neutral:1,info:'Production · UAT · Training'}),
  K('Numbering Series',30,{u:'#',d:0,neutral:1}),K('DoA Rules',26,{u:'#',d:0,neutral:1}),
  K('Alert Rules',48,{u:'#',d:0}),K('Notification Templates',D2.TPL.length,{u:'#',d:0}),
  K('Integrations Live',9,{u:'#',d:0,neutral:1}),K('Config Drift Detected',0,{u:'#',good:'down',d:0,st:'green'}),
  K('Last Publish','09:41',{u:'text',st:'blue'})];
 const secs=[
  {k:'html',id:'cosetup',ti:'Company Entities & Settings — create companies & edit fiscal/localization settings',cls:'wide',hint:'LIVE — writes to the real ERP database (audited). Sign in once per session.',live:1},
  {k:'html',id:'setree',ti:'Module Settings — select a module, edit, stage for approval',cls:'wide',hint:'Amber bar = staged change · nothing goes live without change control',live:1},
  {k:'html',id:'changes',ti:'Configuration Change Control — pending approvals & rollbacks',cls:'wide'},
  {k:'table',id:'integrations',ti:'Integration Hub — endpoints & health',cls:'wide',cfg:{id:'integrations',page:10,cols:[{k:'a',l:'Interface'},{k:'b',l:'Endpoint'},{k:'c',l:'Direction'},{k:'d',l:'Latency',y:'num'},{k:'e',l:'Uptime 30d',y:'pct'},{k:'f',l:'Last event',y:'date'},{k:'g',l:'Status',y:'badge'}],rows:[
   {a:'GRA e-invoice (certified)',b:'https://api.gra.gov.gh/evat/v3',c:'Out',d:412,e:99.7,f:'2026-08-10 09:02',g:'green',gL:'Healthy'},
   {a:'GRA returns portal',b:'https://api.gra.gov.gh/returns/v2',c:'Out',d:620,e:99.2,f:'2026-08-09 18:00',g:'green',gL:'Healthy'},
   {a:'GCB Bank host-to-host',b:'sftp.bank.gcb.gh',c:'In/Out',d:2400,e:99.9,f:'2026-08-10 06:30',g:'green',gL:'Healthy'},
   {a:'MoMo — MTN & Telecel',b:'https://momo.partner.gh/pay',c:'In',d:310,e:99.95,f:'2026-08-10 09:04',g:'green',gL:'Healthy'},
   {a:'GPS telematics (fleet)',b:'wss://tel.africa-fleet.io/stream',c:'In',d:95,e:99.6,f:'live',g:'green',gL:'Streaming'},
   {a:'Plant IoT sensors',b:'mqtts://iot.nowills.gh:8883',c:'In',d:64,e:98.9,f:'live',g:'green',gL:'Streaming'},
   {a:'Drone survey service',b:'https://survey.nowills.gh/api',c:'In',d:1200,e:100,f:'2026-08-06 06:15',g:'blue',gL:'Scheduled'},
   {a:'SMS / WhatsApp gateway',b:'https://hub.mnotify.com/api',c:'Out',d:510,e:99.8,f:'2026-08-10 08:58',g:'green',gL:'Healthy'},
   {a:'BI / OLAP export',b:'https://bi.nowills.gh/cubes',c:'Out',d:890,e:100,f:'2026-08-10 06:00',g:'green',gL:'Healthy'}]}},
  {k:'html',id:'tmpl',ti:'Notification Templates — events, channels, recipients (13 events)',cls:'wide'},
  {k:'html',id:'fxenv',ti:'Currencies & Environments',cls:'wide'},
  {k:'chart',id:'cfgact',ti:'Configuration Change Activity (per week)',spec:br(['W28','W29','W30','W31','W32'],[S('Staged',fct(ts(5,6,.5,0,'ca1'),1),C[4]),S('Published',fct(ts(5,4,.4,0,'ca2'),1),C[2]),S('Rolled back',fct(ts(5,0.4,1.2,0,'ca3'),1),C[6])],{fmt:'num',min:0})},
  {k:'table',id:'publog',ti:'Publish & Version Log',cls:'wide',cfg:{id:'publog',page:9,cols:[{k:'a',l:'Version'},{k:'b',l:'At',y:'date'},{k:'c',l:'Modules'},{k:'d',l:'Changes',y:'num'},{k:'e',l:'Approved by'},{k:'f',l:'Rollback point'},{k:'g',l:'Status',y:'badge'}],rows:[
   {a:'v26.8.14',b:'2026-08-10 09:41',c:'tax · docs',d:3,e:'Internal Auditor',f:'rb-8812',g:'green',gL:'Live'},
   {a:'v26.8.13',b:'2026-08-08 15:20',c:'proc',d:1,e:'Internal Auditor',f:'rb-8799',g:'green',gL:'Live'},
   {a:'v26.8.12',b:'2026-08-06 11:02',c:'hse · ai',d:4,e:'COO',f:'rb-8780',g:'green',gL:'Live'},
   {a:'v26.8.11',b:'2026-08-04 16:44',c:'weigh',d:2,e:'Internal Auditor',f:'rb-8761',g:'grey',gL:'Superseded'}]}}
 ];
 return {title:'setup',sub:'Every module: numbering, targets, tolerances, DoA, rules, integrations',cards:cards,sections:secs};
};
window.__MH4=1;
})();
