R
LATAM Remote Tech Radar B2B ENGINE
Daily Verified Hiring Signals Across US & EU Startups

Pitch Direct US Employers
Actively Hiring in LATAM Timezones.

Zero recruitment agencies. Zero middleman bodyshops. Our automated radar tracks 1,000+ direct tech scale-up openings across Latin America, calculates real-time compensation percentiles, and generates ready-to-dispatch business development hooks.

1079
Active Direct Openings
Daily verified & rotated
390
Direct Employers
100% Agency Filtered
$55,500
Median Senior Tech Pay
NIST Percentile Verified
100x+
Agency ROI
1 placement = $15k+ revenue

Technographic Distribution

Classified technologies across current active remote engineering requisitions.

Snapshot: 2026-10-27T06:01:07.232023
๐Ÿ’ฐ Live Market Intelligence Tool

Interactive LATAM Salary & Demand Estimator

Statistical compensation benchmarks (NIST linear interpolation) across 1,000+ verified direct requisitions.

๐Ÿ“– Full 2026 Executive Brief →
๐Ÿ“Š Full Brief ($49)
Python โ€ข Senior Sample: 31 disclosed salaries
Median Compensation
$55,500
~$4,625 / month
25th - 75th Percentile
$41.1k โ€” $158.8k
Active spread: $117.7k
Total Active Requisitions: 116 verified direct roles
Companion Tech Stack (Co-occurrence):
SQL / Postgres (49.1%) AI / LLMs (33.6%) AWS (28.4%)
โšก B2B Staffing & Agency Matcher

Agency Opportunity Matcher & Pitch Generator

Select an agency or custom stack to preview live startup triggers, salary stats, and auto-generated pitch copy.

32 Verified Agencies
Ideaware โ€ข Live Matches 3 Direct Requisitions
Generated LinkedIn Connection Note (≤300 chars):
Loading pitch note...
Export Platform:

Live Verified Hiring Triggers

Direct US/EU employers hiring remote engineers in LATAM/Americas timezones right now.

Showing top sample from 1079 active records
๐Ÿ”
Live Instant Search ๐Ÿ“ฅ Export Sample CSV
iMerit Technology Unspecified

AI Trainer - Video Annotation

๐Ÿ“ Scope: Worldwide ๐Ÿ’ฐ 70K-80K

Askable Unspecified

Software Engineer, AI Coding Tasks

๐Ÿ“ Scope: Worldwide ๐Ÿ’ฐ $1000 per task

Python TypeScript Rust Java
Inspect Direct Posting →
Coalition Technologies Junior / Associate

Remote Office Assistant

๐Ÿ“ Scope: Worldwide ๐Ÿ’ฐ $35,3k- $52k

PHP SQL / PostgreSQL
Inspect Direct Posting →
Credit Wellness, LLC Unspecified

Inside Sales Contractor

๐Ÿ“ Scope: Worldwide ๐Ÿ’ฐ OTE $25k - $35k

Unio Digital Lead / Manager

Tier III Service Desk Engineer

๐Ÿ“ Scope: Worldwide ๐Ÿ’ฐ Undisclosed

IAPWE Unspecified

Freelance Writer

๐Ÿ“ Scope: Worldwide ๐Ÿ’ฐ $50-$75 /hour

Coalition Technologies Lead / Manager

Freelance Copywriter

๐Ÿ“ Scope: Worldwide ๐Ÿ’ฐ $20k -$35k

Ping Identity Staff / Principal

Director, Partner Operations

๐Ÿ“ Scope: Americas / Remote ๐Ÿ’ฐ Undisclosed

Ping Identity Staff / Principal

Director, Global Alliances โ€“ Accenture

๐Ÿ“ Scope: Americas / Remote ๐Ÿ’ฐ Undisclosed

Upstart Unspecified

DevOps Engineer II, Cloud Platform

๐Ÿ“ Scope: Americas / Remote ๐Ÿ’ฐ Undisclosed

Machine Learning Data Engineering
Inspect Direct Posting →
Keeper Security Staff / Principal

Communications Intern

๐Ÿ“ Scope: Americas / Remote ๐Ÿ’ฐ Undisclosed

Keeper Security Unspecified

Bilingual Channel Sales Engineer, French (EMEA)

๐Ÿ“ Scope: Americas / Remote ๐Ÿ’ฐ Undisclosed

The Math for Nearshore Agencies

Nearshore staff augmentation and recruiting agencies bill $4,500 to $10,000/month per developer. Here is how our daily radar creates an unfair sales advantage:

1. Immediate Hiring Need
Direct Openings = Real Budget

When scale-ups like Vercel, DuckDuckGo, or LaunchDarkly post remote roles open to the Americas, they have budgeted headcount today. You pitch pre-vetted LATAM talent right as the requisition opens.

2. 100x+ Capital Return
$79/mo vs $15,000+ Placement

A single direct contractor placement billed at $6,000/mo generates $72,000 in annual gross revenue. Radar Standard costs $948/year. Closing ONE deal every two years delivers a **76x to 150x return**.

3. Zero Middleman Spam
100% Direct Employers

We algorithmically eliminate freelance brokerages, contractor bodyshops, and scraping scrapers. Your business development team only contacts legitimate hiring managers.

โšก Programmatic B2B REST API v1.3.0 Live
Developer Documentation & Console →

Integrate direct hiring triggers directly into your CRM (HubSpot, Clay, Smartlead, Apollo, Zapier) or AI agent workflows. Filter by tech stack, compensation, and location scope with sub-millisecond JSON latency:

curl -s "http://185.205.194.112/v1/radar/jobs?tech=python&limit=10" View /v1/radar/stats

Predictable B2B Data Subscriptions & Reports

Cancel anytime. All feeds delivered daily directly to your business development team.

2026 Executive Brief

Data Pack
$49 one-time

Complete statistical compensation benchmarks + raw CSV of all 1079 active requisitions.

  • โœ“ Full Markdown & PDF Executive Brief
  • โœ“ Complete 1079-role Raw Dataset CSV
  • โœ“ NIST Percentile Breakdown across 10 Stacks
  • โœ“ Technology Co-occurrence Matrix
  • โœ“ Instant Tokenized Download

Radar Standard

Daily Feed
$79 / month

Perfect for boutique nearshore dev shops and solo recruiting partners.

  • โœ“ Daily 06:00 UTC CSV Feed + New Diffs
  • โœ“ 1079+ Verified Direct Tech Roles
  • โœ“ Granular Technographic Stack Tagging
  • โœ“ Direct Company Job Board URLs
  • โœ“ 100% Bodyshop & Middleman Filtering
Or request 7-day free trial
Recommended for Agencies

Radar Pro (Enriched)

Full Intel
$199 / month

Complete intelligence engine for high-velocity agency sales development teams.

  • โœ“ Everything in Radar Standard
  • โœ“ Enriched Company Profiles (Industry & Domains)
  • โœ“ Ready-to-Send Outreach Angles & Pitches
  • โœ“ Programmatic REST & JSON API (50k calls/mo)
  • โœ“ Instant Webhook Alerts for New Requisitions
Or request complimentary trial dossier

Request Your 7-Day Complimentary Trial

Receive today's full 1079-role CSV feed and an executive intelligence sample dossier for your primary focus tech stack.

No credit card required. Instant in-browser CSV download + executive email dossier.

๐Ÿ“ˆ Asymmetrical ROI Model

Agency ROI & Value Asymmetry Calculator

Simulate your return on Radar Pro ($199/mo) based on placed remote software engineers.

Radar Pro: $2,388/yr
Expected Annual Placements 4 Engineers
1 placement 10 placements 20 placements
Average Placement Margin (USD) $6,000
$2,000 / hire $8,000 / hire $15,000 / hire
๐Ÿ’ก The Asymmetry Thesis: Just 1 engineer placement ($6,000 margin) fully covers 2.5 years of Radar Pro subscription. Any additional placement is 100% pure agency profit.
Gross Value Created $24,000
Radar Pro Cost $2,388
Net Profit Generated +$21,612
ROI Multiplier: 10.1x Breakeven: 0.40 hires (1.2 mos)
๐ŸŽฏ Executive Outbound Intelligence

Decision-Maker & Lead Intelligence Finder

Discover verified engineering leadership (CTO, VP Eng, Founders), corporate email permutations, and tailored pitch copy for any hiring employer.

Quick Examples:
Click "Discover Decision-Makers" to run real-time executive discovery and generate tailored pitch copy.
๐Ÿ’ฐ Client Deal Acceleration & Proposal Engine

US vs LATAM Cost Arbitrage & Proposal Generator

Model mathematical cost savings, monthly cash burn reduction, and venture runway extension. Generate executive strategy proposals ready to close US scaleups.

Calibrated with NIST radar data
2 Devs
1 Dev 5 Devs 10 Devs
$59 / hr
$35/hr $65/hr $95/hr
US Total Cost (Squad)
$488,384
$127.18/hr loaded
Nearshore Squad Cost
$226,452
$59.00/hr billed
Net Annual Client Savings 53.6%
$261,932 / yr
$21,828 / mo burn reduction
Runway Extension
+2.7 Months
Agency Profit: $86,051/yr
๐Ÿ“‹ Ready-to-Send Outbound Sales Assets
Cold Email to VP of Engineering

                    
LinkedIn Connection Note (<=300 Chars)
Day-4 CFO Value Bump
๐ŸŽฏ 5-Touch Cadence & Outreach Automation

Multi-Channel Sequence & Playbook Orchestrator

High-converting 5-step cadence across Cold Email and LinkedIn. Synthesizes pre-vetted LATAM candidate bench showcases and exports directly into Apollo.io, Instantly.ai, and Lemlist.

$48 / hr
Deliverability 98.5%
Open Rate 68.2%
Reply Rate 19.4%
Intro Meetings 4.8%
Projected Pipeline $184,320
Client Savings $245,680
Step 1: Cold Email (Day 1)
Subject Line
Body Copy
Pre-Vetted Bench Candidates Ready in 10 Days
๐Ÿ’ก Candidate profiles are dynamically synthesized to match the exact requisition stack with NIST-calibrated market rates.
๐Ÿค Deal Closer & Commercial Agreement Engine

Statement of Work (SOW) & Agency Unit Economics

Configure commercial engagement terms (Monthly Retainer, Time & Materials, Contingency), generate enforceable legal-grade SOW term sheets with 14-day zero-risk trial warranties, and dispatch deal packets to your CRM.

14-day risk-free trial warranty included
2 Devs
1 Dev 5 Devs 10 Devs
$55 / $32 hr
Bill Rate ($) Talent Pay ($)
Client Annual Savings $242,880 / yr 53.5% vs US Onshore
Agency Monthly Profit $7,360 / mo 41.8% Gross Margin
Agency Annual Margin $88,320 / yr Recurring Net Value
Radar SaaS ROI ($199/mo) 37.0x ROI Breakeven in 6.5 days
Loading Statement of Work...
๐Ÿงช Technical Vetting & Assessment Engine

Candidate Vetting Matrix & Technical Scorecard

Generate stack-calibrated 5-dimension vetting rubrics (Architecture, Code, Debugging, English, Async), live coding challenges, seniority calibrations, and printable hiring scorecards for Latin American talent.

Quick Presets:
Vetting Assessment ID
VET-202610-PREV
100-Point Calibrated
Target Score Range
78 - 90 / 100
Senior Engineer Standard
Interview Agenda
60 Minutes
5 Structured Phases
Evaluation Dimensions
5 Dimensions
Arch, Code, Debug, English, Remote
Loading rubric...
โš–๏ธ International Compliance & Invoicing Engine

Client Onboarding, Tax Compliance & Milestone Invoicing

Automate IRS Form W-8BEN/W-8BEN-E foreign contractor classification (0% US withholding under IRC ยง 861), localized moral rights IP assignments, cross-border FX rail optimization, and executive milestone invoices with 2/10 Net 30 early cashflow incentives.

Engineering Squad Size: 2 Developers
Client Hourly Bill Rate: $55.00 / hr
Milestone Invoice Total
$17,600.00
Monthly Retainer Milestone
Early Pay Savings (2/10)
$352.00
2.0% Cash Incentive
Payment Rail FX Savings
$6,397 / yr
vs Legacy SWIFT Wire
IRS Withholding Status
0.0% Exempt
IRC ยง 861 Foreign Source
๐ŸŽฏ Talent Matcher & Bench Allocation Engine

Candidate Sourcing, Talent Bench & Requisition Matcher

Algorithmic 5-dimension candidate fit scoring across tech stack, timezone overlap, English C1/C2 fluency, and compensation arbitrage. Instantly match open roles against vetted LATAM engineers or autonomously source live developer profiles via local SearXNG.

2 Developers
1 Dev 3 Devs 6 Devs
$55.00 / hr
$35/hr $55/hr $95/hr
Avg Match Score 85.5% ๐ŸŽฏ Qualified Bench
Allocated Squad 2 Engineers from 12 evaluated
Client Annual Savings $158,800/yr vs US BLS Benchmark
Agency Gross Margin $78,720/yr 37.3% Gross Margin
๐Ÿ“Š Executive Retention, Velocity & QBR Engine

Client Retention, Sprint Velocity & Executive QBR Engine

Automates two-week sprint velocity tracking, Google DORA metrics classification (Elite/High/Medium/Low), realized executive ROI calculations, algorithmic churn risk prediction, and proactive capacity expansion proposals with pre-vetted bench matching.

12 Weeks (6 Sprints)
2 Engineers
Full-time dedicated engineers
$55.00 / hr
All-inclusive client billing
Retention Health 98.5/100 Elite Retention
Say-Do Velocity 96.5% 246 story pts
DORA Rating Elite 3.7h avg cycle
Realized Savings $71,520 57.5% vs US
ROI Multiple 2.35x $215/pt (-58%)
๐Ÿ” AST Static Analysis & Technical Debt Auditor

Repository Due Diligence & Technical Debt Auditor

Automates Python/JS/Go AST analysis, McCabe cyclomatic complexity calculation, security vulnerability & secret leak scanning, dependency license risk evaluation, and quantifies US vs LATAM nearshore refactoring cost arbitrage.

RQI Composite 96.0 Grade A+ (Elite)
Source Volume 74,500 285 files
Test-to-Code 44.0% 32,800 test lines
Complexity & Security 3.4 McCabes 2 security flags
Debt Arbitrage Savings $7,665 66.6% vs US in-house
โ˜๏ธ FinOps & Cloud Infrastructure Arbitrage

Cloud Cost Waste Auditor & Self-Funding DevOps Squad

Model unattached storage, GP2 penalties, overprovisioned EKS/RDS clusters, and fund a dedicated senior LATAM DevOps engineer ($55/hr) 100% out of recaptured cloud waste.

โ˜… 100% Self-Funding Engineering Model PROFIT POSITIVE
Eliminate $15,525/mo in AWS Waste โ†’ Fund Senior DevOps for FREE with +$6,285/mo Net Cash Flow
Instead of paying $165/hr ($27,720/mo) for US DevOps, our dedicated LATAM Senior Cloud/DevOps lead ($55/hr = $9,240/mo) recovers enough idle cloud spend to deliver a 1.68x net cash ROI.
Net Annual Profit
+$75,420
1.68x ROI multiple
1 FTE ($9,240/mo)
Monthly Cloud Spend $45,000 / month
Monthly Spend $45,000 $540k/yr
Identifiable Waste -$15,525 34.5% of bill
FinOps Maturity 46.7 Grade D (Severe Bleed)
LATAM Squad Cost $9,240 @ $55/hr (168 hrs)
Net Client Profit +$6,285 100% Free DevOps
VPS Health Index
98/100 (A+)
Prime Production Status
Service Health
10/10 Active
100% Uptime โ€ข 0 Restarts
Edge API Latency
<1.0 ms
Sub-millisecond Edge Proxies
Cgroup Headroom
>80% Safety
Deterministic OOM Isolation
Kernel TCP Tuning
7/7 Optimal
TCP Fast Open โ€ข Zero Slow Start
Host Resources HEALTHY
CPU Load (1m, 5m, 15m) 0.00, 0.00, 0.00
RAM Available 2,458 MB
RAM Utilization 36.5%
SSD Storage Free 22.2 GB (58.8% free)
Swappiness Policy 10 (Conservative)
Daemon CGroup Containment View Cgroups โ†’
latam-waitlist 94.1 MB (84.3% headroom)
email-listener 17.4 MB (97.3% headroom)
antigravity-telegram 31.7 MB (98.2% headroom)
agent-search-api 41.3 MB (90.8% headroom)
Kernel TCP Parameters View Network โ†’
TCP Fast Open (TFO) Enabled (mode 3)
SYN Backlog Queue 4,096 slots
TCP Slow Start After Idle Disabled (0)
FIN Socket Timeout 15s (4x fast release)
TIME_WAIT Socket Reuse Enabled (1)
SQLite & Journal Health
Active Databases 8/8 Verified OK
Total Storage Footprint 48.5 MB
WAL Compaction Status TRUNCATE (Active)
Freelist Fragmentation 0 Pages (0.0% clean)
Systemd Journal Size 40.0 MB (Auto-vacuum)
File Descriptors & Sockets View FDs โ†’
System Allocated FDs 2,176 handles
System Capacity Util <0.0001% (Unlimited)
Monitored Daemons 9/9 Daemons Tracked
Max Daemon FD Util 1.0% (latam-waitlist)
Socket Leak Status Zero Leaks (Healthy)
Linux VM & Dirty Writeback View VM โ†’
Write Stall Risk ZERO_WRITE_STALL
Dirty Pages in RAM ~1,000 / 89,000
Dirty Background Flusher 10% Memory Ratio
Max Dirty Write Stall 20% Dirty Ratio
VFS Cache Pressure 50 (Aggressive Dentry)
Linux PSI (Hardware Stall) View PSI โ†’
PSI Stall Status OPTIMAL_ZERO_STALL
CPU Stall (avg10) <0.2% (Optimal)
RAM Stall (avg10) 0.00% (Zero Stall)
I/O Stall (avg10) <1.0% (Negligible)
OOM Killer Risk NEGLIGIBLE (Safe)
Service Resilience & Flapping View Resilience โ†’
Resilience Status ROCK_SOLID_100_PERCENT
Total Daemons Tracked 10/10 Online
Total Crash Restarts 0 Restarts
Flapping Daemons 0 Flapping (Zero Risk)
Availability SLA 100.0% Uptime
Disaster Recovery & Hot Backups View Backups โ†’
DR Resilience Score 100.0 / 100 [A+]
RPO Compliance 8/8 Databases (<24h)
RTO Recovery Target <30.0s Atomic Restore
Hot Snapshots Footprint 9.37 MB (Gzip)
Integrity Verification 100% SHA-256 Verified
Perimeter Security & Firewall View Firewall โ†’
Perimeter Security Score 100.0 / 100 [A+]
Loopback Isolation 14/18 Sockets (77.8%)
Unauthorized Ports 0 Detected (Locked)
Host Firewall (UFW) Active (Default Deny)
SSH Hardening Port 51820 (No Password)
๐Ÿ›ฐ๏ธ Autonomous Deep Web Research & Intelligence Engine

