@fayz-ai/plugin-marketing 0.8.1 → 0.9.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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.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 +16 -12
- 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
- package/dist/index.cjs +0 -4551
- package/dist/index.cjs.map +0 -1
package/src/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from 'react'
|
|
2
2
|
import type { PluginManifest, PluginRegistryDef, PluginScope, VerticalId } from '@fayz-ai/core'
|
|
3
|
-
import { createSafeDataProvider,
|
|
3
|
+
import { createSafeDataProvider, registerTranslations } from '@fayz-ai/core'
|
|
4
4
|
import { PluginSettingsPanel } from '@fayz-ai/saas'
|
|
5
5
|
import { MarketingPage } from './MarketingPage'
|
|
6
6
|
import { SettingsView } from './views/SettingsView'
|
|
@@ -17,12 +17,14 @@ import type {
|
|
|
17
17
|
SitesPerformanceBridge,
|
|
18
18
|
} from './data/types'
|
|
19
19
|
import { createMockMarketingProvider } from './data/mock'
|
|
20
|
+
import { createSupabaseMarketingProvider } from './data/supabase'
|
|
21
|
+
import { T } from './data/tables'
|
|
20
22
|
import type { ContentPlannerProvider } from './data/contentTypes'
|
|
21
23
|
import { createMockContentPlannerProvider } from './data/contentMock'
|
|
22
24
|
import { createSupabaseContentPlannerProvider } from './data/contentSupabase'
|
|
23
25
|
import { createMarketingStore } from './store'
|
|
24
26
|
import { createContentPlannerStore } from './views/content/contentStore'
|
|
25
|
-
import { MIGRATION_000_PLG_RENAME, MIGRATION_001_CONTENT_PLANNER, MIGRATION_002_MULTI_PLATFORM, MIGRATION_003_RECORDING_OPS, MIGRATION_004_RANKLAYER } from './migrations'
|
|
27
|
+
import { MIGRATION_000_PLG_RENAME, MIGRATION_001_CONTENT_PLANNER, MIGRATION_002_MULTI_PLATFORM, MIGRATION_003_RECORDING_OPS, MIGRATION_004_RANKLAYER, MIGRATION_005_ANALYTICS_BASE, MIGRATION_006_ANALYTICS_VIEWS, MIGRATION_007_AGENT_RPCS } from './migrations'
|
|
26
28
|
import { ranklayerConnectorDef } from './integrations/ranklayer/connectorDef'
|
|
27
29
|
import { DEFAULT_CURRENCY, type MarketingCurrency } from './format'
|
|
28
30
|
import { MARKETING_PRESETS, type MarketingDomain, type MarketingDomainModules } from './presets'
|
|
@@ -93,16 +95,26 @@ function resolveConfig(options?: MarketingPluginOptions): { config: ResolvedMark
|
|
|
93
95
|
return { config, domain }
|
|
94
96
|
}
|
|
95
97
|
|
|
96
|
-
function createSafeProvider(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
98
|
+
function createSafeProvider(
|
|
99
|
+
config: ResolvedMarketingConfig,
|
|
100
|
+
domain: MarketingDomain,
|
|
101
|
+
options?: MarketingPluginOptions,
|
|
102
|
+
): MarketingDataProvider {
|
|
103
|
+
return createSafeDataProvider(
|
|
104
|
+
() => createSupabaseMarketingProvider({
|
|
105
|
+
channels: config.channels,
|
|
106
|
+
conversion: config.conversion,
|
|
107
|
+
attributionBridge: options?.attributionBridge,
|
|
108
|
+
sitesBridge: options?.sitesBridge,
|
|
109
|
+
}),
|
|
110
|
+
() => createMockMarketingProvider({ channels: config.channels, conversion: config.conversion, domain }),
|
|
111
|
+
)
|
|
100
112
|
}
|
|
101
113
|
|
|
102
114
|
export function createMarketingPlugin(options?: MarketingPluginOptions): PluginManifest {
|
|
103
115
|
registerTranslations(marketingLocales)
|
|
104
116
|
const { config, domain } = resolveConfig(options)
|
|
105
|
-
const provider = options?.dataProvider ?? createSafeProvider(config, domain)
|
|
117
|
+
const provider = options?.dataProvider ?? createSafeProvider(config, domain, options)
|
|
106
118
|
const store = createMarketingStore(provider)
|
|
107
119
|
const dashboardWidgets = createMarketingDashboardWidgets({ config, provider, store })
|
|
108
120
|
|
|
@@ -157,6 +169,95 @@ export function createMarketingPlugin(options?: MarketingPluginOptions): PluginM
|
|
|
157
169
|
...(config.modules.contentPlanner ? [{ id: 'marketing.content', label: config.labels.content, group: 'Engage' }] : []),
|
|
158
170
|
...(config.modules.blog ? [{ id: 'marketing.blog', label: config.labels.blog, group: 'Engage' }] : []),
|
|
159
171
|
],
|
|
172
|
+
declaredLimits: [
|
|
173
|
+
...(config.modules.campaigns ? [{ key: 'campaigns_active', label: 'Active campaigns', table: T.campaigns }] : []),
|
|
174
|
+
...(config.modules.contentPlanner ? [{ key: 'content_posts_month', label: 'Content posts / month', table: 'plg_marketing_content_posts', period: 'month' as const }] : []),
|
|
175
|
+
...(config.modules.blog ? [{ key: 'blog_posts', label: 'Blog posts', table: 'plg_blog_posts' }] : []),
|
|
176
|
+
],
|
|
177
|
+
// Read-models for the agent's data primitives (searchRecords/queryData) —
|
|
178
|
+
// mirrors agenda's `agenda:appointments`. Keys are stable ASCII; fields are
|
|
179
|
+
// the provider's camelCase output shape.
|
|
180
|
+
queryEntities: [
|
|
181
|
+
...(config.modules.campaigns ? [{
|
|
182
|
+
key: 'marketing:campaigns',
|
|
183
|
+
writable: false,
|
|
184
|
+
entity: {
|
|
185
|
+
name: 'Campaign',
|
|
186
|
+
namePlural: 'Campaigns',
|
|
187
|
+
icon: 'Megaphone',
|
|
188
|
+
permission: { feature: 'marketing', action: 'read' as const },
|
|
189
|
+
fields: [
|
|
190
|
+
{ key: 'name', label: 'Name', type: 'text' as const, searchable: true },
|
|
191
|
+
{ key: 'channelKey', label: 'Channel', type: 'text' as const, searchable: true },
|
|
192
|
+
{ key: 'channelLabel', label: 'Channel label', type: 'text' as const },
|
|
193
|
+
{ key: 'status', label: 'Status', type: 'text' as const },
|
|
194
|
+
{ key: 'startsAt', label: 'Starts at', type: 'text' as const },
|
|
195
|
+
{ key: 'endsAt', label: 'Ends at', type: 'text' as const },
|
|
196
|
+
{ key: 'spend', label: 'Spend', type: 'number' as const },
|
|
197
|
+
{ key: 'createdAt', label: 'Created at', type: 'text' as const },
|
|
198
|
+
],
|
|
199
|
+
data: {
|
|
200
|
+
table: 'v_marketing_campaigns',
|
|
201
|
+
tenantScoped: true,
|
|
202
|
+
searchColumns: ['name', 'channel_key'],
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
}] : []),
|
|
206
|
+
...(config.modules.channels ? [{
|
|
207
|
+
key: 'marketing:channels',
|
|
208
|
+
writable: false,
|
|
209
|
+
entity: {
|
|
210
|
+
name: 'Marketing channel',
|
|
211
|
+
namePlural: 'Marketing channels',
|
|
212
|
+
icon: 'Radio',
|
|
213
|
+
permission: { feature: 'marketing', action: 'read' as const },
|
|
214
|
+
fields: [
|
|
215
|
+
{ key: 'channelKey', label: 'Key', type: 'text' as const, searchable: true },
|
|
216
|
+
{ key: 'label', label: 'Channel', type: 'text' as const, searchable: true },
|
|
217
|
+
{ key: 'kind', label: 'Type', type: 'text' as const },
|
|
218
|
+
{ key: 'isActive', label: 'Active', type: 'boolean' as const },
|
|
219
|
+
{ key: 'monthlySpend', label: 'Monthly spend', type: 'number' as const },
|
|
220
|
+
],
|
|
221
|
+
data: {
|
|
222
|
+
table: 'v_marketing_channels',
|
|
223
|
+
tenantScoped: true,
|
|
224
|
+
searchColumns: ['label', 'channel_key'],
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
}] : []),
|
|
228
|
+
...(config.modules.contentPlanner ? [{
|
|
229
|
+
key: 'marketing:contentPosts',
|
|
230
|
+
writable: false,
|
|
231
|
+
entity: {
|
|
232
|
+
name: 'Content post',
|
|
233
|
+
namePlural: 'Content posts',
|
|
234
|
+
icon: 'FileText',
|
|
235
|
+
permission: { feature: 'marketing.content', action: 'read' as const },
|
|
236
|
+
fields: [
|
|
237
|
+
{ key: 'title', label: 'Title', type: 'text' as const, searchable: true },
|
|
238
|
+
{ key: 'format', label: 'Format', type: 'text' as const },
|
|
239
|
+
{ key: 'status', label: 'Status', type: 'text' as const },
|
|
240
|
+
{ key: 'weekNumber', label: 'Week', type: 'number' as const },
|
|
241
|
+
{ key: 'scheduledDate', label: 'Scheduled date', type: 'text' as const },
|
|
242
|
+
{ key: 'hook', label: 'Hook', type: 'text' as const, searchable: true },
|
|
243
|
+
],
|
|
244
|
+
data: {
|
|
245
|
+
table: T.contentPosts,
|
|
246
|
+
tenantScoped: true,
|
|
247
|
+
searchColumns: ['title', 'hook'],
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
}] : []),
|
|
251
|
+
],
|
|
252
|
+
declaredRpcs: [
|
|
253
|
+
...(config.modules.campaigns ? [{
|
|
254
|
+
name: 'agent_marketing_create_campaign',
|
|
255
|
+
kind: 'write' as const,
|
|
256
|
+
description:
|
|
257
|
+
'Guarded campaign create: agent_guard (role→plan→campaigns_active cap), channel validated against the tenant channel set, audited.',
|
|
258
|
+
audits: true,
|
|
259
|
+
}] : []),
|
|
260
|
+
],
|
|
160
261
|
navigation: [
|
|
161
262
|
{
|
|
162
263
|
section: options?.navSection ?? 'main',
|
|
@@ -216,6 +317,24 @@ export function createMarketingPlugin(options?: MarketingPluginOptions): PluginM
|
|
|
216
317
|
sql: MIGRATION_004_RANKLAYER,
|
|
217
318
|
description: 'RankLayer connector state: plg_marketing_ranklayer_integrations + _sync_log (tenant RLS)',
|
|
218
319
|
},
|
|
320
|
+
{
|
|
321
|
+
id: 'marketing-005-analytics-base',
|
|
322
|
+
version: '1.4.0',
|
|
323
|
+
sql: MIGRATION_005_ANALYTICS_BASE,
|
|
324
|
+
description: 'Analytics base: plg_marketing_channels + plg_marketing_campaigns with canonical tenant RLS',
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
id: 'marketing-006-analytics-views',
|
|
328
|
+
version: '1.4.0',
|
|
329
|
+
sql: MIGRATION_006_ANALYTICS_VIEWS,
|
|
330
|
+
description: 'Read views v_marketing_channels/_campaigns + generic spine-only v_marketing_attribution',
|
|
331
|
+
},
|
|
332
|
+
{
|
|
333
|
+
id: 'marketing-007-agent-rpcs',
|
|
334
|
+
version: '1.4.0',
|
|
335
|
+
sql: MIGRATION_007_AGENT_RPCS,
|
|
336
|
+
description: 'agent_marketing_create_campaign — guarded, audited server-plane campaign create',
|
|
337
|
+
},
|
|
219
338
|
],
|
|
220
339
|
// RankLayer SEO connector — renders in the Integrações settings tab. Scaffold
|
|
221
340
|
// (control plane only); the real sync lands via an external PR (RANKLAYER.md).
|
|
@@ -260,18 +379,26 @@ export function createMarketingPlugin(options?: MarketingPluginOptions): PluginM
|
|
|
260
379
|
{
|
|
261
380
|
id: 'marketing.create-campaign',
|
|
262
381
|
name: 'createCampaign',
|
|
263
|
-
description:
|
|
382
|
+
description:
|
|
383
|
+
'Creates an acquisition campaign on a channel. Resolve the channel first via queryData/searchRecords on marketing channels (use its channel key). The user confirms before creating.',
|
|
264
384
|
icon: 'Plus',
|
|
265
385
|
mode: 'persist' as const,
|
|
386
|
+
limitKey: 'campaigns_active',
|
|
387
|
+
execution: { plane: 'server' as const, kind: 'rpc' as const, rpc: 'agent_marketing_create_campaign' },
|
|
266
388
|
category: 'Marketing',
|
|
267
389
|
parameters: {
|
|
268
390
|
type: 'object' as const,
|
|
269
391
|
properties: {
|
|
270
392
|
name: { type: 'string' as const, description: 'Campaign name' },
|
|
271
|
-
|
|
393
|
+
channel_key: { type: 'string' as const, description: "Acquisition channel key (e.g. 'instagram') or its label" },
|
|
394
|
+
status: { type: 'string' as const, enum: ['draft', 'active', 'paused'], description: 'Defaults to draft' },
|
|
395
|
+
starts_at: { type: 'string' as const, description: 'ISO start date-time (defaults to now)' },
|
|
396
|
+
ends_at: { type: 'string' as const, description: 'ISO end date-time (optional)' },
|
|
397
|
+
spend: { type: 'number' as const, description: 'Planned/committed spend (optional)' },
|
|
272
398
|
},
|
|
273
|
-
required: ['name', '
|
|
399
|
+
required: ['name', 'channel_key'],
|
|
274
400
|
},
|
|
401
|
+
suggestions: [{ label: 'Create an Instagram campaign for this month' }],
|
|
275
402
|
permission: { feature: 'marketing', action: 'create' as const },
|
|
276
403
|
},
|
|
277
404
|
],
|
|
@@ -304,6 +431,7 @@ export type {
|
|
|
304
431
|
} from './types'
|
|
305
432
|
export { MARKETING_PRESETS, type MarketingDomain } from './presets'
|
|
306
433
|
export { createMockMarketingProvider } from './data/mock'
|
|
434
|
+
export { createSupabaseMarketingProvider } from './data/supabase'
|
|
307
435
|
export type {
|
|
308
436
|
ContentPlannerProvider,
|
|
309
437
|
ContentPlan,
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
-- Marketing Plugin: analytics base tables (channels + campaigns).
|
|
2
|
+
-- Prefix: plg_marketing_
|
|
3
|
+
-- Channels are tenant-owned rows lazily seeded from the app's domain preset
|
|
4
|
+
-- (channel_key = preset/config id). Campaign performance is DERIVED at read
|
|
5
|
+
-- time from v_marketing_attribution (006); only spend is stored.
|
|
6
|
+
-- Canonical RLS form: tenant_id IN (SELECT public.user_tenant_ids()).
|
|
7
|
+
|
|
8
|
+
CREATE TABLE IF NOT EXISTS public.plg_marketing_channels (
|
|
9
|
+
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
10
|
+
tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
|
|
11
|
+
channel_key text NOT NULL,
|
|
12
|
+
label text NOT NULL,
|
|
13
|
+
icon text,
|
|
14
|
+
kind text NOT NULL DEFAULT 'organic'
|
|
15
|
+
CHECK (kind IN ('paid', 'organic', 'social', 'referral', 'direct', 'outbound')),
|
|
16
|
+
is_active boolean NOT NULL DEFAULT true,
|
|
17
|
+
monthly_spend numeric NOT NULL DEFAULT 0,
|
|
18
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
19
|
+
updated_at timestamptz NOT NULL DEFAULT now()
|
|
20
|
+
);
|
|
21
|
+
CREATE INDEX IF NOT EXISTS idx_plg_marketing_channels_tenant ON public.plg_marketing_channels(tenant_id);
|
|
22
|
+
CREATE UNIQUE INDEX IF NOT EXISTS u_plg_marketing_channels_tenant_key ON public.plg_marketing_channels(tenant_id, channel_key);
|
|
23
|
+
|
|
24
|
+
CREATE TABLE IF NOT EXISTS public.plg_marketing_campaigns (
|
|
25
|
+
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
26
|
+
tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
|
|
27
|
+
name text NOT NULL,
|
|
28
|
+
channel_key text NOT NULL,
|
|
29
|
+
status text NOT NULL DEFAULT 'draft'
|
|
30
|
+
CHECK (status IN ('active', 'paused', 'ended', 'draft')),
|
|
31
|
+
starts_at timestamptz,
|
|
32
|
+
ends_at timestamptz,
|
|
33
|
+
spend numeric NOT NULL DEFAULT 0,
|
|
34
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
35
|
+
updated_at timestamptz NOT NULL DEFAULT now()
|
|
36
|
+
);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS idx_plg_marketing_campaigns_tenant ON public.plg_marketing_campaigns(tenant_id);
|
|
38
|
+
CREATE INDEX IF NOT EXISTS idx_plg_marketing_campaigns_channel ON public.plg_marketing_campaigns(tenant_id, channel_key);
|
|
39
|
+
|
|
40
|
+
DO $$
|
|
41
|
+
DECLARE t text;
|
|
42
|
+
BEGIN
|
|
43
|
+
FOR t IN SELECT unnest(ARRAY['plg_marketing_channels','plg_marketing_campaigns'])
|
|
44
|
+
LOOP
|
|
45
|
+
EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);
|
|
46
|
+
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON public.%I TO authenticated', t);
|
|
47
|
+
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_select') THEN
|
|
48
|
+
EXECUTE format('CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_select', t);
|
|
49
|
+
END IF;
|
|
50
|
+
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_insert') THEN
|
|
51
|
+
EXECUTE format('CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_insert', t);
|
|
52
|
+
END IF;
|
|
53
|
+
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_update') THEN
|
|
54
|
+
EXECUTE format('CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_update', t);
|
|
55
|
+
END IF;
|
|
56
|
+
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_delete') THEN
|
|
57
|
+
EXECUTE format('CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_delete', t);
|
|
58
|
+
END IF;
|
|
59
|
+
END LOOP;
|
|
60
|
+
END $$;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
-- Marketing Plugin: analytics read views.
|
|
2
|
+
-- v_marketing_channels / v_marketing_campaigns — bridge views for the surface
|
|
3
|
+
-- and the agent's data primitives.
|
|
4
|
+
-- v_marketing_attribution — GENERIC, spine-only attribution event stream
|
|
5
|
+
-- (people/appointments/orders metadata). `channel_raw` is the unnormalized
|
|
6
|
+
-- origin string; the provider matches it against the app's channel set
|
|
7
|
+
-- (id or label, case/punctuation-insensitive).
|
|
8
|
+
-- Apps whose origin lives in an app-local extension table (e.g. beauty's
|
|
9
|
+
-- clients.origin) may CREATE OR REPLACE this view in their own incubator
|
|
10
|
+
-- migration, KEEPING the column contract:
|
|
11
|
+
-- (tenant_id uuid, kind text, source text, channel_raw text,
|
|
12
|
+
-- occurred_at timestamptz, value numeric)
|
|
13
|
+
|
|
14
|
+
CREATE OR REPLACE VIEW public.v_marketing_channels WITH (security_invoker=true) AS
|
|
15
|
+
SELECT c.id, c.tenant_id, c.channel_key, c.label, c.icon, c.kind,
|
|
16
|
+
c.is_active, c.monthly_spend, c.created_at, c.updated_at
|
|
17
|
+
FROM public.plg_marketing_channels c;
|
|
18
|
+
GRANT SELECT ON public.v_marketing_channels TO authenticated;
|
|
19
|
+
|
|
20
|
+
CREATE OR REPLACE VIEW public.v_marketing_campaigns WITH (security_invoker=true) AS
|
|
21
|
+
SELECT g.id, g.tenant_id, g.name, g.channel_key, ch.label AS channel_label,
|
|
22
|
+
g.status, g.starts_at, g.ends_at, g.spend, g.created_at, g.updated_at
|
|
23
|
+
FROM public.plg_marketing_campaigns g
|
|
24
|
+
LEFT JOIN public.plg_marketing_channels ch
|
|
25
|
+
ON ch.tenant_id = g.tenant_id AND ch.channel_key = g.channel_key;
|
|
26
|
+
GRANT SELECT ON public.v_marketing_campaigns TO authenticated;
|
|
27
|
+
|
|
28
|
+
CREATE OR REPLACE VIEW public.v_marketing_attribution WITH (security_invoker=true) AS
|
|
29
|
+
-- lead events (CRM leads; sourceId aligns with lead-sources/channel ids)
|
|
30
|
+
SELECT p.tenant_id,
|
|
31
|
+
'lead'::text AS kind,
|
|
32
|
+
'crm'::text AS source,
|
|
33
|
+
COALESCE(p.metadata->>'sourceId', p.metadata->>'sourceName', p.metadata->>'origin') AS channel_raw,
|
|
34
|
+
p.created_at AS occurred_at,
|
|
35
|
+
NULLIF(p.metadata->>'value', '')::numeric AS value
|
|
36
|
+
FROM public.people p
|
|
37
|
+
WHERE p.kind = 'lead'
|
|
38
|
+
UNION ALL
|
|
39
|
+
-- booking conversions (agenda verticals)
|
|
40
|
+
SELECT b.tenant_id, 'conversion', 'agenda',
|
|
41
|
+
COALESCE(b.metadata->>'origin', pc.metadata->>'origin', pc.metadata->>'sourceId', pc.metadata->>'sourceName'),
|
|
42
|
+
b.starts_at,
|
|
43
|
+
o.total
|
|
44
|
+
FROM public.appointments b
|
|
45
|
+
LEFT JOIN public.people pc ON pc.id = b.party_id
|
|
46
|
+
LEFT JOIN public.orders o ON o.id = b.order_id
|
|
47
|
+
WHERE b.status NOT IN ('cancelled', 'no_show')
|
|
48
|
+
UNION ALL
|
|
49
|
+
-- order conversions (commerce verticals)
|
|
50
|
+
SELECT o.tenant_id, 'conversion', 'orders',
|
|
51
|
+
COALESCE(o.metadata->>'origin', pp.metadata->>'origin', pp.metadata->>'sourceId'),
|
|
52
|
+
o.created_at,
|
|
53
|
+
o.total
|
|
54
|
+
FROM public.orders o
|
|
55
|
+
LEFT JOIN public.people pp ON pp.id = o.party_id
|
|
56
|
+
WHERE o.kind NOT IN ('appointment', 'deal')
|
|
57
|
+
AND o.status NOT IN ('cancelled', 'draft')
|
|
58
|
+
UNION ALL
|
|
59
|
+
-- won-deal conversions (CRM verticals)
|
|
60
|
+
SELECT o.tenant_id, 'conversion', 'crm',
|
|
61
|
+
COALESCE(pp.metadata->>'sourceId', pp.metadata->>'sourceName', o.metadata->>'origin'),
|
|
62
|
+
o.updated_at,
|
|
63
|
+
o.total
|
|
64
|
+
FROM public.orders o
|
|
65
|
+
LEFT JOIN public.people pp ON pp.id = o.party_id
|
|
66
|
+
WHERE o.kind = 'deal' AND o.status = 'won';
|
|
67
|
+
|
|
68
|
+
GRANT SELECT ON public.v_marketing_attribution TO authenticated;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
-- ============================================================================
|
|
2
|
+
-- plugin-marketing 007: server-plane agent write RPC.
|
|
3
|
+
--
|
|
4
|
+
-- public.agent_marketing_create_campaign — guarded campaign create for the
|
|
5
|
+
-- assistant. Mirrors agent_agenda_create_appointment (agenda 005):
|
|
6
|
+
-- * actor-authorized: public.agent_guard (spine 015) runs role→plan→limit
|
|
7
|
+
-- BEFORE anything — denial comes back as structured jsonb;
|
|
8
|
+
-- * channel is validated against the tenant's plg_marketing_channels rows
|
|
9
|
+
-- (key or label, case/punctuation-insensitive); when the tenant has no
|
|
10
|
+
-- channel rows yet (surface not opened → lazy seed not run) the raw key is
|
|
11
|
+
-- accepted as-is;
|
|
12
|
+
-- * audited: audit_logs row with the acting user.
|
|
13
|
+
--
|
|
14
|
+
-- Contract (all agent_* RPCs): (p_tenant_id, p_actor_user_id, p_payload jsonb)
|
|
15
|
+
-- → jsonb {ok:true, id, record:{...}} | {ok:false, denial:{...}} | {ok:false,
|
|
16
|
+
-- error text}. GRANT authenticated+service_role — NEVER anon.
|
|
17
|
+
-- ============================================================================
|
|
18
|
+
|
|
19
|
+
CREATE OR REPLACE FUNCTION public.agent_marketing_create_campaign(
|
|
20
|
+
p_tenant_id uuid,
|
|
21
|
+
p_actor_user_id uuid,
|
|
22
|
+
p_payload jsonb
|
|
23
|
+
) RETURNS jsonb
|
|
24
|
+
LANGUAGE plpgsql SECURITY DEFINER
|
|
25
|
+
SET search_path = public
|
|
26
|
+
AS $$
|
|
27
|
+
DECLARE
|
|
28
|
+
v_denial jsonb;
|
|
29
|
+
v_used int;
|
|
30
|
+
v_name text;
|
|
31
|
+
v_channel_raw text;
|
|
32
|
+
v_channel_key text;
|
|
33
|
+
v_status text;
|
|
34
|
+
v_starts timestamptz;
|
|
35
|
+
v_ends timestamptz;
|
|
36
|
+
v_spend numeric;
|
|
37
|
+
v_has_channels boolean;
|
|
38
|
+
v_id uuid;
|
|
39
|
+
BEGIN
|
|
40
|
+
-- ── payload ──────────────────────────────────────────────────────────────
|
|
41
|
+
v_name := left(trim(p_payload->>'name'), 200);
|
|
42
|
+
v_channel_raw := trim(p_payload->>'channel_key');
|
|
43
|
+
v_status := COALESCE(NULLIF(trim(p_payload->>'status'), ''), 'draft');
|
|
44
|
+
v_spend := COALESCE(NULLIF(p_payload->>'spend', '')::numeric, 0);
|
|
45
|
+
BEGIN
|
|
46
|
+
v_starts := NULLIF(p_payload->>'starts_at', '')::timestamptz;
|
|
47
|
+
v_ends := NULLIF(p_payload->>'ends_at', '')::timestamptz;
|
|
48
|
+
EXCEPTION WHEN OTHERS THEN
|
|
49
|
+
RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);
|
|
50
|
+
END;
|
|
51
|
+
IF v_name IS NULL OR v_name = '' OR v_channel_raw IS NULL OR v_channel_raw = '' THEN
|
|
52
|
+
RETURN jsonb_build_object('ok', false, 'error', 'name and channel_key are required');
|
|
53
|
+
END IF;
|
|
54
|
+
IF v_status NOT IN ('active', 'paused', 'ended', 'draft') THEN
|
|
55
|
+
RETURN jsonb_build_object('ok', false, 'error', 'status must be one of active|paused|ended|draft');
|
|
56
|
+
END IF;
|
|
57
|
+
|
|
58
|
+
-- ── authorization: role → plan → campaigns_active cap ────────────────────
|
|
59
|
+
SELECT count(*) INTO v_used FROM plg_marketing_campaigns c
|
|
60
|
+
WHERE c.tenant_id = p_tenant_id AND c.status = 'active';
|
|
61
|
+
v_denial := agent_guard(p_tenant_id, p_actor_user_id,
|
|
62
|
+
'marketing', 'create', 'campaigns_active', v_used,
|
|
63
|
+
CASE WHEN v_status = 'active' THEN 1 ELSE 0 END);
|
|
64
|
+
IF v_denial IS NOT NULL THEN
|
|
65
|
+
RETURN jsonb_build_object('ok', false, 'denial', v_denial);
|
|
66
|
+
END IF;
|
|
67
|
+
|
|
68
|
+
-- ── channel resolution (key or label, normalized) ────────────────────────
|
|
69
|
+
SELECT EXISTS (SELECT 1 FROM plg_marketing_channels ch WHERE ch.tenant_id = p_tenant_id)
|
|
70
|
+
INTO v_has_channels;
|
|
71
|
+
IF v_has_channels THEN
|
|
72
|
+
SELECT ch.channel_key INTO v_channel_key
|
|
73
|
+
FROM plg_marketing_channels ch
|
|
74
|
+
WHERE ch.tenant_id = p_tenant_id
|
|
75
|
+
AND (
|
|
76
|
+
regexp_replace(lower(ch.channel_key), '[^a-z0-9]', '', 'g')
|
|
77
|
+
= regexp_replace(lower(v_channel_raw), '[^a-z0-9]', '', 'g')
|
|
78
|
+
OR regexp_replace(lower(ch.label), '[^a-z0-9]', '', 'g')
|
|
79
|
+
= regexp_replace(lower(v_channel_raw), '[^a-z0-9]', '', 'g')
|
|
80
|
+
)
|
|
81
|
+
LIMIT 1;
|
|
82
|
+
IF v_channel_key IS NULL THEN
|
|
83
|
+
RETURN jsonb_build_object('ok', false, 'error',
|
|
84
|
+
'unknown channel "' || v_channel_raw || '" — valid channels: ' ||
|
|
85
|
+
COALESCE((SELECT string_agg(ch.channel_key, ', ' ORDER BY ch.channel_key)
|
|
86
|
+
FROM plg_marketing_channels ch WHERE ch.tenant_id = p_tenant_id), ''));
|
|
87
|
+
END IF;
|
|
88
|
+
ELSE
|
|
89
|
+
v_channel_key := v_channel_raw;
|
|
90
|
+
END IF;
|
|
91
|
+
|
|
92
|
+
-- ── write + audit ────────────────────────────────────────────────────────
|
|
93
|
+
INSERT INTO plg_marketing_campaigns (tenant_id, name, channel_key, status, starts_at, ends_at, spend)
|
|
94
|
+
VALUES (p_tenant_id, v_name, v_channel_key, v_status, COALESCE(v_starts, now()), v_ends, v_spend)
|
|
95
|
+
RETURNING id INTO v_id;
|
|
96
|
+
|
|
97
|
+
INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)
|
|
98
|
+
VALUES (p_tenant_id, p_actor_user_id, 'agent.createCampaign', 'marketing_campaign', v_id::text,
|
|
99
|
+
jsonb_build_object('payload', p_payload));
|
|
100
|
+
|
|
101
|
+
RETURN jsonb_build_object(
|
|
102
|
+
'ok', true,
|
|
103
|
+
'id', v_id,
|
|
104
|
+
'record', jsonb_build_object(
|
|
105
|
+
'id', v_id,
|
|
106
|
+
'name', v_name,
|
|
107
|
+
'channel_key', v_channel_key,
|
|
108
|
+
'status', v_status,
|
|
109
|
+
'starts_at', COALESCE(v_starts, now()),
|
|
110
|
+
'spend', v_spend
|
|
111
|
+
)
|
|
112
|
+
);
|
|
113
|
+
END;
|
|
114
|
+
$$;
|
|
115
|
+
|
|
116
|
+
REVOKE ALL ON FUNCTION public.agent_marketing_create_campaign(uuid, uuid, jsonb) FROM public;
|
|
117
|
+
REVOKE EXECUTE ON FUNCTION public.agent_marketing_create_campaign(uuid, uuid, jsonb) FROM anon;
|
|
118
|
+
GRANT EXECUTE ON FUNCTION public.agent_marketing_create_campaign(uuid, uuid, jsonb)
|
|
119
|
+
TO authenticated, service_role;
|