Customers come and go: contracts, renewals at the market price, growth, haggles and leaving (#178)

Every customer now signs for a term (enterprise and hosting 1-3 years, wholesale and circuits 2-5,
fiber pairs 10-20). When it ends most renew at today's bandwidth price, happy ones often grow to
the next size, a few with competitors around ask for a discount 30 days ahead (match, meet halfway
or let go in Deals; no answer matches), and some leave: unhappy ones because of the service, others
acquired, bust, insourced, moved (they stay if you have a POP there), multihomed, project ended,
a cheaper bid, or now and then one of the odder reasons (never more than one every 60 days).

The bandwidth market is flat for six months, then about 10% cheaper a year, slowed by dearer
hardware, moving in a slow three-year cycle and pushed up during a shortage. New offers and
renewals are priced in it; one renewal moves a price at most 25% down or 10% up.

Nothing happens in a first term. Rolls are hashes of the customer and its term, never Math.random,
so seeded games keep their stream. Old saves get renewals spread over the next year. Happy
customers of a year or more send a referral about every six weeks. The dashboard's Customers tab
shows customers won and lost each month and why, renewals due and the market; customer rows show
the contract end.

The differential fuzz now leaves out state fields only this checkout has, so a new feature's state
does not fail the comparison with main while everything both games share must still match.
This commit is contained in:
Frederic Jung 2026-11-05 08:15:46 +01:00
parent b8d313b029
commit 8841fdacb9
No known key found for this signature in database
24 changed files with 859 additions and 19 deletions

View file

@ -17,6 +17,7 @@ function hwShockStart(){const k=pick(Object.keys(HW_SHOCK)),n=45+Math.floor(Math
function hwCard(){if(!S||!rule('market')||(S.day<=HW_FREE&&!hwShock()&&!hwLock()))return '';const t=hwTrend(S.day),s=hwShock(),l=hwLock();
return `<div class="ibx"><div class="nm">📦 ${tr('common.supply_chain')}</div>
<div class="kv"><span>${tr('common.hardware_prices')}</span><b>${t>1.005?tr('supply_chain.p_since_you_started',{p:pct(t-1)}):tr('supply_chain.as_when_you_started')}</b></div>
<div class="kv"><span>${tr('lifecycle.bandwidth_prices')}</span><b>${mktTxt()}</b></div>
${s?`<div class="kv"><span>${tr('common.shortage')}</span><b>${tr('supply_chain.what_p_n_days_left',{what:tr(HW_SHOCK[s.k].n),p:pct(s.mul-1),n:s.until-S.day})}</b></div>`:''}
${l?`<div class="kv"><span>${tr('common.price_lock')}</span><b>${tr('supply_chain.until_date_at_p',{date:dateStr(l.until),p:pct(l.mul-1)})}</b></div>`
:`<p class="meta">${tr('supply_chain.routers_optics_and_new_builds_at')}</p><div class="btns">${btn(tr('supply_chain.lock_prices_for_a_year_cost',{cost:fmt$(hwLockCost())}),'hwLock',{},'sm',S.cash<hwLockCost())}</div>`}</div>`;}

View file

@ -31,6 +31,6 @@ function brTick(){for(const l of S.links){const L=l.list;if(!L||l.kind!=='df'||!
function brSell(l,t,n){const T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;};
const o=fiberOffer(t,l,nm,0.9);if(t==='wwave'){o.slots=n;o.rate=wwRate(l,n,0.9);o.what=wwWhat(l,n);}
const more=t==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===l.id&&b.name===o.name);
if(more){more.slots=(more.slots||0)+n;more.rate+=o.rate;more.what=wwWhat(l,more.slots);}else S.biz.push(offerCustomer(o));
if(more){more.slots=(more.slots||0)+n;more.rate+=o.rate;more.what=wwWhat(l,more.slots);}else S.biz.push(clSign(offerCustomer(o)));
toast(tr('broker.sold',{name:esc(o.name),what:esc(t==='wwave'?wwWhat(l,n):o.what),price:fmt$(o.rate)}),'good');
floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');}

View file

@ -55,7 +55,9 @@ function sanitize(s){
for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('common.your_ix')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);}
const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity));
const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;};
{const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>unpackBiz(fixBiz(b),ids));}s.offers=s.offers.filter(okBiz).map(fixBiz);
{const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz);
// Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally.
for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);
// Sponsorships and capacity conferences (#168): registrations are true or 'sp', the glow and the pending deals are checked.
for(const k of Object.keys(s.confReg))s.confReg[k]=s.confReg[k]==='sp'?'sp':!!s.confReg[k];
if(s.conf){const c=s.conf;if(typeof c!=='object'||!own(REG,c.reg))s.conf=null;else s.conf={until:num(c.until,0),reg:c.reg,name:String(c.name||'').slice(0,40),sp:!!c.sp};}

