@fayz-ai/plugin-marketing 0.8.1 → 0.8.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/dist/MarketingPage.d.ts.map +1 -1
- package/dist/data/capability.test.d.ts +2 -0
- package/dist/data/capability.test.d.ts.map +1 -0
- package/dist/data/supabase.d.ts +10 -0
- package/dist/data/supabase.d.ts.map +1 -0
- package/dist/data/tables.d.ts +7 -0
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/types.d.ts +2 -0
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.cjs +744 -58
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +746 -61
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.d.ts +3 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/registries.d.ts +3 -3
- package/dist/registries.d.ts.map +1 -1
- package/dist/schema/index.d.ts +354 -0
- package/dist/schema/index.d.ts.map +1 -1
- package/dist/schema.cjs +30 -0
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.js +30 -2
- package/dist/schema.js.map +1 -1
- package/dist/store.d.ts +2 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/views/CampaignsView.d.ts.map +1 -1
- package/dist/views/blog/BlogEntityForm.d.ts.map +1 -1
- package/dist/views/content/ContentView.d.ts.map +1 -1
- package/package.json +8 -6
- package/src/MarketingPage.tsx +5 -1
- package/src/data/capability.test.ts +92 -0
- package/src/data/supabase.ts +401 -0
- package/src/data/tables.ts +9 -0
- package/src/data/types.ts +2 -0
- package/src/index.ts +138 -10
- package/src/migrations/005_analytics_base.sql +60 -0
- package/src/migrations/006_analytics_views.sql +68 -0
- package/src/migrations/007_agent_rpcs.sql +119 -0
- package/src/migrations/index.ts +257 -1
- package/src/registries.ts +18 -6
- package/src/schema/index.ts +38 -1
- package/src/store.ts +21 -8
- package/src/views/CampaignsView.tsx +4 -1
- package/src/views/blog/BlogEntityForm.tsx +11 -2
- package/src/views/content/ContentView.tsx +8 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ContentView.d.ts","sourceRoot":"","sources":["../../../src/views/content/ContentView.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAwsBzB,wBAAgB,WAAW,CAAC,EAAE,UAAU,EAAE,EAAE;IAC1C,UAAU,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAA;CACjC,
|
|
1
|
+
{"version":3,"file":"ContentView.d.ts","sourceRoot":"","sources":["../../../src/views/content/ContentView.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAwsBzB,wBAAgB,WAAW,CAAC,EAAE,UAAU,EAAE,EAAE;IAC1C,UAAU,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAA;CACjC,qBAiMA"}
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"fayz": {
|
|
4
4
|
"status": "beta"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.8.
|
|
6
|
+
"version": "0.8.2",
|
|
7
7
|
"description": "Fayz SDK — marketing campaigns & broadcasts plugin",
|
|
8
8
|
"type": "module",
|
|
9
9
|
"main": "./dist/index.cjs",
|
|
@@ -35,17 +35,18 @@
|
|
|
35
35
|
"@tanstack/react-table": "^8.20.0",
|
|
36
36
|
"lucide-react": "^0.400.0",
|
|
37
37
|
"zustand": "^4.5.0",
|
|
38
|
-
"@fayz-ai/
|
|
39
|
-
"@fayz-ai/
|
|
40
|
-
"@fayz-ai/
|
|
41
|
-
"@fayz-ai/
|
|
38
|
+
"@fayz-ai/ui": "^0.8.4",
|
|
39
|
+
"@fayz-ai/core": "^0.8.4",
|
|
40
|
+
"@fayz-ai/db": "^0.8.4",
|
|
41
|
+
"@fayz-ai/saas": "^0.8.4"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/react": "^18.3.0",
|
|
45
45
|
"react": "^18.3.0",
|
|
46
46
|
"tsup": "^8.2.0",
|
|
47
47
|
"typescript": "^5.5.0",
|
|
48
|
-
"@types/react-dom": "^18.3.0"
|
|
48
|
+
"@types/react-dom": "^18.3.0",
|
|
49
|
+
"vitest": "^2.1.9"
|
|
49
50
|
},
|
|
50
51
|
"license": "MIT",
|
|
51
52
|
"keywords": [
|
|
@@ -60,6 +61,7 @@
|
|
|
60
61
|
"build": "tsup && tsc --emitDeclarationOnly --declaration --declarationMap --noEmit false",
|
|
61
62
|
"dev": "tsup --watch",
|
|
62
63
|
"typecheck": "tsc --noEmit",
|
|
64
|
+
"test": "vitest run",
|
|
63
65
|
"clean": "rm -rf dist"
|
|
64
66
|
}
|
|
65
67
|
}
|
package/src/MarketingPage.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import React from 'react'
|
|
2
2
|
import type { StoreApi } from 'zustand/vanilla'
|
|
3
3
|
import { ModulePage, type ModuleNavItem } from '@fayz-ai/ui'
|
|
4
|
-
import { useTranslation } from '@fayz-ai/core'
|
|
4
|
+
import { useTranslation, useDataChanged } from '@fayz-ai/core'
|
|
5
5
|
import type { PluginQuickAction } from '@fayz-ai/core'
|
|
6
6
|
import { useModuleNavigation, ModuleActionBar, createViewRouter } from '@fayz-ai/saas'
|
|
7
7
|
import { MarketingContextProvider, type ResolvedMarketingConfig } from './MarketingContext'
|
|
@@ -81,6 +81,10 @@ export function MarketingPage({ config, provider, store, contentProvider, conten
|
|
|
81
81
|
|
|
82
82
|
React.useEffect(() => { void store.getState().load() }, [store])
|
|
83
83
|
|
|
84
|
+
// Agent RPC writes (createCampaign) land outside the provider — refresh past
|
|
85
|
+
// its read cache when any agent write is announced.
|
|
86
|
+
useDataChanged({ table: 'plg_marketing_campaigns' }, () => { void store.getState().refresh() }, [store])
|
|
87
|
+
|
|
84
88
|
const isOverview = view === 'overview'
|
|
85
89
|
const nav = buildNav(config, view, navigate)
|
|
86
90
|
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Capability test for the marketing analytics data slice (mock provider) —
|
|
2
|
+
// template: plugin-tasks/src/data/capability.test.ts. The Supabase provider
|
|
3
|
+
// implements the same MarketingDataProvider interface against
|
|
4
|
+
// plg_marketing_channels/_campaigns + v_marketing_attribution.
|
|
5
|
+
import { describe, it, expect } from 'vitest'
|
|
6
|
+
import { createMockMarketingProvider } from './mock'
|
|
7
|
+
import { MARKETING_PRESETS } from '../presets'
|
|
8
|
+
|
|
9
|
+
function makeProvider() {
|
|
10
|
+
const preset = MARKETING_PRESETS.beauty
|
|
11
|
+
return createMockMarketingProvider({
|
|
12
|
+
channels: preset.channels,
|
|
13
|
+
conversion: preset.conversion,
|
|
14
|
+
domain: 'beauty',
|
|
15
|
+
})
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe('plugin-marketing capability · analytics slice (mock provider)', () => {
|
|
19
|
+
it('reports per-channel performance for every configured channel', async () => {
|
|
20
|
+
const provider = makeProvider()
|
|
21
|
+
const perf = await provider.channelPerformance({ range: '30d' })
|
|
22
|
+
expect(perf.map((c) => c.channelId).sort()).toEqual(
|
|
23
|
+
MARKETING_PRESETS.beauty.channels.map((c) => c.id).sort(),
|
|
24
|
+
)
|
|
25
|
+
for (const c of perf) {
|
|
26
|
+
expect(c.conversions).toBeGreaterThanOrEqual(0)
|
|
27
|
+
expect(c.cvr).toBeGreaterThanOrEqual(0)
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('overview aggregates the same channels the mix reports', async () => {
|
|
32
|
+
const provider = makeProvider()
|
|
33
|
+
const overview = await provider.overview({ range: '30d' })
|
|
34
|
+
expect(overview.channelMix.length).toBe(MARKETING_PRESETS.beauty.channels.length)
|
|
35
|
+
expect(overview.conversions).toBe(
|
|
36
|
+
overview.channelMix.reduce((s, c) => s + c.conversions, 0),
|
|
37
|
+
)
|
|
38
|
+
expect(overview.topChannelId).toBeTruthy()
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('persists a created campaign: it surfaces in list and get', async () => {
|
|
42
|
+
const provider = makeProvider()
|
|
43
|
+
const created = await provider.saveCampaign({
|
|
44
|
+
name: 'Campanha Teste',
|
|
45
|
+
channelId: 'instagram',
|
|
46
|
+
status: 'active',
|
|
47
|
+
start: new Date('2026-07-01').toISOString(),
|
|
48
|
+
spend: 150,
|
|
49
|
+
})
|
|
50
|
+
expect(created.id).toBeTruthy()
|
|
51
|
+
|
|
52
|
+
const listed = await provider.listCampaigns({ range: '30d' })
|
|
53
|
+
expect(listed.some((c) => c.id === created.id)).toBe(true)
|
|
54
|
+
|
|
55
|
+
const fetched = await provider.getCampaign(created.id)
|
|
56
|
+
expect(fetched?.name).toBe('Campanha Teste')
|
|
57
|
+
expect(fetched?.channelId).toBe('instagram')
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('round-trips update and delete', async () => {
|
|
61
|
+
const provider = makeProvider()
|
|
62
|
+
const created = await provider.saveCampaign({
|
|
63
|
+
name: 'temp',
|
|
64
|
+
channelId: 'google',
|
|
65
|
+
status: 'draft',
|
|
66
|
+
start: new Date('2026-07-01').toISOString(),
|
|
67
|
+
spend: 0,
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
const updated = await provider.saveCampaign({
|
|
71
|
+
id: created.id,
|
|
72
|
+
name: 'temp',
|
|
73
|
+
channelId: 'google',
|
|
74
|
+
status: 'paused',
|
|
75
|
+
start: created.start,
|
|
76
|
+
spend: 80,
|
|
77
|
+
})
|
|
78
|
+
expect(updated.status).toBe('paused')
|
|
79
|
+
|
|
80
|
+
await provider.deleteCampaign(created.id)
|
|
81
|
+
expect(await provider.getCampaign(created.id)).toBeNull()
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it('funnel stages end on the vertical conversion label', async () => {
|
|
85
|
+
const provider = makeProvider()
|
|
86
|
+
const funnel = await provider.funnel({ range: '30d' })
|
|
87
|
+
expect(funnel.length).toBeGreaterThanOrEqual(2)
|
|
88
|
+
expect(funnel[funnel.length - 1].label).toBe(
|
|
89
|
+
MARKETING_PRESETS.beauty.conversion.labelPlural,
|
|
90
|
+
)
|
|
91
|
+
})
|
|
92
|
+
})
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'
|
|
2
|
+
import type {
|
|
3
|
+
AttributionBridge,
|
|
4
|
+
MarketingDataProvider,
|
|
5
|
+
SaveCampaignInput,
|
|
6
|
+
SitesPerformanceBridge,
|
|
7
|
+
} from './types'
|
|
8
|
+
import type {
|
|
9
|
+
AcquisitionChannel,
|
|
10
|
+
Campaign,
|
|
11
|
+
ChannelPerformance,
|
|
12
|
+
ConversionModel,
|
|
13
|
+
DateRangeKey,
|
|
14
|
+
FunnelStage,
|
|
15
|
+
LandingPagePerf,
|
|
16
|
+
MarketingOverview,
|
|
17
|
+
MarketingQuery,
|
|
18
|
+
} from '../types'
|
|
19
|
+
import { T, V } from './tables'
|
|
20
|
+
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
// Supabase marketing provider. Channels/campaigns are real CRUD rows
|
|
23
|
+
// (plg_marketing_channels/_campaigns, lazily seeded from the app's channel
|
|
24
|
+
// config); performance is derived from v_marketing_attribution — REAL
|
|
25
|
+
// conversions (bookings/orders/won deals) and leads, attributed by matching
|
|
26
|
+
// the event's origin string against the channel set. Reach has no generic
|
|
27
|
+
// source yet, so it reads 0 until a sites/ads integration feeds it.
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
export interface SupabaseMarketingProviderOptions {
|
|
31
|
+
channels: AcquisitionChannel[]
|
|
32
|
+
conversion: ConversionModel
|
|
33
|
+
attributionBridge?: AttributionBridge
|
|
34
|
+
sitesBridge?: SitesPerformanceBridge
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const RANGE_DAYS: Record<DateRangeKey, number> = { '7d': 7, '30d': 30, '90d': 90 }
|
|
38
|
+
|
|
39
|
+
function getClient() {
|
|
40
|
+
const supabase = getSupabaseClientOptional() as any
|
|
41
|
+
if (!supabase) throw new Error('Supabase not initialized')
|
|
42
|
+
return supabase
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function requireTenantId(): string {
|
|
46
|
+
const tenantId = getActiveTenantId()
|
|
47
|
+
if (!tenantId) throw new Error('No active tenant')
|
|
48
|
+
return tenantId
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 'Walk-in' → 'walkin', 'paid-search' → 'paidsearch' — origin strings match
|
|
52
|
+
* channel ids OR labels regardless of case/punctuation. */
|
|
53
|
+
function normKey(value: string | null | undefined): string {
|
|
54
|
+
return (value ?? '').toLowerCase().replace(/[^a-z0-9]/g, '')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface AttributionRow {
|
|
58
|
+
kind: 'lead' | 'conversion'
|
|
59
|
+
source: string
|
|
60
|
+
channel_raw: string | null
|
|
61
|
+
occurred_at: string
|
|
62
|
+
value: number | null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function createSupabaseMarketingProvider(
|
|
66
|
+
options: SupabaseMarketingProviderOptions,
|
|
67
|
+
): MarketingDataProvider {
|
|
68
|
+
const { channels, conversion, attributionBridge, sitesBridge } = options
|
|
69
|
+
|
|
70
|
+
const channelByNorm = new Map<string, string>()
|
|
71
|
+
for (const ch of channels) {
|
|
72
|
+
channelByNorm.set(normKey(ch.id), ch.id)
|
|
73
|
+
channelByNorm.set(normKey(ch.label), ch.id)
|
|
74
|
+
}
|
|
75
|
+
const resolveChannel = (raw: string | null): string | null =>
|
|
76
|
+
channelByNorm.get(normKey(raw)) ?? null
|
|
77
|
+
|
|
78
|
+
// Lazy per-tenant seed: the channel set comes from app config (SQL can't know
|
|
79
|
+
// the domain), so the first read upserts the preset rows. Idempotent via the
|
|
80
|
+
// (tenant_id, channel_key) unique index.
|
|
81
|
+
const seeded = new Set<string>()
|
|
82
|
+
async function ensureChannels(tenantId: string): Promise<void> {
|
|
83
|
+
if (seeded.has(tenantId)) return
|
|
84
|
+
seeded.add(tenantId)
|
|
85
|
+
await getClient()
|
|
86
|
+
.from(T.channels)
|
|
87
|
+
.upsert(
|
|
88
|
+
channels.map((c) => ({
|
|
89
|
+
tenant_id: tenantId,
|
|
90
|
+
channel_key: c.id,
|
|
91
|
+
label: c.label,
|
|
92
|
+
icon: c.icon,
|
|
93
|
+
kind: c.kind,
|
|
94
|
+
})),
|
|
95
|
+
{ onConflict: 'tenant_id,channel_key', ignoreDuplicates: true },
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// One store.load() fans out to overview + channels + funnel + campaigns, and
|
|
100
|
+
// dashboard widgets pile on top — without dedup that's ~10 concurrent
|
|
101
|
+
// requests per mount (a stampede the instant mock never surfaced). Share
|
|
102
|
+
// in-flight promises and cache briefly; writes clear the cache.
|
|
103
|
+
const CACHE_TTL_MS = 30_000
|
|
104
|
+
const cache = new Map<string, { at: number; promise: Promise<unknown> }>()
|
|
105
|
+
function memo<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
106
|
+
const hit = cache.get(key)
|
|
107
|
+
if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.promise as Promise<T>
|
|
108
|
+
const promise = fn().catch((err) => {
|
|
109
|
+
cache.delete(key)
|
|
110
|
+
throw err
|
|
111
|
+
})
|
|
112
|
+
cache.set(key, { at: Date.now(), promise })
|
|
113
|
+
return promise
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function windowFor(range: DateRangeKey): { since: Date; days: number } {
|
|
117
|
+
const days = RANGE_DAYS[range]
|
|
118
|
+
// Quantized to the minute so equal ranges hit the same cache key.
|
|
119
|
+
const now = Math.floor(Date.now() / 60_000) * 60_000
|
|
120
|
+
return { since: new Date(now - days * 86_400_000), days }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function fetchAttribution(
|
|
124
|
+
tenantId: string,
|
|
125
|
+
since: Date,
|
|
126
|
+
until?: Date,
|
|
127
|
+
): Promise<AttributionRow[]> {
|
|
128
|
+
const key = `attr:${tenantId}:${since.getTime()}:${until?.getTime() ?? ''}`
|
|
129
|
+
return memo(key, async () => {
|
|
130
|
+
let q = getClient()
|
|
131
|
+
.from(V.attribution)
|
|
132
|
+
.select('kind, source, channel_raw, occurred_at, value')
|
|
133
|
+
.eq('tenant_id', tenantId)
|
|
134
|
+
.gte('occurred_at', since.toISOString())
|
|
135
|
+
// Leads always count; conversions only from the vertical's source.
|
|
136
|
+
.or(`kind.eq.lead,and(kind.eq.conversion,source.eq.${conversion.source})`)
|
|
137
|
+
if (until) q = q.lt('occurred_at', until.toISOString())
|
|
138
|
+
const { data, error } = await q
|
|
139
|
+
if (error) throw error
|
|
140
|
+
return (data ?? []) as AttributionRow[]
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface ChannelRollup {
|
|
145
|
+
leads: number
|
|
146
|
+
conversions: number
|
|
147
|
+
value: number
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function rollup(rows: AttributionRow[]): Map<string, ChannelRollup> {
|
|
151
|
+
const map = new Map<string, ChannelRollup>()
|
|
152
|
+
for (const row of rows) {
|
|
153
|
+
const channelId = resolveChannel(row.channel_raw)
|
|
154
|
+
if (!channelId) continue
|
|
155
|
+
const agg = map.get(channelId) ?? { leads: 0, conversions: 0, value: 0 }
|
|
156
|
+
if (row.kind === 'lead') agg.leads += 1
|
|
157
|
+
else {
|
|
158
|
+
agg.conversions += 1
|
|
159
|
+
agg.value += Number(row.value ?? conversion.avgValue)
|
|
160
|
+
}
|
|
161
|
+
map.set(channelId, agg)
|
|
162
|
+
}
|
|
163
|
+
return map
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function fetchSpend(
|
|
167
|
+
tenantId: string,
|
|
168
|
+
days: number,
|
|
169
|
+
since: Date,
|
|
170
|
+
): Promise<Map<string, number>> {
|
|
171
|
+
return memo(`spend:${tenantId}:${days}:${since.getTime()}`, () => fetchSpendRaw(tenantId, days, since))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function fetchSpendRaw(
|
|
175
|
+
tenantId: string,
|
|
176
|
+
days: number,
|
|
177
|
+
since: Date,
|
|
178
|
+
): Promise<Map<string, number>> {
|
|
179
|
+
const client = getClient()
|
|
180
|
+
const [channelRows, campaignRows] = await Promise.all([
|
|
181
|
+
client.from(V.channels).select('channel_key, monthly_spend').eq('tenant_id', tenantId),
|
|
182
|
+
client
|
|
183
|
+
.from(V.campaigns)
|
|
184
|
+
.select('channel_key, spend, status, starts_at, ends_at')
|
|
185
|
+
.eq('tenant_id', tenantId)
|
|
186
|
+
.neq('status', 'draft'),
|
|
187
|
+
])
|
|
188
|
+
const spend = new Map<string, number>()
|
|
189
|
+
for (const row of channelRows.data ?? []) {
|
|
190
|
+
const id = resolveChannel(row.channel_key)
|
|
191
|
+
if (!id) continue
|
|
192
|
+
spend.set(id, (spend.get(id) ?? 0) + (Number(row.monthly_spend) * days) / 30)
|
|
193
|
+
}
|
|
194
|
+
for (const row of campaignRows.data ?? []) {
|
|
195
|
+
const id = resolveChannel(row.channel_key)
|
|
196
|
+
if (!id) continue
|
|
197
|
+
// Count a campaign's spend when its window overlaps the query window.
|
|
198
|
+
const ended = row.ends_at ? new Date(row.ends_at) : null
|
|
199
|
+
if (ended && ended < since) continue
|
|
200
|
+
spend.set(id, (spend.get(id) ?? 0) + Number(row.spend))
|
|
201
|
+
}
|
|
202
|
+
return spend
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function channelPerformance(query: MarketingQuery): Promise<ChannelPerformance[]> {
|
|
206
|
+
const tenantId = requireTenantId()
|
|
207
|
+
await ensureChannels(tenantId)
|
|
208
|
+
const { since, days } = windowFor(query.range)
|
|
209
|
+
const [rows, spend] = await Promise.all([
|
|
210
|
+
fetchAttribution(tenantId, since),
|
|
211
|
+
fetchSpend(tenantId, days, since),
|
|
212
|
+
])
|
|
213
|
+
const byChannel = rollup(rows)
|
|
214
|
+
if (attributionBridge) {
|
|
215
|
+
const bridged = await attributionBridge.conversionsByChannel(query)
|
|
216
|
+
for (const b of bridged) {
|
|
217
|
+
const agg = byChannel.get(b.channelId) ?? { leads: 0, conversions: 0, value: 0 }
|
|
218
|
+
agg.conversions = b.conversions
|
|
219
|
+
agg.value = b.value
|
|
220
|
+
byChannel.set(b.channelId, agg)
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const list = channels.map((ch) => {
|
|
224
|
+
const agg = byChannel.get(ch.id) ?? { leads: 0, conversions: 0, value: 0 }
|
|
225
|
+
const chSpend = spend.get(ch.id) ?? 0
|
|
226
|
+
return {
|
|
227
|
+
channelId: ch.id,
|
|
228
|
+
reach: 0,
|
|
229
|
+
leads: agg.leads,
|
|
230
|
+
conversions: agg.conversions,
|
|
231
|
+
spend: Math.round(chSpend),
|
|
232
|
+
value: Math.round(agg.value),
|
|
233
|
+
cvr: 0,
|
|
234
|
+
cpa: agg.conversions > 0 && chSpend > 0 ? chSpend / agg.conversions : 0,
|
|
235
|
+
}
|
|
236
|
+
})
|
|
237
|
+
return query.channelId ? list.filter((c) => c.channelId === query.channelId) : list
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function campaignFromRow(row: Record<string, any>): Campaign {
|
|
241
|
+
return {
|
|
242
|
+
id: row.id,
|
|
243
|
+
name: row.name,
|
|
244
|
+
channelId: row.channel_key,
|
|
245
|
+
status: row.status,
|
|
246
|
+
start: row.starts_at ?? row.created_at,
|
|
247
|
+
end: row.ends_at ?? undefined,
|
|
248
|
+
spend: Number(row.spend ?? 0),
|
|
249
|
+
reach: 0,
|
|
250
|
+
leads: 0,
|
|
251
|
+
conversions: 0,
|
|
252
|
+
value: 0,
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function withDerived(campaign: Campaign, rows: AttributionRow[]): Campaign {
|
|
257
|
+
const start = new Date(campaign.start).getTime()
|
|
258
|
+
const end = campaign.end ? new Date(campaign.end).getTime() : Number.POSITIVE_INFINITY
|
|
259
|
+
let leads = 0
|
|
260
|
+
let conversions = 0
|
|
261
|
+
let value = 0
|
|
262
|
+
for (const row of rows) {
|
|
263
|
+
if (resolveChannel(row.channel_raw) !== campaign.channelId) continue
|
|
264
|
+
const at = new Date(row.occurred_at).getTime()
|
|
265
|
+
if (at < start || at > end) continue
|
|
266
|
+
if (row.kind === 'lead') leads += 1
|
|
267
|
+
else {
|
|
268
|
+
conversions += 1
|
|
269
|
+
value += Number(row.value ?? conversion.avgValue)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return { ...campaign, leads, conversions, value: Math.round(value) }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return {
|
|
276
|
+
channelPerformance,
|
|
277
|
+
|
|
278
|
+
async overview(query: MarketingQuery): Promise<MarketingOverview> {
|
|
279
|
+
const tenantId = requireTenantId()
|
|
280
|
+
const perf = await channelPerformance(query)
|
|
281
|
+
const { since, days } = windowFor(query.range)
|
|
282
|
+
const prevRows = await fetchAttribution(
|
|
283
|
+
tenantId,
|
|
284
|
+
new Date(since.getTime() - days * 86_400_000),
|
|
285
|
+
since,
|
|
286
|
+
)
|
|
287
|
+
const conversions = perf.reduce((s, c) => s + c.conversions, 0)
|
|
288
|
+
const spend = perf.reduce((s, c) => s + c.spend, 0)
|
|
289
|
+
const value = perf.reduce((s, c) => s + c.value, 0)
|
|
290
|
+
const conversionsPrev = prevRows.filter(
|
|
291
|
+
(r) => r.kind === 'conversion' && resolveChannel(r.channel_raw),
|
|
292
|
+
).length
|
|
293
|
+
const top = [...perf].sort((a, b) => b.conversions - a.conversions)[0]
|
|
294
|
+
return {
|
|
295
|
+
conversions,
|
|
296
|
+
conversionsPrev,
|
|
297
|
+
cvr: 0,
|
|
298
|
+
cvrPrev: 0,
|
|
299
|
+
spend,
|
|
300
|
+
cpa: conversions > 0 && spend > 0 ? spend / conversions : 0,
|
|
301
|
+
value,
|
|
302
|
+
topChannelId: top && top.conversions > 0 ? top.channelId : null,
|
|
303
|
+
channelMix: perf.map((c) => ({ channelId: c.channelId, conversions: c.conversions })),
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
|
|
307
|
+
async funnel(query: MarketingQuery): Promise<FunnelStage[]> {
|
|
308
|
+
if (attributionBridge) return attributionBridge.funnel(query)
|
|
309
|
+
const tenantId = requireTenantId()
|
|
310
|
+
const { since } = windowFor(query.range)
|
|
311
|
+
const rows = await fetchAttribution(tenantId, since)
|
|
312
|
+
const leads = rows.filter((r) => r.kind === 'lead').length
|
|
313
|
+
const conversions = rows.filter((r) => r.kind === 'conversion').length
|
|
314
|
+
return [
|
|
315
|
+
{ id: 'leads', label: 'Leads', count: leads, color: '#0ea5e9' },
|
|
316
|
+
{ id: 'converted', label: conversion.labelPlural, count: conversions, color: '#22c55e' },
|
|
317
|
+
]
|
|
318
|
+
},
|
|
319
|
+
|
|
320
|
+
async listCampaigns(query: MarketingQuery): Promise<Campaign[]> {
|
|
321
|
+
const tenantId = requireTenantId()
|
|
322
|
+
const fetchRows = () =>
|
|
323
|
+
memo(`campaigns:${tenantId}`, async () => {
|
|
324
|
+
const { data, error } = await getClient()
|
|
325
|
+
.from(V.campaigns)
|
|
326
|
+
.select('*')
|
|
327
|
+
.eq('tenant_id', tenantId)
|
|
328
|
+
.order('created_at', { ascending: false })
|
|
329
|
+
if (error) throw error
|
|
330
|
+
return (data ?? []) as Record<string, any>[]
|
|
331
|
+
})
|
|
332
|
+
const [data, rows] = await Promise.all([
|
|
333
|
+
fetchRows(),
|
|
334
|
+
fetchAttribution(tenantId, windowFor(query.range).since),
|
|
335
|
+
])
|
|
336
|
+
const list = query.channelId ? data.filter((r) => r.channel_key === query.channelId) : data
|
|
337
|
+
return list.map((row) => withDerived(campaignFromRow(row), rows))
|
|
338
|
+
},
|
|
339
|
+
|
|
340
|
+
async getCampaign(id: string): Promise<Campaign | null> {
|
|
341
|
+
const tenantId = requireTenantId()
|
|
342
|
+
const { data, error } = await getClient()
|
|
343
|
+
.from(V.campaigns)
|
|
344
|
+
.select('*')
|
|
345
|
+
.eq('tenant_id', tenantId)
|
|
346
|
+
.eq('id', id)
|
|
347
|
+
.maybeSingle()
|
|
348
|
+
if (error) throw error
|
|
349
|
+
if (!data) return null
|
|
350
|
+
const campaign = campaignFromRow(data)
|
|
351
|
+
const rows = await fetchAttribution(tenantId, new Date(campaign.start))
|
|
352
|
+
return withDerived(campaign, rows)
|
|
353
|
+
},
|
|
354
|
+
|
|
355
|
+
async saveCampaign(input: SaveCampaignInput): Promise<Campaign> {
|
|
356
|
+
const tenantId = requireTenantId()
|
|
357
|
+
const payload = {
|
|
358
|
+
name: input.name,
|
|
359
|
+
channel_key: input.channelId,
|
|
360
|
+
status: input.status,
|
|
361
|
+
starts_at: input.start || null,
|
|
362
|
+
ends_at: input.end || null,
|
|
363
|
+
spend: input.spend ?? 0,
|
|
364
|
+
}
|
|
365
|
+
if (input.id) {
|
|
366
|
+
const { data, error } = await getClient()
|
|
367
|
+
.from(T.campaigns)
|
|
368
|
+
.update(payload)
|
|
369
|
+
.eq('id', input.id)
|
|
370
|
+
.select('*')
|
|
371
|
+
.single()
|
|
372
|
+
if (error) throw error
|
|
373
|
+
cache.clear()
|
|
374
|
+
return campaignFromRow(data)
|
|
375
|
+
}
|
|
376
|
+
const { data, error } = await getClient()
|
|
377
|
+
.from(T.campaigns)
|
|
378
|
+
.insert({ tenant_id: tenantId, ...payload })
|
|
379
|
+
.select('*')
|
|
380
|
+
.single()
|
|
381
|
+
if (error) throw error
|
|
382
|
+
cache.clear()
|
|
383
|
+
return campaignFromRow(data)
|
|
384
|
+
},
|
|
385
|
+
|
|
386
|
+
async deleteCampaign(id: string): Promise<void> {
|
|
387
|
+
const { error } = await getClient().from(T.campaigns).delete().eq('id', id)
|
|
388
|
+
if (error) throw error
|
|
389
|
+
cache.clear()
|
|
390
|
+
},
|
|
391
|
+
|
|
392
|
+
invalidateCache() {
|
|
393
|
+
cache.clear()
|
|
394
|
+
},
|
|
395
|
+
|
|
396
|
+
async landingPages(query: MarketingQuery): Promise<LandingPagePerf[]> {
|
|
397
|
+
if (sitesBridge) return sitesBridge.landingPages(query)
|
|
398
|
+
return []
|
|
399
|
+
},
|
|
400
|
+
}
|
|
401
|
+
}
|
package/src/data/tables.ts
CHANGED
|
@@ -4,4 +4,13 @@ export const T = {
|
|
|
4
4
|
socialAccounts: 'plg_marketing_social_accounts',
|
|
5
5
|
contentPlans: 'plg_marketing_content_plans',
|
|
6
6
|
contentPosts: 'plg_marketing_content_posts',
|
|
7
|
+
channels: 'plg_marketing_channels',
|
|
8
|
+
campaigns: 'plg_marketing_campaigns',
|
|
9
|
+
} as const
|
|
10
|
+
|
|
11
|
+
// Read views (bridge views over spine + plugin tables; see 006_analytics_views.sql)
|
|
12
|
+
export const V = {
|
|
13
|
+
channels: 'v_marketing_channels',
|
|
14
|
+
campaigns: 'v_marketing_campaigns',
|
|
15
|
+
attribution: 'v_marketing_attribution',
|
|
7
16
|
} as const
|
package/src/data/types.ts
CHANGED
|
@@ -34,6 +34,8 @@ export interface MarketingDataProvider {
|
|
|
34
34
|
deleteCampaign(id: string): Promise<void>
|
|
35
35
|
funnel(query: MarketingQuery): Promise<FunnelStage[]>
|
|
36
36
|
landingPages(query: MarketingQuery): Promise<LandingPagePerf[]>
|
|
37
|
+
/** Drop any provider-side read cache (external writes, e.g. agent RPCs). */
|
|
38
|
+
invalidateCache?(): void
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
// ---------------------------------------------------------------------------
|