@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.
Files changed (57) hide show
  1. package/dist/components/CrmGeneralSettings.d.ts.map +1 -1
  2. package/dist/data/supabase.d.ts.map +1 -1
  3. package/dist/index.cjs +168 -33
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +169 -34
  7. package/dist/index.js.map +1 -1
  8. package/dist/lib/form-answers.d.ts +10 -0
  9. package/dist/lib/form-answers.d.ts.map +1 -0
  10. package/dist/locales/en.d.ts.map +1 -1
  11. package/dist/locales/pt-BR.d.ts.map +1 -1
  12. package/dist/migrations/index.d.ts +2 -0
  13. package/dist/migrations/index.d.ts.map +1 -1
  14. package/dist/public/context.d.ts +23 -0
  15. package/dist/public/context.d.ts.map +1 -0
  16. package/dist/public/createPublicFormsPlugin.d.ts +38 -0
  17. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -0
  18. package/dist/public/data.supabase.d.ts +7 -0
  19. package/dist/public/data.supabase.d.ts.map +1 -0
  20. package/dist/public/inbox.d.ts +22 -0
  21. package/dist/public/inbox.d.ts.map +1 -0
  22. package/dist/public/index.cjs +306 -0
  23. package/dist/public/index.cjs.map +1 -0
  24. package/dist/public/index.d.ts +10 -0
  25. package/dist/public/index.d.ts.map +1 -0
  26. package/dist/public/index.js +298 -0
  27. package/dist/public/index.js.map +1 -0
  28. package/dist/public/types.d.ts +92 -0
  29. package/dist/public/types.d.ts.map +1 -0
  30. package/dist/views/DealSidebar.d.ts.map +1 -1
  31. package/dist/views/LeadDetailView.d.ts.map +1 -1
  32. package/dist/views/LeadFormView.d.ts.map +1 -1
  33. package/dist/views/LeadListView.d.ts.map +1 -1
  34. package/dist/views/PipelineView.d.ts.map +1 -1
  35. package/dist/views/QuoteFormView.d.ts.map +1 -1
  36. package/package.json +11 -5
  37. package/src/components/CrmGeneralSettings.tsx +35 -15
  38. package/src/data/supabase.ts +47 -4
  39. package/src/index.ts +9 -0
  40. package/src/lib/form-answers.tsx +39 -0
  41. package/src/locales/en.ts +1 -0
  42. package/src/locales/pt-BR.ts +1 -0
  43. package/src/migrations/005_public_lead.sql +189 -0
  44. package/src/migrations/006_lead_enters_pipeline.sql +265 -0
  45. package/src/migrations/index.ts +461 -1
  46. package/src/public/context.tsx +69 -0
  47. package/src/public/createPublicFormsPlugin.ts +188 -0
  48. package/src/public/data.supabase.ts +86 -0
  49. package/src/public/inbox.ts +136 -0
  50. package/src/public/index.ts +30 -0
  51. package/src/public/types.ts +113 -0
  52. package/src/views/DealSidebar.tsx +31 -0
  53. package/src/views/LeadDetailView.tsx +53 -0
  54. package/src/views/LeadFormView.tsx +10 -0
  55. package/src/views/LeadListView.tsx +19 -0
  56. package/src/views/PipelineView.tsx +34 -1
  57. package/src/views/QuoteFormView.tsx +5 -0
@@ -1,4 +1,4 @@
1
- // AUTO-GENERATED from 000_plg_rename.sql, 001_crm_base.sql, 002_activities.sql, 003_crm_views_rls.sql, 004_seed_default_pipeline.sql — regenerate with scripts/embed-migrations.mjs
1
+ // AUTO-GENERATED from 000_plg_rename.sql, 001_crm_base.sql, 002_activities.sql, 003_crm_views_rls.sql, 004_seed_default_pipeline.sql, 005_public_lead.sql, 006_lead_enters_pipeline.sql — regenerate with scripts/embed-migrations.mjs
2
2
  // SQL files are the source of truth; this inline copy lets the manifest declare
