@fayz-ai/plugin-crm 0.8.0 → 0.8.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/dist/components/CrmGeneralSettings.d.ts.map +1 -1
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/index.cjs +168 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +169 -34
- package/dist/index.js.map +1 -1
- package/dist/lib/form-answers.d.ts +10 -0
- package/dist/lib/form-answers.d.ts.map +1 -0
- package/dist/locales/en.d.ts.map +1 -1
- package/dist/locales/pt-BR.d.ts.map +1 -1
- package/dist/migrations/index.d.ts +2 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/public/context.d.ts +23 -0
- package/dist/public/context.d.ts.map +1 -0
- package/dist/public/createPublicFormsPlugin.d.ts +38 -0
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -0
- package/dist/public/data.supabase.d.ts +7 -0
- package/dist/public/data.supabase.d.ts.map +1 -0
- package/dist/public/inbox.d.ts +22 -0
- package/dist/public/inbox.d.ts.map +1 -0
- package/dist/public/index.cjs +306 -0
- package/dist/public/index.cjs.map +1 -0
- package/dist/public/index.d.ts +10 -0
- package/dist/public/index.d.ts.map +1 -0
- package/dist/public/index.js +298 -0
- package/dist/public/index.js.map +1 -0
- package/dist/public/types.d.ts +92 -0
- package/dist/public/types.d.ts.map +1 -0
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadDetailView.d.ts.map +1 -1
- package/dist/views/LeadFormView.d.ts.map +1 -1
- package/dist/views/LeadListView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/dist/views/QuoteFormView.d.ts.map +1 -1
- package/package.json +11 -5
- package/src/components/CrmGeneralSettings.tsx +35 -15
- package/src/data/supabase.ts +47 -4
- package/src/index.ts +9 -0
- package/src/lib/form-answers.tsx +39 -0
- package/src/locales/en.ts +1 -0
- package/src/locales/pt-BR.ts +1 -0
- package/src/migrations/005_public_lead.sql +189 -0
- package/src/migrations/006_lead_enters_pipeline.sql +265 -0
- package/src/migrations/index.ts +461 -1
- package/src/public/context.tsx +69 -0
- package/src/public/createPublicFormsPlugin.ts +188 -0
- package/src/public/data.supabase.ts +86 -0
- package/src/public/inbox.ts +136 -0
- package/src/public/index.ts +30 -0
- package/src/public/types.ts +113 -0
- package/src/views/DealSidebar.tsx +31 -0
- package/src/views/LeadDetailView.tsx +53 -0
- package/src/views/LeadFormView.tsx +10 -0
- package/src/views/LeadListView.tsx +19 -0
- package/src/views/PipelineView.tsx +34 -1
- package/src/views/QuoteFormView.tsx +5 -0
package/src/data/supabase.ts
CHANGED
|
@@ -33,6 +33,27 @@ function getClients() {
|
|
|
33
33
|
return { core: supabase, pub: supabase }
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
/**
|
|
37
|
+
* Patch keys into people.metadata, preserving everything already there.
|
|
38
|
+
*
|
|
39
|
+
* people.metadata is a single opaque bag holding unrelated things: the lead's
|
|
40
|
+
* pipeline `status`, plus `formId`/`fields`/`utm` — the public form's answers,
|
|
41
|
+
* which are the entire content of a lead that arrived from a landing page.
|
|
42
|
+
* A plain `.update({ metadata: {...} })` REPLACES the column, so any code that
|
|
43
|
+
* only meant to set the status was deleting the enquiry. Two call sites did
|
|
44
|
+
* exactly that.
|
|
45
|
+
*
|
|
46
|
+
* Read-merge-write rather than a `jsonb ||` RPC: it matches the pattern already
|
|
47
|
+
* used elsewhere in this file, and these writes are single-operator actions
|
|
48
|
+
* (dragging one card), not concurrent ones.
|
|
49
|
+
*/
|
|
50
|
+
async function mergePersonMetadata(personId: string, patch: Record<string, unknown>): Promise<void> {
|
|
51
|
+
const { core } = getClients()
|
|
52
|
+
const { data: row } = await core.from('people').select('metadata').eq('id', personId).maybeSingle()
|
|
53
|
+
const current = (row?.metadata ?? {}) as Record<string, unknown>
|
|
54
|
+
await core.from('people').update({ metadata: { ...current, ...patch } }).eq('id', personId)
|
|
55
|
+
}
|
|
56
|
+
|
|
36
57
|
export function createSupabaseCrmProvider(options?: {
|
|
37
58
|
clientConversion?: { archetypeKind: string; extensionTable: string; fkColumn: string }
|
|
38
59
|
}): CrmDataProvider {
|
|
@@ -85,7 +106,15 @@ export function createSupabaseCrmProvider(options?: {
|
|
|
85
106
|
return {
|
|
86
107
|
id: r.id, name: r.name, email: r.email, phone: r.phone,
|
|
87
108
|
company: r.company, status: r.lead_status ?? 'new',
|
|
109
|
+
sourceName: r.source_name,
|
|
88
110
|
tags: r.tags ?? [], notes: r.notes,
|
|
111
|
+
// Answers from a public form. Kept as an opaque bag so a new landing
|
|
112
|
+
// page needs no schema change; the detail view renders whatever is here.
|
|
113
|
+
metadata: {
|
|
114
|
+
formId: r.form_id ?? undefined,
|
|
115
|
+
fields: r.custom_fields ?? {},
|
|
116
|
+
utm: r.utm ?? {},
|
|
117
|
+
},
|
|
89
118
|
tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
|
|
90
119
|
} as Lead
|
|
91
120
|
},
|
|
@@ -111,16 +140,19 @@ export function createSupabaseCrmProvider(options?: {
|
|
|
111
140
|
if (partial.email !== undefined) row.email = partial.email
|
|
112
141
|
if (partial.phone !== undefined) row.phone = partial.phone
|
|
113
142
|
if (partial.notes !== undefined) row.notes = partial.notes
|
|
114
|
-
|
|
115
|
-
const { data, error } = await core.from('people').update(row).eq('id', id).select().single()
|
|
143
|
+
const { error } = await core.from('people').update(row).eq('id', id).select().single()
|
|
116
144
|
if (error) throw new Error(error.message)
|
|
145
|
+
// The third call site that replaced the bag. Editing a lead's status from
|
|
146
|
+
// the list wiped formId/fields/utm exactly as dragging its card did — the
|
|
147
|
+
// same fix, applied here too rather than left for the next reader to find.
|
|
148
|
+
if (partial.status) await mergePersonMetadata(id, { status: partial.status })
|
|
117
149
|
return (await provider.getLeadById(id))!
|
|
118
150
|
},
|
|
119
151
|
|
|
120
152
|
async convertLeadToDeal(leadId: string, dealInput: CreateDealInput): Promise<Deal> {
|
|
121
153
|
const { core } = getClients()
|
|
122
154
|
// Update lead status to converted
|
|
123
|
-
await
|
|
155
|
+
await mergePersonMetadata(leadId, { status: 'converted' })
|
|
124
156
|
return provider.createDeal({ ...dealInput, leadId } as any)
|
|
125
157
|
},
|
|
126
158
|
|
|
@@ -175,6 +207,11 @@ export function createSupabaseCrmProvider(options?: {
|
|
|
175
207
|
stageName: r.stage_name, stageColor: r.stage_color,
|
|
176
208
|
probability: r.probability ?? 0, status: r.status ?? 'open',
|
|
177
209
|
contactName: r.contact_name, tags: r.tags ?? [],
|
|
210
|
+
// v_deals exposes de.lead_id and Deal declares leadId, but the mapping
|
|
211
|
+
// dropped it — so DealSidebar's `if (d?.leadId)` never fired and the
|
|
212
|
+
// card opened blank: no contact, no form answers. For a card that came
|
|
213
|
+
// from a form, the lead IS the content.
|
|
214
|
+
leadId: r.lead_id ?? undefined,
|
|
178
215
|
tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
|
|
179
216
|
} as Deal
|
|
180
217
|
},
|
|
@@ -190,6 +227,7 @@ export function createSupabaseCrmProvider(options?: {
|
|
|
190
227
|
stageName: r.stage_name, stageColor: r.stage_color,
|
|
191
228
|
probability: r.probability ?? 0, status: r.status ?? 'open',
|
|
192
229
|
contactName: r.contact_name, tags: r.tags ?? [],
|
|
230
|
+
leadId: r.lead_id ?? undefined,
|
|
193
231
|
tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
|
|
194
232
|
} as Deal))
|
|
195
233
|
|
|
@@ -273,7 +311,12 @@ export function createSupabaseCrmProvider(options?: {
|
|
|
273
311
|
const { data: ext } = await pub.from(T.dealExtensions).select('lead_id').eq('order_id', dealId).single()
|
|
274
312
|
if (ext?.lead_id) {
|
|
275
313
|
const newLeadStatus = deriveLeadStatus(typedStage)
|
|
276
|
-
|
|
314
|
+
// MERGE, never replace. people.metadata is the lead's whole opaque
|
|
315
|
+
// bag — formId, the public form's answers, utm. Writing a bare
|
|
316
|
+
// { status } here silently destroyed all of it, so dragging a card to
|
|
317
|
+
// another column erased the enquiry that created it. Same read-merge
|
|
318
|
+
// pattern already used further down for personMeta/existingMeta.
|
|
319
|
+
await mergePersonMetadata(ext.lead_id, { status: newLeadStatus })
|
|
277
320
|
}
|
|
278
321
|
// Update quote statuses
|
|
279
322
|
const { data: quotes } = await core.from('orders').select('id, status').eq('kind', 'quote')
|
package/src/index.ts
CHANGED
|
@@ -148,6 +148,15 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
|
|
|
148
148
|
{ id: 'crm.quotes', label: config.labels.quotes, group: config.labels.pageTitle },
|
|
149
149
|
{ id: 'crm.pipeline', label: config.labels.pipeline, group: config.labels.pageTitle },
|
|
150
150
|
],
|
|
151
|
+
// Stock quantity caps. leads/deals/quotes share core tables partitioned by
|
|
152
|
+
// `kind` (people/orders), so each declaration carries a kindFilter. A lead
|
|
153
|
+
// create auto-spawns a deal, so the lead guard also gates deal creation;
|
|
154
|
+
// `deals` has no standalone create UI (declared for usage banners/counts).
|
|
155
|
+
declaredLimits: [
|
|
156
|
+
{ key: 'leads', label: 'Leads', table: 'people', kindFilter: 'lead' },
|
|
157
|
+
{ key: 'deals', label: 'Deals', table: 'orders', kindFilter: 'deal' },
|
|
158
|
+
{ key: 'quotes', label: 'Quotes', table: 'orders', kindFilter: 'quote' },
|
|
159
|
+
],
|
|
151
160
|
navigation: [
|
|
152
161
|
{
|
|
153
162
|
section: options?.navSection ?? 'main',
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import React from 'react'
|
|
2
|
+
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// Rendering whatever a public form captured.
|
|
5
|
+
//
|
|
6
|
+
// Deliberately schema-free. Every landing page asks something different — hair
|
|
7
|
+
// coverage on one, a coupon on another, subject/message on a third — and the
|
|
8
|
+
// capture side (create_public_lead) already stores the answers as an opaque bag
|
|
9
|
+
// so a new campaign ships with no migration. The display side needs the same
|
|
10
|
+
// property: anything typed here makes the NEXT form invisible.
|
|
11
|
+
//
|
|
12
|
+
// Shared because two views show the same data and had drifted: the lead detail
|
|
13
|
+
// page rendered answers with private helpers, while the pipeline card rendered
|
|
14
|
+
// none at all.
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
/** `hair_remaining` / `hairRemaining` → "Hair remaining". Keys that arrive
|
|
18
|
+
* already humanized ("Assunto") come back unchanged. */
|
|
19
|
+
export function humanizeKey(key: string): string {
|
|
20
|
+
const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\d])([A-Z])/g, '$1 $2')
|
|
21
|
+
return spaced.charAt(0).toUpperCase() + spaced.slice(1)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Arrays are joined rather than dropped: a multi-select ("Preocupações") is
|
|
25
|
+
* often the most qualifying answer on the form. */
|
|
26
|
+
export function renderFieldValue(value: unknown): React.ReactNode {
|
|
27
|
+
if (value === null || value === undefined || value === '') return null
|
|
28
|
+
if (Array.isArray(value)) return value.length ? value.join(', ') : null
|
|
29
|
+
if (typeof value === 'boolean') return value ? 'Sim' : 'Não'
|
|
30
|
+
if (typeof value === 'object') return JSON.stringify(value)
|
|
31
|
+
return String(value)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Answer entries worth showing, empty values already removed. */
|
|
35
|
+
export function answerEntries(fields: unknown): Array<[string, unknown]> {
|
|
36
|
+
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return []
|
|
37
|
+
return Object.entries(fields as Record<string, unknown>)
|
|
38
|
+
.filter(([, v]) => v !== null && v !== undefined && v !== '')
|
|
39
|
+
}
|
package/src/locales/en.ts
CHANGED
|
@@ -57,6 +57,7 @@ export const en: Record<string, string> = {
|
|
|
57
57
|
"crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
|
|
58
58
|
"crm.leadDetail.assignedTo": "Assigned to",
|
|
59
59
|
"crm.leadDetail.backToList": "Back to list",
|
|
60
|
+
"crm.leadDetail.formAnswers": "Form answers",
|
|
60
61
|
"crm.leadDetail.company": "Company",
|
|
61
62
|
"crm.leadDetail.contactInfo": "Contact Information",
|
|
62
63
|
"crm.leadDetail.createQuote": "Create Quote",
|
package/src/locales/pt-BR.ts
CHANGED
|
@@ -57,6 +57,7 @@ export const ptBR: Record<string, string> = {
|
|
|
57
57
|
"crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
|
|
58
58
|
"crm.leadDetail.assignedTo": "Atribuído a",
|
|
59
59
|
"crm.leadDetail.backToList": "Voltar à lista",
|
|
60
|
+
"crm.leadDetail.formAnswers": "Dados do formulário",
|
|
60
61
|
"crm.leadDetail.company": "Empresa",
|
|
61
62
|
"crm.leadDetail.contactInfo": "Informações de Contato",
|
|
62
63
|
"crm.leadDetail.createQuote": "Criar Orçamento",
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
-- plugin-crm 005: anon-safe lead capture from public sites.
|
|
2
|
+
--
|
|
3
|
+
-- The counterpart of agenda's create_public_booking: a marketing site posts a
|
|
4
|
+
-- form and a lead lands in the CRM of the right tenant. Same shape of trust —
|
|
5
|
+
-- the caller is an anonymous browser holding only a publishable key, so every
|
|
6
|
+
-- decision that matters (which tenant, which status, whether it is spam) is
|
|
7
|
+
-- made here and cannot be set by the caller.
|
|
8
|
+
--
|
|
9
|
+
-- Why p_fields jsonb: every landing page asks something different (hair
|
|
10
|
+
-- coverage on one, discount coupon on another, subject/message on a third).
|
|
11
|
+
-- Modelling those as columns means a migration per campaign — the site this was
|
|
12
|
+
-- built for already had 22 columns on its lead table. They go to people.metadata
|
|
13
|
+
-- under 'fields', which v_leads already reads from, so a new form ships with
|
|
14
|
+
-- zero schema change.
|
|
15
|
+
|
|
16
|
+
CREATE OR REPLACE FUNCTION public.create_public_lead(
|
|
17
|
+
p_tenant_id uuid,
|
|
18
|
+
p_name text,
|
|
19
|
+
p_phone text DEFAULT NULL,
|
|
20
|
+
p_email text DEFAULT NULL,
|
|
21
|
+
p_form_id text DEFAULT NULL,
|
|
22
|
+
p_form_name text DEFAULT NULL,
|
|
23
|
+
p_fields jsonb DEFAULT '{}'::jsonb,
|
|
24
|
+
p_notes text DEFAULT NULL,
|
|
25
|
+
p_utm jsonb DEFAULT '{}'::jsonb
|
|
26
|
+
)
|
|
27
|
+
RETURNS TABLE(lead_id uuid, created_at timestamptz)
|
|
28
|
+
LANGUAGE plpgsql
|
|
29
|
+
SECURITY DEFINER
|
|
30
|
+
SET search_path TO 'public'
|
|
31
|
+
AS $function$
|
|
32
|
+
DECLARE
|
|
33
|
+
v_person_id uuid;
|
|
34
|
+
v_phone text;
|
|
35
|
+
v_email text;
|
|
36
|
+
v_fields jsonb;
|
|
37
|
+
v_utm jsonb;
|
|
38
|
+
v_recent int;
|
|
39
|
+
BEGIN
|
|
40
|
+
-- ---------------------------------------------------------------------
|
|
41
|
+
-- validation: anon-callable, so everything is checked here
|
|
42
|
+
-- ---------------------------------------------------------------------
|
|
43
|
+
IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN
|
|
44
|
+
RAISE EXCEPTION 'invalid name';
|
|
45
|
+
END IF;
|
|
46
|
+
|
|
47
|
+
v_phone := NULLIF(regexp_replace(COALESCE(p_phone, ''), '\D', '', 'g'), '');
|
|
48
|
+
IF v_phone IS NOT NULL AND length(v_phone) NOT BETWEEN 8 AND 15 THEN
|
|
49
|
+
RAISE EXCEPTION 'invalid phone';
|
|
50
|
+
END IF;
|
|
51
|
+
|
|
52
|
+
v_email := NULLIF(trim(COALESCE(p_email, '')), '');
|
|
53
|
+
IF v_email IS NOT NULL AND (length(v_email) > 254 OR v_email !~ '^[^@\s]+@[^@\s]+\.[^@\s]+$') THEN
|
|
54
|
+
RAISE EXCEPTION 'invalid email';
|
|
55
|
+
END IF;
|
|
56
|
+
|
|
57
|
+
-- a lead with no way to reach them back is not a lead
|
|
58
|
+
IF v_phone IS NULL AND v_email IS NULL THEN
|
|
59
|
+
RAISE EXCEPTION 'phone or email required';
|
|
60
|
+
END IF;
|
|
61
|
+
|
|
62
|
+
PERFORM 1 FROM tenants t WHERE t.id = p_tenant_id;
|
|
63
|
+
IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;
|
|
64
|
+
|
|
65
|
+
-- ---------------------------------------------------------------------
|
|
66
|
+
-- custom fields: object-only, bounded, and scalars only.
|
|
67
|
+
-- Bounding the payload keeps a hostile caller from parking documents in
|
|
68
|
+
-- the CRM; flattening nested values keeps the detail panel renderable.
|
|
69
|
+
-- ---------------------------------------------------------------------
|
|
70
|
+
v_fields := COALESCE(p_fields, '{}'::jsonb);
|
|
71
|
+
IF jsonb_typeof(v_fields) <> 'object' THEN
|
|
72
|
+
RAISE EXCEPTION 'fields must be an object';
|
|
73
|
+
END IF;
|
|
74
|
+
IF length(v_fields::text) > 8000 THEN
|
|
75
|
+
RAISE EXCEPTION 'fields too large';
|
|
76
|
+
END IF;
|
|
77
|
+
IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN
|
|
78
|
+
RAISE EXCEPTION 'too many fields';
|
|
79
|
+
END IF;
|
|
80
|
+
|
|
81
|
+
v_utm := COALESCE(p_utm, '{}'::jsonb);
|
|
82
|
+
IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN
|
|
83
|
+
RAISE EXCEPTION 'invalid utm';
|
|
84
|
+
END IF;
|
|
85
|
+
|
|
86
|
+
-- ---------------------------------------------------------------------
|
|
87
|
+
-- anti-spam: same tenant + same contact + same form, twice in 5 minutes is
|
|
88
|
+
-- a double-click or a bot, not two inquiries. Repeat interest days later IS
|
|
89
|
+
-- a new lead, so this window stays deliberately short.
|
|
90
|
+
-- ---------------------------------------------------------------------
|
|
91
|
+
SELECT count(*) INTO v_recent
|
|
92
|
+
FROM people p
|
|
93
|
+
WHERE p.tenant_id = p_tenant_id
|
|
94
|
+
AND p.kind = 'lead'
|
|
95
|
+
AND p.created_at > now() - interval '5 minutes'
|
|
96
|
+
AND COALESCE(p.metadata->>'formId', '') = COALESCE(p_form_id, '')
|
|
97
|
+
AND (
|
|
98
|
+
(v_phone IS NOT NULL AND p.phone = v_phone)
|
|
99
|
+
OR (v_email IS NOT NULL AND p.email = v_email)
|
|
100
|
+
);
|
|
101
|
+
IF v_recent > 0 THEN
|
|
102
|
+
RAISE EXCEPTION 'duplicate submission';
|
|
103
|
+
END IF;
|
|
104
|
+
|
|
105
|
+
-- burst cap per tenant: a flood is never legitimate marketing traffic
|
|
106
|
+
IF (
|
|
107
|
+
SELECT count(*) FROM people p
|
|
108
|
+
WHERE p.tenant_id = p_tenant_id
|
|
109
|
+
AND p.kind = 'lead'
|
|
110
|
+
AND p.created_at > now() - interval '1 minute'
|
|
111
|
+
) >= 20 THEN
|
|
112
|
+
RAISE EXCEPTION 'too many submissions';
|
|
113
|
+
END IF;
|
|
114
|
+
|
|
115
|
+
-- ---------------------------------------------------------------------
|
|
116
|
+
-- the lead. status/kind are hardcoded — the caller cannot promote itself
|
|
117
|
+
-- into a customer or land pre-qualified.
|
|
118
|
+
-- ---------------------------------------------------------------------
|
|
119
|
+
INSERT INTO people (tenant_id, kind, name, phone, email, notes, tags, is_active, metadata)
|
|
120
|
+
VALUES (
|
|
121
|
+
p_tenant_id,
|
|
122
|
+
'lead',
|
|
123
|
+
trim(p_name),
|
|
124
|
+
v_phone,
|
|
125
|
+
v_email,
|
|
126
|
+
left(p_notes, 2000),
|
|
127
|
+
ARRAY[]::text[],
|
|
128
|
+
true,
|
|
129
|
+
jsonb_strip_nulls(
|
|
130
|
+
jsonb_build_object(
|
|
131
|
+
'status', 'new',
|
|
132
|
+
'source', 'public_form',
|
|
133
|
+
'sourceName', COALESCE(NULLIF(trim(COALESCE(p_form_name, '')), ''), 'Site'),
|
|
134
|
+
'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),
|
|
135
|
+
'fields', v_fields,
|
|
136
|
+
'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
)
|
|
140
|
+
RETURNING id, people.created_at INTO v_person_id, created_at;
|
|
141
|
+
|
|
142
|
+
lead_id := v_person_id;
|
|
143
|
+
RETURN NEXT;
|
|
144
|
+
END;
|
|
145
|
+
$function$;
|
|
146
|
+
|
|
147
|
+
-- anon: the whole point. authenticated too, so a logged-in visitor on the same
|
|
148
|
+
-- site takes the identical path.
|
|
149
|
+
GRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb)
|
|
150
|
+
TO anon, authenticated;
|
|
151
|
+
|
|
152
|
+
-- Leads are read through v_leads, which is tenant-scoped by RLS on people.
|
|
153
|
+
-- No anon SELECT is granted here: a public form writes, it never reads back.
|
|
154
|
+
CREATE INDEX IF NOT EXISTS idx_people_lead_tenant_created
|
|
155
|
+
ON public.people (tenant_id, created_at DESC)
|
|
156
|
+
WHERE kind = 'lead';
|
|
157
|
+
|
|
158
|
+
-- ---------------------------------------------------------------------------
|
|
159
|
+
-- v_leads gains the custom-field payload.
|
|
160
|
+
--
|
|
161
|
+
-- Without this the whole abstraction is write-only: a form's answers reach
|
|
162
|
+
-- people.metadata and no CRM screen can read them back. Columns are APPENDED
|
|
163
|
+
-- (CREATE OR REPLACE VIEW cannot reorder or drop), and the view keeps
|
|
164
|
+
-- security_invoker=true so people's RLS still scopes rows per tenant.
|
|
165
|
+
-- ---------------------------------------------------------------------------
|
|
166
|
+
CREATE OR REPLACE VIEW public.v_leads
|
|
167
|
+
WITH (security_invoker = true) AS
|
|
168
|
+
SELECT id,
|
|
169
|
+
tenant_id,
|
|
170
|
+
name,
|
|
171
|
+
email,
|
|
172
|
+
phone,
|
|
173
|
+
notes,
|
|
174
|
+
tags,
|
|
175
|
+
is_active,
|
|
176
|
+
(metadata ->> 'company'::text) AS company,
|
|
177
|
+
(metadata ->> 'sourceId'::text) AS source_id,
|
|
178
|
+
(metadata ->> 'sourceName'::text) AS source_name,
|
|
179
|
+
COALESCE((metadata ->> 'status'::text), 'new'::text) AS lead_status,
|
|
180
|
+
(metadata ->> 'value'::text) AS lead_value,
|
|
181
|
+
(metadata ->> 'assignedToId'::text) AS assigned_to_id,
|
|
182
|
+
created_at,
|
|
183
|
+
updated_at,
|
|
184
|
+
-- appended:
|
|
185
|
+
(metadata ->> 'formId'::text) AS form_id,
|
|
186
|
+
COALESCE(metadata -> 'fields'::text, '{}'::jsonb) AS custom_fields,
|
|
187
|
+
COALESCE(metadata -> 'utm'::text, '{}'::jsonb) AS utm
|
|
188
|
+
FROM people p
|
|
189
|
+
WHERE (kind = 'lead'::text);
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
-- plugin-crm 006: every lead lands on the board, guaranteed by the database.
|
|
2
|
+
--
|
|
3
|
+
-- The bug this closes: the leads LIST reads v_leads (public.people WHERE
|
|
4
|
+
-- kind='lead') while the PIPELINE reads v_deals (public.orders WHERE kind='deal'
|
|
5
|
+
-- + plg_crm_deal_extensions). A lead is a person; a card is an order. Nothing
|
|
6
|
+
-- created the second from the first — create_public_lead never touches orders —
|
|
7
|
+
-- so form leads landed in the list and the board stayed empty. Forever, not
|
|
8
|
+
-- intermittently. plg_crm_deal_extensions.lead_id has existed since 001 and was
|
|
9
|
+
-- NULL on every row in the pool: the link was designed and never wired.
|
|
10
|
+
--
|
|
11
|
+
-- Why a TRIGGER and not application code: a lead reaches people through at
|
|
12
|
+
-- least four independent writers today — the anon RPC create_public_lead, the
|
|
13
|
+
-- agent's generic createRecord, CSV import, and the CRM's own form. Putting the
|
|
14
|
+
-- board insert in any one of them leaves the other three silently broken, and
|
|
15
|
+
-- the next writer added leaves a fifth. Here it cannot be forgotten or bypassed,
|
|
16
|
+
-- including by a direct SQL insert.
|
|
17
|
+
--
|
|
18
|
+
-- Idempotent by construction: a UNIQUE index on deal_extensions.lead_id means a
|
|
19
|
+
-- second attempt for the same lead is a no-op, so re-running the backfill or
|
|
20
|
+
-- replaying the migration cannot double-card anyone.
|
|
21
|
+
|
|
22
|
+
-- ---------------------------------------------------------------------------
|
|
23
|
+
-- 1. One card per lead, enforced by the database rather than by the trigger
|
|
24
|
+
-- remembering to check.
|
|
25
|
+
-- ---------------------------------------------------------------------------
|
|
26
|
+
CREATE UNIQUE INDEX IF NOT EXISTS plg_crm_deal_extensions_lead_idx
|
|
27
|
+
ON public.plg_crm_deal_extensions (lead_id) WHERE lead_id IS NOT NULL;
|
|
28
|
+
|
|
29
|
+
-- ---------------------------------------------------------------------------
|
|
30
|
+
-- 1b. The default board, as a callable function instead of 004's one-shot loop.
|
|
31
|
+
-- Same pipeline and stages 004 seeds; idempotent per tenant.
|
|
32
|
+
-- ---------------------------------------------------------------------------
|
|
33
|
+
CREATE OR REPLACE FUNCTION public.crm_seed_default_pipeline(p_tenant_id uuid)
|
|
34
|
+
RETURNS uuid
|
|
35
|
+
LANGUAGE plpgsql
|
|
36
|
+
SECURITY DEFINER
|
|
37
|
+
SET search_path TO 'public'
|
|
38
|
+
AS $$
|
|
39
|
+
DECLARE
|
|
40
|
+
v_pipeline uuid;
|
|
41
|
+
BEGIN
|
|
42
|
+
SELECT id INTO v_pipeline
|
|
43
|
+
FROM public.plg_crm_pipelines
|
|
44
|
+
WHERE tenant_id = p_tenant_id
|
|
45
|
+
ORDER BY is_default DESC, created_at ASC
|
|
46
|
+
LIMIT 1;
|
|
47
|
+
IF v_pipeline IS NOT NULL THEN
|
|
48
|
+
RETURN v_pipeline;
|
|
49
|
+
END IF;
|
|
50
|
+
|
|
51
|
+
INSERT INTO public.plg_crm_pipelines (tenant_id, name, is_default, is_active)
|
|
52
|
+
VALUES (p_tenant_id, 'Sales Pipeline', true, true)
|
|
53
|
+
RETURNING id INTO v_pipeline;
|
|
54
|
+
|
|
55
|
+
INSERT INTO public.plg_crm_pipeline_stages
|
|
56
|
+
(tenant_id, pipeline_id, name, "order", color, probability, is_won, is_lost)
|
|
57
|
+
VALUES
|
|
58
|
+
(p_tenant_id, v_pipeline, 'New', 0, '#6366f1', 10, false, false),
|
|
59
|
+
(p_tenant_id, v_pipeline, 'Contacted', 1, '#3b82f6', 25, false, false),
|
|
60
|
+
(p_tenant_id, v_pipeline, 'Qualified', 2, '#f59e0b', 50, false, false),
|
|
61
|
+
(p_tenant_id, v_pipeline, 'Proposal', 3, '#f97316', 75, false, false),
|
|
62
|
+
(p_tenant_id, v_pipeline, 'Negotiation', 4, '#8b5cf6', 90, false, false),
|
|
63
|
+
(p_tenant_id, v_pipeline, 'Won', 5, '#22c55e', 100, true, false),
|
|
64
|
+
(p_tenant_id, v_pipeline, 'Lost', 6, '#ef4444', 0, false, true);
|
|
65
|
+
|
|
66
|
+
RETURN v_pipeline;
|
|
67
|
+
END;
|
|
68
|
+
$$;
|
|
69
|
+
|
|
70
|
+
-- ---------------------------------------------------------------------------
|
|
71
|
+
-- 2. The lead → card projection, shared by the trigger and the backfill so the
|
|
72
|
+
-- two can never drift apart.
|
|
73
|
+
--
|
|
74
|
+
-- Placement is the tenant's DEFAULT pipeline, lowest `order` stage that is
|
|
75
|
+
-- neither won nor lost (the "New" column). A tenant with no pipeline yet is
|
|
76
|
+
-- skipped rather than failing: the lead must still be captured — losing a
|
|
77
|
+
-- real customer enquiry because a board was not configured would be a far
|
|
78
|
+
-- worse bug than a missing card. 004 seeds a default pipeline for every
|
|
79
|
+
-- tenant, so this is the empty-tenant edge, not the normal path.
|
|
80
|
+
-- ---------------------------------------------------------------------------
|
|
81
|
+
CREATE OR REPLACE FUNCTION public.crm_place_lead_on_board(p_lead_id uuid)
|
|
82
|
+
RETURNS uuid
|
|
83
|
+
LANGUAGE plpgsql
|
|
84
|
+
SECURITY DEFINER
|
|
85
|
+
SET search_path TO 'public'
|
|
86
|
+
AS $$
|
|
87
|
+
DECLARE
|
|
88
|
+
v_lead public.people%ROWTYPE;
|
|
89
|
+
v_pipeline uuid;
|
|
90
|
+
v_stage uuid;
|
|
91
|
+
v_prob numeric;
|
|
92
|
+
v_order_id uuid;
|
|
93
|
+
BEGIN
|
|
94
|
+
SELECT * INTO v_lead FROM public.people WHERE id = p_lead_id;
|
|
95
|
+
IF NOT FOUND OR v_lead.kind <> 'lead' THEN
|
|
96
|
+
RETURN NULL;
|
|
97
|
+
END IF;
|
|
98
|
+
|
|
99
|
+
-- Already on the board (re-run, or a card made by hand): nothing to do.
|
|
100
|
+
IF EXISTS (SELECT 1 FROM public.plg_crm_deal_extensions WHERE lead_id = p_lead_id) THEN
|
|
101
|
+
RETURN NULL;
|
|
102
|
+
END IF;
|
|
103
|
+
|
|
104
|
+
SELECT id INTO v_pipeline
|
|
105
|
+
FROM public.plg_crm_pipelines
|
|
106
|
+
WHERE tenant_id = v_lead.tenant_id
|
|
107
|
+
ORDER BY is_default DESC, created_at ASC
|
|
108
|
+
LIMIT 1;
|
|
109
|
+
|
|
110
|
+
-- No board yet? Build the default one and carry on.
|
|
111
|
+
--
|
|
112
|
+
-- 004 seeds the default pipeline as a ONE-SHOT backfill with no trigger, so
|
|
113
|
+
-- every tenant created after it ran has none — 3 of the 8 tenants in this pool
|
|
114
|
+
-- were in that state. Their board renders blank no matter how many leads
|
|
115
|
+
-- arrive, and it would punch a hole straight through the guarantee this
|
|
116
|
+
-- migration exists to make: a lead in such a tenant would be captured and then
|
|
117
|
+
-- silently skipped for want of a stage to sit in.
|
|
118
|
+
--
|
|
119
|
+
-- Seeded here, on demand, rather than from a trigger on public.tenants: the
|
|
120
|
+
-- board is the CRM's own concern, and a plugin has no business attaching
|
|
121
|
+
-- itself to tenant creation in a core table.
|
|
122
|
+
IF v_pipeline IS NULL THEN
|
|
123
|
+
v_pipeline := public.crm_seed_default_pipeline(v_lead.tenant_id);
|
|
124
|
+
END IF;
|
|
125
|
+
IF v_pipeline IS NULL THEN
|
|
126
|
+
RETURN NULL;
|
|
127
|
+
END IF;
|
|
128
|
+
|
|
129
|
+
SELECT id, probability INTO v_stage, v_prob
|
|
130
|
+
FROM public.plg_crm_pipeline_stages
|
|
131
|
+
WHERE pipeline_id = v_pipeline AND NOT is_won AND NOT is_lost
|
|
132
|
+
ORDER BY "order" ASC
|
|
133
|
+
LIMIT 1;
|
|
134
|
+
IF v_stage IS NULL THEN
|
|
135
|
+
RETURN NULL;
|
|
136
|
+
END IF;
|
|
137
|
+
|
|
138
|
+
-- The card's money value comes from the lead when the form captured one;
|
|
139
|
+
-- 0 otherwise. `notes` is the deal TITLE (v_deals maps o.notes -> title), so
|
|
140
|
+
-- it carries the lead's name, not the lead's message.
|
|
141
|
+
INSERT INTO public.orders (
|
|
142
|
+
tenant_id, kind, status, total, currency, party_id, notes, tags, metadata
|
|
143
|
+
) VALUES (
|
|
144
|
+
v_lead.tenant_id,
|
|
145
|
+
'deal',
|
|
146
|
+
'open',
|
|
147
|
+
COALESCE((v_lead.metadata ->> 'value')::numeric, 0),
|
|
148
|
+
'BRL',
|
|
149
|
+
v_lead.id,
|
|
150
|
+
v_lead.name,
|
|
151
|
+
COALESCE(v_lead.tags, '{}'),
|
|
152
|
+
jsonb_build_object(
|
|
153
|
+
'contactName', v_lead.name,
|
|
154
|
+
'createdFrom', 'lead',
|
|
155
|
+
-- Which form produced it, when there was one: lets the board be filtered
|
|
156
|
+
-- by campaign without re-joining people.
|
|
157
|
+
'formId', v_lead.metadata ->> 'formId'
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
RETURNING id INTO v_order_id;
|
|
161
|
+
|
|
162
|
+
INSERT INTO public.plg_crm_deal_extensions (
|
|
163
|
+
order_id, tenant_id, pipeline_id, stage_id, probability, lead_id
|
|
164
|
+
) VALUES (
|
|
165
|
+
v_order_id, v_lead.tenant_id, v_pipeline, v_stage, COALESCE(v_prob, 0), v_lead.id
|
|
166
|
+
)
|
|
167
|
+
-- Concurrent inserts for the same lead: the unique index above turns the
|
|
168
|
+
-- loser into a no-op instead of an error the trigger would propagate back to
|
|
169
|
+
-- the form submission.
|
|
170
|
+
ON CONFLICT (lead_id) WHERE lead_id IS NOT NULL DO NOTHING;
|
|
171
|
+
|
|
172
|
+
RETURN v_order_id;
|
|
173
|
+
END;
|
|
174
|
+
$$;
|
|
175
|
+
|
|
176
|
+
COMMENT ON FUNCTION public.crm_place_lead_on_board(uuid) IS
|
|
177
|
+
'Projects a people row of kind=lead onto the tenant default pipeline as an orders(kind=deal) + deal_extension. Idempotent per lead.';
|
|
178
|
+
|
|
179
|
+
-- ---------------------------------------------------------------------------
|
|
180
|
+
-- 3. The trigger. AFTER INSERT so a failure here can never roll back the lead
|
|
181
|
+
-- itself, and EXCEPTION-guarded for the same reason: capturing the enquiry
|
|
182
|
+
-- is the part that must not fail. A board that missed a card is recoverable
|
|
183
|
+
-- (step 4 re-runs); a lost lead is not.
|
|
184
|
+
-- ---------------------------------------------------------------------------
|
|
185
|
+
CREATE OR REPLACE FUNCTION public.crm_lead_to_board()
|
|
186
|
+
RETURNS trigger
|
|
187
|
+
LANGUAGE plpgsql
|
|
188
|
+
SECURITY DEFINER
|
|
189
|
+
SET search_path TO 'public'
|
|
190
|
+
AS $$
|
|
191
|
+
BEGIN
|
|
192
|
+
IF NEW.kind = 'lead' THEN
|
|
193
|
+
BEGIN
|
|
194
|
+
PERFORM public.crm_place_lead_on_board(NEW.id);
|
|
195
|
+
EXCEPTION WHEN OTHERS THEN
|
|
196
|
+
RAISE WARNING 'crm_lead_to_board: lead % captured but not placed on the board: %', NEW.id, SQLERRM;
|
|
197
|
+
END;
|
|
198
|
+
END IF;
|
|
199
|
+
RETURN NULL;
|
|
200
|
+
END;
|
|
201
|
+
$$;
|
|
202
|
+
|
|
203
|
+
DROP TRIGGER IF EXISTS people_lead_to_board ON public.people;
|
|
204
|
+
CREATE TRIGGER people_lead_to_board
|
|
205
|
+
AFTER INSERT ON public.people
|
|
206
|
+
FOR EACH ROW
|
|
207
|
+
WHEN (NEW.kind = 'lead')
|
|
208
|
+
EXECUTE FUNCTION public.crm_lead_to_board();
|
|
209
|
+
|
|
210
|
+
-- A person PROMOTED to lead later (kind edited from contact/customer) must land
|
|
211
|
+
-- on the board too — otherwise the guarantee holds only for the insert path.
|
|
212
|
+
DROP TRIGGER IF EXISTS people_promoted_to_lead_to_board ON public.people;
|
|
213
|
+
CREATE TRIGGER people_promoted_to_lead_to_board
|
|
214
|
+
AFTER UPDATE OF kind ON public.people
|
|
215
|
+
FOR EACH ROW
|
|
216
|
+
WHEN (NEW.kind = 'lead' AND OLD.kind IS DISTINCT FROM 'lead')
|
|
217
|
+
EXECUTE FUNCTION public.crm_lead_to_board();
|
|
218
|
+
|
|
219
|
+
-- ---------------------------------------------------------------------------
|
|
220
|
+
-- 4. Realtime, so an open board updates itself instead of waiting for a reload.
|
|
221
|
+
--
|
|
222
|
+
-- The trigger above writes the card with no client involved, so the browser
|
|
223
|
+
-- has nothing to react to unless the change is streamed. The pool's
|
|
224
|
+
-- supabase_realtime publication was EMPTY — every .subscribe() in the SDK
|
|
225
|
+
-- was silently receiving nothing — so the table is added explicitly rather
|
|
226
|
+
-- than assumed. FOR EACH ROW replica identity stays default (PK): the
|
|
227
|
+
-- handler refetches the board, so the payload's contents are irrelevant.
|
|
228
|
+
-- ---------------------------------------------------------------------------
|
|
229
|
+
DO $$
|
|
230
|
+
BEGIN
|
|
231
|
+
IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN
|
|
232
|
+
CREATE PUBLICATION supabase_realtime;
|
|
233
|
+
END IF;
|
|
234
|
+
IF NOT EXISTS (
|
|
235
|
+
SELECT 1 FROM pg_publication_tables
|
|
236
|
+
WHERE pubname = 'supabase_realtime'
|
|
237
|
+
AND schemaname = 'public'
|
|
238
|
+
AND tablename = 'plg_crm_deal_extensions'
|
|
239
|
+
) THEN
|
|
240
|
+
ALTER PUBLICATION supabase_realtime ADD TABLE public.plg_crm_deal_extensions;
|
|
241
|
+
END IF;
|
|
242
|
+
END $$;
|
|
243
|
+
|
|
244
|
+
-- ---------------------------------------------------------------------------
|
|
245
|
+
-- 5. Backfill every lead that predates the trigger. Idempotent via step 2's
|
|
246
|
+
-- own guard, so replaying this migration adds nothing.
|
|
247
|
+
-- ---------------------------------------------------------------------------
|
|
248
|
+
DO $$
|
|
249
|
+
DECLARE
|
|
250
|
+
r record;
|
|
251
|
+
n int := 0;
|
|
252
|
+
BEGIN
|
|
253
|
+
FOR r IN
|
|
254
|
+
SELECT p.id
|
|
255
|
+
FROM public.people p
|
|
256
|
+
LEFT JOIN public.plg_crm_deal_extensions de ON de.lead_id = p.id
|
|
257
|
+
WHERE p.kind = 'lead' AND de.id IS NULL
|
|
258
|
+
ORDER BY p.created_at
|
|
259
|
+
LOOP
|
|
260
|
+
IF public.crm_place_lead_on_board(r.id) IS NOT NULL THEN
|
|
261
|
+
n := n + 1;
|
|
262
|
+
END IF;
|
|
263
|
+
END LOOP;
|
|
264
|
+
RAISE NOTICE 'crm 006 backfill: % lead(s) placed on the board', n;
|
|
265
|
+
END $$;
|