@conversionpros/aiva 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +148 -0
- package/auto-deploy.js +190 -0
- package/bin/aiva.js +81 -0
- package/cli-sync.js +126 -0
- package/d2a-prompt-template.txt +106 -0
- package/diagnostics-api.js +304 -0
- package/docs/ara-dedup-fix-scope.md +112 -0
- package/docs/ara-fix-round2-scope.md +61 -0
- package/docs/ara-greeting-fix-scope.md +70 -0
- package/docs/calendar-date-fix-scope.md +28 -0
- package/docs/getting-started.md +115 -0
- package/docs/network-architecture-rollout-scope.md +43 -0
- package/docs/scope-google-oauth-integration.md +351 -0
- package/docs/settings-page-scope.md +50 -0
- package/docs/xai-imagine-scope.md +116 -0
- package/docs/xai-voice-integration-scope.md +115 -0
- package/docs/xai-voice-tools-scope.md +165 -0
- package/email-router.js +512 -0
- package/follow-up-handler.js +606 -0
- package/gateway-monitor.js +158 -0
- package/google-email.js +379 -0
- package/google-oauth.js +310 -0
- package/grok-imagine.js +97 -0
- package/health-reporter.js +287 -0
- package/invisible-prefix-base.txt +206 -0
- package/invisible-prefix-owner.txt +26 -0
- package/invisible-prefix-slim.txt +10 -0
- package/invisible-prefix.txt +43 -0
- package/knowledge-base.js +472 -0
- package/lib/cli.js +19 -0
- package/lib/config.js +124 -0
- package/lib/health.js +57 -0
- package/lib/process.js +207 -0
- package/lib/server.js +42 -0
- package/lib/setup.js +472 -0
- package/meta-capi.js +206 -0
- package/meta-leads.js +411 -0
- package/notion-oauth.js +323 -0
- package/package.json +61 -0
- package/public/agent-config.html +241 -0
- package/public/aiva-avatar-anime.png +0 -0
- package/public/css/docs.css.bak +688 -0
- package/public/css/onboarding.css +543 -0
- package/public/diagrams/claude-subscription-pool.html +329 -0
- package/public/diagrams/claude-subscription-pool.png +0 -0
- package/public/docs-icon.png +0 -0
- package/public/escalation.html +237 -0
- package/public/group-config.html +300 -0
- package/public/icon-192.png +0 -0
- package/public/icon-512.png +0 -0
- package/public/icons/agents.svg +1 -0
- package/public/icons/attach.svg +1 -0
- package/public/icons/characters.svg +1 -0
- package/public/icons/chat.svg +1 -0
- package/public/icons/docs.svg +1 -0
- package/public/icons/heartbeat.svg +1 -0
- package/public/icons/messages.svg +1 -0
- package/public/icons/mic.svg +1 -0
- package/public/icons/notes.svg +1 -0
- package/public/icons/settings.svg +1 -0
- package/public/icons/tasks.svg +1 -0
- package/public/images/onboarding/p0-communication-layer.png +0 -0
- package/public/images/onboarding/p0-infinite-surface.png +0 -0
- package/public/images/onboarding/p0-learning-model.png +0 -0
- package/public/images/onboarding/p0-meet-aiva.png +0 -0
- package/public/images/onboarding/p4-contact-intelligence.png +0 -0
- package/public/images/onboarding/p4-context-compounds.png +0 -0
- package/public/images/onboarding/p4-message-router.png +0 -0
- package/public/images/onboarding/p4-per-contact-rules.png +0 -0
- package/public/images/onboarding/p4-send-messages.png +0 -0
- package/public/images/onboarding/p6-be-precise.png +0 -0
- package/public/images/onboarding/p6-review-escalations.png +0 -0
- package/public/images/onboarding/p6-voice-input.png +0 -0
- package/public/images/onboarding/p7-completion.png +0 -0
- package/public/index.html +11594 -0
- package/public/js/onboarding.js +699 -0
- package/public/manifest.json +24 -0
- package/public/messages-v2.html +2824 -0
- package/public/permission-approve.html.bak +107 -0
- package/public/permissions.html +150 -0
- package/public/styles/design-system.css +68 -0
- package/router-db.js +604 -0
- package/router-utils.js +28 -0
- package/router-v2/adapters/imessage.js +191 -0
- package/router-v2/adapters/quo.js +82 -0
- package/router-v2/adapters/whatsapp.js +192 -0
- package/router-v2/contact-manager.js +234 -0
- package/router-v2/conversation-engine.js +498 -0
- package/router-v2/data/knowledge-base.json +176 -0
- package/router-v2/data/router-v2.db +0 -0
- package/router-v2/data/router-v2.db-shm +0 -0
- package/router-v2/data/router-v2.db-wal +0 -0
- package/router-v2/data/router.db +0 -0
- package/router-v2/db.js +457 -0
- package/router-v2/escalation-bridge.js +540 -0
- package/router-v2/follow-up-engine.js +347 -0
- package/router-v2/index.js +441 -0
- package/router-v2/ingestion.js +213 -0
- package/router-v2/knowledge-base.js +231 -0
- package/router-v2/lead-qualifier.js +152 -0
- package/router-v2/learning-loop.js +202 -0
- package/router-v2/outbound-sender.js +160 -0
- package/router-v2/package.json +13 -0
- package/router-v2/permission-gate.js +86 -0
- package/router-v2/playbook.js +177 -0
- package/router-v2/prompts/base.js +52 -0
- package/router-v2/prompts/first-contact.js +38 -0
- package/router-v2/prompts/lead-qualification.js +37 -0
- package/router-v2/prompts/scheduling.js +72 -0
- package/router-v2/prompts/style-overrides.js +22 -0
- package/router-v2/scheduler.js +301 -0
- package/router-v2/scripts/migrate-v1-to-v2.js +215 -0
- package/router-v2/scripts/seed-faq.js +67 -0
- package/router-v2/seed-knowledge-base.js +39 -0
- package/router-v2/utils/ai.js +129 -0
- package/router-v2/utils/phone.js +52 -0
- package/router-v2/utils/response-validator.js +98 -0
- package/router-v2/utils/sanitize.js +222 -0
- package/router.js +5005 -0
- package/routes/google-calendar.js +186 -0
- package/scripts/deploy.sh +62 -0
- package/scripts/macos-calendar.sh +232 -0
- package/scripts/onboard-device.sh +466 -0
- package/server.js +5131 -0
- package/start.sh +24 -0
- package/templates/AGENTS.md +548 -0
- package/templates/IDENTITY.md +15 -0
- package/templates/docs-agents.html +132 -0
- package/templates/docs-app.html +130 -0
- package/templates/docs-home.html +83 -0
- package/templates/docs-imessage.html +121 -0
- package/templates/docs-tasks.html +123 -0
- package/templates/docs-tips.html +175 -0
- package/templates/getting-started.html +809 -0
- package/templates/invisible-prefix-base.txt +171 -0
- package/templates/invisible-prefix-owner.txt +282 -0
- package/templates/invisible-prefix.txt +338 -0
- package/templates/manifest.json +61 -0
- package/templates/memory-org/clients.md +7 -0
- package/templates/memory-org/credentials.md +9 -0
- package/templates/memory-org/devices.md +7 -0
- package/templates/updates.html +464 -0
- package/templates/workspace/AGENTS.md.tmpl +161 -0
- package/templates/workspace/HEARTBEAT.md.tmpl +17 -0
- package/templates/workspace/IDENTITY.md.tmpl +15 -0
- package/templates/workspace/MEMORY.md.tmpl +16 -0
- package/templates/workspace/SOUL.md.tmpl +51 -0
- package/templates/workspace/USER.md.tmpl +25 -0
- package/tts-proxy.js +96 -0
- package/voice-call-local.js +731 -0
- package/voice-call.js +732 -0
- package/wa-listener.js +354 -0
package/meta-leads.js
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Meta Lead Form Integration Module
|
|
3
|
+
* Handles real-time webhook + polling for Meta lead forms,
|
|
4
|
+
* processes leads through GHL (upsert, pipeline, SMS, email),
|
|
5
|
+
* and fires CAPI events back to Meta.
|
|
6
|
+
*/
|
|
7
|
+
const https = require('https');
|
|
8
|
+
const { sendEvent } = require('./meta-capi');
|
|
9
|
+
|
|
10
|
+
// --- Config (env vars with fallbacks) ---
|
|
11
|
+
const GHL_TOKEN = process.env.GHL_PIT_TOKEN || 'pit-49079755-6cc5-44b2-b4d5-5195e662ed96';
|
|
12
|
+
const GHL_LOCATION_ID = process.env.GHL_LOCATION_ID || 'aZ66KgncoFQZ6kHEJXzl';
|
|
13
|
+
const GHL_PIPELINE_ID = process.env.GHL_PIPELINE_ID || 'LFU6adJ5XgO6VzH7wU02';
|
|
14
|
+
const GHL_STAGE_FORM_SUBMITTED = process.env.GHL_STAGE_FORM_SUBMITTED || 'e3eb0f2f-3604-4610-a4fe-58519349a7d7';
|
|
15
|
+
|
|
16
|
+
const META_ACCESS_TOKEN = process.env.META_ACCESS_TOKEN;
|
|
17
|
+
const META_API_VERSION = 'v21.0';
|
|
18
|
+
const META_VERIFY_TOKEN = 'cmp_lead_verify_2026';
|
|
19
|
+
|
|
20
|
+
const AIVA_FORM_ID = '1502539338103793';
|
|
21
|
+
const SOFTWARE_FORM_ID = '1855096478341715';
|
|
22
|
+
|
|
23
|
+
const BOOKING_LINK = 'https://api.leadconnectorhq.com/widget/booking/brandons-personal-calendar-1';
|
|
24
|
+
|
|
25
|
+
// --- Form config map ---
|
|
26
|
+
const FORM_CONFIG = {
|
|
27
|
+
[AIVA_FORM_ID]: {
|
|
28
|
+
offer: 'aiva',
|
|
29
|
+
tags: ['meta-lead', 'aiva-offer', 'facebook-ads'],
|
|
30
|
+
sms: (firstName) =>
|
|
31
|
+
`Hey ${firstName}! This is Brandon from Conversion Pros. Thanks for your interest in AIVA - your AI personal assistant. I'd love to show you a quick demo. What time works best for a 15-min call this week?`,
|
|
32
|
+
emailSubject: 'Your AI Assistant Demo - Next Steps',
|
|
33
|
+
emailBody: (firstName) =>
|
|
34
|
+
`Hey ${firstName},\n\nThanks so much for your interest in AIVA. I'm really excited to show you what your own AI personal assistant can do for your business.\n\nI'd love to hop on a quick 15-minute call to walk you through a live demo and answer any questions you have.\n\nYou can grab a time that works for you here:\n${BOOKING_LINK}\n\nLooking forward to connecting!\n\nBrandon Burgan\nConversion Marketing Pros`,
|
|
35
|
+
},
|
|
36
|
+
[SOFTWARE_FORM_ID]: {
|
|
37
|
+
offer: 'software',
|
|
38
|
+
tags: ['meta-lead', 'software-offer', 'facebook-ads'],
|
|
39
|
+
sms: (firstName) =>
|
|
40
|
+
`Hey ${firstName}! This is Brandon from Conversion Pros. Thanks for requesting your free business audit. I'd love to learn more about your business and show you what's possible. What time works best for a quick call this week?`,
|
|
41
|
+
emailSubject: 'Your Free Business Audit - Next Steps',
|
|
42
|
+
emailBody: (firstName) =>
|
|
43
|
+
`Hey ${firstName},\n\nThanks for requesting your free business audit. I'm looking forward to learning more about your business and showing you some quick wins we can get you.\n\nLet's set up a quick call so I can ask a few questions and put together a custom plan for you.\n\nYou can book a time here:\n${BOOKING_LINK}\n\nTalk soon!\n\nBrandon Burgan\nConversion Marketing Pros`,
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// --- GHL API helpers ---
|
|
48
|
+
|
|
49
|
+
function ghlRequest(method, path, body) {
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const data = body ? JSON.stringify(body) : null;
|
|
52
|
+
const req = https.request(
|
|
53
|
+
{
|
|
54
|
+
hostname: 'services.leadconnectorhq.com',
|
|
55
|
+
path,
|
|
56
|
+
method,
|
|
57
|
+
headers: {
|
|
58
|
+
Authorization: `Bearer ${GHL_TOKEN}`,
|
|
59
|
+
Version: '2021-07-28',
|
|
60
|
+
'Content-Type': 'application/json',
|
|
61
|
+
...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}),
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
(res) => {
|
|
65
|
+
let raw = '';
|
|
66
|
+
res.on('data', (chunk) => (raw += chunk));
|
|
67
|
+
res.on('end', () => {
|
|
68
|
+
try {
|
|
69
|
+
const parsed = JSON.parse(raw);
|
|
70
|
+
if (res.statusCode >= 400) {
|
|
71
|
+
console.error(`[meta-leads] GHL ${method} ${path} ${res.statusCode}:`, raw);
|
|
72
|
+
return reject(new Error(`GHL ${res.statusCode}: ${raw}`));
|
|
73
|
+
}
|
|
74
|
+
resolve(parsed);
|
|
75
|
+
} catch (e) {
|
|
76
|
+
reject(new Error(`GHL parse error: ${raw}`));
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
);
|
|
81
|
+
req.on('error', reject);
|
|
82
|
+
if (data) req.write(data);
|
|
83
|
+
req.end();
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function upsertContact({ firstName, lastName, email, phone, tags, source }) {
|
|
88
|
+
const body = {
|
|
89
|
+
firstName,
|
|
90
|
+
lastName,
|
|
91
|
+
locationId: GHL_LOCATION_ID,
|
|
92
|
+
source: source || 'Facebook Ads',
|
|
93
|
+
};
|
|
94
|
+
if (email) body.email = email;
|
|
95
|
+
if (phone) body.phone = phone;
|
|
96
|
+
if (tags && tags.length) body.tags = tags;
|
|
97
|
+
|
|
98
|
+
const result = await ghlRequest('POST', '/contacts/upsert', body);
|
|
99
|
+
const contactId = result.contact?.id || result.id;
|
|
100
|
+
console.log(`[meta-leads] Contact upserted: ${contactId} (${firstName} ${lastName})`);
|
|
101
|
+
return { contactId, contact: result.contact || result };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function createOpportunity({ contactId, firstName, lastName, offerLabel }) {
|
|
105
|
+
const body = {
|
|
106
|
+
pipelineId: GHL_PIPELINE_ID,
|
|
107
|
+
locationId: GHL_LOCATION_ID,
|
|
108
|
+
stageId: GHL_STAGE_FORM_SUBMITTED,
|
|
109
|
+
contactId,
|
|
110
|
+
name: `${offerLabel} Lead - ${firstName} ${lastName}`,
|
|
111
|
+
status: 'open',
|
|
112
|
+
};
|
|
113
|
+
const result = await ghlRequest('POST', '/opportunities/upsert', body);
|
|
114
|
+
const oppId = result.opportunity?.id || result.id;
|
|
115
|
+
console.log(`[meta-leads] Opportunity created: ${oppId}`);
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function sendSMS(contactId, message) {
|
|
120
|
+
const result = await ghlRequest('POST', '/conversations/messages', {
|
|
121
|
+
type: 'SMS',
|
|
122
|
+
contactId,
|
|
123
|
+
message,
|
|
124
|
+
});
|
|
125
|
+
console.log(`[meta-leads] SMS sent to contactId=${contactId}`);
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function sendEmail(contactId, subject, body) {
|
|
130
|
+
const result = await ghlRequest('POST', '/conversations/messages', {
|
|
131
|
+
type: 'Email',
|
|
132
|
+
contactId,
|
|
133
|
+
subject,
|
|
134
|
+
message: body,
|
|
135
|
+
emailFrom: 'brandon@conversionmarketingpros.com',
|
|
136
|
+
});
|
|
137
|
+
console.log(`[meta-leads] Email sent to contactId=${contactId}`);
|
|
138
|
+
return result;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// --- Lead parsing ---
|
|
142
|
+
|
|
143
|
+
function parseMetaLeadData(leadData) {
|
|
144
|
+
// Meta sends field_data as array of { name, values }
|
|
145
|
+
const fields = {};
|
|
146
|
+
if (Array.isArray(leadData.field_data)) {
|
|
147
|
+
for (const f of leadData.field_data) {
|
|
148
|
+
fields[f.name] = f.values?.[0] || '';
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Split full_name if present
|
|
153
|
+
let firstName = fields.first_name || '';
|
|
154
|
+
let lastName = fields.last_name || '';
|
|
155
|
+
if (!firstName && fields.full_name) {
|
|
156
|
+
const parts = fields.full_name.trim().split(/\s+/);
|
|
157
|
+
firstName = parts[0] || '';
|
|
158
|
+
lastName = parts.slice(1).join(' ') || '';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
firstName,
|
|
163
|
+
lastName,
|
|
164
|
+
email: fields.email || '',
|
|
165
|
+
phone: fields.phone_number || fields.phone || '',
|
|
166
|
+
leadId: leadData.id,
|
|
167
|
+
createdTime: leadData.created_time,
|
|
168
|
+
rawFields: fields,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// --- Main processing pipeline ---
|
|
173
|
+
|
|
174
|
+
async function processLead(leadData, formId) {
|
|
175
|
+
const config = FORM_CONFIG[formId];
|
|
176
|
+
if (!config) {
|
|
177
|
+
console.warn(`[meta-leads] Unknown form ID: ${formId}, using AIVA defaults`);
|
|
178
|
+
}
|
|
179
|
+
const cfg = config || FORM_CONFIG[AIVA_FORM_ID];
|
|
180
|
+
const offerLabel = cfg.offer === 'aiva' ? 'AIVA' : 'Software';
|
|
181
|
+
|
|
182
|
+
const parsed = parseMetaLeadData(leadData);
|
|
183
|
+
const { firstName, lastName, email, phone } = parsed;
|
|
184
|
+
|
|
185
|
+
console.log(`[meta-leads] Processing ${offerLabel} lead: ${firstName} ${lastName} | email=${email} | phone=${phone}`);
|
|
186
|
+
|
|
187
|
+
const results = { steps: [] };
|
|
188
|
+
|
|
189
|
+
// 1. Upsert contact in GHL
|
|
190
|
+
try {
|
|
191
|
+
const { contactId } = await upsertContact({
|
|
192
|
+
firstName,
|
|
193
|
+
lastName,
|
|
194
|
+
email,
|
|
195
|
+
phone,
|
|
196
|
+
tags: cfg.tags,
|
|
197
|
+
source: 'Facebook Ads',
|
|
198
|
+
});
|
|
199
|
+
results.contactId = contactId;
|
|
200
|
+
results.steps.push('contact_upserted');
|
|
201
|
+
|
|
202
|
+
// 2. Create opportunity
|
|
203
|
+
try {
|
|
204
|
+
await createOpportunity({ contactId, firstName, lastName, offerLabel });
|
|
205
|
+
results.steps.push('opportunity_created');
|
|
206
|
+
} catch (err) {
|
|
207
|
+
console.error(`[meta-leads] Opportunity creation failed:`, err.message);
|
|
208
|
+
results.steps.push('opportunity_failed');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// 3. Send SMS (only if phone present)
|
|
212
|
+
if (phone) {
|
|
213
|
+
try {
|
|
214
|
+
await sendSMS(contactId, cfg.sms(firstName || 'there'));
|
|
215
|
+
results.steps.push('sms_sent');
|
|
216
|
+
} catch (err) {
|
|
217
|
+
console.error(`[meta-leads] SMS failed:`, err.message);
|
|
218
|
+
results.steps.push('sms_failed');
|
|
219
|
+
}
|
|
220
|
+
} else {
|
|
221
|
+
results.steps.push('sms_skipped_no_phone');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// 4. Send email (only if email present)
|
|
225
|
+
if (email) {
|
|
226
|
+
try {
|
|
227
|
+
await sendEmail(contactId, cfg.emailSubject, cfg.emailBody(firstName || 'there'));
|
|
228
|
+
results.steps.push('email_sent');
|
|
229
|
+
} catch (err) {
|
|
230
|
+
console.error(`[meta-leads] Email failed:`, err.message);
|
|
231
|
+
results.steps.push('email_failed');
|
|
232
|
+
}
|
|
233
|
+
} else {
|
|
234
|
+
results.steps.push('email_skipped_no_email');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 5. Fire CAPI Lead event back to Meta
|
|
238
|
+
try {
|
|
239
|
+
const capiResult = await sendEvent('Lead', {
|
|
240
|
+
sourceUrl: 'https://www.conversionmarketingpros.com',
|
|
241
|
+
actionSource: 'system_generated',
|
|
242
|
+
}, {
|
|
243
|
+
email,
|
|
244
|
+
phone,
|
|
245
|
+
firstName,
|
|
246
|
+
lastName,
|
|
247
|
+
});
|
|
248
|
+
results.capiEventId = capiResult.eventId;
|
|
249
|
+
results.steps.push('capi_fired');
|
|
250
|
+
} catch (err) {
|
|
251
|
+
console.error(`[meta-leads] CAPI event failed:`, err.message);
|
|
252
|
+
results.steps.push('capi_failed');
|
|
253
|
+
}
|
|
254
|
+
} catch (err) {
|
|
255
|
+
console.error(`[meta-leads] Contact upsert failed:`, err.message);
|
|
256
|
+
results.steps.push('contact_upsert_failed');
|
|
257
|
+
results.error = err.message;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
console.log(`[meta-leads] Pipeline complete for ${firstName} ${lastName}: ${results.steps.join(', ')}`);
|
|
261
|
+
return results;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// --- Meta Lead Retrieval (polling) ---
|
|
265
|
+
|
|
266
|
+
function metaGraphRequest(path) {
|
|
267
|
+
return new Promise((resolve, reject) => {
|
|
268
|
+
https
|
|
269
|
+
.get(`https://graph.facebook.com/${META_API_VERSION}${path}&access_token=${encodeURIComponent(META_ACCESS_TOKEN)}`, (res) => {
|
|
270
|
+
let data = '';
|
|
271
|
+
res.on('data', (chunk) => (data += chunk));
|
|
272
|
+
res.on('end', () => {
|
|
273
|
+
try {
|
|
274
|
+
const parsed = JSON.parse(data);
|
|
275
|
+
if (parsed.error) {
|
|
276
|
+
console.error(`[meta-leads] Graph API error:`, parsed.error);
|
|
277
|
+
return reject(new Error(parsed.error.message));
|
|
278
|
+
}
|
|
279
|
+
resolve(parsed);
|
|
280
|
+
} catch (e) {
|
|
281
|
+
reject(new Error(`Meta Graph parse error: ${data}`));
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
})
|
|
285
|
+
.on('error', reject);
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function pollFormLeads(formId) {
|
|
290
|
+
console.log(`[meta-leads] Polling form ${formId} for leads...`);
|
|
291
|
+
const result = await metaGraphRequest(`/${formId}/leads?`);
|
|
292
|
+
return result.data || [];
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// --- Express Router ---
|
|
296
|
+
|
|
297
|
+
function createRouter(express) {
|
|
298
|
+
const router = express.Router();
|
|
299
|
+
|
|
300
|
+
// GET - Meta webhook verification
|
|
301
|
+
router.get('/webhook', (req, res) => {
|
|
302
|
+
const mode = req.query['hub.mode'];
|
|
303
|
+
const token = req.query['hub.verify_token'];
|
|
304
|
+
const challenge = req.query['hub.challenge'];
|
|
305
|
+
|
|
306
|
+
if (mode === 'subscribe' && token === META_VERIFY_TOKEN) {
|
|
307
|
+
console.log('[meta-leads] Webhook verified');
|
|
308
|
+
return res.status(200).send(challenge);
|
|
309
|
+
}
|
|
310
|
+
console.warn('[meta-leads] Webhook verification failed');
|
|
311
|
+
return res.status(403).send('Forbidden');
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// POST - Meta sends lead data here
|
|
315
|
+
router.post('/webhook', async (req, res) => {
|
|
316
|
+
// Respond immediately to Meta (they require fast 200)
|
|
317
|
+
res.status(200).json({ status: 'received' });
|
|
318
|
+
|
|
319
|
+
try {
|
|
320
|
+
const body = req.body;
|
|
321
|
+
console.log('[meta-leads] Webhook received:', JSON.stringify(body).slice(0, 500));
|
|
322
|
+
|
|
323
|
+
// Meta sends: { object: "page", entry: [{ id, time, changes: [{ field: "leadgen", value: { ... } }] }] }
|
|
324
|
+
if (body.object === 'page' && Array.isArray(body.entry)) {
|
|
325
|
+
for (const entry of body.entry) {
|
|
326
|
+
const changes = entry.changes || [];
|
|
327
|
+
for (const change of changes) {
|
|
328
|
+
if (change.field === 'leadgen') {
|
|
329
|
+
const leadgenData = change.value;
|
|
330
|
+
const formId = String(leadgenData.form_id || '');
|
|
331
|
+
const leadgenId = leadgenData.leadgen_id;
|
|
332
|
+
|
|
333
|
+
// Fetch full lead data from Meta
|
|
334
|
+
try {
|
|
335
|
+
const leadDetail = await metaGraphRequest(`/${leadgenId}?`);
|
|
336
|
+
await processLead(leadDetail, formId);
|
|
337
|
+
} catch (err) {
|
|
338
|
+
console.error(`[meta-leads] Failed to fetch/process lead ${leadgenId}:`, err.message);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
} catch (err) {
|
|
345
|
+
console.error('[meta-leads] Webhook processing error:', err.message);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
// GET - Poll both forms for recent leads
|
|
350
|
+
router.get('/poll', async (req, res) => {
|
|
351
|
+
try {
|
|
352
|
+
if (!META_ACCESS_TOKEN) {
|
|
353
|
+
return res.status(500).json({ error: 'META_ACCESS_TOKEN not configured' });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const [aivaLeads, softwareLeads] = await Promise.all([
|
|
357
|
+
pollFormLeads(AIVA_FORM_ID).catch((e) => { console.error('[meta-leads] AIVA poll error:', e.message); return []; }),
|
|
358
|
+
pollFormLeads(SOFTWARE_FORM_ID).catch((e) => { console.error('[meta-leads] Software poll error:', e.message); return []; }),
|
|
359
|
+
]);
|
|
360
|
+
|
|
361
|
+
// Process toggle - only process if ?process=true (safety)
|
|
362
|
+
const shouldProcess = req.query.process === 'true';
|
|
363
|
+
const results = { aiva: { count: aivaLeads.length, leads: aivaLeads }, software: { count: softwareLeads.length, leads: softwareLeads }, processed: [] };
|
|
364
|
+
|
|
365
|
+
if (shouldProcess) {
|
|
366
|
+
for (const lead of aivaLeads) {
|
|
367
|
+
try {
|
|
368
|
+
const r = await processLead(lead, AIVA_FORM_ID);
|
|
369
|
+
results.processed.push({ leadId: lead.id, formId: AIVA_FORM_ID, ...r });
|
|
370
|
+
} catch (err) {
|
|
371
|
+
results.processed.push({ leadId: lead.id, formId: AIVA_FORM_ID, error: err.message });
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
for (const lead of softwareLeads) {
|
|
375
|
+
try {
|
|
376
|
+
const r = await processLead(lead, SOFTWARE_FORM_ID);
|
|
377
|
+
results.processed.push({ leadId: lead.id, formId: SOFTWARE_FORM_ID, ...r });
|
|
378
|
+
} catch (err) {
|
|
379
|
+
results.processed.push({ leadId: lead.id, formId: SOFTWARE_FORM_ID, error: err.message });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
res.json(results);
|
|
385
|
+
} catch (err) {
|
|
386
|
+
console.error('[meta-leads] Poll error:', err.message);
|
|
387
|
+
res.status(500).json({ error: err.message });
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
// GET - Health/status check
|
|
392
|
+
router.get('/status', (req, res) => {
|
|
393
|
+
res.json({
|
|
394
|
+
ok: true,
|
|
395
|
+
forms: {
|
|
396
|
+
aiva: AIVA_FORM_ID,
|
|
397
|
+
software: SOFTWARE_FORM_ID,
|
|
398
|
+
},
|
|
399
|
+
pipeline: {
|
|
400
|
+
id: GHL_PIPELINE_ID,
|
|
401
|
+
stageId: GHL_STAGE_FORM_SUBMITTED,
|
|
402
|
+
},
|
|
403
|
+
verifyToken: META_VERIFY_TOKEN,
|
|
404
|
+
metaTokenConfigured: !!META_ACCESS_TOKEN,
|
|
405
|
+
});
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
return router;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
module.exports = { createRouter, processLead, parseMetaLeadData, upsertContact, createOpportunity };
|