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.
Files changed (34) hide show
  1. package/contracts/api-versions.json +12 -8
  2. package/dist/commands/install.js +186 -0
  3. package/dist/commands/setup.js +18 -1
  4. package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +23 -23
  5. package/extracted-skill/tracking-events-generator/agents/browser-tracking.md +172 -72
  6. package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +20 -0
  7. package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +48 -16
  8. package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +7 -7
  9. package/extracted-skill/tracking-events-generator/agents/database-agent.md +8 -8
  10. package/extracted-skill/tracking-events-generator/agents/debug-agent.md +13 -13
  11. package/extracted-skill/tracking-events-generator/agents/devops-agent.md +31 -7
  12. package/extracted-skill/tracking-events-generator/agents/email-agent.md +27 -0
  13. package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +205 -0
  14. package/extracted-skill/tracking-events-generator/agents/google-agent.md +118 -0
  15. package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +90 -4
  16. package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +8 -641
  17. package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +108 -0
  18. package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +1 -1
  19. package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +68 -8
  20. package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +71 -34
  21. package/extracted-skill/tracking-events-generator/agents/memory-agent.md +98 -0
  22. package/extracted-skill/tracking-events-generator/agents/performance-agent.md +29 -19
  23. package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +11 -1
  24. package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +137 -28
  25. package/extracted-skill/tracking-events-generator/agents/server-tracking.md +7 -8
  26. package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +63 -0
  27. package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +100 -5
  28. package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +100 -0
  29. package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +58 -5
  30. package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +16 -16
  31. package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +140 -25
  32. package/extracted-skill/tracking-events-generator/contracts/api-versions.json +12 -8
  33. package/package.json +2 -2
  34. package/server-edge-tracker/worker.js +53 -8
@@ -212,10 +212,14 @@
212
212
  ]
213
213
  },
214
214
  "conversions_api": {
215
- "current": "v2",
216
- "minimum_supported": "v1",
217
- "recommended": "v2",
218
- "endpoint_pattern": "https://api.linkedin.com/rest/attributionConversions/{VERSION}",
215
+ "current": "202401",
216
+ "minimum_supported": "202401",
217
+ "recommended": "202401",
218
+ "endpoint_pattern": "https://api.linkedin.com/rest/conversionEvents",
219
+ "required_headers": {
220
+ "LinkedIn-Version": "202401",
221
+ "X-Restli-Protocol-Version": "2.0.0"
222
+ },
219
223
  "authentication": "Bearer token (LINKEDIN_ACCESS_TOKEN)",
220
224
  "rate_limits": {
221
225
  "requests_per_second": 10,
@@ -359,10 +363,10 @@
359
363
  },
360
364
 
361
365
  "last_updated_by": {
362
- "agent": "Intelligence Agent",
363
- "session_id": "CDP_2026-03-28_sync",
364
- "timestamp": "2026-03-28T00:00:00.000Z"
366
+ "agent": "Audit — CDP Edge v2.0",
367
+ "session_id": "CDP_2026-04-10_audit",
368
+ "timestamp": "2026-04-10T00:00:00.000Z"
365
369
  },
366
370
 
367
- "next_review_date": "2026-04-27T00:00:00.000Z"
371
+ "next_review_date": "2026-05-10T00:00:00.000Z"
368
372
  }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * CDP Edge Install Command