Autonomous Company Due Diligence & Technographic Extraction

Zero-cost multi-query intelligence synthesis powered by local SearXNG (14ms latency). Extract verified tech stacks, executive rosters, competitor positioning, and primary citations.

Presets:
Confidence
98.4%
Cross-verified
Category
Open-Source BaaS
Developer Platform
Domain
supabase.com
Verified Root
Capital / Stage
Series B ($116M)
Venture Backed
Headquarters
Singapore / Remote
Global Workforce
Executive Brief: Supabase is an open-source Firebase alternative providing a dedicated PostgreSQL database, instant REST and GraphQL APIs, real-time WebSocket subscriptions, built-in Authentication, Edge Functions, and vector embeddings (pgvector).
๐Ÿ›ก๏ธ Enterprise Vendor Security & SOC-2 / ISO-27001 Auditor

Third-Party Risk Assessment & Procurement Clearance

Automate enterprise vendor security audits, Standardized Information Gathering (SIG Lite) matrices, and Delaware DPA covenants with 100% zero AI model training guarantees.

Archetypes:
Security Index (VSI)
96.7 / 100
Grade A+ (Elite)
Procurement Verdict
Approved โœ“
Tier 1 Partner
Encryption Standard
AES-256 / TLS 1.3
KMS Key Rotation
Breach Notice SLA
< 48 Hours
Exceeds GDPR (72h)
AI Model Training
0% (Zero Training)
Contractual DPA
๐Ÿ“ก Pipeline Quality Sentinel & Extraction SLA Telemetry

Autonomous Data Ingestion & Shannon Entropy Sentinel

Continuous 5-pillar data quality audit, Simpson source diversity, ATS categorization & 24h ingestion SLA enforcement.

Pipeline Quality Index
82.3 / 100
Grade B (Elevated Drift)
Active Requisitions
1,079
390 Canonical Companies
Freshness SLA Status
COMPLIANT
< 24h Ingestion Cadence
Simpson Source Diversity
0.9043
Low Starvation Risk
๐Ÿ—๏ธ Tech Stack Migration & Strangler Fig Forecaster

Autonomous Architecture Modernization Engine

Model Technical Debt Scores (TDS 0-100), Modernization Velocity Index (MVI), 4-phase Strangler Fig roadmaps, and nearshore squad arbitrage.

Target Entity:
Technical Debt Score
62.9 / 100
Scale: 0 (Low) - 100 (Critical)
Velocity Gain (MVI)
3.4x
Post-Cutover PR & Deploy Velocity
Feasibility Grade
B+ Enterprise
Risk Profile: MODERATE
Squad Net Savings
$252,800
3.19x Capital Multiplier (1.5mo Payback)
๐Ÿค– Autonomous AI Workforce & Cybernetic Arbitrage

Autonomous Agentic ROI & Workforce Modeler

Evaluate cognitive task automability (0-100 TAS), frontier model token economics, supporting infrastructure, and 1 Tech Lead + Agent cybernetic squad savings.

Target Enterprise:
Baseline US Team Size: 4 US FTEs
Task Automability (TAS)
90.0 / 100
Tier A: Highly Automatable
Annual Cash Recaptured
+$641,214
86.7% Net Cost Reduction
Monthly Free Cash Flow
+$53,435 / mo
Capital ROI: 7.54x
Throughput Velocity
3.2x
Payback Period: 14 Days
Workforce Model Team Structure Monthly TCO Annual TCO Net Savings vs US Margin %
๐Ÿ’ผ Enterprise CPQ & Client Proposals

Commercial Proposal & CPQ Deal Architect

Configure dedicated engineering squads, model multi-year TCO & NPV savings, calculate payback horizons, and render executive presentation decks.

Target Enterprise:
Annual Net Savings +$493,500 64.9% vs US Onsite
Velocity Multiplier 2.8x Sprint Output Increase
Payback Horizon 0.5 mo Break-Even Milestone
36-Month NPV (8%) +$1,312,373 Discounted Value Created
Horizon US Onsite Benchmark Proposed Retainer Net Cash Savings ROI Multiple
๐ŸŽฏ Commercial Intelligence & Account Strategy

Executive Deal Battlecard & Account Intelligence

Map competitor wedges, SWOT matrices, VP-level discovery trap questions, and objection handling for high-value enterprise accounts.

