Compare commits

..

10 Commits

Author SHA1 Message Date
b26903c4ee Hide AI recommendation from results view; keep DB capture
AI text is still generated and saved to calc_submissions for internal
follow-up, but no longer displayed to the user — keeps the detailed
analysis behind the product sign-up wall.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 11:12:02 -04:00
ec0b8feac5 Fix AI prompt ambiguity around annual dues income vs. collection frequency
Clarify that annualIncome is the total per year, and payment frequency
describes the cash flow timing of installments — not a multiplier on income.
Include per-installment dollar amount so the model understands cash float correctly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 11:06:48 -04:00
4bddd96b40 fixed email blurb 2026-03-11 11:01:56 -04:00
8a369f6a57 Add calculator UX enhancements and submission tracking
- Button loading spinner + disable on submit to prevent duplicate AI calls
- Email field and opt-in consent checkbox on calculator form (checked by default)
- Privacy assurance blurb below opt-in
- Refinement blurb on results screen explaining live cash-flow optimization
- calc_submissions SQLite table stores form inputs, computed results, AI text, email, opt-in
- GET /api/calc-submissions endpoint (x-admin-key protected) to retrieve submissions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 10:58:19 -04:00
f195c6082d Tweaked wording of ROI Widget 2026-03-11 10:45:55 -04:00
bf70efc0d7 Add OpenAI-compatible AI investment advisor to benefit calculator
- server.js: add /api/calculate endpoint using openai SDK with configurable
  AI_API_URL, AI_API_KEY, AI_MODEL, AI_DEBUG env vars (works with any
  OpenAI-compatible provider: NVIDIA NIM, Together AI, Groq, Ollama, etc.)
- app.js: make calculator submit handler async; call /api/calculate with
  graceful fallback to client-side generated text if AI is unavailable
- package.json: add openai and dotenv dependencies
- AI_SETUP.md: rewrite to document new unified env var config with provider examples

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 10:05:41 -04:00
c95fd7d424 added example env file 2026-03-11 10:02:55 -04:00
15d35cff66 Fix Cononical 2026-03-11 09:59:31 -04:00
b658f50c9c Add Chatwoot support widget and AI API setup documentation
- Insert Chatwoot chat widget script at bottom of index.html body
  (connects to chat.hoaledgeriq.com with token 1QMW1fycL5xHvd6XMfg4Dbb4)
- Add AI_SETUP.md documenting how to upgrade the benefit calculator
  from client-side math to live AI API calls (Claude or OpenAI),
  including endpoint code, app.js changes, prompt tuning, cost
  estimates, and rate limiting guidance

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 09:54:53 -04:00
ba9ddee99d Add interest income benefit calculator widget to hero
- New "✦ Calculate Your Interest Income Potential" button between hero CTAs
  with gradient border styling distinct from primary/ghost buttons
- Modal overlay collects: homesites, property type, annual dues + frequency,
  reserve fund balance, and 2025 actual interest income
- Conservative calculation model: 4.0% HYSA for operating cash, 4.25% CD
  ladder for 65% of investable reserves; operating multiplier varies by
  payment frequency (monthly 10%, quarterly 20%, annual 35%)
- Results screen shows animated dollar counter, operating vs reserve
  breakdown, AI-style narrative recommendation, and direct CTA to signup
- Modal closes on backdrop click or Escape key; CTA closes modal and
  scrolls to early access signup form

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 09:49:18 -04:00
8 changed files with 2097 additions and 1 deletions

10
.env.example Normal file
View File

@@ -0,0 +1,10 @@
# Server
PORT=3000
ADMIN_KEY=your-admin-key-here
# AI ROI Estimator (OpenAI-compatible API)
AI_API_URL=https://integrate.api.nvidia.com/v1
AI_API_KEY=your_nvidia_api_key_here
AI_MODEL=qwen/qwen3.5-397b-a17b
# Set to 'true' to enable detailed AI prompt/response logging
AI_DEBUG=false

118
AI_SETUP.md Normal file
View File