3
+ * Instala o CDP Edge em qualquer projeto de cliente
4
+ *
5
+ * Uso: cdp-edge install [dir] [--name "Nome do Projeto"] [--cursor]
6
+ *
7
+ * O que faz:
8
+ * 1. Copia os arquivos do CDP Edge para <dir>/cdp-edge/
9
+ * 2. Cria <dir>/.claude/commands/cdp.md → habilita /cdp no Claude Code
10
+ * 3. Cria <dir>/CLAUDE.md → auto-ativação opcional
11
+ * 4. Cria <dir>/.cursorrules → Cursor IDE (flag --cursor)
12
+ */
13
+
14
+ import fs from 'fs';
15
+ import path from 'path';
16
+ import { fileURLToPath } from 'url';
17
+ import chalk from 'chalk';
18
+
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+
21
+ // Raiz do pacote CDP Edge (2 níveis acima de dist/commands/)
22
+ const CDP_EDGE_ROOT = path.resolve(__dirname, '..', '..');
23
+
24
+ function printBanner() {
25
+ console.log('');
26
+ console.log(chalk.white.bold(' CDP Edge Installation'));
27
+ console.log('');
28
+ console.log(chalk.cyan(' ██████╗██████╗ ██████╗ ███████╗██████╗ ██████╗ ███████╗'));
29
+ console.log(chalk.cyan('██╔════╝██╔══██╗██╔══██╗ ██╔════╝██╔══██╗██╔════╝ ██╔════╝'));
30
+ console.log(chalk.cyan('██║ ██║ ██║██████╔╝ █████╗ ██║ ██║██║ ███╗█████╗ '));
31
+ console.log(chalk.cyan('██║ ██║ ██║██╔═══╝ ██╔══╝ ██║ ██║██║ ██║██╔══╝ '));
32
+ console.log(chalk.cyan('╚██████╗██████╔╝██║ ███████╗██████╔╝╚██████╔╝███████╗'));
33
+ console.log(chalk.cyan(' ╚═════╝╚═════╝ ╚═╝ ╚══════╝╚═════╝ ╚═════╝╚══════╝'));
34
+ console.log('');
35
+ console.log(chalk.gray(' Customer Data Platform on the Edge · Global Edge Tracking · v2.0.2'));
36
+ console.log('');
37
+ console.log(chalk.gray('═'.repeat(68)));
38
+ console.log('');
39
+ }
40
+
41
+ export async function runInstall(targetDir = '.', options = {}) {
42
+ const projectName = options.name || path.basename(path.resolve(targetDir));
43
+ const target = path.resolve(targetDir);
44
+
45
+ printBanner();
46
+
47
+ console.log(chalk.gray(` Projeto: ${chalk.white(projectName)}`));
48
+ console.log(chalk.gray(` Destino: ${chalk.white(target)}\n`));
49
+
50
+ // 1. Garantir que o diretório alvo existe
51
+ if (!fs.existsSync(target)) {
52
+ fs.mkdirSync(target, { recursive: true });
53
+ console.log(chalk.green(`✔ Diretório criado: ${target}`));
54
+ }
55
+
56
+ // 2. Copiar arquivos CDP Edge para <target>/cdp-edge/
57
+ const cdpEdgeDest = path.join(target, 'cdp-edge');
58
+ const foldersToInstall = [
59
+ 'extracted-skill',
60
+ 'server-edge-tracker',
61
+ 'templates',
62
+ 'docs',
63
+ ];
64
+
65
+ let installedFromSource = false;
66
+ const missingFolders = [];
67
+
68
+ for (const folder of foldersToInstall) {
69
+ const src = path.join(CDP_EDGE_ROOT, folder);
70
+ const dest = path.join(cdpEdgeDest, folder);
71
+
72
+ if (fs.existsSync(src)) {
73
+ copyDir(src, dest);
74
+ console.log(chalk.green(`✔ Copiado: cdp-edge/${folder}/`));
75
+ installedFromSource = true;
76
+ } else {
77
+ missingFolders.push(folder);
78
+ }
79
+ }
80
+
81
+ if (!installedFromSource) {
82
+ // Pacote instalado via npm sem os arquivos de código-fonte
83
+ console.log(chalk.yellow('\n⚠ Arquivos de skill não encontrados no pacote npm.'));
84
+ console.log(chalk.yellow(' Clone o repositório completo manualmente:'));
85
+ console.log(chalk.cyan('\n git clone https://github.com/ricardosoli777/CDP-Edge-Premium cdp-edge\n'));
86
+ } else if (missingFolders.length > 0) {
87
+ console.log(chalk.yellow(`\n⚠ Pastas não encontradas (ignoradas): ${missingFolders.join(', ')}`));
88
+ }
89
+
90
+ // 3. Criar .claude/commands/cdp.md → habilita /cdp no Claude Code
91
+ const commandSrc = path.join(CDP_EDGE_ROOT, 'templates', 'install', '.claude', 'commands', 'cdp.md');
92
+ const commandDest = path.join(target, '.claude', 'commands', 'cdp.md');
93
+
94
+ if (fs.existsSync(commandDest)) {
95
+ console.log(chalk.yellow('⚠ .claude/commands/cdp.md já existe — não sobrescrito.'));
96
+ } else {
97
+ fs.mkdirSync(path.dirname(commandDest), { recursive: true });
98
+ if (fs.existsSync(commandSrc)) {
99
+ fs.copyFileSync(commandSrc, commandDest);
100
+ } else {
101
+ // Fallback inline
102
+ fs.writeFileSync(commandDest,
103
+ 'Leia o arquivo `cdp-edge/extracted-skill/tracking-events-generator/agents/master-orchestrator.md` e ative o Master Orchestrator exibindo a mensagem de boas-vindas completa.\n',
104
+ 'utf8'
105
+ );
106
+ }
107
+ console.log(chalk.green('✔ Criado: .claude/commands/cdp.md → /cdp habilitado'));
108
+ }
109
+
110
+ // 4. Criar CLAUDE.md na raiz (auto-ativação ao abrir sessão)
111
+ const claudeMdSrc = path.join(CDP_EDGE_ROOT, 'templates', 'install', 'CLAUDE.md');
112
+ const claudeMdDest = path.join(target, 'CLAUDE.md');
113
+
114
+ if (fs.existsSync(claudeMdDest)) {
115
+ console.log(chalk.yellow('⚠ CLAUDE.md já existe — não sobrescrito.'));
116
+ } else {
117
+ let content;
118
+ if (fs.existsSync(claudeMdSrc)) {
119
+ content = fs.readFileSync(claudeMdSrc, 'utf8');
120
+ content = content.replace('[NOME DO PROJETO]', projectName);
121
+ } else {
122
+ content = generateClaudeMd(projectName);
123
+ }
124
+ fs.writeFileSync(claudeMdDest, content, 'utf8');
125
+ console.log(chalk.green('✔ Criado: CLAUDE.md'));
126
+ }
127
+
128
+ // 5. Criar .cursorrules (flag --cursor)
129
+ if (options.cursor) {
130
+ const cursorDest = path.join(target, '.cursorrules');
131
+ if (fs.existsSync(cursorDest)) {
132
+ console.log(chalk.yellow('⚠ .cursorrules já existe — não sobrescrito.'));
133
+ } else {
134
+ const content = fs.readFileSync(claudeMdDest, 'utf8');
135
+ fs.writeFileSync(cursorDest, content, 'utf8');
136
+ console.log(chalk.green('✔ Criado: .cursorrules (Cursor IDE)'));
137
+ }
138
+ }
139
+
140
+ // 6. Resumo final
141
+ console.log(chalk.gray('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'));
142
+ console.log(chalk.green.bold(' CDP Edge instalado!'));
143
+ console.log(chalk.gray('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n'));
144
+ console.log(chalk.cyan('Próximos passos:\n'));
145
+ console.log(` 1. Abra o projeto no Claude Code:`);
146
+ console.log(chalk.bold(` claude ${target}`));
147
+ console.log(` 2. Digite ${chalk.bold('/cdp')} para ativar o Master Orchestrator\n`);
148
+ }
149
+
150
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
151
+
152
+ function copyDir(src, dest) {
153
+ fs.mkdirSync(dest, { recursive: true });
154
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
155
+ const srcPath = path.join(src, entry.name);
156
+ const destPath = path.join(dest, entry.name);
157
+ if (entry.isDirectory()) {
158
+ copyDir(srcPath, destPath);
159
+ } else {
160
+ fs.copyFileSync(srcPath, destPath);
161
+ }
162
+ }
163
+ }
164
+
165
+ function generateClaudeMd(projectName) {
166
+ return `# ${projectName} — CDP Edge Quantum Tracking
167
+
168
+ ## Ativação automática do CDP Edge
169
+
170
+ **Ao iniciar esta sessão, execute imediatamente:**
171
+
172
+ 1. Leia o arquivo: \`cdp-edge/extracted-skill/tracking-events-generator/agents/master-orchestrator.md\`
173
+ 2. Ative o **Master Orchestrator** exibindo a mensagem de boas-vindas
174
+ 3. Aguarde as instruções do usuário para iniciar o setup
175
+
176
+ ---
177
+
178
+ ## Comandos rápidos
179
+
180
+ | Comando | O que faz |
181
+ |---|---|
182
+ | \`/cdp\` | Ativa o Master Orchestrator |
183
+ | \`/cdp setup\` | Inicia o wizard de configuração completo |
184
+ | \`/cdp status\` | Verifica saúde do projeto atual |
185
+ `;
186
+ }
@@ -8,8 +8,25 @@ import inquirer from 'inquirer';
8
8
  import chalk from 'chalk';