3
3
  // migrations as data. Do not edit by hand — run the embed script instead.
4
4
 
@@ -238,10 +238,470 @@ BEGIN
238
238
  END $$;
239
239
  `
240
240
 
241
+ export const MIGRATION_005_PUBLIC_LEAD = `-- plugin-crm 005: anon-safe lead capture from public sites.
242
+ --
243
+ -- The counterpart of agenda's create_public_booking: a marketing site posts a
244
+ -- form and a lead lands in the CRM of the right tenant. Same shape of trust —
245
+ -- the caller is an anonymous browser holding only a publishable key, so every
246
+ -- decision that matters (which tenant, which status, whether it is spam) is
247
+ -- made here and cannot be set by the caller.
248
+ --
249
+ -- Why p_fields jsonb: every landing page asks something different (hair
250
+ -- coverage on one, discount coupon on another, subject/message on a third).
251
+ -- Modelling those as columns means a migration per campaign — the site this was
252
+ -- built for already had 22 columns on its lead table. They go to people.metadata
253
+ -- under 'fields', which v_leads already reads from, so a new form ships with
254
+ -- zero schema change.
255
+
256
+ CREATE OR REPLACE FUNCTION public.create_public_lead(
257
+ p_tenant_id uuid,
258
+ p_name text,
259
+ p_phone text DEFAULT NULL,
260
+ p_email text DEFAULT NULL,
261
+ p_form_id text DEFAULT NULL,
262
+ p_form_name text DEFAULT NULL,
263
+ p_fields jsonb DEFAULT '{}'::jsonb,
264
+ p_notes text DEFAULT NULL,
265
+ p_utm jsonb DEFAULT '{}'::jsonb
266
+ )
267
+ RETURNS TABLE(lead_id uuid, created_at timestamptz)
268
+ LANGUAGE plpgsql
269
+ SECURITY DEFINER
270
+ SET search_path TO 'public'
271
+ AS $function$
272
+ DECLARE
273
+ v_person_id uuid;
274
+ v_phone text;
275
+ v_email text;
276
+ v_fields jsonb;
277
+ v_utm jsonb;
278
+ v_recent int;
279
+ BEGIN
280
+ -- ---------------------------------------------------------------------
281
+ -- validation: anon-callable, so everything is checked here
282
+ -- ---------------------------------------------------------------------
283
+ IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN
284
+ RAISE EXCEPTION 'invalid name';
285
+ END IF;
286
+
287
+ v_phone := NULLIF(regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g'), '');
288
+ IF v_phone IS NOT NULL AND length(v_phone) NOT BETWEEN 8 AND 15 THEN
289
+ RAISE EXCEPTION 'invalid phone';
290
+ END IF;
291
+
292
+ v_email := NULLIF(trim(COALESCE(p_email, '')), '');
293
+ IF v_email IS NOT NULL AND (length(v_email) > 254 OR v_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN
294
+ RAISE EXCEPTION 'invalid email';
295
+ END IF;
296
+
297
+ -- a lead with no way to reach them back is not a lead
298
+ IF v_phone IS NULL AND v_email IS NULL THEN
299
+ RAISE EXCEPTION 'phone or email required';
300
+ END IF;
301
+
302
+ PERFORM 1 FROM tenants t WHERE t.id = p_tenant_id;
303
+ IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;
304
+
305
+ -- ---------------------------------------------------------------------
306
+ -- custom fields: object-only, bounded, and scalars only.
307
+ -- Bounding the payload keeps a hostile caller from parking documents in
308
+ -- the CRM; flattening nested values keeps the detail panel renderable.
309
+ -- ---------------------------------------------------------------------
310
+ v_fields := COALESCE(p_fields, '{}'::jsonb);
311
+ IF jsonb_typeof(v_fields) <> 'object' THEN
312
+ RAISE EXCEPTION 'fields must be an object';
313
+ END IF;
314
+ IF length(v_fields::text) > 8000 THEN
315
+ RAISE EXCEPTION 'fields too large';
316
+ END IF;
317
+ IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN
318
+ RAISE EXCEPTION 'too many fields';
319
+ END IF;
320
+
321
+ v_utm := COALESCE(p_utm, '{}'::jsonb);
322
+ IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN
323
+ RAISE EXCEPTION 'invalid utm';
324
+ END IF;
325
+
326
+ -- ---------------------------------------------------------------------
327
+ -- anti-spam: same tenant + same contact + same form, twice in 5 minutes is
328
+ -- a double-click or a bot, not two inquiries. Repeat interest days later IS
329
+ -- a new lead, so this window stays deliberately short.
330
+ -- ---------------------------------------------------------------------
331
+ SELECT count(*) INTO v_recent
332
+ FROM people p
333
+ WHERE p.tenant_id = p_tenant_id
334
+ AND p.kind = 'lead'
335
+ AND p.created_at > now() - interval '5 minutes'
336
+ AND COALESCE(p.metadata->>'formId', '') = COALESCE(p_form_id, '')
337
+ AND (
338
+ (v_phone IS NOT NULL AND p.phone = v_phone)
339
+ OR (v_email IS NOT NULL AND p.email = v_email)
340
+ );
341
+ IF v_recent > 0 THEN
342
+ RAISE EXCEPTION 'duplicate submission';
343
+ END IF;
344
+
345
+ -- burst cap per tenant: a flood is never legitimate marketing traffic
346
+ IF (
347
+ SELECT count(*) FROM people p
348
+ WHERE p.tenant_id = p_tenant_id
349
+ AND p.kind = 'lead'
350
+ AND p.created_at > now() - interval '1 minute'
351
+ ) >= 20 THEN
352
+ RAISE EXCEPTION 'too many submissions';
353
+ END IF;
354
+
355
+ -- ---------------------------------------------------------------------
356
+ -- the lead. status/kind are hardcoded — the caller cannot promote itself
357
+ -- into a customer or land pre-qualified.
358
+ -- ---------------------------------------------------------------------
359
+ INSERT INTO people (tenant_id, kind, name, phone, email, notes, tags, is_active, metadata)
360
+ VALUES (
361
+ p_tenant_id,
362
+ 'lead',
363
+ trim(p_name),
364
+ v_phone,
365
+ v_email,
366
+ left(p_notes, 2000),
367
+ ARRAY[]::text[],
368
+ true,
369
+ jsonb_strip_nulls(
370
+ jsonb_build_object(
371
+ 'status', 'new',
372
+ 'source', 'public_form',
373
+ 'sourceName', COALESCE(NULLIF(trim(COALESCE(p_form_name, '')), ''), 'Site'),
374
+ 'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),
375
+ 'fields', v_fields,
376
+ 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END
377
+ )
378
+ )
379
+ )
380
+ RETURNING id, people.created_at INTO v_person_id, created_at;
381
+
382
+ lead_id := v_person_id;
383
+ RETURN NEXT;
384
+ END;
385
+ $function$;
386
+
387
+ -- anon: the whole point. authenticated too, so a logged-in visitor on the same
388
+ -- site takes the identical path.
389
+ GRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb)
390
+ TO anon, authenticated;
391
+
392
+ -- Leads are read through v_leads, which is tenant-scoped by RLS on people.
393
+ -- No anon SELECT is granted here: a public form writes, it never reads back.
394
+ CREATE INDEX IF NOT EXISTS idx_people_lead_tenant_created
395
+ ON public.people (tenant_id, created_at DESC)
396
+ WHERE kind = 'lead';
397
+
398
+ -- ---------------------------------------------------------------------------
399
+ -- v_leads gains the custom-field payload.
400
+ --
401
+ -- Without this the whole abstraction is write-only: a form's answers reach
402
+ -- people.metadata and no CRM screen can read them back. Columns are APPENDED
403
+ -- (CREATE OR REPLACE VIEW cannot reorder or drop), and the view keeps
404
+ -- security_invoker=true so people's RLS still scopes rows per tenant.
405
+ -- ---------------------------------------------------------------------------
406
+ CREATE OR REPLACE VIEW public.v_leads
407
+ WITH (security_invoker = true) AS
408
+ SELECT id,
409
+ tenant_id,
410
+ name,
411
+ email,
412
+ phone,
413
+ notes,
414
+ tags,
415
+ is_active,
416
+ (metadata ->> 'company'::text) AS company,
417
+ (metadata ->> 'sourceId'::text) AS source_id,
418
+ (metadata ->> 'sourceName'::text) AS source_name,
419
+ COALESCE((metadata ->> 'status'::text), 'new'::text) AS lead_status,
420
+ (metadata ->> 'value'::text) AS lead_value,
421
+ (metadata ->> 'assignedToId'::text) AS assigned_to_id,
422
+ created_at,
423
+ updated_at,
424
+ -- appended:
425
+ (metadata ->> 'formId'::text) AS form_id,
426
+ COALESCE(metadata -> 'fields'::text, '{}'::jsonb) AS custom_fields,
427
+ COALESCE(metadata -> 'utm'::text, '{}'::jsonb) AS utm
428
+ FROM people p
429
+ WHERE (kind = 'lead'::text);
430
+ `
431
+
432
+ export const MIGRATION_006_LEAD_ENTERS_PIPELINE = `-- plugin-crm 006: every lead lands on the board, guaranteed by the database.
433
+ --
434
+ -- The bug this closes: the leads LIST reads v_leads (public.people WHERE
435
+ -- kind='lead') while the PIPELINE reads v_deals (public.orders WHERE kind='deal'
436
+ -- + plg_crm_deal_extensions). A lead is a person; a card is an order. Nothing
437
+ -- created the second from the first — create_public_lead never touches orders —
438
+ -- so form leads landed in the list and the board stayed empty. Forever, not
439
+ -- intermittently. plg_crm_deal_extensions.lead_id has existed since 001 and was
440
+ -- NULL on every row in the pool: the link was designed and never wired.
441
+ --
442
+ -- Why a TRIGGER and not application code: a lead reaches people through at
443
+ -- least four independent writers today — the anon RPC create_public_lead, the
444
+ -- agent's generic createRecord, CSV import, and the CRM's own form. Putting the
445
+ -- board insert in any one of them leaves the other three silently broken, and
446
+ -- the next writer added leaves a fifth. Here it cannot be forgotten or bypassed,
447
+ -- including by a direct SQL insert.
448
+ --
449
+ -- Idempotent by construction: a UNIQUE index on deal_extensions.lead_id means a
450
+ -- second attempt for the same lead is a no-op, so re-running the backfill or
451
+ -- replaying the migration cannot double-card anyone.
452
+
453
+ -- ---------------------------------------------------------------------------
454
+ -- 1. One card per lead, enforced by the database rather than by the trigger
455
+ -- remembering to check.
456
+ -- ---------------------------------------------------------------------------
457
+ CREATE UNIQUE INDEX IF NOT EXISTS plg_crm_deal_extensions_lead_idx
458
+ ON public.plg_crm_deal_extensions (lead_id) WHERE lead_id IS NOT NULL;
459
+
460
+ -- ---------------------------------------------------------------------------
461
+ -- 1b. The default board, as a callable function instead of 004's one-shot loop.
462
+ -- Same pipeline and stages 004 seeds; idempotent per tenant.
463
+ -- ---------------------------------------------------------------------------
464
+ CREATE OR REPLACE FUNCTION public.crm_seed_default_pipeline(p_tenant_id uuid)
465
+ RETURNS uuid
466
+ LANGUAGE plpgsql
467
+ SECURITY DEFINER
468
+ SET search_path TO 'public'
469
+ AS $$
470
+ DECLARE
471
+ v_pipeline uuid;
472
+ BEGIN
473
+ SELECT id INTO v_pipeline
474
+ FROM public.plg_crm_pipelines
475
+ WHERE tenant_id = p_tenant_id
476
+ ORDER BY is_default DESC, created_at ASC
477
+ LIMIT 1;
478
+ IF v_pipeline IS NOT NULL THEN
479
+ RETURN v_pipeline;
480
+ END IF;
481
+
482
+ INSERT INTO public.plg_crm_pipelines (tenant_id, name, is_default, is_active)
483
+ VALUES (p_tenant_id, 'Sales Pipeline', true, true)
484
+ RETURNING id INTO v_pipeline;
485
+
486
+ INSERT INTO public.plg_crm_pipeline_stages
487
+ (tenant_id, pipeline_id, name, "order", color, probability, is_won, is_lost)
488
+ VALUES
489
+ (p_tenant_id, v_pipeline, 'New', 0, '#6366f1', 10, false, false),
490
+ (p_tenant_id, v_pipeline, 'Contacted', 1, '#3b82f6', 25, false, false),
491
+ (p_tenant_id, v_pipeline, 'Qualified', 2, '#f59e0b', 50, false, false),
492
+ (p_tenant_id, v_pipeline, 'Proposal', 3, '#f97316', 75, false, false),
493
+ (p_tenant_id, v_pipeline, 'Negotiation', 4, '#8b5cf6', 90, false, false),
494
+ (p_tenant_id, v_pipeline, 'Won', 5, '#22c55e', 100, true, false),
495
+ (p_tenant_id, v_pipeline, 'Lost', 6, '#ef4444', 0, false, true);
496
+
497
+ RETURN v_pipeline;
498
+ END;
499
+ $$;
500
+
501
+ -- ---------------------------------------------------------------------------
502
+ -- 2. The lead → card projection, shared by the trigger and the backfill so the
503
+ -- two can never drift apart.
504
+ --
505
+ -- Placement is the tenant's DEFAULT pipeline, lowest \`order\` stage that is
506
+ -- neither won nor lost (the "New" column). A tenant with no pipeline yet is
507
+ -- skipped rather than failing: the lead must still be captured — losing a
508
+ -- real customer enquiry because a board was not configured would be a far
509
+ -- worse bug than a missing card. 004 seeds a default pipeline for every
510
+ -- tenant, so this is the empty-tenant edge, not the normal path.
511
+ -- ---------------------------------------------------------------------------
512
+ CREATE OR REPLACE FUNCTION public.crm_place_lead_on_board(p_lead_id uuid)
513
+ RETURNS uuid
514
+ LANGUAGE plpgsql
515
+ SECURITY DEFINER
516
+ SET search_path TO 'public'
517
+ AS $$
518
+ DECLARE
519
+ v_lead public.people%ROWTYPE;
520
+ v_pipeline uuid;
521
+ v_stage uuid;
522
+ v_prob numeric;
523
+ v_order_id uuid;
524
+ BEGIN
525
+ SELECT * INTO v_lead FROM public.people WHERE id = p_lead_id;
526
+ IF NOT FOUND OR v_lead.kind <> 'lead' THEN
527
+ RETURN NULL;
528
+ END IF;
529
+
530
+ -- Already on the board (re-run, or a card made by hand): nothing to do.
531
+ IF EXISTS (SELECT 1 FROM public.plg_crm_deal_extensions WHERE lead_id = p_lead_id) THEN
532
+ RETURN NULL;
533
+ END IF;
534
+
535
+ SELECT id INTO v_pipeline
536
+ FROM public.plg_crm_pipelines
537
+ WHERE tenant_id = v_lead.tenant_id
538
+ ORDER BY is_default DESC, created_at ASC
539
+ LIMIT 1;
540
+
541
+ -- No board yet? Build the default one and carry on.
542
+ --
543
+ -- 004 seeds the default pipeline as a ONE-SHOT backfill with no trigger, so
544
+ -- every tenant created after it ran has none — 3 of the 8 tenants in this pool
545
+ -- were in that state. Their board renders blank no matter how many leads
546
+ -- arrive, and it would punch a hole straight through the guarantee this
547
+ -- migration exists to make: a lead in such a tenant would be captured and then
548
+ -- silently skipped for want of a stage to sit in.
549
+ --
550
+ -- Seeded here, on demand, rather than from a trigger on public.tenants: the
551
+ -- board is the CRM's own concern, and a plugin has no business attaching
552
+ -- itself to tenant creation in a core table.
553
+ IF v_pipeline IS NULL THEN
554
+ v_pipeline := public.crm_seed_default_pipeline(v_lead.tenant_id);
555
+ END IF;
556
+ IF v_pipeline IS NULL THEN
557
+ RETURN NULL;
558
+ END IF;
559
+
560
+ SELECT id, probability INTO v_stage, v_prob
561
+ FROM public.plg_crm_pipeline_stages
562
+ WHERE pipeline_id = v_pipeline AND NOT is_won AND NOT is_lost
563
+ ORDER BY "order" ASC
564
+ LIMIT 1;
565
+ IF v_stage IS NULL THEN
566
+ RETURN NULL;
567
+ END IF;
568
+
569
+ -- The card's money value comes from the lead when the form captured one;
570
+ -- 0 otherwise. \`notes\` is the deal TITLE (v_deals maps o.notes -> title), so
571
+ -- it carries the lead's name, not the lead's message.
572
+ INSERT INTO public.orders (
573
+ tenant_id, kind, status, total, currency, party_id, notes, tags, metadata
574
+ ) VALUES (
575
+ v_lead.tenant_id,
576
+ 'deal',
577
+ 'open',
578
+ COALESCE((v_lead.metadata ->> 'value')::numeric, 0),
579
+ 'BRL',
580
+ v_lead.id,
581
+ v_lead.name,
582
+ COALESCE(v_lead.tags, '{}'),
583
+ jsonb_build_object(
584
+ 'contactName', v_lead.name,
585
+ 'createdFrom', 'lead',
586
+ -- Which form produced it, when there was one: lets the board be filtered
587
+ -- by campaign without re-joining people.
588
+ 'formId', v_lead.metadata ->> 'formId'
589
+ )
590
+ )
591
+ RETURNING id INTO v_order_id;
592
+
593
+ INSERT INTO public.plg_crm_deal_extensions (
594
+ order_id, tenant_id, pipeline_id, stage_id, probability, lead_id
595
+ ) VALUES (
596
+ v_order_id, v_lead.tenant_id, v_pipeline, v_stage, COALESCE(v_prob, 0), v_lead.id
597
+ )
598
+ -- Concurrent inserts for the same lead: the unique index above turns the
599
+ -- loser into a no-op instead of an error the trigger would propagate back to
600
+ -- the form submission.
601
+ ON CONFLICT (lead_id) WHERE lead_id IS NOT NULL DO NOTHING;
602
+
603
+ RETURN v_order_id;
604
+ END;
605
+ $$;
606
+
607
+ COMMENT ON FUNCTION public.crm_place_lead_on_board(uuid) IS
608
+ 'Projects a people row of kind=lead onto the tenant default pipeline as an orders(kind=deal) + deal_extension. Idempotent per lead.';
609
+
610
+ -- ---------------------------------------------------------------------------
611
+ -- 3. The trigger. AFTER INSERT so a failure here can never roll back the lead
612
+ -- itself, and EXCEPTION-guarded for the same reason: capturing the enquiry
613
+ -- is the part that must not fail. A board that missed a card is recoverable
614
+ -- (step 4 re-runs); a lost lead is not.
615
+ -- ---------------------------------------------------------------------------
616
+ CREATE OR REPLACE FUNCTION public.crm_lead_to_board()
617
+ RETURNS trigger
618
+ LANGUAGE plpgsql
619
+ SECURITY DEFINER
620
+ SET search_path TO 'public'
621
+ AS $$
622
+ BEGIN
623
+ IF NEW.kind = 'lead' THEN
624
+ BEGIN
625
+ PERFORM public.crm_place_lead_on_board(NEW.id);
626
+ EXCEPTION WHEN OTHERS THEN
627
+ RAISE WARNING 'crm_lead_to_board: lead % captured but not placed on the board: %', NEW.id, SQLERRM;
628
+ END;
629
+ END IF;
630
+ RETURN NULL;
631
+ END;
632
+ $$;
633
+
634
+ DROP TRIGGER IF EXISTS people_lead_to_board ON public.people;
635
+ CREATE TRIGGER people_lead_to_board
636
+ AFTER INSERT ON public.people
637
+ FOR EACH ROW
638
+ WHEN (NEW.kind = 'lead')
639
+ EXECUTE FUNCTION public.crm_lead_to_board();
640
+
641
+ -- A person PROMOTED to lead later (kind edited from contact/customer) must land
642
+ -- on the board too — otherwise the guarantee holds only for the insert path.
643
+ DROP TRIGGER IF EXISTS people_promoted_to_lead_to_board ON public.people;
644
+ CREATE TRIGGER people_promoted_to_lead_to_board
645
+ AFTER UPDATE OF kind ON public.people
646
+ FOR EACH ROW
647
+ WHEN (NEW.kind = 'lead' AND OLD.kind IS DISTINCT FROM 'lead')
648
+ EXECUTE FUNCTION public.crm_lead_to_board();
649
+
650
+ -- ---------------------------------------------------------------------------
651
+ -- 4. Realtime, so an open board updates itself instead of waiting for a reload.
652
+ --
653
+ -- The trigger above writes the card with no client involved, so the browser
654
+ -- has nothing to react to unless the change is streamed. The pool's
655
+ -- supabase_realtime publication was EMPTY — every .subscribe() in the SDK
656
+ -- was silently receiving nothing — so the table is added explicitly rather
657
+ -- than assumed. FOR EACH ROW replica identity stays default (PK): the
658
+ -- handler refetches the board, so the payload's contents are irrelevant.
659
+ -- ---------------------------------------------------------------------------
660
+ DO $$
661
+ BEGIN
662
+ IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN
663
+ CREATE PUBLICATION supabase_realtime;
664
+ END IF;
665
+ IF NOT EXISTS (
666
+ SELECT 1 FROM pg_publication_tables
667
+ WHERE pubname = 'supabase_realtime'
668
+ AND schemaname = 'public'
669
+ AND tablename = 'plg_crm_deal_extensions'
670
+ ) THEN
671
+ ALTER PUBLICATION supabase_realtime ADD TABLE public.plg_crm_deal_extensions;
672
+ END IF;
673
+ END $$;
674
+
675
+ -- ---------------------------------------------------------------------------
676
+ -- 5. Backfill every lead that predates the trigger. Idempotent via step 2's
677
+ -- own guard, so replaying this migration adds nothing.
678
+ -- ---------------------------------------------------------------------------
679
+ DO $$
680
+ DECLARE
681
+ r record;
682
+ n int := 0;
683
+ BEGIN
684
+ FOR r IN
685
+ SELECT p.id
686
+ FROM public.people p
687
+ LEFT JOIN public.plg_crm_deal_extensions de ON de.lead_id = p.id
688
+ WHERE p.kind = 'lead' AND de.id IS NULL
689
+ ORDER BY p.created_at
690
+ LOOP
691
+ IF public.crm_place_lead_on_board(r.id) IS NOT NULL THEN
692
+ n := n + 1;
693
+ END IF;
694
+ END LOOP;
695
+ RAISE NOTICE 'crm 006 backfill: % lead(s) placed on the board', n;
696
+ END $$;
697
+ `
698
+
241
699
  export const MIGRATIONS: Array<{ id: string; sql: string }> = [
242
700
  { id: "000_plg_rename", sql: MIGRATION_000_PLG_RENAME },
243
701
  { id: "001_crm_base", sql: MIGRATION_001_CRM_BASE },
244
702
  { id: "002_activities", sql: MIGRATION_002_ACTIVITIES },
245
703
  { id: "003_crm_views_rls", sql: MIGRATION_003_CRM_VIEWS_RLS },
246
704
  { id: "004_seed_default_pipeline", sql: MIGRATION_004_SEED_DEFAULT_PIPELINE },
705
+ { id: "005_public_lead", sql: MIGRATION_005_PUBLIC_LEAD },
706
+ { id: "006_lead_enters_pipeline", sql: MIGRATION_006_LEAD_ENTERS_PIPELINE },
247
707
  ]
@@ -0,0 +1,69 @@
1
+ import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
2
+ import { LeadSubmitError, type LeadFields, type LeadSubmitResult, type PublicFormDef } from './types'
3
+
4
+ interface PublicFormsContextValue {
5
+ forms: Map<string, PublicFormDef>
6
+ submit: (formId: string, values: LeadFields) => Promise<LeadSubmitResult>
7
+ }
8
+
9
+ const PublicFormsContext = createContext<PublicFormsContextValue | null>(null)
10
+
11
+ export interface PublicFormsProviderProps extends PublicFormsContextValue {
12
+ children: ReactNode
13
+ }
14
+
15
+ export function PublicFormsProvider({ forms, submit, children }: PublicFormsProviderProps) {
16
+ const value = useMemo(() => ({ forms, submit }), [forms, submit])
17
+ return <PublicFormsContext.Provider value={value}>{children}</PublicFormsContext.Provider>
18
+ }
19
+
20
+ /** The hook a site's own form component calls. Owns only the submission
21
+ * lifecycle — the markup, the fields and the validation copy stay the site's. */
22
+ export function useLeadForm(formId: string) {
23
+ const ctx = useContext(PublicFormsContext)
24
+ if (!ctx) {
25
+ throw new Error('[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.')
26
+ }
27
+
28
+ const [submitting, setSubmitting] = useState(false)
29
+ const [error, setError] = useState<LeadSubmitError | null>(null)
30
+ const [result, setResult] = useState<LeadSubmitResult | null>(null)
31
+
32
+ const submit = useCallback(
33
+ async (values: LeadFields): Promise<LeadSubmitResult | null> => {
34
+ if (submitting) return null
35
+ setSubmitting(true)
36
+ setError(null)
37
+ try {
38
+ const res = await ctx.submit(formId, values)
39
+ setResult(res)
40
+ return res
41
+ } catch (err) {
42
+ const e =
43
+ err instanceof LeadSubmitError
44
+ ? err
45
+ : new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar.')
46
+ setError(e)
47
+ return null
48
+ } finally {
49
+ setSubmitting(false)
50
+ }
51
+ },
52
+ [ctx, formId, submitting],
53
+ )
54
+
55
+ const reset = useCallback(() => {
56
+ setError(null)
57
+ setResult(null)
58
+ }, [])
59
+
60
+ return {
61
+ submit,
62
+ reset,
63
+ submitting,
64
+ error,
65
+ result,
66
+ success: result !== null,
67
+ form: ctx.forms.get(formId) ?? null,
68
+ }
69
+ }