View file

@ -0,0 +1,148 @@
/* ---------- Customers come and go (#178) ----------
Every customer signs for a term. When it ends, most renew at today's market price, happy ones often grow, a few haggle
for a discount, and some leave for reasons that are not your fault (or, when they were unhappy, because they were).
Nothing changes during a customer's first term. Every roll is a hash of the customer and its term, never
Math.random, so seeded games and tests keep their random stream. */
/* The bandwidth market: what a Gbps sells for, 1 when you start. Flat for the first six months, then about 10% cheaper
a year (transit really does fall: 11–17% a year in the big hubs), slowed by dearer hardware, moving up and down in a
slow three-year cycle, and pushed up while a shortage lasts. Without the market rule it stays at 1. */
const MK_YR=0.10,MK_FREE=180,MK_FLOOR=0.3,MK_SHOCK={opt:1.15,rt:1.1,build:1.08};
function mktBase(d){if(d<=MK_FREE)return 1;const y=(d-MK_FREE)/365;
return Math.max(MK_FLOOR,Math.pow(1-MK_YR,y)*Math.sqrt(hwTrend(d))*(1+0.06*Math.sin(2*Math.PI*y/3)));}
function mkt(){if(!S||!rule('market'))return 1;const s=hwShock();return mktBase(S.day)*(s?MK_SHOCK[s.k]||1:1);}
// Terms in months: enterprise and hosting 1–3 years, wholesale and circuits 2–5, IRUs and fiber pairs 10–20.
const CL_TERMS={ip:[12,24,36],whole:[24,36,48,60],iru:[120,180,240]};
// Events, capacity deals and scripted scenario customers have their own endings.
const clKind=t=>{const T=BIZ_T[t];if(!T||T.event||T.cap)return null;if(t==='dfpair'||t==='pairs')return 'iru';return T.l2||T.fiber||t==='isp'||t==='gpu'?'whole':'ip';};
const clOn=b=>!!b&&!b.scripted&&!!clKind(b.type);
// A stable roll in [0,1) for this customer, this term and this question.
const clR=(b,q)=>(hstr(((S&&S.asn)||0)+'|'+b.id+'|'+b.te+'|'+q)%100000)/100000;
const clPick=(a,b,q)=>a[Math.floor(clR(b,q)*a.length)];
function clTerm(b,from){const m=clPick(CL_TERMS[clKind(b.type)],{id:b.id,te:from},'term');return from+Math.round(m*365/12);}
// What this customer's contract would be priced at today: its price moved by the market since it was signed.
// A renewal moves at most 25% down or 10% up at once, so an old save is not repriced in one go.
const clFair=b=>rule('market')&&b.mk>0?Math.round(b.rate*clamp(mkt()/b.mk,0.75,1.1)):b.rate;
// Competition where the customer is: carriers selling transit there (a fiber or circuit customer counts both ends).
const clComp=b=>{const cs=bCities(b);let n=0;for(const n2 of NETS)if(cs.some(c=>sellsAt(n2,c)))n++;return n;};
// Why they leave when it is not your fault: which reasons fit which customers. Moved and multihomed may keep them.
const CL_WHY={
acq:{l:N_('lifecycle.why_acquired'),left:N_('lifecycle.left_acquired'),ok:()=>true},
bust:{l:N_('lifecycle.why_bust'),left:N_('lifecycle.left_bust'),ok:t=>['gpu','stream','game','cgame','metav','ai','agi','hft','provedor','dia','host','mars'].includes(t)},
insrc:{l:N_('lifecycle.why_insourced'),left:N_('lifecycle.left_insourced'),ok:t=>['isp','hyper','onramp','provedor','edu','sov','aiwan','stream'].includes(t)},
moved:{l:N_('lifecycle.why_moved'),left:N_('lifecycle.left_moved'),ok:t=>{const T=BIZ_T[t];return !T.l2&&!T.fiber&&!T.nni;}},
multi:{l:N_('lifecycle.why_multihomed'),left:N_('lifecycle.left_multihomed'),ok:t=>{const T=BIZ_T[t];return !T.l2&&!T.fiber;}},
ended:{l:N_('lifecycle.why_project_ended'),left:N_('lifecycle.left_project_ended'),ok:t=>{const T=BIZ_T[t];return T.l2||T.fiber||t==='bulk';}},
cheap:{l:N_('lifecycle.why_cheaper_bid'),left:N_('lifecycle.left_cheaper'),ok:()=>true},
sad:{l:N_('lifecycle.why_unhappy'),ok:()=>false},
odd:{l:N_('lifecycle.why_other'),ok:()=>false},
};
// The other reasons: now and then (never more than once every two months) a customer leaves for one of these.
const CL_ODD=[N_('lifecycle.odd_asn_six'),N_('lifecycle.odd_bad_holiday'),N_('lifecycle.odd_rdns'),N_('lifecycle.odd_too_many_feet'),N_('lifecycle.odd_dead_beef'),N_('lifecycle.odd_looking_glass'),
N_('lifecycle.odd_communities'),N_('lifecycle.odd_quadrant'),N_('lifecycle.odd_spreadsheet_cell'),N_('lifecycle.odd_fewer_vendors'),N_('lifecycle.odd_the_cloud'),N_('lifecycle.odd_bought_thrice'),
N_('lifecycle.odd_alphabetical'),N_('lifecycle.odd_goat_farmer'),N_('lifecycle.odd_mate'),N_('lifecycle.odd_95th'),N_('lifecycle.odd_holiday_card'),N_('lifecycle.odd_raccoon'),N_('lifecycle.odd_espresso'),
N_('lifecycle.odd_landlord'),N_('lifecycle.odd_wrong_blue'),N_('lifecycle.odd_space'),N_('lifecycle.odd_4g_dongle'),N_('lifecycle.odd_center'),N_('lifecycle.odd_wireguard')];
const CL_ODD_GAP=60,CL_HAG_MAX=3,CL_MONTHS=24;
// The month's tally for the dashboard: won, renewed, grew, haggled and who left why.
function clNote(k,why){const C=S.cl||(S.cl={odd:-1e9,mo:[]}),c=cal(S.day),m=c.y*12+c.m;let e=C.mo[C.mo.length-1];
if(!e||e.m!==m){e={m,won:0,ren:0,grew:0,hag:0,lost:{}};C.mo.push(e);if(C.mo.length>CL_MONTHS)C.mo.shift();}
if(k==='lost')e.lost[why]=(e.lost[why]||0)+1;else e[k]=(e[k]||0)+1;}
// A new customer: its first term and the market it signed in.
function clSign(b){if(!clOn(b))return b;b.mk=b.mk>0?b.mk:mkt();b.te=clTerm(b,S.day);clNote('won');return b;}
function clRenew(b,rate){b.rate=Math.max(0,Math.round(rate));b.mk=mkt();delete b.hag;delete b.hr;b.te=clTerm(b,b.te);}
function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);}
const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ ');
// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing.
function clGrow(b){const T=BIZ_T[b.type];if(T.fiber)return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=up||b.bw*2;return true;}
// Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says.
function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))};
if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;}
const C=S.cl;if(d-C.odd>=CL_ODD_GAP&&clR(b,'odd')<0.25){C.odd=d;clGone(b,'odd');out.lost.push(tr('lifecycle.left_odd',{...v,why:tr(clPick(CL_ODD,b,'oddline'))}));return;}
const ks=Object.keys(CL_WHY).filter(k=>CL_WHY[k].ok(b.type)),k=clPick(ks,b,'why');
if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;}
if(k==='moved'){const reg=CITY[b.city].reg,to=Object.keys(S.pops).filter(c=>c!==b.city&&CITY[c].reg===reg&&bizCity(c)).sort();
const c2=to.length&&clR(b,'stay')<0.5?clPick(to,b,'to'):null;
if(c2){const from=CITY[b.city].name;b.city=c2;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.moved_stays',{name:v.name,from:esc(from),to:esc(CITY[c2].name)}));return;}}
if(k==='multi'&&b.bw>=2){const keep=(T.opts||[]).filter(x=>x<=b.bw/2).pop()||b.bw/2;b.bw=keep;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.multihomed_keeps',{...v,bw:fmtG(b.bw)}));return;}
clGone(b,k);out.lost.push(tr(CL_WHY[k].left,v));}
/* A day of contracts, after the moods. 30 days before a term ends a customer with competitors around may ask for a
discount (at most three open at a time); at the end, the rest renew, grow or leave. An unanswered haggle renews at
the asked price. */
function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0);
const pat=rule('moods')==='patient'?0.5:1;
for(const b of S.biz.slice()){if(!b.te||!clOn(b))continue;
if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;}
if(d<b.te-30)continue;
if(d<b.te){if(b.hr===b.te)continue;b.hr=b.te;const comp=clComp(b),cf=Math.min(1,comp/6);
if(open<CL_HAG_MAX&&comp>=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(0.8+0.12*clR(b,'ask')));
if(ask>0&&ask<b.rate){b.hag={rate:ask,until:b.te};open++;clNote('hag');out.hag.push(b);}}
continue;}
const cf=Math.min(1,clComp(b)/6),u=(100-b.mood)/100,leave=(0.04+0.08*cf+0.35*u*u)*pat;
if(clR(b,'leave')<leave){clLeave(b,d,out);continue;}
const g=clR(b,'grow');if((b.mood>=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}}
clRenew(b,clFair(b));clNote('ren');out.ren++;}
clNews(out);clReferral(d);}
// What the day says: haggles one by one (they want an answer), the rest in a few lines so a big network is not a wall of toasts.
function clNews(out){
for(const b of out.hag){const was=bizMo(b),now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate;
toast(tr('lifecycle.haggle',{name:esc(b.name),city:esc(clWhere(b)),price:fmt$(now),p:pct(1-now/Math.max(1,was)),n:b.hag.until-S.day}),'',[{l:tr('common.deals'),act:'leftTab',args:{t:'deals'}}],{a:'cust',v:b.id});}
const few=(list,kind)=>{for(const t of list.slice(0,3))toast(t,kind);if(list.length>3)toast(trn('lifecycle.n_more',list.length-3),kind);};
few(out.ok,'good');few(out.lost,'');
if(out.ren)toast(trn('lifecycle.n_renewed',out.ren,{p:mktTxt()}),'');}
const mktTxt=()=>{const m=mkt();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});};
/* Growth by word of mouth: about every six weeks the happiest long-standing customer (a year or more, 90%+ happy)
tells someone like them, who shows up in Deals asking for the smallest size at today's price. */
const CL_REF=['dia','game','host','isp','stream','edu','scrub','provedor','gpu','cgame','metav'];
function clReferral(d){if(d%45!==0||S.offers.length>=6)return;
const b=S.biz.filter(x=>clOn(x)&&CL_REF.includes(x.type)&&x.mood>=90&&d-(x.since||0)>=365&&bizCity(x.city)&&lvl()>=(BIZ_T[x.type].lv||1)).sort((a,c)=>c.mood-a.mood||(a.since||0)-(c.since||0)||(a.id<c.id?-1:1))[0];
if(!b||S.offers.some(o=>o.ref===b.id))return;const T=BIZ_T[b.type],list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));if(!list.length)return;
const name=clPick(list,{id:b.id,te:d},'refname');useName(name);
S.offers.push({id:uid(),city:b.city,city2:null,name,type:b.type,bw:(T.opts||[1])[0],rate:Math.round((CITY[b.city].au?T.rate*AU_ARPU:T.rate)*mkt()),mk:mkt(),reqs:[],exp:d+40,ref:b.id,refN:b.name});}
// New offers are priced at today's market (spawnOffer and friends price at 1; this moves them).
function mktPrice(from){const m=mkt();for(let i=from;i<S.offers.length;i++){const o=S.offers[i];if(o.mk)continue;o.mk=m;if(m!==1){o.rate=Math.round(o.rate*m);if(o.fee)o.fee=Math.round(o.fee*m);}}}
const clHags=()=>S?S.biz.reduce((a,b)=>a+(b.hag?1:0),0):0;
// The renewals waiting for an answer, at the top of Deals.
function clDealsHtml(){const hs=S.biz.filter(b=>b.hag).sort((a,b)=>a.hag.until-b.hag.until);if(!hs.length)return '';
return `<h3 class="sub4">${tr('lifecycle.renewals')}</h3><p class="meta" style="margin:0 0 6px">${tr('lifecycle.unanswered_matches')}</p>`+hs.map(b=>{const now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate,was=bizMo(b);
return `<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(BIZ_T[b.type].l)} · ${esc(clWhere(b))} · ${tr('ui.n_d_left',{n:b.hag.until-S.day})}</div>
<div class="meta">${tr('lifecycle.wants_price',{was:fmt$(was),price:fmt$(now),p:pct(1-now/Math.max(1,was))})}</div>
<div class="btns">${btn(tr('lifecycle.match'),'renewMatch',{id:b.id},'green sm')}${btn(tr('lifecycle.meet_halfway'),'renewMeet',{id:b.id},'sm')}${btn(tr('lifecycle.let_them_go'),'renewLet',{id:b.id},'ghost sm')}</div></div></div>`;}).join('');}
// The contract line on a customer row.
const clTermTxt=b=>clOn(b)&&b.te?(b.hag?tr('lifecycle.renewal_haggle',{date:dateStr(b.te)}):tr('lifecycle.contract_until',{date:dateStr(b.te)})):'';
/* Dashboard: customers won and lost per month (and why), renewals coming up, and the bandwidth market. */
function clPanel(){const C=S.cl||{mo:[]},mo=C.mo.slice(-12);const soon=S.biz.filter(b=>clOn(b)&&b.te&&b.te-S.day<=30&&b.te>=S.day).length;
const sum=k=>mo.reduce((a,e)=>a+(k==='lost'?Object.values(e.lost).reduce((x,y)=>x+y,0):e[k]||0),0),why={};for(const e of mo)for(const k in e.lost)why[k]=(why[k]||0)+e.lost[k];
let h=`<div class="panel2" id="churnSec" style="margin-top:12px"><h3>${tr('lifecycle.won_and_lost')}</h3><p class="note" style="margin-top:0">${tr('lifecycle.won_and_lost_note')}</p>
<div class="dgrid" style="margin:0 0 8px"><div class="tile"><div class="lbl">${tr('lifecycle.won')}</div><div class="val">${sum('won')}</div><div class="sub">${tr('lifecycle.last_12_months')}</div></div>
<div class="tile"><div class="lbl">${tr('lifecycle.lost')}</div><div class="val" style="color:${sum('lost')>sum('won')?'var(--bad)':'inherit'}">${sum('lost')}</div><div class="sub">${trn('lifecycle.n_grew',sum('grew'))}</div></div>
<div class="tile"><div class="lbl">${tr('lifecycle.renewals_soon')}</div><div class="val">${soon}</div><div class="sub">${tr('lifecycle.next_30_days')}</div></div>
<div class="tile"><div class="lbl">${tr('lifecycle.bandwidth_market')}</div><div class="val">${Math.round(mkt()*100)}</div><div class="sub">${mktTxt()}</div></div></div>`;
if(mo.length){const max=Math.max(1,...mo.map(e=>Math.max(e.won,Object.values(e.lost).reduce((x,y)=>x+y,0)))),W=600,H=120,mid=H/2,bw=W/12;
let g=`<line x1="0" x2="${W}" y1="${mid}" y2="${mid}" stroke="#D5DEEC"/>`;
mo.forEach((e,i)=>{const lost=Object.values(e.lost).reduce((x,y)=>x+y,0),x=(i+12-mo.length)*bw+bw*0.2,w=bw*0.6,hw=(mid-12)*e.won/max,hl=(mid-12)*lost/max;
g+=`<rect x="${x}" y="${mid-hw}" width="${w}" height="${hw}" fill="#16A866" rx="2"><title>${MONTHS[e.m%12]} · ${tr('lifecycle.won')} ${e.won}</title></rect><rect x="${x}" y="${mid}" width="${w}" height="${hl}" fill="#FF4D5E" rx="2"><title>${MONTHS[e.m%12]} · ${tr('lifecycle.lost')} ${lost}</title></rect><text x="${x+w/2}" y="${H-1}" text-anchor="middle" font-size="9" fill="#55608A" font-weight="700">${MONTHS[e.m%12]}</text>`;});
h+=`<svg class="chart" viewBox="0 0 ${W} ${H}" role="img" aria-label="${tr('lifecycle.won_and_lost')}">${g}</svg>`;}
const ks=Object.keys(why).sort((a,b)=>why[b]-why[a]);
h+=ks.length?`<h4 class="sub4">${tr('lifecycle.why_they_left')}</h4>`+ks.map(k=>`<div class="kv"><span>${tr(CL_WHY[k]?CL_WHY[k].l:CL_WHY.odd.l)}</span><b>${why[k]}</b></div>`).join(''):`<p class="empty">${tr('lifecycle.nobody_left_yet')}</p>`;
return h+`</div>`;}
/* Saves from before contracts: renewals spread over the next year (from the customer's id, so they do not all fall on
one day), and the market they signed in from the day they signed. */
function clFix(s,b){if(b.scripted||!clKind(b.type)){delete b.te;delete b.mk;delete b.hag;delete b.hr;return b;}
const day=Math.max(0,Math.floor(+s.day||0)),ok=v=>typeof v==='number'&&isFinite(v);
if(!ok(b.te)||b.te<day-1||b.te>day+365*21)b.te=day+30+hstr('te|'+b.id)%335;b.te=Math.floor(b.te);
if(!ok(b.mk)||b.mk<=0||b.mk>5)b.mk=mktBase(Math.max(0,Math.floor(+b.since||0)));
if(b.hag&&(typeof b.hag!=='object'||!ok(b.hag.rate)||b.hag.rate<0||!ok(b.hag.until)))delete b.hag;else if(b.hag)b.hag={rate:Math.round(b.hag.rate),until:Math.floor(Math.min(b.hag.until,b.te))};
if(b.hr!==undefined&&b.hr!==b.te)delete b.hr;return b;}
function clFixState(s){const C=s.cl&&typeof s.cl==='object'&&!Array.isArray(s.cl)?s.cl:{},o={odd:typeof C.odd==='number'&&isFinite(C.odd)?C.odd:-1e9,mo:[]};
if(Array.isArray(C.mo))for(const e of C.mo.slice(-CL_MONTHS)){if(!e||typeof e!=='object'||!Number.isInteger(e.m))continue;const n=v=>Math.max(0,Math.min(1e7,Math.floor(+v)||0)),lost={};
if(e.lost&&typeof e.lost==='object')for(const k in e.lost)if(own(CL_WHY,k))lost[k]=n(e.lost[k]);o.mo.push({m:e.m,won:n(e.won),ren:n(e.ren),grew:n(e.grew),hag:n(e.hag),lost});}
s.cl=o;}