Target Enterprise:
Active Openings 14 Roles High velocity
US Engineering Base $185,000 Senior domestic salary
Nearshore Pod Cost $85,000 EST/CST aligned
Annual Arbitrage / Dev +$100,000 54.1% net reduction
STRENGTHS
    WEAKNESSES
      OPPORTUNITIES (OUR WEDGES)
        THREATS
          โ›๏ธ Multi-Channel Opportunity Extraction

          Autonomous Lead Miner & Intelligence Engine

          Mine live high-arbitrage remote tech roles, verified LATAM SMB WhatsApp business contacts, and Reddit contractor sentiment.

          Total Leads Mined 15 Verified Leads 3 Ingestion Channels
          Pipeline TAM $1,230,000 Gross contract volume
          Annual Arbitrage TAM +$472,000 $94.4k/hire margin
          Lead Readiness Score 94.8 / 100 Grade A+ Validated
          Role & Company Tech Stack US Benchmark LATAM Cost Annual Arbitrage Urgency Action
          ๐ŸŽฏ Omni-Channel Sales Cadence & Deliverability Copilot

          Sales Outreach Sequence & Deliverability Engine

          Synthesize 5-touch sales playbooks (Email, LinkedIn, WhatsApp & Phone) with real-time spam scoring and Flesch readability analysis.

          Deliverability Score 90.2 / 100 Grade A+ Certified
          Inbox Placement Forecast 96.4% - 98.8% Primary Tab Projected
          Annual Arbitrage Hook +$85,000 Per matched hire
          Flesch Grade Level 11.3 / Grade Executive Readability
          ๐Ÿข Enterprise Deal Room & War Room Orchestrator

          Autonomous Deal Room & Account Pipeline

          Synthesize 360ยฐ Account Intelligence, Stack Modernization, Cybernetic AI Workforce, Boardroom CPQ, Omni-Channel Sales Cadence, and Binding SOW into an executive war room.

          Deal Health Composite 93.0 / 100 Grade A+ (Prime Enterprise Close)
          Estimated Annual ACV $266,880 $22,240 / month retainer
          36-Month Net Present Value +$1,312,373 @ 8% Corporate Hurdle Rate
          Payback & Velocity 0.5 Mo / 2.8x 14-Day 100% Risk-Free Trial
          Key Conversion & Deal Health Drivers Immediate Executive Presentation
          โšก Real-Time Agency Webhooks & Alerts

          Instant Lead Dispatch for Your Agency

          Stream direct-hire requisitions matching your technology stack straight into Slack, Discord, or your CRM.

          HMAC-SHA256 Signed

          Configure Webhook or Email Alert

          Leave blank to receive email alerts only.
          Sample Webhook Delivery Inspector POST application/json
          {
            "event": "job_alert",
            "timestamp": "2026-10-26T20:50:00Z",
            "subscription": {
              "stack_filter": "Python,React",
              "min_salary": 50000
            },
            "matched_count": 15,
            "jobs": [
              {
                "title": "Senior Backend Engineer",
                "company": "Karat",
                "salary": "$80,000 - $120,000 USD",
                "seniority": "Senior",
                "apply_url": "https://..."
              }
            ]
          }
          Headers delivered: X-Radar-Event, X-Radar-Signature: sha256=...
          ๐Ÿ“Š Embeddable Technographic Widget

          Embed Live LATAM Salary & Demand Badges

          Add live compensation percentiles and talent demand to your blog, agency portfolio, or developer community.

          View Pro API Access →
          Live Rendered Preview
          Copy Embed Code (HTML)
          <div class="latam-radar-widget" data-stack="Python" data-theme="dark"></div>
          <script src="https://vasilii.lat/b2b/widget.js" async></script>

          Zero dependencies. Responsive, theme-aware (dark or light), and pulls live NIST-interpolated percentiles directly from our sub-millisecond edge cache.

          The Asymmetrical Business Case

          Why Nearshore Agencies Choose Radar Pro

          A typical nearshore placement yields $6,000+ USD in staffing margin. A single placed engineer pays for 2.5 years of Radar Pro.

          First-Year Value Return
          2.5x – 5.0x

          1 placed candidate out of 1,000+ monitored requisitions pays for your entire annual subscription.

          Time-to-Pitch Advantage
          < 2 Hours

          Real-time webhooks alert your BD team to newly funded startup openings before generic recruiters find them.

          API & Delivery SLA
          99.9% Uptime

          Sub-10ms query latencies via edge reverse proxy with full HMAC-SHA256 signature verification.

          `; } if (demoWidgetContainer) { demoWidgetContainer.innerHTML = `
          `; } }); } if (copyWidgetBtn && widgetCodeBox) { copyWidgetBtn.addEventListener('click', () => { navigator.clipboard.writeText(widgetCodeBox.textContent.trim()); copyWidgetBtn.textContent = 'โœ“ Copied!'; setTimeout(() => { copyWidgetBtn.textContent = '๐Ÿ“‹ Copy Snippet'; }, 2000); }); } // Interactive ROI Calculator Logic const roiPlacementsSlider = document.getElementById('roi-placements-slider'); const roiMarginSlider = document.getElementById('roi-margin-slider'); const roiPlacementsVal = document.getElementById('roi-placements-val'); const roiMarginVal = document.getElementById('roi-margin-val'); const roiGrossVal = document.getElementById('roi-gross-val'); const roiNetGain = document.getElementById('roi-net-gain'); const roiMultiplier = document.getElementById('roi-multiplier'); const roiBreakeven = document.getElementById('roi-breakeven'); function updateRoiCalculations() { if (!roiPlacementsSlider || !roiMarginSlider) return; const placements = parseInt(roiPlacementsSlider.value, 10); const margin = parseFloat(roiMarginSlider.value); if (roiPlacementsVal) roiPlacementsVal.textContent = `${placements} ${placements === 1 ? 'Engineer' : 'Engineers'}`; if (roiMarginVal) roiMarginVal.textContent = `$${margin.toLocaleString('en-US')}`; const annualCost = 2388.0; const totalValue = placements * margin; const netGain = totalValue - annualCost; const mult = (totalValue / annualCost).toFixed(1); const breakevenHires = (annualCost / margin).toFixed(2); const breakevenMos = (breakevenHires / placements * 12).toFixed(1); if (roiGrossVal) roiGrossVal.textContent = `$${totalValue.toLocaleString('en-US')}`; if (roiNetGain) { roiNetGain.textContent = `${netGain >= 0 ? '+' : ''}$${Math.round(netGain).toLocaleString('en-US')}`; if (netGain >= 0) { roiNetGain.className = 'text-2xl font-black font-mono text-emerald-300'; } else { roiNetGain.className = 'text-2xl font-black font-mono text-rose-400'; } } if (roiMultiplier) roiMultiplier.textContent = `${mult}x`; if (roiBreakeven) roiBreakeven.textContent = `${breakevenHires} hires (${breakevenMos} mos)`; } if (roiPlacementsSlider && roiMarginSlider) { roiPlacementsSlider.addEventListener('input', updateRoiCalculations); roiMarginSlider.addEventListener('input', updateRoiCalculations); updateRoiCalculations(); } // CRM Campaign Pack Export Handler const btnExportCampaignPack = document.getElementById('btn-export-campaign-pack'); const campaignPackFormat = document.getElementById('campaign-pack-format'); if (btnExportCampaignPack && campaignPackFormat) { btnExportCampaignPack.addEventListener('click', () => { const fmt = campaignPackFormat.value || 'instantly'; const agencySelect = document.getElementById('match-agency-select'); let stackParam = ''; if (agencySelect && agencySelect.value === 'custom') { const customStack = document.getElementById('match-custom-stacks'); if (customStack && customStack.value) { stackParam = `&stack=${encodeURIComponent(customStack.value.trim())}`; } } window.location.href = `/b2b/campaign-pack.csv?format=${fmt}${stackParam}`; }); } // Lead Enrichment Engine function setEnrichCompany(name) { const inp = document.getElementById('enrich-company-input'); if (inp) { inp.value = name; performEnrichment(); } } function performEnrichment() { const inp = document.getElementById('enrich-company-input'); const container = document.getElementById('enrich-results-container'); const btn = document.getElementById('download-enrich-btn'); const spinner = document.getElementById('enrich-btn-spinner'); if (!inp || !container) return; const comp = inp.value.trim(); if (!comp) return; if (spinner) spinner.classList.remove('hidden'); if (btn) btn.href = `/b2b/enrich.csv?company=${encodeURIComponent(comp)}`; container.innerHTML = `
          ๐Ÿ” Querying local SearXNG & cross-referencing radar requisitions for ${comp}...
          `; fetch(`/b2b/api/enrich?company=${encodeURIComponent(comp)}`) .then(r => r.json()) .then(res => { if (spinner) spinner.classList.add('hidden'); if (res.status !== 'success' || !res.data) { container.innerHTML = `
          Failed to enrich company.
          `; return; } const d = res.data; const radar = d.radar_intelligence || {}; const dms = d.decision_makers || []; const stacks = (radar.top_stacks || []).slice(0, 5).join(', '); let html = `
          ${d.company} https://${d.domain}
          ${radar.open_roles_count || 0} active roles ${d.speed_sec}s
          Active Stacks: ${stacks || 'General Software Engineering'}
          Talent Inboxes: ${(d.talent_aliases || []).join(', ') || 'N/A'}

          Discovered Engineering & Executive Leadership (${dms.length})

          `; if (dms.length === 0) { html += `
          No executive profiles discovered via LinkedIn query. Use talent aliases above for outreach.
          `; } else { dms.forEach(dm => { const pitch = dm.outreach_pitch || {}; const note = (pitch.linkedin_note || '').replace(/"/g, '"'); html += `
          ${dm.name}
          LinkedIn

          ${dm.headline}

          ๐Ÿ“ ${dm.location}

          Email: ${dm.primary_email || 'N/A'}
          LinkedIn Pitch Note: "${dm.outreach_pitch?.linkedin_note || ''}"
          `; }); } html += `
          `; container.innerHTML = html; }) .catch(err => { if (spinner) spinner.classList.add('hidden'); container.innerHTML = `
          Error querying enrichment endpoint: ${err.message}
          `; }); } // Cost Arbitrage Calculator & Proposal Generator let _arbData = null; let _arbDebounce = null; function setArbitrageCompany(name) { const inp = document.getElementById('arb-company'); if (inp) { inp.value = name; calculateArbitrageLive(); } } function calculateArbitrageLive() { if (_arbDebounce) clearTimeout(_arbDebounce); _arbDebounce = setTimeout(() => { const comp = document.getElementById('arb-company')?.value.trim() || 'Scaleup'; const stack = document.getElementById('arb-stack')?.value || 'Python,Kubernetes'; const teamSize = document.getElementById('arb-team-size')?.value || 2; const billRate = document.getElementById('arb-bill-rate')?.value || 59; const btn = document.getElementById('download-arbitrage-btn'); if (btn) { btn.href = `/b2b/arbitrage-proposal.md?company=${encodeURIComponent(comp)}&stack=${encodeURIComponent(stack)}&team_size=${teamSize}&bill_rate=${billRate}`; } fetch(`/b2b/api/arbitrage?company=${encodeURIComponent(comp)}&stack=${encodeURIComponent(stack)}&team_size=${teamSize}&bill_rate=${billRate}`) .then(r => r.json()) .then(res => { if (res.status !== 'success' || !res.data) return; _arbData = res.data; const m = res.data.metrics; const arb = m.arbitrage_savings; const us = m.us_market; const ns = m.nearshore_agency; const elUsCost = document.getElementById('arb-us-cost'); if (elUsCost) elUsCost.textContent = '$' + Math.round(us.total_team_annual_cost).toLocaleString(); const elUsRate = document.getElementById('arb-us-rate'); if (elUsRate) elUsRate.textContent = '$' + us.effective_hourly_rate.toFixed(2) + '/hr loaded'; const elNsCost = document.getElementById('arb-ns-cost'); if (elNsCost) elNsCost.textContent = '$' + Math.round(ns.total_team_annual_cost).toLocaleString(); const elNsRate = document.getElementById('arb-ns-rate'); if (elNsRate) elNsRate.textContent = '$' + ns.hourly_bill_rate.toFixed(2) + '/hr billed'; const elBadge = document.getElementById('arb-savings-badge'); if (elBadge) elBadge.textContent = arb.savings_percentage + '%'; const elSavings = document.getElementById('arb-savings-total'); if (elSavings) elSavings.textContent = '$' + Math.round(arb.total_annual_savings).toLocaleString() + ' / yr'; const elMonthly = document.getElementById('arb-monthly-savings'); if (elMonthly) elMonthly.textContent = '$' + Math.round(arb.total_monthly_savings).toLocaleString() + ' / mo burn reduction'; const elRunway = document.getElementById('arb-runway'); if (elRunway) elRunway.textContent = '+' + arb.net_runway_extension_months + ' Months'; const elMargin = document.getElementById('arb-agency-margin'); if (elMargin) elMargin.textContent = 'Agency Profit: $' + Math.round(ns.total_agency_annual_margin).toLocaleString() + '/yr'; const assets = res.data.sales_assets || {}; const elEmail = document.getElementById('arb-preview-email'); if (elEmail) elEmail.textContent = assets.cold_email_body || ''; const elLi = document.getElementById('arb-preview-linkedin'); if (elLi) elLi.textContent = assets.linkedin_connection_note || ''; const elCfo = document.getElementById('arb-preview-cfo'); if (elCfo) elCfo.textContent = assets.day4_cfo_bump || ''; }) .catch(err => console.error('Arbitrage calculation error:', err)); }, 150); } function copyArbitrageAsset(type) { if (!_arbData || !_arbData.sales_assets) { alert('Please wait for proposal calculation to finish.'); return; } let text = ''; if (type === 'email') text = _arbData.sales_assets.cold_email_body; else if (type === 'linkedin') text = _arbData.sales_assets.linkedin_connection_note; else if (type === 'cfo') text = _arbData.sales_assets.day4_cfo_bump; if (text) { navigator.clipboard.writeText(text); alert('Copied ' + type.toUpperCase() + ' sales copy to clipboard!'); } } let _seqData = null; let _seqDebounce = null; let _seqActiveStep = 1; function selectSequenceTab(stepNum) { _seqActiveStep = stepNum; for (let i = 1; i <= 5; i++) { const btn = document.getElementById('seq-tab-btn-' + i); if (btn) { if (i === stepNum) { btn.className = "px-3 py-1.5 text-xs font-semibold rounded-lg bg-purple-600 text-white transition"; } else { btn.className = "px-3 py-1.5 text-xs font-semibold rounded-lg bg-slate-800 text-slate-400 hover:text-white transition"; } } } renderSequenceStep(); } function renderSequenceStep() { if (!_seqData || !_seqData.sequence_steps) return; const step = _seqData.sequence_steps.find(s => s.step_number === _seqActiveStep); if (!step) return; const elTitle = document.getElementById('seq-step-title'); const elSubjCont = document.getElementById('seq-subject-container'); const elSubj = document.getElementById('seq-subject-text'); const elBody = document.getElementById('seq-body-text'); if (step.channel === 'LinkedIn') { if (elTitle) elTitle.textContent = `Step 2: LinkedIn Note (${step.character_count}/300 chars)`; if (elSubjCont) elSubjCont.style.display = 'none'; if (elBody) elBody.textContent = step.note || ''; } else { if (elTitle) elTitle.textContent = `Step ${step.step_number}: ${step.channel} (Day ${step.day})`; if (elSubjCont) elSubjCont.style.display = 'block'; if (elSubj) elSubj.textContent = step.subject || ''; if (elBody) elBody.textContent = step.body || ''; } } function loadSequenceLive() { if (_seqDebounce) clearTimeout(_seqDebounce); _seqDebounce = setTimeout(() => { const comp = document.getElementById('seq-company')?.value.trim() || 'Supabase'; const stack = document.getElementById('seq-stack')?.value || 'Python,Kubernetes'; const contact = document.getElementById('seq-contact')?.value || 'Ant Wilson (CTO)'; const rate = document.getElementById('seq-rate')?.value || 48; fetch(`/b2b/api/sequence?company=${encodeURIComponent(comp)}&stack=${encodeURIComponent(stack)}&contact_name=${encodeURIComponent(contact)}&bill_rate=${rate}`) .then(r => r.json()) .then(res => { if (res.status !== 'success' || !res.data) return; _seqData = res.data; const p = res.data.projections || {}; const f = p.funnel_rates || {}; const c = p.projected_counts || {}; const fin = p.financial_outcomes || {}; const elDel = document.getElementById('proj-deliverability'); if (elDel && f.deliverability_pct) elDel.textContent = f.deliverability_pct + '%'; const elOpen = document.getElementById('proj-opens'); if (elOpen && f.open_rate_pct) elOpen.textContent = f.open_rate_pct + '%'; const elRep = document.getElementById('proj-replies'); if (elRep && f.reply_rate_pct) elRep.textContent = f.reply_rate_pct + '%'; const elMeet = document.getElementById('proj-meetings'); if (elMeet && f.meeting_booking_pct) elMeet.textContent = f.meeting_booking_pct + '%'; const elPipe = document.getElementById('proj-pipeline'); if (elPipe && fin.projected_pipeline_value) elPipe.textContent = '$' + Math.round(fin.projected_pipeline_value).toLocaleString(); const elSav = document.getElementById('proj-savings'); if (elSav && res.data.metadata?.total_annual_savings) elSav.textContent = '$' + Math.round(res.data.metadata.total_annual_savings).toLocaleString(); // Render candidates const cList = document.getElementById('seq-candidates-list'); if (cList && res.data.candidates) { cList.innerHTML = res.data.candidates.map(cand => `
          ${cand.name} $${Math.round(cand.hourly_rate)}/hr
          ${cand.title} โ€ข ${cand.location}
          ${cand.skills.slice(0, 3).join(', ')}
          `).join(''); } renderSequenceStep(); }) .catch(err => console.error('Sequence loading error:', err)); }, 150); } function copySequenceActiveStep() { if (!_seqData || !_seqData.sequence_steps) return; const step = _seqData.sequence_steps.find(s => s.step_number === _seqActiveStep); if (!step) return; const text = step.channel === 'LinkedIn' ? step.note : `${step.subject} ${step.body}`; navigator.clipboard.writeText(text); const lbl = document.getElementById('copy-seq-label'); if (lbl) { lbl.textContent = 'Copied!'; setTimeout(() => { lbl.textContent = 'Copy Copy'; }, 2000); } } function downloadSequenceExport() { const sel = document.getElementById('sequence-export-select'); const fmt = sel ? sel.value : 'playbook'; const comp = document.getElementById('seq-company')?.value.trim() || 'Supabase'; const stack = document.getElementById('seq-stack')?.value || 'Python,Kubernetes'; const contact = document.getElementById('seq-contact')?.value || 'Ant Wilson (CTO)'; const rate = document.getElementById('seq-rate')?.value || 48; window.location.href = `/b2b/sequence-export?company=${encodeURIComponent(comp)}&stack=${encodeURIComponent(stack)}&contact_name=${encodeURIComponent(contact)}&bill_rate=${rate}&format=${fmt}`; } // Deal Closer & SOW Generator JS Logic let _dealData = null; let _dealDebounce = null; function setDealCompany(name) { const inp = document.getElementById('deal-company'); if (inp) { inp.value = name; calculateDealLive(); } } function calculateDealLive() { if (_dealDebounce) clearTimeout(_dealDebounce); _dealDebounce = setTimeout(() => { const comp = document.getElementById('deal-company')?.value.trim() || 'Scaleup Technologies'; const model = document.getElementById('deal-model')?.value || 'retainer'; const teamSize = document.getElementById('deal-team-size')?.value || 2; const billRate = document.getElementById('deal-bill-rate')?.value || 55; const talentCost = document.getElementById('deal-talent-cost')?.value || 32; const url = `/b2b/api/deal?company=${encodeURIComponent(comp)}&model=${encodeURIComponent(model)}&team_size=${teamSize}&bill_rate=${billRate}&talent_cost=${talentCost}`; fetch(url) .then(res => res.json()) .then(data => { if (data.status !== 'success') return; _dealData = data; const f = data.financials; const s = data.sow; // Update KPI Cards const elSav = document.getElementById('deal-kpi-savings'); if (elSav) elSav.textContent = '$' + Number(f.client_annual_savings).toLocaleString() + ' / yr'; const elSavPct = document.getElementById('deal-kpi-savings-pct'); if (elSavPct) elSavPct.textContent = f.client_savings_pct + '% vs US Onshore'; const elMo = document.getElementById('deal-kpi-agency-monthly'); if (elMo) elMo.textContent = '$' + Number(f.agency_gross_margin_monthly).toLocaleString() + ' / mo'; const elMar = document.getElementById('deal-kpi-agency-margin'); if (elMar) elMar.textContent = f.agency_gross_margin_pct + '% Gross Margin'; const elYr = document.getElementById('deal-kpi-agency-annual'); if (elYr) elYr.textContent = '$' + Number(f.agency_gross_margin_annual).toLocaleString() + ' / yr'; const elRoi = document.getElementById('deal-kpi-roi'); if (elRoi) elRoi.textContent = f.radar_saas_annual_roi_multiple + 'x ROI'; const elBk = document.getElementById('deal-kpi-breakeven'); if (elBk) elBk.textContent = 'Breakeven in ' + f.radar_saas_breakeven_working_days + ' days'; // Update Rates label const elRatesLbl = document.getElementById('deal-rates-label'); if (elRatesLbl) elRatesLbl.textContent = '$' + f.bill_rate_hourly + ' / $' + f.talent_cost_hourly + ' hr'; // Update SOW markdown view const elSow = document.getElementById('deal-view-sow'); if (elSow) elSow.textContent = s.markdown; // Update Economics Tab const elEcComp = document.getElementById('econ-company'); if (elEcComp) elEcComp.textContent = f.company_name; const elEcSq = document.getElementById('econ-squad'); if (elEcSq) elEcSq.textContent = f.team_size + ' Dev(s)'; const elEcBill = document.getElementById('econ-bill-rate'); if (elEcBill) elEcBill.textContent = '$' + Number(f.bill_rate_hourly).toFixed(2) + '/hr'; const elEcTal = document.getElementById('econ-talent-cost'); if (elEcTal) elEcTal.textContent = '$' + Number(f.talent_cost_hourly).toFixed(2) + '/hr'; const elEcClMo = document.getElementById('econ-client-monthly'); if (elEcClMo) elEcClMo.textContent = '$' + Number(f.client_monthly_spend).toLocaleString(); const elEcClSav = document.getElementById('econ-client-savings'); if (elEcClSav) elEcClSav.textContent = '$' + Number(f.client_annual_savings).toLocaleString() + ' (' + f.client_savings_pct + '%)'; const elEcMarHr = document.getElementById('econ-margin-hr'); if (elEcMarHr) elEcMarHr.textContent = '$' + Number(f.agency_gross_margin_hourly).toFixed(2) + '/hr (' + f.agency_gross_margin_pct + '%)'; const elEcMarMo = document.getElementById('econ-margin-mo'); if (elEcMarMo) elEcMarMo.textContent = '$' + Number(f.agency_gross_margin_monthly).toLocaleString() + ' / mo'; const elEcMarYr = document.getElementById('econ-margin-yr'); if (elEcMarYr) elEcMarYr.textContent = '$' + Number(f.agency_gross_margin_annual).toLocaleString() + ' / yr'; const elEcPay = document.getElementById('econ-payback'); if (elEcPay) elEcPay.textContent = f.radar_saas_breakeven_working_days + ' working days'; const elEcRoi = document.getElementById('econ-roi-multiple'); if (elEcRoi) elEcRoi.textContent = f.radar_saas_annual_roi_multiple + 'x Multiple'; // Update Action Links const dlBtn = document.getElementById('download-deal-sow-btn'); if (dlBtn) dlBtn.href = `/b2b/deal-sow.md?company=${encodeURIComponent(comp)}&team_size=${teamSize}&bill_rate=${billRate}&talent_cost=${talentCost}&model=${encodeURIComponent(model)}`; const prBtn = document.getElementById('view-deal-contract-btn'); if (prBtn) prBtn.href = `/b2b/deal-contract.html?company=${encodeURIComponent(comp)}&team_size=${teamSize}&bill_rate=${billRate}&talent_cost=${talentCost}&model=${encodeURIComponent(model)}`; }) .catch(err => console.error('Deal closer error:', err)); }, 150); } function switchDealTab(tab) { ['sow', 'economics', 'webhook'].forEach(t => { const el = document.getElementById('deal-view-' + t); const btn = document.getElementById('deal-tab-btn-' + t); if (el) el.classList.toggle('hidden', t !== tab); if (btn) { if (t === tab) { btn.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40'; } else { btn.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-400 hover:text-white'; } } }); } function copyDealSow() { if (!_dealData || !_dealData.sow) { alert('Please wait for SOW calculation to complete.'); return; } navigator.clipboard.writeText(_dealData.sow.markdown); alert('Statement of Work copied to clipboard!'); } function dispatchDealWebhook() { const urlInp = document.getElementById('deal-webhook-url'); const feedback = document.getElementById('deal-webhook-feedback'); const url = urlInp ? urlInp.value.trim() : ''; if (!url || !url.startsWith('http')) { if (feedback) feedback.innerHTML = 'Please provide a valid HTTP/HTTPS webhook URL.'; return; } if (feedback) feedback.innerHTML = 'Dispatching deal packet...'; fetch('/b2b/api/deal/webhook', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ webhook_url: url, deal_packet: _dealData, dry_run: false }) }) .then(res => res.json()) .then(res => { if (res.status === 'success') { if (feedback) feedback.innerHTML = `โœ“ [HTTP ${res.code}] ${res.message}`; } else { if (feedback) feedback.innerHTML = `โœ— [HTTP ${res.code || 500}] ${res.message}`; } }) .catch(err => { if (feedback) feedback.innerHTML = `Dispatch Error: ${err.message}`; }); } // ------------------------------------------------------------------------ // Candidate Technical Vetting & Assessment Matrix Controller // ------------------------------------------------------------------------ let _vetData = null; let _vetDebounceTimer = null; function debounceRecalcVet() { if (_vetDebounceTimer) clearTimeout(_vetDebounceTimer); _vetDebounceTimer = setTimeout(calculateVetLive, 200); } function setVetPreset(company, role, stack, seniority) { const elC = document.getElementById('vet-input-company'); const elR = document.getElementById('vet-input-role'); const elS = document.getElementById('vet-input-stack'); const elL = document.getElementById('vet-input-seniority'); if (elC) elC.value = company; if (elR) elR.value = role; if (elS) elS.value = stack; if (elL) elL.value = seniority; calculateVetLive(); } function calculateVetLive() { const elC = document.getElementById('vet-input-company'); const elR = document.getElementById('vet-input-role'); const elS = document.getElementById('vet-input-stack'); const elL = document.getElementById('vet-input-seniority'); const company = elC ? elC.value.trim() : 'Supabase'; const role = elR ? elR.value.trim() : 'Senior Cloud & Backend Engineer'; const stack = elS ? elS.value.trim() : 'Python, Kubernetes, PostgreSQL'; const seniority = elL ? elL.value.trim() : 'senior'; const qs = new URLSearchParams({ company, role, stack, seniority }).toString(); fetch(`/b2b/api/vet?${qs}`) .then(res => res.json()) .then(res => { if (res.status !== 'success') return; _vetData = res; const r = res.rubric; // Update KPIs const elId = document.getElementById('vet-kpi-id'); if (elId) elId.textContent = r.assessment_id; const elSc = document.getElementById('vet-kpi-score'); if (elSc) elSc.textContent = r.seniority_profile.expected_score_range; // Update Rubric View const elRub = document.getElementById('vet-view-rubric'); if (elRub) elRub.textContent = res.markdown_rubric; // Update Questions View const elQList = document.getElementById('vet-questions-list'); if (elQList) { if (r.deep_technical_questions && r.deep_technical_questions.length > 0) { elQList.innerHTML = r.deep_technical_questions.map((q, idx) => `
          Inquiry #${idx + 1}: ${q.question}
          Ideal Response: ${q.expected}
          Disqualifying Red Flag: ${q.red_flag}
          `).join(''); } else { elQList.innerHTML = '
          No stack-specific inquiries found.
          '; } } // Update Coding Challenge View const elChBox = document.getElementById('vet-challenge-box'); if (elChBox) { if (r.live_coding_challenges && r.live_coding_challenges.length > 0) { const ch = r.live_coding_challenges[0]; elChBox.innerHTML = `
          ${ch.title}
          ${ch.scenario}
          Scoring Criteria: ${ch.evaluation_criteria}
          `; } else { elChBox.innerHTML = '
          No challenge scenarios available.
          '; } } // Update Download & Printable Links const dlBtn = document.getElementById('download-vet-rubric-btn'); if (dlBtn) dlBtn.href = `/b2b/vet-rubric.md?${qs}`; const prBtn = document.getElementById('view-vet-scorecard-btn'); if (prBtn) prBtn.href = `/b2b/vet-scorecard.html?${qs}`; }) .catch(err => console.error('Candidate vetting calculation error:', err)); } function switchVetTab(tab) { ['rubric', 'questions', 'challenge'].forEach(t => { const el = document.getElementById('vet-view-' + t); const btn = document.getElementById('vet-tab-btn-' + t); if (el) el.classList.toggle('hidden', t !== tab); if (btn) { if (t === tab) { btn.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold bg-sky-500/20 text-sky-300 border border-sky-500/40'; } else { btn.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-400 hover:text-white'; } } }); } function copyVetRubric() { if (!_vetData || !_vetData.markdown_rubric) { alert('Please wait for vetting rubric generation to complete.'); return; } navigator.clipboard.writeText(_vetData.markdown_rubric); alert('Candidate Vetting Rubric copied to clipboard!'); } // ------------------------------------------------------------------------ // Client Onboarding, Compliance & Milestone Invoicing Controller // ------------------------------------------------------------------------ let _onboardData = null; let _onboardDebounceTimer = null; function debounceRecalcOnboard() { if (_onboardDebounceTimer) clearTimeout(_onboardDebounceTimer); _onboardDebounceTimer = setTimeout(calculateOnboardLive, 200); } async function calculateOnboardLive() { const company = document.getElementById('onboard-input-company')?.value.trim() || 'Supabase'; const country = document.getElementById('onboard-input-country')?.value || 'colombia'; const cycle = document.getElementById('onboard-input-cycle')?.value || 'monthly'; const stack = document.getElementById('onboard-input-stack')?.value.trim() || 'Python, Kubernetes'; const squad = parseInt(document.getElementById('onboard-slider-squad')?.value || '2', 10); const rate = parseFloat(document.getElementById('onboard-slider-rate')?.value || '55.0'); // Update slider labels const squadDisp = document.getElementById('onboard-squad-display'); if (squadDisp) squadDisp.textContent = `${squad} Developer${squad > 1 ? 's' : ''}`; const rateDisp = document.getElementById('onboard-rate-display'); if (rateDisp) rateDisp.textContent = `$${rate.toFixed(2)} / hr`; // Update download links const compBtn = document.getElementById('download-onboard-compliance-btn'); if (compBtn) compBtn.href = `/b2b/onboard-compliance.md?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&squad_size=${squad}&bill_rate=${rate}&billing_cycle=${cycle}&country=${country}`; const invBtn = document.getElementById('view-client-invoice-btn'); if (invBtn) invBtn.href = `/b2b/client-invoice.html?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&squad_size=${squad}&bill_rate=${rate}&billing_cycle=${cycle}&country=${country}`; try { const res = await fetch('/b2b/api/onboard', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ company: company, country: country, billing_cycle: cycle, stack: stack, squad_size: squad, bill_rate: rate, email: 'finance@' + company.toLowerCase().replace(/[^a-z0-9]/g, '') + '.com' }) }); const data = await res.json(); if (data.status !== 'success') return; _onboardData = data; const pack = data.onboarding_pack; const inv = pack.milestone_invoice; const rails = pack.payment_rail_economics; // KPI badges const kpiTot = document.getElementById('onboard-kpi-total'); if (kpiTot) kpiTot.textContent = `$${inv.total_due_usd.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`; const kpiSub = document.getElementById('onboard-kpi-subtext'); if (kpiSub) kpiSub.textContent = inv.billing_cycle_label; const kpiDisc = document.getElementById('onboard-kpi-discount'); if (kpiDisc) kpiDisc.textContent = `$${inv.early_discount_savings_usd.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`; const kpiSav = document.getElementById('onboard-kpi-savings'); if (kpiSav) kpiSav.textContent = `$${Math.round(rails.max_annual_fee_savings_usd).toLocaleString()}/yr`; const kpiRail = document.getElementById('onboard-kpi-rail'); if (kpiRail) kpiRail.textContent = `via ${rails.recommended_rail}`; // Compliance View const compView = document.getElementById('onboard-view-compliance'); if (compView) compView.textContent = data.markdown_compliance || ''; // Invoice Preview const invBox = document.getElementById('onboard-invoice-preview'); if (invBox) { invBox.innerHTML = `
          Invoice ${inv.invoice_number}
          ${inv.client.company_name} • ${inv.billing_cycle_label}
          Issue Date: ${inv.issue_date} | Due Date: ${inv.due_date}
          Amount Due
          $${inv.total_due_usd.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}
          0.0% US Withholding (IRC ยง 861)
          Wire Remittance ${inv.remittance_options.wire_swift.bank_name} SWIFT: ${inv.remittance_options.wire_swift.swift_bic}
          Wise ACH Rail ${inv.remittance_options.wise_ach.wise_account} Routing: ${inv.remittance_options.wise_ach.ach_routing}
          Digital Dollar (USDC) ${inv.remittance_options.digital_dollar_usdc.erc20_address.substring(0, 24)}...
          `; } // Rails Table const tbody = document.getElementById('onboard-rails-table-body'); if (tbody && rails.rails) { tbody.innerHTML = rails.rails.map(r => ` ${r.name} ${r.type} ${r.settlement_speed} $${r.annual_tx_fees_usd.toLocaleString('en-US', {minimumFractionDigits: 2})} $${r.annual_fx_loss_usd.toLocaleString('en-US', {minimumFractionDigits: 2})} $${r.total_annual_friction_usd.toLocaleString('en-US', {minimumFractionDigits: 2})} (${r.friction_percentage}%) +$${r.annual_savings_vs_swift_usd.toLocaleString('en-US', {minimumFractionDigits: 2})} `).join(''); } } catch (err) { console.error("Onboard calculation error:", err); } } function switchOnboardTab(tab) { ['invoice', 'compliance', 'rails'].forEach(t => { const v = document.getElementById(`onboard-view-${t}`); const btn = document.getElementById(`onboard-tab-btn-${t}`); if (v) { if (t === tab) v.classList.remove('hidden'); else v.classList.add('hidden'); } if (btn) { if (t === tab) { btn.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40'; } else { btn.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-400 hover:text-white'; } } }); } function copyOnboardCompliance() { if (!_onboardData || !_onboardData.markdown_compliance) { alert('Please wait for compliance generation to complete.'); return; } navigator.clipboard.writeText(_onboardData.markdown_compliance); alert('International Compliance Pack copied to clipboard!'); } // ------------------------------------------------------------------------ // Candidate Sourcing & Talent Matcher Controller // ------------------------------------------------------------------------ let _talentData = null; let _talentDebounceTimer = null; function debounceRecalcTalent() { if (_talentDebounceTimer) clearTimeout(_talentDebounceTimer); _talentDebounceTimer = setTimeout(calculateTalentLive, 200); } function setTalentStackPreset(stack) { const inp = document.getElementById('talent-input-stack'); if (inp) { inp.value = stack; debounceRecalcTalent(); } } async function calculateTalentLive() { const company = document.getElementById('talent-input-company')?.value.trim() || 'Supabase'; const role = document.getElementById('talent-input-role')?.value.trim() || 'Senior Backend Engineer'; const seniority = document.getElementById('talent-input-seniority')?.value || 'senior'; const country = document.getElementById('talent-input-country')?.value || ''; const stack = document.getElementById('talent-input-stack')?.value.trim() || 'Python, Kubernetes, PostgreSQL'; const squad = parseInt(document.getElementById('talent-slider-squad')?.value || '2', 10); const rate = parseFloat(document.getElementById('talent-slider-rate')?.value || '55.0'); // Update slider labels const squadDisp = document.getElementById('talent-squad-display'); if (squadDisp) squadDisp.textContent = `${squad} Developer${squad > 1 ? 's' : ''}`; const rateDisp = document.getElementById('talent-rate-display'); if (rateDisp) rateDisp.textContent = `$${rate.toFixed(2)} / hr`; // Update download links const shortBtn = document.getElementById('download-talent-shortlist-btn'); if (shortBtn) shortBtn.href = `/b2b/talent-shortlist.md?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&seniority=${seniority}&role=${encodeURIComponent(role)}&bill_rate=${rate}&team_size=${squad}&country=${encodeURIComponent(country)}`; const deckBtn = document.getElementById('view-talent-deck-btn'); if (deckBtn) deckBtn.href = `/b2b/talent-deck.html?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&seniority=${seniority}&role=${encodeURIComponent(role)}&bill_rate=${rate}&team_size=${squad}&country=${encodeURIComponent(country)}`; try { const res = await fetch('/b2b/api/talent/match', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ company: company, role: role, seniority: seniority, country: country || null, stack: stack, team_size: squad, bill_rate: rate, min_score: 60.0 }) }); const data = await res.json(); if (data.status !== 'success') return; _talentData = data.requisition; const summ = _talentData.summary; const candidates = _talentData.matched_candidates || []; // KPI badges const kpiScore = document.getElementById('talent-kpi-score'); if (kpiScore) kpiScore.textContent = `${summ.squad_avg_match_score}%`; const kpiSquad = document.getElementById('talent-kpi-squad'); if (kpiSquad) kpiSquad.textContent = `${summ.squad_size_allocated} Engineer${summ.squad_size_allocated > 1 ? 's' : ''}`; const kpiCand = document.getElementById('talent-kpi-candidates'); if (kpiCand) kpiCand.textContent = `from ${summ.total_candidates_evaluated} evaluated (${summ.qualified_matches_count} qualified)`; const kpiSav = document.getElementById('talent-kpi-savings'); if (kpiSav) kpiSav.textContent = `$${Math.round(summ.squad_annual_client_savings).toLocaleString()}/yr`; const kpiMarg = document.getElementById('talent-kpi-margin'); if (kpiMarg) kpiMarg.textContent = `$${Math.round(summ.squad_annual_agency_margin).toLocaleString()}/yr`; // Candidate Cards const container = document.getElementById('talent-cards-container'); if (container) { const topPicks = candidates.slice(0, 4); container.innerHTML = topPicks.map((c, i) => { const m = c.match_analysis; const econ = m.economic_arbitrage; const color = m.color_code || '#0284c7'; const primPills = c.primary_stack.map(s => `${s}`).join(' '); const secPills = c.secondary_stack.slice(0, 4).map(s => `${s}`).join(' '); const pastScale = c.past_scaleups.join(', '); return `
          Top Match #${i + 1} • ${c.id}
          ${c.display_name}
          ${c.role_title} (${c.years_experience} yrs)
          ${m.total_score.toFixed(0)}%
          ${m.verdict}
          ๐Ÿ“ Location: ${c.city}, ${c.country} (${c.timezone}) • ${c.timezone_overlap_hours}h Overlap
          ๐Ÿ—ฃ๏ธ English: ${c.english_level}
          ๐Ÿข Scaleups: ${pastScale}
          ๐Ÿš€ ${c.key_highlight}
          Core: ${primPills}
          Tools: ${secPills}
          $${rate.toFixed(2)}/hr (Base: $${c.base_hourly_cost.toFixed(0)}/hr)
          +$${Math.round(econ.client_annual_savings_vs_us).toLocaleString()}/yr saved
          `; }).join(''); } // Economics Table const tbody = document.getElementById('talent-economics-table-body'); if (tbody) { tbody.innerHTML = candidates.map(c => { const m = c.match_analysis; const econ = m.economic_arbitrage; return ` ${c.display_name} ${c.country} (${c.timezone}) $${c.base_hourly_cost.toFixed(2)}/hr $${rate.toFixed(2)}/hr +$${econ.agency_hourly_margin.toFixed(2)}/hr (${econ.agency_gross_margin_pct}%) +$${Math.round(econ.client_annual_savings_vs_us).toLocaleString()}/yr ${m.total_score.toFixed(1)}% `; }).join(''); } // Shortlist Markdown Preview const shortView = document.getElementById('talent-view-shortlist'); if (shortView) { try { const mdRes = await fetch(`/b2b/talent-shortlist.md?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&seniority=${seniority}&role=${encodeURIComponent(role)}&bill_rate=${rate}&team_size=${squad}&country=${encodeURIComponent(country)}`); shortView.textContent = await mdRes.text(); } catch (e) { shortView.textContent = "Error loading markdown shortlist."; } } } catch (err) { console.error("Talent matching error:", err); } } function switchTalentTab(tab) { ['candidates', 'shortlist', 'economics'].forEach(t => { const v = document.getElementById(`talent-view-${t}`); const btn = document.getElementById(`talent-tab-${t}`); if (v) { if (t === tab) v.classList.remove('hidden'); else v.classList.add('hidden'); } if (btn) { if (t === tab) { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-cyan-600 text-slate-950 transition'; } else { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; } } }); } let _perfData = null; let _perfDebounceTimer = null; function debounceRecalcPerf() { if (_perfDebounceTimer) clearTimeout(_perfDebounceTimer); _perfDebounceTimer = setTimeout(calculatePerfLive, 200); } function setPerfStack(stack) { const inp = document.getElementById('perf-input-stack'); if (inp) { inp.value = stack; debounceRecalcPerf(); } } async function calculatePerfLive() { const company = document.getElementById('perf-input-company')?.value.trim() || 'Supabase'; const seniority = document.getElementById('perf-input-seniority')?.value || 'senior'; const quarter = document.getElementById('perf-input-quarter')?.value.trim() || 'Q4 2026'; const stack = document.getElementById('perf-input-stack')?.value.trim() || 'Python, Kubernetes, PostgreSQL'; const podSize = parseInt(document.getElementById('perf-slider-pod')?.value || '2', 10); const rate = parseFloat(document.getElementById('perf-slider-rate')?.value || '55.0'); const weeks = parseInt(document.getElementById('perf-slider-weeks')?.value || '12', 10); const podDisp = document.getElementById('perf-pod-display'); if (podDisp) podDisp.textContent = `${podSize} Engineer${podSize > 1 ? 's' : ''}`; const rateDisp = document.getElementById('perf-rate-display'); if (rateDisp) rateDisp.textContent = `$${rate.toFixed(2)} / hr`; const weeksDisp = document.getElementById('perf-weeks-display'); if (weeksDisp) weeksDisp.textContent = `${weeks} Weeks (${Math.round(weeks / 2)} Sprints)`; const repBtn = document.getElementById('download-qbr-report-btn'); if (repBtn) repBtn.href = `/b2b/qbr-report.md?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&seniority=${seniority}&bill_rate=${rate}&pod_size=${podSize}&weeks=${weeks}&quarter=${encodeURIComponent(quarter)}`; const deckBtn = document.getElementById('view-qbr-deck-btn'); if (deckBtn) deckBtn.href = `/b2b/qbr-deck.html?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&seniority=${seniority}&bill_rate=${rate}&pod_size=${podSize}&weeks=${weeks}&quarter=${encodeURIComponent(quarter)}`; try { const res = await fetch('/b2b/api/performance/report', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ company: company, stack: stack, seniority: seniority, bill_rate: rate, pod_size: podSize, weeks: weeks, quarter: quarter, }) }); const data = await res.json(); if (data.status !== 'success') return; _perfData = data.dossier; const s = _perfData.sprint_metrics; const d = _perfData.dora_metrics; const r = _perfData.realized_roi; const h = _perfData.retention_health; const e = _perfData.expansion_recommendation; // KPI badges const kpiHealth = document.getElementById('perf-kpi-health'); if (kpiHealth) kpiHealth.textContent = `${h.health_score}/100`; const kpiTier = document.getElementById('perf-kpi-tier'); if (kpiTier) kpiTier.textContent = h.tier; const kpiVel = document.getElementById('perf-kpi-velocity'); if (kpiVel) kpiVel.textContent = `${s.say_do_ratio_pct}%`; const kpiPts = document.getElementById('perf-kpi-points'); if (kpiPts) kpiPts.textContent = `${s.total_completed_points} story pts`; const kpiDora = document.getElementById('perf-kpi-dora'); if (kpiDora) kpiDora.textContent = d.overall_tier; const kpiCyc = document.getElementById('perf-kpi-cycle'); if (kpiCyc) kpiCyc.textContent = `${s.avg_pr_cycle_time_hours}h avg cycle`; const kpiSav = document.getElementById('perf-kpi-savings'); if (kpiSav) kpiSav.textContent = `$${Math.round(r.net_dollar_savings).toLocaleString()}`; const kpiSavPct = document.getElementById('perf-kpi-savings-pct'); if (kpiSavPct) kpiSavPct.textContent = `${r.savings_percentage}% vs US loaded`; const kpiRoi = document.getElementById('perf-kpi-roi'); if (kpiRoi) kpiRoi.textContent = `${r.roi_multiple}x`; const kpiCpp = document.getElementById('perf-kpi-cpp'); if (kpiCpp) kpiCpp.textContent = `$${Math.round(r.cost_per_point_latam)}/pt (-${r.cost_per_point_savings_pct}%)`; // DORA Cards Container const doraContainer = document.getElementById('perf-dora-cards-container'); if (doraContainer) { const pillars = d.pillars; const pKeys = ['deployment_frequency', 'lead_time_changes', 'change_failure_rate', 'mean_time_to_recovery']; doraContainer.innerHTML = pKeys.map(k => { const pil = pillars[k]; return `
          ${pil.name} ${pil.badge}
          ${pil.measured_value} ${k === 'deployment_frequency' ? 'deploys/wk' : (k === 'change_failure_rate' ? '%' : 'hrs')}
          ${pil.label}
          `; }).join(''); } // Sprints Table Body const sprintsBody = document.getElementById('perf-sprints-table-body'); if (sprintsBody) { sprintsBody.innerHTML = s.history.map(sp => { const sayDo = Math.round((sp.completed_points / Math.max(sp.planned_points, 1)) * 100); return ` ${sp.sprint_id} ${sp.sprint_name} ${sp.planned_points} ${sp.completed_points} ${sayDo}% ${sp.prs_merged} ${sp.avg_pr_cycle_hours}h ${sp.test_coverage_pct}% `; }).join(''); } // ROI Container const roiCont = document.getElementById('perf-roi-container'); if (roiCont) { roiCont.innerHTML = `
          Quarterly Realized Financials
          Equivalent US Loaded Spend:$${Math.round(r.us_equivalent_spend).toLocaleString()}
          Actual Nearshore Investment:$${Math.round(r.client_actual_spend).toLocaleString()}
          Net Realized Capital Savings:$${Math.round(r.net_dollar_savings).toLocaleString()} (${r.savings_percentage}%)
          Annualized Savings Projection:$${Math.round(r.annual_projected_savings).toLocaleString()}/yr
          Unit Economic Efficiency
          Cost Per Story Point Delivered
          $${r.cost_per_point_latam.toFixed(2)} $${r.cost_per_point_us.toFixed(2)} US
          -${r.cost_per_point_savings_pct}% cheaper per unit of shipped software
          Capital Productivity Multiplier
          ${r.roi_multiple}x ROI
          Every $1 invested yields $${r.roi_multiple} in equivalent US output value.
          `; } // Expansion Container const expCont = document.getElementById('perf-expansion-container'); if (expCont) { const cands = e.matched_candidates || []; const candCards = cands.map(c => `
          ${c.display_name} $${c.client_bill_rate.toFixed(2)}/hr
          ${c.role_title} โ€ข ${c.country} (${c.timezone})

          ${c.key_highlight}

          English: ${c.english_level} ${c.availability}
          `).join(''); expCont.innerHTML = `
          1-Click Expansion Requisition
          Recommended Squad Addition: +1 ${e.recommended_role}
          Velocity Uplift +${e.projected_velocity_uplift_pct}% Output

          ${e.strategic_rationale}

          ${candCards}
          Incremental Investment: $${Math.round(e.monthly_incremental_investment).toLocaleString()} / mo โœ“ 14-Day Zero-Risk Trial Warranty
          `; } // Markdown preview const mdPrev = document.getElementById('perf-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/qbr-report.md?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&seniority=${seniority}&bill_rate=${rate}&pod_size=${podSize}&weeks=${weeks}&quarter=${encodeURIComponent(quarter)}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading markdown QBR report."; } } } catch (err) { console.error("Performance report error:", err); } } function switchPerfTab(tab) { ['dora', 'sprints', 'roi', 'expansion', 'markdown'].forEach(t => { const v = document.getElementById(`perf-view-${t}`); const btn = document.getElementById(`perf-tab-${t}`); if (v) { if (t === tab) v.classList.remove('hidden'); else v.classList.add('hidden'); } if (btn) { if (t === tab) { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-emerald-600 text-slate-950 transition'; } else { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; } } }); } let _auditDebounceTimer = null; let _auditData = null; function debounceRecalcAudit() { if (_auditDebounceTimer) clearTimeout(_auditDebounceTimer); _auditDebounceTimer = setTimeout(calculateAuditLive, 200); } function setAuditPreset(arch, stack) { const archSelect = document.getElementById('audit-input-archetype'); if (archSelect) archSelect.value = arch; const stackInput = document.getElementById('audit-input-stack'); if (stackInput) stackInput.value = stack; debounceRecalcAudit(); } async function calculateAuditLive() { const company = document.getElementById('audit-input-company')?.value.trim() || 'Supabase'; const archetype = document.getElementById('audit-input-archetype')?.value || 'microservices_cloud'; const stack = document.getElementById('audit-input-stack')?.value.trim() || 'Python, Kubernetes'; const repBtn = document.getElementById('download-audit-report-btn'); if (repBtn) repBtn.href = `/b2b/audit-report.md?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&archetype=${encodeURIComponent(archetype)}`; const deckBtn = document.getElementById('view-audit-deck-btn'); if (deckBtn) deckBtn.href = `/b2b/audit-deck.html?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&archetype=${encodeURIComponent(archetype)}`; try { const res = await fetch('/b2b/api/audit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ company: company, stack: stack, archetype: archetype, }) }); const data = await res.json(); if (data.status !== 'success') return; _auditData = data.dossier; const s = _auditData.scoring; const m = _auditData.metrics; const t = s.technical_debt; const p = s.pillars; const sq = t.squad_recommendation; // KPI badges const kpiRqi = document.getElementById('audit-kpi-rqi'); if (kpiRqi) { kpiRqi.textContent = s.rqi; kpiRqi.style.color = s.grade_color; } const kpiGrade = document.getElementById('audit-kpi-grade'); if (kpiGrade) { kpiGrade.textContent = `Grade ${s.grade} (${s.grade_label})`; kpiGrade.style.color = s.grade_color; } const kpiSloc = document.getElementById('audit-kpi-sloc'); if (kpiSloc) kpiSloc.textContent = m.total_sloc.toLocaleString(); const kpiFiles = document.getElementById('audit-kpi-files'); if (kpiFiles) kpiFiles.textContent = `${m.files_count} files`; const kpiTest = document.getElementById('audit-kpi-test'); if (kpiTest) kpiTest.textContent = `${(p.testing.test_to_code_ratio * 100).toFixed(1)}%`; const kpiTestLoc = document.getElementById('audit-kpi-test-loc'); if (kpiTestLoc) kpiTestLoc.textContent = `${m.test_sloc.toLocaleString()} test lines`; const kpiSec = document.getElementById('audit-kpi-sec'); if (kpiSec) kpiSec.textContent = `${m.avg_complexity} McCabes`; const kpiSecFlags = document.getElementById('audit-kpi-sec-flags'); if (kpiSecFlags) kpiSecFlags.textContent = `${m.security_findings.length} security flags`; const kpiSav = document.getElementById('audit-kpi-savings'); if (kpiSav) kpiSav.textContent = `$${Math.round(t.net_arbitrage_savings).toLocaleString()}`; const kpiSavPct = document.getElementById('audit-kpi-savings-pct'); if (kpiSavPct) kpiSavPct.textContent = `${t.savings_percentage}% vs US in-house`; // Tab 1: Pillars View const pilContainer = document.getElementById('audit-view-pillars'); if (pilContainer) { const pilList = [ { name: "1. Architecture & Modularity", score: p.architecture.score, max: p.architecture.max, desc: `${p.architecture.tier} โ€ข Avg Complexity: ${m.avg_complexity}` }, { name: "2. Test Density & Verification", score: p.testing.score, max: p.testing.max, desc: `${p.testing.tier} โ€ข ${(p.testing.test_to_code_ratio * 100).toFixed(1)}% ratio` }, { name: "3. Security & Secret Posture", score: p.security.score, max: p.security.max, desc: `${p.security.tier} โ€ข ${m.security_findings.length} flags` }, { name: "4. Dependency & Licensing", score: p.dependencies.score, max: p.dependencies.max, desc: `${p.dependencies.tier} โ€ข ${m.dependencies_count || 0} packages` }, { name: "5. Maintainability & Docs", score: p.maintainability.score, max: p.maintainability.max, desc: `${p.maintainability.tier} โ€ข ${(p.maintainability.comment_ratio * 100).toFixed(1)}% doc density` }, { name: "6. Git Hygiene & CI/CD", score: p.git_hygiene.score, max: p.git_hygiene.max, desc: `${p.git_hygiene.tier} โ€ข Automated validation active` }, ]; pilContainer.innerHTML = pilList.map(item => `
          ${item.name} ${item.score} / ${item.max} pts

          ${item.desc}

          `).join(''); } // Tab 2: Security View const secContainer = document.getElementById('audit-view-security'); if (secContainer) { if (m.security_findings && m.security_findings.length > 0) { const rows = m.security_findings.map(f => { const sev = (f.severity || 'medium').toLowerCase(); const badgeColor = (sev === 'critical' || sev === 'high') ? 'bg-rose-500/20 text-rose-400 border-rose-500/40' : 'bg-amber-500/20 text-amber-400 border-amber-500/40'; return ` ${sev} ${f.rule_name || f.rule || 'Violation'} ${f.file || ''}:${f.line || 1} ${f.remediation || f.description || 'Remediate in sprint 1'} `; }).join(''); secContainer.innerHTML = ` ${rows}
          SeverityViolationLocationRemediation Action
          `; } else { secContainer.innerHTML = `
          โœ“ No security vulnerabilities or exposed secrets detected across codebase.
          `; } } // Tab 3: Hotspots View const hotContainer = document.getElementById('audit-view-hotspots'); if (hotContainer) { if (m.high_complexity_funcs && m.high_complexity_funcs.length > 0) { const rows = m.high_complexity_funcs.slice(0, 8).map(h => ` ${h.name || 'func'} ${h.file || ''}:${h.line || 1} ${h.complexity || 10} ${h.lines || 0} `).join(''); hotContainer.innerHTML = ` ${rows}
          Function / RoutineLocationComplexityLines
          `; } else { hotContainer.innerHTML = `
          โœ“ All analyzed functions maintain clean cyclomatic flow under 10 McCabes.
          `; } } // Tab 4: Arbitrage View const arbContainer = document.getElementById('audit-view-arbitrage'); if (arbContainer) { arbContainer.innerHTML = `
          US In-House Cost ($165/hr)
          $${Math.round(t.us_remediation_cost).toLocaleString()}

          ${t.estimated_debt_hours} estimated hours

          LATAM Pod Cost ($55/hr)
          $${Math.round(t.latam_remediation_cost).toLocaleString()}

          ${sq.squad_size}x ${sq.role} (${sq.estimated_duration_weeks} wks)

          Net Capital Savings
          $${Math.round(t.net_arbitrage_savings).toLocaleString()}

          ${t.savings_percentage}% direct financial arbitrage

          `; } // Tab 5: Markdown Preview const mdPrev = document.getElementById('audit-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/audit-report.md?company=${encodeURIComponent(company)}&stack=${encodeURIComponent(stack)}&archetype=${encodeURIComponent(archetype)}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading markdown audit report."; } } } catch (err) { console.error("Audit calculation error:", err); } } function switchAuditTab(tab) { ['pillars', 'security', 'hotspots', 'arbitrage', 'markdown'].forEach(t => { const v = document.getElementById(`audit-view-${t}`); const btn = document.getElementById(`audit-tab-${t}`); if (v) { if (t === tab) v.classList.remove('hidden'); else v.classList.add('hidden'); } if (btn) { if (t === tab) { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-cyan-600 text-slate-950 transition'; } else { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; } } }); } let _finopsDebounceTimer = null; let _finopsData = null; function debounceRecalcFinOps() { if (_finopsDebounceTimer) clearTimeout(_finopsDebounceTimer); _finopsDebounceTimer = setTimeout(calculateFinOpsLive, 200); } async function calculateFinOpsLive() { const company = document.getElementById('finops-input-company')?.value.trim() || 'Supabase'; const provider = document.getElementById('finops-input-provider')?.value || 'aws'; const archetype = document.getElementById('finops-input-archetype')?.value || 'kubernetes_microservices'; const spend = parseFloat(document.getElementById('finops-input-spend')?.value || 45000); const squadSize = parseInt(document.getElementById('finops-input-squad')?.value || 1); const repBtn = document.getElementById('download-finops-report-btn'); if (repBtn) repBtn.href = `/b2b/finops-report.md?company=${encodeURIComponent(company)}&spend=${spend}&provider=${encodeURIComponent(provider)}&archetype=${encodeURIComponent(archetype)}&squad_size=${squadSize}`; const deckBtn = document.getElementById('view-finops-deck-btn'); if (deckBtn) deckBtn.href = `/b2b/finops-deck.html?company=${encodeURIComponent(company)}&spend=${spend}&provider=${encodeURIComponent(provider)}&archetype=${encodeURIComponent(archetype)}&squad_size=${squadSize}`; try { const res = await fetch('/b2b/api/finops', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company: company, spend: spend, provider: provider, archetype: archetype, squad_size: squadSize, bill_rate: 55.0 }) }); const data = await res.json(); if (data.status !== 'success' || !data.audit) return; _finopsData = data.audit; const fin = _finopsData.financial_summary; const fmi = _finopsData.maturity_index; const arb = _finopsData.arbitrage; const cats = _finopsData.category_breakdown; // Update Banner const banTitle = document.getElementById('finops-banner-title'); if (banTitle) banTitle.innerHTML = `Eliminate $${fin.identifiable_waste_monthly.toLocaleString()}/mo in Cloud Waste โ†’ Fund Senior DevOps for FREE with +$${arb.net_monthly_client_profit.toLocaleString()}/mo Net Cash Flow`; const banAnnual = document.getElementById('finops-banner-net-annual'); if (banAnnual) banAnnual.textContent = `+$${arb.net_annual_client_profit.toLocaleString()}`; const banRoi = document.getElementById('finops-banner-roi'); if (banRoi) banRoi.textContent = `${arb.roi_multiple}x ROI multiple`; // Update KPIs const kpiSpend = document.getElementById('finops-kpi-spend'); if (kpiSpend) kpiSpend.textContent = `$${fin.current_monthly_spend.toLocaleString()}`; const kpiRunrate = document.getElementById('finops-kpi-runrate'); if (kpiRunrate) kpiRunrate.textContent = `$${Math.round(fin.current_annual_spend/1000)}k/yr`; const kpiWaste = document.getElementById('finops-kpi-waste'); if (kpiWaste) kpiWaste.textContent = `-$${fin.identifiable_waste_monthly.toLocaleString()}`; const kpiWastePct = document.getElementById('finops-kpi-waste-pct'); if (kpiWastePct) kpiWastePct.textContent = `${fin.waste_percentage}% of bill`; const kpiFmi = document.getElementById('finops-kpi-fmi'); if (kpiFmi) kpiFmi.textContent = fmi.score; const kpiGrade = document.getElementById('finops-kpi-grade'); if (kpiGrade) kpiGrade.textContent = `Grade ${fmi.grade} (${fmi.status.split(' ')[0]})`; const kpiSquad = document.getElementById('finops-kpi-squad'); if (kpiSquad) kpiSquad.textContent = `$${arb.latam_monthly_cost.toLocaleString()}`; const kpiProfit = document.getElementById('finops-kpi-profit'); if (kpiProfit) kpiProfit.textContent = `+$${arb.net_monthly_client_profit.toLocaleString()}`; // Render Tab 1: Cloud Pillars const pilContainer = document.getElementById('finops-view-pillars'); if (pilContainer) { let html = ''; for (const [catName, cat] of Object.entries(cats)) { html += `
          ${catName} -${cat.potential_saving_pct}% waste
          $${cat.current_monthly_spend.toLocaleString()}/mo
          Identifiable Waste: -$${cat.identifiable_waste_monthly.toLocaleString()}/mo
          `; } pilContainer.innerHTML = html; } // Render Tab 2: Findings const findContainer = document.getElementById('finops-view-findings'); if (findContainer) { let html = ''; _finopsData.findings.forEach((f, idx) => { const sevColor = f.severity === 'high' ? 'rose' : (f.severity === 'medium' ? 'amber' : 'emerald'); html += `
          ${f.severity} โ€ข ${f.category} ~${f.potential_saving_pct}% waste target
          ${idx + 1}. ${f.title}
          ${f.impact}
          Remediation: ${f.remediation}
          `; }); findContainer.innerHTML = html; } // Render Tab 3: Roadmap const roadContainer = document.getElementById('finops-view-roadmap'); if (roadContainer) { let html = ''; _finopsData.remediation_roadmap.forEach(r => { const actionsHtml = r.actions.map(act => `
        • ${act}
        • `).join(''); html += `
          ${r.phase} +${r.monthly_savings_unlocked.toLocaleString()}/mo unlocked
          ${r.timeline} โ€” ${r.focus}
          `; }); roadContainer.innerHTML = html; } // Render Tab 4: Arbitrage const arbContainer = document.getElementById('finops-view-arbitrage'); if (arbContainer) { arbContainer.innerHTML = `
          US In-House DevOps Benchmark
          $${arb.us_monthly_cost.toLocaleString()}/mo
          1x Senior Cloud/DevOps Engineer at $165/hr loaded US cost ($27,720/mo). Even after recapturing cloud waste, net monthly cashflow is -$${Math.abs(arb.us_net_monthly_cashflow).toLocaleString()}/mo.
          LATAM Nearshore DevOps Squad
          +$${arb.net_monthly_client_profit.toLocaleString()}/mo NET PROFIT
          Dedicated LATAM Senior Cloud/DevOps lead ($55/hr = $9,240/mo) is 100% self-funded by recovered AWS/GCP waste, generating +$${arb.net_annual_client_profit.toLocaleString()}/year in pure financial upside.
          `; } // Render Tab 5: Markdown Preview const mdPrev = document.getElementById('finops-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/finops-report.md?company=${encodeURIComponent(company)}&spend=${spend}&provider=${encodeURIComponent(provider)}&archetype=${encodeURIComponent(archetype)}&squad_size=${squadSize}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading markdown FinOps report."; } } } catch (err) { console.error("FinOps calculation error:", err); } } function switchFinOpsTab(tab) { ['pillars', 'findings', 'roadmap', 'arbitrage', 'markdown'].forEach(t => { const v = document.getElementById(`finops-view-${t}`); const btn = document.getElementById(`finops-tab-${t}`); if (v) { if (t === tab) v.classList.remove('hidden'); else v.classList.add('hidden'); } if (btn) { if (t === tab) { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-sky-600 text-slate-950 transition'; } else { btn.className = 'px-4 py-2 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; } } }); } let _activeResearchQuery = "Supabase"; let _activeResearchArchetype = "supabase"; let _researchData = null; function selectResearchPreset(query, archetype) { _activeResearchQuery = query; _activeResearchArchetype = archetype; const input = document.getElementById('research-custom-input'); if (input) input.value = query; document.querySelectorAll('.research-pill-btn').forEach(btn => { if (btn.textContent.trim().toLowerCase() === query.toLowerCase()) { btn.className = 'research-pill-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-teal-600 text-slate-950 transition'; } else { btn.className = 'research-pill-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; } }); calculateResearchLive(); } function triggerCustomResearch() { const input = document.getElementById('research-custom-input'); const val = input ? input.value.trim() : ""; if (!val) return; _activeResearchQuery = val; _activeResearchArchetype = null; document.querySelectorAll('.research-pill-btn').forEach(btn => { btn.className = 'research-pill-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; }); calculateResearchLive(); } async function calculateResearchLive() { try { const query = _activeResearchQuery || "Supabase"; const archetype = _activeResearchArchetype; const repBtn = document.getElementById('download-research-report-btn'); if (repBtn) repBtn.href = `/b2b/research-report.md?query=${encodeURIComponent(query)}&depth=deep${archetype ? '&archetype=' + encodeURIComponent(archetype) : ''}`; const deckBtn = document.getElementById('view-research-deck-btn'); if (deckBtn) deckBtn.href = `/b2b/research-deck.html?query=${encodeURIComponent(query)}&depth=deep${archetype ? '&archetype=' + encodeURIComponent(archetype) : ''}`; const res = await fetch('/b2b/api/research', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: query, depth: 'deep', archetype: archetype, timeout: 6.0 }) }); const data = await res.json(); if (data.status !== 'success' || !data.dossier) return; _researchData = data.dossier; // Update KPIs const kpiConf = document.getElementById('research-kpi-confidence'); if (kpiConf) kpiConf.textContent = `${_researchData.confidence_score}%`; const kpiCat = document.getElementById('research-kpi-category'); if (kpiCat) kpiCat.textContent = _researchData.category; const kpiDom = document.getElementById('research-kpi-domain'); if (kpiDom) kpiDom.textContent = _researchData.official_domain; const kpiStage = document.getElementById('research-kpi-stage'); if (kpiStage) kpiStage.textContent = _researchData.funding_stage; const kpiHq = document.getElementById('research-kpi-hq'); if (kpiHq) kpiHq.textContent = _researchData.headquarters; const summaryText = document.getElementById('research-summary-text'); if (summaryText) summaryText.textContent = _researchData.summary; // Render Tab 1: Tech Stack const techContainer = document.getElementById('research-view-tech'); if (techContainer) { const cats = [ { key: 'languages', title: 'Languages', color: 'border-sky-400 text-sky-300' }, { key: 'frameworks', title: 'Frameworks', color: 'border-purple-400 text-purple-300' }, { key: 'cloud_devops', title: 'Cloud & DevOps', color: 'border-emerald-400 text-emerald-300' }, { key: 'databases_ai', title: 'Data & AI', color: 'border-amber-400 text-amber-300' } ]; let html = ''; cats.forEach(c => { const items = (_researchData.technographics && _researchData.technographics[c.key]) || []; const badges = items.map(it => `${it}`).join(' ') || 'None detected'; html += `
          ${c.title}
          ${badges}
          `; }); techContainer.innerHTML = html; } // Render Tab 2: Leadership const leaderContainer = document.getElementById('research-view-leaders'); if (leaderContainer) { let html = ''; (_researchData.leadership || []).forEach(l => { html += `
          ${l.name}
          ${l.role}
          Profile โ†—
          `; }); leaderContainer.innerHTML = html; } // Render Tab 3: Competitors const compContainer = document.getElementById('research-view-competitors'); if (compContainer) { let rows = ''; (_researchData.competitors || []).forEach(c => { rows += ` ${c.name} ${c.type || 'Peer'} ${c.differentiator || ''} `; }); compContainer.innerHTML = ` ${rows}
          Competitor / Peer Classification Key Differentiator
          `; } // Render Tab 4: Citations const citContainer = document.getElementById('research-view-citations'); if (citContainer) { let html = ''; (_researchData.citations || []).forEach((cit, idx) => { html += `
          #${idx + 1} โ€ข ${cit.domain} Open Link โ†—
          ${cit.title}
          "${cit.snippet}"
          `; }); citContainer.innerHTML = html; } // Render Tab 5: Markdown const mdPrev = document.getElementById('research-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/research-report.md?query=${encodeURIComponent(query)}&depth=deep${archetype ? '&archetype=' + encodeURIComponent(archetype) : ''}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading markdown research dossier."; } } } catch (err) { console.error("Research calculation error:", err); } } function switchResearchTab(tab) { ['tech', 'leaders', 'competitors', 'citations', 'markdown'].forEach(t => { const v = document.getElementById(`research-view-${t}`); const btn = document.getElementById(`research-tab-${t}`); if (v) { if (t === tab) v.classList.remove('hidden'); else v.classList.add('hidden'); } if (btn) { if (t === tab) { btn.className = 'px-3.5 py-1.5 rounded-lg text-xs font-bold bg-teal-600 text-slate-950 transition'; } else { btn.className = 'px-3.5 py-1.5 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; } } }); } // ------------------------------------------------------------- // Enterprise Vendor Security & Compliance Auditor Engine // ------------------------------------------------------------- let _activeComplianceCompany = "Supabase"; let _activeComplianceArchetype = "nearshore_engineering_partner"; let _complianceData = null; function selectComplianceArchetype(archetype, btn) { _activeComplianceArchetype = archetype; document.querySelectorAll('.compliance-pill-btn').forEach(b => { b.className = 'compliance-pill-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; }); if (btn) { btn.className = 'compliance-pill-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-600 text-slate-950 transition'; } calculateComplianceLive(); } function triggerCustomComplianceAudit() { const input = document.getElementById('compliance-company-input'); const val = input ? input.value.trim() : ""; if (!val) return; _activeComplianceCompany = val; calculateComplianceLive(); } function switchComplianceTab(tab, btn) { ['pillars', 'sig-lite', 'dpa', 'markdown'].forEach(t => { const el = document.getElementById(`compliance-view-${t}`); if (el) { if (t === tab) el.classList.remove('hidden'); else el.classList.add('hidden'); } }); document.querySelectorAll('.compliance-tab-btn').forEach(b => { b.className = 'compliance-tab-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; }); if (btn) { btn.className = 'compliance-tab-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-600 text-slate-950 transition'; } } async function calculateComplianceLive() { try { const company = _activeComplianceCompany || "Supabase"; const archetype = _activeComplianceArchetype || "nearshore_engineering_partner"; const dosBtn = document.getElementById('download-compliance-dossier-btn'); if (dosBtn) dosBtn.href = `/b2b/compliance-dossier.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`; const deckBtn = document.getElementById('view-compliance-deck-btn'); if (deckBtn) deckBtn.href = `/b2b/compliance-deck.html?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`; const res = await fetch('/b2b/api/compliance', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company: company, archetype: archetype }) }); const data = await res.json(); if (data.status !== 'success' || !data.audit) return; _complianceData = data.audit; // Update KPIs const vsi = _complianceData.vendor_security_index; const verdict = _complianceData.procurement_verdict; const kpiVsi = document.getElementById('compliance-kpi-vsi'); if (kpiVsi) kpiVsi.textContent = `${vsi.score} / 100`; const kpiGrade = document.getElementById('compliance-kpi-grade'); if (kpiGrade) kpiGrade.textContent = `Grade ${vsi.grade} (${vsi.status.split('(')[0].trim()})`; const kpiVerd = document.getElementById('compliance-kpi-verdict'); if (kpiVerd) kpiVerd.textContent = verdict.approved_for_enterprise ? 'Approved โœ“' : 'Conditional โš ๏ธ'; const kpiClear = document.getElementById('compliance-kpi-clearance'); if (kpiClear) kpiClear.textContent = verdict.security_clearance; // Render Tab 1: 6-Pillar Framework const pillarsContainer = document.getElementById('compliance-view-pillars'); if (pillarsContainer && _complianceData.pillars) { let html = ''; for (const [pKey, p] of Object.entries(_complianceData.pillars)) { const scoreColor = p.score >= 95 ? '#10b981' : (p.score >= 88 ? '#38bdf8' : '#f59e0b'); html += `
          ${p.name} ${p.score}%

          ${p.description}

          `; } pillarsContainer.innerHTML = html; } // Render Tab 2: SIG Lite Matrix const sigContainer = document.getElementById('compliance-view-sig-lite'); if (sigContainer && _complianceData.sig_lite) { let rows = ''; _complianceData.sig_lite.forEach(q => { rows += ` ${q.id}
          ${q.question}
          ${q.response}
          Evidence: ${q.evidence}
          ${q.status} `; }); sigContainer.innerHTML = ` ${rows}
          Control ID Question & Verified Covenants Status
          `; } // Render Tab 3: DPA Covenants const dpaContainer = document.getElementById('compliance-view-dpa'); if (dpaContainer && _complianceData.dpa_summary) { const dpa = _complianceData.dpa_summary; dpaContainer.innerHTML = `
          Governing Legal Framework
          ${dpa.governing_framework}

          ${dpa.standard_contractual_clauses}

          AI Model IP Covenant
          Zero Customer IP Training

          ${dpa.zero_ai_training_guarantee}

          Breach Escalation SLA
          Under ${dpa.breach_notification_sla_hours} Hours

          Mandatory forensic incident notification sent to customer security team.

          Liability & Audit Rights
          ${dpa.liability_cap}

          ${dpa.audit_rights}

          `; } // Render Tab 4: Markdown const mdPrev = document.getElementById('compliance-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/compliance-dossier.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading markdown compliance dossier."; } } } catch (err) { console.error("Compliance calculation error:", err); } } let _activeModernizeArchetype = 'django_to_fastapi_nextjs'; let _activeModernizeCompany = 'Scale AI'; let _modernizeData = null; function selectModernizeArchetype(arch, btn) { _activeModernizeArchetype = arch; document.querySelectorAll('.modernize-archetype-btn').forEach(b => { b.className = 'modernize-archetype-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-950 text-slate-400 border border-slate-800 hover:border-slate-700 transition'; }); if (btn) { btn.className = 'modernize-archetype-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-violet-600 text-white border border-violet-500 transition'; } calculateModernizationLive(); } function switchModernizeTab(tabName, btn) { ['pillars', 'strangler', 'roadmap', 'arbitrage', 'markdown'].forEach(t => { const el = document.getElementById(`modernize-view-${t}`); if (el) { if (t === tabName) el.classList.remove('hidden'); else el.classList.add('hidden'); } }); document.querySelectorAll('.modernize-tab-btn').forEach(b => { b.className = 'modernize-tab-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; }); if (btn) { btn.className = 'modernize-tab-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-violet-600 text-white transition'; } } async function calculateModernizationLive() { try { const compInput = document.getElementById('modernize-company-input'); const company = compInput ? (compInput.value.trim() || 'Scale AI') : 'Scale AI'; const archetype = _activeModernizeArchetype || 'django_to_fastapi_nextjs'; const bpBtn = document.getElementById('download-modernize-blueprint-btn'); if (bpBtn) bpBtn.href = `/b2b/modernization-blueprint.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`; const dkBtn = document.getElementById('view-modernize-deck-btn'); if (dkBtn) dkBtn.href = `/b2b/modernization-deck.html?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`; const res = await fetch('/b2b/api/modernize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company: company, archetype: archetype }) }); const data = await res.json(); if (data.status !== 'success' || !data.forecast) return; _modernizeData = data.forecast; // Update KPIs const tds = _modernizeData.technical_debt_score; const mvi = _modernizeData.modernization_velocity_index; const grade = _modernizeData.feasibility_grade; const risk = _modernizeData.feasibility_risk; const arb = _modernizeData.financial_arbitrage || {}; const elTds = document.getElementById('modernize-kpi-tds'); if (elTds) elTds.textContent = `${tds} / 100`; const elMvi = document.getElementById('modernize-kpi-mvi'); if (elMvi) elMvi.textContent = `${mvi}`; const elGrade = document.getElementById('modernize-kpi-grade'); if (elGrade) elGrade.textContent = grade; const elRisk = document.getElementById('modernize-kpi-risk'); if (elRisk) elRisk.textContent = `Risk Profile: ${risk}`; const elSav = document.getElementById('modernize-kpi-savings'); if (elSav) elSav.textContent = `$${(arb.net_arbitrage_savings_usd || 0).toLocaleString()}`; const elMult = document.getElementById('modernize-kpi-multiplier'); if (elMult) elMult.textContent = `${arb.capital_efficiency_multiplier || '3.0x'} Capital Multiplier (${arb.payback_period_months || 1.5}mo Payback)`; // Tab 1: 5-Pillar Complexity Breakdown const pillarsEl = document.getElementById('modernize-view-pillars'); if (pillarsEl && _modernizeData.pillar_breakdown) { let html = ''; for (const [pKey, p] of Object.entries(_modernizeData.pillar_breakdown)) { const scoreColor = p.score < 55 ? '#10b981' : (p.score < 75 ? '#f59e0b' : '#f43f5e'); html += `
          ${p.name} ${p.score}% [${p.status}]

          ${p.description}

          `; } pillarsEl.innerHTML = html; } // Tab 2: Strangler Pattern & Pitfalls const strDesc = document.getElementById('modernize-strangler-description'); if (strDesc) strDesc.textContent = _modernizeData.strangler_pattern; const pitList = document.getElementById('modernize-pitfalls-list'); if (pitList && _modernizeData.key_pitfalls) { pitList.innerHTML = _modernizeData.key_pitfalls.map(p => `
        • ${p}
        • `).join(''); } const mitList = document.getElementById('modernize-mitigations-list'); if (mitList && _modernizeData.mitigations) { mitList.innerHTML = _modernizeData.mitigations.map(m => `
        • ${m}
        • `).join(''); } // Tab 3: 4-Phase Roadmap const rdEl = document.getElementById('modernize-view-roadmap'); if (rdEl && _modernizeData.roadmap_phases) { let html = ''; _modernizeData.roadmap_phases.forEach(ph => { const delivs = (ph.deliverables || []).map(d => `
        • ${d}
        • `).join(''); html += `
          ${ph.title} ${ph.week_span} (${ph.duration_weeks} wks)

          Objective: ${ph.objective}

          Risk Mitigation: ${ph.risk_mitigation}

          `; }); rdEl.innerHTML = html; } // Tab 4: Arbitrage const usTot = document.getElementById('modernize-arb-us-total'); if (usTot) usTot.textContent = `$${(arb.us_onshore?.total_project_cost || 0).toLocaleString()}`; const usRate = document.getElementById('modernize-arb-us-rate'); if (usRate) usRate.textContent = `$${arb.us_onshore?.blended_hourly_rate || 125}/hr ($${(arb.us_onshore?.weekly_squad_cost || 0).toLocaleString()}/wk)`; const latTot = document.getElementById('modernize-arb-latam-total'); if (latTot) latTot.textContent = `$${(arb.latam_nearshore?.total_project_cost || 0).toLocaleString()}`; const latRate = document.getElementById('modernize-arb-latam-rate'); if (latRate) latRate.textContent = `$${arb.latam_nearshore?.blended_hourly_rate || 45}/hr ($${(arb.latam_nearshore?.weekly_squad_cost || 0).toLocaleString()}/wk)`; const savEl = document.getElementById('modernize-arb-savings'); if (savEl) savEl.textContent = `$${(arb.net_arbitrage_savings_usd || 0).toLocaleString()} (${arb.savings_percentage || 0}%)`; const payEl = document.getElementById('modernize-arb-payback'); if (payEl) payEl.textContent = `${arb.payback_period_months || 1.5} Months`; const effEl = document.getElementById('modernize-arb-efficiency'); if (effEl) effEl.textContent = `${arb.capital_efficiency_multiplier || '3.19x'} Capital Multiplier`; // Tab 5: Markdown Preview const mdPrev = document.getElementById('modernize-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/modernization-blueprint.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading markdown blueprint."; } } } catch (err) { console.error("Modernization calculation error:", err); } } let _activeAIWorkforceArchetype = 'qa_automation'; let _aiWorkforceData = null; function selectAIWorkforceArchetype(arch, btn) { _activeAIWorkforceArchetype = arch; document.querySelectorAll('.aiworkforce-archetype-btn').forEach(b => { b.className = 'aiworkforce-archetype-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-950 text-slate-400 border border-slate-800 hover:border-slate-700 transition'; }); if (btn) { btn.className = 'aiworkforce-archetype-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-indigo-600 text-white border border-indigo-500 transition'; } calculateAIWorkforceLive(); } function switchAIWorkforceTab(tabName, btn) { ['arbitrage', 'pillars', 'tokens', 'governance', 'markdown'].forEach(t => { const el = document.getElementById(`aiworkforce-view-${t}`); if (el) { if (t === tabName) el.classList.remove('hidden'); else el.classList.add('hidden'); } }); document.querySelectorAll('.aiworkforce-tab-btn').forEach(b => { b.className = 'aiworkforce-tab-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-slate-800 text-slate-300 hover:text-white transition'; }); if (btn) { btn.className = 'aiworkforce-tab-btn px-3 py-1.5 rounded-lg text-xs font-bold bg-indigo-600 text-white transition'; } } async function calculateAIWorkforceLive() { try { const compInput = document.getElementById('aiworkforce-company-input'); const company = compInput ? (compInput.value.trim() || 'Client Enterprise') : 'Client Enterprise'; const archetype = _activeAIWorkforceArchetype || 'qa_automation'; const slider = document.getElementById('aiworkforce-team-size-slider'); const teamSize = slider ? parseInt(slider.value, 10) : 4; const sizeVal = document.getElementById('aiworkforce-team-size-val'); if (sizeVal) sizeVal.textContent = `${teamSize} US FTEs`; const repBtn = document.getElementById('download-aiworkforce-report-btn'); if (repBtn) repBtn.href = `/b2b/ai-workforce-report.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}&team_size=${teamSize}`; const dkBtn = document.getElementById('view-aiworkforce-deck-btn'); if (dkBtn) dkBtn.href = `/b2b/ai-workforce-deck.html?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}&team_size=${teamSize}`; const res = await fetch('/b2b/api/ai-workforce', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company: company, archetype: archetype, team_size: teamSize }) }); const data = await res.json(); if (data.status !== 'success' || !data.model) return; _aiWorkforceData = data.model; const aut = _aiWorkforceData.automability || {}; const fc = _aiWorkforceData.financial_comparison || {}; const cyb = fc.cybernetic_hybrid || {}; const us = fc.us_onshore || {}; const latam = fc.latam_nearshore || {}; const pure = fc.pure_ai_fleet || {}; const eco = _aiWorkforceData.agent_economics || {}; // KPIs const tasEl = document.getElementById('aiworkforce-kpi-tas'); if (tasEl) tasEl.textContent = `${aut.task_automability_score || 90.0} / 100`; const tierEl = document.getElementById('aiworkforce-kpi-tier'); if (tierEl) tierEl.textContent = aut.overall_tier || 'Tier A: Highly Automatable'; const savEl = document.getElementById('aiworkforce-kpi-savings'); if (savEl) savEl.textContent = `+$${Math.round(cyb.savings_vs_us || 0).toLocaleString()}`; const pctEl = document.getElementById('aiworkforce-kpi-pct'); if (pctEl) pctEl.textContent = `${cyb.savings_pct || 0}% Net Cost Reduction`; const monEl = document.getElementById('aiworkforce-kpi-monthly'); if (monEl) monEl.textContent = `+$${Math.round(cyb.monthly_savings || 0).toLocaleString()} / mo`; const roiEl = document.getElementById('aiworkforce-kpi-roi'); if (roiEl) roiEl.textContent = `Capital ROI: ${cyb.roi_multiple || '7.54'}x`; const velEl = document.getElementById('aiworkforce-kpi-velocity'); if (velEl) velEl.textContent = `${cyb.velocity_multiplier || '3.2'}x`; const pbEl = document.getElementById('aiworkforce-kpi-payback'); if (pbEl) pbEl.textContent = `Payback Period: ${cyb.payback_days || 14} Days`; // Tab 1: 4-Tier Financial Table const tbody = document.getElementById('aiworkforce-arbitrage-table-body'); if (tbody) { tbody.innerHTML = ` 1. US Onshore (Status Quo) ${us.team_size || 4} US FTEs $${Math.round(us.monthly_cost || 0).toLocaleString()} $${Math.round(us.annual_cost || 0).toLocaleString()} $0.00 0.0% 2. Dedicated LATAM Nearshore ${latam.team_size || 4} LATAM FTEs $${Math.round(latam.monthly_cost || 0).toLocaleString()} $${Math.round(latam.annual_cost || 0).toLocaleString()} +$${Math.round(latam.savings_vs_us || 0).toLocaleString()} ${latam.savings_pct || 0}% 3. Pure Autonomous AI Fleet Agents + Hourly QA $${Math.round(pure.monthly_cost || 0).toLocaleString()} $${Math.round(pure.annual_cost || 0).toLocaleString()} +$${Math.round(pure.savings_vs_us || 0).toLocaleString()} ${pure.savings_pct || 0}% โ˜… 4. Cybernetic Squad (RECOMMENDED) 1 Tech Lead + Agents $${Math.round(cyb.monthly_cost || 0).toLocaleString()} $${Math.round(cyb.annual_cost || 0).toLocaleString()} +$${Math.round(cyb.savings_vs_us || 0).toLocaleString()} ${cyb.savings_pct || 0}% `; } // Tab 2: Cognitive Pillars Grid const pilGrid = document.getElementById('aiworkforce-pillars-grid'); if (pilGrid && aut.pillars) { pilGrid.innerHTML = Object.values(aut.pillars).map(p => `
          ${p.name} ${p.score} / ${p.max} (${p.percentage}%)

          ${p.description}

          `).join(''); } // Tab 3: Token & Infra const modName = document.getElementById('aiworkforce-model-name'); if (modName) modName.textContent = eco.model_used || 'Claude 3.5 Sonnet'; const modTier = document.getElementById('aiworkforce-model-tier'); if (modTier) modTier.textContent = eco.model_tier || 'Frontier Reasoning'; const tokCost = document.getElementById('aiworkforce-token-cost'); if (tokCost) tokCost.textContent = `$${(eco.monthly_token_cost || 0).toLocaleString()} / mo`; const tokTasks = document.getElementById('aiworkforce-token-tasks'); if (tokTasks) tokTasks.textContent = `${eco.daily_tasks || 120} tasks/day (${((eco.daily_total_tokens || 0)/1000000).toFixed(1)}M tokens/day)`; const infCost = document.getElementById('aiworkforce-infra-cost'); if (infCost) infCost.textContent = `$${(eco.monthly_infra_total || 300).toLocaleString()} / mo`; // Tab 4: Governance & Risk const rk = _aiWorkforceData.risk_and_mitigation || {}; const rkText = document.getElementById('aiworkforce-risk-text'); if (rkText) rkText.textContent = rk.key_risk || 'Non-deterministic outputs.'; const mitText = document.getElementById('aiworkforce-mitigation-text'); if (mitText) mitText.textContent = rk.mitigation_protocol || 'Lead review.'; const slaText = document.getElementById('aiworkforce-sla-text'); if (slaText) slaText.textContent = rk.sla_guarantee || '99.8% precision.'; // Tab 5: Markdown Preview const mdPrev = document.getElementById('aiworkforce-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/ai-workforce-report.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}&team_size=${teamSize}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading markdown AI workforce briefing."; } } } catch (err) { console.error("AI Workforce calculation error:", err); } } let _activeProposalArchetype = 'cybernetic_ai_pod'; let _proposalData = null; function selectProposalArchetype(arch, btn) { _activeProposalArchetype = arch; document.querySelectorAll('.proposal-archetype-btn').forEach(b => { b.className = 'proposal-archetype-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-950 text-slate-400 border border-slate-800 hover:border-slate-700 transition'; }); if (btn) { btn.className = 'proposal-archetype-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-emerald-600 text-white border border-emerald-500 transition'; } calculateProposalLive(); } function switchProposalTab(tabName, btn) { ['tco', 'squad', 'roadmap', 'guarantees', 'markdown'].forEach(t => { const el = document.getElementById(`proposal-view-${t}`); if (el) { if (t === tabName) el.classList.remove('hidden'); else el.classList.add('hidden'); } }); document.querySelectorAll('.proposal-tab-btn').forEach(b => { b.className = 'proposal-tab-btn px-3 py-1.5 rounded-lg font-semibold text-slate-400 hover:text-slate-200 transition'; }); if (btn) { btn.className = 'proposal-tab-btn px-3 py-1.5 rounded-lg font-bold bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition'; } } async function calculateProposalLive() { try { const compInput = document.getElementById('proposal-company-input'); const company = compInput ? (compInput.value.trim() || 'Scale AI') : 'Scale AI'; const archetype = _activeProposalArchetype || 'cybernetic_ai_pod'; const repBtn = document.getElementById('download-proposal-dossier-btn'); if (repBtn) repBtn.href = `/b2b/proposal-dossier.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`; const dkBtn = document.getElementById('view-proposal-deck-btn'); if (dkBtn) dkBtn.href = `/b2b/proposal-deck.html?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`; const res = await fetch('/b2b/api/proposal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company: company, archetype: archetype }) }); const data = await res.json(); if (data.status !== 'success' || !data.proposal) return; _proposalData = data.proposal; const p = _proposalData.pricing || {}; const s = _proposalData.savings || {}; const im = _proposalData.investment_metrics || {}; const proj = im.projections || {}; // KPIs const savEl = document.getElementById('proposal-kpi-savings'); if (savEl) savEl.textContent = `+$${Math.round(s.annual_net_savings || 0).toLocaleString()}`; const pctEl = document.getElementById('proposal-kpi-pct'); if (pctEl) pctEl.textContent = `${s.savings_percentage || 0}% vs US Onsite`; const velEl = document.getElementById('proposal-kpi-velocity'); if (velEl) velEl.textContent = `${_proposalData.velocity_multiplier || 2.8}x`; const pbEl = document.getElementById('proposal-kpi-payback'); if (pbEl) pbEl.textContent = `${im.payback_period_months || 0.5} mo`; const npvEl = document.getElementById('proposal-kpi-npv'); if (npvEl) npvEl.textContent = `+$${Math.round(im.npv_36_months || 0).toLocaleString()}`; // Tab 1: TCO Table const tbody = document.getElementById('proposal-tco-table-body'); if (tbody && proj.year_1 && proj.year_2 && proj.year_3) { tbody.innerHTML = ` Year 1 (12 Months) $${Math.round(proj.year_1.us_cumulative_cost).toLocaleString()} $${Math.round(proj.year_1.proposed_cumulative_cost).toLocaleString()} +$${Math.round(proj.year_1.net_cumulative_savings).toLocaleString()} ${proj.year_1.roi_multiple}x (${proj.year_1.roi_percentage}%) Year 2 (24 Months) $${Math.round(proj.year_2.us_cumulative_cost).toLocaleString()} $${Math.round(proj.year_2.proposed_cumulative_cost).toLocaleString()} +$${Math.round(proj.year_2.net_cumulative_savings).toLocaleString()} ${proj.year_2.roi_multiple}x (${proj.year_2.roi_percentage}%) โ˜… Year 3 (36 Months) $${Math.round(proj.year_3.us_cumulative_cost).toLocaleString()} $${Math.round(proj.year_3.proposed_cumulative_cost).toLocaleString()} +$${Math.round(proj.year_3.net_cumulative_savings).toLocaleString()} ${proj.year_3.roi_multiple}x (${proj.year_3.roi_percentage}%) `; } // Tab 2: Squad Roles const rolesGrid = document.getElementById('proposal-roles-grid'); if (rolesGrid && _proposalData.team_composition) { rolesGrid.innerHTML = _proposalData.team_composition.map(r => `
          ${r.title} ${r.seniority}
          $${r.hourly_rate}/hr
          ${r.count} Dedicated (${r.hours_per_month}h/mo) $${(r.hourly_rate * r.hours_per_month * r.count).toLocaleString()}/mo
          `).join(''); } // Tab 3: Milestones const msGrid = document.getElementById('proposal-milestones-grid'); if (msGrid) { const milestones = [ { step: 'Phase 0', duration: 'Weeks 1-2', title: 'Architecture Alignment', desc: 'ADR sign-off, repo audit, environment provisioning & baseline verification.' }, { step: 'Phase 1', duration: 'Weeks 3-6', title: 'Foundation & Alpha', desc: 'Deploy first vertical feature, verify automated sentinels, 14-day trial review.' }, { step: 'Phase 2', duration: 'Weeks 7-18', title: 'Velocity Scaling', desc: 'Full sprint velocity, 2.8x throughput, bi-weekly DORA reports & zero Sev-1 issues.' }, { step: 'Phase 3', duration: 'Weeks 19-24', title: 'Cutover & Retainer', desc: 'Zero-downtime cutover, knowledge transfer, SLA lock-in & long-term maintenance.' }, ]; msGrid.innerHTML = milestones.map(m => `
          ${m.step} ${m.duration}
          ${m.title}

          ${m.desc}

          `).join(''); } // Tab 5: Markdown Dossier const mdPrev = document.getElementById('proposal-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/proposal-dossier.md?company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading proposal dossier markdown."; } } } catch (err) { console.error("Proposal calculation error:", err); } } let _activeBattlecardCompany = 'Supabase'; let _battlecardData = null; function selectBattlecardAccount(company, btn) { _activeBattlecardCompany = company; const compInput = document.getElementById('battlecard-company-input'); if (compInput) compInput.value = company; document.querySelectorAll('.battlecard-account-btn').forEach(b => { b.className = 'battlecard-account-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-950 text-slate-400 border border-slate-800 hover:border-slate-700 transition'; }); if (btn) { btn.className = 'battlecard-account-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white border border-cyan-500 transition'; } calculateBattlecardLive(); } function switchBattlecardTab(tabName, btn) { ['swot', 'competitors', 'discovery', 'objections', 'markdown'].forEach(t => { const el = document.getElementById(`battlecard-view-${t}`); if (el) { if (t === tabName) el.classList.remove('hidden'); else el.classList.add('hidden'); } }); document.querySelectorAll('.battlecard-tab-btn').forEach(b => { b.className = 'battlecard-tab-btn px-3 py-1.5 rounded-lg font-semibold text-slate-400 hover:text-slate-200 transition'; }); if (btn) { btn.className = 'battlecard-tab-btn px-3 py-1.5 rounded-lg font-bold bg-cyan-600/20 text-cyan-300 border border-cyan-500/30 transition'; } } async function calculateBattlecardLive() { try { const compInput = document.getElementById('battlecard-company-input'); const company = compInput ? (compInput.value.trim() || 'Supabase') : 'Supabase'; const repBtn = document.getElementById('download-battlecard-dossier-btn'); if (repBtn) repBtn.href = `/b2b/battlecard-report.md?company=${encodeURIComponent(company)}`; const dkBtn = document.getElementById('view-battlecard-deck-btn'); if (dkBtn) dkBtn.href = `/b2b/battlecard-deck.html?company=${encodeURIComponent(company)}`; const res = await fetch('/b2b/api/battlecard', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company: company }) }); const data = await res.json(); if (data.status !== 'success' || !data.battlecard) return; _battlecardData = data.battlecard; const sig = _battlecardData.hiring_signals || {}; const swot = _battlecardData.swot || {}; // Update KPI badges const openEl = document.getElementById('battlecard-kpi-openings'); if (openEl) openEl.textContent = `${sig.active_openings || 0} Roles`; const velEl = document.getElementById('battlecard-kpi-velocity'); if (velEl) velEl.textContent = `${sig.hiring_velocity || 'Active'} velocity`; const usEl = document.getElementById('battlecard-kpi-us-base'); if (usEl) usEl.textContent = `$${(sig.avg_us_salary || 0).toLocaleString()}`; const latamEl = document.getElementById('battlecard-kpi-latam-cost'); if (latamEl) latamEl.textContent = `$${(sig.estimated_latam_cost || 0).toLocaleString()}`; const arbEl = document.getElementById('battlecard-kpi-arbitrage'); if (arbEl) arbEl.textContent = `+$${(sig.annual_arbitrage_per_dev || 0).toLocaleString()}`; const pctEl = document.getElementById('battlecard-kpi-savings-pct'); if (pctEl && sig.avg_us_salary) { const pct = Math.round((sig.annual_arbitrage_per_dev / sig.avg_us_salary) * 100); pctEl.textContent = `${pct}% net reduction`; } // Tab 1: SWOT const strEl = document.getElementById('battlecard-swot-strengths'); if (strEl && swot.strengths) { strEl.innerHTML = swot.strengths.map(s => `
        • โœ“ ${s}
        • `).join(''); } const weakEl = document.getElementById('battlecard-swot-weaknesses'); if (weakEl && swot.weaknesses) { weakEl.innerHTML = swot.weaknesses.map(w => `
        • ! ${w}
        • `).join(''); } const oppEl = document.getElementById('battlecard-swot-opportunities'); if (oppEl && swot.opportunities) { oppEl.innerHTML = swot.opportunities.map(o => `
        • โ˜… ${o}
        • `).join(''); } const thrEl = document.getElementById('battlecard-swot-threats'); if (thrEl && swot.threats) { thrEl.innerHTML = swot.threats.map(t => `
        • โš  ${t}
        • `).join(''); } // Tab 2: Competitors const compBody = document.getElementById('battlecard-competitors-tbody'); if (compBody && _battlecardData.competitors) { compBody.innerHTML = _battlecardData.competitors.map(c => ` ${c.name} ${c.relative_positioning} ${c.comparative_stack} ${c.vulnerability_wedge} `).join(''); } // Tab 3: Discovery Questions const qList = document.getElementById('battlecard-questions-list'); if (qList && _battlecardData.discovery_trap_questions) { qList.innerHTML = _battlecardData.discovery_trap_questions.map((q, idx) => `
          ${idx + 1} "${q.question}"
          Expected Response "${q.expected_answer}"
          Hidden Meaning ${q.hidden_meaning}
          Strategic Pivot ${q.pivot_wedge}
          `).join(''); } // Tab 4: Objections const objList = document.getElementById('battlecard-objections-list'); if (objList && _battlecardData.objection_playbook) { objList.innerHTML = _battlecardData.objection_playbook.map((o, idx) => `
          Objection ${idx + 1} "${o.objection}"
          Recommended Rebuttal: ${o.rebuttal}
          `).join(''); } // Tab 5: Markdown Dossier const mdPrev = document.getElementById('battlecard-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/battlecard-report.md?company=${encodeURIComponent(company)}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading battlecard dossier markdown."; } } } catch (err) { console.error("Battlecard calculation error:", err); } } let _minerData = null; function switchMinerTab(tabName, btn) { ['jobs', 'whatsapp', 'reddit', 'markdown'].forEach(t => { const el = document.getElementById(`miner-view-${t}`); if (el) { if (t === tabName) el.classList.remove('hidden'); else el.classList.add('hidden'); } }); document.querySelectorAll('.miner-tab-btn').forEach(b => { b.className = 'miner-tab-btn px-3 py-1.5 rounded-lg font-semibold text-slate-400 hover:text-slate-200 transition'; }); if (btn) { btn.className = 'miner-tab-btn px-3 py-1.5 rounded-lg font-bold bg-teal-600/20 text-teal-300 border border-teal-500/30 transition'; } } async function calculateMinerLive() { try { const stackInput = document.getElementById('miner-stack-input'); const nicheInput = document.getElementById('miner-niche-input'); const cityInput = document.getElementById('miner-city-input'); const limitInput = document.getElementById('miner-limit-input'); const stack = stackInput ? stackInput.value.trim() : 'Python,React,Kubernetes'; const niche = nicheInput ? nicheInput.value.trim() : 'clinica dental'; const city = cityInput ? cityInput.value.trim() : 'Bogotรก'; const limit = limitInput ? parseInt(limitInput.value) || 5 : 5; const qParams = `stack=${encodeURIComponent(stack)}&niche=${encodeURIComponent(niche)}&city=${encodeURIComponent(city)}&limit=${limit}`; const repBtn = document.getElementById('download-miner-dossier-btn'); if (repBtn) repBtn.href = `/b2b/lead-mining-dossier.md?${qParams}`; const dkBtn = document.getElementById('view-miner-deck-btn'); if (dkBtn) dkBtn.href = `/b2b/lead-mining-deck.html?${qParams}`; const csvBtn = document.getElementById('download-miner-csv-btn'); if (csvBtn) csvBtn.href = `/b2b/leads.csv?${qParams}`; const res = await fetch('/b2b/api/miner', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ stack, niche, city, limit }) }); if (!res.ok) return; const data = await res.json(); if (data.status !== 'success' || !data.dossier) return; _minerData = data.dossier; const metrics = _minerData.metrics || {}; const channels = _minerData.channels || {}; const totEl = document.getElementById('miner-kpi-total'); if (totEl) totEl.textContent = `${metrics.total_leads_mined || 0} Verified Leads`; const tamEl = document.getElementById('miner-kpi-tam'); if (tamEl) tamEl.textContent = `$${(metrics.aggregate_pipeline_tam || 0).toLocaleString()}`; const arbEl = document.getElementById('miner-kpi-arbitrage'); if (arbEl) arbEl.textContent = `+$${(metrics.annual_arbitrage_tam || 0).toLocaleString()}`; const readEl = document.getElementById('miner-kpi-readiness'); if (readEl) readEl.textContent = `${metrics.lead_readiness_score || 95} / 100`; // Tab 1: Remote Jobs Table const jobsBody = document.getElementById('miner-jobs-tbody'); if (jobsBody && channels.remote_tech_jobs) { jobsBody.innerHTML = channels.remote_tech_jobs.map(j => ` ${j.title} ${j.company} • ${j.location}
          ${(j.tech_stack || []).slice(0, 3).map(s => `${s}`).join('')}
          $${(j.us_benchmark || 0).toLocaleString()} $${(j.latam_cost || 0).toLocaleString()} +$${(j.annual_arbitrage || 0).toLocaleString()}/yr ${j.urgency_score}/100 Apply → `).join(''); } // Tab 2: WhatsApp SMBs Table const waBody = document.getElementById('miner-whatsapp-tbody'); if (waBody && channels.whatsapp_smb_leads) { waBody.innerHTML = channels.whatsapp_smb_leads.map(w => ` ${w.business_name} ${w.website_url ? `${w.website_url.replace('https://', '')}` : 'Direct Mobile'} ${w.niche} ${w.city}, ${w.country} ${w.formatted_phone} ${w.potential_deal_size} ${w.verification_status} ๐Ÿ’ฌ WhatsApp `).join(''); } // Tab 3: Reddit Community List const rdList = document.getElementById('miner-reddit-list'); if (rdList && channels.reddit_contractors) { rdList.innerHTML = channels.reddit_contractors.map(r => `
          r/${r.subreddit} ${r.date || 'Recent'}
          "${r.title}"
          Rate: ${r.rate_benchmark} Sentiment: ${r.sentiment} Signal: ${r.hiring_signal}
          `).join(''); } // Tab 4: Markdown Preview const mdPrev = document.getElementById('miner-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/lead-mining-dossier.md?${qParams}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading lead mining dossier markdown."; } } } catch (err) { console.error("Lead miner calculation error:", err); } } let _outreachData = null; let _outreachTone = 'challenger'; function setOutreachCompany(company) { const inp = document.getElementById('outreach-company-input'); if (inp) { inp.value = company; calculateOutreachLive(); } } function setOutreachTone(tone) { _outreachTone = tone; ['challenger', 'consultative', 'growth_velocity'].forEach(t => { const btn = document.getElementById(`tone-btn-${t}`); if (btn) { if (t === tone) { btn.className = 'outreach-tone-btn p-2 rounded-lg border text-left transition bg-violet-600/20 border-violet-500/50 text-violet-200'; } else { btn.className = 'outreach-tone-btn p-2 rounded-lg border text-left transition bg-slate-900 border-slate-700 text-slate-300 hover:border-slate-600'; } } }); calculateOutreachLive(); } function switchOutreachTab(tabName, btn) { ['touches', 'coldcall', 'tester', 'markdown'].forEach(t => { const el = document.getElementById(`outreach-view-${t}`); if (el) { if (t === tabName) el.classList.remove('hidden'); else el.classList.add('hidden'); } }); document.querySelectorAll('.outreach-tab-btn').forEach(b => { b.className = 'outreach-tab-btn px-3 py-1.5 rounded-lg font-semibold text-slate-400 hover:text-slate-200 transition'; }); if (btn) { btn.className = 'outreach-tab-btn px-3 py-1.5 rounded-lg font-bold bg-violet-600/20 text-violet-300 border border-violet-500/30 transition'; } } async function calculateOutreachLive() { try { const compInput = document.getElementById('outreach-company-input'); const company = compInput ? compInput.value.trim() : 'Supabase'; const tone = _outreachTone || 'challenger'; const qParams = `company=${encodeURIComponent(company)}&tone=${encodeURIComponent(tone)}`; const repBtn = document.getElementById('download-outreach-playbook-btn'); if (repBtn) repBtn.href = `/b2b/outreach-playbook.md?${qParams}`; const dkBtn = document.getElementById('view-outreach-deck-btn'); if (dkBtn) dkBtn.href = `/b2b/outreach-deck.html?${qParams}`; const csvBtn = document.getElementById('download-outreach-csv-btn'); if (csvBtn) csvBtn.href = `/b2b/outreach.csv?${qParams}`; const res = await fetch('/b2b/api/outreach', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company, tone }) }); if (!res.ok) return; const data = await res.json(); if (data.status !== 'success' || !data.cadence) return; _outreachData = data.cadence; const deliv = _outreachData.overall_deliverability || {}; const touches = _outreachData.touches || []; const scEl = document.getElementById('outreach-kpi-score'); if (scEl) scEl.textContent = `${(deliv.score || 90.2).toFixed(1)} / 100`; const grEl = document.getElementById('outreach-kpi-grade'); if (grEl) grEl.textContent = `Grade ${deliv.grade || 'A+'} Certified`; const inbEl = document.getElementById('outreach-kpi-inbox'); if (inbEl) inbEl.textContent = deliv.inbox_placement_rate_forecast || '96.4% - 98.8%'; const arbEl = document.getElementById('outreach-kpi-arbitrage'); if (arbEl) arbEl.textContent = `+$${(_outreachData.annual_savings_per_hire || 85000).toLocaleString()}`; const flEl = document.getElementById('outreach-kpi-flesch'); if (flEl) flEl.textContent = `${deliv.avg_flesch_grade_level || 11.3} / Grade`; // Tab 1: Touches Container const touchesContainer = document.getElementById('outreach-touches-container'); if (touchesContainer && touches.length) { touchesContainer.innerHTML = touches.map(t => { const dScore = t.deliverability ? t.deliverability.deliverability_score : 92.0; return `
          Touch ${t.touch_number} • Day ${t.day_offset} ${t.channel} (${t.objective || ''})
          Deliverability: ${dScore.toFixed(1)}/100
          Subject: ${t.subject || 'N/A'}
          ${t.body || ''}
          ${t.linkedin_note ? `
          ๐Ÿ”— LinkedIn Connection Request Note (${t.linkedin_note.length}/300 chars): "${t.linkedin_note}"
          ` : ''} ${t.whatsapp_message ? `
          ๐Ÿ“ฑ Direct WhatsApp / Voice Note Script: "${t.whatsapp_message}"
          ` : ''}
          `}).join(''); } // Tab 2: Cold Call & Objection Playbook const touch3 = touches.find(t => t.cold_call_script); if (touch3 && touch3.cold_call_script) { const ccs = touch3.cold_call_script; const opEl = document.getElementById('outreach-coldcall-opener'); if (opEl) opEl.textContent = ccs.opener_30s || ''; const gkEl = document.getElementById('outreach-coldcall-gatekeeper'); if (gkEl && ccs.gatekeeper_bypass) { gkEl.innerHTML = ccs.gatekeeper_bypass.map(g => `
        • ${g}
        • `).join(''); } const objEl = document.getElementById('outreach-objection-playbook'); if (objEl && ccs.objection_playbook) { objEl.innerHTML = Object.entries(ccs.objection_playbook).map(([key, item]) => `
          Objection: "${item.prospect_says}" Reframe Pivot: "${item.reframe_pivot}"
          `).join(''); } } // Tab 4: Markdown Playbook Preview const mdPrev = document.getElementById('outreach-markdown-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/outreach-playbook.md?${qParams}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading outreach playbook markdown."; } } } catch (err) { console.error("Outreach calculation error:", err); } } async function auditDeliverabilityLive() { try { const subInput = document.getElementById('test-email-subject'); const bodyInput = document.getElementById('test-email-body'); const subject = subInput ? subInput.value : ''; const body = bodyInput ? bodyInput.value : ''; const res = await fetch('/b2b/api/outreach/deliverability', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ subject, body }) }); if (!res.ok) return; const data = await res.json(); if (data.status !== 'success' || !data.audit) return; const a = data.audit; const scEl = document.getElementById('test-audit-score'); if (scEl) { scEl.textContent = `${a.deliverability_score.toFixed(1)} / 100`; scEl.className = `text-lg font-black font-mono ${a.deliverability_score >= 85 ? 'text-emerald-400' : a.deliverability_score >= 70 ? 'text-amber-400' : 'text-rose-400'}`; } const spEl = document.getElementById('test-audit-spam-count'); if (spEl) { const count = (a.detected_spam_triggers || []).length; spEl.textContent = `${count} Detected`; spEl.className = `text-lg font-black font-mono ${count === 0 ? 'text-white' : 'text-rose-400'}`; } const reEl = document.getElementById('test-audit-reading-ease'); if (reEl) reEl.textContent = `${a.flesch_reading_ease.toFixed(1)} (${a.reading_ease_category})`; const glEl = document.getElementById('test-audit-grade-level'); if (glEl) glEl.textContent = `${a.flesch_kincaid_grade_level.toFixed(1)}`; const wcEl = document.getElementById('test-audit-word-count'); if (wcEl) wcEl.textContent = `${a.word_count} words`; const recEl = document.getElementById('test-audit-recommendations'); if (recEl) { if (a.recommendations && a.recommendations.length) { recEl.innerHTML = `Optimizations:` + a.recommendations.map(r => `• ${r}`).join('
          '); } else { recEl.innerHTML = `โœ“ Clean pre-flight delivery posture. Grade ${a.deliverability_grade}.`; } } } catch (e) { console.error("Deliverability audit error:", e); } } // Deal Room Engine Interactive State & Handlers let _dealroomCompany = 'Scale AI'; let _dealroomArchetype = 'cybernetic_ai_pod'; let _dealroomTone = 'challenger'; let _dealroomData = null; function setDealroomCompany(comp) { const inp = document.getElementById('dealroom-company-input'); if (inp) inp.value = comp; calculateDealroomLive(); } function setDealroomArchetype(arch) { _dealroomArchetype = arch; document.querySelectorAll('.dealroom-arch-btn').forEach(btn => { btn.className = 'dealroom-arch-btn p-2 rounded-lg border text-left transition bg-slate-900 border-slate-700 text-slate-300 hover:border-slate-600'; }); const active = document.getElementById(`dealroom-arch-btn-${arch}`); if (active) { active.className = 'dealroom-arch-btn p-2 rounded-lg border text-left transition bg-amber-600/20 border-amber-500/50 text-amber-200'; } calculateDealroomLive(); } function setDealroomTone(tone) { _dealroomTone = tone; document.querySelectorAll('.dealroom-tone-btn').forEach(btn => { btn.className = 'dealroom-tone-btn px-2 py-1 rounded border text-center transition bg-slate-900 border-slate-700 text-slate-400 hover:border-slate-600 text-[11px]'; }); const active = document.getElementById(`dealroom-tone-btn-${tone}`); if (active) { active.className = 'dealroom-tone-btn px-2 py-1 rounded border text-center transition bg-amber-600/20 border-amber-500/50 text-amber-200 text-[11px] font-bold'; } calculateDealroomLive(); } function switchDealroomTab(tabName, btn) { ['hud', 'engines', 'dossier', 'json'].forEach(t => { const el = document.getElementById(`dealroom-view-${t}`); if (el) el.classList.add('hidden'); }); const target = document.getElementById(`dealroom-view-${tabName}`); if (target) { target.classList.remove('hidden'); } document.querySelectorAll('.dealroom-tab-btn').forEach(b => { b.className = 'dealroom-tab-btn px-3 py-1.5 rounded-lg font-semibold text-slate-400 hover:text-slate-200 transition'; }); if (btn) { btn.className = 'dealroom-tab-btn px-3 py-1.5 rounded-lg font-bold bg-amber-600/20 text-amber-300 border border-amber-500/30 transition'; } } async function calculateDealroomLive() { try { const compInput = document.getElementById('dealroom-company-input'); const company = compInput ? compInput.value.trim() : 'Scale AI'; const archetype = _dealroomArchetype || 'cybernetic_ai_pod'; const tone = _dealroomTone || 'challenger'; const qParams = `company=${encodeURIComponent(company)}&archetype=${encodeURIComponent(archetype)}&tone=${encodeURIComponent(tone)}`; const repBtn = document.getElementById('download-dealroom-dossier-btn'); if (repBtn) repBtn.href = `/b2b/dealroom-dossier.md?${qParams}`; const dkBtn = document.getElementById('view-dealroom-deck-btn'); if (dkBtn) dkBtn.href = `/b2b/dealroom-deck.html?${qParams}`; const res = await fetch('/b2b/api/dealroom', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ company, archetype, tone }) }); if (!res.ok) return; const data = await res.json(); if (data.status !== 'success' || !data.deal_room) return; _dealroomData = data.deal_room; const health = _dealroomData.deal_health || {}; const kpis = _dealroomData.kpis || {}; const scEl = document.getElementById('dealroom-kpi-health'); if (scEl) scEl.textContent = `${(health.score || 93.0).toFixed(1)} / 100`; const grEl = document.getElementById('dealroom-kpi-grade'); if (grEl) grEl.textContent = health.grade || 'Grade A+ (Prime Enterprise Close)'; const acvEl = document.getElementById('dealroom-kpi-acv'); if (acvEl) acvEl.textContent = `$${(kpis.estimated_acv || 266880).toLocaleString()}`; const retEl = document.getElementById('dealroom-kpi-retainer'); if (retEl) retEl.textContent = `$${(kpis.monthly_retainer || 22240).toLocaleString()} / month retainer`; const npvEl = document.getElementById('dealroom-kpi-npv'); if (npvEl) npvEl.textContent = `+$${(kpis.npv_36m || 1312373).toLocaleString()}`; const pbEl = document.getElementById('dealroom-kpi-payback'); if (pbEl) pbEl.textContent = `${(kpis.payback_months || 0.5).toFixed(1)} Mo / ${(kpis.velocity_multiplier || 2.8).toFixed(1)}x`; const rdEl = document.getElementById('dealroom-hud-readiness'); if (rdEl) rdEl.textContent = health.readiness || 'Immediate Executive Presentation'; const factorsEl = document.getElementById('dealroom-hud-factors'); if (factorsEl && health.key_factors) { factorsEl.innerHTML = health.key_factors.map(f => `
          โœ“ ${f}
          `).join(''); } // Tab 3: Markdown Preview const mdPrev = document.getElementById('dealroom-dossier-preview'); if (mdPrev) { try { const mdRes = await fetch(`/b2b/dealroom-dossier.md?${qParams}`); mdPrev.textContent = await mdRes.text(); } catch (e) { mdPrev.textContent = "Error loading deal room dossier markdown."; } } // Tab 4: JSON Preview const jsonPrev = document.getElementById('dealroom-json-preview'); if (jsonPrev) { jsonPrev.textContent = JSON.stringify(_dealroomData, null, 2); } } catch (err) { console.error("Deal room calculation error:", err); } } async function loadInfrastructureVitalsLive() { try { const resp = await fetch('/b2b/api/system/vitals'); if (!resp.ok) return; const data = await resp.json(); if (data.cpu_load) { const cpuEl = document.getElementById('vitals-cpu-load'); if (cpuEl) cpuEl.textContent = data.cpu_load; } if (data.ram) { const ramEl = document.getElementById('vitals-ram-avail'); if (ramEl) ramEl.textContent = `${data.ram.available_mb.toLocaleString()} MB`; const pctEl = document.getElementById('vitals-ram-pct'); if (pctEl) pctEl.textContent = `${data.ram.used_pct}%`; } if (data.disk) { const diskEl = document.getElementById('vitals-disk-free'); if (diskEl) diskEl.textContent = `${data.disk.available_gb} GB (${(100 - data.disk.used_pct).toFixed(1)}% free)`; } if (data.swap) { const swapEl = document.getElementById('vitals-swappiness'); if (swapEl) swapEl.textContent = `${data.swap.swappiness} (Conservative)`; } const cgroupsContainer = document.getElementById('vitals-cgroups-list'); if (cgroupsContainer && data.key_services) { let html = ''; for (const [name, svc] of Object.entries(data.key_services)) { html += `
          ${name} ${svc.memory_mb.toFixed(1)} MB (${svc.headroom_pct}% headroom)
          `; } cgroupsContainer.innerHTML = html; } // Fetch FD Telemetry try { const fdResp = await fetch('/b2b/api/system/fds'); if (fdResp.ok) { const fdData = await fdResp.json(); if (fdData.system_wide) { const sysFdEl = document.getElementById('vitals-system-fds'); if (sysFdEl) sysFdEl.textContent = `${fdData.system_wide.allocated_file_handles.toLocaleString()} handles`; } if (fdData.summary) { const maxFdEl = document.getElementById('vitals-max-fd-util'); if (maxFdEl) maxFdEl.textContent = `${fdData.summary.max_daemon_utilization_pct}% (Max Active)`; } } } catch (fderr) { console.error("FD fetch error:", fderr); } // Fetch VM Telemetry try { const vmResp = await fetch('/b2b/api/system/vm'); if (vmResp.ok) { const vmData = await vmResp.json(); if (vmData.dirty_pages) { const stallEl = document.getElementById('vitals-write-stall-risk'); if (stallEl) stallEl.textContent = vmData.dirty_pages.write_stall_risk; const dirtyEl = document.getElementById('vitals-dirty-pages'); if (dirtyEl) dirtyEl.textContent = `${vmData.dirty_pages.current_nr_dirty.toLocaleString()} / ${vmData.dirty_pages.dirty_threshold.toLocaleString()}`; } } } catch (vmerr) { console.error("VM fetch error:", vmerr); } // Fetch VPS Health Score try { const scoreResp = await fetch('/b2b/api/system/health-score'); if (scoreResp.ok) { const scoreData = await scoreResp.json(); if (scoreData.vps_health_score !== undefined) { const scoreEl = document.getElementById('vitals-health-score'); if (scoreEl) scoreEl.textContent = `${scoreData.vps_health_score}/100 (${scoreData.grade})`; } } } catch (scerr) { console.error("Score fetch error:", scerr); } // Fetch Linux PSI try { const psiResp = await fetch('/b2b/api/system/psi'); if (psiResp.ok) { const psiData = await psiResp.json(); const psiStatusEl = document.getElementById('vitals-psi-status'); if (psiStatusEl) psiStatusEl.textContent = psiData.status || 'OPTIMAL_ZERO_STALL'; if (psiData.cpu && psiData.cpu.some) { const cpuEl = document.getElementById('vitals-psi-cpu'); if (cpuEl) cpuEl.textContent = `${psiData.cpu.some.avg10}% (${psiData.cpu.status})`; } if (psiData.memory && psiData.memory.some) { const memEl = document.getElementById('vitals-psi-mem'); if (memEl) memEl.textContent = `${psiData.memory.some.avg10}% (Zero Stall)`; } if (psiData.io && psiData.io.some) { const ioEl = document.getElementById('vitals-psi-io'); if (ioEl) ioEl.textContent = `${psiData.io.some.avg10}% (${psiData.io.status})`; } if (psiData.memory && psiData.memory.oom_risk) { const oomEl = document.getElementById('vitals-psi-oom'); if (oomEl) oomEl.textContent = `${psiData.memory.oom_risk} (Safe)`; } } } catch (psierr) { console.error("PSI fetch error:", psierr); } // Fetch Service Resilience try { const resResp = await fetch('/b2b/api/system/resilience'); if (resResp.ok) { const resData = await resResp.json(); const statusEl = document.getElementById('vitals-resilience-status'); if (statusEl) statusEl.textContent = resData.status || 'ROCK_SOLID_100_PERCENT'; if (resData.summary) { const totalEl = document.getElementById('vitals-resilience-total'); if (totalEl) totalEl.textContent = `${resData.summary.active_services}/${resData.summary.total_services} Online`; const restartsEl = document.getElementById('vitals-resilience-restarts'); if (restartsEl) restartsEl.textContent = `${resData.summary.total_restarts} Restarts`; const flappingEl = document.getElementById('vitals-resilience-flapping'); if (flappingEl) flappingEl.textContent = `${resData.summary.flapping_count} Flapping (${resData.summary.flapping_risk} Risk)`; const availEl = document.getElementById('vitals-resilience-avail'); if (availEl) availEl.textContent = `${resData.summary.availability_pct}% Uptime`; } } } catch (reserr) { console.error("Resilience fetch error:", reserr); } } catch (e) { console.error("Error fetching vitals:", e); } } // Initialize Arbitrage, Sequence, Deal Closer, Vetting, Onboarding, Talent, Performance, Audit, FinOps & Infrastructure Vitals on load document.addEventListener('DOMContentLoaded', () => { calculateArbitrageLive(); loadSequenceLive(); calculateDealLive(); calculateVetLive(); calculateOnboardLive(); calculateTalentLive(); calculatePerfLive(); calculateAuditLive(); calculateFinOpsLive(); calculateResearchLive(); calculateComplianceLive(); calculateModernizationLive(); calculateAIWorkforceLive(); calculateProposalLive(); calculateBattlecardLive(); calculateMinerLive(); calculateOutreachLive(); calculateDealroomLive(); const dealroomCompInput = document.getElementById('dealroom-company-input'); if (dealroomCompInput) { dealroomCompInput.addEventListener('input', () => { clearTimeout(window._dealroomTimer); window._dealroomTimer = setTimeout(calculateDealroomLive, 400); }); } const outreachCompInput = document.getElementById('outreach-company-input'); if (outreachCompInput) { outreachCompInput.addEventListener('input', () => { clearTimeout(window._outreachTimer); window._outreachTimer = setTimeout(calculateOutreachLive, 400); }); } const minerStackInput = document.getElementById('miner-stack-input'); if (minerStackInput) { minerStackInput.addEventListener('input', () => { clearTimeout(window._minerTimer); window._minerTimer = setTimeout(calculateMinerLive, 400); }); } const minerNicheInput = document.getElementById('miner-niche-input'); if (minerNicheInput) { minerNicheInput.addEventListener('input', () => { clearTimeout(window._minerTimer); window._minerTimer = setTimeout(calculateMinerLive, 400); }); } const batCompInput = document.getElementById('battlecard-company-input'); if (batCompInput) { batCompInput.addEventListener('input', () => { clearTimeout(window._batTimer); window._batTimer = setTimeout(calculateBattlecardLive, 400); }); } const propCompInput = document.getElementById('proposal-company-input'); if (propCompInput) { propCompInput.addEventListener('input', () => { clearTimeout(window._propTimer); window._propTimer = setTimeout(calculateProposalLive, 400); }); } const modCompInput = document.getElementById('modernize-company-input'); if (modCompInput) { modCompInput.addEventListener('input', () => { clearTimeout(window._modTimer); window._modTimer = setTimeout(calculateModernizationLive, 400); }); } const aiCompInput = document.getElementById('aiworkforce-company-input'); if (aiCompInput) { aiCompInput.addEventListener('input', () => { clearTimeout(window._aiTimer); window._aiTimer = setTimeout(calculateAIWorkforceLive, 400); }); } const aiSlider = document.getElementById('aiworkforce-team-size-slider'); if (aiSlider) { aiSlider.addEventListener('input', () => { calculateAIWorkforceLive(); }); } loadInfrastructureVitalsLive(); });