cdp-edge 1.18.0 → 1.18.2
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/contracts/api-versions.json +12 -8
- package/dist/commands/install.js +186 -0
- package/dist/commands/setup.js +18 -1
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +23 -23
- package/extracted-skill/tracking-events-generator/agents/browser-tracking.md +172 -72
- package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +20 -0
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +48 -16
- package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/database-agent.md +8 -8
- package/extracted-skill/tracking-events-generator/agents/debug-agent.md +13 -13
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +31 -7
- package/extracted-skill/tracking-events-generator/agents/email-agent.md +27 -0
- package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +205 -0
- package/extracted-skill/tracking-events-generator/agents/google-agent.md +118 -0
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +90 -4
- package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +8 -641
- package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +108 -0
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +68 -8
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +71 -34
- package/extracted-skill/tracking-events-generator/agents/memory-agent.md +98 -0
- package/extracted-skill/tracking-events-generator/agents/performance-agent.md +29 -19
- package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +11 -1
- package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +137 -28
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +7 -8
- package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +63 -0
- package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +100 -5
- package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +100 -0
- package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +58 -5
- package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +16 -16
- package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +140 -25
- package/extracted-skill/tracking-events-generator/contracts/api-versions.json +12 -8
- package/package.json +2 -2
- package/server-edge-tracker/worker.js +53 -8
|
@@ -109,99 +109,199 @@ Implementado via `anti-blocking.js`:
|
|
|
109
109
|
|
|
110
110
|
## 💻 EXEMPLO DE CÓDIGO GERADO
|
|
111
111
|
|
|
112
|
-
### `cdpTrack.js` (SDK Principal)
|
|
112
|
+
### `cdpTrack.js` (SDK Principal — Padrão Multi-Plataforma)
|
|
113
|
+
|
|
114
|
+
> Este é o padrão canônico do cdpTrack SDK para Meta, TikTok e GA4.
|
|
115
|
+
> Cada agente de plataforma injeta seus eventos neste SDK via Browser Tracking Agent.
|
|
113
116
|
|
|
114
117
|
```javascript
|
|
115
118
|
/**
|
|
116
119
|
* cdpTrack SDK - CDP Edge Quantum Tier
|
|
117
120
|
* Browser Tracking SDK Principal
|
|
121
|
+
* Suporta: Meta Pixel, TikTok Pixel, GA4, Pinterest Tag, Reddit Pixel, Spotify Pixel
|
|
118
122
|
*/
|
|
119
123
|
|
|
120
|
-
(function(w
|
|
121
|
-
|
|
122
|
-
w._pbq.push = w._pbq.push || [];
|
|
123
|
-
w._spotify = w._spotify || {};
|
|
124
|
-
|
|
125
|
-
// Carregar configuração
|
|
126
|
-
const config = window.cdpTrack?.config || {};
|
|
124
|
+
(function(w) {
|
|
125
|
+
'use strict';
|
|
127
126
|
|
|
128
|
-
//
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
127
|
+
// ──────────────────────────────────────────────
|
|
128
|
+
// CORE: Geração de event_id único (deduplicação)
|
|
129
|
+
// O mesmo event_id deve ser usado no browser E no servidor (CAPI)
|
|
130
|
+
// ──────────────────────────────────────────────
|
|
131
|
+
function generateEventId() {
|
|
132
|
+
return 'evt_' + Date.now() + '_' + Math.random().toString(36).substring(2, 11);
|
|
132
133
|
}
|
|
133
134
|
|
|
134
|
-
//
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
135
|
+
// ──────────────────────────────────────────────
|
|
136
|
+
// CORE: Envio para Cloudflare Worker (same-domain)
|
|
137
|
+
// Usa /track no mesmo domínio — imune a ad-blockers
|
|
138
|
+
// ──────────────────────────────────────────────
|
|
139
|
+
async function sendToWorker(eventName, payload) {
|
|
140
|
+
const eventId = generateEventId();
|
|
141
|
+
|
|
142
|
+
const body = {
|
|
143
|
+
event: eventName,
|
|
144
|
+
event_id: eventId, // CRÍTICO: mesmo ID usado nas CAPIs
|
|
145
|
+
url: window.location.href,
|
|
146
|
+
referrer: document.referrer,
|
|
147
|
+
timestamp: Date.now(),
|
|
148
|
+
...payload
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
try {
|
|
152
|
+
// Tentativa primária: fetch
|
|
153
|
+
await fetch('/track', {
|
|
154
|
+
method: 'POST',
|
|
155
|
+
headers: { 'Content-Type': 'application/json' },
|
|
156
|
+
body: JSON.stringify(body),
|
|
157
|
+
keepalive: true
|
|
152
158
|
});
|
|
159
|
+
} catch (_) {
|
|
160
|
+
// Fallback: Beacon API (funciona mesmo no unload da página)
|
|
161
|
+
navigator.sendBeacon('/track', JSON.stringify(body));
|
|
153
162
|
}
|
|
154
|
-
};
|
|
155
163
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
w._spotify.trackEvent('ViewContent', {
|
|
159
|
-
content_name: contentName,
|
|
160
|
-
content_id: contentId,
|
|
161
|
-
...params
|
|
162
|
-
});
|
|
163
|
-
};
|
|
164
|
+
return eventId;
|
|
165
|
+
}
|
|
164
166
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
};
|
|
167
|
+
// ──────────────────────────────────────────────
|
|
168
|
+
// CORE: Captura de cookies first-party
|
|
169
|
+
// ──────────────────────────────────────────────
|
|
170
|
+
function getCookie(name) {
|
|
171
|
+
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
|
|
172
|
+
return match ? decodeURIComponent(match[2]) : null;
|
|
173
|
+
}
|
|
173
174
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
175
|
+
// ──────────────────────────────────────────────
|
|
176
|
+
// CORE: Captura de click IDs da URL (Meta, TikTok, Google)
|
|
177
|
+
// ──────────────────────────────────────────────
|
|
178
|
+
function getClickIds() {
|
|
179
|
+
const params = new URLSearchParams(window.location.search);
|
|
180
|
+
return {
|
|
181
|
+
fbclid: params.get('fbclid') || getCookie('fbclid') || null,
|
|
182
|
+
ttclid: params.get('ttclid') || getCookie('ttclid') || null,
|
|
183
|
+
gclid: params.get('gclid') || null,
|
|
184
|
+
gbraid: params.get('gbraid') || null,
|
|
185
|
+
wbraid: params.get('wbraid') || null,
|
|
186
|
+
fbp: getCookie('_fbp') || null,
|
|
187
|
+
fbc: getCookie('_fbc') || null,
|
|
188
|
+
ttp: getCookie('_ttp') || null,
|
|
189
|
+
uid: getCookie('_cdp_uid') || null // Identity Graph first-party cookie
|
|
190
|
+
};
|
|
191
|
+
}
|
|
183
192
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
193
|
+
// ──────────────────────────────────────────────
|
|
194
|
+
// API PÚBLICA
|
|
195
|
+
// ──────────────────────────────────────────────
|
|
196
|
+
const cdpTrack = {
|
|
197
|
+
generateEventId,
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Rastrear evento genérico — enviado para o Worker
|
|
201
|
+
* O Worker despacha para Meta CAPI, GA4 MP, TikTok Events API etc.
|
|
202
|
+
*
|
|
203
|
+
* @param {string} eventName - Nome do evento (ex: 'Lead', 'Purchase', 'PageView')
|
|
204
|
+
* @param {Object} params - Parâmetros adicionais do evento
|
|
205
|
+
*/
|
|
206
|
+
track(eventName, params = {}) {
|
|
207
|
+
const clickIds = getClickIds();
|
|
208
|
+
return sendToWorker(eventName, { ...clickIds, ...params });
|
|
209
|
+
},
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Rastrear Lead (captura de formulário)
|
|
213
|
+
* Enviar dados PII crus — o Worker faz SHA-256 no servidor
|
|
214
|
+
*/
|
|
215
|
+
trackLead(userData = {}) {
|
|
216
|
+
const clickIds = getClickIds();
|
|
217
|
+
return sendToWorker('Lead', {
|
|
218
|
+
...clickIds,
|
|
219
|
+
email: userData.email || null, // Worker aplica SHA-256
|
|
220
|
+
phone: userData.phone || null, // Worker aplica E.164 + SHA-256
|
|
221
|
+
first_name: userData.first_name || null,
|
|
222
|
+
last_name: userData.last_name || null,
|
|
223
|
+
city: userData.city || null,
|
|
224
|
+
state: userData.state || null,
|
|
225
|
+
zip: userData.zip || null,
|
|
226
|
+
country: userData.country || 'BR'
|
|
227
|
+
});
|
|
228
|
+
},
|
|
192
229
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
230
|
+
/**
|
|
231
|
+
* Rastrear Purchase (confirmação de compra)
|
|
232
|
+
*/
|
|
233
|
+
trackPurchase(orderData = {}) {
|
|
234
|
+
const clickIds = getClickIds();
|
|
235
|
+
return sendToWorker('Purchase', {
|
|
236
|
+
...clickIds,
|
|
237
|
+
value: orderData.value || 0,
|
|
238
|
+
currency: orderData.currency || 'BRL',
|
|
239
|
+
order_id: orderData.order_id || null,
|
|
240
|
+
content_name: orderData.product || null
|
|
241
|
+
});
|
|
242
|
+
},
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Rastrear PageView — chamar no load da página
|
|
246
|
+
*/
|
|
247
|
+
trackPageView() {
|
|
248
|
+
const clickIds = getClickIds();
|
|
249
|
+
return sendToWorker('PageView', { ...clickIds });
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Rastrear InitiateCheckout
|
|
254
|
+
*/
|
|
255
|
+
trackInitiateCheckout(checkoutData = {}) {
|
|
256
|
+
const clickIds = getClickIds();
|
|
257
|
+
return sendToWorker('InitiateCheckout', {
|
|
258
|
+
...clickIds,
|
|
259
|
+
value: checkoutData.value || 0,
|
|
260
|
+
currency: checkoutData.currency || 'BRL'
|
|
261
|
+
});
|
|
262
|
+
}
|
|
200
263
|
};
|
|
201
264
|
|
|
202
|
-
|
|
265
|
+
// Expor no window
|
|
266
|
+
w.cdpTrack = cdpTrack;
|
|
267
|
+
|
|
268
|
+
// Auto page_view no load
|
|
269
|
+
if (document.readyState === 'loading') {
|
|
270
|
+
document.addEventListener('DOMContentLoaded', () => cdpTrack.trackPageView());
|
|
271
|
+
} else {
|
|
272
|
+
cdpTrack.trackPageView();
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
})(window);
|
|
203
276
|
```
|
|
204
277
|
|
|
278
|
+
### Uso típico no HTML do cliente
|
|
279
|
+
|
|
280
|
+
```html
|
|
281
|
+
<!-- 1. Carregar o SDK -->
|
|
282
|
+
<script src="/tracking/cdpTrack.js"></script>
|
|
283
|
+
|
|
284
|
+
<!-- 2. Rastrear lead ao submeter formulário -->
|
|
285
|
+
<script>
|
|
286
|
+
document.getElementById('lead-form').addEventListener('submit', function(e) {
|
|
287
|
+
cdpTrack.trackLead({
|
|
288
|
+
email: document.getElementById('email').value,
|
|
289
|
+
phone: document.getElementById('phone').value,
|
|
290
|
+
first_name: document.getElementById('name').value
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
</script>
|
|
294
|
+
|
|
295
|
+
<!-- 3. Rastrear checkout (botão de compra) -->
|
|
296
|
+
<script>
|
|
297
|
+
document.getElementById('buy-btn').addEventListener('click', function() {
|
|
298
|
+
cdpTrack.trackInitiateCheckout({ value: 97.00, currency: 'BRL' });
|
|
299
|
+
});
|
|
300
|
+
</script>
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
> **Nota:** O Worker recebe os dados crus, aplica SHA-256, e despacha para Meta CAPI v22.0, GA4 MP, TikTok Events API v1.3 e demais plataformas configuradas — tudo em paralelo via `Promise.allSettled`.
|
|
304
|
+
|
|
205
305
|
---
|
|
206
306
|
|
|
207
307
|
## 🔧 INTEGRAÇÃO COM OUTROS AGENTES
|
|
@@ -2044,6 +2044,26 @@ async function handleGetCurrentPolicy(request, env) {
|
|
|
2044
2044
|
- **security-enterprise-agent.md**: Usa encryption de PII para LGPD/GDPR
|
|
2045
2045
|
- **attribution-agent.md**: Respeita consentimento para analytics e marketing
|
|
2046
2046
|
- **master-orchestrator.md**: Implementa middleware de consentimento antes de tracking
|
|
2047
|
+
- **validator-agent.md**: O Compliance Agent DEVE ser consultado pelo Validator Agent para verificar conformidade de PII. Fluxo:
|
|
2048
|
+
|
|
2049
|
+
```
|
|
2050
|
+
validator-agent (auditoria do código gerado)
|
|
2051
|
+
└─► checkComplianceCompliance(generatedCode)
|
|
2052
|
+
├─ Verificar: SHA-256 aplicado em todos os campos PII (em, ph, fn, ln)?
|
|
2053
|
+
├─ Verificar: Google Consent Mode v2 implementado (ad_storage, analytics_storage)?
|
|
2054
|
+
├─ Verificar: url_passthrough: true ativo?
|
|
2055
|
+
├─ Verificar: PII nunca logada em plaintext?
|
|
2056
|
+
└─ Verificar: opt-in explícito antes de tracking de marketing?
|
|
2057
|
+
|
|
2058
|
+
// No validator-agent, chamar:
|
|
2059
|
+
const complianceCheck = await validateComplianceRequirements(generatedBrowserCode, generatedWorkerCode);
|
|
2060
|
+
if (!complianceCheck.passed) {
|
|
2061
|
+
// Bloquear entrega e reportar issues ao Master Orchestrator
|
|
2062
|
+
return { status: 'BLOCKED', issues: complianceCheck.issues };
|
|
2063
|
+
}
|
|
2064
|
+
```
|
|
2065
|
+
|
|
2066
|
+
- **google-agent.md**: Consent Mode v2 gerado por este agente valida conformidade detectada pelo Compliance Agent
|
|
2047
2067
|
|
|
2048
2068
|
---
|
|
2049
2069
|
|
|
@@ -12,6 +12,38 @@ Você é o **Agente de Integração CRM do CDP Edge**. Sua responsabilidade: **c
|
|
|
12
12
|
|
|
13
13
|
---
|
|
14
14
|
|
|
15
|
+
## 🔗 FLUXO DE ATIVAÇÃO (Como este agente é chamado)
|
|
16
|
+
|
|
17
|
+
O CRM Integration Agent é ativado pelo **Webhook Agent** após confirmação de compra ou captura de lead:
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
Webhook Agent (purchase confirmado)
|
|
21
|
+
└─► ctx.waitUntil(syncToCRM(env, 'purchase', payload))
|
|
22
|
+
│
|
|
23
|
+
├─ Criar/atualizar contato no CRM com status 'customer'
|
|
24
|
+
├─ Criar negócio/oportunidade com valor da compra
|
|
25
|
+
└─ Atualizar D1 com CRM_CONTACT_ID para rastreamento futuro
|
|
26
|
+
|
|
27
|
+
Webhook Agent (lead capturado via /track)
|
|
28
|
+
└─► ctx.waitUntil(syncToCRM(env, 'lead', payload))
|
|
29
|
+
│
|
|
30
|
+
├─ Criar contato no CRM com status 'lead'
|
|
31
|
+
└─ Registrar no D1 para cruzamento futuro
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
**Assinatura da função exportada (injetada no Worker):**
|
|
35
|
+
|
|
36
|
+
```javascript
|
|
37
|
+
// Injetada no worker.js pelo CRM Integration Agent
|
|
38
|
+
export async function syncToCRM(env, eventType, payload) {
|
|
39
|
+
// eventType: 'lead' | 'purchase' | 'checkout_abandoned'
|
|
40
|
+
// payload: { email, name, product, value, order_id, phone }
|
|
41
|
+
// Retorna: { success: boolean, crm_contact_id: string | null }
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
15
47
|
## 🎯 OBJETIVO PRINCIPAL
|
|
16
48
|
|
|
17
49
|
Implementar **integração bidirecional** entre CDP Edge D1 e CRMs externos, permitindo que dados de tracking (leads, purchases, user journeys) fluam automaticamente para sistemas de vendas, marketing e atendimento, eliminando importações manuais e maximizando conversão.
|
|
@@ -612,8 +644,8 @@ export const PURCHASE_FIELD_MAPPINGS = {
|
|
|
612
644
|
|
|
613
645
|
```javascript
|
|
614
646
|
// Sincronizar leads do D1 para CRM em batch
|
|
615
|
-
export async function syncLeadsToCRM(hours = 24, batchSize = 50) {
|
|
616
|
-
const leads = await DB.prepare(`
|
|
647
|
+
export async function syncLeadsToCRM(env, hours = 24, batchSize = 50) {
|
|
648
|
+
const leads = await env.DB.prepare(`
|
|
617
649
|
SELECT * FROM leads
|
|
618
650
|
WHERE created_at > datetime('now', '-${hours} hours')
|
|
619
651
|
ORDER BY created_at DESC
|
|
@@ -699,8 +731,8 @@ async function sendLeadsBatchToCRM(leadsBatch) {
|
|
|
699
731
|
};
|
|
700
732
|
}
|
|
701
733
|
|
|
702
|
-
async function markLeadAsSynced(leadId) {
|
|
703
|
-
await DB.prepare(`
|
|
734
|
+
async function markLeadAsSynced(leadId, env) {
|
|
735
|
+
await env.DB.prepare(`
|
|
704
736
|
UPDATE leads SET crm_synced = 1, crm_synced_at = datetime('now')
|
|
705
737
|
WHERE id = ?
|
|
706
738
|
`).bind(leadId).run();
|
|
@@ -711,8 +743,8 @@ async function markLeadAsSynced(leadId) {
|
|
|
711
743
|
|
|
712
744
|
```javascript
|
|
713
745
|
// Sincronizar compras do D1 para CRM em batch
|
|
714
|
-
export async function syncPurchasesToCRM(hours = 24, batchSize = 20) {
|
|
715
|
-
const purchases = await DB.prepare(`
|
|
746
|
+
export async function syncPurchasesToCRM(env, hours = 24, batchSize = 20) {
|
|
747
|
+
const purchases = await env.DB.prepare(`
|
|
716
748
|
SELECT p.*, l.email
|
|
717
749
|
FROM purchases p
|
|
718
750
|
LEFT JOIN leads l ON p.lead_id = l.id
|
|
@@ -800,8 +832,8 @@ async function sendPurchasesBatchToCRM(purchasesBatch) {
|
|
|
800
832
|
};
|
|
801
833
|
}
|
|
802
834
|
|
|
803
|
-
async function markPurchaseAsSynced(purchaseId) {
|
|
804
|
-
await DB.prepare(`
|
|
835
|
+
async function markPurchaseAsSynced(purchaseId, env) {
|
|
836
|
+
await env.DB.prepare(`
|
|
805
837
|
UPDATE purchases SET crm_synced = 1, crm_synced_at = datetime('now')
|
|
806
838
|
WHERE id = ?
|
|
807
839
|
`).bind(purchaseId).run();
|
|
@@ -853,8 +885,8 @@ export async function handleCRMWebhook(request, env) {
|
|
|
853
885
|
}
|
|
854
886
|
}
|
|
855
887
|
|
|
856
|
-
async function updateLeadStageFromCRM(payload) {
|
|
857
|
-
await DB.prepare(`
|
|
888
|
+
async function updateLeadStageFromCRM(payload, env) {
|
|
889
|
+
await env.DB.prepare(`
|
|
858
890
|
UPDATE leads SET crm_stage = ?, crm_stage_updated_at = datetime('now')
|
|
859
891
|
WHERE email = ?
|
|
860
892
|
`).bind(payload.stage, payload.email).run();
|
|
@@ -862,8 +894,8 @@ async function updateLeadStageFromCRM(payload) {
|
|
|
862
894
|
console.log(`Stage do lead ${payload.email} atualizado para: ${payload.stage}`);
|
|
863
895
|
}
|
|
864
896
|
|
|
865
|
-
async function updateDealStatusFromCRM(payload) {
|
|
866
|
-
await DB.prepare(`
|
|
897
|
+
async function updateDealStatusFromCRM(payload, env) {
|
|
898
|
+
await env.DB.prepare(`
|
|
867
899
|
UPDATE purchases SET crm_deal_status = ?, crm_deal_status_updated_at = datetime('now')
|
|
868
900
|
WHERE transaction_id = ?
|
|
869
901
|
`).bind(payload.status, payload.transaction_id).run();
|
|
@@ -871,8 +903,8 @@ async function updateDealStatusFromCRM(payload) {
|
|
|
871
903
|
console.log(`Status da compra ${payload.transaction_id} atualizado para: ${payload.status}`);
|
|
872
904
|
}
|
|
873
905
|
|
|
874
|
-
async function updateLeadScoreFromCRM(payload) {
|
|
875
|
-
await DB.prepare(`
|
|
906
|
+
async function updateLeadScoreFromCRM(payload, env) {
|
|
907
|
+
await env.DB.prepare(`
|
|
876
908
|
UPDATE leads SET lead_score = ?, lead_score_updated_at = datetime('now')
|
|
877
909
|
WHERE email = ?
|
|
878
910
|
`).bind(payload.lead_score, payload.email).run();
|
|
@@ -979,7 +1011,7 @@ export async function registerCRMWebhooks(crmType, webhookUrl) {
|
|
|
979
1011
|
};
|
|
980
1012
|
|
|
981
1013
|
// Salvar configuração no D1
|
|
982
|
-
await DB.prepare(`
|
|
1014
|
+
await env.DB.prepare(`
|
|
983
1015
|
INSERT INTO crm_webhook_config (webhook_url, crm_type, events, signature_enabled)
|
|
984
1016
|
VALUES (?, ?, ?, ?)
|
|
985
1017
|
`).bind(
|
|
@@ -994,7 +1026,7 @@ export async function registerCRMWebhooks(crmType, webhookUrl) {
|
|
|
994
1026
|
|
|
995
1027
|
// Endpoint de saúde da integração
|
|
996
1028
|
export async function handleCRMHealthCheck(request, env) {
|
|
997
|
-
const stats = await DB.prepare(`
|
|
1029
|
+
const stats = await env.DB.prepare(`
|
|
998
1030
|
SELECT
|
|
999
1031
|
COUNT(*) as total_leads,
|
|
1000
1032
|
COUNT(CASE WHEN crm_synced = 1 THEN 1 END) as synced_leads,
|
|
@@ -96,16 +96,16 @@ Definir o Dashboard como um **Centro de Comando de Dados** que equilibra:
|
|
|
96
96
|
**Implementação:**
|
|
97
97
|
```javascript
|
|
98
98
|
// Carregar dados do cache
|
|
99
|
-
const fetchMetrics = async (forceRefresh = false) => {
|
|
99
|
+
const fetchMetrics = async (env, forceRefresh = false) => {
|
|
100
100
|
const cacheKey = 'dashboard_metrics';
|
|
101
|
-
const cached = await
|
|
101
|
+
const cached = await env.GEO_CACHE.get(cacheKey);
|
|
102
102
|
|
|
103
103
|
if (cached && !forceRefresh) {
|
|
104
104
|
return JSON.parse(cached);
|
|
105
105
|
}
|
|
106
106
|
|
|
107
107
|
// Cache miss ou refresh forçado — consultar D1
|
|
108
|
-
const metrics = await DB.prepare(`
|
|
108
|
+
const metrics = await env.DB.prepare(`
|
|
109
109
|
SELECT
|
|
110
110
|
AVG(heat_score) as avg_heat,
|
|
111
111
|
COUNT(DISTINCT fingerprint) as total_users,
|
|
@@ -115,7 +115,7 @@ const fetchMetrics = async (forceRefresh = false) => {
|
|
|
115
115
|
`).all();
|
|
116
116
|
|
|
117
117
|
// Salvar no KV com TTL de 1 hora
|
|
118
|
-
await
|
|
118
|
+
await env.GEO_CACHE.put(cacheKey, JSON.stringify(metrics), { expirationTtl: 3600 });
|
|
119
119
|
|
|
120
120
|
return metrics;
|
|
121
121
|
};
|
|
@@ -217,13 +217,13 @@ export const DASHBOARD_API = {
|
|
|
217
217
|
};
|
|
218
218
|
|
|
219
219
|
// HANDLER DE SINCronizaÇÃO (atualização de cache)
|
|
220
|
-
export async function invalidateCache(domain, pattern) {
|
|
220
|
+
export async function invalidateCache(domain, pattern, env) {
|
|
221
221
|
const deletePattern = `${domain}:${pattern}`;
|
|
222
222
|
|
|
223
223
|
// Deletar do KV
|
|
224
|
-
const keys = await
|
|
224
|
+
const keys = await env.GEO_CACHE.list({ prefix: deletePattern });
|
|
225
225
|
for (const key of keys.keys) {
|
|
226
|
-
await
|
|
226
|
+
await env.GEO_CACHE.delete(key);
|
|
227
227
|
}
|
|
228
228
|
|
|
229
229
|
// Retornar contagem
|
|
@@ -78,7 +78,7 @@ crons = ["0 2 * * 7", "0 3 1 * *"]
|
|
|
78
78
|
- **ID:** `SEU_D1_DATABASE_ID`
|
|
79
79
|
- **Região:** ENAM (US East)
|
|
80
80
|
- **Engine:** SQLite (Cloudflare D1)
|
|
81
|
-
- **Tabelas ativas:**
|
|
81
|
+
- **Tabelas ativas:** 24 (core: 13, migrate-v6: 1, Enterprise Fases 1-4: 10)
|
|
82
82
|
|
|
83
83
|
### Schema Completo (Produção)
|
|
84
84
|
|
|
@@ -259,7 +259,7 @@ CREATE INDEX IF NOT EXISTS idx_wa_ctwa_clid ON whatsapp_contacts(ctwa_clid);
|
|
|
259
259
|
CREATE INDEX IF NOT EXISTS idx_wa_created_at ON whatsapp_contacts(created_at);
|
|
260
260
|
```
|
|
261
261
|
> **Migration:** `migrate-v6.sql` — aplicar com `wrangler d1 execute cdp-edge-db --file=migrate-v6.sql --remote`
|
|
262
|
-
> **Tabelas ativas após v6:**
|
|
262
|
+
> **Tabelas ativas após v6:** 14 (core: 13 + whatsapp_contacts)
|
|
263
263
|
|
|
264
264
|
---
|
|
265
265
|
|
|
@@ -313,9 +313,9 @@ ctx.waitUntil(
|
|
|
313
313
|
|
|
314
314
|
---
|
|
315
315
|
|
|
316
|
-
## 📬 BINDING 2 — QUEUES (`env.
|
|
316
|
+
## 📬 BINDING 2 — QUEUES (`env.RETRY_QUEUE`) — ✅ Configurado
|
|
317
317
|
|
|
318
|
-
> **Status:**
|
|
318
|
+
> **Status:** Ativo em produção — `wrangler.toml` com `RETRY_QUEUE` binding e consumer configurados.
|
|
319
319
|
|
|
320
320
|
### Configuração no `wrangler.toml`
|
|
321
321
|
```toml
|
|
@@ -387,9 +387,9 @@ Queue Consumer (assíncrono)
|
|
|
387
387
|
|
|
388
388
|
---
|
|
389
389
|
|
|
390
|
-
## 🗂️ BINDING 3 — KV NAMESPACE (`env.GEO_CACHE`) —
|
|
390
|
+
## 🗂️ BINDING 3 — KV NAMESPACE (`env.GEO_CACHE`) — ✅ Configurado
|
|
391
391
|
|
|
392
|
-
> **Status:**
|
|
392
|
+
> **Status:** Ativo em produção — usado para geo cache, fraud blocklist, fraud velocity counters e A/B test cache.
|
|
393
393
|
|
|
394
394
|
### Configuração no `wrangler.toml`
|
|
395
395
|
```toml
|
|
@@ -548,7 +548,7 @@ async function runIntelligenceAgent(cron, env) {
|
|
|
548
548
|
| `META_TEST_CODE` | ⚠️ Reconfigurar | Só testes | meta-agent |
|
|
549
549
|
| `META_AD_ACCOUNT_ID` | ⚠️ Reconfigurar | Customer Match | meta-agent |
|
|
550
550
|
| `META_AUDIENCE_ID` | ⚠️ Reconfigurar | Customer Match | meta-agent |
|
|
551
|
-
| `
|
|
551
|
+
| `WHATSAPP_ACCESS_TOKEN` | ⚠️ Reconfigurar | WhatsApp | whatsapp-agent |
|
|
552
552
|
| `WHATSAPP_PHONE_NUMBER_ID` | ⚠️ Reconfigurar | WhatsApp | whatsapp-agent |
|
|
553
553
|
| `RESEND_API_KEY` | ⚠️ Reconfigurar | Email | email-agent |
|
|
554
554
|
| `RESEND_FROM_EMAIL` | ⚠️ Reconfigurar | Email | email-agent |
|
|
@@ -560,7 +560,7 @@ async function runIntelligenceAgent(cron, env) {
|
|
|
560
560
|
wrangler secret put META_ACCESS_TOKEN
|
|
561
561
|
wrangler secret put GA4_API_SECRET
|
|
562
562
|
wrangler secret put TIKTOK_ACCESS_TOKEN
|
|
563
|
-
wrangler secret put
|
|
563
|
+
wrangler secret put WHATSAPP_ACCESS_TOKEN
|
|
564
564
|
wrangler secret put WHATSAPP_PHONE_NUMBER_ID
|
|
565
565
|
wrangler secret put RESEND_API_KEY
|
|
566
566
|
wrangler secret put RESEND_FROM_EMAIL
|
|
@@ -56,9 +56,9 @@ export function logWorker(level, category, message, context = {}) {
|
|
|
56
56
|
console.log(`[${level}] [${category}] ${message}`, JSON.stringify(context));
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
async function persistLogEntry(logEntry) {
|
|
59
|
+
async function persistLogEntry(env, logEntry) {
|
|
60
60
|
try {
|
|
61
|
-
await DB.prepare(`
|
|
61
|
+
await env.DB.prepare(`
|
|
62
62
|
INSERT INTO worker_logs (timestamp, level, category, message, context, session_id, request_id)
|
|
63
63
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
64
64
|
`).bind(
|
|
@@ -82,7 +82,7 @@ async function dispatchEventToMeta(event, userContext) {
|
|
|
82
82
|
try {
|
|
83
83
|
const response = await fetch('https://graph.facebook.com/v22.0/events', {
|
|
84
84
|
method: 'POST',
|
|
85
|
-
headers: { 'Authorization': `Bearer ${META_ACCESS_TOKEN}` },
|
|
85
|
+
headers: { 'Authorization': `Bearer ${env.META_ACCESS_TOKEN}` },
|
|
86
86
|
body: JSON.stringify(event)
|
|
87
87
|
});
|
|
88
88
|
|
|
@@ -221,7 +221,7 @@ cdpTrack.track = function(eventName, params) {
|
|
|
221
221
|
};
|
|
222
222
|
|
|
223
223
|
// Enviar para Worker
|
|
224
|
-
fetch('/
|
|
224
|
+
fetch('/track', {
|
|
225
225
|
method: 'POST',
|
|
226
226
|
headers: { 'Content-Type': 'application/json' },
|
|
227
227
|
body: JSON.stringify(eventPayload)
|
|
@@ -331,7 +331,7 @@ export async function handleDebugRequest(request, env) {
|
|
|
331
331
|
}
|
|
332
332
|
|
|
333
333
|
async function getApiHealth(platform) {
|
|
334
|
-
const recentFailures = await DB.prepare(`
|
|
334
|
+
const recentFailures = await env.DB.prepare(`
|
|
335
335
|
SELECT
|
|
336
336
|
COUNT(*) as failure_count,
|
|
337
337
|
MAX(created_at) as last_failure_at
|
|
@@ -339,7 +339,7 @@ async function getApiHealth(platform) {
|
|
|
339
339
|
WHERE platform = ? AND created_at > datetime('now', '-1 hour')
|
|
340
340
|
`).bind(platform).get();
|
|
341
341
|
|
|
342
|
-
const recentSuccesses = await DB.prepare(`
|
|
342
|
+
const recentSuccesses = await env.DB.prepare(`
|
|
343
343
|
SELECT COUNT(*) as success_count
|
|
344
344
|
FROM events_log
|
|
345
345
|
WHERE platform = ? AND status = 'success' AND created_at > datetime('now', '-1 hour')
|
|
@@ -394,7 +394,7 @@ export async function handleHealthCheck(request, env) {
|
|
|
394
394
|
}
|
|
395
395
|
|
|
396
396
|
async function getSimpleApiHealth(platform) {
|
|
397
|
-
const lastSuccess = await DB.prepare(`
|
|
397
|
+
const lastSuccess = await env.DB.prepare(`
|
|
398
398
|
SELECT created_at
|
|
399
399
|
FROM events_log
|
|
400
400
|
WHERE platform = ? AND status = 'success'
|
|
@@ -402,7 +402,7 @@ async function getSimpleApiHealth(platform) {
|
|
|
402
402
|
LIMIT 1
|
|
403
403
|
`).bind(platform).get();
|
|
404
404
|
|
|
405
|
-
const lastFailure = await DB.prepare(`
|
|
405
|
+
const lastFailure = await env.DB.prepare(`
|
|
406
406
|
SELECT created_at
|
|
407
407
|
FROM api_failures
|
|
408
408
|
WHERE platform = ?
|
|
@@ -433,7 +433,7 @@ export async function handleEventsLogRequest(request, env) {
|
|
|
433
433
|
const limit = parseInt(url.searchParams.get('limit') || '50');
|
|
434
434
|
const hours = parseInt(url.searchParams.get('hours') || '24');
|
|
435
435
|
|
|
436
|
-
const events = await DB.prepare(`
|
|
436
|
+
const events = await env.DB.prepare(`
|
|
437
437
|
SELECT
|
|
438
438
|
event_name,
|
|
439
439
|
platform,
|
|
@@ -485,7 +485,7 @@ export async function handleEventsLogRequest(request, env) {
|
|
|
485
485
|
|
|
486
486
|
- [ ] **Envio de eventos para Worker:**
|
|
487
487
|
- [ ] Verificar Network tab em Developer Tools
|
|
488
|
-
- [ ] Confirmar requisição para `/
|
|
488
|
+
- [ ] Confirmar requisição para `/track`
|
|
489
489
|
- [ ] Verificar status da resposta (deve ser 200 OK)
|
|
490
490
|
- [ ] Verificar payload enviado (deve conter event_name, params, timestamp)
|
|
491
491
|
|
|
@@ -1033,7 +1033,7 @@ export async function handleEventsLogRequest(request, env) {
|
|
|
1033
1033
|
const limit = parseInt(url.searchParams.get('limit') || '50');
|
|
1034
1034
|
const hours = parseInt(url.searchParams.get('hours') || '24');
|
|
1035
1035
|
|
|
1036
|
-
const events = await DB.prepare(`
|
|
1036
|
+
const events = await env.DB.prepare(`
|
|
1037
1037
|
SELECT event_name, platform, status, error_message, created_at
|
|
1038
1038
|
FROM events_log
|
|
1039
1039
|
WHERE created_at > datetime('now', '-${hours} hours')
|
|
@@ -1057,7 +1057,7 @@ export async function handleBrowserLogs(request, env) {
|
|
|
1057
1057
|
|
|
1058
1058
|
// Persistir logs do browser no D1
|
|
1059
1059
|
for (const log of logs) {
|
|
1060
|
-
await DB.prepare(`
|
|
1060
|
+
await env.DB.prepare(`
|
|
1061
1061
|
INSERT INTO browser_logs (timestamp, level, category, message, context, session_id, page_url)
|
|
1062
1062
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
1063
1063
|
`).bind(
|
|
@@ -1182,7 +1182,7 @@ window.pbDebugLogger = logger;
|
|
|
1182
1182
|
**Possíveis Causas:**
|
|
1183
1183
|
|
|
1184
1184
|
1. **Evento não está sendo enviado para a plataforma**
|
|
1185
|
-
- Verificar se `/
|
|
1185
|
+
- Verificar se `/track` está recebendo o evento
|
|
1186
1186
|
- Consultar `/api/events-log` para ver se evento foi processado
|
|
1187
1187
|
- Verificar logs do Worker: `wrangler tail`
|
|
1188
1188
|
|