View file

@ -57,6 +57,8 @@ function dayPost(d){
toast(tr('day_tick.name_is_furious_fix_service_in',{name:esc(b.name),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:'')+(paused?`<br><b>${tr('common.game_paused')}</b>`:''),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');}
else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('day_tick.name_is_getting_unhappy_happiness_p',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:''),'',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);}}
if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}
// contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js)
clDay(d);
// own IX members join
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<myFab(c).max){
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
@ -67,7 +69,7 @@ function dayPost(d){
// offers
S.offers=S.offers.filter(o=>o.exp>d);
brTick();
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1))spawnOffer();
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)){const n0=S.offers.length;spawnOffer();mktPrice(n0);}
// failures & events
// Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never.
let dirty=false;const cm=chaosMul();

View file

@ -12,8 +12,18 @@ Object.assign(ACT,{
const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name);
if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots);
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;}
S.offers=S.offers.filter(x=>x!==o);S.biz.push(customer);
S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;S.biz.push(clSign(customer));
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();},
decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();},
dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();},
});
/* The renewal haggle (#178, 75-customer-lifecycle.js): match their price, meet halfway (they take it about two times
in three), or let them go. */
function clHagOf(id){const b=S.biz.find(x=>x.id===id);return b&&b.hag?b:null;}
Object.assign(ACT,{
renewMatch:({id})=>{const b=clHagOf(id);if(!b)return;clRenew(b,b.hag.rate);clNote('ren');toast(tr('lifecycle.matched',{name:esc(b.name)}),'good');sfx('coin');after();},
renewMeet:({id})=>{const b=clHagOf(id);if(!b)return;const mid=Math.round((b.hag.rate+clFair(b))/2);
if(clR(b,'meet')<0.65){clRenew(b,mid);clNote('ren');toast(tr('lifecycle.meet_yes',{name:esc(b.name),price:fmt$(BIZ_T[b.type].fiber?b.rate:b.bw*b.rate)}),'good');sfx('coin');}
else{clGone(b,'cheap');toast(tr('lifecycle.meet_no',{name:esc(b.name)}),'bad');sfx('err');}after();},
renewLet:({id})=>{const b=clHagOf(id);if(!b)return;clGone(b,'cheap');toast(tr('lifecycle.let_go',{name:esc(b.name)}),'');after();},
});