9
9
  import ora from 'ora';
10
10
 
11
+ function printBanner() {
12
+ console.log('');
13
+ console.log(chalk.white.bold(' CDP Edge Setup Wizard'));
14
+ console.log('');
15
+ console.log(chalk.cyan(' ██████╗██████╗ ██████╗ ███████╗██████╗ ██████╗ ███████╗'));
16
+ console.log(chalk.cyan('██╔════╝██╔══██╗██╔══██╗ ██╔════╝██╔══██╗██╔════╝ ██╔════╝'));
17
+ console.log(chalk.cyan('██║ ██║ ██║██████╔╝ █████╗ ██║ ██║██║ ███╗█████╗ '));
18
+ console.log(chalk.cyan('██║ ██║ ██║██╔═══╝ ██╔══╝ ██║ ██║██║ ██║██╔══╝ '));
19
+ console.log(chalk.cyan('╚██████╗██████╔╝██║ ███████╗██████╔╝╚██████╔╝███████╗'));
20
+ console.log(chalk.cyan(' ╚═════╝╚═════╝ ╚═╝ ╚══════╝╚═════╝ ╚═════╝╚══════╝'));
21
+ console.log('');
22
+ console.log(chalk.gray(' Customer Data Platform on the Edge · Global Edge Tracking · v2.0.2'));
23
+ console.log('');
24
+ console.log(chalk.gray('═'.repeat(68)));
25
+ console.log('');
26
+ }
27
+
11
28
  export async function runSetupWizard(dir = '.') {
12
- console.log(chalk.cyan.bold('\n CDP Edge Quantum Tier - Setup Wizard\n'));
29
+ printBanner();
13
30
 
14
31
  // === MENSAGEM INICIAL ===
15
32
 
@@ -264,7 +264,7 @@ function wShapeAttribution(touchpoints) {
264
264
 
265
265
  ```javascript
266
266
  // Modelo Data-Driven simplificado
267
- async function dataDrivenAttribution(touchpoints, userJourneyHistory) {
267
+ async function dataDrivenAttribution(touchpoints, userJourneyHistory, env) {
268
268
  if (!touchpoints || touchpoints.length === 0) return [];
269
269
 
270
270
  // 1. Calcular pesos baseados em dados históricos
@@ -297,14 +297,14 @@ async function dataDrivenAttribution(touchpoints, userJourneyHistory) {
297
297
  }
298
298
 
299
299
  // Calcular peso de canal baseado em conversão histórica
300
- async function calculateChannelWeights(touchpoints, history) {
300
+ async function calculateChannelWeights(touchpoints, history, env) {
301
301
  const weights = {};
302
302
 
303
303
  for (const tp of touchpoints) {
304
304
  const channel = tp.utm_source;
305
305
 
306
306
  // Buscar conversões históricas deste canal
307
- const historicalConversions = await DB.prepare(`
307
+ const historicalConversions = await env.DB.prepare(`
308
308
  SELECT
309
309
  COUNT(*) as total_conversions,
310
310
  AVG(value) as avg_value
@@ -325,14 +325,14 @@ async function calculateChannelWeights(touchpoints, history) {
325
325
  }
326
326
 
327
327
  // Calcular peso de posição baseado em conversão histórica
328
- async function calculatePositionWeights(touchpoints, history) {
328
+ async function calculatePositionWeights(touchpoints, history, env) {
329
329
  const weights = {};
330
330
 
331
331
  for (const tp of touchpoints) {
332
332
  const position = tp.position; // 0 = first, 1 = second, etc.
333
333
 
334
334
  // Buscar conversões históricas nesta posição
335
- const historicalConversions = await DB.prepare(`
335
+ const historicalConversions = await env.DB.prepare(`
336
336
  SELECT
337
337
  COUNT(*) as total_conversions
338
338
  FROM multi_touch_attribution
@@ -458,7 +458,7 @@ CREATE INDEX IF NOT EXISTS idx_channel_model ON channel_performance(attribution_
458
458
 
459
459
  ```javascript
460
460
  // Capturar touchpoint da jornada
461
- export async function captureTouchpoint(eventData, request) {
461
+ export async function captureTouchpoint(eventData, request, env) {
462
462
  const {
463
463
  user_id,
464
464
  session_id,
@@ -485,7 +485,7 @@ export async function captureTouchpoint(eventData, request) {
485
485
  const position = await calculateJourneyPosition(user_id, event_timestamp);
486
486
 
487
487
  // Persistir touchpoint no D1
488
- await DB.prepare(`
488
+ await env.DB.prepare(`
489
489
  INSERT INTO user_journeys
490
490
  (user_id, session_id, email, event_id, event_name,
491
491
  utm_source, utm_medium, utm_campaign, utm_content, utm_term,
@@ -512,8 +512,8 @@ export async function captureTouchpoint(eventData, request) {
512
512
  }
513
513
 
514
514
  // Calcular posição na jornada
515
- async function calculateJourneyPosition(userId, eventTimestamp) {
516
- const result = await DB.prepare(`
515
+ async function calculateJourneyPosition(userId, eventTimestamp, env) {
516
+ const result = await env.DB.prepare(`
517
517
  SELECT COUNT(*) as position
518
518
  FROM user_journeys
519
519
  WHERE user_id = ? AND event_timestamp < ?
@@ -523,7 +523,7 @@ async function calculateJourneyPosition(userId, eventTimestamp) {
523
523
  }
524
524
 
525
525
  // Agendar cálculo de atribuição (via Cloudflare Queue)
526
- async function scheduleAttributionCalculation(email, conversionId, eventName) {
526
+ async function scheduleAttributionCalculation(email, conversionId, eventName, env) {
527
527
  await QUEUE.send('cdp-edge-attribution', {
528
528
  type: 'CALCULATE_ATTRIBUTION',
529
529
  email,
@@ -538,7 +538,7 @@ async function scheduleAttributionCalculation(email, conversionId, eventName) {
538
538
 
539
539
  ```javascript
540
540
  // Calcular atribuição multi-touch
541
- export async function calculateMultiTouchAttribution(conversionData) {
541
+ export async function calculateMultiTouchAttribution(conversionData, env) {
542
542
  const {
543
543
  email,
544
544
  conversion_id,
@@ -548,7 +548,7 @@ export async function calculateMultiTouchAttribution(conversionData) {
548
548
  } = conversionData;
549
549
 
550
550
  // 1. Buscar jornada completa do usuário
551
- const journey = await DB.prepare(`
551
+ const journey = await env.DB.prepare(`
552
552
  SELECT
553
553
  user_id,
554
554
  session_id,
@@ -594,7 +594,7 @@ export async function calculateMultiTouchAttribution(conversionData) {
594
594
  // 3. Persistir atribuição para cada modelo
595
595
  for (const [modelName, attribution] of Object.entries(attributionModels)) {
596
596
  for (const touchpoint of attribution) {
597
- await DB.prepare(`
597
+ await env.DB.prepare(`
598
598
  INSERT OR REPLACE INTO multi_touch_attribution
599
599
  (conversion_id, user_id, email, attribution_model, touchpoint_index,
600
600
  utm_source, utm_medium, utm_campaign, event_name, event_timestamp,
@@ -628,7 +628,7 @@ export async function calculateMultiTouchAttribution(conversionData) {
628
628
  }
629
629
 
630
630
  // Atualizar performance de canal
631
- async function updateChannelPerformance(attributionModels, value, currency) {
631
+ async function updateChannelPerformance(attributionModels, value, currency, env) {
632
632
  const today = new Date().toISOString().split('T')[0];
633
633
 
634
634
  for (const [modelName, attribution] of Object.entries(attributionModels)) {
@@ -660,7 +660,7 @@ async function updateChannelPerformance(attributionModels, value, currency) {
660
660
 
661
661
  // Atualizar tabela de performance
662
662
  for (const perf of Object.values(channelPerformance)) {
663
- await DB.prepare(`
663
+ await env.DB.prepare(`
664
664
  INSERT OR REPLACE INTO channel_performance
665
665
  (utm_source, utm_medium, utm_campaign, attribution_model,
666
666
  total_attribution, total_conversions, total_value, avg_conversion_value, date)
@@ -685,7 +685,7 @@ async function updateChannelPerformance(attributionModels, value, currency) {
685
685
 
686
686
  ```javascript
687
687
  // Enviar Purchase com atribuição calculada
688
- export async function sendPurchaseWithAttribution(conversionData, attributionModel = 'U_SHAPE') {
688
+ export async function sendPurchaseWithAttribution(conversionData, env, attributionModel = 'U_SHAPE') {
689
689
  const {
690
690
  email,
691
691
  conversion_id,
@@ -695,7 +695,7 @@ export async function sendPurchaseWithAttribution(conversionData, attributionMod
695
695
  } = conversionData;
696
696
 
697
697
  // 1. Buscar atribuição calculada
698
- const attribution = await DB.prepare(`
698
+ const attribution = await env.DB.prepare(`
699
699
  SELECT
700
700
  utm_source,
701
701
  utm_medium,
@@ -773,7 +773,7 @@ async function sendMetaPurchaseWithAttribution(purchaseData, attribution) {
773
773
  const response = await fetch('https://graph.facebook.com/v22.0/events', {
774
774
  method: 'POST',
775
775
  headers: {
776
- 'Authorization': `Bearer ${META_ACCESS_TOKEN}`,
776
+ 'Authorization': `Bearer ${env.META_ACCESS_TOKEN}`,
777
777
  'Content-Type': 'application/json'
778
778
  },
779
779
  body: JSON.stringify({ data: [payload] })
@@ -829,7 +829,7 @@ async function sendTikTokPurchaseWithAttribution(purchaseData, attribution) {
829
829
  const response = await fetch('https://business-api.tiktok.com/open_api/v1.3/pixel/conversion/', {
830
830
  method: 'POST',
831
831
  headers: {
832
- 'Authorization': `Bearer ${TIKTOK_ACCESS_TOKEN}`,
832
+ 'Authorization': `Bearer ${env.TIKTOK_ACCESS_TOKEN}`,
833
833
  'Content-Type': 'application/json'
834
834
  },
835
835
  body: JSON.stringify(payload)
@@ -1036,7 +1036,7 @@ export async function getAttributionForConversion(request, env) {
1036
1036
  }
1037
1037
 
1038
1038
  // Buscar atribuição calculada
1039
- const attribution = await DB.prepare(`
1039
+ const attribution = await env.DB.prepare(`
1040
1040
  SELECT
1041
1041
  utm_source,
1042
1042
  utm_medium,
@@ -1052,7 +1052,7 @@ export async function getAttributionForConversion(request, env) {
1052
1052
  `).bind(conversionId, model).all();
1053
1053
 
1054
1054
  // Buscar dados da conversão
1055
- const conversion = await DB.prepare(`
1055
+ const conversion = await env.DB.prepare(`
1056
1056
  SELECT
1057
1057
  value,
1058
1058
  currency,
@@ -1096,7 +1096,7 @@ export async function compareAttributionModels(request, env) {
1096
1096
  const comparison = {};
1097
1097
 
1098
1098
  for (const model of ATTRIBUTION_CONFIG.available_models) {
1099
- const attribution = await DB.prepare(`
1099
+ const attribution = await env.DB.prepare(`
1100
1100
  SELECT
1101
1101
  utm_source,
1102
1102
  credit_percentage
@@ -1136,7 +1136,7 @@ export async function getChannelPerformance(request, env) {
1136
1136
  const days = parseInt(url.searchParams.get('days') || '30');
1137
1137
  const groupBy = url.searchParams.get('group_by') || 'source'; // 'source' ou 'campaign'
1138
1138
 
1139
- const performance = await DB.prepare(`
1139
+ const performance = await env.DB.prepare(`
1140
1140
  SELECT
1141
1141
  ${groupBy === 'source' ? 'utm_source' : 'utm_campaign'} as group_by,
1142
1142
  SUM(total_attribution) as total_attribution,