Rajiv Weeraratne, MBA, PMP

Senior Finance and Operations Executive

Finance and operations executive with 20 years leading regulated, multi-entity portfolios across GovCon, international development, energy, and public-sector environments. Builds audit-ready controls, precise forecasts, ERP-enabled workflows, and scalable finance operations.

Target roles: Director of Finance, VP Finance, Head of Finance, CFO-track, and senior Finance & Operations leadership, with strong controllership, FP&A, audit readiness, and transformation depth.

Target sectors: GovCon, regulated private-sector finance, mission-driven organizations, municipal/public-sector finance, and finance transformation.

Ventura, CA | Greater Los Angeles / West Coast hybrid | U.S. remote | Travel-ready | U.S. work-authorized, no sponsorship required

$644MAggregate Portfolio Directed
16 YearsDeloitte Tenure
FAR/DCAAAudit-Ready Operations
99.8% Forecasting Accuracy
Scale and Impact
Portfolio Responsibility $644M Direct P&L management, working capital optimization, and full-cycle controllership View Portfolio ›
Additional Funding Secured $24.5M Secured through financial analysis and pricing discipline View Funding ›
Grants and Sub-awards Directed $40.5M Governed across global partner and donor environments View Grants ›
Countries Supported 21 Operating models standardized across cross-border environments View Footprint ›
JD Alignment Evaluator

Paste any job posting and get a scored alignment report against my career profile. Covers fit percentage by category, strengths, gaps, and interview prep questions with suggested answers.

Built on a fixed rubric, with credential equivalences applied and deductions capped. Results export to PDF.

Education & Certifications
Undergraduate Education BA | Economics & Mathematics University of Texas at Austin
Graduate Education MBA | Finance & Information Systems University of Colorado at Colorado Springs
Global Certification Project Management Professional (PMP®) PMI | Valid through February 2028
Get In Touch
500 remaining

Know someone who should see this?

Share this portfolio with your network on LinkedIn.