View file

@ -32,7 +32,7 @@ function renderLeft(){checkLayer();
renderTabbar();
if(!S||pzOn()){L.hidden=true;return;}L.hidden=false;
const ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length;
const tabs=[['goals',`<span class="tl">${tr('common.goals')}</span><span class="cnt">${ndone}/${GOALS.length}</span>`],['deals',`<span class="tl">${tr('common.deals')}</span>${S.offers.length?`<span class="cnt">${S.offers.length}</span>`:''}`],['noc',`<span class="tl">NOC</span>${S.inc.length?`<span class="cnt red dot" aria-hidden="true"></span>`:''}`],['nets',`<span class="tl">${tr('common.networks')}</span>`]];
const tabs=[['goals',`<span class="tl">${tr('common.goals')}</span><span class="cnt">${ndone}/${GOALS.length}</span>`],['deals',`<span class="tl">${tr('common.deals')}</span>${S.offers.length+clHags()?`<span class="cnt">${S.offers.length+clHags()}</span>`:''}`],['noc',`<span class="tl">NOC</span>${S.inc.length?`<span class="cnt red dot" aria-hidden="true"></span>`:''}`],['nets',`<span class="tl">${tr('common.networks')}</span>`]];
$('leftTabs').innerHTML=tabs.map(([k,l])=>`<button class="${UI.left===k?'on':''}" data-act="leftTab" data-args='{"t":"${k}"}'>${l}</button>`).join('')+(innerWidth<760?`<button data-act="toggleLeft" style="margin-left:auto" aria-label="${tr('common.close')}">×</button>`:'');
let h='';
if(UI.left==='goals'){
@ -42,11 +42,11 @@ function renderLeft(){checkLayer();
h+=badgeGrid();
}else if(UI.left==='deals'){
{const st=custStats();if(st.n)h+=`<div class="row" style="margin-bottom:8px"><div class="grow"><div class="nm">${tr('common.your_customers')} <span class="meta">${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}</span></div><div class="bar ${moodCls(st.avg)}"><i style="width:${st.avg}%"></i></div>${st.unhappy?`<div class="why">${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}</div>`:''}</div>${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}</div>`;}
h+=confSection()+seatSection();
h+=clDealsHtml()+confSection()+seatSection();
{const lv=S.lvl||1,nx=LEVELS[lv];h+=`<div class="inc" style="background:#FFF6CF"><div class="nm">${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}</div><div class="meta">${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}</div></div>`;}
if(!S.offers.length)h+=`<p class="empty">${tr('hud_and_panels.no_open_offers_right_now_businesses')}</p>`;
for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o);
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}</div>${spotWhy(o)}${bRisk(o)}${reqList(o)}
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}</div>${o.refN?`<div class="meta">${tr('lifecycle.referred_by',{name:esc(o.refN)})}</div>`:''}${spotWhy(o)}${bRisk(o)}${reqList(o)}
<div class="btns">${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}</div>${has?'':`<div class="why">${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div></div>`;}
}else if(UI.left==='noc'){
h+=`<div class="btns" style="margin-bottom:8px">${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${btn(tr('common.connections'),'connOpen',{},'')}${btn(tr('common.traceroute'),'trace',{},'')}${btn(`⚙️ ${tr('routing.routing_and_ddos')}${S.te&&!coreTE()?'<span class="cnt red dot" aria-hidden="true"></span>':''}`,'routingOpen',{},'')}</div>`;

View file

@ -37,7 +37,7 @@ function cityPanel(c){
h+=`</section><section><h3>${tr('common.business_customers')}</h3>`;
const bz=S.biz.filter(b=>bCities(b).includes(c));
if(!bz.length)h+=`<p class="empty">${tr('city_panel.no_businesses_yet_offers_pop_up')}</p>`;
for(const b of bz)h+=`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · <b style="color:var(--bad)">'+tr('city_panel.fiber_is_down')+'</b>':''}${BIZ_T[b.type].event&&eventLive(b)?` · <b>${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}</b>`:''}${b.type==='scrub'&&!hasScrub()?' · <b style="color:var(--bad)">'+tr('common.needs_a_scrubbing_center')+'</b>':''}${S.day-(b.since||0)<15?` · <b>${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}</b>`:''}</div>${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}<div class="bar ${b.mood<30?'bad':b.mood<65?'warn':''}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('common.happiness_p',{p:Math.round(b.mood)})}</div></div>${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}</div>`;
for(const b of bz)h+=`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · <b style="color:var(--bad)">'+tr('city_panel.fiber_is_down')+'</b>':''}${BIZ_T[b.type].event&&eventLive(b)?` · <b>${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}</b>`:''}${b.type==='scrub'&&!hasScrub()?' · <b style="color:var(--bad)">'+tr('common.needs_a_scrubbing_center')+'</b>':''}${S.day-(b.since||0)<15?` · <b>${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}</b>`:''}</div>${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}<div class="bar ${b.mood<30?'bad':b.mood<65?'warn':''}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('common.happiness_p',{p:Math.round(b.mood)})}</div></div>${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}</div>`;
h+=`</section>`+offersHere(c);
}else if(UI.tab==='up'){
h+=portNote(c)+latNote(c);

View file

@ -30,5 +30,5 @@ function custSection(){const F=UI.kf||{};let h=`<div class="panel2" id="custSec"
const trend=b=>b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' <span style="color:var(--eye)">▲</span>':' <span style="color:var(--bad)">▼</span>';
const sorts=[['mood',tr('common.happiness')],['mo',tr('common.per_month')],['name',tr('common.name')],['city',tr('common.where')]];
h+=`<div class="seg" style="margin-bottom:4px">${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}</div>`;
h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `<div class="row"><div class="grow"><div class="nm">${esc(b.name)} <span class="meta">${esc(BIZ_T[b.type].l)}</span></div><div class="meta">${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('common.price_mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}</div>${bRisk(b)}${why.length?`<div class="why">${why.map(esc).join(' · ')}</div>`:''}<div class="bar ${moodCls(b.mood)}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('common.happiness_p',{p:Math.round(b.mood)})}${trend(b)}</div></div>${btn(tr('common.open'),'custGo',{id:b.id},'ghost sm')}</div>`;}).join('');
h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `<div class="row"><div class="grow"><div class="nm">${esc(b.name)} <span class="meta">${esc(BIZ_T[b.type].l)}</span></div><div class="meta">${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('common.price_mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}${clTermTxt(b)?' · '+clTermTxt(b):''}</div>${bRisk(b)}${why.length?`<div class="why">${why.map(esc).join(' · ')}</div>`:''}<div class="bar ${moodCls(b.mood)}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('common.happiness_p',{p:Math.round(b.mood)})}${trend(b)}</div></div>${btn(tr('common.open'),'custGo',{id:b.id},'ghost sm')}</div>`;}).join('');
return h+listMore('cust',rows.length,n=>trn('customers.n_more_customer',n))+`</div>`;}

View file

@ -18,7 +18,7 @@ function renderDash(){checkLayer();
{const e={c:0,p:0,ix:0,t:0};let w=0;for(const n of NETS)if(n.tail){const x=R.netEg[n.id];if(x)for(const k in e)e[k]+=x[k]||0;w+=R.demTo[n.id]||0;}nets.push(row({id:'_tail',name:tr('dashboard.the_long_tail_n_small_networks',{n:NETS.filter(n=>n.tail).length}),asn:'many',type:'eye',col:'#8A93B8'},e,w));}
for(let i=nets.length-1;i>=0;i--)if(!(nets[i].t>0.01||(!filt&&nets[i].want>0.01)))nets.splice(i,1);
{const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (A<B?-1:A>B?1:0)*dir||b.t-a.t;});}
if(DT==='cust')h+=custSection();
if(DT==='cust')h+=clPanel()+custSection();
if(DT==='conn')h+=connSection();
if(DT==='traffic')h+=`<div class="btns">${btn(tr('ops.standing_orders'),'opsOpen',{},'sm')}</div>`;
if(DT==='traffic')h+=`<div class="panel2" style="margin-top:12px"><h3>${tr('dashboard.traffic_by_network_asn')}</h3><p class="note" style="margin-top:0">${tr('dashboard.where_your_users_traffic_comes_from')}</p>${chartLegend('mix')}<div class="tscroll"><table class="tbl"><thead><tr>${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>`<th class="${c}">${k==='mix'?l:`<button class="thb" data-act="dashSort" data-args="${esc(JSON.stringify({k}))}">${l}${UI.dashSort===k?(UI.dashDir>0?' ▲':' ▼'):''}</button>`}</th>`).join('')}</tr></thead><tbody>