sightbox/website/assets/js/calculator.js

727 lines
41 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Self-assess calculator — embedded in index.html as a collapsed section
* (#selfAssessSection), revealed by the "Self-assess" CTA. Every
* calculation function below (fmt, setMode, toggleLead, toggleBlendedRate,
* calcEff, calcOpp) is UNCHANGED from the original standalone
* bettersight-calculator.html — the weighted-rate model, tier sizing, and
* every dollar figure are exactly as originally written and tested
* (CLAUDE_CALCULATOR.md's explicit "do not touch the calculation logic"
* rule). The only changes from the original file:
* - buildEffBody()/buildOppBody() return the raw plain-text string
* instead of encodeURIComponent(...) — they used to feed a mailto:
* link, now they feed a JSON payload field directly (exactly the
* change CLAUDE_CALCULATOR.md §4b anticipates)
* - calcEff()/calcOpp() no longer build a mailto: href; each stores its
* already-computed display values in window.__effResults /
* window.__oppResults (new, additive — nothing existing was removed
* beyond the mailto construction) so the new payload builders below
* can read them without re-deriving anything
* - everything from validateEmail() onward is new: the "email me a
* copy" flow and the inline "let's talk" contact form, replacing the
* old mailto CTA, per CLAUDE_CALCULATOR.md §4a/§4b/§4c/§7 (adapted to
* call this site's own backend instead of an n8n webhook)
*/
// ── State ──────────────────────────────────────────────────────────
let useBlendedRate = false, eLeadOpen = false, oLeadOpen = false;
// International figures per CLAUDE_PRICING_UPDATE.md ($599 / $899 /
// $1,995+ — sales-call-only, not the public Caribbean "starts from"
// prices). Sovereign's "+" is open-ended/negotiated; $1,995 is used here
// as its floor since the calculator needs one fixed number to compute against.
const ESSENTIALS = 599*12;
const INTELLIGENCE = 899*12;
const SOVEREIGN = 1995*12;
function fmt(n){
if(n>=1000000) return '$'+(n/1000000).toFixed(1)+'M';
if(n>=1000) return '$'+Math.round(n/1000)+'k';
return '$'+Math.round(n);
}
// ── Reveal / collapse ──────────────────────────────────────────────
/**
* Opens the calculator's <details> accordion (the same native
* expand/collapse element the FAQ below it uses) and scrolls to it —
* called by the "Self-assess" CTA in the nav and hero (index.html). The
* accordion's own "Efficiency Self Assessment" trigger toggles it
* open/closed on its own; this just handles the two CTAs that live
* elsewhere on the page and need to jump straight to an opened panel.
*/
function openSelfAssess(){
const details = document.getElementById('selfAssessDetails');
details.open = true;
details.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// ── Mode toggle ────────────────────────────────────────────────────
function setMode(m){
document.querySelectorAll('#selfAssessSection .mode-btn').forEach(b=>b.classList.remove('active'));
document.querySelectorAll('#selfAssessSection .calc-panel').forEach(p=>p.classList.remove('active'));
document.querySelector('#selfAssessSection .mode-btn.'+m).classList.add('active');
document.getElementById('panel-'+m).classList.add('active');
document.getElementById('progFill').style.width='0%';
}
// ── Lead toggles ───────────────────────────────────────────────────
function toggleLead(p){
if(p==='e'){ eLeadOpen=!eLeadOpen; document.getElementById('e-toggle').classList.toggle('on',eLeadOpen); document.getElementById('e-lead-fields').classList.toggle('show',eLeadOpen); }
else{ oLeadOpen=!oLeadOpen; document.getElementById('o-toggle').classList.toggle('on',oLeadOpen); document.getElementById('o-lead-fields').classList.toggle('show',oLeadOpen); }
}
// ── Efficiency calc ────────────────────────────────────────────────
function toggleBlendedRate(){
useBlendedRate = !useBlendedRate;
document.getElementById('e-blend-toggle').classList.toggle('on', useBlendedRate);
document.getElementById('e-custom-row').classList.toggle('show', useBlendedRate);
document.querySelectorAll('#selfAssessSection .rate-select').forEach(sel => sel.disabled = useBlendedRate);
calcEff();
}
function calcEff(){
const s1=parseFloat(document.getElementById('e-s1').value)||0;
const s2=parseFloat(document.getElementById('e-s2').value)||0;
const s3=parseFloat(document.getElementById('e-s3').value)||0;
const s4=parseFloat(document.getElementById('e-s4').value)||0;
const t1=parseFloat(document.getElementById('e-t1').value)||0;
const t2=parseFloat(document.getElementById('e-t2').value)||0;
const t3=parseFloat(document.getElementById('e-t3').value)||0;
const t4=parseFloat(document.getElementById('e-t4').value)||0;
const blendedRate=parseFloat(document.getElementById('e-custom-rate').value)||0;
const r1=parseFloat(document.getElementById('e-r1').value)||0;
const r2=parseFloat(document.getElementById('e-r2').value)||0;
const r3=parseFloat(document.getElementById('e-r3').value)||0;
const r4=parseFloat(document.getElementById('e-r4').value)||0;
['e-s1','e-s2','e-s3','e-s4','e-t1','e-t2','e-t3','e-t4'].forEach(id=>{
document.getElementById(id).classList.toggle('has-val',parseFloat(document.getElementById(id).value)>0);
});
// Each activity's daily hours are driven by its own staff count —
// a document search isn't done by the same person writing proposals.
// Each activity also carries its own rate by default, since the
// person searching documents is rarely the person writing proposals —
// unless the blended-rate toggle is on, in which case one rate applies to all.
const hrs1=s1*t1, hrs2=s2*t2, hrs3=s3*t3, hrs4=s4*t4;
const hrsDayTotal=hrs1+hrs2+hrs3+hrs4; // combined person-hours per day across all activities
const hrsWeek=hrsDayTotal*5;
let weekCost;
let rate; // used only for display/footnote purposes when blended
if(useBlendedRate){
rate=blendedRate;
weekCost=hrsWeek*blendedRate;
} else {
// Sum each activity's cost at its own rate, then combine
weekCost=(hrs1*r1 + hrs2*r2 + hrs3*r3 + hrs4*r4)*5;
// Effective blended rate for display purposes only (weighted average)
rate=hrsDayTotal>0 ? weekCost/hrsWeek : 0;
}
const yearCost=weekCost*52;
const anyStaff=(s1+s2+s3+s4)>0;
const anyHours=(t1+t2+t3+t4)>0;
const rateReady=useBlendedRate ? blendedRate>0 : true; // per-activity selects always have a default value
const filled=[anyStaff?1:0, anyHours?1:0, rateReady?1:0].filter(v=>v>0).length;
document.getElementById('progFill').style.width=Math.round((filled/3)*100)+'%';
const card=document.getElementById('e-results');
const cta=document.getElementById('e-cta');
if(anyStaff&&anyHours&&rateReady&&hrsDayTotal>0){
card.classList.add('show');
// ── WEIGHTED RECOVERY CALCULATION ───────────────────────────
// Each activity has a different AI-assisted time reduction:
// t1 Searching documents/policies → AI returns cited answer ~1 min → ~98% reduction
// t2 Re-answering repeated questions → AI returns in ~2 min → ~90% reduction
// t3 Preparing reports/proposals → AI assists assembly, human edits → ~65% reduction
// t4 Onboarding/explaining context → AI answers factual questions → ~75% reduction
// Weighted composite = sum(activity_hrs × reduction) / total_hrs
// Published rate capped at 80% as conservative floor — never overclaim
const W_SEARCH = 0.98;
const W_REANSWER = 0.90;
const W_REPORTS = 0.65;
const W_ONBOARD = 0.75;
// Weight by person-hours per activity (staff × hours), not raw hours —
// this correctly reflects that different staff do different activities
const rawWeighted = hrsDayTotal > 0
? ((hrs1*W_SEARCH) + (hrs2*W_REANSWER) + (hrs3*W_REPORTS) + (hrs4*W_ONBOARD)) / hrsDayTotal
: 0;
const recoveryRate = Math.min(rawWeighted, 0.80);
const weightedPct = Math.round(rawWeighted * 100);
const publishedPct = Math.round(recoveryRate * 100);
// Build footnote text — shown as * next to metric, not as a prominent block
const t1Pct = hrs1>0 ? `document search ${Math.round(W_SEARCH*100)}%` : '';
const t2Pct = hrs2>0 ? `repeated queries ${Math.round(W_REANSWER*100)}%` : '';
const t3Pct = hrs3>0 ? `reports/proposals ${Math.round(W_REPORTS*100)}%` : '';
const t4Pct = hrs4>0 ? `onboarding ${Math.round(W_ONBOARD*100)}%` : '';
const activePcts = [t1Pct,t2Pct,t3Pct,t4Pct].filter(Boolean).join(', ');
const rateModeText = useBlendedRate
? `Cost calculated using a single blended rate of $${blendedRate}/hr across all activities. `
: `Cost calculated per activity using its own hourly rate, then combined — a document search is rarely done by the same person writing proposals. Effective blended rate: $${rate.toFixed(0)}/hr. `;
const footnoteText = `* Recovery rate basis: staff and hours counted separately per activity, since different people typically do different tasks. ${rateModeText}`
+ `AI-assisted time reduction by activity — ${activePcts}. `
+ `Weighted composite: ${weightedPct}%. `
+ `Published rate capped at ${publishedPct}% as a conservative floor to account for `
+ `retrieval misses (~10% of queries), answer verification time, and documents not yet indexed. `
+ `Most organizations see higher returns once the system is calibrated to their specific documents.`;
document.getElementById('e-basis').textContent = footnoteText;
document.getElementById('e-hours').textContent=hrsWeek.toFixed(1)+' hrs';
document.getElementById('e-week').textContent=fmt(weekCost);
document.getElementById('e-month').textContent=fmt(weekCost*4.33);
document.getElementById('e-year').textContent=fmt(yearCost);
// insight
let msg='';
if(yearCost<5000) msg=`Your annual efficiency loss of <strong>${fmt(yearCost)}/year</strong> is modest at face value — but most organizations find the real number is 2–3× higher once meeting prep, policy confusion, and knowledge transfer costs are included.`;
else if(yearCost<20000) msg=`<strong>${fmt(yearCost)} per year</strong> is your annual efficiency loss in unproductive retrieval time — the equivalent of roughly <strong>${Math.round(yearCost/(rate*2000)*10)/10} full-time salaries</strong> absorbed by work a knowledge system handles automatically.`;
else if(yearCost<60000) msg=`At <strong>${fmt(yearCost)} per year</strong> your organization faces a significant annual efficiency loss that never appears on any report. Your people are not the problem — they are capable professionals operating in a system that forces them to act as search engines.`;
else msg=`<strong>${fmt(yearCost)} per year</strong> — this is a material annual efficiency loss hiding inside your salary line. At this scale a knowledge infrastructure investment is a strategic financial decision, not an efficiency tool.`;
// Reframes the lost hours as redirectable capacity, not just a cost —
// the same hrsWeek figure shown above, restated as what it actually
// frees your team up to do instead.
msg += ` That's <strong>${hrsWeek.toFixed(1)} hours a week</strong> your team could redirect toward higher-value, income-generating work — not spent searching for documents, re-answering the same questions, or manually assembling reports.`;
document.getElementById('e-insight').innerHTML=msg;
// recovery logic
const recovered=yearCost*recoveryRate;
const reco=document.getElementById('e-reco');
reco.innerHTML='';
let tierRec,boxClass,recoTop,recoTitle,recoBody,netGain,tierAnnual;
if(recovered>=SOVEREIGN*2){ tierRec='sovereign'; tierAnnual=SOVEREIGN; }
else if(recovered>=INTELLIGENCE*2){ tierRec='intelligence'; tierAnnual=INTELLIGENCE; }
else if(recovered>=ESSENTIALS*2){ tierRec='essentials'; tierAnnual=ESSENTIALS; }
else if(recovered>=ESSENTIALS){ tierRec='essentials_borderline'; tierAnnual=ESSENTIALS; }
else { tierRec='none'; tierAnnual=ESSENTIALS; }
netGain=recovered-tierAnnual;
if(tierRec==='none'){
boxClass='warn-reco';
recoTop='<span style="color:#B45309;">Your result</span>';
recoTitle='Your annual efficiency loss may not justify the investment yet';
recoBody=`At a ${publishedPct}% weighted recovery rate, you stand to recover <strong style="color:#B45309">${fmt(recovered)}/year</strong>. That is a real saving — and there are likely additional losses not captured here. Most organizations find their real number is 2–3× higher once we look at the full picture. Your potential recovery could be significantly greater.`;
} else {
const tierLabel=tierRec==='intelligence'?'Intelligence':'Essentials';
boxClass='eff-reco';
recoTop='<span style="color:#059669;">What you stand to recover</span>';
recoTitle='';
recoBody=(tierRec==='essentials_borderline')
?`Based on your numbers, your potential recovery exceeds the possible service cost from day one. As your document base grows the recovery value improves over time.`
:`Based on your numbers, your potential recovery significantly exceeds the possible service cost. The ${publishedPct}% recovery estimate used here is a conservative floor — most organizations see higher returns once the system is calibrated to their specific documents and workflows.`;
}
const box=document.createElement('div');
box.className='reco-box '+boxClass;
if(tierRec==='none'){
box.innerHTML=`<div class="reco-top">${recoTop}</div><div class="reco-title">${recoTitle}</div><div class="reco-body">${recoBody}</div>`;
} else {
// No reco-top heading here — it would just repeat the "What you
// stand to recover" section divider immediately above this box
// (found live: a visitor's results transcript showed the same
// heading rendered twice in a row).
box.innerHTML=`
<div class="reco-nums">
<div><div class="reco-num-label">Value recovered / year *</div><div class="reco-num-val" style="color:var(--green);">${fmt(recovered)}</div><div style="font-size:.72rem;color:#6B7A99;margin-top:3px;">at ${publishedPct}% conservative recovery rate</div></div>
<div><div class="reco-num-label">Net gain after cost</div><div class="reco-num-val" style="color:${netGain>0?'var(--green)':'var(--amber)'};">${netGain>0?fmt(netGain):'-'+fmt(Math.abs(netGain))}</div><div style="font-size:.72rem;color:#6B7A99;margin-top:3px;">net gain after possible service cost</div></div>
</div>
<div class="reco-body" style="border-top:1px solid #10D98A;padding-top:10px;">${recoBody}</div>`;
}
reco.appendChild(box);
document.getElementById('e-bar').style.width=(Math.min(Math.max(netGain,0)/yearCost,1)*100)+'%';
document.getElementById('e-ratio').textContent=(netGain>0?fmt(netGain):'-'+fmt(Math.abs(netGain)))+' net';
document.getElementById('e-bar-label').textContent='Annual efficiency loss: '+fmt(yearCost);
// Reveal proactive question and lead card once results are showing
document.querySelectorAll('#panel-eff .proactive-box, #panel-eff .lead-card').forEach(el => {
el.classList.add('revealed');
el.style.display = 'block';
requestAnimationFrame(() => { el.style.opacity='1'; el.style.transform='translateY(0)'; });
});
cta.style.display='block';
document.getElementById('e-cta-note').textContent='We have your results. Let\'s create a plan that considers the size and peculiarities of your organization.';
// Summary statement before CTA
const eSummary = document.getElementById('e-summary');
const eRecoveredFmt = fmt(recovered);
const eNetFmt = netGain>0?fmt(netGain):'-'+fmt(Math.abs(netGain));
const eYearFmt = fmt(yearCost);
if(tierRec==='none'){
eSummary.innerHTML = `Your results show an annual efficiency loss of <strong>${eYearFmt}</strong>. At a ${publishedPct}% weighted recovery rate, you stand to recover <strong>${eRecoveredFmt}/year</strong> — after a possible service cost, a net gain of <strong>${eNetFmt}/year</strong>. Your results give us what we need to identify where the highest-impact changes are — and to create a plan that considers the size and peculiarities of your organization.`;
} else {
eSummary.innerHTML = `Your results show an annual efficiency loss of <strong>${eYearFmt}</strong>. At a ${publishedPct}% weighted recovery rate, you stand to recover <strong>${eRecoveredFmt}/year</strong> — after a possible service cost, a net gain of <strong>${eNetFmt}/year</strong>. These numbers give us everything we need to create a plan that considers the size and peculiarities of your organization.`;
}
// Captured for the "email me a copy" / "let's talk" payload builders
// below — every value here is already computed above, nothing
// recalculated (CLAUDE_CALCULATOR.md: do not touch the calc logic).
// Raw values (not just display strings) are kept too, since
// buildContactPayload() must call buildEffBody() with the real
// numbers — passing it placeholders would send the studio a lead
// email with wrong, zeroed-out figures.
window.__effResults = {
raw: { hrsWeek, weekCost, yearCost, rate, recovered, tierRec, publishedPct },
displayHours: hrsWeek.toFixed(1)+' hrs',
displayWeek: fmt(weekCost),
displayMonth: fmt(weekCost*4.33),
displayYear: eYearFmt,
displayRecovered: eRecoveredFmt,
displayNetGain: eNetFmt,
footnote: footnoteText,
summaryHtml: eSummary.innerHTML,
};
} else {
card.classList.remove('show');
cta.style.display='none';
document.querySelectorAll('#panel-eff .proactive-box, #panel-eff .lead-card').forEach(el => {
el.classList.remove('revealed');
el.style.opacity='0'; el.style.transform='translateY(10px)';
setTimeout(() => { el.style.display='none'; }, 350);
});
}
}
// ── Opportunity calc ───────────────────────────────────────────────
function calcOpp(){
const props=parseFloat(document.getElementById('o-proposals').value)||0;
const hrsPerProp=parseFloat(document.getElementById('o-hrs-per-prop').value)||0;
const skipped=parseFloat(document.getElementById('o-skipped').value)||0;
const contractVal=parseFloat(document.getElementById('o-contract-val').value)||0;
const winRate=(parseFloat(document.getElementById('o-win-rate').value)||0)/100;
const filled=[props+skipped,hrsPerProp,contractVal,winRate].filter(v=>v>0).length;
document.getElementById('progFill').style.width=Math.round((filled/4)*100)+'%';
const card=document.getElementById('o-results');
const cta=document.getElementById('o-cta');
if(props>0&&hrsPerProp>0&&contractVal>0&&winRate>0){
card.classList.add('show');
// ── COMPOSITE CAPACITY MODEL ─────────────────────────────────
// Uses the same published W_REPORTS rate (65%) as the efficiency
// calculator's report/proposal reduction — one rate, used consistently,
// never inflated for this calculator specifically.
const W_REPORTS = 0.65;
const currentAnnualHours = props * hrsPerProp;
const hoursFreed = currentAnnualHours * W_REPORTS;
const newHrsPerProp = hrsPerProp * (1 - W_REPORTS); // 35% of original time remains
const extraCapacity = newHrsPerProp>0 ? Math.floor(hoursFreed / newHrsPerProp) : 0;
// Total addressable opportunities = current submissions + previously skipped + new capacity
const newTotalProps = props + extraCapacity;
// Wins at existing win rate — no assumed improvement in quality or conversion
const currentWins = Math.round(props * winRate);
const newWins = Math.round(newTotalProps * winRate);
const extraWins = Math.max(newWins - currentWins, 0);
const extraRev = extraWins * contractVal;
// Skipped opportunity value — what was already achievable but not pursued at all
const skippedValue = skipped * winRate * contractVal;
const totalOpportunityValue = extraRev + skippedValue;
// Possible service cost — same tier constants as efficiency calculator
let tierAnnualOpp;
if(totalOpportunityValue>=SOVEREIGN*2){ tierAnnualOpp=SOVEREIGN; }
else if(totalOpportunityValue>=INTELLIGENCE*2){ tierAnnualOpp=INTELLIGENCE; }
else { tierAnnualOpp=ESSENTIALS; }
const netGainOpp = totalOpportunityValue - tierAnnualOpp;
document.getElementById('o-extra-props').textContent='+'+extraCapacity;
document.getElementById('o-extra-wins').textContent='+'+extraWins;
document.getElementById('o-extra-rev').textContent=fmt(totalOpportunityValue);
// Insight
let msg='';
if(totalOpportunityValue<10000) msg=`The additional <strong>${fmt(totalOpportunityValue)}/year</strong> is calculated from your own preparation pace — ${hrsPerProp} hours per proposal today, reduced by a published 65% rate. The real number grows as your document base matures and preparation time drops further.`;
else if(totalOpportunityValue<50000) msg=`<strong>${fmt(totalOpportunityValue)}/year</strong> in additional opportunity value — from the same team, the same expertise, the same win rate — just without the preparation bottleneck limiting how many opportunities you could pursue.`;
else msg=`<strong>${fmt(totalOpportunityValue)}/year</strong> in additional opportunity value — from opportunities that already exist in your market, at your existing win rate. The only thing that changes is how many you can prepare for.`;
if(skippedValue>0) msg+=` That figure includes approximately <strong>${fmt(skippedValue)}/year</strong> from opportunities you were already capable of winning but skipped entirely. Many tender and grant windows are short — at a reduced preparation time of ${newHrsPerProp.toFixed(1)} hours per proposal, opportunities you currently miss on timing become ones you can realistically pursue.`;
document.getElementById('o-insight').innerHTML=msg;
// Reco box
const reco=document.getElementById('o-reco');
reco.innerHTML='';
const box=document.createElement('div');
box.className='reco-box opp-reco';
let recoMsg;
if(totalOpportunityValue>=INTELLIGENCE*3){
recoMsg=`Your opportunity value of <strong>${fmt(totalOpportunityValue)}/year</strong> represents a strong return relative to a possible service cost. The additional capacity and wins compound — the more your team uses it, the wider the advantage grows.`;
} else if(totalOpportunityValue>=ESSENTIALS*2){
recoMsg=`Your opportunity value of <strong>${fmt(totalOpportunityValue)}/year</strong> represents a clear positive return relative to a possible service cost. As your proposal volume grows, the potential compounds further.`;
} else {
recoMsg=`Even calculated conservatively from your own preparation pace, the additional opportunity value is real. Your results give us everything we need to identify the specific opportunities in your pipeline where this would have the fastest impact.`;
}
// No reco-top heading here — it would just repeat the "What you stand
// to gain" section divider immediately above this box.
box.innerHTML=`
<div class="reco-nums">
<div><div class="reco-num-label">Annual opportunity value *</div><div class="reco-num-val" style="color:var(--green);">${fmt(totalOpportunityValue)}</div><div style="font-size:.72rem;color:#6B7A99;margin-top:3px;">extra capacity + skipped value recovered</div></div>
<div><div class="reco-num-label">Net gain after cost</div><div class="reco-num-val" style="color:${netGainOpp>0?'var(--green)':'var(--amber)'};">${netGainOpp>0?fmt(netGainOpp):'-'+fmt(Math.abs(netGainOpp))}</div><div style="font-size:.72rem;color:#6B7A99;margin-top:3px;">annual value minus possible service cost</div></div>
</div>
<div class="reco-body" style="border-top:1px solid #10D98A;padding-top:10px;">${recoMsg}</div>`;
reco.appendChild(box);
document.getElementById('o-bar').style.width=(Math.min(Math.max(netGainOpp,0)/(totalOpportunityValue||1),1)*100)+'%';
document.getElementById('o-ratio').textContent=(netGainOpp>0?fmt(netGainOpp):'-'+fmt(Math.abs(netGainOpp)))+' net';
document.getElementById('o-bar-label').textContent='Annual opportunity value: '+fmt(totalOpportunityValue);
// Footnote — calculation basis
const basisEl = document.getElementById('o-basis');
basisEl.textContent = `* Capacity gain basis: at ${hrsPerProp} hours per proposal today, a 65% time reduction (the same published rate used in our efficiency calculations for report and proposal preparation) frees ${hoursFreed.toFixed(0)} hours per year — enough for approximately ${extraCapacity} additional proposals at your current pace. Wins are calculated at your existing ${(winRate*100).toFixed(0)}% win rate, with no assumed improvement in quality or conversion. Net gain is the annual opportunity value minus a possible service cost, using the tier your results indicate.`;
// Reveal proactive question and lead card once results are showing
document.querySelectorAll('#panel-opp .proactive-box, #panel-opp .lead-card').forEach(el => {
el.classList.add('revealed');
el.style.display = 'block';
requestAnimationFrame(() => { el.style.opacity='1'; el.style.transform='translateY(0)'; });
});
cta.style.display='block';
// Summary statement before CTA
const oSummary = document.getElementById('o-summary');
const oNetFmt = netGainOpp>0?fmt(netGainOpp):'-'+fmt(Math.abs(netGainOpp));
oSummary.innerHTML = `Your results show <strong>${extraCapacity} additional proposals</strong> of capacity per year and <strong>${fmt(totalOpportunityValue)}/year</strong> in opportunity value — after a possible service cost, a net gain of <strong>${oNetFmt}/year</strong>. These numbers give us everything we need to create a plan that considers the size and peculiarities of your organization.`;
// Captured for the "email me a copy" / "let's talk" payload builders —
// raw values kept too, for the same reason as calcEff() above
window.__oppResults = {
raw: { props, hrsPerProp, skipped, contractVal, winRate, extraCapacity, extraWins, totalOpportunityValue, skippedValue, netGainOpp },
displayExtraCapacity: '+'+extraCapacity,
displayExtraWins: '+'+extraWins,
displayValue: fmt(totalOpportunityValue),
displayNetGain: oNetFmt,
footnote: basisEl.textContent,
summaryHtml: oSummary.innerHTML,
};
} else {
card.classList.remove('show');
cta.style.display='none';
document.querySelectorAll('#panel-opp .proactive-box, #panel-opp .lead-card').forEach(el => {
el.classList.remove('revealed');
el.style.opacity='0'; el.style.transform='translateY(10px)';
setTimeout(() => { el.style.display='none'; }, 350);
});
}
}
// ── Email builders ─────────────────────────────────────────────────
// Return the raw plain-text string (not encodeURIComponent'd) — these used
// to feed a mailto: link; now they feed a JSON payload field directly, per
// CLAUDE_CALCULATOR.md §4b's explicit instruction to keep these functions
// as-is beyond that one change.
function buildEffBody(s1,s2,s3,s4,t1,t2,t3,t4,r1,r2,r3,r4,useBlendedRate,blendedRate,hrsWeek,weekCost,yearCost,rate,recovered,tierRec,publishedPct){
const tierLabels={sovereign:'Strong ROI case — enterprise-scale recovery potential',intelligence:'Strong ROI case — high recovery potential',essentials:'Positive ROI case — solid recovery potential',essentials_borderline:'Borderline ROI — worth reviewing full picture',none:'Low loss detected — may have uncounted factors'};
const name=document.getElementById('e-name').value||'Not specified';
const org=document.getElementById('e-org').value||'Not specified';
const sector=document.getElementById('e-sector').value||'Not specified';
const proactive=document.getElementById('e-proactive').value||'Not provided';
const rateLines = useBlendedRate
? ['Rate mode: single blended rate — $'+blendedRate+'/hr for all activities']
: [
'Rate mode: per-activity rates',
'Document search rate: $'+r1+'/hr',
'Repeated questions rate: $'+r2+'/hr',
'Reports/proposals rate: $'+r3+'/hr',
'Onboarding rate: $'+r4+'/hr'
];
const lines=[
'Bettersight Intelligence — Efficiency Results','',
'Name: '+name,'Organization: '+org,'Sector: '+sector,'',
'--- Audit Results (by activity) ---',
'Document search: '+s1+' staff x '+t1+' hrs/day',
'Repeated questions: '+s2+' staff x '+t2+' hrs/day',
'Reports/proposals: '+s3+' staff x '+t3+' hrs/day',
'Onboarding: '+s4+' staff x '+t4+' hrs/day',
...rateLines,
'Effective blended rate: $'+rate.toFixed(0)+'/hr',
'Total person-hours lost per week: '+hrsWeek.toFixed(1)+' hrs',
'Annual efficiency loss: $'+Math.round(yearCost),'',
'--- Recovery projection ('+publishedPct+'% weighted rate) ---',
'Value recoverable per year: $'+Math.round(recovered),
'Recovery assessment: '+(tierLabels[tierRec]||'To be discussed in review'),'',
'--- Opportunity question ---',proactive,'',
'I have completed the efficiency calculator. Please contact me to review my results and discuss next steps.'
];
return lines.join('\n');
}
function buildOppBody(props,hrsPerProp,skipped,contractVal,winRate,extraCapacity,extraWins,totalOpportunityValue,skippedValue,netGainOpp){
const name=document.getElementById('o-name').value||'Not specified';
const org=document.getElementById('o-org').value||'Not specified';
const sector=document.getElementById('o-sector').value||'Not specified';
const proactive=document.getElementById('o-proactive').value||'Not provided';
const lines=[
'Bettersight Intelligence — Opportunity Results Review','',
'Name: '+name,'Organization: '+org,'Sector: '+sector,'',
'--- Opportunity Results ---',
'Current proposals per year: '+props,
'Average hours per proposal: '+hrsPerProp,
'Opportunities skipped per year: '+skipped,
'Average contract/grant value: $'+contractVal,
'Current win rate: '+(winRate*100)+'%',
'Additional capacity (proposals/year): '+extraCapacity,
'Additional wins projected: '+extraWins,
'Annual opportunity value: $'+Math.round(totalOpportunityValue),
'Skipped opportunity value included: $'+Math.round(skippedValue),
'Net gain after possible service cost: $'+Math.round(netGainOpp),'',
'--- Biggest untapped opportunity ---',proactive,'',
'I have completed the opportunity calculator. Please contact me to review my results and discuss next steps.'
];
return lines.join('\n');
}
// ── Email validation (CLAUDE_CALCULATOR.md §4c) ─────────────────────
/**
* Simple, permissive email format check — not RFC 5322 compliant, good
* enough to catch obvious typos client-side. The backend validates again
* server-side; this is UX only.
*/
function validateEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
// ── "Email me a copy" (CLAUDE_CALCULATOR.md §4a/§5a, Flask instead of n8n) ──
/**
* Sends the current calculator's results as a "copy me this" request.
* Data flow: email input + window.__effResults/__oppResults (already
* computed by calcEff()/calcOpp(), not recalculated here) → POST
* /api/calculator/copy (same-origin, proxied to the backend by nginx) →
* success/error shown inline. Never notifies the studio inbox — see
* routes/calculator.py.
*
* @param {string} panel - 'e' for efficiency, 'o' for opportunity
*/
async function sendCopy(panel){
const emailInput = document.getElementById(panel+'-copy-email');
const statusEl = document.getElementById(panel+'-copy-status');
const btn = document.getElementById(panel+'-copy-btn');
const email = emailInput.value.trim();
if(!validateEmail(email)){
statusEl.textContent = 'Enter a valid email address.';
statusEl.style.color = '#F04438';
return;
}
btn.disabled = true;
btn.textContent = 'Sending...';
statusEl.textContent = '';
try {
const payload = buildCopyPayload(panel, email);
const response = await fetch('/api/calculator/copy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if(!response.ok) throw new Error('Request failed');
statusEl.textContent = 'Sent! Check your inbox for your PDF.';
statusEl.style.color = '#10D98A';
} catch(err) {
statusEl.textContent = 'Something went wrong. Please try again.';
statusEl.style.color = '#F04438';
} finally {
btn.disabled = false;
btn.textContent = 'Email me a copy';
}
}
/**
* Builds the payload for the "email me a copy" endpoint from the current
* panel's already-computed results — reads window.__effResults /
* window.__oppResults (set at the end of calcEff()/calcOpp()), never
* recalculates anything.
*
* @param {string} panel - 'e' or 'o'
* @param {string} email - validated recipient email
*/
function buildCopyPayload(panel, email){
if(panel === 'e'){
const r = window.__effResults || {};
return {
calculator: 'efficiency',
title: 'Your Efficiency Results',
summary_text: r.summaryHtml || '',
results: [
{ label: 'Person-hours lost / week', value: r.displayHours },
{ label: 'Cost / week', value: r.displayWeek },
{ label: 'Cost / month', value: r.displayMonth },
{ label: 'Annual efficiency loss', value: r.displayYear },
{ label: 'Value recovered / year', value: r.displayRecovered },
{ label: 'Net gain after cost', value: r.displayNetGain },
],
basis_footnote: r.footnote || '',
proactive_question: "What would your team do more of — or for the first time — if producing a report or proposal took four hours instead of three days?",
proactive_answer: document.getElementById('e-proactive').value || '',
recipient_email: email,
};
}
const r = window.__oppResults || {};
return {
calculator: 'opportunity',
title: 'Your Opportunity Results',
summary_text: r.summaryHtml || '',
results: [
{ label: 'Additional capacity / yr', value: r.displayExtraCapacity },
{ label: 'Additional wins / yr', value: r.displayExtraWins },
{ label: 'Annual opportunity value', value: r.displayValue },
{ label: 'Net gain after cost', value: r.displayNetGain },
],
basis_footnote: r.footnote || '',
proactive_question: "If your team could respond to every relevant opportunity — and win at a higher rate — what would that mean for your organization in 12 months?",
proactive_answer: document.getElementById('o-proactive').value || '',
recipient_email: email,
};
}
// ── Inline "let's talk" contact form (replaces the old mailto CTA) ────
/**
* Reveals the inline contact form for the given panel, pre-filling from
* the existing lead-toggle fields if the visitor already completed them.
*
* @param {string} panel - 'e' or 'o'
*/
function showContactForm(panel){
const form = document.getElementById(panel+'-contact-form');
form.classList.add('show');
prefillContactForm(panel);
form.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
/**
* Copies values from the existing optional lead-toggle fields
* (e-name/e-org or o-name/o-org) into the new contact form fields, if
* those fields have values — avoids asking the visitor to type their
* name/org twice if they already did via the lead toggle earlier.
*
* @param {string} panel - 'e' or 'o'
*/
function prefillContactForm(panel){
const nameField = document.getElementById(panel+'-name');
const orgField = document.getElementById(panel+'-org');
if(nameField && nameField.value){
document.getElementById(panel+'-contact-name').value = nameField.value;
}
if(orgField && orgField.value){
document.getElementById(panel+'-contact-org').value = orgField.value;
}
}
/**
* Submits the inline contact form — sends contact details plus the
* current assessment results and PDF to the studio inbox via this site's
* own backend. Data flow: contact form fields + current results → POST
* /api/calculator/contact → confirmation shown, form collapses.
*
* @param {string} panel - 'e' or 'o'
*/
async function submitContactForm(panel){
const name = document.getElementById(panel+'-contact-name').value.trim();
const email = document.getElementById(panel+'-contact-email').value.trim();
const org = document.getElementById(panel+'-contact-org').value.trim();
const phone = document.getElementById(panel+'-contact-phone').value.trim();
const statusEl = document.getElementById(panel+'-contact-status');
const btn = document.getElementById(panel+'-contact-submit-btn');
if(!name || !validateEmail(email)){
statusEl.textContent = 'Please enter your name and a valid email.';
statusEl.style.color = '#F04438';
return;
}
btn.disabled = true;
btn.textContent = 'Sending...';
try {
const payload = buildContactPayload(panel, { name, email, org, phone });
const response = await fetch('/api/calculator/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if(!response.ok) throw new Error('Request failed');
document.getElementById(panel+'-contact-form').innerHTML =
'<div style="text-align:center;padding:12px;color:#0D1526;font-family:var(--fd);font-weight:600;">' +
'Thanks — we have your details and your results. We\'ll be in touch shortly.</div>';
} catch(err) {
statusEl.textContent = 'Something went wrong. Please try again or email us directly.';
statusEl.style.color = '#F04438';
btn.disabled = false;
btn.textContent = 'Send my details →';
}
}
/**
* Builds the payload for the contact-form endpoint — same results shape
* as buildCopyPayload, plus the contact fields and the plain-text summary
* already generated by buildEffBody()/buildOppBody() (reused verbatim as
* the studio notification email body, per CLAUDE_CALCULATOR.md §5b).
*
* @param {string} panel - 'e' or 'o'
* @param {object} contact - {name, email, org, phone}
*/
function buildContactPayload(panel, contact){
const sectorField = document.getElementById(panel+'-sector');
const sector = sectorField ? sectorField.value : '';
const base = panel === 'e' ? buildCopyPayload('e', contact.email) : buildCopyPayload('o', contact.email);
delete base.recipient_email;
// Uses the RAW values captured in window.__effResults/__oppResults at
// calculation time (see calcEff()/calcOpp()) — not re-derived from the
// form fields and not placeholders, since buildEffBody()/buildOppBody()
// need the real numbers to produce a correct plain-text summary. Only
// the name-field-derived inputs (staff/hours/rates) come straight from
// the DOM, exactly as buildEffBody() already expects.
let email_body_plaintext;
if(panel === 'e'){
const s1=parseFloat(document.getElementById('e-s1').value)||0;
const s2=parseFloat(document.getElementById('e-s2').value)||0;
const s3=parseFloat(document.getElementById('e-s3').value)||0;
const s4=parseFloat(document.getElementById('e-s4').value)||0;
const t1=parseFloat(document.getElementById('e-t1').value)||0;
const t2=parseFloat(document.getElementById('e-t2').value)||0;
const t3=parseFloat(document.getElementById('e-t3').value)||0;
const t4=parseFloat(document.getElementById('e-t4').value)||0;
const r1=parseFloat(document.getElementById('e-r1').value)||0;
const r2=parseFloat(document.getElementById('e-r2').value)||0;
const r3=parseFloat(document.getElementById('e-r3').value)||0;
const r4=parseFloat(document.getElementById('e-r4').value)||0;
const blendedRate=parseFloat(document.getElementById('e-custom-rate').value)||0;
const raw = (window.__effResults || {}).raw || {};
email_body_plaintext = buildEffBody(
s1,s2,s3,s4,t1,t2,t3,t4,r1,r2,r3,r4,useBlendedRate,blendedRate,
raw.hrsWeek, raw.weekCost, raw.yearCost, raw.rate, raw.recovered, raw.tierRec, raw.publishedPct
);
} else {
const raw = (window.__oppResults || {}).raw || {};
email_body_plaintext = buildOppBody(
raw.props, raw.hrsPerProp, raw.skipped, raw.contractVal, raw.winRate,
raw.extraCapacity, raw.extraWins, raw.totalOpportunityValue, raw.skippedValue, raw.netGainOpp
);
}
return {
...base,
contact: { name: contact.name, email: contact.email, organization: contact.org, phone: contact.phone, sector },
email_body_plaintext,
};
}