@fayz-ai/plugin-crm 0.3.0 → 0.8.1

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 (76) hide show
  1. package/README.md +2 -0
  2. package/dist/components/CrmGeneralSettings.d.ts.map +1 -1
  3. package/dist/data/supabase.d.ts.map +1 -1
  4. package/dist/data/tables.d.ts +10 -0
  5. package/dist/data/tables.d.ts.map +1 -0
  6. package/dist/index.cjs +209 -60
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +3 -3
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +210 -61
  11. package/dist/index.js.map +1 -1
  12. package/dist/lib/form-answers.d.ts +10 -0
  13. package/dist/lib/form-answers.d.ts.map +1 -0
  14. package/dist/locales/en.d.ts.map +1 -1
  15. package/dist/locales/pt-BR.d.ts.map +1 -1
  16. package/dist/migrations/index.d.ts +12 -0
  17. package/dist/migrations/index.d.ts.map +1 -0
  18. package/dist/public/context.d.ts +23 -0
  19. package/dist/public/context.d.ts.map +1 -0
  20. package/dist/public/createPublicFormsPlugin.d.ts +38 -0
  21. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -0
  22. package/dist/public/data.supabase.d.ts +7 -0
  23. package/dist/public/data.supabase.d.ts.map +1 -0
  24. package/dist/public/inbox.d.ts +22 -0
  25. package/dist/public/inbox.d.ts.map +1 -0
  26. package/dist/public/index.cjs +306 -0
  27. package/dist/public/index.cjs.map +1 -0
  28. package/dist/public/index.d.ts +10 -0
  29. package/dist/public/index.d.ts.map +1 -0
  30. package/dist/public/index.js +298 -0
  31. package/dist/public/index.js.map +1 -0
  32. package/dist/public/types.d.ts +92 -0
  33. package/dist/public/types.d.ts.map +1 -0
  34. package/dist/registries.d.ts.map +1 -1
  35. package/dist/schema/index.d.ts +65 -65
  36. package/dist/schema/index.d.ts.map +1 -1
  37. package/dist/schema.cjs +23 -23
  38. package/dist/schema.cjs.map +1 -1
  39. package/dist/schema.js +24 -24
  40. package/dist/schema.js.map +1 -1
  41. package/dist/views/DealSidebar.d.ts.map +1 -1
  42. package/dist/views/LeadDetailView.d.ts.map +1 -1
  43. package/dist/views/LeadFormView.d.ts.map +1 -1
  44. package/dist/views/LeadListView.d.ts.map +1 -1
  45. package/dist/views/PipelineView.d.ts.map +1 -1
  46. package/dist/views/QuoteFormView.d.ts.map +1 -1
  47. package/package.json +17 -5
  48. package/src/components/CrmGeneralSettings.tsx +35 -15
  49. package/src/data/supabase.ts +74 -28
  50. package/src/data/tables.ts +11 -0
  51. package/src/index.ts +15 -3
  52. package/src/lib/form-answers.tsx +39 -0
  53. package/src/locales/en.ts +1 -0
  54. package/src/locales/pt-BR.ts +1 -0
  55. package/src/migrations/000_plg_rename.sql +28 -0
  56. package/src/migrations/001_crm_base.sql +32 -32
  57. package/src/migrations/002_activities.sql +14 -14
  58. package/src/migrations/003_crm_views_rls.sql +8 -8
  59. package/src/migrations/004_seed_default_pipeline.sql +5 -5
  60. package/src/migrations/005_public_lead.sql +189 -0
  61. package/src/migrations/006_lead_enters_pipeline.sql +265 -0
  62. package/src/migrations/index.ts +707 -0
  63. package/src/public/context.tsx +69 -0
  64. package/src/public/createPublicFormsPlugin.ts +188 -0
  65. package/src/public/data.supabase.ts +86 -0
  66. package/src/public/inbox.ts +136 -0
  67. package/src/public/index.ts +30 -0
  68. package/src/public/types.ts +113 -0
  69. package/src/registries.ts +6 -5
  70. package/src/schema/index.ts +25 -25
  71. package/src/views/DealSidebar.tsx +31 -0
  72. package/src/views/LeadDetailView.tsx +53 -0
  73. package/src/views/LeadFormView.tsx +10 -0
  74. package/src/views/LeadListView.tsx +19 -0
  75. package/src/views/PipelineView.tsx +34 -1
  76. package/src/views/QuoteFormView.tsx +5 -0
@@ -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 $$;