@@ -0,0 +1,118 @@
# HOA LedgerIQ — AI Investment Advisor Configuration
## Overview
The **Benefit Calculator** uses an AI model to generate a personalized investment recommendation. It supports any **OpenAI-compatible API** — including OpenAI, NVIDIA NIM, Together AI, Groq, Ollama, and others — configured via environment variables.
---
## Architecture
```
Browser (app.js)
└─► POST /api/calculate (server.js)
└─► OpenAI-compatible API (AI_API_URL)
└─► Returns AI-generated recommendation text
└─► JSON response back to browser
(falls back to client-side math text if unavailable)
```
---
## Configuration (.env)
Add these variables to your `.env` file (or systemd `EnvironmentFile`):
```env
# AI Investment Advisor (OpenAI-compatible API)
AI_API_URL=https://integrate.api.nvidia.com/v1
AI_API_KEY=your_api_key_here
AI_MODEL=qwen/qwen3.5-397b-a17b
# Set to 'true' to enable detailed AI prompt/response logging
AI_DEBUG=false
```
### Provider Examples
| Provider | AI_API_URL | Example Model |
|---|---|---|
| OpenAI | `https://api.openai.com/v1` | `gpt-4o-mini` |
| NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | `qwen/qwen3.5-397b-a17b` |
| Together AI | `https://api.together.xyz/v1` | `meta-llama/Llama-3-70b-chat-hf` |
| Groq | `https://api.groq.com/openai/v1` | `llama3-70b-8192` |
| Ollama (local) | `http://localhost:11434/v1` | `llama3` |
> If `AI_API_KEY` is not set, the `/api/calculate` endpoint returns 503 and the calculator falls back to client-side generated text automatically.
---
## How It Works
`server.js` initializes the OpenAI client with your configured base URL and key:
```js
const aiClient = AI_API_KEY
? new OpenAI({ apiKey: AI_API_KEY, baseURL: AI_API_URL })
: null;
```
The `POST /api/calculate` endpoint builds a prompt from the form inputs and calls:
```js
const completion = await aiClient.chat.completions.create({
model: AI_MODEL,
max_tokens: 300,
messages: [{ role: 'user', content: prompt }],
});
```
`app.js` calls this endpoint on form submit and falls back to the client-side text if the server returns an error or is unreachable.
---
## Restart & Verify
```bash
sudo systemctl restart hoaledgeriqweb
# Test the endpoint
curl -X POST http://localhost:3000/api/calculate \
-H "Content-Type: application/json" \
-d '{"homesites":150,"propertyType":"sfh","annualIncome":300000,"paymentFreq":"monthly","reserveFunds":500000,"interest2025":4200}'
```
---
## Prompt Tuning
Edit the prompt in `server.js` (inside the `/api/calculate` route) to adjust tone or output:
| Goal | Change |
|---|---|
| More optimistic estimates | Change "conservative" to "moderate" |
| Shorter output | Reduce `max_tokens` to `150` |
| Specific products | Add "mention Vanguard Federal Money Market or 6-month T-bills" |
| Add disclaimer | Append "End with one sentence reminding them this is not financial advice." |
---
## Debug Logging
Set `AI_DEBUG=true` in `.env` to log the full prompt and response to the server console. Useful for testing new models or prompt changes.
---
## Security
- **Never put `AI_API_KEY` in `app.js`** — all AI calls go through `server.js`.
- Rate-limit the endpoint to prevent abuse:
```bash
npm install express-rate-limit --ignore-scripts
```
```js
const rateLimit = require('express-rate-limit');
app.use('/api/calculate', rateLimit({ windowMs: 60_000, max: 10 }));
```

143
app.js
View File

