cdp-edge 2.5.1 → 2.5.3
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 +23 -3
- package/contracts/agent-versions.json +383 -83
- package/extracted-skill/tracking-events-generator/agents/ab-ltv-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ab-testing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +18 -18
- package/extracted-skill/tracking-events-generator/agents/bidding-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/bing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/code-guardian-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +10 -10
- package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/database-agent.md +17 -25
- package/extracted-skill/tracking-events-generator/agents/debug-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +18 -1
- package/extracted-skill/tracking-events-generator/agents/domain-setup-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/email-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/fraud-detection-agent.md +2 -0
- package/extracted-skill/tracking-events-generator/agents/google-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +23 -29
- package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/localization-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +16 -16
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +13 -13
- package/extracted-skill/tracking-events-generator/agents/memory-agent.md +14 -14
- package/extracted-skill/tracking-events-generator/agents/meta-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/page-analyzer.md +1 -0
- package/extracted-skill/tracking-events-generator/agents/performance-agent.md +12 -12
- package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/pinterest-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/r2-setup-agent.md +8 -8
- package/extracted-skill/tracking-events-generator/agents/reddit-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +21 -21
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +15 -15
- package/extracted-skill/tracking-events-generator/agents/spotify-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/validator-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +9 -9
- package/package.json +10 -10
- package/server-edge-tracker/.client.env +5 -0
- package/server-edge-tracker/modules/dispatch/whatsapp.ts +15 -15
- package/server-edge-tracker/schema-utm.sql +5 -3
- package/server-edge-tracker/wrangler.toml +1 -1
- package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +0 -10
- /package/server-edge-tracker/{deploy-client.js → deploy-client.cjs} +0 -0
|
@@ -39,7 +39,7 @@ POST /api/ltv/ab-test/winner → aplica vencedor ao LTV padrão
|
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
**Upstream (de onde recebe dados):**
|
|
42
|
-
- `
|
|
42
|
+
- `index.ts → predictLtv()` — ponto de interceptação do teste
|
|
43
43
|
- `webhook events` — fonte verdade do revenue real para scoring
|
|
44
44
|
|
|
45
45
|
**Downstream (quem consome outputs):**
|
|
@@ -44,7 +44,7 @@ Browser (Cliente) Worker (Server-Side) APIs (Meta/Google/TikT
|
|
|
44
44
|
|
|
45
45
|
**Uso:** Campanhas de última milha, conversão rápida.
|
|
46
46
|
|
|
47
|
-
```
|
|
47
|
+
```typescript
|
|
48
48
|
function lastClickAttribution(touchpoints) {
|
|
49
49
|
if (!touchpoints || touchpoints.length === 0) return [];
|
|
50
50
|
|
|
@@ -69,7 +69,7 @@ function lastClickAttribution(touchpoints) {
|
|
|
69
69
|
|
|
70
70
|
**Uso:** Brand awareness, campanhas de descoberta.
|
|
71
71
|
|
|
72
|
-
```
|
|
72
|
+
```typescript
|
|
73
73
|
function firstClickAttribution(touchpoints) {
|
|
74
74
|
if (!touchpoints || touchpoints.length === 0) return [];
|
|
75
75
|
|
|
@@ -94,7 +94,7 @@ function firstClickAttribution(touchpoints) {
|
|
|
94
94
|
|
|
95
95
|
**Uso:** Jornadas longas, múltiplos touchpoints importantes.
|
|
96
96
|
|
|
97
|
-
```
|
|
97
|
+
```typescript
|
|
98
98
|
function linearAttribution(touchpoints) {
|
|
99
99
|
if (!touchpoints || touchpoints.length === 0) return [];
|
|
100
100
|
|
|
@@ -122,7 +122,7 @@ function linearAttribution(touchpoints) {
|
|
|
122
122
|
|
|
123
123
|
**Fórmula:** `Credit = 0.9^dias_desde_touchpoint`
|
|
124
124
|
|
|
125
|
-
```
|
|
125
|
+
```typescript
|
|
126
126
|
function timeDecayAttribution(touchpoints, decayFactor = 0.9) {
|
|
127
127
|
if (!touchpoints || touchpoints.length === 0) return [];
|
|
128
128
|
|
|
@@ -165,7 +165,7 @@ function timeDecayAttribution(touchpoints, decayFactor = 0.9) {
|
|
|
165
165
|
|
|
166
166
|
**Uso:** Funis com pesquisa (awareness) + conversão direta.
|
|
167
167
|
|
|
168
|
-
```
|
|
168
|
+
```typescript
|
|
169
169
|
function uShapeAttribution(touchpoints) {
|
|
170
170
|
if (!touchpoints || touchpoints.length === 0) return [];
|
|
171
171
|
|
|
@@ -207,7 +207,7 @@ function uShapeAttribution(touchpoints) {
|
|
|
207
207
|
|
|
208
208
|
**Uso:** Funis muito longos, jornada complexa.
|
|
209
209
|
|
|
210
|
-
```
|
|
210
|
+
```typescript
|
|
211
211
|
function wShapeAttribution(touchpoints) {
|
|
212
212
|
if (!touchpoints || touchpoints.length === 0) return [];
|
|
213
213
|
|
|
@@ -262,7 +262,7 @@ function wShapeAttribution(touchpoints) {
|
|
|
262
262
|
|
|
263
263
|
**Fórmula:** `Credit = BaseScore * CanalWeight * PositionWeight * ConversionRateWeight`
|
|
264
264
|
|
|
265
|
-
```
|
|
265
|
+
```typescript
|
|
266
266
|
// Modelo Data-Driven simplificado
|
|
267
267
|
async function dataDrivenAttribution(touchpoints, userJourneyHistory, env) {
|
|
268
268
|
if (!touchpoints || touchpoints.length === 0) return [];
|
|
@@ -456,7 +456,7 @@ CREATE INDEX IF NOT EXISTS idx_channel_model ON channel_performance(attribution_
|
|
|
456
456
|
|
|
457
457
|
### 2.1 Captura de Jornada Completa
|
|
458
458
|
|
|
459
|
-
```
|
|
459
|
+
```typescript
|
|
460
460
|
// Capturar touchpoint da jornada
|
|
461
461
|
export async function captureTouchpoint(eventData, request, env) {
|
|
462
462
|
const {
|
|
@@ -536,7 +536,7 @@ async function scheduleAttributionCalculation(email, conversionId, eventName, en
|
|
|
536
536
|
|
|
537
537
|
### 2.2 Cálculo de Atribuição Multi-Touch
|
|
538
538
|
|
|
539
|
-
```
|
|
539
|
+
```typescript
|
|
540
540
|
// Calcular atribuição multi-touch
|
|
541
541
|
export async function calculateMultiTouchAttribution(conversionData, env) {
|
|
542
542
|
const {
|
|
@@ -683,7 +683,7 @@ async function updateChannelPerformance(attributionModels, value, currency, env)
|
|
|
683
683
|
|
|
684
684
|
### 2.3 Enviar Atribuição para Plataformas
|
|
685
685
|
|
|
686
|
-
```
|
|
686
|
+
```typescript
|
|
687
687
|
// Enviar Purchase com atribuição calculada
|
|
688
688
|
export async function sendPurchaseWithAttribution(conversionData, env, attributionModel = 'U_SHAPE') {
|
|
689
689
|
const {
|
|
@@ -914,7 +914,7 @@ async function sendGA4PurchaseWithAttribution(purchaseData, channelValues) {
|
|
|
914
914
|
|
|
915
915
|
### 3.1 Configuração via Arquivo
|
|
916
916
|
|
|
917
|
-
```
|
|
917
|
+
```typescript
|
|
918
918
|
// attribution.config.js
|
|
919
919
|
export const ATTRIBUTION_CONFIG = {
|
|
920
920
|
// Modelo padrão para cálculo de atribuição
|
|
@@ -1024,7 +1024,7 @@ export default ATTRIBUTION_CONFIG;
|
|
|
1024
1024
|
|
|
1025
1025
|
### 4.1 Endpoint de Atribuição
|
|
1026
1026
|
|
|
1027
|
-
```
|
|
1027
|
+
```typescript
|
|
1028
1028
|
// Endpoint para consultar atribuição de conversão
|
|
1029
1029
|
export async function getAttributionForConversion(request, env) {
|
|
1030
1030
|
const url = new URL(request.url);
|
|
@@ -1167,10 +1167,10 @@ export async function getChannelPerformance(request, env) {
|
|
|
1167
1167
|
|
|
1168
1168
|
## 🎯 FORMATO DE SAÍDA
|
|
1169
1169
|
|
|
1170
|
-
### DELIVERABLE 1: `attribution-engine.
|
|
1170
|
+
### DELIVERABLE 1: `modules/attribution-engine.ts`
|
|
1171
1171
|
|
|
1172
|
-
```
|
|
1173
|
-
// attribution-engine.
|
|
1172
|
+
```typescript
|
|
1173
|
+
// modules/attribution-engine.ts - Engine de atribuição multi-touch
|
|
1174
1174
|
export {
|
|
1175
1175
|
captureTouchpoint,
|
|
1176
1176
|
calculateMultiTouchAttribution,
|
|
@@ -1207,10 +1207,10 @@ CREATE INDEX IF NOT EXISTS idx_channel_source ON channel_performance(utm_source)
|
|
|
1207
1207
|
CREATE INDEX IF NOT EXISTS idx_channel_campaign ON channel_performance(utm_campaign);
|
|
1208
1208
|
```
|
|
1209
1209
|
|
|
1210
|
-
### DELIVERABLE 3: `attribution-config.
|
|
1210
|
+
### DELIVERABLE 3: `modules/attribution-config.ts`
|
|
1211
1211
|
|
|
1212
|
-
```
|
|
1213
|
-
// attribution-config.
|
|
1212
|
+
```typescript
|
|
1213
|
+
// modules/attribution-config.ts - Configuração de modelos de atribuição
|
|
1214
1214
|
export const ATTRIBUTION_CONFIG = {
|
|
1215
1215
|
default_model: 'U_SHAPE',
|
|
1216
1216
|
available_models: [
|
|
@@ -53,7 +53,7 @@ Sempre que o usuário desejar suporte Microsoft B2B/B2C High-Ticket:
|
|
|
53
53
|
```json
|
|
54
54
|
{
|
|
55
55
|
"arquivos_gerados": {
|
|
56
|
-
"server": "bing
|
|
56
|
+
"server": "modules/dispatch/bing.ts (módulo cloudflare TypeScript)"
|
|
57
57
|
},
|
|
58
58
|
"tecnologia_alvo": "Cloudflare Worker (Server-Side S2S)",
|
|
59
59
|
"api_endpoint": "https://bat.bing.com/action/0",
|
|
@@ -137,7 +137,7 @@ Regras que nunca podem ser violadas, independente do contexto:
|
|
|
137
137
|
## ESCOPO
|
|
138
138
|
|
|
139
139
|
Este agente monitora:
|
|
140
|
-
- `server-edge-tracker/
|
|
140
|
+
- `server-edge-tracker/index.ts` — código crítico de produção
|
|
141
141
|
- `extracted-skill/tracking-events-generator/cdpTrack.js` — SDK browser
|
|
142
142
|
- `extracted-skill/tracking-events-generator/agents/*.md` — definições de agentes
|
|
143
143
|
- `server-edge-tracker/wrangler.toml` — configuração de infraestrutura
|
|
@@ -183,7 +183,7 @@ CREATE INDEX IF NOT EXISTS idx_consent_policy_version
|
|
|
183
183
|
|
|
184
184
|
### Consent Collection & Storage
|
|
185
185
|
|
|
186
|
-
```
|
|
186
|
+
```typescript
|
|
187
187
|
/**
|
|
188
188
|
* Consent Manager
|
|
189
189
|
* Manages user consent collection, storage, and tracking
|
|
@@ -559,7 +559,7 @@ let consentManager = null;
|
|
|
559
559
|
|
|
560
560
|
### GDPR/LGPD/CCPA Data Rights Implementation
|
|
561
561
|
|
|
562
|
-
```
|
|
562
|
+
```typescript
|
|
563
563
|
/**
|
|
564
564
|
* Data Rights Manager
|
|
565
565
|
* Handles GDPR/LGPD/CCPA data rights: access, deletion, portability, rectification
|
|
@@ -1110,7 +1110,7 @@ let dataRightsManager = null;
|
|
|
1110
1110
|
|
|
1111
1111
|
### Automated Data Retention Policies
|
|
1112
1112
|
|
|
1113
|
-
```
|
|
1113
|
+
```typescript
|
|
1114
1114
|
/**
|
|
1115
1115
|
* Data Retention Manager
|
|
1116
1116
|
* Manages automated data retention and deletion policies
|
|
@@ -1381,7 +1381,7 @@ let dataRetentionManager = null;
|
|
|
1381
1381
|
|
|
1382
1382
|
### Comprehensive Audit Logging
|
|
1383
1383
|
|
|
1384
|
-
```
|
|
1384
|
+
```typescript
|
|
1385
1385
|
/**
|
|
1386
1386
|
* Compliance Audit Logger
|
|
1387
1387
|
* Records all compliance-related activities for audit purposes
|
|
@@ -1533,7 +1533,7 @@ let complianceAuditLogger = null;
|
|
|
1533
1533
|
|
|
1534
1534
|
### Compliance Management Endpoints
|
|
1535
1535
|
|
|
1536
|
-
```
|
|
1536
|
+
```typescript
|
|
1537
1537
|
/**
|
|
1538
1538
|
* Compliance Management Endpoints
|
|
1539
1539
|
*/
|
|
@@ -33,8 +33,8 @@ Webhook Agent (lead capturado via /track)
|
|
|
33
33
|
|
|
34
34
|
**Assinatura da função exportada (injetada no Worker):**
|
|
35
35
|
|
|
36
|
-
```
|
|
37
|
-
// Injetada no
|
|
36
|
+
```typescript
|
|
37
|
+
// Injetada no index.ts pelo CRM Integration Agent
|
|
38
38
|
export async function syncToCRM(env, eventType, payload) {
|
|
39
39
|
// eventType: 'lead' | 'purchase' | 'checkout_abandoned'
|
|
40
40
|
// payload: { email, name, product, value, order_id, phone }
|
|
@@ -67,7 +67,7 @@ Implementar **integração bidirecional** entre CDP Edge D1 e CRMs externos, per
|
|
|
67
67
|
|
|
68
68
|
### 1.1 Tipos de CRM Suportados
|
|
69
69
|
|
|
70
|
-
```
|
|
70
|
+
```typescript
|
|
71
71
|
// CRMs suportados com mapeamentos
|
|
72
72
|
export const SUPPORTED_CRMS = {
|
|
73
73
|
HUBSPOT: {
|
|
@@ -188,7 +188,7 @@ export function configureCRM(crmType, config) {
|
|
|
188
188
|
|
|
189
189
|
### 2.1 Mapeamento de Leads
|
|
190
190
|
|
|
191
|
-
```
|
|
191
|
+
```typescript
|
|
192
192
|
// Mapeamento de campos de lead do D1 para cada CRM
|
|
193
193
|
export const LEAD_FIELD_MAPPINGS = {
|
|
194
194
|
HUBSPOT: {
|
|
@@ -439,7 +439,7 @@ function extractLastName(fullName) {
|
|
|
439
439
|
|
|
440
440
|
### 2.2 Mapeamento de Compras (Conversões)
|
|
441
441
|
|
|
442
|
-
```
|
|
442
|
+
```typescript
|
|
443
443
|
// Mapeamento de campos de purchase para cada CRM
|
|
444
444
|
export const PURCHASE_FIELD_MAPPINGS = {
|
|
445
445
|
HUBSPOT: {
|
|
@@ -642,7 +642,7 @@ export const PURCHASE_FIELD_MAPPINGS = {
|
|
|
642
642
|
|
|
643
643
|
### 3.1 Sync de Leads (Batch)
|
|
644
644
|
|
|
645
|
-
```
|
|
645
|
+
```typescript
|
|
646
646
|
// Sincronizar leads do D1 para CRM em batch
|
|
647
647
|
export async function syncLeadsToCRM(env, hours = 24, batchSize = 50) {
|
|
648
648
|
const leads = await env.DB.prepare(`
|
|
@@ -741,7 +741,7 @@ async function markLeadAsSynced(leadId, env) {
|
|
|
741
741
|
|
|
742
742
|
### 3.2 Sync de Compras (Batch)
|
|
743
743
|
|
|
744
|
-
```
|
|
744
|
+
```typescript
|
|
745
745
|
// Sincronizar compras do D1 para CRM em batch
|
|
746
746
|
export async function syncPurchasesToCRM(env, hours = 24, batchSize = 20) {
|
|
747
747
|
const purchases = await env.DB.prepare(`
|
|
@@ -846,7 +846,7 @@ async function markPurchaseAsSynced(purchaseId, env) {
|
|
|
846
846
|
|
|
847
847
|
### 4.1 Webhook Endpoint para Atualizações do CRM
|
|
848
848
|
|
|
849
|
-
```
|
|
849
|
+
```typescript
|
|
850
850
|
// Endpoint para receber webhooks do CRM
|
|
851
851
|
export async function handleCRMWebhook(request, env) {
|
|
852
852
|
const payload = await request.json();
|
|
@@ -929,7 +929,7 @@ function validateWebhookSignature(payload, signature, crmType) {
|
|
|
929
929
|
|
|
930
930
|
### 5.1 Schedule Config (Batch vs Real-time)
|
|
931
931
|
|
|
932
|
-
```
|
|
932
|
+
```typescript
|
|
933
933
|
// Configuração de como a sincronização deve funcionar
|
|
934
934
|
export const SYNC_CONFIG = {
|
|
935
935
|
mode: 'BATCH', // ou 'REAL-TIME'
|
|
@@ -993,7 +993,7 @@ export const CRM_SPECIFIC_CONFIG = {
|
|
|
993
993
|
|
|
994
994
|
### DELIVERABLE 1: `crm-webhook-handlers.js`
|
|
995
995
|
|
|
996
|
-
```
|
|
996
|
+
```typescript
|
|
997
997
|
// Funções para Cloudflare Worker - Webhooks do CRM
|
|
998
998
|
import { validateWebhookSignature, updateLeadStageFromCRM, updateDealStatusFromCRM, updateLeadScoreFromCRM } from './crm-sync.js';
|
|
999
999
|
|
|
@@ -94,7 +94,7 @@ Definir o Dashboard como um **Centro de Comando de Dados** que equilibra:
|
|
|
94
94
|
- Dados de evento: 15 minutos
|
|
95
95
|
|
|
96
96
|
**Implementação:**
|
|
97
|
-
```
|
|
97
|
+
```typescript
|
|
98
98
|
// Carregar dados do cache
|
|
99
99
|
const fetchMetrics = async (env, forceRefresh = false) => {
|
|
100
100
|
const cacheKey = 'dashboard_metrics';
|
|
@@ -129,7 +129,7 @@ const fetchMetrics = async (env, forceRefresh = false) => {
|
|
|
129
129
|
- Desativação manual ou timeout de inatividade
|
|
130
130
|
|
|
131
131
|
**Implementação:**
|
|
132
|
-
```
|
|
132
|
+
```typescript
|
|
133
133
|
const useRealTime = async () => {
|
|
134
134
|
// WebSockets ou Server-Sent Events (SSE)
|
|
135
135
|
const eventSource = new EventSource('/api/metrics/stream');
|
|
@@ -187,7 +187,7 @@ Invalidação:
|
|
|
187
187
|
|
|
188
188
|
### Para Cloudflare Worker
|
|
189
189
|
|
|
190
|
-
```
|
|
190
|
+
```typescript
|
|
191
191
|
// ENDPOINTS DE CONSULTA (otimizados)
|
|
192
192
|
export const DASHBOARD_API = {
|
|
193
193
|
// Métricas globais (cache no KV)
|
|
@@ -44,7 +44,7 @@ Deploy: (data do último deploy)
|
|
|
44
44
|
### `wrangler.toml` — Estado Real
|
|
45
45
|
```toml
|
|
46
46
|
name = "server-edge-tracker"
|
|
47
|
-
main = "
|
|
47
|
+
main = "index.ts"
|
|
48
48
|
compatibility_date = "2025-01-01"
|
|
49
49
|
compatibility_flags = ["nodejs_compat"]
|
|
50
50
|
|
|
@@ -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:** 31 (core: 13, migrate-v6: 1, migrate-v7: 2, Fases 1-4: 10, schema-ltv-feedback: +3 colunas, schema-utm: 1, schema-quiz: 1, schema-sales-engine: 3)
|
|
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:** 14 (core: 13 + whatsapp_contacts)
|
|
262
|
+
> **Tabelas ativas após v6:** 14 (core: 13 + whatsapp_contacts). Total final após todos os schemas: 31 tabelas.
|
|
263
263
|
|
|
264
264
|
---
|
|
265
265
|
|
|
@@ -280,7 +280,7 @@ CREATE TABLE intelligence_logs (
|
|
|
280
280
|
```
|
|
281
281
|
|
|
282
282
|
### Padrões de Acesso D1 no Worker
|
|
283
|
-
```
|
|
283
|
+
```typescript
|
|
284
284
|
// SELECT com bind (previne SQL injection)
|
|
285
285
|
const { results } = await env.DB
|
|
286
286
|
.prepare('SELECT * FROM leads WHERE email = ? ORDER BY created_at DESC LIMIT 1')
|
|
@@ -339,7 +339,7 @@ wrangler queues create cdp-edge-dlq
|
|
|
339
339
|
```
|
|
340
340
|
|
|
341
341
|
### Uso no Worker (Produtor)
|
|
342
|
-
```
|
|
342
|
+
```typescript
|
|
343
343
|
// Enfileirar evento com falha para retry
|
|
344
344
|
await env.RETRY_QUEUE.send({
|
|
345
345
|
platform: 'meta',
|
|
@@ -351,7 +351,7 @@ await env.RETRY_QUEUE.send({
|
|
|
351
351
|
```
|
|
352
352
|
|
|
353
353
|
### Handler do Consumidor
|
|
354
|
-
```
|
|
354
|
+
```typescript
|
|
355
355
|
export default {
|
|
356
356
|
async queue(batch, env) {
|
|
357
357
|
for (const msg of batch.messages) {
|
|
@@ -406,7 +406,7 @@ wrangler kv namespace create GEO_CACHE
|
|
|
406
406
|
```
|
|
407
407
|
|
|
408
408
|
### Uso no Worker
|
|
409
|
-
```
|
|
409
|
+
```typescript
|
|
410
410
|
// Cache de geolocalização por IP (TTL: 1 hora)
|
|
411
411
|
const cacheKey = `geo:${clientIp}`;
|
|
412
412
|
let geoData = await env.GEO_CACHE.get(cacheKey, { type: 'json' });
|
|
@@ -448,7 +448,7 @@ wrangler r2 bucket create cdp-edge-logs
|
|
|
448
448
|
```
|
|
449
449
|
|
|
450
450
|
### Uso no Worker
|
|
451
|
-
```
|
|
451
|
+
```typescript
|
|
452
452
|
// Armazenar evento bruto para auditoria (LGPD)
|
|
453
453
|
const logKey = `events/${year}/${month}/${day}/${eventId}.json`;
|
|
454
454
|
await env.AUDIT_LOGS.put(logKey, JSON.stringify({
|
|
@@ -474,7 +474,7 @@ Limite Free: 10.000 neurônios/dia (~350 predições/dia com Granite)
|
|
|
474
474
|
```
|
|
475
475
|
|
|
476
476
|
### Uso no Worker (LTV Prediction)
|
|
477
|
-
```
|
|
477
|
+
```typescript
|
|
478
478
|
async function predictLtv(leadData, env) {
|
|
479
479
|
if (!env.AI) return { ltv_class: 'unknown', ltv_value: 0 };
|
|
480
480
|
|
|
@@ -510,7 +510,7 @@ async function predictLtv(leadData, env) {
|
|
|
510
510
|
| `0 3 1 * *` | Dia 1 03:00 | Intelligence Agent — auditoria mensal de erros |
|
|
511
511
|
|
|
512
512
|
### Handler no Worker
|
|
513
|
-
```
|
|
513
|
+
```typescript
|
|
514
514
|
export default {
|
|
515
515
|
async scheduled(event, env, ctx) {
|
|
516
516
|
ctx.waitUntil(runIntelligenceAgent(event.cron, env));
|
|
@@ -573,7 +573,7 @@ wrangler secret put RESEND_FROM_EMAIL
|
|
|
573
573
|
|
|
574
574
|
Todo I/O que não bloqueia a resposta ao browser **DEVE** usar `ctx.waitUntil`:
|
|
575
575
|
|
|
576
|
-
```
|
|
576
|
+
```typescript
|
|
577
577
|
export default {
|
|
578
578
|
async fetch(request, env, ctx) {
|
|
579
579
|
|
|
@@ -601,20 +601,12 @@ export default {
|
|
|
601
601
|
|
|
602
602
|
## 🗺️ ROADMAP DE INFRAESTRUTURA
|
|
603
603
|
|
|
604
|
-
### Fase Atual (✅ Implementado)
|
|
605
|
-
- D1 com
|
|
606
|
-
- Workers AI
|
|
607
|
-
- 2 Cron Triggers ativos
|
|
608
|
-
-
|
|
609
|
-
|
|
610
|
-
### Fase 2 (🔧 Próximos Passos)
|
|
611
|
-
- Queues para retry robusto (substituir retry síncrono atual)
|
|
612
|
-
- KV para cache de geo/sessão (reduzir latência)
|
|
613
|
-
|
|
614
|
-
### Fase 3 (🚀 Enterprise)
|
|
615
|
-
- R2 para logs auditáveis (conformidade LGPD)
|
|
616
|
-
- Múltiplos Workers especializados (routing por subdomínio)
|
|
617
|
-
- Durable Objects para sessões real-time
|
|
604
|
+
### Fase Atual (✅ Implementado — v2.5.1)
|
|
605
|
+
- D1 com 31 tabelas em produção (core + Fases 1-7)
|
|
606
|
+
- Workers AI: Granite 4.0 Micro (LTV + Quiz Scoring) + bge-m3 (Clustering)
|
|
607
|
+
- 2 Cron Triggers ativos (semanal + mensal)
|
|
608
|
+
- Rate Limiter, KV, R2 Audit Logs, Queues configurados
|
|
609
|
+
- Quiz Scoring Engine + Nurture Engine + ROAS Feedback Loop ativos
|
|
618
610
|
|
|
619
611
|
---
|
|
620
612
|
|
|
@@ -26,7 +26,7 @@ Prover **ferramentas profissionais de diagnóstico** que permitam identificar, i
|
|
|
26
26
|
|
|
27
27
|
### 1.1 Log de Worker (Server-Side)
|
|
28
28
|
|
|
29
|
-
```
|
|
29
|
+
```typescript
|
|
30
30
|
// Funções de logging estruturado para Cloudflare Worker
|
|
31
31
|
export const WORKER_LOG_LEVELS = {
|
|
32
32
|
ERROR: 'ERROR',
|
|
@@ -276,7 +276,7 @@ CREATE INDEX IF NOT EXISTS idx_browser_logs_session ON browser_logs(session_id);
|
|
|
276
276
|
|
|
277
277
|
### 2.1 Endpoint `/debug` — Informações Gerais
|
|
278
278
|
|
|
279
|
-
```
|
|
279
|
+
```typescript
|
|
280
280
|
// Endpoint de diagnóstico geral do sistema
|
|
281
281
|
export async function handleDebugRequest(request, env) {
|
|
282
282
|
const debugInfo = {
|
|
@@ -360,7 +360,7 @@ async function getApiHealth(platform) {
|
|
|
360
360
|
|
|
361
361
|
### 2.2 Endpoint `/health` — Health Check Simplificado
|
|
362
362
|
|
|
363
|
-
```
|
|
363
|
+
```typescript
|
|
364
364
|
// Endpoint simplificado para monitoring externo
|
|
365
365
|
export async function handleHealthCheck(request, env) {
|
|
366
366
|
const checks = {
|
|
@@ -426,7 +426,7 @@ async function getSimpleApiHealth(platform) {
|
|
|
426
426
|
|
|
427
427
|
### 2.3 Endpoint `/events-log` — Logs de Eventos Recentes
|
|
428
428
|
|
|
429
|
-
```
|
|
429
|
+
```typescript
|
|
430
430
|
// Endpoint para consultar logs de eventos
|
|
431
431
|
export async function handleEventsLogRequest(request, env) {
|
|
432
432
|
const url = new URL(request.url);
|
|
@@ -630,7 +630,7 @@ export async function handleEventsLogRequest(request, env) {
|
|
|
630
630
|
|
|
631
631
|
### 4.1 Diagnóstico de Erros de Meta (400/401/429)
|
|
632
632
|
|
|
633
|
-
```
|
|
633
|
+
```typescript
|
|
634
634
|
// Análise de erros específicos de Meta API
|
|
635
635
|
export async function diagnoseMetaError(errorCode, errorContext) {
|
|
636
636
|
const errorMap = {
|
|
@@ -747,7 +747,7 @@ export async function diagnoseMetaError(errorCode, errorContext) {
|
|
|
747
747
|
|
|
748
748
|
### 4.2 Diagnóstico de Erros de Google (400/401/429)
|
|
749
749
|
|
|
750
|
-
```
|
|
750
|
+
```typescript
|
|
751
751
|
// Análise de erros específicos de Google API
|
|
752
752
|
export async function diagnoseGoogleError(errorCode, errorContext) {
|
|
753
753
|
const errorMap = {
|
|
@@ -847,7 +847,7 @@ export async function diagnoseGoogleError(errorCode, errorContext) {
|
|
|
847
847
|
|
|
848
848
|
### 4.3 Diagnóstico de Erros de TikTok (400/401/429)
|
|
849
849
|
|
|
850
|
-
```
|
|
850
|
+
```typescript
|
|
851
851
|
// Análise de erros específicos de TikTok API
|
|
852
852
|
export async function diagnoseTikTokError(errorCode, errorContext) {
|
|
853
853
|
const errorMap = {
|
|
@@ -967,9 +967,9 @@ export async function diagnoseTikTokError(errorCode, errorContext) {
|
|
|
967
967
|
|
|
968
968
|
## 🎯 FORMATO DE SAÍDA
|
|
969
969
|
|
|
970
|
-
### DELIVERABLE 1: `debug-endpoints.
|
|
970
|
+
### DELIVERABLE 1: `modules/debug-endpoints.ts`
|
|
971
971
|
|
|
972
|
-
```
|
|
972
|
+
```typescript
|
|
973
973
|
// Funções de diagnóstico para Cloudflare Worker
|
|
974
974
|
import { logWorker, WORKER_LOG_LEVELS } from './worker-logging.js';
|
|
975
975
|
import { getApiHealth, getSimpleApiHealth } from './api-health.js';
|
|
@@ -120,6 +120,10 @@ wrangler d1 execute cdp-edge-db --file=schema-indexes.sql --remote
|
|
|
120
120
|
# Fase 5: LTV Model (regressão logística) + Match Quality Log
|
|
121
121
|
wrangler d1 execute cdp-edge-db --file=migrate-v7.sql --remote
|
|
122
122
|
|
|
123
|
+
# Fase 5b: Colunas LTV Feedback em user_profiles (real_ltv_value, ltv_accuracy, ltv_feedback_at)
|
|
124
|
+
# OBRIGATÓRIO — sem isso recordLtvFeedback() falha silenciosamente em todo Purchase com value > 0
|
|
125
|
+
wrangler d1 execute cdp-edge-db --file=schema-ltv-feedback.sql --remote
|
|
126
|
+
|
|
123
127
|
# UTM Segmentação
|
|
124
128
|
wrangler d1 execute cdp-edge-db --file=schema-utm.sql --remote
|
|
125
129
|
|
|
@@ -141,6 +145,12 @@ Após cada migração: confirmar sucesso antes de prosseguir.
|
|
|
141
145
|
> - `match_quality_log` — registra flags de qualidade de dados (has_email, has_fbp, etc.) a cada CAPI dispatch
|
|
142
146
|
> Sem essas tabelas: o modelo LTV não persiste e o Match Quality Alert não funciona.
|
|
143
147
|
>
|
|
148
|
+
> **Fase 5b adiciona 3 colunas em `user_profiles` (ALTER TABLE):**
|
|
149
|
+
> - `real_ltv_value` — valor real de compra registrado após Purchase
|
|
150
|
+
> - `ltv_accuracy` — acurácia do modelo: `1 - |pred-real|/real` (0–1)
|
|
151
|
+
> - `ltv_feedback_at` — timestamp do último feedback
|
|
152
|
+
> **SEM ESSA MIGRAÇÃO:** `recordLtvFeedback()` falha silenciosamente em todo Purchase com value > 0 — ciclo preditivo nunca fecha.
|
|
153
|
+
>
|
|
144
154
|
> **Fase 6 (Lead Scoring) cria:**
|
|
145
155
|
> - `quiz_sessions` — qualificação por lead com breakdown dimensional auditável
|
|
146
156
|
> - `v_quiz_qualification_summary`, `v_quiz_dimension_impact` — VIEWs de análise
|
|
@@ -179,7 +189,11 @@ wrangler secret put WHATSAPP_PHONE_NUMBER_ID
|
|
|
179
189
|
wrangler secret put WA_NOTIFY_NUMBER
|
|
180
190
|
wrangler secret put WA_WEBHOOK_VERIFY_TOKEN
|
|
181
191
|
|
|
182
|
-
#
|
|
192
|
+
# Nurture Engine — email (obrigatório se Nurture habilitado)
|
|
193
|
+
wrangler secret put RESEND_API_KEY # API Key resend.com
|
|
194
|
+
wrangler secret put RESEND_FROM_EMAIL # ex: "CDP Edge <noreply@seudominio.com.br>"
|
|
195
|
+
|
|
196
|
+
# Plataformas de anúncio opcionais (conforme selecionadas)
|
|
183
197
|
wrangler secret put TIKTOK_ACCESS_TOKEN
|
|
184
198
|
wrangler secret put PINTEREST_ACCESS_TOKEN
|
|
185
199
|
wrangler secret put REDDIT_ACCESS_TOKEN
|
|
@@ -187,6 +201,9 @@ wrangler secret put LINKEDIN_ACCESS_TOKEN
|
|
|
187
201
|
wrangler secret put SPOTIFY_ACCESS_TOKEN
|
|
188
202
|
wrangler secret put CALLMEBOT_PHONE
|
|
189
203
|
wrangler secret put CALLMEBOT_APIKEY
|
|
204
|
+
|
|
205
|
+
# Webhooks de gateway de pagamento
|
|
206
|
+
wrangler secret put WEBHOOK_SECRET_TICTO # HMAC-SHA256 Ticto
|
|
190
207
|
```
|
|
191
208
|
|
|
192
209
|
---
|
|
@@ -139,13 +139,13 @@ SITE_DOMAIN = "clientdomain.com"
|
|
|
139
139
|
|
|
140
140
|
---
|
|
141
141
|
|
|
142
|
-
## Fase 4 — Verificar Cookie Domain no
|
|
142
|
+
## Fase 4 — Verificar Cookie Domain no index.ts
|
|
143
143
|
|
|
144
144
|
O cookie `_cdp_uid` precisa ser definido com `Domain=.clientdomain.com` (ponto antes = root domain = compartilhado entre subdomínios).
|
|
145
145
|
|
|
146
|
-
### Localizar no
|
|
146
|
+
### Localizar no index.ts a função de cookie:
|
|
147
147
|
|
|
148
|
-
```
|
|
148
|
+
```typescript
|
|
149
149
|
// Buscar por: Set-Cookie ou _cdp_uid
|
|
150
150
|
// Deve conter:
|
|
151
151
|
`_cdp_uid=${uid}; Max-Age=31536000; Path=/; Domain=.${env.SITE_DOMAIN}; SameSite=None; Secure`
|
|
@@ -155,7 +155,7 @@ Se o worker usa `env.SITE_DOMAIN` no Domain do cookie (correto), basta atualizar
|
|
|
155
155
|
|
|
156
156
|
Se o worker usa o domínio hardcoded ou `workers.dev`, atualizar manualmente:
|
|
157
157
|
|
|
158
|
-
```
|
|
158
|
+
```typescript
|
|
159
159
|
// Substituir:
|
|
160
160
|
`Domain=.workers.dev`
|
|
161
161
|
// Por:
|
|
@@ -224,7 +224,7 @@ const CDP_ENDPOINT = 'https://track.clientdomain.com/track';
|
|
|
224
224
|
| 522 Connection Timed Out | CNAME não-proxied ou worker offline | Verificar proxy status + `wrangler deploy` |
|
|
225
225
|
| Cookie Domain errado | SITE_DOMAIN antigo | Confirmar `wrangler.toml` + deploy |
|
|
226
226
|
| Worker Route não ativando | Route sem deploy | `wrangler deploy` novamente |
|
|
227
|
-
| CORS error no browser | Origin não permitido | Verificar headers CORS no
|
|
227
|
+
| CORS error no browser | Origin não permitido | Verificar headers CORS no index.ts |
|
|
228
228
|
|
|
229
229
|
---
|
|
230
230
|
|
|
@@ -19,8 +19,8 @@ Webhook Agent (Hotmart/Kiwify/Ticto)
|
|
|
19
19
|
|
|
20
20
|
**Assinatura da função que este agente gera:**
|
|
21
21
|
|
|
22
|
-
```
|
|
23
|
-
// Injetada no Worker principal (
|
|
22
|
+
```typescript
|
|
23
|
+
// Injetada no Worker principal (index.ts)
|
|
24
24
|
export async function sendEmail(env, type, payload) {
|
|
25
25
|
const { to, name, product, value } = payload;
|
|
26
26
|
// ... implementação completa abaixo
|
|
@@ -73,7 +73,7 @@ Sempre que o usuário precisar de automação de e-mail:
|
|
|
73
73
|
```json
|
|
74
74
|
{
|
|
75
75
|
"arquivos_criados": [
|
|
76
|
-
"
|
|
76
|
+
"modules/email-service.ts"
|
|
77
77
|
],
|
|
78
78
|
"tipos_de_email": {
|
|
79
79
|
"purchase_confirmation": "ativo",
|
|
@@ -21,11 +21,11 @@ Sempre que o usuário sangrar dinheiro por culpa de "Perda de Cookies/Atribuiç
|
|
|
21
21
|
|
|
22
22
|
---
|
|
23
23
|
|
|
24
|
-
## 💻 IMPLEMENTAÇÃO REAL —
|
|
24
|
+
## 💻 IMPLEMENTAÇÃO REAL — modules/fingerprint-middleware.ts
|
|
25
25
|
|
|
26
26
|
### Módulo completo para injetar no Worker
|
|
27
27
|
|
|
28
|
-
```
|
|
28
|
+
```typescript
|
|
29
29
|
/**
|
|
30
30
|
* Fingerprint Middleware — CDP Edge
|
|
31
31
|
* Edge-only signals: IP + Accept-Language + UA base + ASN
|
|
@@ -212,7 +212,7 @@ CREATE TABLE IF NOT EXISTS fingerprint_sessions (
|
|
|
212
212
|
CREATE INDEX IF NOT EXISTS idx_fp_last_seen ON fingerprint_sessions(last_seen_at);
|
|
213
213
|
```
|
|
214
214
|
|
|
215
|
-
### Uso no
|
|
215
|
+
### Uso no index.ts
|
|
216
216
|
|
|
217
217
|
```javascript
|
|
218
218
|
// No início do handler /track, ANTES do fraud gate:
|
|
@@ -246,7 +246,7 @@ payload = await fingerprintMiddleware(request, env, payload);
|
|
|
246
246
|
```json
|
|
247
247
|
{
|
|
248
248
|
"arquivos_criados": [
|
|
249
|
-
"
|
|
249
|
+
"modules/fingerprint-middleware.ts"
|
|
250
250
|
],
|
|
251
251
|
"sinais_utilizados": ["ip", "accept-language", "user-agent-base", "cf-asorg"],
|
|
252
252
|
"janela_restauracao_horas": 48,
|
|
@@ -35,6 +35,8 @@ checkFraudGate(env, request, payload)
|
|
|
35
35
|
logFraudSignal(env, ...) → D1: fraud_signals + fraud_alerts
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
+
**Implementação:** `modules/ml/fraud.ts` — `checkFraudGate(env: Env, request: Request, payload: TrackPayload)` (TypeScript)
|
|
39
|
+
|
|
38
40
|
**Integração automática com fluxo `/track`:**
|
|
39
41
|
- Executa ANTES do LTV, fingerprinting e CAPI
|
|
40
42
|
- Silent drop (retorna 200 ao browser para não vazar a detecção)
|