Hugdrigo's picture
Upload 3 files
eaab3ed verified
Raw History Blame Contribute Delete
49.4 kB
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="StockPilot offline inventory replenishment and supply resilience simulator"><title>StockPilot | Inventory Intelligence Laboratory</title><style>:root{font-family:Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,Arial,sans-serif;color:#eaf2fc;background:#090f1d;color-scheme:dark;--surface:#132038;--border:#2b3e55;--muted:#93a6c0;--mint:#6ee7c3;--blue:#7facf5;--warn:#f9c477;--red:#ff8f96}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:radial-gradient(ellipse at 72% 0,#152b41 0,#0b1426 38%,#080e1b 100%)}button,select,input{font:inherit}button{cursor:pointer}button:disabled{opacity:.45;cursor:default}h1,h2,h3,p{margin:0}.layout{display:grid;grid-template-columns:246px minmax(0,1fr);min-height:100vh}.side{height:100vh;position:sticky;top:0;padding:26px 18px;background:#0c1628;border-right:1px solid #25344c;display:flex;flex-direction:column;z-index:20}.logo{display:flex;align-items:center;gap:12px;margin-bottom:32px;padding:0 7px}.logoIcon{width:42px;height:42px;background:linear-gradient(135deg,#90f7c8,#35a7b0);color:#08343b;display:grid;place-items:center;border-radius:12px;font-weight:900;font-size:23px}.logo b{display:block;font-size:20px;letter-spacing:-.8px}.logo small{display:block;letter-spacing:.4px;font-size:10px;color:#8da4be;margin-top:4px}.navLabel{padding:0 12px;font-weight:800;letter-spacing:2px;color:#6c829a;font-size:10px;margin-bottom:11px}.nav{display:grid;gap:5px}.nav button{display:flex;align-items:center;gap:12px;border:1px solid transparent;border-radius:10px;background:none;color:#9ab1ca;padding:12px 11px;font-size:12px;font-weight:730;text-align:left;width:100%}.nav button .em{font-size:18px;width:23px}.nav button.active{background:linear-gradient(95deg,#1a403d,#183042);color:#b8ffe5;border-color:#347465}.nav button:hover{color:white;background:#1b2d42}.sideFooter{margin-top:auto;border:1px solid #30435b;background:#142237;border-radius:12px;padding:15px;color:#aec4d7;font-size:11px;line-height:1.6}.sideFooter b{color:#b0ffe2}.pulse{display:inline-block;width:7px;height:7px;background:#6df5c4;border-radius:50%;margin-right:6px}.main{padding:0 36px 45px;max-width:1650px;min-width:0;width:100%;margin:0 auto}.top{display:flex;align-items:center;justify-content:space-between;gap:20px;min-height:84px;border-bottom:1px solid #24364e}.breadcrumb{color:#92a9c5;font-size:12px}.breadcrumb strong{color:#e1eefa}.topright{display:flex;align-items:center;flex-wrap:wrap;gap:8px}.pill{border:1px solid #376959;background:#153a36;color:#a0f7d0;border-radius:30px;padding:8px 11px;font-size:10px;font-weight:750}.minor{color:#95a9c2;border:1px solid #2c3c57;background:#122037;border-radius:30px;padding:8px 11px;font-size:10px}.mobileMenu{display:none}.content{padding-top:27px}.head{display:flex;justify-content:space-between;align-items:end;gap:20px;margin-bottom:24px}.eyebrow{color:#7ae9c4;letter-spacing:2.1px;font-size:10px;font-weight:850;text-transform:uppercase;margin-bottom:12px}.head h1{font-size:clamp(25px,3vw,38px);font-weight:850;letter-spacing:-1.35px;margin-bottom:10px}.head p{color:#9bb0c9;line-height:1.7;font-size:12px;max-width:780px}.btn{border:1px solid #3c526f;background:#192b43;color:#e8f2fc;padding:10px 13px;border-radius:10px;font-weight:750;font-size:11px;white-space:nowrap}.btn:hover{border-color:#82c8b4;background:#203c4f}.btn.primary{color:#0c3533;background:linear-gradient(130deg,#9af6cb,#46d7b6);border-color:#66eabb}.btn.sm{font-size:10px;padding:8px 10px}.actions{display:flex;gap:8px;flex-wrap:wrap}.card{background:linear-gradient(145deg,#17283e,#121d32);border:1px solid #2c3e56;border-radius:15px;padding:19px;min-width:0;box-shadow:0 10px 35px #0002}.card h2{font-size:15px;letter-spacing:-.3px}.sub{font-size:11px;color:#8fa7c1;line-height:1.55;margin-top:7px}.cardHead{display:flex;align-items:start;justify-content:space-between;gap:11px;flex-wrap:wrap;margin-bottom:17px}.label{font-size:10px;color:#95abc5;letter-spacing:.2px}.kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:15px;margin-bottom:18px}.kpi{min-height:139px}.kpiTop{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:11px;color:#a5b5ca}.kpiIcon{font-size:18px}.big{font-weight:850;font-size:clamp(23px,2.5vw,35px);letter-spacing:-1px;margin:23px 0 10px}.big.mint{color:#8ff6d4}.big.orange{color:#f6d296}.big.red{color:#ff9aa0}.small{font-size:10px;line-height:1.6;color:#89a2bc}.cols{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(290px,.9fr);gap:17px;margin-bottom:17px}.cols.equal{grid-template-columns:repeat(2,minmax(0,1fr))}.stack{display:grid;gap:17px}.control{display:grid;gap:7px}.control label{color:#b0c1d4;font-size:11px;font-weight:720}.control select,.control input:not([type=file]){background:#0f1d30;color:#e4f1fd;border:1px solid #3a5069;border-radius:9px;padding:10px 11px;width:100%;font-size:12px;outline:none}.control input[type=range]{accent-color:#69e2bb;padding:7px 0;border:0;background:none}.control input:focus,.control select:focus{border-color:#76efc9}.formgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.info{border:1px solid #37675c;border-radius:11px;padding:12px;background:#15372f;font-size:11px;line-height:1.7;color:#b6f4da}.info.warn{background:#3a3027;border-color:#816c4d;color:#ffe0ab}.info.danger{background:#422831;border-color:#93545c;color:#ffc6ca}.mini{border:1px solid #30455b;background:#101d31;border-radius:11px;padding:13px}.mini span{display:block;color:#9bb4ce;font-size:10px}.mini b{font-size:21px;margin-top:6px;display:block}.miniGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.tablewrap{overflow-x:auto;border:1px solid #293d54;border-radius:10px}table{border-collapse:collapse;width:100%;min-width:550px;font-size:11px}th{background:#1b2b42;color:#9bb1ca;font-size:10px;letter-spacing:.4px;text-align:left;padding:12px}td{color:#d4e4f5;padding:12px;border-top:1px solid #293c52}tbody tr:hover{background:#1c2e43}.tag{display:inline-block;background:#263a51;color:#b3cde1;font-size:9px;font-weight:850;border-radius:6px;padding:5px 7px;text-transform:uppercase}.tag.good{color:#9af4cf;background:#19483e}.tag.bad{color:#ffb1b5;background:#492e3a}.tag.warn{color:#ffe1a5;background:#4a3a2d}.chart{width:100%;height:auto;display:block;overflow:visible}.chart .grid{stroke:#34445c;stroke-width:1}.chart text{fill:#91a9c3;font-size:10px;font-family:inherit}.barrow{display:grid;grid-template-columns:95px minmax(0,1fr) 56px;gap:10px;align-items:center;margin:14px 0;font-size:11px;color:#b8cfe4}.track{background:#24374d;height:10px;border-radius:8px;overflow:hidden}.track i{display:block;height:100%;border-radius:8px;background:linear-gradient(90deg,#528bda,#7beac3)}.story{line-height:1.7;color:#a4bcd3;font-size:11px}.story b{color:#f0f5ff}.note{margin-top:12px;border-left:3px solid #63ddb6;padding-left:11px;font-size:11px;color:#b8cfe1;line-height:1.65}.method{border-bottom:1px solid #2a4057;padding:14px 0;color:#afc2d7;font-size:11px;line-height:1.7}.method:last-child{border-bottom:none}.method b{color:#eff7ff}.filebox{padding:17px;border:1px dashed #527b81;background:#112c37;border-radius:12px}.filebox input{font-size:11px;max-width:100%}.selectbar{display:flex;gap:10px;flex-wrap:wrap;align-items:center}.selectbar select{max-width:270px}.footer{border-top:1px solid #273951;margin-top:30px;padding-top:18px;color:#6f879f;font-size:10px;line-height:1.6}.toast{position:fixed;bottom:20px;right:22px;z-index:60;max-width:min(400px,90vw);padding:14px;border-radius:11px;background:#1a4a40;border:1px solid #66aa9a;font-size:12px;color:#e3fff2;box-shadow:0 10px 25px #0008}.toast.err{background:#522a36;border-color:#dc7588}.toast.hidden{display:none}.cap{font-size:9px;letter-spacing:1px;font-weight:850;color:#84e7c2;text-transform:uppercase}.heat{width:100%;border-collapse:collapse;min-width:470px}.heat td{padding:14px;text-align:center}.inlineCall{color:#aaf9d3;font-weight:800}.muted{color:#8ea3bb}.hint{font-size:10px;color:#9bafc5;line-height:1.7}.badgeLine{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.badgeLine i{display:inline-block;height:7px;width:7px;background:#76eac5;border-radius:50%}
@media(max-width:1150px){.kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.cols{grid-template-columns:minmax(0,1fr)}.main{padding:0 22px 40px}}@media(max-width:780px){.layout{grid-template-columns:minmax(0,1fr)}.side{position:fixed;left:0;top:0;transform:translateX(-105%);transition:transform .2s ease;width:260px;box-shadow:14px 0 25px #0009}.side.open{transform:translateX(0)}.main{padding:0 15px 28px}.top{min-height:66px}.mobileMenu{display:inline-flex}.minor{display:none}.head{align-items:start;flex-direction:column;gap:14px;margin-bottom:20px}.head h1{font-size:28px}.kpis{gap:10px}.kpi{min-height:125px}.kpi .big{font-size:25px}.card{padding:15px}.formgrid{grid-template-columns:1fr}.miniGrid{grid-template-columns:1fr}.cols{gap:13px}.selectbar select{max-width:100%}.pill{font-size:9px}.topright{gap:5px}}@media(max-width:400px){.kpis{grid-template-columns:1fr 1fr}.kpi .big{font-size:22px}.head h1{font-size:26px}}
.note code{white-space:normal;overflow-wrap:anywhere;word-break:break-word}.filebox{overflow-wrap:anywhere}.card{overflow-wrap:break-word}
</style></head><body><div class="layout"><aside class="side" id="side"><div class="logo"><div class="logoIcon">S</div><div><b>StockPilot</b><small>REPLENISHMENT LAB · #52</small></div></div><div class="navLabel">WORKSPACE</div><nav id="nav" class="nav"></nav><div class="sideFooter"><div class="cap">METHODS & RESPONSIBILITY</div><div style="margin:9px 0">Synthetic inventory simulation</div><div>Models are illustrative and fully offline. They do not make actual procurement decisions.</div><div style="margin-top:12px"><span class="pulse"></span><b>Local compute · No APIs</b></div></div></aside><main class="main"><div class="top"><div class="breadcrumb"><button class="btn sm mobileMenu" id="mobileMenu" aria-label="Open navigation">☰</button> <strong>StockPilot</strong> &nbsp; / &nbsp; <span id="where">Command Center</span></div><div class="topright"><span class="pill">●&nbsp; STATIC LAB</span><span class="minor" id="reps">70 simulations</span><span class="minor" id="count">6 items</span></div></div><div class="content"><div class="head"><div><div class="eyebrow">INVENTORY INTELLIGENCE / PROJECT 52</div><h1 id="heading">Operations Command Center</h1><p id="summary">Offline simulation and inventory policy comparison</p></div><div class="actions"><select id="scenario" class="btn" aria-label="Choose demonstration scenario"></select><button class="btn primary" id="exportTop">↓ Export audit</button></div></div><div id="view"></div><div class="footer">STOCKPILOT / PROJECT 52 &nbsp; • &nbsp; MIT LICENSE &nbsp; • &nbsp; Offline synthetic analytics. All scenario inputs and assumptions are illustrative. Not financial, clinical or procurement advice.</div></div></main></div><div id="toast" class="toast hidden" role="status" aria-live="polite"></div><script>/* StockPilot quantitative engine. All computations are local, deterministic given a seed. */
const CORE = (() => {
const round=(x,d=2)=>Number(x.toFixed(d));
const sum=a=>a.reduce((x,y)=>x+y,0);
const mean=a=>a.length?sum(a)/a.length:0;
const percentile=(a,p)=>{if(!a.length)return 0;const v=[...a].sort((x,y)=>x-y),z=(v.length-1)*p,i=Math.floor(z);return v[i]+(v[Math.min(i+1,v.length-1)]-v[i])*(z-i)};
const rand=(seed)=>{let x=(Number(seed)>>>0)||1;return()=>{x^=x<<13;x^=x>>>17;x^=x<<5;return (x>>>0)/4294967296}};
const normal=(rng)=>{const u=Math.max(1e-12,rng()),v=rng();return Math.sqrt(-2*Math.log(u))*Math.cos(2*Math.PI*v)};
const escapeHtml=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const csvValue=v=>{let s=String(v??'');if(/^[\s]*[=+@\-\t\r]/.test(s))s="'"+s;return '"'+s.replace(/"/g,'""')+'"'};
const toCSV=(rows,cols)=>[cols.join(','),...rows.map(r=>cols.map(k=>csvValue(r[k])).join(','))].join('\r\n')+'\r\n';
function parseCSV(raw){if(typeof raw!=='string'||raw.length>250000)throw Error('CSV must be smaller than 250 KB.');raw=raw.replace(/^\uFEFF/,'');let rows=[],row=[],field='',quoted=false,afterQuote=false;for(let i=0;i<raw.length;i++){const c=raw[i];if(quoted){if(c==='"'&&raw[i+1]==='"'){field+='"';i++}else if(c==='"'){quoted=false;afterQuote=true;}else field+=c;}else if(c==='"'){if(field!==''||afterQuote)throw Error('Invalid quote in CSV.');quoted=true;}else if(c===','){row.push(field);field='';afterQuote=false;}else if(c==='\n'||c==='\r'){if(c==='\r'&&raw[i+1]==='\n')i++;row.push(field);field='';afterQuote=false;if(row.some(v=>v!==''))rows.push(row);row=[];}else if(afterQuote){if(c!==' '&&c!=='\t')throw Error('Unexpected character after CSV quote.');}else field+=c;}if(quoted)throw Error('Unclosed CSV quote.');row.push(field);if(row.some(v=>v!==''))rows.push(row);if(!rows.length)throw Error('CSV is empty.');const header=rows.shift().map(s=>s.trim().toLowerCase());if(new Set(header).size!==header.length)throw Error('Duplicate CSV headers.');if(rows.some(r=>r.length!==header.length))throw Error('Inconsistent CSV column count.');return rows.map(row=>Object.fromEntries(header.map((k,i)=>[k,row[i].trim()])))}
const fields=['sku','name','category','avg_daily','std_daily','lead_days','unit_cost','sell_price','holding_rate','order_cost','shortage_penalty','capacity','opening_stock'];
function validateRows(rows){if(!Array.isArray(rows)||rows.length<2||rows.length>25)throw Error('Provide between 2 and 25 SKUs.');const seen=new Set();return rows.map((r,i)=>{for(const k of fields)if(!(k in r))throw Error('Missing column: '+k);const o={};for(const k of ['sku','name','category']){o[k]=String(r[k]).trim();if(!o[k]||o[k].length>65)throw Error('Invalid '+k+' in row '+(i+1));}if(!/^[a-zA-Z0-9._-]{2,25}$/.test(o.sku))throw Error('SKU must contain 2-25 alphanumeric characters, dots, underscores or hyphens.');if(seen.has(o.sku))throw Error('Duplicate SKU: '+o.sku);seen.add(o.sku);for(const k of fields.slice(3)){const s=String(r[k]).trim();if(s===''||!Number.isFinite(Number(s)))throw Error('Invalid '+k+' for '+o.sku);o[k]=Number(s);}
const constraints={avg_daily:[0.1,500],std_daily:[0,500],lead_days:[1,45],unit_cost:[0.01,100000],sell_price:[0.01,100000],holding_rate:[0,2],order_cost:[0,10000],shortage_penalty:[0,100000],capacity:[1,100000],opening_stock:[0,100000]};for(const [k,[lo,hi]] of Object.entries(constraints)){if(o[k]<lo||o[k]>hi)throw Error(k+' out of range for '+o.sku);}if(o.sell_price<o.unit_cost)throw Error('sell_price must be >= unit_cost for '+o.sku);if(o.opening_stock>o.capacity)throw Error('opening_stock exceeds capacity for '+o.sku);return o;});}
const dayConfig={horizon:90,reps:70,seed:2105,demandMultiplier:1,leadShock:0,holdingMultiplier:1,targetFill:0.95};
function config(overrides={}){let c={...dayConfig,...overrides};for(const [k,lo,hi] of [['horizon',28,365],['reps',10,1000],['seed',1,4294967295],['demandMultiplier',.5,1.9],['leadShock',0,15],['holdingMultiplier',.5,2],['targetFill',.7,.999]])if(!Number.isFinite(c[k])||c[k]<lo||c[k]>hi)throw Error('Invalid '+k);return c;}
function policy(sku,strategy,c){let z={lean:.15,balanced:1.3,resilient:2.1}[strategy];if(z===undefined)throw Error('Unknown policy');const lead=sku.lead_days+c.leadShock*.25;const effectiveMu=sku.avg_daily*c.demandMultiplier;const effectiveSigma=sku.std_daily*c.demandMultiplier;const reorder=Math.min(sku.capacity,Math.max(1,Math.ceil(effectiveMu*lead+z*effectiveSigma*Math.sqrt(lead))));const cycle={lean:9,balanced:16,resilient:23}[strategy];const upTo=Math.min(sku.capacity,Math.max(reorder,Math.ceil(reorder+effectiveMu*cycle)));return {reorder,upTo,strategy};}
function samples(sk,c,rep){const rng=rand((c.seed+((rep+1)*2654435761>>>0)+sk.sku.split('').reduce((v,a)=>v*33+a.charCodeAt(0),5381))>>>0);const demands=[],delays=[];for(let d=0;d<c.horizon;d++){let weekly=1+0.11*Math.sin(2*Math.PI*(d%7)/7);let wave=1+.065*Math.sin((d+rep%9)/19);let mu=sk.avg_daily*c.demandMultiplier*weekly*wave;let qty=Math.max(0,Math.round(mu+sk.std_daily*c.demandMultiplier*normal(rng)));demands.push(qty);delays.push(Math.max(0,Math.round(c.leadShock*rng())));}return {demands,delays}}
function simulate(sku,pol,c,path){let stock=sku.opening_stock,orders=[],totalDemand=0,sold=0,lost=0,hold=0,ordCost=0,orderCount=0,totalInventory=0,leadUnits=0;const points=[];
for(let d=0;d<c.horizon;d++){let arriving=0;orders=orders.filter(o=>{if(o.day<=d){arriving+=o.qty;return false;}return true});stock+=arriving;const demand=path.demands[d],fulfilled=Math.min(stock,demand);stock-=fulfilled;totalDemand+=demand;sold+=fulfilled;lost+=demand-fulfilled;hold+=stock*sku.unit_cost*sku.holding_rate*c.holdingMultiplier/365;totalInventory+=stock;
const position=stock+sum(orders.map(o=>o.qty));if(position<=pol.reorder){const qty=Math.min(Math.max(0,sku.capacity-position),Math.max(0,pol.upTo-position));if(qty>=1){const lead=sku.lead_days+path.delays[d];orders.push({day:d+Math.max(1,lead),qty});ordCost+=sku.order_cost;orderCount++;leadUnits+=qty;}}
if(d%3===0||d===c.horizon-1)points.push({day:d+1,stock,demand,lost:demand-fulfilled,arriving});}
return {demand:totalDemand,sold,lost,fill:totalDemand?sold/totalDemand:1,holding:hold,ordering:ordCost,shortage:lost*sku.shortage_penalty,relevantCost:hold+ordCost+lost*sku.shortage_penalty,netContribution:sold*(sku.sell_price-sku.unit_cost)-hold-ordCost,orderCount,meanInventory:totalInventory/c.horizon,points};}
function analyze(data,cfg={},strategies=['lean','balanced','resilient']){const c=config(cfg);const products=validateRows(data);const rngs=products.map(p=>Array.from({length:c.reps},(_,i)=>samples(p,c,i)));let policies=[];
for(const st of strategies){let itemRows=[],allPaths=[],snapshots=[];for(let s=0;s<products.length;s++){const sku=products[s],pol=policy(sku,st,c);const outputs=rngs[s].map(path=>simulate(sku,pol,c,path));itemRows.push({...sku,...pol,fill:mean(outputs.map(o=>o.fill)),lost:mean(outputs.map(o=>o.lost)),cost:mean(outputs.map(o=>o.relevantCost)),holding:mean(outputs.map(o=>o.holding)),ordering:mean(outputs.map(o=>o.ordering)),shortage:mean(outputs.map(o=>o.shortage)),contribution:mean(outputs.map(o=>o.netContribution)),orders:mean(outputs.map(o=>o.orderCount))});snapshots.push(outputs[0].points);allPaths.push(outputs);}
const values=[];for(let rep=0;rep<c.reps;rep++){const os=allPaths.map(p=>p[rep]);const demand=sum(os.map(o=>o.demand)),sold=sum(os.map(o=>o.sold));values.push({fill:demand?sold/demand:1,cost:sum(os.map(o=>o.relevantCost)),contribution:sum(os.map(o=>o.netContribution)),lost:sum(os.map(o=>o.lost))});}
policies.push({strategy:st,fill:mean(values.map(p=>p.fill)),fillP10:percentile(values.map(p=>p.fill),.1),cost:mean(values.map(p=>p.cost)),costP90:percentile(values.map(p=>p.cost),.9),contribution:mean(values.map(p=>p.contribution)),lost:mean(values.map(p=>p.lost)),items:itemRows,values,snapshots,feasible:mean(values.map(p=>p.fill))>=c.targetFill});}
const best=policies.filter(p=>p.feasible).sort((a,b)=>a.cost-b.cost)[0]||null;
return {cfg:c,policies,best,products};}
return {round,sum,mean,percentile,rand,normal,escapeHtml,csvValue,toCSV,parseCSV,validateRows,config,policy,samples,simulate,analyze,fields};
})();
if(typeof module!=='undefined')module.exports=CORE;
const PRESETS=[
{name:'Urban retail network',desc:'Illustrative retail assortment and replenishment economics',items:[
['UR-101','Home essentials','Home',22,7,4,14,23,.24,58,11,460,125],
['UR-102','Coffee & pantry','Food',36,10,3,7,12,.18,35,6,620,170],
['UR-103','Personal care','Health',18,6,6,11,19,.22,44,9,470,95],
['UR-104','Seasonal accessories','Lifestyle',13,7,9,24,41,.3,64,18,520,120],
['UR-105','Tech consumables','Electronics',16,5,7,27,43,.26,78,23,410,150],
['UR-106','Cleaning supplies','Home',27,8,5,10,18,.2,45,8,580,135]]},
{name:'Regional medical supply',desc:'Synthetic consumable supply chain, not a clinical decision aid',items:[
['MS-110','Examination gloves','Consumables',52,14,3,5,9,.22,48,16,1150,270],
['MS-120','Sterile dressings','Consumables',29,9,6,8,14,.2,70,19,830,180],
['MS-130','Lab collection tubes','Laboratory',20,6,8,12,22,.19,85,26,620,160],
['MS-140','Filter cartridges','Equipment',8,3,12,35,57,.24,120,52,420,165],
['MS-150','Surface wipes','Hygiene',41,12,4,6,11,.26,42,15,900,225],
['MS-160','Test kits','Laboratory',17,6,11,31,49,.27,110,44,520,160]]},
{name:'Andean agrifood exports',desc:'Fictional export materials and packaging flows',items:[
['AG-110','Quinoa packaging','Packaging',26,9,6,4,9,.24,65,10,650,150],
['AG-120','Quality test supplies','Quality',12,5,12,29,48,.19,112,36,440,140],
['AG-130','Export carton sleeves','Packaging',43,13,5,3,7,.2,72,8,880,200],
['AG-140','Pallet stretch film','Packaging',19,6,9,16,28,.22,96,20,550,170],
['AG-150','Organic labels','Compliance',36,15,7,2,6,.16,48,9,720,230],
['AG-160','Humidity indicators','Quality',11,4,15,24,41,.25,104,39,400,100]]}
].map(p=>({...p,items:p.items.map(row=>Object.fromEntries(CORE.fields.map((k,i)=>[k,row[i]])))}));
(() => {
'use strict';
const $=id=>document.getElementById(id),fmt=(v,d=1)=>Number(v||0).toLocaleString('en-US',{minimumFractionDigits:d,maximumFractionDigits:d}),money=(v)=>'$'+fmt(v,0),pct=v=>fmt(v*100,1)+'%',safe=CORE.escapeHtml;
let preset=0,items=CORE.validateRows(PRESETS[0].items),page='overview',sku=items[0].sku,conf={horizon:90,reps:70,seed:2105,demandMultiplier:1,leadShock:0,holdingMultiplier:1,targetFill:.95},result=CORE.analyze(items,conf),lastImport='',importError=false;
const PAGE={overview:['Operations Command Center','A transparent view of inventory exposure, replenishment economics and service quality.'],simulator:['Scenario Laboratory','Stress-test inventory decisions under uncertain demand and delayed replenishment.'],policies:['Policy Benchmark','Compare three replenishment policies on identical demand and delay paths.'],products:['SKU Intelligence','Inspect each item, reorder point and 90-day inventory trajectory.'],data:['Data Workbench','Import an assortment, validate its schema and export reproducible input templates.'],methods:['Audit & Methodology','Understand the calculations, assumptions, diagnostics and limitations.']};
const links=[['overview','◫','Command Center'],['simulator','◷','Scenario Laboratory'],['policies','♧','Policy Benchmark'],['products','▦','SKU Intelligence'],['data','▤','Data Workbench'],['methods','◇','Audit & Methods']];
const policyName=k=>({lean:'Lean inventory',balanced:'Balanced inventory',resilient:'Resilient inventory'}[k]);
const policyColor=k=>({lean:'#7facf5',balanced:'#75efc5',resilient:'#f6c880'}[k]);
const panel=(title,desc,html,action='')=>`<section class="card"><div class="cardHead"><div><h2>${title}</h2><p class="sub">${desc}</p></div>${action}</div>${html}</section>`;
const tag=(s,type='good')=>`<span class="tag ${type}">${safe(s)}</span>`;
const kpi=(label,val,sub,kind='',ico='◈')=>`<div class="card kpi"><div class="kpiTop"><span>${safe(label)}</span><span class="kpiIcon">${ico}</span></div><div class="big ${kind}">${val}</div><div class="small">${sub}</div></div>`;
const selected=()=>result.policies.find(p=>p.strategy===$('policyTop').value)||result.policies[1];
const active=()=>result.policies.find(p=>p.strategy===document.body.dataset.activePolicy)||result.policies[1];
const policySelect=()=>`<div class="control"><label for="activePolicy">Policy in focus</label><select id="activePolicy">${result.policies.map(p=>`<option value="${p.strategy}" ${p.strategy===document.body.dataset.activePolicy?'selected':''}>${policyName(p.strategy)}</option>`).join('')}</select></div>`;
function svgLine(series,{maxY=null,minY=0,format=v=>fmt(v,0),height=240,colors=['#72f4c7','#72a8f0','#efc178'],labels=[]}={}){const width=720,left=57,right=15,top=20,bottom=36,plotW=width-left-right,plotH=height-top-bottom;let n=Math.max(2,...series.map(s=>s.length));let rawmax=maxY??Math.max(1,...series.flatMap(s=>s.map(x=>x??0)));let ymax=maxY!==null?maxY:Math.max(minY+1,rawmax*1.08);const x=i=>left+(i/(n-1))*plotW;const y=v=>top+plotH-(v-minY)/(ymax-minY)*plotH;let svg=`<svg class="chart" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" role="img" aria-label="${safe(labels.join(' versus ')||'Analytic time series chart')}">`;
for(let i=0;i<=4;i++){let yy=top+i/4*plotH;svg+=`<line class="grid" x1="${left}" y1="${yy}" x2="${width-right}" y2="${yy}"/><text text-anchor="end" x="${left-10}" y="${yy+4}">${safe(format(ymax-i/4*(ymax-minY)))}</text>`;}for(let i=0;i<5;i++){let xx=left+i/4*plotW;svg+=`<text text-anchor="middle" x="${xx}" y="${height-9}">${Math.round(1+i/4*(n-1))}</text>`;}
series.forEach((arr,j)=>{const points=arr.map((v,i)=>`${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');svg+=`<polyline fill="none" stroke="${colors[j%colors.length]}" stroke-width="${j===0?3:2.5}" stroke-linejoin="round" stroke-linecap="round" points="${points}"/>`;});return svg+'</svg>'+`<div class="badgeLine" style="margin-top:8px">${labels.map((l,i)=>`<span style="font-size:10px;color:#9fb1c8"><i style="background:${colors[i%colors.length]}"></i>${safe(l)}</span>`).join('')}</div>`;}
function barRows(rows,max){return rows.map(r=>`<div class="barrow"><span title="${safe(r.name)}">${safe(r.name.slice(0,14))}</span><div class="track"><i style="width:${Math.max(.2,100*r.value/(max||1))}%"></i></div><b style="text-align:right">${safe(r.txt)}</b></div>`).join('');}
function overview(){const focus=active(),low=result.policies.find(p=>p.strategy==='lean'),good=result.best;const baselineCost=low.cost;const gap=focus.fill-conf.targetFill;
const stats=`<div class="kpis">${kpi('Portfolio fill rate',pct(focus.fill),'Share of simulated demand fulfilled',focus.fill>=conf.targetFill?'mint':'orange','◉')}${kpi('Relevant cost / horizon',money(focus.cost),'Holding + order + shortage penalties','','$')}${kpi('Units unavailable',fmt(focus.lost,0),'Average lost demand per simulated horizon','orange','◷')}${kpi('Service target gap',(gap>=0?'+':'')+fmt(gap*100,1)+' pp','Target '+pct(conf.targetFill),gap>=0?'mint':'red','◎')}</div>`;
const chart=svgLine(result.policies.map(p=>p.values.slice(0,35).map(v=>v.fill*100)),{minY:0,maxY:105,format:v=>fmt(v,0)+'%',labels:result.policies.map(p=>policyName(p.strategy))});
const decision=good?`The <b>${safe(policyName(good.strategy))}</b> policy has the lowest estimated relevant cost among the three options meeting the configured mean fill-rate target of <b>${pct(conf.targetFill)}</b>. This is a simulation-based comparison, not a global optimum.`:`<b>None of the three predefined policies meets the mean fill-rate target (${pct(conf.targetFill)}).</b> Consider changes in lead times, supplier reliability, capacity or policy parameters instead of declaring a winner.`;
return `${stats}<div class="cols">${panel('Service performance across shared simulations','35 of the paired demand trajectories used for policy comparison.',chart)}${panel('Decision support','Choose a policy and review whether it meets the target.',`${policySelect()}<div class="info ${good?'':'warn'}" style="margin-top:16px">${decision}</div><div class="miniGrid" style="margin-top:13px"><div class="mini"><span>Policy in focus</span><b style="font-size:14px">${safe(focus.strategy)}</b></div><div class="mini"><span>10th pct fill</span><b>${pct(focus.fillP10)}</b></div><div class="mini"><span>90th pct cost</span><b>${money(focus.costP90)}</b></div></div>`)}</div><div class="cols">${panel('Replenishment exposure by SKU','Shortage penalty costs averaged over identical demand paths.',barRows(focus.items.map(p=>({name:p.name,value:p.shortage,txt:money(p.shortage)})),Math.max(...focus.items.map(p=>p.shortage),1))+`<div class="note">Shortage penalty is an explicit assumption. It includes the estimated cost of unmet demand and must not be interpreted as a measured accounting loss.</div>`)}${panel('Scenario footprint','All results shown are computed in your browser.',`<div class="method"><b>Illustrative dataset</b><br>${safe(PRESETS[preset]?.desc||'Locally imported custom assortment')}</div><div class="method"><b>Study scope</b><br>${items.length} SKUs · ${conf.horizon} days · ${conf.reps} shared stochastic replications</div><div class="method"><b>Simulated uncertainty</b><br>Demand multiplier ${fmt(conf.demandMultiplier,2)}× · additional lead-time delay up to ${fmt(conf.leadShock,0)} days</div><div class="method"><b>Privacy</b><br>All processing runs in this browser. No remote APIs or trackers.</div>`)} </div>`;}
function simulator(){const f=active();const sliders=[['demandMultiplier','Demand multiplier','×',.5,1.9,.05],['leadShock','Maximum supply delay',' days',0,15,1],['holdingMultiplier','Holding cost multiplier','×',.5,2,.05],['targetFill','Minimum mean fill rate','%',.7,.999,.005]];const control=sliders.map(([id,label,s,min,max,step])=>{const val=conf[id];const value=id==='targetFill'?fmt(val*100,1)+'%':fmt(val,id==='leadShock'?0:2)+s;return `<div class="control"><label for="${id}">${label} · <strong id="${id}Value">${value}</strong></label><input id="${id}" type="range" min="${min}" max="${max}" step="${step}" value="${val}"></div>`;}).join('');
const inputs=`<div class="formgrid">${control}</div><div class="formgrid" style="margin-top:16px"><div class="control"><label for="seed">Reproducibility seed</label><input id="seed" type="number" min="1" max="2147483647" value="${conf.seed}"></div><div class="control"><label for="horizon">Simulation days</label><select id="horizon">${[60,90,120,180,365].map(n=>`<option value="${n}" ${conf.horizon===n?'selected':''}>${n} days</option>`).join('')}</select></div></div><div class="actions" style="margin-top:16px"><button data-action="run" class="btn primary">▶ Run paired simulation</button><button data-action="reset-config" class="btn">↺ Reset assumptions</button></div>`;
const data=result.policies.map(p=>({name:policyName(p.strategy),fill:p.fill,cost:p.cost,lost:p.lost}));return `<div class="cols">${panel('Stress-test assumptions','Parameters are hypotheses and do not represent official market forecasts.',inputs)}${panel('Comparison after last run','Press Run paired simulation to apply pending changes.',`<div class="stack" style="gap:12px">${data.map(p=>`<div class="mini"><div class="badgeLine"><span class="tag">${p.name}</span><span style="margin-left:auto;color:#87eac5;font-size:14px;font-weight:800">${pct(p.fill)}</span></div><div class="track" style="margin:10px 0"><i style="width:${p.fill*100}%"></i></div><span>Cost: ${money(p.cost)} · Lost units: ${fmt(p.lost,0)}</span></div>`).join('')}</div>`)} </div><div class="cols equal">${panel('Cost sensitivity','Each policy uses identical random demand and delay streams.',svgLine(result.policies.map(p=>p.values.slice(0,30).map(v=>v.cost)),{labels:result.policies.map(p=>policyName(p.strategy)),format:v=>'$'+fmt(v/1000,0)+'k'}))}${panel('Model notes','What changes when you move the controls.',`<div class="method"><b>Demand multiplier</b><br>Scales both expected demand and its variability.</div><div class="method"><b>Supplier disruption</b><br>Adds a random delay between 0 and the configured maximum.</div><div class="method"><b>Holding multiplier</b><br>Changes cost while leaving demand and lead-time samples unchanged.</div><div class="method"><b>Service target</b><br>Changes feasibility classification. It does not secretly modify the policies.</div>`)} </div>`;}
function policies(){const best=result.best;return `${panel('Replenishment strategies','All three strategies are evaluated against identical stochastic samples. A feasible policy meets the target on average, not in every simulation.',`<div class="tablewrap"><table><thead><tr><th>Strategy</th><th>Mean fill rate</th><th>10th pct fill</th><th>Relevant cost</th><th>90th pct cost</th><th>Estimated net contribution</th><th>Target</th></tr></thead><tbody>${result.policies.map(p=>`<tr><td>${safe(policyName(p.strategy))}</td><td>${pct(p.fill)}</td><td>${pct(p.fillP10)}</td><td>${money(p.cost)}</td><td>${money(p.costP90)}</td><td>${money(p.contribution)}</td><td>${p.feasible?tag('Meets target'):tag('Below target','warn')}</td></tr>`).join('')}</tbody></table></div><div class="note">${best?'Lowest-cost feasible option among three presets: <b>'+policyName(best.strategy)+'</b>.':'No predefined policy meets the chosen target.'} Exact global optimization is not claimed.</div>`) }<div class="cols equal">${panel('Cost structure by policy','Average relevant costs, simulated over ${conf.horizon} days.',svgLine([result.policies.map(p=>p.cost),result.policies.map(p=>p.items.reduce((n,i)=>n+i.shortage,0))],{labels:['Total relevant cost','Stockout penalty component'],format:v=>'$'+fmt(v/1000,0)+'k',height:240}))}${panel('Paired analysis','Why the comparison is reproducible.',`<div class="method"><b>Common random numbers</b><br>Every policy sees the same ${conf.reps} demand paths per SKU and the same supply delays.</div><div class="method"><b>Transparent rules</b><br>Lean, Balanced and Resilient differ only in safety-stock z value and replenishment cycle.</div><div class="method"><b>Feasibility</b><br>Mean simulated fill rate must be at least ${pct(conf.targetFill)}.</div><div class="method"><b>Uncertainty</b><br>10th- and 90th-percentile diagnostics describe simulations, not statistically calibrated forecasts.</div>`)}</div>${panel('SKU-level policy details','Reorder point and order-up-to levels are capped at the illustrative item capacity.',`<div class="tablewrap"><table><thead><tr><th>SKU</th><th>Policy</th><th>Reorder at</th><th>Order-up-to</th><th>Average fill</th><th>Cost</th></tr></thead><tbody>${result.policies.flatMap(p=>p.items.map(s=>`<tr><td>${safe(s.sku)}</td><td>${safe(policyName(p.strategy))}</td><td>${fmt(s.reorder,0)}</td><td>${fmt(s.upTo,0)}</td><td>${pct(s.fill)}</td><td>${money(s.cost)}</td></tr>`)).join('')}</tbody></table></div>`)}`;}
function products(){if(!items.find(s=>s.sku===sku))sku=items[0].sku;const rows=result.policies.map(p=>p.items.find(it=>it.sku===sku));const s=rows[0];const choice=active(),idx=items.findIndex(it=>it.sku===sku);const p=choice.items[idx];const points=choice.snapshots[idx];return `<div class="cols">${panel('SKU selector','Switch products to explore their operational model.',`<div class="control"><label for="sku">Item</label><select id="sku">${items.map(i=>`<option value="${safe(i.sku)}" ${i.sku===sku?'selected':''}>${safe(i.sku+' · '+i.name)}</option>`).join('')}</select></div><div class="miniGrid" style="margin-top:16px"><div class="mini"><span>Average daily demand</span><b>${fmt(s.avg_daily,1)}</b></div><div class="mini"><span>Lead time</span><b>${fmt(s.lead_days,0)}d</b></div><div class="mini"><span>Storage capacity</span><b>${fmt(s.capacity,0)}</b></div></div><div class="note">Forecast demand and replenishment assumptions are synthetic. The app has no live purchase orders or warehouse integration.</div>`)}${panel('Service and policy exposure','Estimated policy outcomes for this SKU.',`<div class="stack" style="gap:13px">${rows.map(r=>`<div class="mini"><div class="badgeLine"><span>${safe(policyName(r.strategy))}</span><b style="margin-left:auto;color:${policyColor(r.strategy)};font-size:16px">${pct(r.fill)}</b></div><div class="small" style="margin-top:8px">Reorder ${r.reorder} · Replenish to ${r.upTo} · Cost ${money(r.cost)}</div></div>`).join('')}</div>`)}</div><div class="cols">${panel('Inventory on-hand trajectory','One illustrative stochastic replication for '+safe(s.name)+' under '+safe(policyName(choice.strategy))+'.',svgLine([points.map(x=>x.stock),points.map(x=>x.demand)],{labels:['On-hand units','Daily demand'],format:v=>fmt(v,0),colors:['#7eebc5','#86b2f8']}))}${panel('SKU unit economics','Values are declared inputs and illustrative modeled outputs.',`<div class="method"><b>Unit acquisition / selling price</b><br>${money(s.unit_cost)} / ${money(s.sell_price)}</div><div class="method"><b>Shortage penalty / unit</b><br>${money(s.shortage_penalty)}</div><div class="method"><b>Annual holding cost rate</b><br>${fmt(s.holding_rate*100,1)}%</div><div class="method"><b>Relevant cost / horizon</b><br>${money(p.cost)} (${money(p.holding)} holding + ${money(p.ordering)} ordering + ${money(p.shortage)} shortages)</div>`)}</div>`;}
function data(){const columns=CORE.fields.join(',');const template='sku,name,category,avg_daily,std_daily,lead_days,unit_cost,sell_price,holding_rate,order_cost,shortage_penalty,capacity,opening_stock\nDEMO01,Sample Widget,Example,12,4,5,8,14,0.23,44,12,420,90\nDEMO02,Sample Pack,Example,19,5,7,16,24,0.27,70,18,510,100\n';return `<div class="cols">${panel('Import a custom assortment','Upload a .csv file with 2–25 SKUs. Invalid imports preserve the current dataset.',`<div class="filebox"><div class="control"><label for="upload">Choose a local CSV file</label><input type="file" id="upload" accept=".csv,text/csv"/></div><p class="hint" style="margin-top:12px">Maximum file size: 250 KB. The file is analyzed in your browser and never transmitted by this application.</p></div>${lastImport?`<div class="info ${importError?'danger':''}" style="margin-top:13px">${safe(lastImport)}</div>`:''}<div class="note">Required columns: <code>${safe(columns)}</code></div>`,`<button class="btn sm" data-export="template" data-action="download">↓ Template CSV</button>`)}${panel('Export reproducible evidence','The exports reflect the active scenario, simulation seed and input configuration.',`<div class="stack" style="gap:9px">${[['audit','Full simulation audit · JSON'],['policies','Policy comparison · CSV'],['skus','SKU diagnostics · CSV'],['traces','Inventory trajectory · CSV'],['dataset','Current assortment · CSV'],['report','Executive report · Markdown'],['template','CSV import template']].map(([key,title])=>`<button class="btn" style="text-align:left" data-action="download" data-export="${key}">↓ &nbsp; ${title}</button>`).join('')}</div>`)}</div>${panel('Current input inventory','The current simulated SKU parameters. All values can be updated by importing a CSV.',`<div class="tablewrap"><table><thead><tr><th>SKU</th><th>Item</th><th>Category</th><th>Daily μ</th><th>Daily σ</th><th>Lead days</th><th>Capacity</th><th>Unit cost</th></tr></thead><tbody>${items.map(s=>`<tr><td>${safe(s.sku)}</td><td>${safe(s.name)}</td><td>${safe(s.category)}</td><td>${fmt(s.avg_daily,1)}</td><td>${fmt(s.std_daily,1)}</td><td>${s.lead_days}</td><td>${s.capacity}</td><td>${money(s.unit_cost)}</td></tr>`).join('')}</tbody></table></div>`)}`;}
function methods(){return `<div class="cols equal">${panel('Mathematical method','Transparent, documented discrete-time stochastic simulation.',`<div class="method"><b>Demand generation</b><br>Daily demand = max(0, round[scaled mean × weekly / seasonal factors + scaled standard deviation × standard normal shock]). Each replication uses a deterministic seeded PRNG.</div><div class="method"><b>Supply delays</b><br>Every new order has a nominal item lead time plus a sampled integer delay from zero to maximum leadShock.</div><div class="method"><b>Inventory position</b><br>Stock on hand + units in transit. If at or below reorder point, place an order toward the order-up-to target subject to a static stock-capacity approximation.</div><div class="method"><b>Simulation service level</b><br>Fill rate = units sold / units demanded. Unsatisfied demand is lost, not backordered.</div><div class="method"><b>Relevant cost</b><br>Daily carrying cost + fixed ordering cost + unsatisfied units × shortage penalty.</div><div class="method"><b>Comparison</b><br>Identical demand paths and potential delays across Lean, Balanced and Resilient. Lowest expected relevant cost is selected only among presets meeting the mean fill target.</div>`) }${panel('Assumptions and boundaries','Disclosures that must accompany any interpretation.',`<div class="method"><b>Not a live warehouse integration</b><br>All initial products and demand curves are synthetic. No ERP connection or real-world inventory update is performed.</div><div class="method"><b>No unconditional optimum</b><br>Only three preset policies are benchmarked. The displayed lowest-cost feasible policy is not a globally optimal mixed-integer solution.</div><div class="method"><b>Capacity approximation</b><br>The policy caps inventory position at capacity at order time. Multiple delayed deliveries could exceed physical storage capacity at receipt; warehouse-level inbound capacity is not modeled.</div><div class="method"><b>Independent SKU models</b><br>No shared purchasing budget, supplier constraints, discounts, substitution or correlated demand among products is modeled.</div><div class="method"><b>Monte Carlo uncertainty</b><br>Simulation percentiles depend on the synthetic generator and sample count. No real data forecast calibration, causal inference or statistical guarantee is implied.</div><div class="method"><b>Privacy and persistence</b><br>All calculations run locally in the browser. Imported files and scenario edits are lost on reload unless exported.</div>`)}</div>${panel('Reproduction settings','Inputs recorded with exported audits.',`<div class="tablewrap"><table><thead><tr><th>Parameter</th><th>Value</th><th>Parameter</th><th>Value</th></tr></thead><tbody><tr><td>Random seed</td><td>${conf.seed}</td><td>Replications</td><td>${conf.reps}</td></tr><tr><td>Horizon</td><td>${conf.horizon} days</td><td>Demand multiplier</td><td>${fmt(conf.demandMultiplier,2)}×</td></tr><tr><td>Lead disruption</td><td>${conf.leadShock} days</td><td>Holding multiplier</td><td>${fmt(conf.holdingMultiplier,2)}×</td></tr><tr><td>Minimum fill rate</td><td>${pct(conf.targetFill)}</td><td>SKUs</td><td>${items.length}</td></tr></tbody></table></div>`)}`;}
function render(){const titles=PAGE[page];$('nav').innerHTML=links.map(([k,em,title])=>`<button data-page="${k}" class="${page===k?'active':''}"><span class="em">${em}</span>${title}</button>`).join('');$('where').textContent=titles[0];$('heading').textContent=titles[0];$('summary').textContent=titles[1];$('scenario').innerHTML=`<option value="custom" ${preset===-1?'selected':''}>${preset===-1?'Custom imported dataset':'Choose example'}</option>`+PRESETS.map((p,i)=>`<option value="${i}" ${i===preset?'selected':''}>${safe(p.name)}</option>`).join('');$('reps').textContent=conf.reps+' simulations';$('count').textContent=items.length+' items · '+conf.horizon+' days';$('view').innerHTML=({overview,simulator,policies,products,data,methods}[page])();}
function toast(msg,error=false){const el=$('toast');el.className='toast'+(error?' err':'');el.textContent=msg;clearTimeout(toast.timer);toast.timer=setTimeout(()=>el.classList.add('hidden'),3500);}
function save(name,text,mime){const blob=new Blob([text],{type:mime}),url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),2000);}
const filename='stockpilot-'+(preset>=0?PRESETS[preset].name.toLowerCase().replace(/[^a-z0-9]+/g,'-'):'custom');
function exportKind(kind){const base=filename,focus=active();if(kind==='audit')return save(base+'-audit.json',JSON.stringify({generatedAt:new Date().toISOString(),title:'StockPilot illustrative inventory audit',dataLabel:preset>=0?PRESETS[preset].name:'Custom imported data',warning:'Simulation-based analysis only; not real supplier forecasts or guaranteed optimal inventory decisions.',config:conf,items,policies:result.policies.map(({strategy,fill,fillP10,cost,costP90,contribution,lost,feasible,items})=>({strategy,fill,fillP10,cost,costP90,contribution,lost,feasible,items})),bestFeasiblePolicy:result.best?.strategy??null},null,2),'application/json');if(kind==='dataset')return save(base+'-assortment.csv',CORE.toCSV(items,CORE.fields),'text/csv');if(kind==='template')return save('stockpilot-import-template.csv',CORE.toCSV([{sku:'DEMO01',name:'Sample Widget',category:'Example',avg_daily:12,std_daily:4,lead_days:5,unit_cost:8,sell_price:14,holding_rate:.23,order_cost:44,shortage_penalty:12,capacity:420,opening_stock:90},{sku:'DEMO02',name:'Sample Pack',category:'Example',avg_daily:19,std_daily:5,lead_days:7,unit_cost:16,sell_price:24,holding_rate:.27,order_cost:70,shortage_penalty:18,capacity:510,opening_stock:100}],CORE.fields),'text/csv');if(kind==='policies')return save(base+'-policies.csv',CORE.toCSV(result.policies.map(({strategy,fill,fillP10,cost,costP90,contribution,lost,feasible})=>({strategy,fill,fillP10,cost,costP90,contribution,lost,feasible})),['strategy','fill','fillP10','cost','costP90','contribution','lost','feasible']),'text/csv');if(kind==='skus')return save(base+'-skus.csv',CORE.toCSV(result.policies.flatMap(p=>p.items.map(o=>({strategy:p.strategy,sku:o.sku,name:o.name,reorder:o.reorder,upTo:o.upTo,fill:o.fill,cost:o.cost,shortage:o.shortage,holding:o.holding,ordering:o.ordering}))),['strategy','sku','name','reorder','upTo','fill','cost','shortage','holding','ordering']),'text/csv');if(kind==='traces')return save(base+'-trajectory.csv',CORE.toCSV(result.policies.flatMap(p=>p.snapshots.flatMap((arr,i)=>arr.map(o=>({policy:p.strategy,sku:items[i].sku,...o})))),['policy','sku','day','stock','demand','lost','arriving']),'text/csv');if(kind==='report'){let b=result.best;return save(base+'-report.md',`# StockPilot | Inventory simulation report\n\nCreated ${new Date().toISOString()}\n\n## Scope\n\n- Scenario: ${preset>=0?PRESETS[preset].name:'Custom CSV'}\n- Seed: ${conf.seed}\n- Replications: ${conf.reps}\n- Horizon: ${conf.horizon} days\n- Demand multiplier: ${conf.demandMultiplier}\n- Maximum lead-time delay: ${conf.leadShock} days\n- Minimum mean fill rate: ${pct(conf.targetFill)}\n\n## Policy comparison\n\n${result.policies.map(p=>`- **${policyName(p.strategy)}**: fill ${pct(p.fill)}; relevant cost ${money(p.cost)}; expected unmet demand ${fmt(p.lost,0)} units; target ${p.feasible?'met':'not met'}`).join('\n')}\n\n## Decision\n\n${b?'Lowest estimated cost among predefined policies meeting the mean service target: '+policyName(b.strategy):'No predefined policy meets the mean fill-rate target.'}\n\n## Important caveats\n\n- Demand and lead-time paths are simulated, not measured forecasts.\n- Relative cost uses input shortage penalties, not proven accounting loss.\n- Three preset policies only, not a global optimum.\n- Physical receiving capacity, SKU correlations and purchasing budgets are not modeled.\n- Imported datasets remain local to the browser.\n`,'text/markdown');}}
$('nav').addEventListener('click',e=>{const el=e.target.closest('[data-page]');if(el){page=el.dataset.page;$('side').classList.remove('open');render();}});
$('view').addEventListener('click',e=>{const b=e.target.closest('[data-action]');if(!b)return;try{if(b.dataset.action==='download'){exportKind(b.dataset.export);toast('Export prepared.');}else if(b.dataset.action==='run'){const next={...conf};for(const k of ['demandMultiplier','leadShock','holdingMultiplier','targetFill','seed','horizon']){const el=$(k);next[k]=Number(el.value);}const updated=CORE.analyze(items,next);conf=next;result=updated;render();toast('Paired simulation completed.');}else if(b.dataset.action==='reset-config'){conf=CORE.config({});result=CORE.analyze(items,conf);render();toast('Assumptions restored.');}}catch(err){toast(err.message,true);}});
$('view').addEventListener('input',e=>{const t=e.target;if(['demandMultiplier','leadShock','holdingMultiplier','targetFill'].includes(t.id)){const el=$(t.id+'Value');if(el)el.textContent=t.id==='targetFill'?fmt(Number(t.value)*100,1)+'%':fmt(Number(t.value),t.id==='leadShock'?0:2)+(t.id==='leadShock'?' days':'×');}});
$('view').addEventListener('change',async e=>{const el=e.target;if(el.id==='activePolicy'){document.body.dataset.activePolicy=el.value;render();}else if(el.id==='sku'){sku=el.value;render();}else if(el.id==='upload'&&el.files?.length){const file=el.files[0];try{if(file.size>250000)throw Error('File exceeds 250 KB.');const rows=CORE.parseCSV(await file.text());const nextItems=CORE.validateRows(rows);const nextResult=CORE.analyze(nextItems,conf);items=nextItems;result=nextResult;preset=-1;sku=items[0].sku;importError=false;lastImport='Validated and imported '+items.length+' products. Previous data replaced only after all checks passed.';render();toast('Custom dataset imported.');}catch(err){importError=true;lastImport='Import rejected: '+err.message+' Previous data preserved.';render();toast(lastImport,true);}}});
$('scenario').addEventListener('change',e=>{const v=e.target.value;if(v==='custom')return;try{const n=Number(v);const next=CORE.validateRows(PRESETS[n].items),updated=CORE.analyze(next,conf);items=next;result=updated;preset=n;sku=items[0].sku;lastImport='';page='overview';render();toast('Scenario loaded.');}catch(err){toast(err.message,true);}});
$('mobileMenu').addEventListener('click',()=>$('side').classList.toggle('open'));
$('exportTop').addEventListener('click',()=>{exportKind('audit');toast('Audit JSON downloaded.');});
document.body.dataset.activePolicy='balanced';render();
})();
</script></body></html>