@@ -20,6 +20,149 @@
if (signupEl) signupEl.textContent = text; if (signupEl) signupEl.textContent = text;
})(); })();
// ── Benefit Calculator ───────────────────────────────────
(function initCalculator() {
const overlay = document.getElementById('calcOverlay');
const openBtn = document.getElementById('openCalc');
const closeBtn = document.getElementById('calcClose');
const submitBtn = document.getElementById('calcSubmit');
const recalcBtn = document.getElementById('calcRecalc');
const calcForm = document.getElementById('calcForm');
const calcRes = document.getElementById('calcResults');
const calcErr = document.getElementById('calcError');
const ctaBtn = document.getElementById('calcCTABtn');
if (!overlay) return;
function open() { overlay.classList.add('open'); document.body.style.overflow = 'hidden'; }
function close() { overlay.classList.remove('open'); document.body.style.overflow = ''; }
openBtn?.addEventListener('click', open);
closeBtn?.addEventListener('click', close);
overlay.addEventListener('click', e => { if (e.target === overlay) close(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') close(); });
recalcBtn?.addEventListener('click', () => {
calcRes.classList.add('hidden');
calcForm.classList.remove('hidden');
});
// Close modal and scroll to signup when CTA clicked
ctaBtn?.addEventListener('click', () => {
close();
});
const calcBtnText = submitBtn?.querySelector('.calc-btn-text');
const calcBtnLoading = submitBtn?.querySelector('.calc-btn-loading');
function setCalcLoading(on) {
if (!submitBtn) return;
submitBtn.disabled = on;
calcBtnText?.classList.toggle('hidden', on);
calcBtnLoading?.classList.toggle('hidden', !on);
}
submitBtn?.addEventListener('click', async () => {
const homesites = parseFloat(document.getElementById('calcHomesites').value) || 0;
const propertyType = document.getElementById('calcPropertyType').value;
const annualIncome = parseFloat(document.getElementById('calcAnnualIncome').value) || 0;
const paymentFreq = document.getElementById('calcPaymentFreq').value;
const reserveFunds = parseFloat(document.getElementById('calcReserveFunds').value) || 0;
const interest2025 = parseFloat(document.getElementById('calcInterest2025').value) || 0;
const calcEmail = document.getElementById('calcEmail')?.value.trim() || '';
const calcOptIn = document.getElementById('calcOptIn')?.checked ?? true;
if (!homesites || !annualIncome) {
calcErr.classList.remove('hidden');
return;
}
calcErr.classList.add('hidden');
setCalcLoading(true);
// ── Conservative investment assumptions ──
// Operating cash: depending on payment frequency, portion investable in high-yield savings
const opMultiplier = { monthly: 0.10, quarterly: 0.20, annually: 0.35 }[paymentFreq] || 0.10;
const opRate = 0.040; // 4.0% money market / HYSA
const resRatio = 0.65; // 65% of reserves investable (keep 35% liquid)
const resRate = 0.0425; // 4.25% CD ladder / short-term treasuries
const investableOp = annualIncome * opMultiplier;
const investableRes = reserveFunds * resRatio;
const opInterest = Math.round(investableOp * opRate);
const resInterest = Math.round(investableRes * resRate);
const totalPotential = opInterest + resInterest;
const increase = totalPotential - interest2025;
const pctIncrease = interest2025 > 0
? Math.round((increase / interest2025) * 100)
: (totalPotential > 0 ? 100 : 0);
// ── Populate results ──
const fmt = n => '$' + Math.round(n).toLocaleString();
document.getElementById('resultAmount').textContent = fmt(totalPotential);
document.getElementById('resultCurrent').textContent = fmt(interest2025);
document.getElementById('resultOperating').textContent = fmt(opInterest);
document.getElementById('resultReserve').textContent = fmt(resInterest);
const badge = document.getElementById('resultBadge');
if (increase > 0) {
badge.textContent = `+${fmt(increase)} · +${pctIncrease}%`;
badge.style.display = 'inline-block';
} else {
badge.style.display = 'none';
}
// ── AI-style suggestion text ──
const typeLabels = { sfh:'single-family home', townhomes:'townhome', condos:'condo', mixed:'mixed-use', '':'' };
const typeLabel = typeLabels[propertyType] || '';
const freqLabel = { monthly:'monthly', quarterly:'quarterly', annually:'annual' }[paymentFreq];
const communityDesc = [homesites && `${homesites}-unit`, typeLabel, 'community'].filter(Boolean).join(' ');
let ai = `Based on your ${communityDesc} collecting ${fmt(annualIncome)} in ${freqLabel} dues`;
if (reserveFunds > 0) ai += ` and ${fmt(reserveFunds)} in reserve funds`;
ai += `, a conservative investment strategy could generate approximately ${fmt(totalPotential)} in annual interest income. `;
if (resInterest > 0) ai += `Deploying ${fmt(investableRes)} of your reserve funds into a short-term CD ladder at ~4.25% yields ${fmt(resInterest)} annually. `;
if (opInterest > 0) ai += `Keeping a ${fmt(investableOp)} operating cash buffer in a high-yield money market at ~4.0% adds another ${fmt(opInterest)}. `;
if (interest2025 > 0 && increase > 0) {
ai += `That's a ${fmt(increase)} improvement (+${pctIncrease}%) over your 2025 interest income of ${fmt(interest2025)} — with no additional risk.`;
} else if (interest2025 === 0) {
ai += `This would represent entirely new interest income for your community at no additional risk.`;
}
// ── AI recommendation — call server to generate & save to DB (not displayed) ──
try {
await fetch('/api/calculate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
homesites, propertyType, annualIncome, paymentFreq, reserveFunds, interest2025,
email: calcEmail, optIn: calcOptIn,
totalPotential, opInterest, resInterest,
}),
});
} catch (_) { /* best-effort — DB save failed silently */ }
// ── Animate the main number ──
animateValue(document.getElementById('resultAmount'), 0, totalPotential);
setCalcLoading(false);
calcForm.classList.add('hidden');
calcRes.classList.remove('hidden');
});
function animateValue(el, from, to) {
const duration = 900;
const start = performance.now();
function step(now) {
const progress = Math.min((now - start) / duration, 1);
const ease = 1 - Math.pow(1 - progress, 3);
el.textContent = '$' + Math.round(from + (to - from) * ease).toLocaleString();
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
})();
// ── Screenshot Carousel ────────────────────────────────── // ── Screenshot Carousel ──────────────────────────────────
(function initCarousel() { (function initCarousel() {
const carousel = document.getElementById('screenshotCarousel'); const carousel = document.getElementById('screenshotCarousel');

View File

@@ -8,6 +8,7 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="styles.css" /> <link rel="stylesheet" href="styles.css" />
<link rel="cononical" href="https://www.hoaledgeriq.com" />
</head> </head>
<!-- Google tag (gtag.js) --> <!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-RTWNVXPMRF"></script> <script async src="https://www.googletagmanager.com/gtag/js?id=G-RTWNVXPMRF"></script>
@@ -63,6 +64,7 @@
</p> </p>
<div class="hero-actions"> <div class="hero-actions">
<a href="#preview-signup" class="btn btn-primary btn-lg">Join the Preview List</a> <a href="#preview-signup" class="btn btn-primary btn-lg">Join the Preview List</a>
<button class="btn btn-calc btn-lg" id="openCalc">✦ Calculate Your Interest Income Potential</button>
<a href="#features" class="btn btn-ghost btn-lg">See What's Inside ↓</a> <a href="#features" class="btn btn-ghost btn-lg">See What's Inside ↓</a>
</div> </div>
<div class="hero-trust"> <div class="hero-trust">
@@ -428,6 +430,143 @@
</div> </div>
</footer> </footer>
<!-- ── BENEFIT CALCULATOR MODAL ─────────────────────── -->
<div class="calc-overlay" id="calcOverlay" aria-modal="true" role="dialog">
<div class="calc-modal">
<button class="calc-close" id="calcClose" aria-label="Close calculator">×</button>
<div class="calc-header">
<div class="section-label">ROI Calculator</div>
<h2>See What HOA LedgerIQ Could Earn Your Community</h2>
<p>Answer a few quick questions for a personalized, AI-Driven interest income estimate.</p>
</div>
<!-- INPUTS -->
<div id="calcForm">
<div class="calc-grid">
<div class="calc-field">
<label for="calcHomesites">Number of Homesites</label>
<input type="number" id="calcHomesites" placeholder="e.g. 150" min="1" />
</div>
<div class="calc-field">
<label for="calcPropertyType">Property Type</label>
<select id="calcPropertyType">
<option value="">Select type...</option>
<option value="sfh">Single Family Homes</option>
<option value="townhomes">Townhomes</option>
<option value="condos">Condos</option>
<option value="mixed">Mixed Use</option>
</select>
</div>
<div class="calc-field">
<label for="calcAnnualIncome">Annual Dues Income</label>
<div class="input-prefix-wrap">
<span class="input-prefix">$</span>
<input type="number" id="calcAnnualIncome" placeholder="e.g. 250,000" min="0" />
</div>
</div>
<div class="calc-field">
<label for="calcPaymentFreq">Dues Payment Frequency</label>
<select id="calcPaymentFreq">
<option value="monthly">Monthly</option>
<option value="quarterly">Quarterly</option>
<option value="annually">Annually</option>
</select>
</div>
<div class="calc-field">
<label for="calcReserveFunds">Current Reserve Fund Balance</label>
<div class="input-prefix-wrap">
<span class="input-prefix">$</span>
<input type="number" id="calcReserveFunds" placeholder="e.g. 500,000" min="0" />
</div>
</div>
<div class="calc-field">
<label for="calcInterest2025">Interest Income Earned in 2025</label>
<div class="input-prefix-wrap">
<span class="input-prefix">$</span>
<input type="number" id="calcInterest2025" placeholder="e.g. 4,500" min="0" />
</div>
</div>
</div>
<p class="calc-error hidden" id="calcError">Please fill in homesites and annual dues income to continue.</p>
<!-- Email + opt-in -->
<div class="calc-email-row">
<div class="calc-field calc-field--full">
<label for="calcEmail">Your Email Address <span class="calc-optional">(optional)</span></label>
<input type="email" id="calcEmail" placeholder="you@example.com" />
</div>
<label class="calc-optin-label">
<input type="checkbox" id="calcOptIn" checked />
<span>I'd like HOA LedgerIQ to provide informative insights over time.</span>
</label>
<p class="calc-privacy">🔒 Your email and submitted data are used solely to provide your ROI estimate and will never be shared with any third party or outside organization.</p>
</div>
<p class="calc-error hidden" id="calcError">Please fill in homesites and annual dues income to continue.</p>
<button class="btn btn-primary btn-lg calc-submit-btn" id="calcSubmit">
<span class="calc-btn-text">Calculate My Potential →</span>
<span class="calc-btn-loading hidden"><span class="calc-spinner"></span> Calculating…</span>
</button>
<p class="calc-fine">Conservative estimates for illustrative purposes only. Not financial advice.</p>
</div>
<!-- RESULTS -->
<div id="calcResults" class="hidden">
<div class="result-highlight">
<div class="result-label">Estimated Annual Interest Income Potential</div>
<div class="result-amount" id="resultAmount">$0</div>
<div class="result-comparison">
<span>vs. your 2025 earnings: <strong id="resultCurrent">$0</strong></span>
<span class="result-badge" id="resultBadge"></span>
</div>
</div>
<div class="result-breakdown">
<div class="result-row">
<span>Operating fund cash management</span>
<span class="result-row-val" id="resultOperating">$0</span>
</div>
<div class="result-row">
<span>Reserve fund investment income</span>
<span class="result-row-val" id="resultReserve">$0</span>
</div>
</div>
<!-- AI text captured to DB only — not displayed -->
<p id="calcAiText" style="display:none"></p>
<div class="calc-refine-blurb">
<span class="calc-refine-icon"></span>
<p>This is a high-level estimate based on your inputs. Inside HOA LedgerIQ, your investment strategy is continuously refined against your live cash flows, upcoming expenses, and reserve study timelines — automatically maximizing yield while keeping your community fully liquid.</p>
</div>
<div class="calc-cta">
<p>Ready to put these gains to work for your community?</p>
<a href="#preview-signup" class="btn btn-primary btn-lg calc-cta-btn" id="calcCTABtn">Get Early Access — Reserve My Spot →</a>
<button class="btn btn-ghost calc-recalc" id="calcRecalc">← Recalculate</button>
</div>
</div>
</div>
</div>
<script src="app.js"></script> <script src="app.js"></script>
<!-- Support Chat Widget -->
<script>
(function(d,t) {
var BASE_URL="https://chat.hoaledgeriq.com";
var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=BASE_URL+"/packs/js/sdk.js";
g.async = true;
s.parentNode.insertBefore(g,s);
g.onload=function(){
window.chatwootSDK.run({
websiteToken: '1QMW1fycL5xHvd6XMfg4Dbb4',
baseUrl: BASE_URL
})
}
})(document,"script");
</script>
</body> </body>
</html> </html>

1286
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,8 @@
}, },
"dependencies": { "dependencies": {
"better-sqlite3": "^9.4.3", "better-sqlite3": "^9.4.3",
"express": "^4.18.3" "dotenv": "^17.3.1",
"express": "^4.18.3",
"openai": "^6.27.0"
} }
} }

137
server.js
View File

@@ -14,9 +14,20 @@ const path = require('path');
const fs = require('fs'); const fs = require('fs');
const express = require('express'); const express = require('express');
const Database = require('better-sqlite3'); const Database = require('better-sqlite3');
const OpenAI = require('openai');
// ── Config ────────────────────────────────────────────── // ── Config ──────────────────────────────────────────────
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
// ── AI client (OpenAI-compatible) ────────────────────────
const AI_API_URL = process.env.AI_API_URL || 'https://api.openai.com/v1';
const AI_API_KEY = process.env.AI_API_KEY || '';
const AI_MODEL = process.env.AI_MODEL || 'gpt-4o-mini';
const AI_DEBUG = process.env.AI_DEBUG === 'true';
const aiClient = AI_API_KEY
? new OpenAI({ apiKey: AI_API_KEY, baseURL: AI_API_URL })
: null;
const DB_DIR = path.join(__dirname, 'data'); const DB_DIR = path.join(__dirname, 'data');
const DB_PATH = path.join(DB_DIR, 'leads.db'); const DB_PATH = path.join(DB_DIR, 'leads.db');
@@ -42,6 +53,25 @@ db.exec(`
); );
`); `);
db.exec(`
CREATE TABLE IF NOT EXISTS calc_submissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT,
opt_in INTEGER DEFAULT 1,
homesites REAL,
property_type TEXT,
annual_income REAL,
payment_freq TEXT,
reserve_funds REAL,
interest_2025 REAL,
total_potential REAL,
op_interest REAL,
res_interest REAL,
ai_recommendation TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);
`);
// Migrate existing DBs: add new columns if they don't exist yet // Migrate existing DBs: add new columns if they don't exist yet
const cols = db.pragma('table_info(leads)').map(c => c.name); const cols = db.pragma('table_info(leads)').map(c => c.name);
if (!cols.includes('org_name')) db.exec('ALTER TABLE leads ADD COLUMN org_name TEXT'); if (!cols.includes('org_name')) db.exec('ALTER TABLE leads ADD COLUMN org_name TEXT');
@@ -56,6 +86,19 @@ const insertLead = db.prepare(`
const findByEmail = db.prepare(`SELECT id FROM leads WHERE email = ? LIMIT 1`); const findByEmail = db.prepare(`SELECT id FROM leads WHERE email = ? LIMIT 1`);
const insertCalcSubmission = db.prepare(`
INSERT INTO calc_submissions
(email, opt_in, homesites, property_type, annual_income, payment_freq,
reserve_funds, interest_2025, total_potential, op_interest, res_interest, ai_recommendation)
VALUES
(@email, @optIn, @homesites, @propertyType, @annualIncome, @paymentFreq,
@reserveFunds, @interest2025, @totalPotential, @opInterest, @resInterest, @aiRecommendation)
`);
const getAllCalcSubmissions = db.prepare(`
SELECT * FROM calc_submissions ORDER BY created_at DESC
`);
const getAllLeads = db.prepare(` const getAllLeads = db.prepare(`
SELECT id, first_name, last_name, email, org_name, state, role, unit_count, beta_interest, source, created_at SELECT id, first_name, last_name, email, org_name, state, role, unit_count, beta_interest, source, created_at
FROM leads FROM leads
@@ -127,6 +170,100 @@ app.get('/api/leads', (req, res) => {
res.json({ count: leads.length, leads }); res.json({ count: leads.length, leads });
}); });
// POST /api/calculate — AI-powered investment recommendation
app.post('/api/calculate', async (req, res) => {
function saveCalcSubmission(aiRecommendation) {
try {
insertCalcSubmission.run({
email: email?.trim() || null,
optIn: optIn ? 1 : 0,
homesites: homesites || null,
propertyType: propertyType || null,
annualIncome: annualIncome || null,
paymentFreq: paymentFreq || null,
reserveFunds: reserveFunds || null,
interest2025: interest2025 || null,
totalPotential: totalPotential || null,
opInterest: opInterest || null,
resInterest: resInterest || null,
aiRecommendation: aiRecommendation || null,
});
} catch (err) {
console.error('Failed to save calc submission:', err.message);
}
}
if (!aiClient) {
saveCalcSubmission(null);
return res.status(503).json({ error: 'AI service not configured.' });
}
const {
homesites, propertyType, annualIncome, paymentFreq, reserveFunds, interest2025,
email, optIn, totalPotential, opInterest, resInterest,
} = req.body ?? {};
if (!homesites || !annualIncome) {
return res.status(400).json({ error: 'homesites and annualIncome are required.' });
}
const fmt = n => '$' + Math.round(n).toLocaleString();
const typeLabel = { sfh: 'single-family home', townhomes: 'townhome', condos: 'condo', mixed: 'mixed-use' }[propertyType] || '';
const freqDivisor = { monthly: 12, quarterly: 4, annually: 1 }[paymentFreq] || 12;
const installmentAmt = annualIncome / freqDivisor;
const freqDesc = { monthly: 'monthly installments', quarterly: 'quarterly installments', annually: 'one lump-sum annual payment' }[paymentFreq] || 'monthly installments';
const prompt = `You are a conservative HOA financial advisor. Given the following community data, provide a brief (3-4 sentence) plain-English investment income recommendation. Use only conservative, realistic estimates. Do not speculate beyond what the data supports.
Community: ${homesites}-unit ${typeLabel} association
Total annual dues income: ${fmt(annualIncome)} per year
Dues collection schedule: collected in ${freqDesc} of approximately ${fmt(installmentAmt)} per cycle (this affects operating cash flow timing, not the total annual amount)
Reserve fund balance: ${fmt(reserveFunds || 0)}
Interest income earned in 2025: ${fmt(interest2025 || 0)}
Provide a recommendation focused on:
1. How much of the reserve funds could conservatively be invested and in what vehicle (e.g. CD ladder, money market, T-bills)
2. How much operating cash float could earn interest between each collection cycle and upcoming expenses, given the ${freqDesc} schedule
3. A realistic estimated annual interest income potential based on the full ${fmt(annualIncome)} annual dues total
4. A single sentence comparing that to their 2025 actual if provided
Keep the tone professional and factual. No bullet points — flowing paragraph only.`;
if (AI_DEBUG) {
console.log('[AI_DEBUG] model:', AI_MODEL);
console.log('[AI_DEBUG] prompt:', prompt);
}
try {
const completion = await aiClient.chat.completions.create({
model: AI_MODEL,
max_tokens: 300,
messages: [{ role: 'user', content: prompt }],
});
const text = completion.choices[0]?.message?.content ?? '';
if (AI_DEBUG) console.log('[AI_DEBUG] response:', text);
saveCalcSubmission(text);
res.json({ recommendation: text });
} catch (err) {
console.error('AI API error:', err.message);
saveCalcSubmission(null);
res.status(502).json({ error: 'AI service unavailable. Showing estimated result.' });
}
});
// GET /api/calc-submissions — internal: list all calculator submissions
app.get('/api/calc-submissions', (req, res) => {
const secret = req.headers['x-admin-key'];
if (!secret || secret !== process.env.ADMIN_KEY) {
return res.status(401).json({ error: 'Unauthorized.' });
}
const rows = getAllCalcSubmissions.all();
res.json({ count: rows.length, submissions: rows });
});
// Health check // Health check
app.get('/api/health', (_req, res) => res.json({ status: 'ok', ts: new Date().toISOString() })); app.get('/api/health', (_req, res) => res.json({ status: 'ok', ts: new Date().toISOString() }));