Share on LinkedIn
const experienceData = { "gps": { title: "Lead Finance Partner: Global GPS Portfolios", company: "Deloitte", fullCompany: "Deloitte Consulting LLP", period: "August 2024 - December 2025", location: "Ventura, CA", duration: 17, bullets: [ { text: "Directed finance operations for a $238M international development portfolio spanning 15 entities, holding sole accountability for P&L, compliance, audit readiness, and financial reporting across Deloitte GPS's international accounts.", category: "finance", tags: ["fp_a","controllership","audit"] }, { text: "Standardized the procurement lifecycle, AP, and month-end close via Sage Intacct, accelerating client invoicing cycles and improving working capital visibility across the full portfolio.", category: "systems", tags: ["erp","controllership"] }, { text: "Enforced consistent ledger coding and vendor management through Source-to-Pay controls, enabling precise management reporting and audit-ready documentation across all active entities.", category: "finance", tags: ["govcon","controllership","audit"] }, { text: "Pivoted the portfolio from growth strategy to crisis financial management following Stop Work orders triggered by federal policy shifts, protecting program revenue and executing compliant wind-downs within compressed timelines.", category: "finance", tags: ["fp_a","closeout"] }, { text: "Executed Termination for Convenience protocols and structured financial wind-downs with no unresolved financial liabilities, managing asset disposition and local labor-law severance exposure across multiple jurisdictions.", category: "finance", tags: ["closeout"] }, { text: "Led proposal pricing for $10M to $75M federal and state pursuits at DOE, EPA, NNSA, Library of Congress, California DWR, and NYSERDA as sole pricing SME across CPFF, T&M, and FFP structures.", category: "procurement", tags: ["govcon","pricing"] } ] }, "saep": { title: "Director of Finance & Operations: Southern Africa Energy Program (SAEP)", company: "Deloitte", fullCompany: "Deloitte Consulting LLP", period: "June 2017 - July 2024", location: "Pretoria, South Africa", duration: 86, bullets: [ { text: "Directed finance strategy, P&L execution, AP, AR, payroll, and full audit readiness for a $75M USAID/Power Africa regional energy program across 10 countries, leading a team of 10 finance staff across 8 regional offices.", category: "finance", tags: ["fp_a","controllership","audit"] }, { text: "Achieved 99.8% forecasting accuracy, capturing 100% of the $5.2M available fixed fee and restricting unspent variance to $122K through rigorous burn-rate modeling.", category: "finance", tags: ["fp_a"] }, { text: "Secured $5M in additional strategic funding for South Africa's Just Energy Transition by proving program performance to USAID through financial justifications tied to measurable output KPIs.", category: "finance", tags: ["fp_a","govcon"] }, { text: "Resolved a $7M international tax deadlock by restructuring invoicing from USD to ZAR, preventing a 15% budget overrun and enabling full input VAT recovery.", category: "finance", tags: ["govcon","controllership"] }, { text: "Brought 5,771 MW of generation capacity to financial close and enabled 3.03M direct electricity connections by designing a Results-Based Financing framework tied to USAID/Power Africa performance indicators.", category: "finance", tags: ["fp_a","municipal"] }, { text: "Reduced global payment cycles by 10 days and improved invoice and expense accuracy by 25% by migrating manual procurement workflows to Sage Intacct.", category: "systems", tags: ["erp","controllership"] }, { text: "Built PowerBI dashboards integrated with Sage Intacct and developed activity-based budgeting tools tied to country and outcome-level spend, improving executive decision support for the Senior Leadership Team.", category: "systems", tags: ["erp","fp_a"] }, { text: "Directed a $28.5M sub-award portfolio including McKinsey and CrossBoundary through rigorous Source-to-Pay vendor governance, maintaining clean annual audits and 100% allowable cost recovery.", category: "procurement", tags: ["grants","govcon","audit"] }, { text: "Managed a $3.5M Catalyzing Local Opportunities Grants Fund via Fluxx, deploying $2.7M in verified disbursements, unlocking $4M in commercial working capital, and driving 108,721 verified Solar Home System sales across Malawi.", category: "procurement", tags: ["grants"] }, { text: "Identified $87.1M in municipal electricity revenue opportunities across 10 South African municipalities, realizing $3.1M by end of 2023 and training 125 municipal staff on revenue management, billing, metering, and controls.", category: "finance", tags: ["municipal"] }, { text: "Managed VAT, payroll withholding, SARS compliance, USAID donor rules, and multi-currency treasury, securing clean audits across all operating jurisdictions throughout the program lifecycle.", category: "finance", tags: ["govcon","controllership","audit"] }, { text: "Executed full program closeout with no unresolved liabilities, including office decommissioning, asset disposition, labor retrenchment, SARS final financials, VAT recovery, and legal entity deregistration across South Africa and Zambia.", category: "finance", tags: ["closeout"] } ] }, "carcep": { title: "Director of Finance & Operations: Caribbean Clean Energy Program (CARCEP)", company: "Deloitte", fullCompany: "Deloitte Consulting LLP", period: "November 2015 - May 2017", location: "Kingston, Jamaica", duration: 19, bullets: [ { text: "Led full-cycle financial operations for a $20M USAID regional energy program across 8 Caribbean countries with a 6-person team, maintaining 100% FAR compliance across all budget execution, AP, AR, and reporting functions.", category: "finance", tags: ["fp_a","govcon","controllership","audit"] }, { text: "Established operating infrastructure in Jamaica and Barbados, including legal entity registration, banking, leases, hiring, and procurement workflows, enabling immediate program launch and full financial control from day one.", category: "finance", tags: ["closeout","controllership"] }, { text: "Shortened monthly financial reporting cycles by 5 days and improved asset tracking accuracy by 50% by standardizing ledger coding through automated accrual workflows.", category: "finance", tags: ["controllership","fp_a"] }, { text: "Governed a $7M sub-award and Procure-to-Pay ledger covering technical grid deliverables, including transmission planning and DigSilent power modeling, maintaining audit-ready documentation across all transactions.", category: "procurement", tags: ["grants","govcon","audit"] }, { text: "Managed a $1.5M regional clean energy grants fund, conducting 30+ grantee site visits and implementing one of the earliest Fluxx Grants Management System deployments in the USAID ecosystem.", category: "procurement", tags: ["grants"] }, { text: "Delivered an energy benchmarking SaaS platform to 100+ PAHO healthcare facilities and CHTA hotel operators by directing agile vendor delivery through structured software procurement governance.", category: "systems", tags: ["erp"] } ] }, "faces": { title: "Program Manager: DC FACES - Child and Family Services Agency (CFSA)", company: "Deloitte", fullCompany: "Deloitte Consulting LLP", period: "June 2015 - October 2015", location: "Washington, DC", duration: 5, bullets: [ { text: "Directed an 8-member cross-functional team on SACWIS/FACES child welfare system maintenance and enhancements, delivering all scheduled releases on time and within budget with near-zero system downtime.", category: "systems", tags: ["erp"] }, { text: "Maintained 100% responsiveness to CFSA caseworker inquiries by standardizing operational workflows through centralized resource allocation, agile triage protocols, and remote and onsite coordination.", category: "systems", tags: ["erp"] }, { text: "Protected child welfare data integrity and regulatory compliance by managing enhancement prioritization through structured change control boards, enforcing auditable financial documentation across all system modifications.", category: "finance", tags: ["govcon","controllership"] }, { text: "Controlled project budget and managed all vendor activities, maintaining cost discipline and audit-ready financial documentation across all program expenditures.", category: "finance", tags: ["fp_a"] } ] }, "core2": { title: "State Public Financial Management Team Lead: Strengthening Core Economic Governance Institutions in South Sudan II (CORE II)", company: "Deloitte", fullCompany: "Deloitte Consulting LLP", period: "May 2012 - May 2015", location: "Juba, South Sudan", duration: 37, bullets: [ { text: "Directed FreeBalance IFMIS rollout across State Ministries of Finance in 10 South Sudan state governments on a $90M USAID governance program, covering chart of accounts configuration, revenue and expenditure accounting, and fiscal year-end preparation.", category: "systems", tags: ["erp","municipal"] }, { text: "Improved state fiscal management performance by up to 70% and achieved a 90% financial reporting compliance rate by deploying KPI-driven scorecards and budget execution oversight across all participating ministries.", category: "finance", tags: ["fp_a","municipal"] }, { text: "Built technical capacity across 100+ state government finance officers, delivering structured training that directly underpinned each state's ability to meet federal reporting standards and complete fiscal year-end procedures independently.", category: "finance", tags: ["municipal"] }, { text: "Maintained IFMIS system continuity through the December 2013 civil conflict and severe macroeconomic volatility, sustaining financial operations without disruption to program reporting or budget execution.", category: "systems", tags: ["erp"] } ] }, "acss": { title: "Finance Manager: Afghanistan Civil Service Support (ACSS) Program", company: "Deloitte", fullCompany: "Deloitte Consulting LLP", period: "May 2010 - April 2012", location: "Kabul, Afghanistan", duration: 24, bullets: [ { text: "Managed forecasting, fund chain management, AP, AR, multi-currency reconciliation, and monthly payroll for a $219M multi-CLIN USAID program supporting 700+ personnel via Deltek Costpoint.", category: "finance", tags: ["fp_a","controllership","govcon"] }, { text: "Secured $19.5M in additional program funding by demonstrating execution velocity through rigorous burn-rate analysis and LOE expenditure modeling submitted to donor stakeholders.", category: "finance", tags: ["fp_a"] }, { text: "Maintained uninterrupted financial operations throughout active security constraints and rapid program drawdown by preserving liquidity controls and transaction continuity across all cost centers.", category: "finance", tags: ["controllership"] }, { text: "Spearheaded the financial closeout of the program and full wind-down of Deloitte's Afghanistan entity, resolving all vendor settlements, managing asset disposition, and reconciling all accounts with no unresolved liabilities.", category: "finance", tags: ["closeout"] }, { text: "Enforced 100% FAR and Deloitte financial policy compliance in a DCAA-adjacent, high-risk operational environment, serving as primary interface with external auditors throughout the program lifecycle.", category: "finance", tags: ["govcon","controllership","audit"] } ] }, "ict": { title: "ICT Advisor: Information Technology Master Plan - Implementation Phase (ITMP-IP)", company: "Deloitte", fullCompany: "Deloitte Consulting LLP", period: "May 2009 - April 2010", location: "Amman, Jordan", duration: 12, bullets: [ { text: "Assessed Jordan Ministry of Water and Irrigation ICT performance against the 2006 IT Master Plan using ITIL standards, SLAs, and change control protocols across a $2M innovation and ICT portfolio.", category: "systems", tags: ["erp","municipal"] }, { text: "Built an organizational performance management tool and supporting user manual, enabling KPI-driven tracking of department-specific service level agreements and improvement targets.", category: "systems", tags: ["erp"] }, { text: "Specified requirements for an automated service desk to replace legacy manual systems, reducing ICT response cycle times and strengthening change control discipline.", category: "systems", tags: ["erp"] } ] }, "bearingpoint": { title: "Financial Specialist / Sr. Business Analyst", company: "BearingPoint", fullCompany: "BearingPoint", period: "September 2005 - April 2009", location: "Global", duration: 44, bullets: [ { text: "Maintained the Integrated Master Schedule for the Walter Reed Army Medical Center transition to National Naval Medical Center, Fort Belvoir, and Malcolm Grow Medical Center, coordinating updates with the Army Corps of Engineers.", category: "finance", tags: ["fp_a"] }, { text: "Supported PPP feasibility assessments for Port of Aqaba terminals by building ROI and scenario analysis models, contributing to investor identification, financial bundling strategies, and market feedback capture.", category: "finance", tags: ["fp_a"] }, { text: "Built the PMIS and external project website for the Aqaba Development Corporation New Port Project and contributed to the National Project Management Unit's planning and reporting workflows.", category: "systems", tags: ["erp"] }, { text: "Reconciled subcontractor and consultant payments and maintained ETC versus current budget analyses across federal infrastructure and emerging markets engagements.", category: "finance", tags: ["controllership","fp_a"] }, { text: "Documented current-state process flows and non-value-added activities for business process reengineering and coordinated IT and project management training for field teams.", category: "systems", tags: ["erp"] } ] } }; const timelineContainer = document.getElementById('timeline-container'); const detailsContainer = document.getElementById('experience-details'); let currentActiveId = 'gps'; let lastActiveElement = null; let factBaseReturnElement = null; let currentAiMode = 'url'; let aiAbortController = null; let currentAiResult = null; let currentJdPayload = null; let activeCareerFilter = null; const EVALUATOR_REQUEST_TIMEOUT_MS = 90000; const EVAL_ENDPOINT = 'https://www.rajivweeraratne.com/api/evaluate'; const EVALUATOR_MAILTO_LIMIT = 8000; function toggleMobileMenu() { const menu = document.getElementById('mobile-menu'); const iconMenu = document.getElementById('icon-menu'); const iconClose = document.getElementById('icon-close'); const nav = document.getElementById('main-nav'); const btn = document.getElementById('mobile-menu-btn'); if (menu.classList.contains('hidden')) { menu.classList.remove('hidden'); iconMenu.classList.add('hidden'); iconClose.classList.remove('hidden'); nav.classList.remove('bg-slate-900/85', 'backdrop-blur-md'); nav.classList.add('bg-slate-900'); if (btn) btn.setAttribute('aria-expanded', 'true'); } else { closeMobileMenu(); } } function closeMobileMenu() { const menu = document.getElementById('mobile-menu'); const iconMenu = document.getElementById('icon-menu'); const iconClose = document.getElementById('icon-close'); const nav = document.getElementById('main-nav'); const btn = document.getElementById('mobile-menu-btn'); if (!menu.classList.contains('hidden')) { menu.classList.add('hidden'); iconMenu.classList.remove('hidden'); iconClose.classList.add('hidden'); nav.classList.add('bg-slate-900/85', 'backdrop-blur-md'); nav.classList.remove('bg-slate-900'); if (btn) btn.setAttribute('aria-expanded', 'false'); } } function renderTimeline() { timelineContainer.innerHTML = ''; const allRoles = ['gps', 'saep', 'carcep', 'faces', 'core2', 'acss', 'ict', 'bearingpoint']; allRoles.forEach((key) => { const data = experienceData[key]; const btn = document.createElement('div'); btn.dataset.key = key; btn.setAttribute('role', 'button'); btn.setAttribute('tabindex', '0'); btn.setAttribute('aria-label', `Scroll to ${data.title}`); btn.onkeydown = (e) => { if(e.key === 'Enter' || e.key === ' ') { e.preventDefault(); btn.click(); } }; const titleParts = data.title.split(':'); const roleTitle = titleParts[0]; const programTitle = titleParts.length > 1 ? titleParts[1].trim() : ''; btn.className = 'kpi-card timeline-item p-4 lg:p-5 rounded-xl bg-white border border-slate-200 border-t-4 border-t-slate-300 shadow-sm text-slate-500 cursor-pointer flex flex-col justify-center outline-none transition-all opacity-80 hover:opacity-100 hover:border-t-blue-400'; btn.innerHTML = `
${data.company}
${roleTitle}${programTitle ? `${programTitle}` : ''}
${data.period}
`; btn.onclick = () => { const target = document.getElementById(`role-${key}`); if (target) { const navHeight = document.getElementById('main-nav').offsetHeight; const offsetPosition = target.getBoundingClientRect().top + window.pageYOffset - navHeight - 24; window.scrollTo({ top: offsetPosition, behavior: 'smooth' }); } }; timelineContainer.appendChild(btn); }); } function renderExperienceStack() { detailsContainer.innerHTML = ''; const allRoles = ['gps', 'saep', 'carcep', 'faces', 'core2', 'acss', 'ict', 'bearingpoint']; const colorMap = { 'finance': 'before:bg-blue-900', 'procurement': 'before:bg-emerald-700', 'systems': 'before:bg-amber-600', 'default': 'before:bg-blue-900' }; allRoles.forEach((key) => { const data = experienceData[key]; const bulletsHtml = data.bullets.map(b => { const text = typeof b === 'string' ? b : b.text; const cat = typeof b === 'string' ? 'default' : (b.category || 'default'); const tags = (typeof b === 'object' && b.tags) ? b.tags.join(',') : ''; const dotColor = colorMap[cat] || colorMap['default']; return `
  • ${text}
  • `; }).join(''); const roleDiv = document.createElement('div'); roleDiv.id = `role-${key}`; roleDiv.className = 'relative scroll-mt-24'; roleDiv.innerHTML = `

    ${data.title}

    ${data.fullCompany || data.company}

    ${data.period} | ${data.location}
    `; detailsContainer.appendChild(roleDiv); }); } function updateTimelineActiveState(activeKey) { document.querySelectorAll('.timeline-item').forEach(el => { if (el.dataset.key === activeKey) { el.className = 'kpi-card timeline-item p-4 lg:p-5 rounded-xl bg-white border border-slate-200 border-t-4 border-t-blue-900 shadow-md text-slate-900 cursor-pointer flex flex-col justify-center outline-none transition-all scale-[1.02]'; const container = document.getElementById('timeline-container'); const elRect = el.getBoundingClientRect(); const containerRect = container.getBoundingClientRect(); if (elRect.top < containerRect.top || elRect.bottom > containerRect.bottom) { el.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } } else { el.className = 'kpi-card timeline-item p-4 lg:p-5 rounded-xl bg-white border border-slate-200 border-t-4 border-t-slate-300 shadow-sm text-slate-500 cursor-pointer flex flex-col justify-center outline-none transition-all opacity-80 hover:opacity-100 hover:border-t-blue-400'; } }); } function initExperienceScrollSpy() { const roleElements = document.querySelectorAll('[id^="role-"]'); if (roleElements.length === 0) return; const observerOptions = { root: null, rootMargin: '-120px 0px -60% 0px', threshold: 0 }; const observer = new IntersectionObserver((entries) => { let topmost = null; let topmostY = Infinity; entries.forEach(entry => { if (entry.isIntersecting) { const y = entry.boundingClientRect.top; if (y < topmostY) { topmostY = y; topmost = entry.target; } } }); if (topmost) { const activeKey = topmost.id.replace('role-', ''); updateTimelineActiveState(activeKey); } }, observerOptions); roleElements.forEach(section => observer.observe(section)); } function renderMobileAccordion() { const container = document.getElementById('mobile-accordion-container'); container.innerHTML = ''; const allRoles = ['gps', 'saep', 'carcep', 'faces', 'core2', 'acss', 'ict', 'bearingpoint']; const colorMap = { 'finance': 'before:bg-blue-900', 'procurement': 'before:bg-emerald-700', 'systems': 'before:bg-amber-600', 'default': 'before:bg-blue-900' }; allRoles.forEach((key, index) => { const data = experienceData[key]; const isFirst = index === 0; const titleParts = data.title.split(':'); const roleTitle = titleParts[0]; const programTitle = titleParts.length > 1 ? titleParts[1].trim() : ''; const bulletsHtml = data.bullets.map(b => { const text = typeof b === 'string' ? b : b.text; const cat = typeof b === 'string' ? 'default' : (b.category || 'default'); const tags = (typeof b === 'object' && b.tags) ? b.tags.join(',') : ''; const dotColor = colorMap[cat] || colorMap['default']; return `
  • ${text}
  • `; }).join(''); const card = document.createElement('div'); card.className = "bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm"; card.innerHTML = `
    `; container.appendChild(card); }); } const CHIP_ACTIVE = 'career-filter-chip bg-blue-900 text-white border-blue-900 text-xs font-semibold px-2.5 py-1 rounded-full border transition-colors focus-ring'; const CHIP_INACTIVE = 'career-filter-chip bg-white text-slate-600 border-slate-300 hover:border-slate-500 text-xs font-semibold px-2.5 py-1 rounded-full border transition-colors focus-ring'; const ROLE_KEYS = ['gps', 'saep', 'carcep', 'faces', 'core2', 'acss', 'ict', 'bearingpoint']; let careerSearchQuery = ''; function bulletVisible(li) { const tagMatch = !activeCareerFilter || li.dataset.tags.split(',').includes(activeCareerFilter); const textMatch = !careerSearchQuery || li.textContent.toLowerCase().includes(careerSearchQuery); return tagMatch && textMatch; } function renderCareerVisibility() { document.querySelectorAll('.career-filter-chip').forEach(chip => { chip.className = chip.dataset.tag === (activeCareerFilter || 'all') ? CHIP_ACTIVE : CHIP_INACTIVE; }); ROLE_KEYS.forEach(key => { let desktopVisible = 0; const roleDiv = document.getElementById('role-' + key); if (roleDiv) { roleDiv.querySelectorAll('li[data-tags]').forEach(li => { const show = bulletVisible(li); li.style.display = show ? '' : 'none'; if (show) desktopVisible++; }); roleDiv.style.display = desktopVisible === 0 ? 'none' : ''; } const tlItem = document.querySelector('.timeline-item[data-key="' + key + '"]'); if (tlItem) tlItem.style.display = desktopVisible === 0 ? 'none' : ''; let mobileVisible = 0; const accBtn = document.getElementById('acc-btn-' + key); if (accBtn) { const accCard = accBtn.parentElement; if (accCard) { accCard.querySelectorAll('li[data-tags]').forEach(li => { const show = bulletVisible(li); li.style.display = show ? '' : 'none'; if (show) mobileVisible++; }); accCard.style.display = mobileVisible === 0 ? 'none' : ''; } } }); } window.applyCareerFilter = function(tag) { activeCareerFilter = (tag === 'all' || activeCareerFilter === tag) ? null : tag; renderCareerVisibility(); }; window.applyCareerSearch = function(query) { careerSearchQuery = query.trim().toLowerCase(); renderCareerVisibility(); }; window.toggleAccordion = function(key) { const body = document.getElementById(`acc-body-${key}`); const icon = document.getElementById(`acc-icon-${key}`); const btn = document.getElementById(`acc-btn-${key}`); const isHidden = body.classList.contains('hidden'); document.querySelectorAll('.acc-body').forEach(el => el.classList.add('hidden')); document.querySelectorAll('.acc-icon').forEach(el => { el.style.transform = 'rotate(0deg)'; el.classList.remove('text-blue-900'); }); document.querySelectorAll('.acc-btn').forEach(el => { el.classList.remove('border-t-blue-900'); el.classList.add('border-t-slate-300'); el.setAttribute('aria-expanded', 'false'); }); if (isHidden) { body.classList.remove('hidden'); icon.style.transform = 'rotate(180deg)'; icon.classList.add('text-blue-900'); btn.classList.remove('border-t-slate-300'); btn.classList.add('border-t-blue-900'); btn.setAttribute('aria-expanded', 'true'); setTimeout(() => { const navHeight = document.getElementById('main-nav').offsetHeight; const elementPosition = btn.getBoundingClientRect().top; const offsetPosition = elementPosition + window.pageYOffset - navHeight - 16; window.scrollTo({ top: offsetPosition, behavior: 'smooth' }); }, 50); } }; function submitContactForm(e) { e.preventDefault(); const name = document.getElementById('contactName').value.trim(); const email = document.getElementById('contactEmail').value.trim(); const subject = document.getElementById('contactSubject').value.trim() || 'Portfolio Inquiry'; const message = document.getElementById('contactMessage').value.trim(); const errEl = document.getElementById('contactFormError'); if (!name || !email || !message) { errEl.textContent = 'Please fill in your name, email, and message before sending.'; errEl.classList.remove('hidden'); return; } errEl.classList.add('hidden'); const mailSubject = encodeURIComponent(subject + (name ? ' \u2014 from ' + name : '')); const mailBody = encodeURIComponent('Name: ' + name + '\nEmail: ' + email + '\n\n' + message); window.location.href = 'mailto:[email protected]?subject=' + mailSubject + '&body=' + mailBody; } function openAiModal() { closeMobileMenu(); lastActiveElement = document.activeElement; const modal = document.getElementById('aiModal'); modal.style.display = 'flex'; document.body.style.overflow = 'hidden'; document.getElementById('aiInputArea').classList.remove('hidden'); document.getElementById('aiOutputArea').classList.add('hidden'); document.getElementById('jdInput').value = ''; document.getElementById('jdUrlInput').value = ''; currentAiResult = null; currentJdPayload = null; switchAiTab('url'); setTimeout(() => { const modalBody = document.querySelector('#aiModal .modal-body'); if (modalBody) modalBody.scrollTop = 0; document.getElementById('jdUrlInput').focus(); }, 50); } function closeAiModal(e) { if(e && e.target !== e.currentTarget) return; document.getElementById('aiModal').style.display = 'none'; document.body.style.overflow = ''; if (aiAbortController) { aiAbortController.abort(); aiAbortController = null; const btn = document.getElementById('aiSubmitBtn'); const spinner = document.getElementById('spinner'); const btnText = document.getElementById('btnText'); if (btn) btn.disabled = false; if (spinner) spinner.classList.add('hidden'); if (btnText) btnText.innerText = "Run Alignment"; } if (lastActiveElement) lastActiveElement.focus(); } function switchAiTab(mode) { currentAiMode = mode; const textBtn = document.getElementById('tabTextBtn'); const urlBtn = document.getElementById('tabUrlBtn'); const textGroup = document.getElementById('textInputGroup'); const urlGroup = document.getElementById('urlInputGroup'); if (mode === 'text') { textBtn.className = "text-blue-900 font-bold border-b-2 border-blue-900 pb-2 transition-colors focus-ring rounded-sm"; urlBtn.className = "text-slate-400 hover:text-blue-900 font-medium pb-2 transition-colors focus-ring rounded-sm"; textGroup.classList.remove('hidden'); textGroup.classList.add('block'); urlGroup.classList.remove('block'); urlGroup.classList.add('hidden'); setTimeout(() => document.getElementById('jdInput').focus(), 50); } else { urlBtn.className = "text-blue-900 font-bold border-b-2 border-blue-900 pb-2 transition-colors focus-ring rounded-sm"; textBtn.className = "text-slate-400 hover:text-blue-900 font-medium pb-2 transition-colors focus-ring rounded-sm"; urlGroup.classList.remove('hidden'); urlGroup.classList.add('block'); textGroup.classList.remove('block'); textGroup.classList.add('hidden'); setTimeout(() => document.getElementById('jdUrlInput').focus(), 50); } } function injectCtaAfterResult() { const output = document.getElementById('aiOutputArea'); if (!output || output.classList.contains('hidden')) return; if (document.getElementById('ai-cta-block')) return; const cta = document.createElement('div'); cta.id = 'ai-cta-block'; cta.className = 'mt-8 pt-7 border-t border-slate-100 text-center'; cta.innerHTML = '

    Next step

    Email MeResume
    '; output.appendChild(cta); } function resetAi() { document.getElementById('aiInputArea').classList.remove('hidden'); document.getElementById('aiOutputArea').classList.add('hidden'); document.getElementById('jdInput').value = ''; document.getElementById('jdUrlInput').value = ''; currentAiResult = null; currentJdPayload = null; const cta = document.getElementById('ai-cta-block'); if (cta) cta.remove(); switchAiTab('url'); } function buildOwnerAnalysisSection() { return `
    `; } function buildScoreBreakdownSection() { const result = currentAiResult; if (!result || !result.score_components || typeof result.score_components !== 'object') return ''; const componentLabels = { role_function_alignment: 'Role Function Alignment', seniority_scope_alignment: 'Seniority & Scope', technical_finance_alignment: 'Technical Finance', industry_domain_alignment: 'Industry & Domain', systems_tools_alignment: 'Systems & Tools', credential_regulatory_alignment: 'Credentials & Regulatory', location_work_model_alignment: 'Location & Work Model', marketability_alignment: 'Marketability' }; const components = result.score_components; const componentRows = Object.entries(components).map(([key, comp]) => { const label = componentLabels[key] || key.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()); const score = Number.isFinite(Number(comp.score)) ? Number(comp.score) : 0; const max = Number.isFinite(Number(comp.max_score)) ? Number(comp.max_score) : 0; const pct = max > 0 ? Math.round((score / max) * 100) : 0; const barColor = pct >= 75 ? '#1e3a8a' : pct >= 50 ? '#3b82f6' : pct >= 25 ? '#94a3b8' : '#e2e8f0'; return `
    ${escapeHtml(label)} ${escapeHtml(String(score))} / ${escapeHtml(String(max))}

    ${escapeHtml(comp.rationale || '')}

    `; }).join(''); let requirementHtml = ''; if (Array.isArray(result.requirement_matches) && result.requirement_matches.length > 0) { const evidenceStyle = { direct: { bg: '#dcfce7', text: '#166534', label: 'Direct' }, adjacent: { bg: '#dbeafe', text: '#1e40af', label: 'Adjacent' }, transferable: { bg: '#fef9c3', text: '#854d0e', label: 'Transferable' }, unsupported: { bg: '#fee2e2', text: '#991b1b', label: 'Unsupported' }, contradicted: { bg: '#fecaca', text: '#7f1d1d', label: 'Contradicted' }, unknown: { bg: '#f1f5f9', text: '#475569', label: 'Unknown' } }; const riskStyle = { none: { text: '#166534', label: 'None' }, low: { text: '#854d0e', label: 'Low' }, medium: { text: '#c2410c', label: 'Medium' }, high: { text: '#991b1b', label: 'High' }, disqualifying: { text: '#7f1d1d', label: 'Disqualifying' } }; const reqRows = result.requirement_matches.map((match, idx) => { const ev = evidenceStyle[match.evidence_strength] || { bg: '#f1f5f9', text: '#475569', label: escapeHtml(String(match.evidence_strength || '')) }; const risk = riskStyle[match.risk_level] || { text: '#475569', label: escapeHtml(String(match.risk_level || '')) }; const hasDetail = !!(match.candidate_evidence || match.notes || (Array.isArray(match.fact_base_refs) && match.fact_base_refs.length)); const refsHtml = (Array.isArray(match.fact_base_refs) && match.fact_base_refs.length) ? `` : ''; const detailHtml = [ match.candidate_evidence ? `

    Evidence: ${escapeHtml(match.candidate_evidence)}

    ` : '', match.notes ? `

    Notes: ${escapeHtml(match.notes)}

    ` : '', refsHtml ? `
    References:${refsHtml}
    ` : '' ].filter(Boolean).join(''); const expandIndicator = hasDetail ? `` : ''; return ` ${escapeHtml(match.jd_requirement || '')}${expandIndicator} ${escapeHtml(ev.label)} ${escapeHtml(risk.label)} ${hasDetail ? ` ${detailHtml} ` : ''}`; }).join(''); requirementHtml = `

    Requirement Detail

    ${reqRows}
    Requirement Evidence Risk
    `; } return `
    ${componentRows} ${requirementHtml}
    `; } function toggleScoreBreakdown() { const panel = document.getElementById('score-breakdown-panel'); const toggle = document.getElementById('score-breakdown-toggle'); const chevron = document.getElementById('score-breakdown-chevron'); if (!panel) return; const opening = panel.classList.contains('hidden'); panel.classList.toggle('hidden', !opening); panel.setAttribute('aria-hidden', String(!opening)); if (toggle) toggle.setAttribute('aria-expanded', String(opening)); if (chevron) chevron.innerHTML = opening ? '▴' : '▾'; } function toggleReqRow(idx) { const detail = document.getElementById('req-detail-' + idx); const chevron = document.getElementById('req-chevron-' + idx); const row = detail ? detail.previousElementSibling : null; if (!detail) return; const opening = detail.classList.contains('hidden'); detail.classList.toggle('hidden', !opening); if (row) row.setAttribute('aria-expanded', String(opening)); if (chevron) chevron.innerHTML = opening ? '▴' : '▾'; } function showOwnerPin() { const trigger = document.getElementById('owner-trigger-row'); const form = document.getElementById('owner-pin-form'); if (trigger) trigger.classList.add('hidden'); if (form) { form.classList.remove('hidden'); document.getElementById('ownerPinInput')?.focus(); } } async function submitOwnerPin() { const pinInput = document.getElementById('ownerPinInput'); const errorEl = document.getElementById('owner-pin-error'); const unlockBtn = document.getElementById('ownerUnlockBtn'); const pin = pinInput ? pinInput.value.trim() : ''; if (!pin) return; if (!currentJdPayload) { if (errorEl) { errorEl.textContent = 'No evaluation loaded.'; errorEl.classList.remove('hidden'); } return; } if (errorEl) errorEl.classList.add('hidden'); if (unlockBtn) { unlockBtn.disabled = true; unlockBtn.textContent = 'Unlocking...'; } try { const response = await fetch(EVAL_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...currentJdPayload, owner_mode: true, owner_key: pin }) }); if (response.status === 403) { if (errorEl) { errorEl.textContent = 'Incorrect owner key.'; errorEl.classList.remove('hidden'); } if (pinInput) { pinInput.value = ''; pinInput.focus(); } return; } if (!response.ok) throw new Error('HTTP ' + response.status); const data = await response.json(); const result = data.result; if (!result?.owner_analysis) { if (errorEl) { errorEl.textContent = 'Owner analysis not available. Ensure the active endpoint supports owner mode.'; errorEl.classList.remove('hidden'); } return; } const form = document.getElementById('owner-pin-form'); if (form) form.classList.add('hidden'); renderOwnerAnalysis(result.owner_analysis); } catch (err) { if (errorEl) { errorEl.textContent = 'Error contacting the evaluator. Please try again.'; errorEl.classList.remove('hidden'); } } finally { if (unlockBtn) { unlockBtn.disabled = false; unlockBtn.textContent = 'Unlock'; } } } function renderOwnerAnalysis(owner) { const el = document.getElementById('owner-analysis-output'); if (!el || !owner) return; const tier = owner.priority_tier; const tierConfig = { A: { bg: '#f0fdf4', border: '#16a34a', text: '#15803d', label: 'Priority A - Apply Now' }, B: { bg: '#fefce8', border: '#ca8a04', text: '#854d0e', label: 'Priority B - Apply Selectively' }, C: { bg: '#fef2f2', border: '#dc2626', text: '#991b1b', label: 'Priority C - Network First' } }; const tc = tierConfig[tier] || tierConfig['C']; const kw = Array.isArray(owner.ats_keywords) ? owner.ats_keywords : []; const keywordHtml = kw.length ? `
    ${kw.map(k => `${escapeHtml(String(k))}`).join('')}
    ` : ''; const listHtml = (items, bulletColor) => { const arr = Array.isArray(items) ? items : []; if (!arr.length) return ''; return ``; }; const raw = `

    Owner Analysis

    ${escapeHtml(tc.label)}
    ${owner.positioning_statement ? `

    Positioning

    ${escapeHtml(String(owner.positioning_statement))}

    ` : ''} ${keywordHtml ? `

    ATS Keywords

    ${keywordHtml}
    ` : ''} ${Array.isArray(owner.red_flags) && owner.red_flags.length ? `

    Red Flags

    ${listHtml(owner.red_flags, 'text-red-500')}
    ` : ''} ${Array.isArray(owner.resume_hints) && owner.resume_hints.length ? `

    Resume Hints

    ${listHtml(owner.resume_hints, 'text-blue-900')}
    ` : ''}
    `; el.innerHTML = window.DOMPurify ? DOMPurify.sanitize(raw) : raw; el.classList.remove('hidden'); setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'nearest' }), 80); } function getScoreStyles(score) { if (score >= 90) return { label: 'Strong Alignment', bg: '#ecfdf5', text: '#064e3b', border: '#059669' }; if (score >= 80) return { label: 'Good Alignment', bg: '#eff6ff', text: '#1e3a8a', border: '#3b82f6' }; if (score >= 70) return { label: 'Moderate Alignment', bg: '#fffbeb', text: '#92400e', border: '#f59e0b' }; if (score >= 60) return { label: 'Limited Alignment', bg: '#fff7ed', text: '#9a3412', border: '#f97316' }; return { label: 'Low Alignment', bg: '#fef2f2', text: '#991b1b', border: '#ef4444' }; } const EVALUATOR_REPORT_TITLE = 'JD Alignment Report for Rajiv Weeraratne'; const EVALUATOR_REPORT_FOOTER = 'Rajiv Weeraratne | [email protected] | www.rajivweeraratne.com'; const EVALUATOR_FALLBACK_FILENAME = 'Rajiv_Weeraratne_JD_Alignment_Report.pdf'; function sanitizeReportFilenameComponent(value, maxLength) { if (typeof value !== 'string') return ''; return value .trim() .replace(/\s+/g, '_') .replace(/[<>:"/\\|?*]+/g, '') .replace(/[^\w.-]+/g, '_') .replace(/_+/g, '_') .replace(/^_+|_+$/g, '') .slice(0, maxLength) .replace(/^_+|_+$/g, ''); } function buildEvaluatorReportFilename(result) { const context = result && typeof result.role_context === 'object' && result.role_context ? result.role_context : {}; const company = sanitizeReportFilenameComponent(context.company, 35); const roleTitle = sanitizeReportFilenameComponent(context.role_title, 60); if (!company || !roleTitle) return EVALUATOR_FALLBACK_FILENAME; return `Rajiv_Weeraratne_${company}_${roleTitle}_JD_Alignment.pdf`.replace(/_+/g, '_'); } function printWithTemporaryTitle(targetWindow, titleText, afterPrintTriggered) { const targetDocument = targetWindow && targetWindow.document; if (!targetDocument) return; const originalTitle = targetDocument.title; targetDocument.title = titleText; targetWindow.print(); setTimeout(() => { targetDocument.title = originalTitle; if (typeof afterPrintTriggered === 'function') afterPrintTriggered(); }, 500); } function buildEvaluatorResultText(result) { if (!result || typeof result !== 'object') return ''; const score = Number.isFinite(Number(result.score)) ? Number(result.score) : 0; const styles = getScoreStyles(score); const context = getEvaluatorRoleContext(result); const dateText = new Date().toLocaleString(); const lines = [ `# ${EVALUATOR_REPORT_TITLE}`, '', `Role Evaluated: ${context.role_title}`, `Company: ${context.company}`, `Location: ${context.location}`, `Source: ${context.source_type}`, `Evaluation Date: ${dateText}`, '', '## Key Requirements from the JD' ]; appendMarkdownList(lines, context.key_jd_signals, 'No key requirements provided by the evaluator.'); lines.push( '', '## Summary', `Alignment: ${score}% - ${styles.label}`, '', result.summary || 'No summary provided.', '', '## Strengths' ); appendMarkdownList(lines, result.strengths, 'No strengths provided by the evaluator.'); lines.push('', '## Gaps / Risks'); if (Array.isArray(result.gaps) && result.gaps.length) { result.gaps.forEach(item => lines.push(`- ${item}`)); } else { lines.push('No material gaps identified by the evaluator.'); } lines.push('', '## Interview Focus Areas'); appendRoadmapMarkdown(lines, result.interview_roadmap); if (result.score_components && typeof result.score_components === 'object') { const componentLabels = { role_function_alignment: 'Role Function Alignment', seniority_scope_alignment: 'Seniority & Scope', technical_finance_alignment: 'Technical Finance', industry_domain_alignment: 'Industry & Domain', systems_tools_alignment: 'Systems & Tools', credential_regulatory_alignment: 'Credentials & Regulatory', location_work_model_alignment: 'Location & Work Model', marketability_alignment: 'Marketability' }; lines.push('', '## Score Breakdown'); Object.entries(result.score_components).forEach(([key, comp]) => { const label = componentLabels[key] || key.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()); const compScore = Number.isFinite(Number(comp.score)) ? Number(comp.score) : 0; const compMax = Number.isFinite(Number(comp.max_score)) ? Number(comp.max_score) : 0; lines.push(`### ${label}: ${compScore} / ${compMax}`); if (comp.rationale) lines.push(comp.rationale); }); } if (Array.isArray(result.requirement_matches) && result.requirement_matches.length > 0) { lines.push('', '## Requirement Detail'); result.requirement_matches.forEach(match => { const evidence = match.evidence_strength || ''; const risk = match.risk_level || ''; lines.push(`- ${match.jd_requirement || ''} | Evidence: ${evidence} | Risk: ${risk}`); }); } lines.push('', EVALUATOR_REPORT_FOOTER); return lines.join('\n'); } function getEvaluatorRoleContext(result) { const context = result && typeof result.role_context === 'object' && result.role_context ? result.role_context : {}; const clean = (value, fallback) => typeof value === 'string' && value.trim() ? value.trim() : fallback; return { role_title: clean(context.role_title, 'Role not specified'), company: clean(context.company, 'Company not specified'), location: clean(context.location, 'Location not specified'), source_type: clean(context.source_type, currentAiMode === 'url' ? 'Job URL' : 'Pasted job description'), key_jd_signals: Array.isArray(context.key_jd_signals) ? context.key_jd_signals.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim()).slice(0, 6) : [] }; } function appendMarkdownList(lines, items, emptyText) { if (Array.isArray(items) && items.length) { items.forEach(item => lines.push(`- ${item}`)); } else { lines.push(emptyText); } } function stripRoadmapLabel(value, labelPattern) { if (typeof value !== 'string') return ''; return value.replace(labelPattern, '').trim(); } function parseRoadmapItem(item) { if (typeof item === 'string') { const text = item.trim(); if (!text) return null; const splitIndex = text.indexOf('Answer:'); if (splitIndex !== -1) { return { question: stripRoadmapLabel(text.substring(0, splitIndex), /^Question:\s*/i), answer: stripRoadmapLabel(text.substring(splitIndex + 'Answer:'.length), /^(?:Suggested\s+Answer|Answer):\s*/i), raw: text, isObject: false }; } return { question: stripRoadmapLabel(text, /^Question:\s*/i), answer: '', isObject: false }; } if (!item || typeof item !== 'object' || Array.isArray(item)) return null; const answerKeys = ['suggested_answer', 'answer', 'suggestedAnswer', 'suggested_response', 'response']; const question = stripRoadmapLabel(item.question, /^Question:\s*/i); const answerKey = answerKeys.find(key => typeof item[key] === 'string' && item[key].trim()); const answer = answerKey ? stripRoadmapLabel(item[answerKey], /^(?:Suggested\s+Answer|Answer):\s*/i) : ''; if (!question || !answer) return null; return { question, answer, isObject: true }; } function appendRoadmapMarkdown(lines, items) { const parsedItems = Array.isArray(items) ? items.map(parseRoadmapItem).filter(Boolean) : []; if (!parsedItems.length) { lines.push('No interview focus areas provided by the evaluator.'); return; } parsedItems.forEach((parsed, index) => { lines.push('', `### Question ${index + 1}`, parsed.question, '', '**Suggested answer:**', parsed.answer || 'Suggested answer not provided.'); }); } function buildCondensedEmailWithinLimit(result, encodedSubject, limit) { if (!result || typeof result !== 'object') return null; const score = Number.isFinite(Number(result.score)) ? Number(result.score) : 0; const styles = getScoreStyles(score); const context = getEvaluatorRoleContext(result); const dateText = new Date().toLocaleString(); const footer = `\n\n(Full report available via Copy Report or Print / Save PDF.)\n\n${EVALUATOR_REPORT_FOOTER}`; const header = [ `# ${EVALUATOR_REPORT_TITLE}`, '', `Role: ${context.role_title} at ${context.company}`, `Location: ${context.location}`, `Evaluation Date: ${dateText}`, '', '## Overall Score', `${score}% \u2014 ${styles.label}` ].join('\n'); const rawSummary = result.summary || ''; const allStrengths = Array.isArray(result.strengths) ? result.strengths : []; const allGaps = Array.isArray(result.gaps) ? result.gaps : []; const tryBuild = (summary, strengthCount, gapCount) => { const lines = [header, '', '## Summary', summary || 'No summary provided.', '', '## Top Strengths']; const strengths = allStrengths.slice(0, strengthCount); if (strengths.length) strengths.forEach(s => lines.push(`- ${s}`)); else lines.push('No strengths provided.'); lines.push('', '## Key Gaps / Risks'); const gaps = allGaps.slice(0, gapCount); if (gaps.length) gaps.forEach(g => lines.push(`- ${g}`)); else lines.push('No material gaps identified.'); const text = lines.join('\n') + footer; const url = `mailto:?subject=${encodedSubject}&body=${encodeURIComponent(text)}`; return url.length <= limit ? url : null; }; const SUMMARY_MAX = 400; const trimmedSummary = rawSummary.length > SUMMARY_MAX ? rawSummary.slice(0, SUMMARY_MAX).replace(/\s+\S*$/, '') + '\u2026' : rawSummary; return tryBuild(rawSummary, 3, 3) || tryBuild(trimmedSummary, 3, 3) || tryBuild(trimmedSummary, 2, 2) || tryBuild(trimmedSummary, 1, 1) || tryBuild('', 1, 1) || null; } function evaluatorReportNeedsPaste() { const text = buildEvaluatorResultText(currentAiResult); if (!text) return false; const context = getEvaluatorRoleContext(currentAiResult); const subject = encodeURIComponent(`JD Alignment Report \u2014 ${context.role_title} at ${context.company}`); const body = encodeURIComponent(text); return (`mailto:?subject=${subject}&body=${body}`).length > EVALUATOR_MAILTO_LIMIT; } async function emailEvaluatorResults() { const status = document.getElementById('copyResultStatus'); if (!currentAiResult) { if (status) status.textContent = 'No results to email.'; return; } const context = getEvaluatorRoleContext(currentAiResult); const subject = encodeURIComponent(`JD Alignment Report \u2014 ${context.role_title} at ${context.company}`); const fullText = buildEvaluatorResultText(currentAiResult); const fullMailto = `mailto:?subject=${subject}&body=${encodeURIComponent(fullText)}`; if (fullMailto.length <= EVALUATOR_MAILTO_LIMIT) { window.location.href = fullMailto; if (status) status.textContent = 'Opening email client\u2026'; } } function emailEvaluatorSummary() { const status = document.getElementById('copyResultStatus'); if (!currentAiResult) { if (status) status.textContent = 'No results to email.'; return; } const context = getEvaluatorRoleContext(currentAiResult); const subject = encodeURIComponent(`JD Alignment Report \u2014 ${context.role_title} at ${context.company}`); const condensedMailto = buildCondensedEmailWithinLimit(currentAiResult, subject, EVALUATOR_MAILTO_LIMIT); if (condensedMailto) { window.location.href = condensedMailto; if (status) status.textContent = 'Opening email with condensed summary\u2026'; } else { if (status) status.textContent = 'Could not build summary email. Try Copy Report instead.'; } } async function emailEvaluatorFullPaste() { const status = document.getElementById('copyResultStatus'); if (!currentAiResult) { if (status) status.textContent = 'No results to email.'; return; } const context = getEvaluatorRoleContext(currentAiResult); const subject = encodeURIComponent(`JD Alignment Report \u2014 ${context.role_title} at ${context.company}`); const fullText = buildEvaluatorResultText(currentAiResult); try { if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(fullText); } else { const ta = document.createElement('textarea'); ta.value = fullText; ta.setAttribute('readonly', ''); ta.style.position = 'fixed'; ta.style.left = '-9999px'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove(); } if (status) status.textContent = 'Full report copied \u2014 paste it into the email that just opened.'; } catch (_) { if (status) status.textContent = 'Email opened \u2014 copy the report text manually and paste it in.'; } window.location.href = `mailto:?subject=${subject}`; } async function copyEvaluatorResults() { const status = document.getElementById('copyResultStatus'); const text = buildEvaluatorResultText(currentAiResult); if (!text) { if (status) status.textContent = 'No results to copy.'; return; } try { if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); } else { const textarea = document.createElement('textarea'); textarea.value = text; textarea.setAttribute('readonly', ''); textarea.style.position = 'fixed'; textarea.style.left = '-9999px'; document.body.appendChild(textarea); textarea.select(); const copied = document.execCommand('copy'); textarea.remove(); if (!copied) throw new Error('copy_unavailable'); } if (status) status.textContent = 'Results copied.'; } catch (error) { if (status) status.textContent = 'Copy unavailable. Select the results and copy manually.'; } } function printEvaluatorResults() { const filename = buildEvaluatorReportFilename(currentAiResult); const printTitle = filename.replace(/\.pdf$/i, ''); const reportHtml = buildEvaluatorPrintHtml(currentAiResult); if (!reportHtml) return; const printWindow = window.open('', '_blank', 'width=900,height=700'); if (!printWindow) { printWithTemporaryTitle(window, printTitle); return; } printWindow.document.open(); printWindow.document.write(reportHtml); printWindow.document.close(); printWindow.focus(); setTimeout(() => { printWithTemporaryTitle(printWindow, printTitle, () => printWindow.close()); }, 250); } function buildEvaluatorPrintHtml(result) { if (!result || typeof result !== 'object') return ''; const score = Number.isFinite(Number(result.score)) ? Number(result.score) : 0; const styles = getScoreStyles(score); const context = getEvaluatorRoleContext(result); const dateText = new Date().toLocaleString(); const listHtml = (items, emptyText) => Array.isArray(items) && items.length ? `` : `

    ${escapeHtml(emptyText)}

    `; const roadmapItems = Array.isArray(result.interview_roadmap) ? result.interview_roadmap.map(parseRoadmapItem).filter(Boolean) : []; const roadmapHtml = roadmapItems.length ? roadmapItems.map((parsed, index) => { return `

    Question ${index + 1}

    ${escapeHtml(parsed.question)}

    Suggested Answer:

    ${escapeHtml(parsed.answer || 'Suggested answer not provided.')}

    `; }).join('') : '

    No interview focus areas provided by the evaluator.

    '; const componentLabels = { role_function_alignment: 'Role Function Alignment', seniority_scope_alignment: 'Seniority & Scope', technical_finance_alignment: 'Technical Finance', industry_domain_alignment: 'Industry & Domain', systems_tools_alignment: 'Systems & Tools', credential_regulatory_alignment: 'Credentials & Regulatory', location_work_model_alignment: 'Location & Work Model', marketability_alignment: 'Marketability' }; const scoreBreakdownHtml = (result.score_components && typeof result.score_components === 'object') ? `

    Score Breakdown

    ${ Object.entries(result.score_components).map(([key, comp]) => { const lbl = componentLabels[key] || key.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()); const cs = Number.isFinite(Number(comp.score)) ? Number(comp.score) : 0; const cm = Number.isFinite(Number(comp.max_score)) ? Number(comp.max_score) : 0; const pct = cm > 0 ? Math.round((cs / cm) * 100) : 0; const barColor = pct >= 75 ? '#1e3a8a' : pct >= 50 ? '#3b82f6' : pct >= 25 ? '#94a3b8' : '#e2e8f0'; return ``; }).join('') }
    ${escapeHtml(lbl)}${escapeHtml(String(cs))} / ${escapeHtml(String(cm))}

    ${escapeHtml(comp.rationale || '')}

    ` : ''; const reqMatchHtml = (Array.isArray(result.requirement_matches) && result.requirement_matches.length > 0) ? `

    Requirement Detail

    ${ result.requirement_matches.map(match => { const evidenceLabels = { direct: 'Direct', adjacent: 'Adjacent', transferable: 'Transferable', unsupported: 'Unsupported', contradicted: 'Contradicted' }; const evidenceBg = { direct: '#dcfce7', adjacent: '#dbeafe', transferable: '#fef9c3', unsupported: '#fee2e2', contradicted: '#fecaca' }; const evidenceText = { direct: '#166534', adjacent: '#1e40af', transferable: '#854d0e', unsupported: '#991b1b', contradicted: '#7f1d1d' }; const riskColors = { none: '#166534', low: '#854d0e', medium: '#c2410c', high: '#991b1b', disqualifying: '#7f1d1d' }; const riskLabels = { none: 'None', low: 'Low', medium: 'Medium', high: 'High', disqualifying: 'Disqualifying' }; const ev = match.evidence_strength || 'unknown'; const rk = match.risk_level || ''; const evLabel = evidenceLabels[ev] || escapeHtml(String(ev)); const evBg = evidenceBg[ev] || '#f1f5f9'; const evText = evidenceText[ev] || '#475569'; const rkLabel = riskLabels[rk] || escapeHtml(String(rk)); const rkColor = riskColors[rk] || '#475569'; return ``; }).join('') }
    RequirementEvidenceRisk
    ${escapeHtml(match.jd_requirement || '')}${evLabel}${rkLabel}
    ` : ''; return ` ${escapeHtml(buildEvaluatorReportFilename(result).replace(/\.pdf$/i, ''))}

    ${EVALUATOR_REPORT_TITLE}

    Role Evaluated: ${escapeHtml(context.role_title)}

    Company: ${escapeHtml(context.company)}

    Location: ${escapeHtml(context.location)}

    Source: ${escapeHtml(context.source_type)}

    Evaluation Date: ${escapeHtml(dateText)}

    Key Requirements from the JD

    ${listHtml(context.key_jd_signals, 'No key requirements provided by the evaluator.')}

    Summary

    ${escapeHtml(result.summary || 'No summary provided.')}

    ${score}% - ${escapeHtml(styles.label)}

    Strengths

    ${listHtml(result.strengths, 'No strengths provided by the evaluator.')}

    Gaps / Risks

    ${Array.isArray(result.gaps) && result.gaps.length ? listHtml(result.gaps, '') : '

    No material gaps identified by the evaluator.

    '}

    Interview Focus Areas

    ${roadmapHtml} ${scoreBreakdownHtml} ${reqMatchHtml}
    `; } function buildResultActions() { const needsPaste = evaluatorReportNeedsPaste(); const emailButtons = needsPaste ? `` : ``; return `

    Report

    ${emailButtons}
    `; } async function runAlignment() { let payload = {}; if (currentAiMode === 'text') { const jd = document.getElementById('jdInput').value.trim(); if (!jd) return; payload = { jd: jd }; } else { const url = document.getElementById('jdUrlInput').value.trim(); if (!url) return; payload = { url: url }; } currentJdPayload = payload; const btn = document.getElementById('aiSubmitBtn'); const spinner = document.getElementById('spinner'); const btnText = document.getElementById('btnText'); const output = document.getElementById('aiOutputArea'); const inputArea = document.getElementById('aiInputArea'); btn.disabled = true; spinner.classList.remove('hidden'); btnText.innerText = "Analyzing Alignment..."; const existingProgress = document.getElementById('ai-progress-area'); if (existingProgress) existingProgress.remove(); const progressHtml = `

    `; document.getElementById('aiSubmitBtn').insertAdjacentHTML('beforebegin', progressHtml); setTimeout(() => { const modalBody = document.querySelector('#aiModal .modal-body'); if (modalBody) modalBody.scrollTop = modalBody.scrollHeight; }, 50); const statusMessages = [ "Reading the job description...", "Comparing requirements against your career profile...", "Evaluating gaps and strengths...", "Building your interview roadmap...", "Almost done..." ]; let msgIndex = 0; let progress = 0; const statusEl = document.getElementById('ai-status-msg'); const progressBar = document.getElementById('ai-progress-bar'); if (statusEl) statusEl.textContent = statusMessages[0]; const progressInterval = setInterval(() => { progress = Math.min(progress + (100 / 90), 92); msgIndex = Math.min(Math.floor(progress / 20), statusMessages.length - 1); if (progressBar) progressBar.style.width = progress + '%'; if (statusEl) statusEl.textContent = statusMessages[msgIndex]; }, 1000); window._aiProgressInterval = progressInterval; if (aiAbortController) aiAbortController.abort(); aiAbortController = new AbortController(); let evaluatorTimedOut = false; const timeoutId = setTimeout(() => { evaluatorTimedOut = true; if (aiAbortController) aiAbortController.abort(); }, EVALUATOR_REQUEST_TIMEOUT_MS); const makeRequest = async (delay = 1000, retry = 0) => { try { // Routes through main domain to pass through Cloudflare WAF; bold-tree-6b48 proxies /api/evaluate to rajiv-jd-evaluator-v2-1 (v2.1 pipeline) const response = await fetch(EVAL_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: aiAbortController.signal }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); if (!data.result) throw new Error('Malformed Response from Proxy'); return data.result; } catch (error) { if (retry < 2 && error.name !== 'AbortError') { await new Promise(r => setTimeout(r, delay)); return makeRequest(delay * 2, retry + 1); } throw error; } }; try { const analysis = await makeRequest(); clearTimeout(timeoutId); if (!analysis) throw new Error("No analysis generated"); inputArea.classList.add('hidden'); output.classList.remove('hidden'); if (typeof analysis === 'string') { currentAiResult = null; const safeHtml = window.DOMPurify ? DOMPurify.sanitize(analysis) : escapeHtml(analysis); output.innerHTML = '
    ' + safeHtml + '
    ' + buildResultActions(); } else if (typeof analysis === 'object') { if (analysis.is_valid === false) { const invalidJdError = new Error(analysis.error_message || "Invalid job description."); invalidJdError.isInvalidJd = true; throw invalidJdError; } currentAiResult = analysis; const score = Number.isFinite(Number(analysis.score)) ? Number(analysis.score) : 0; const styles = getScoreStyles(score); const buildList = (items) => Array.isArray(items) && items.length > 0 ? `` : '

    No data points identified.

    '; const buildRoadmap = (items) => { const parsedItems = Array.isArray(items) ? items.map(parseRoadmapItem).filter(Boolean) : []; if (parsedItems.length === 0) return '

    No data points identified.

    '; return ``; }; const htmlContent = ` ${score}% ${styles.label}

    Summary

    ${escapeHtml(analysis.summary)}

    Strengths

    ${buildList(analysis.strengths)}

    Gaps

    ${buildList(analysis.gaps)}

    Interview Focus Areas

    ${buildRoadmap(analysis.interview_roadmap)} `; const safeHtml = window.DOMPurify ? DOMPurify.sanitize(htmlContent) : htmlContent; output.innerHTML = '
    ' + safeHtml + '
    ' + buildScoreBreakdownSection() + buildResultActions() + buildOwnerAnalysisSection(); } setTimeout(() => { const modalBody = document.querySelector('#aiModal .modal-body'); if (modalBody) modalBody.scrollTop = 0; const contentContainer = document.getElementById('aiOutputContent'); if (contentContainer) contentContainer.focus({ preventScroll: true }); injectCtaAfterResult(); }, 50); } catch (err) { clearTimeout(timeoutId); if (err.name === 'AbortError' && !evaluatorTimedOut) return; if (!err.isInvalidJd) console.error('Final Analysis Catch:', err); let errorMsg = err.message; if (err.name === 'AbortError') { errorMsg = "The request timed out. The job description took too long to process. Please try a shorter text segment."; } else if (!errorMsg || errorMsg === 'Failed to fetch') { errorMsg = "Alignment check temporarily unavailable due to a network or server error. Please try again later."; } const safeErrorMsg = window.DOMPurify ? DOMPurify.sanitize(errorMsg, { ALLOWED_TAGS: [], ALLOWED_ATTR: [] }) : escapeHtml(errorMsg); inputArea.classList.add('hidden'); output.classList.remove('hidden'); output.innerHTML = `

    Analysis Failed

    ${safeErrorMsg}

    `; setTimeout(() => { const modalBody = document.querySelector('#aiModal .modal-body'); if (modalBody) modalBody.scrollTop = 0; const contentContainer = document.getElementById('aiOutputContent'); if (contentContainer) contentContainer.focus({ preventScroll: true }); }, 50); } finally { const btn = document.getElementById('aiSubmitBtn'); const spinner = document.getElementById('spinner'); const btnText = document.getElementById('btnText'); if (btn) btn.disabled = false; if (spinner) spinner.classList.add('hidden'); if (btnText) btnText.innerText = "Run Alignment"; if (window._aiProgressInterval) { clearInterval(window._aiProgressInterval); window._aiProgressInterval = null; } const progressArea = document.getElementById('ai-progress-area'); if (progressArea) progressArea.remove(); } } function showDrillDown(type) { lastActiveElement = document.activeElement; const body = document.getElementById('modalBody'); const header = document.getElementById('drillHeader'); const contentPanel = document.getElementById('drillDownModal').querySelector('.modal-content'); let content = ""; const colorMap = { 'funding': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'grants': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'footprint': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'portfolio': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'finance_cap': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'procurement_cap': { bg: 'bg-emerald-700', border: 'border-emerald-700', hover: 'hover:bg-emerald-600' }, 'systems_cap': { bg: 'bg-amber-600', border: 'border-amber-600', hover: 'hover:bg-amber-500' }, 'private_close': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'private_systems': { bg: 'bg-amber-600', border: 'border-amber-600', hover: 'hover:bg-amber-500' }, 'private_audit': { bg: 'bg-emerald-700', border: 'border-emerald-700', hover: 'hover:bg-emerald-600' }, 'case_gps': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'case_saep': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'case_erp': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'logic_federal': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'logic_domestic': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, 'case_acss': { bg: 'bg-blue-900', border: 'border-blue-900', hover: 'hover:bg-blue-800' }, }; const theme = colorMap[type] || colorMap['portfolio']; header.className = `${theme.bg} p-6 text-white font-bold text-xl uppercase tracking-widest`; contentPanel.className = `modal-content shadow-xl border-t-8 ${theme.border}`; const closeBtn = document.getElementById('modalCloseBtn'); if(closeBtn) closeBtn.className = `${theme.bg} ${theme.hover} text-white px-8 py-2 rounded-lg text-xs font-bold uppercase tracking-widest transition-colors shadow-md focus-ring`; if (type === 'portfolio') { header.innerText = "Portfolio Composition"; content = `
    Governance & PFM
    $309M
    Afghanistan Civil Service Support (ACSS)$219M
    Core Economic Governance Institutions II (CORE II)$90M
    Strategic Controllership
    $238M
    Global Controllership (GPS)$238M
    Energy Reform
    $95M
    Southern Africa Energy Program (SAEP)$75M
    Caribbean Clean Energy Program (CARCEP)$20M
    Innovation & ICT
    $2M
    IT Master Plan Implementation (ITMP-IP)$2M
    `; } else if(type === 'funding') { header.innerText = "Funding Details"; content = '
    Performance-Based Expansion: ACSS$19.5M
    Just Energy Transition (JET) Funding: SAEP$5.0M
    '; } else if(type === 'grants') { header.innerText = "Grants & Sub-awards Managed"; content = `
    Total Directed (CARCEP + SAEP)
    $40.5M
    CARCEP Grants (Innovation Fund)$1.5M
    CARCEP Sub-awards$7.0M
    SAEP Grants (Catalyst Fund)$3.5M
    SAEP Sub-awards$28.5M
    *Note: $2.7M of the $3.5M authorized SAEP Catalyst Fund was fully deployed/executed via Fluxx based on achieved milestones.
    `; } else if(type === 'footprint') { header.innerText = "Global Footprint"; content = `
    Total Operating Footprint
    21 Countries
    Central Asia, Middle East & East Africa3 Countries

    Afghanistan, Jordan, South Sudan.

    Caribbean Basin (OECS)8 Countries

    Antigua, Bahamas, Barbados, Dominica, Grenada, Jamaica, St. Kitts, St. Lucia.

    Southern Africa (SADC)10 Countries

    Angola, Botswana, Eswatini, Lesotho, Madagascar, Malawi, Mozambique, Namibia, South Africa, Zambia.

    `; } else if(type === 'finance_cap') { header.innerText = "Strategic Finance Execution"; content = `
    Global GPS Portfolios (2024 - 2025)
    Southern Africa Energy Program (2017 - 2024)
    Afghanistan Civil Service Support (2010 - 2012)
    `; } else if(type === 'procurement_cap') { header.innerText = "Grants, Contracts & Compliance Execution"; content = `
    Global GPS Portfolios (2024 - 2025)
    Southern Africa Energy Program (2017 - 2024)
    Caribbean Clean Energy Program (2015 - 2017)
    `; } else if(type === 'systems_cap') { header.innerText = "Digital Transformation Execution"; content = `
    Global GPS Portfolios (2024 - 2025)
    Southern Africa Energy Program (2017 - 2024)
    Caribbean Clean Energy Program (2015 - 2017)
    CORE II South Sudan (2012 - 2015)
    `; } else if(type === 'private_close') { header.innerText = "Private-Sector Applicability: Multi-Entity Controllership"; content = `
    What Was Proven

    Ran a $75M multi-currency finance operation across 8 regional offices, covering AP/AR, procurement, invoicing, payroll, treasury, statutory compliance, month-end close, and executive reporting.

    Why It Matters

    At program scale, finance breaks first when entities, currencies, or reporting standards diverge. Consolidated reporting only works if the underlying ledger discipline is enforced consistently, not patched at month-end.

    Where It Applies

    Relevant to growth companies running multi-entity operations where finance needs reliable consolidated reporting and cash visibility before complexity outruns the control model. Prior results include a $75M multi-currency P&L closed monthly with 99.8% forecasting accuracy across 8 regional offices.

    `; } else if(type === 'private_systems') { header.innerText = "Private-Sector Applicability: ERP-Led Finance Transformation"; content = `
    What Was Proven

    Implemented and stabilized finance workflows across Sage Intacct, Deltek Costpoint, FreeBalance IFMIS, Coupa, Fluxx, and PowerBI, including process redesign, UAT, cutover support, reporting improvements, and post-launch stabilization.

    Why It Matters

    ERP changes fail when finance has to choose between fixing the system and running the business. The discipline is doing both, with controls intact, while the underlying infrastructure changes underneath.

    Where It Applies

    Relevant to finance teams replacing manual workflows, modernizing ERP-enabled operations, improving reporting reliability, and reducing payment friction. Prior results include a 10-day payment cycle reduction, 25% invoice and expense accuracy improvement, and 30%+ reduction in manual reporting workload.

    `; } else if(type === 'private_audit') { header.innerText = "Private-Sector Applicability: Audit-Ready Operating Discipline"; content = `
    What Was Proven

    Built and maintained control environments aligned to FAR, AIDAR, CAS, and DCAA audit readiness. Supported major financial closeouts, including the $219M ACSS closeout serving 700+ personnel.

    Why It Matters

    Audit defense begins at the point of transaction entry, not the point of review. Files, approvals, and reconciliations either hold up under scrutiny or they do not. Reconstruction after the fact is the most expensive way to prepare for an audit.

    Where It Applies

    Relevant to regulated or audit-heavy finance environments where controls have to be defensible to skeptical reviewers. Prior results include vendor settlement, payroll closeout, multi-currency reconciliation, asset disposition, and final reporting with no known unresolved liabilities at closeout.

    `; } else if(type === 'logic_federal') { header.innerText = "Federal Operations & Controllership Framework"; content = `

    This control model was built over 20 years of directing $644M in federal and donor-funded portfolios across 21 countries. It was designed to solve recurring execution problems: decentralized procurement without adequate controls, audit exposure that accumulated quietly, market-entry friction, tax deadlocks that locked up cash, and reporting inconsistency across jurisdictions. It converts Federal Acquisition Regulation (FAR), Agency for International Development Acquisition Regulation (AIDAR), Cost Accounting Standards (CAS), Standard Form 1408 (SF-1408), donor rules, and headquarters reporting requirements into operating controls that finance, procurement, grants, payroll, treasury, and close functions can actually use. The objective is to reduce avoidable variance, stay audit-ready, preserve liquidity, and keep execution aligned to contract requirements.

    This is not a task manual. It is an operating discipline for decision-making with fixed evaluation criteria, built to produce control standards that field teams can follow and auditors can verify. It was tested in volatile markets, with decentralized teams, fragile infrastructure, and complex multi-entity structures. It is portable. The same control model can apply to a new domestic agency, a new geography, or a new portfolio without rebuilding from scratch.

    Financial Forecasting and Budget Execution

    A regional energy program in Southern Africa was the clearest proof of concept. It ran $74.8M against a $74.95M ceiling, achieving 99.8% forecasting accuracy, fixed-fee capture, and minimal unspent variance over a multi-year period. That result required every element of this section working simultaneously.

    Audit Defense and Regulatory Compliance

    Compliance is an operating condition, not a function activated when an auditor arrives. The standard is not whether an issue can be explained after the fact. It is whether the file, transaction, and reporting chain hold up under review without improvisation or reconstruction.

    Global Operations and Execution Standards

    The operating environments behind this model include Jordan, Afghanistan, South Sudan, Southern Africa, and the Caribbean. Infrastructure was weak, field conditions were unstable, and the cost of control failure was real. In each environment, the objective was to keep finance, procurement, and reporting consistent regardless of what the local conditions looked like.

    Procurement and Source-to-Pay Governance

    Procurement is a financial control function. In distributed portfolios, weak procurement discipline leads directly to budget distortion, audit problems, and delayed billing. The Source-to-Pay (S2P) process must be structured, visible, and enforceable at every stage of the cycle.

    Strategic Pricing and Capture Logic

    Pricing is part of controllership. What gets priced in at proposal time determines what gets recovered during execution. Weak pricing creates cost recovery problems, margin erosion, and delivery strain that the finance function then spends years managing.

    Core Operating Principle

    The premise underlying this control approach is that the finance function is most valuable before problems occur, not after.

    In high-risk portfolios, the real test of financial leadership is whether it prevents problems from disrupting delivery in the first place. Strong controls, disciplined forecasting, audit-ready records, procurement rigor, and early escalation create the conditions for stable execution.

    When that foundation holds, program leadership can stay focused on technical delivery instead of avoidable operational breakdowns. Contracting officers are not forced into corrective intervention. Audit issues do not accumulate quietly. Delivery teams are not pulled off mission to solve preventable finance, procurement, or compliance failures.

    This control model was built to produce that kind of operating environment and to keep it in place as portfolios grow and conditions shift.

    `; } else if(type === 'logic_domestic') { header.innerText = "Domestic GovCon Controllership Framework"; content = `

    Most domestic Government Contracting (GovCon) finance functions were not designed for the portfolio they are currently running. They were built for a smaller, simpler organization, and the control model never kept pace. The result is a finance function permanently in triage mode, managing individual problems as they surface rather than controlling the operating system that produces them.

    Indirect rates drift. Billing falls behind technical delivery. Procurement runs ahead of financial visibility. Incurred Cost Submission (ICS) preparation becomes a year-end scramble. Subcontract oversight is inconsistent. These problems get managed individually, but none of them gets solved, because solving them requires stepping back from the individual failure and redesigning the finance process that keeps producing it. That is what this document addresses.

    From International Portfolios to Domestic GovCon

    Twenty years building and maintaining finance controls across $644M in federal and donor-funded portfolios in 21 countries produced a specific kind of pattern recognition. That includes active operations in Afghanistan, South Sudan, Southern Africa, and the Caribbean. You see what breaks first under pressure, why it breaks, and what structural change prevents it from recurring. The operating environments were more demanding than most domestic GovCon settings. The failure patterns were the same.

    Budget distortion, audit exposure, procurement drift, billing delays, and indirect rate pressure are not problems unique to fragile markets. They are the same problems that surface in a $60M domestic GovCon firm that has outgrown its finance architecture. The difference is that internationally, those failures carry immediate contractual and operational consequences, which accelerates learning. What that experience produces is a set of operating standards built for environments where the cost of getting it wrong is high. Those standards apply here.

    I. Budget Execution and Forecast Discipline

    In most mid-size GovCon firms, the forecast is a backward-looking document. It explains variance that already happened. By the time a funding ceiling problem, a burn rate discrepancy, or a fee risk appears in a monthly report, the window for clean correction has often closed. Leadership manages the consequence rather than preventing it.

    A forecast that functions as a control mechanism works differently. It is built from execution signals: labor plans, procurement commitments, subcontract disbursement timing, milestone evidence, billing assumptions, and indirect cost behavior. Updated frequently enough to drive decisions rather than explain them, it requires named owners, clear tolerances by spending category, and a monthly cadence that pulls finance, operations, procurement, and technical leadership into the same conversation before problems compound.

    Work Breakdown Structure (WBS) discipline is where this starts. Every major spending category maps to a defined scope element, contract objective, and funding source. Without that mapping, cost pools become generic, variance is hard to attribute, and audit support degrades. With it, the forecast becomes a live picture of contract health rather than a static summary of what was spent.

    A regional energy program in Southern Africa produced 99.8% forecasting accuracy and fixed-fee capture over a multi-year period under significantly more demanding conditions than a domestic GovCon environment. The discipline that produced those results applies directly: bottom-up cost models, frequent reforecasting against actuals, active commitment tracking, and early intervention thresholds that surface problems before they become report items.

    II. DCAA Readiness and Compliance Architecture

    Defense Contract Audit Agency (DCAA) audit readiness is not a project. It is an operating condition. The finance functions that struggle most with DCAA reviews are not the ones that made bad decisions. They are the ones that made reasonable decisions without building the documentation architecture to defend them. Labor support is incomplete. Cost transfers lack rationale. Indirect allocations are defensible in principle but undocumented in practice. ICS preparation requires reconstruction rather than confirmation.

    The fix starts at the front end, with different design. Allowability, allocability, and reasonableness under Federal Acquisition Regulation (FAR) Part 31 should be evaluated before cost entry or commitment, not after. Labor distribution and timekeeping controls should be treated as system-critical. Weak labor support undermines the entire compliance structure, not just the labor line. The general ledger, billing records, project reporting, and federal submissions should reconcile continuously so that ICS preparation is a standardized annual process, not a recovery effort.

    Where Cost Accounting Standards (CAS) apply, the accounting treatment in practice must match the disclosed method. Workarounds that create a gap between policy and execution are a compliance problem regardless of whether an auditor has found them yet. Building the compliance model into daily operations, rather than activating it when a review is announced, is what separates organizations that pass audits cleanly from those that spend months in remediation.

    III. Operational Scale and Control Portability

    Growth breaks finance functions that were not designed for it. A GovCon firm that doubles its contract portfolio without redesigning its finance process does not get a proportionally larger version of its existing finance function. It gets the same control environment under twice the load, and the failure points become visible quickly. Approval thresholds that worked informally at $20M become a liability at $80M. Reporting that was manageable with two contract vehicles becomes unworkable with twelve. Treasury visibility adequate for a single entity breaks down across multiple legal structures.

    The solution is a modular control model where standards are portable and contract-specific variation is managed within a common structure rather than outside it. Delegated authority, approval thresholds, procurement file standards, close procedures, and reporting templates should be designed to replicate into new contracts, new offices, or new entities without rebuilding the control environment from scratch each time.

    Operating across 21 countries with varying legal structures, banking environments, payroll architectures, and infrastructure conditions required exactly this kind of modular design. The same principle applies when a domestic GovCon firm opens a new regional office, adds a significant subcontract structure, or takes on a contract vehicle with different compliance requirements. The control model scales through standardization, not through individual effort.

    IV. Procurement, Subcontracts, and S2P Governance

    Procurement is where margin leaks in domestic GovCon. Not dramatically, and not always visibly. But consistently. Subcontract costs run ahead of financial controls. Vendor payments move without three-way verification. Sole-source decisions lack documented rationale. Partner disbursements are not reconciled to scope or funding source at the point of commitment. Each instance is manageable in isolation. Across a growing portfolio, they accumulate into audit findings, forecast distortion, and margin erosion that the finance function then spends years unwinding.

    Source-to-Pay (S2P) governance treats procurement as a financial control function, not an administrative one. Every committed dollar runs through the same control framework that governs labor, billing, and close, whether it flows through a vendor, subcontractor, consultant, or teaming partner. Requisition, approval, Purchase Order (PO) issuance, receipt, invoice review, general ledger (GL) coding, and payment form one traceable process. No payment moves without matching evidence and approved coding. The process is rigorous, but rigor is what keeps procurement defensible.

    Risk-based oversight is what makes this workable at scale. Not every vendor transaction carries the same risk profile. High-value, high-risk, or compliance-heavy categories warrant stronger file standards, more frequent review, and tighter milestone discipline. That includes subcontracts, professional services, equipment, and facilities. Applying uniform oversight regardless of risk misses the categories that matter and wastes capacity on the ones that do not.

    V. Pricing Discipline and Contract Viability

    Pricing is the first operational decision on whether a contract can be executed profitably and compliantly. It is also where the downstream consequences of a weak finance model become most visible. Not at award. Twelve months into delivery, when indirect rates have drifted from bid assumptions, subcontract costs have exceeded estimates, and the compliance burden turned out to be higher than the model anticipated.

    Cost realism has to precede competitiveness. That means building models from actual labor mix, real indirect burden, documented compliance requirements, subcontract complexity, and delivery-specific cost factors. It means adjusting the pricing approach for the contract type. Cost-plus, time-and-materials (T&M), Firm Fixed Price (FFP), and performance-based structures each shift risk differently and require different cost model discipline. And it means carrying pricing assumptions formally into execution so that what was built into the bid is visible to the team delivering the work.

    Historical performance is underused in most GovCon pricing functions. Indirect rate behavior, staffing patterns, win-loss outcomes, and delivery cost data from prior contracts are the most reliable inputs available for future models. Organizations that build a feedback loop between execution history and pricing assumptions consistently produce more defensible bids and more stable delivery. Those that price from ideal-state assumptions absorb the gap in execution.

    Pricing discipline also connects directly to scale. Organizations that price well win more work, and more work demands a control model that can absorb growth without eroding margin. When that cycle works, each contract funds the competitive position for the next. When it breaks, the finance function spends years managing the gap between what was bid and what it actually costs to deliver. Which direction the cycle runs depends largely on whether the finance function was built to operate upstream.

    Core Operating Principle

    The finance function is most valuable before problems occur, not after. In domestic GovCon, that means building a control environment that scales with the portfolio, holds under audit pressure, and gives program leadership room to focus on delivery rather than managing preventable administrative breakdowns.

    The five domains in this control model are not independent workstreams. Forecast discipline relies on procurement timing and billing accuracy. Compliance relies on labor integrity and documentation quality. Scalability requires a finance process designed to replicate. Procurement governance requires financial controls embedded before commitments move. Pricing viability requires that the organization understand the true cost of the work it is pursuing. And strong pricing, in turn, generates the contract wins that test whether the scale, the compliance architecture, and the procurement controls actually hold. Managed in isolation, these domains weaken under pressure. Managed as connected control surfaces, they reinforce each other. That is the operating standard this control model is designed to build and sustain.

    The GovCon Control Cycle
    `; } else if(type === 'case_gps') { header.innerText = "Case Study: $238M US GovCon Portfolio"; content = `
    Context

    A $238M multi-country portfolio required immediate system stabilization to drive growth. This mandate abruptly shifted to crisis management following sweeping federal policy changes and the dissolution of the USAID pipeline.

    Constraint

    Navigating complex local labor laws, disposing of physical assets, and winding down 15 international entities rapidly while managing legal and financial exposure for the firm.

    Decision & Action

    Standardized month-end close and S2P processes via Sage Intacct to establish baseline visibility. Executed strict Termination for Convenience (T4C) protocols following Stop Work orders. Pivoted $10M to $75M pricing models to domestic agencies (DOE, EPA, NNSA, Library of Congress) to protect account revenue.

    Applied Control Discipline
    Outcome

    Completed a controlled wind-down of targeted bank accounts and entities under established closure protocols. Mitigated international legal risks and successfully translated global governance experience into U.S. domestic market controls.

    Risk Control & Execution Dashboard
    Total Scale: $238M
    Entities Closed
    15
    Bank Accounts Closed
    100%
    Severance & Assets
    Secured
    Month-End Continuity
    Maintained
    Domestic Pivot
    $10M to $75M
    `; } else if(type === 'case_saep') { header.innerText = "Case Study: $75M Power Africa Program"; content = `
    Context

    USAID's flagship mechanism for Power Africa required a decentralized finance and operations infrastructure. The $75M program spanned ten SADC countries, deploying 50+ international staff across 8 regional corporate offices.

    Constraint

    Scaling a massive Procure-to-Pay (P2P) pipeline for $31.2M in sub-awards and grants across unproven markets, while resolving a critical $7M international tax deadlock to prevent stalled operations.

    Decision & Action

    Architected strict global vendor management and statutory tax compliance (PAYE/VAT) workflows to support clean annual audit outcomes. Designed a Results-Based Financing (RBF) framework that deployed $2.7M in catalyst grants to unlock $4M in commercial working capital. Negotiated a permanent shift to local currency (ZAR) invoicing.

    Applied Control Discipline
    Outcome

    Brought 5,771 MW of capacity to financial close and enabled 3.03M direct connections. Executed the $74,832,692 budget with 99.8% forecasting accuracy, capturing 100% of available fees ($5,195,184) and leaving just $122,679 in unspent variance over 7 years.

    RBF, P2P & Operational Execution Metrics
    Capacity Financed
    5,771 MW
    Execution Accuracy
    99.8%
    P2P Vendor Ledger
    $31.2M
    Total Connections
    3.03M
    Fixed Fee Captured
    100%
    Commercial Capital Unlocked
    $4.0M
    `; } else if(type === 'case_erp') { header.innerText = "Case Study: $90M South Sudan Governance"; content = `
    Context

    A $90M mandate to establish baseline public financial management (PFM) infrastructure for South Sudan. Decentralized, manual accounting across ten state governments caused severe data integrity risks and prevented national fiscal visibility.

    Constraint

    Deploying a sovereign enterprise-grade ERP system in a severe low-infrastructure environment, compounded by extreme macroeconomic volatility (oil revenue shocks) and kinetic civil conflict (the December 2013 crisis).

    Decision & Action

    Executed a highly resilient, phased rollout of the FreeBalance IFMIS ERP. Engineered annual fiscal setups in coordination with the technical outcome lead, maintaining a dedicated state-level Chart of Accounts (CoA). Enforced budget discipline via KPI-driven financial scorecards.

    Applied Control Discipline
    Outcome

    Successfully modernized sovereign accounting across all ten state ministries. Maintained system continuity throughout the Dec 2013 crisis and supported transaction entry for new fiscal cycles despite near-zero sovereign liquidity.

    Deployment & Resilience Execution
    Scope: $90M
    State Ministries Onboarded
    10
    Platform
    FreeBalance IFMIS
    Dec 2013 Civil Crisis
    Operations Maintained
    Macroeconomic Volatility
    Mitigated via KPI Scorecards
    `; } else if(type === 'case_acss') { header.innerText = "Case Study: $219M Afghanistan Closeout"; content = `
    Context

    A $219M multi-CLIN USAID program serving 700+ personnel across a high-risk operational environment in Kabul. Finance Manager responsibilities were assumed mid-program. As US engagement wound down, the mandate expanded to include spearheading the full financial close of the program and the complete unwind of Deloitte's in-country presence.

    Constraint

    Executing full program financial close in a high-risk operational environment: final vendor settlement, payroll closeout for 700+ staff, multi-currency treasury reconciliation, physical asset disposition, and final donor and firm-level reporting — with no known unresolved liabilities at closeout and under active security constraints.

    Decision & Action

    Maintained uninterrupted financial operations throughout the transition by managing the financial lifecycle via Deltek Costpoint. Spearheaded the financial close covering vendor settlement, staff payroll closeout, multi-currency reconciliation, and asset disposition. Concurrently secured $19.5M in additional portfolio funding by proving execution velocity to donor stakeholders through rigorous burn-rate analysis.

    Applied Control Discipline
    Outcome

    Full financial close of a $219M program and complete wind-down of Deloitte's in-country presence with no known unresolved liabilities at closeout. $19.5M in additional portfolio funding secured during active execution.

    Closeout Execution Metrics
    Program Scale: $219M
    Staff Payroll Closed
    700+
    Additional Funding Secured
    $19.5M
    Known Unresolved Liabilities
    None at Closeout
    FAR/AIDAR Controls
    Aligned
    ERP Platform
    Deltek Costpoint
    `; } body.innerHTML = content; document.getElementById('drillDownModal').style.display = 'flex'; document.body.style.overflow = 'hidden'; setTimeout(() => { const modalBody = document.querySelector('#drillDownModal .modal-body'); if (modalBody) modalBody.scrollTop = 0; const closeBtn = document.getElementById('modalCloseBtn'); if(closeBtn) closeBtn.focus(); }, 50); } function openFactBaseModal() { factBaseReturnElement = document.activeElement; document.getElementById('factBaseModal').style.display = 'flex'; document.body.style.overflow = 'hidden'; setTimeout(() => { const modalBody = document.querySelector('#factBaseModal .modal-body'); if (modalBody) modalBody.scrollTop = 0; const closeBtn = document.getElementById('factBaseCloseTop'); if (closeBtn) closeBtn.focus(); }, 50); } function closeFactBaseModal(e) { if(e && e.target !== e.currentTarget) return; document.getElementById('factBaseModal').style.display = 'none'; const aiOpen = document.getElementById('aiModal').style.display === 'flex'; const drillOpen = document.getElementById('drillDownModal').style.display === 'flex'; document.body.style.overflow = (aiOpen || drillOpen) ? 'hidden' : ''; if (factBaseReturnElement) factBaseReturnElement.focus(); factBaseReturnElement = null; } function closeDrillModal(e) { if(e && e.target !== e.currentTarget) return; document.getElementById('drillDownModal').style.display = 'none'; document.body.style.overflow = ''; if (lastActiveElement) lastActiveElement.focus(); } function initScrollSpy() { const sections = document.querySelectorAll('section[id]'); const navLinks = document.querySelectorAll('.nav-links a[data-target], #mobile-menu a[data-target]'); const observerOptions = { root: null, rootMargin: '-20% 0px -75% 0px', threshold: 0 }; const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const targetId = entry.target.getAttribute('id'); navLinks.forEach(link => { if (link.getAttribute('data-target') === targetId) { if (targetId === 'ai-tool') { link.classList.add('text-blue-300'); link.classList.remove('text-blue-500'); } else { link.classList.add('text-white'); link.classList.remove('text-slate-400'); } } else { if (link.getAttribute('data-target') === 'ai-tool') { link.classList.remove('text-blue-300'); link.classList.add('text-blue-500'); } else { link.classList.remove('text-white'); link.classList.add('text-slate-400'); } } }); } }); }, observerOptions); sections.forEach(section => observer.observe(section)); } // FIX 8: DOMContentLoaded replaces window.onload so interactive elements initialize before images load document.addEventListener('DOMContentLoaded', () => { renderMobileAccordion(); initScrollSpy(); if (window.innerWidth >= 1024) { renderTimeline(); renderExperienceStack(); initExperienceScrollSpy(); updateTimelineActiveState('gps'); } document.addEventListener('keydown', (e) => { const aiModal = document.getElementById('aiModal'); const drillModal = document.getElementById('drillDownModal'); const factBaseModal = document.getElementById('factBaseModal'); const mobileMenu = document.getElementById('mobile-menu'); const isAiOpen = aiModal && aiModal.style.display === 'flex'; const isDrillOpen = drillModal && drillModal.style.display === 'flex'; const isFactBaseOpen = factBaseModal && factBaseModal.style.display === 'flex'; const isMobileMenuOpen = mobileMenu && !mobileMenu.classList.contains('hidden'); if (e.key === 'Escape') { if (isFactBaseOpen) { closeFactBaseModal(); return; } if (isDrillOpen) { closeDrillModal(); return; } if (isAiOpen) { closeAiModal(); return; } if (isMobileMenuOpen) { closeMobileMenu(); document.getElementById('mobile-menu-btn')?.focus(); } return; } if (e.key === 'Tab') { const activeModal = isFactBaseOpen ? factBaseModal : (isDrillOpen ? drillModal : (isAiOpen ? aiModal : null)); if (!activeModal) return; const focusable = Array.from(activeModal.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(el => { const style = window.getComputedStyle(el); return !el.hasAttribute('disabled') && style.display !== 'none' && style.visibility !== 'hidden' && el.offsetParent !== null; }); if (focusable.length === 0) return; const first = focusable[0]; const last = focusable[focusable.length - 1]; if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } } }); }); // ── Ask Rajiv Chat Widget ───────────────────────────────────────────── const CHAT_ENDPOINT = 'https://www.rajivweeraratne.com/api/chat'; const CHAT_WELCOME = "Hi! I'm an AI built on Rajiv's verified career record. Ask me anything about his experience, background, or the roles he's targeting."; let chatHistory = []; let chatIsOpen = false; let chatLoading = false; let chatWelcomeShown = false; function toggleChat() { chatIsOpen = !chatIsOpen; const panel = document.getElementById('chatPanel'); const btn = document.getElementById('chatToggleBtn'); const iconOpen = document.getElementById('chatIconOpen'); const iconClose = document.getElementById('chatIconClose'); btn.setAttribute('aria-expanded', chatIsOpen); if (chatIsOpen) { panel.classList.remove('chat-panel-hidden'); panel.classList.add('chat-panel-visible'); iconOpen.classList.add('hidden'); iconClose.classList.remove('hidden'); if (!chatWelcomeShown) { chatWelcomeShown = true; appendChatMessage('assistant', CHAT_WELCOME); } setTimeout(() => { const inp = document.getElementById('chatInput'); if (inp) inp.focus(); }, 120); } else { panel.classList.remove('chat-panel-visible'); panel.classList.add('chat-panel-hidden'); iconOpen.classList.remove('hidden'); iconClose.classList.add('hidden'); } } function appendChatMessage(role, text) { const log = document.getElementById('chatMessages'); const wrap = document.createElement('div'); wrap.className = role === 'user' ? 'chat-msg chat-msg-user' : 'chat-msg chat-msg-assistant'; const bubble = document.createElement('div'); bubble.className = 'chat-bubble'; bubble.textContent = text; wrap.appendChild(bubble); log.appendChild(wrap); log.scrollTop = log.scrollHeight; } function showChatTyping() { const log = document.getElementById('chatMessages'); const el = document.createElement('div'); el.id = 'chatTyping'; el.className = 'chat-msg chat-msg-assistant'; el.innerHTML = '
    '; log.appendChild(el); log.scrollTop = log.scrollHeight; } function hideChatTyping() { const el = document.getElementById('chatTyping'); if (el) el.remove(); } async function sendChatMessage() { if (chatLoading) return; const inp = document.getElementById('chatInput'); const text = inp ? inp.value.trim() : ''; if (!text) return; inp.value = ''; inp.disabled = true; const sendBtn = document.getElementById('chatSendBtn'); if (sendBtn) sendBtn.disabled = true; chatLoading = true; appendChatMessage('user', text); chatHistory.push({ role: 'user', content: text }); showChatTyping(); try { const response = await fetch(CHAT_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: chatHistory }) }); hideChatTyping(); if (!response.ok) { const errData = await response.json().catch(() => ({})); throw new Error(errData.error || `Service error (${response.status})`); } const data = await response.json(); const reply = typeof data.reply === 'string' ? data.reply : 'Something went wrong. Please try again.'; chatHistory.push({ role: 'assistant', content: reply }); appendChatMessage('assistant', reply); } catch (err) { hideChatTyping(); const errMsg = err.message && err.message !== 'Failed to fetch' ? err.message : 'Chat is only available on the live site (rajivweeraratne.com). Not accessible from this preview.'; appendChatMessage('assistant', errMsg); } finally { chatLoading = false; if (inp) inp.disabled = false; if (sendBtn) sendBtn.disabled = false; if (inp) inp.focus(); } } document.addEventListener('DOMContentLoaded', () => { const inp = document.getElementById('chatInput'); if (inp) { inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChatMessage(); } }); } // ── Draggable chat button (mobile + desktop) ────────────────────── (function(){ const widget = document.getElementById('chatWidget'); const btn = document.getElementById('chatToggleBtn'); if (!widget || !btn) return; let dragging = false, startX, startY, origLeft, origTop; btn.addEventListener('pointerdown', e => { const r = widget.getBoundingClientRect(); startX = e.clientX; startY = e.clientY; origLeft = r.left; origTop = r.top; dragging = false; btn.setPointerCapture(e.pointerId); }); btn.addEventListener('pointermove', e => { if (!btn.hasPointerCapture(e.pointerId)) return; const dx = e.clientX - startX, dy = e.clientY - startY; if (!dragging && Math.hypot(dx, dy) > 6) { dragging = true; widget.style.bottom = 'auto'; widget.style.right = 'auto'; widget.style.left = origLeft + 'px'; widget.style.top = origTop + 'px'; widget.style.transition = 'none'; } if (dragging) { const newL = origLeft + dx, newT = origTop + dy; widget.style.left = Math.max(8, Math.min(window.innerWidth - widget.offsetWidth - 8, newL)) + 'px'; widget.style.top = Math.max(8, Math.min(window.innerHeight - widget.offsetHeight - 8, newT)) + 'px'; } }); btn.addEventListener('pointerup', e => { if (dragging) { e.preventDefault(); e.stopImmediatePropagation(); } dragging = false; }); btn.addEventListener('click', e => { if (dragging) { e.preventDefault(); e.stopImmediatePropagation(); dragging = false; } }, true); })(); }); // Scroll-triggered counter animations (function(){ if(!('IntersectionObserver' in window)) return; if(window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; function animateCount(el, to, decimals, prefix, suffix){ const dur=1600, t0=performance.now(); function step(t){ const p=Math.min((t-t0)/dur,1); const e=1-Math.pow(1-p,3); const v=e*to; el.textContent=prefix+(decimals>0?v.toFixed(decimals):Math.round(v))+suffix; if(p<1) requestAnimationFrame(step); } requestAnimationFrame(step); } const obs=new IntersectionObserver(entries=>{ entries.forEach(entry=>{ if(!entry.isIntersecting) return; const el=entry.target; const to=parseFloat(el.dataset.countTo); const dec=parseInt(el.dataset.countDecimals||'0',10); const pre=el.dataset.countPrefix||''; const suf=el.dataset.countSuffix||''; animateCount(el,to,dec,pre,suf); obs.unobserve(el); }); },{threshold:0.4}); document.querySelectorAll('[data-count-to]').forEach(el=>{ const pre=el.dataset.countPrefix||''; const suf=el.dataset.countSuffix||''; const dec=parseInt(el.dataset.countDecimals||'0',10); el.textContent=pre+(dec>0?'0.0':'0')+suf; obs.observe(el); }); })(); >>>>>>> 6a3174c (Handle reports that are too long to email in one click)