View File

@@ -623,6 +623,267 @@ body {
color: var(--gray-700); color: var(--gray-700);
} }
/* ---- Calculator CTA button ---- */
.btn-calc {
background: linear-gradient(135deg, rgba(79,70,229,0.25), rgba(14,165,233,0.2));
border: 1.5px solid rgba(99,102,241,0.6);
color: #c7d2fe;
position: relative;
overflow: hidden;
}
.btn-calc::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(135deg, rgba(79,70,229,0.4), rgba(14,165,233,0.3));
opacity: 0;
transition: opacity 0.2s;
}
.btn-calc:hover { color: #fff; border-color: rgba(99,102,241,0.9); transform: translateY(-1px); box-shadow: 0 8px 28px rgba(79,70,229,0.3); }
.btn-calc:hover::before { opacity: 1; }
.btn-calc span, .btn-calc { position: relative; z-index: 1; }
/* ---- Calculator Modal ---- */
.calc-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.75);
backdrop-filter: blur(6px);
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
opacity: 0;
pointer-events: none;
transition: opacity 0.25s ease;
}
.calc-overlay.open {
opacity: 1;
pointer-events: all;
}
.calc-modal {
background: var(--gray-800);
border: 1px solid rgba(99,102,241,0.35);
border-radius: var(--radius-lg);
padding: 44px 48px;
max-width: 700px;
width: 100%;
max-height: 90vh;
overflow-y: auto;
position: relative;
box-shadow: 0 0 80px rgba(79,70,229,0.25), var(--shadow-lg);
transform: translateY(16px);
transition: transform 0.25s ease;
}
.calc-overlay.open .calc-modal { transform: translateY(0); }
.calc-close {
position: absolute;
top: 16px; right: 20px;
background: none;
border: none;
color: var(--gray-500);
font-size: 26px;
cursor: pointer;
line-height: 1;
padding: 4px 8px;
border-radius: 6px;
transition: color 0.15s, background 0.15s;
}
.calc-close:hover { color: #fff; background: rgba(255,255,255,0.08); }
.calc-header { margin-bottom: 28px; }
.calc-header h2 { font-size: 26px; font-weight: 800; color: #fff; letter-spacing: -0.02em; margin-bottom: 8px; }
.calc-header p { font-size: 15px; color: var(--gray-400); }
.calc-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
margin-bottom: 8px;
}
.calc-field { display: flex; flex-direction: column; gap: 6px; }
.calc-field label { font-size: 13px; font-weight: 600; color: var(--gray-400); }
.calc-field input,
.calc-field select {
background: var(--gray-900);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 8px;
padding: 11px 14px;
color: var(--gray-100);
font-size: 15px;
font-family: inherit;
width: 100%;
outline: none;
transition: border-color 0.15s;
-webkit-appearance: none;
}
.calc-field input:focus,
.calc-field select:focus { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(37,99,235,0.2); }
.calc-field input::placeholder { color: var(--gray-700); }
.calc-field select {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%2394a3b8' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 14px center;
padding-right: 36px;
}
.calc-field select option { background: var(--gray-800); color: var(--gray-100); }
.input-prefix-wrap { position: relative; }
.input-prefix {
position: absolute;
left: 13px;
top: 50%;
transform: translateY(-50%);
color: var(--gray-600);
font-size: 15px;
font-weight: 600;
pointer-events: none;
}
.input-prefix-wrap input { padding-left: 28px; }
.calc-error {
color: #f87171;
font-size: 13px;
margin: 8px 0;
font-weight: 500;
}
.calc-submit-btn { width: 100%; justify-content: center; margin-top: 16px; }
.calc-fine {
font-size: 11px;
color: var(--gray-700);
text-align: center;
margin-top: 10px;
line-height: 1.5;
}
/* ── Results ── */
.result-highlight {
background: linear-gradient(135deg, rgba(79,70,229,0.18), rgba(14,165,233,0.12));
border: 1px solid rgba(79,70,229,0.4);
border-radius: var(--radius);
padding: 28px;
text-align: center;
margin-bottom: 20px;
}
.result-label {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--gray-500);
font-weight: 700;
margin-bottom: 10px;
}
.result-amount {
font-size: 52px;
font-weight: 900;
letter-spacing: -0.03em;
color: var(--green);
line-height: 1.1;
margin-bottom: 12px;
}
.result-comparison {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
flex-wrap: wrap;
font-size: 14px;
color: var(--gray-400);
}
.result-badge {
background: rgba(34,197,94,0.15);
border: 1px solid rgba(34,197,94,0.35);
color: var(--green);
padding: 3px 12px;
border-radius: 99px;
font-size: 13px;
font-weight: 700;
white-space: nowrap;
}
.result-breakdown {
background: rgba(255,255,255,0.03);
border: 1px solid rgba(255,255,255,0.07);
border-radius: var(--radius);
padding: 16px 20px;
margin-bottom: 20px;
display: flex;
flex-direction: column;
gap: 10px;
}
.result-row {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 14px;
color: var(--gray-400);
}
.result-row-val { font-weight: 700; color: var(--gray-200); }
.calc-ai-bubble {
background: rgba(79,70,229,0.12);
border: 1px solid rgba(79,70,229,0.3);
border-radius: var(--radius);
padding: 18px 20px;
margin-bottom: 24px;
font-size: 14px;
color: var(--gray-200);
line-height: 1.65;
}
.calc-ai-bubble .ai-label {
display: block;
font-size: 11px;
font-weight: 700;
color: #a5b4fc;
text-transform: uppercase;
letter-spacing: 0.06em;
margin-bottom: 8px;
}
.calc-cta { text-align: center; }
.calc-cta > p { color: var(--gray-400); font-size: 15px; margin-bottom: 16px; }
.calc-cta-btn { width: 100%; justify-content: center; margin-bottom: 12px; }
.calc-recalc { font-size: 14px; color: var(--gray-500); }
.calc-recalc:hover { color: var(--gray-200); }
/* ── Calc email + opt-in ── */
.calc-email-row { margin-top: 20px; display: flex; flex-direction: column; gap: 10px; }
.calc-field--full { grid-column: 1 / -1; }
.calc-optional { font-weight: 400; color: var(--gray-600); font-size: 11px; }
.calc-optin-label {
display: flex; align-items: flex-start; gap: 10px;
font-size: 13px; color: var(--gray-300); cursor: pointer; line-height: 1.5;
}
.calc-optin-label input[type="checkbox"] {
margin-top: 2px; accent-color: var(--blue); flex-shrink: 0;
width: 15px; height: 15px; cursor: pointer;
}
.calc-privacy {
font-size: 11px; color: var(--gray-600); line-height: 1.5;
border-left: 2px solid rgba(255,255,255,0.06); padding-left: 10px; margin: 0;
}
/* ── Calc button spinner ── */
.calc-btn-loading { display: flex; align-items: center; gap: 8px; }
.calc-spinner {
display: inline-block; width: 14px; height: 14px;
border: 2px solid rgba(255,255,255,0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ── Results refinement blurb ── */
.calc-refine-blurb {
display: flex; gap: 12px; align-items: flex-start;
background: rgba(14,165,233,0.07);
border: 1px solid rgba(14,165,233,0.18);
border-radius: 10px;
padding: 14px 16px;
margin-bottom: 20px;
}
.calc-refine-icon {
font-size: 18px; color: var(--sky); flex-shrink: 0; margin-top: 1px;
}
.calc-refine-blurb p {
font-size: 12.5px; color: var(--gray-400); line-height: 1.6; margin: 0;
}
/* ---- Screenshot Carousel ---- */ /* ---- Screenshot Carousel ---- */
.screenshot-carousel { .screenshot-carousel {
width: 100%; width: 100%;