@fayz-ai/plugin-crm 0.8.3 → 0.8.5

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 (84) hide show
  1. package/dist/cascade.d.ts.map +1 -1
  2. package/dist/components/BoardFilters.d.ts +23 -0
  3. package/dist/components/BoardFilters.d.ts.map +1 -0
  4. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
  5. package/dist/components/TagChips.d.ts +16 -0
  6. package/dist/components/TagChips.d.ts.map +1 -0
  7. package/dist/data/mock.d.ts +5 -0
  8. package/dist/data/mock.d.ts.map +1 -1
  9. package/dist/data/supabase.d.ts +6 -0
  10. package/dist/data/supabase.d.ts.map +1 -1
  11. package/dist/data/types.d.ts +12 -2
  12. package/dist/data/types.d.ts.map +1 -1
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1136 -164
  16. package/dist/index.js.map +1 -1
  17. package/dist/lib/access.d.ts +8 -0
  18. package/dist/lib/access.d.ts.map +1 -0
  19. package/dist/locales/en.d.ts.map +1 -1
  20. package/dist/locales/pt-BR.d.ts.map +1 -1
  21. package/dist/migrations/index.d.ts +9 -1
  22. package/dist/migrations/index.d.ts.map +1 -1
  23. package/dist/public/context.d.ts +3 -3
  24. package/dist/public/context.d.ts.map +1 -1
  25. package/dist/public/createPublicFormsPlugin.d.ts +18 -2
  26. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  27. package/dist/public/data.supabase.d.ts.map +1 -1
  28. package/dist/public/index.js +31 -7
  29. package/dist/public/index.js.map +1 -1
  30. package/dist/public/types.d.ts +27 -0
  31. package/dist/public/types.d.ts.map +1 -1
  32. package/dist/registries.d.ts +11 -0
  33. package/dist/registries.d.ts.map +1 -1
  34. package/dist/store.d.ts +12 -2
  35. package/dist/store.d.ts.map +1 -1
  36. package/dist/types.d.ts +51 -2
  37. package/dist/types.d.ts.map +1 -1
  38. package/dist/views/ActivityListView.d.ts +6 -1
  39. package/dist/views/ActivityListView.d.ts.map +1 -1
  40. package/dist/views/DealSidebar.d.ts.map +1 -1
  41. package/dist/views/LeadDetailView.d.ts.map +1 -1
  42. package/dist/views/PipelineView.d.ts.map +1 -1
  43. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  44. package/dist/views/QuoteListView.d.ts.map +1 -1
  45. package/package.json +15 -14
  46. package/src/CrmPage.tsx +1 -1
  47. package/src/cascade.ts +2 -0
  48. package/src/components/BoardFilters.tsx +190 -0
  49. package/src/components/QuoteStatusDropdown.tsx +15 -3
  50. package/src/components/TagChips.tsx +80 -0
  51. package/src/data/mock.ts +140 -7
  52. package/src/data/supabase.ts +256 -11
  53. package/src/data/types.ts +14 -3
  54. package/src/index.ts +179 -3
  55. package/src/lib/access.ts +11 -0
  56. package/src/locales/en.ts +13 -0
  57. package/src/locales/pt-BR.ts +18 -5
  58. package/src/migrations/003_crm_views_rls.sql +10 -2
  59. package/src/migrations/007_activity_log.sql +55 -0
  60. package/src/migrations/008_view_field_aliases.sql +43 -0
  61. package/src/migrations/009_deal_archived_status.sql +30 -0
  62. package/src/migrations/010_quote_archived_status.sql +40 -0
  63. package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
  64. package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
  65. package/src/migrations/013_tag_slugs.sql +177 -0
  66. package/src/migrations/014_public_lead_tags.sql +172 -0
  67. package/src/migrations/index.ts +833 -3
  68. package/src/public/context.tsx +4 -4
  69. package/src/public/createPublicFormsPlugin.ts +72 -2
  70. package/src/public/data.supabase.ts +3 -2
  71. package/src/public/types.ts +28 -0
  72. package/src/registries.ts +44 -11
  73. package/src/store.ts +135 -38
  74. package/src/types.ts +59 -2
  75. package/src/views/ActivityListView.tsx +79 -11
  76. package/src/views/DealSidebar.tsx +48 -39
  77. package/src/views/LeadDetailView.tsx +29 -10
  78. package/src/views/PipelineView.tsx +112 -11
  79. package/src/views/QuoteDetailView.tsx +7 -3
  80. package/src/views/QuoteListView.tsx +26 -12
  81. package/dist/index.cjs +0 -4759
  82. package/dist/index.cjs.map +0 -1
  83. package/dist/public/index.cjs +0 -306
  84. package/dist/public/index.cjs.map +0 -1
@@ -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, 005_public_lead.sql, 006_lead_enters_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, 007_activity_log.sql, 008_view_field_aliases.sql, 009_deal_archived_status.sql, 010_quote_archived_status.sql, 011_agent_rpc_update_lead.sql, 012_agent_rpc_create_lead.sql, 013_tag_slugs.sql, 014_public_lead_tags.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
 
@@ -173,7 +173,12 @@ BEGIN
173
173
  END $$;
174
174
 
175
175
  -- v_leads: public.people (kind='lead')
176
- CREATE OR REPLACE VIEW public.v_leads WITH (security_invoker=true) AS
176
+ -- DROP first: 005 widens this view (form_id/custom_fields/utm), and CREATE OR
177
+ -- REPLACE cannot narrow a live view — replaying 003 on a pool that already ran
178
+ -- 005 would fail with "cannot drop columns from view". 005 replays right after
179
+ -- and widens it again, so the net result is unchanged.
180
+ DROP VIEW IF EXISTS public.v_leads;
181
+ CREATE VIEW public.v_leads WITH (security_invoker=true) AS
177
182
  SELECT
178
183
  p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,
179
184
  p.metadata->>'company' AS company,
@@ -188,7 +193,10 @@ WHERE p.kind = 'lead';
188
193
  GRANT SELECT ON public.v_leads TO authenticated;
189
194
 
190
195
  -- v_deals: public.orders (kind='deal') JOIN plg_crm_deal_extensions JOIN plg_crm_pipeline_stages
191
- CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS
196
+ -- DROP first for the same reason as v_leads above: 008 appends the \`stage\`
197
+ -- alias, and CREATE OR REPLACE cannot narrow a live view on replay.
198
+ DROP VIEW IF EXISTS public.v_deals;
199
+ CREATE VIEW public.v_deals WITH (security_invoker=true) AS
192
200
  SELECT
193
201
  o.id, o.tenant_id, o.status,
194
202
  o.total AS value, o.notes AS title,
@@ -696,6 +704,820 @@ BEGIN
696
704
  END $$;
697
705
  `
698
706
 
707
+ export const MIGRATION_007_ACTIVITY_LOG = `-- CRM plugin — activity log foundation.
708
+ -- Activity types become tenant-editable (icon column) and upsertable by the
709
+ -- provider's lazy per-tenant seed (unique tenant+name). System timeline events
710
+ -- (lead_created, stage_changed, quote_*…) are written by the data provider
711
+ -- into plg_crm_activities with completed_at = now(); they are product-defined
712
+ -- and do NOT live in the types catalog.
713
+ -- Idempotent / replay-safe.
714
+
715
+ ALTER TABLE public.plg_crm_activity_types ADD COLUMN IF NOT EXISTS icon text;
716
+
717
+ -- Guarded: a pre-existing pool could hold duplicate names; skip rather than fail.
718
+ DO $$
719
+ BEGIN
720
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_plg_crm_activity_types_tenant_name
721
+ ON public.plg_crm_activity_types(tenant_id, name);
722
+ EXCEPTION WHEN OTHERS THEN
723
+ RAISE NOTICE 'skipping uq_plg_crm_activity_types_tenant_name: %', SQLERRM;
724
+ END $$;
725
+
726
+ -- Backfill: records created BEFORE auto-logging existed get their timeline
727
+ -- events retroactively (stamped at the record's created_at), so the Activities
728
+ -- view isn't empty on day one. Idempotent via NOT EXISTS per record+type.
729
+ INSERT INTO public.plg_crm_activities
730
+ (tenant_id, lead_id, contact_name, activity_type, title, completed_at, created_at)
731
+ SELECT p.tenant_id, p.id, p.name, 'lead_created', p.name, p.created_at, p.created_at
732
+ FROM public.people p
733
+ WHERE p.kind = 'lead'
734
+ AND NOT EXISTS (
735
+ SELECT 1 FROM public.plg_crm_activities a
736
+ WHERE a.lead_id = p.id AND a.activity_type = 'lead_created'
737
+ );
738
+
739
+ INSERT INTO public.plg_crm_activities
740
+ (tenant_id, deal_id, contact_name, activity_type, title, completed_at, created_at)
741
+ SELECT o.tenant_id, o.id, o.metadata->>'contactName', 'deal_created',
742
+ COALESCE(NULLIF(o.notes, ''), 'Deal'), o.created_at, o.created_at
743
+ FROM public.orders o
744
+ WHERE o.kind = 'deal'
745
+ AND NOT EXISTS (
746
+ SELECT 1 FROM public.plg_crm_activities a
747
+ WHERE a.deal_id = o.id AND a.activity_type = 'deal_created'
748
+ );
749
+
750
+ INSERT INTO public.plg_crm_activities
751
+ (tenant_id, contact_name, activity_type, title, description, completed_at, created_at)
752
+ SELECT o.tenant_id, o.metadata->>'contactName', 'quote_created',
753
+ COALESCE(o.reference_number, 'Quote'), o.metadata->>'contactName',
754
+ o.created_at, o.created_at
755
+ FROM public.orders o
756
+ WHERE o.kind = 'quote'
757
+ AND NOT EXISTS (
758
+ SELECT 1 FROM public.plg_crm_activities a
759
+ WHERE a.activity_type = 'quote_created' AND a.title = COALESCE(o.reference_number, 'Quote')
760
+ AND a.tenant_id = o.tenant_id
761
+ );
762
+ `
763
+
764
+ export const MIGRATION_008_VIEW_FIELD_ALIASES = `-- CRM plugin — agent-ergonomic view aliases.
765
+ -- The assistant's first guess for a groupBy/filter field is the natural name
766
+ -- ('stage', 'status'), not the qualified one ('stage_name', 'lead_status') —
767
+ -- each miss costs a failed tool round. CREATE OR REPLACE can only APPEND
768
+ -- columns, so the aliases land at the end; existing consumers are untouched.
769
+ -- Idempotent.
770
+
771
+ CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS
772
+ SELECT
773
+ o.id, o.tenant_id, o.status,
774
+ o.total AS value, o.notes AS title,
775
+ o.party_id AS contact_id, o.assignee_id AS assigned_to_id, o.tags,
776
+ o.metadata->>'contactName' AS contact_name,
777
+ o.created_at, o.updated_at,
778
+ de.pipeline_id, de.stage_id, de.probability, de.expected_close_date,
779
+ de.lead_id, de.lost_reason,
780
+ ps.name AS stage_name, ps.color AS stage_color, ps."order" AS stage_order,
781
+ ps.name AS stage
782
+ FROM public.orders o
783
+ LEFT JOIN public.plg_crm_deal_extensions de ON de.order_id = o.id
784
+ LEFT JOIN public.plg_crm_pipeline_stages ps ON ps.id = de.stage_id
785
+ WHERE o.kind = 'deal';
786
+ GRANT SELECT ON public.v_deals TO authenticated;
787
+
788
+ -- v_leads: current definition is 005's widened shape — append \`status\`.
789
+ CREATE OR REPLACE VIEW public.v_leads
790
+ WITH (security_invoker = true) AS
791
+ SELECT
792
+ p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,
793
+ p.metadata->>'company' AS company,
794
+ p.metadata->>'sourceId' AS source_id,
795
+ p.metadata->>'sourceName' AS source_name,
796
+ COALESCE(p.metadata->>'status','new') AS lead_status,
797
+ p.metadata->>'value' AS lead_value,
798
+ p.metadata->>'assignedToId' AS assigned_to_id,
799
+ p.created_at, p.updated_at,
800
+ p.metadata->>'formId' AS form_id,
801
+ COALESCE(p.metadata->'fields', '{}'::jsonb) AS custom_fields,
802
+ COALESCE(p.metadata->'utm', '{}'::jsonb) AS utm,
803
+ COALESCE(p.metadata->>'status','new') AS status
804
+ FROM public.people p
805
+ WHERE p.kind = 'lead';
806
+ GRANT SELECT ON public.v_leads TO authenticated;
807
+ `
808
+
809
+ export const MIGRATION_009_DEAL_ARCHIVED_STATUS = `-- CRM plugin — allow status='archived' for deals.
810
+ -- A beauty-era legacy migration (20260617000006) added orders_kind_status_valid
811
+ -- whitelisting per-kind statuses; the deal branch predates archiving and
812
+ -- rejected the soft-remove write. Recreate the check with 'archived' included,
813
+ -- ONLY where the constraint exists (other pools: no-op). NOT VALID kept from
814
+ -- the original — existing rows are not re-validated. Idempotent via the
815
+ -- 'archived' probe.
816
+
817
+ DO $$
818
+ DECLARE def text;
819
+ BEGIN
820
+ SELECT pg_get_constraintdef(oid) INTO def
821
+ FROM pg_constraint
822
+ WHERE conname = 'orders_kind_status_valid' AND conrelid = 'public.orders'::regclass;
823
+ IF def IS NULL OR def LIKE '%archived%' THEN RETURN; END IF;
824
+
825
+ ALTER TABLE public.orders DROP CONSTRAINT orders_kind_status_valid;
826
+ ALTER TABLE public.orders ADD CONSTRAINT orders_kind_status_valid CHECK (
827
+ status IS NULL OR
828
+ CASE kind
829
+ WHEN 'quote' THEN status IN ('draft', 'sent', 'approved', 'rejected', 'expired', 'converted')
830
+ WHEN 'deal' THEN status IN ('open', 'won', 'lost', 'archived')
831
+ WHEN 'appointment' THEN status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid')
832
+ WHEN 'service_order' THEN status IN ('draft', 'scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'invoiced', 'paid')
833
+ WHEN 'invoice_receivable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
834
+ WHEN 'invoice_payable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
835
+ ELSE true
836
+ END
837
+ ) NOT VALID;
838
+ END $$;
839
+ `
840
+
841
+ export const MIGRATION_010_QUOTE_ARCHIVED_STATUS = `-- CRM plugin — allow status='archived' for quotes (follow-up to 009, which
842
+ -- covered deals). Recreates orders_kind_status_valid with 'archived' in BOTH
843
+ -- branches, only where the constraint exists (other pools: no-op). Idempotent:
844
+ -- skips when 'archived' already appears twice (deal + quote branches).
845
+
846
+ DO $$
847
+ DECLARE def text;
848
+ BEGIN
849
+ SELECT pg_get_constraintdef(oid) INTO def
850
+ FROM pg_constraint
851
+ WHERE conname = 'orders_kind_status_valid' AND conrelid = 'public.orders'::regclass;
852
+ IF def IS NULL THEN RETURN; END IF;
853
+ IF (length(def) - length(replace(def, 'archived', ''))) / length('archived') >= 2 THEN RETURN; END IF;
854
+
855
+ ALTER TABLE public.orders DROP CONSTRAINT orders_kind_status_valid;
856
+ ALTER TABLE public.orders ADD CONSTRAINT orders_kind_status_valid CHECK (
857
+ status IS NULL OR
858
+ CASE kind
859
+ WHEN 'quote' THEN status IN ('draft', 'sent', 'approved', 'rejected', 'expired', 'converted', 'archived')
860
+ WHEN 'deal' THEN status IN ('open', 'won', 'lost', 'archived')
861
+ WHEN 'appointment' THEN status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid')
862
+ WHEN 'service_order' THEN status IN ('draft', 'scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'invoiced', 'paid')
863
+ WHEN 'invoice_receivable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
864
+ WHEN 'invoice_payable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
865
+ ELSE true
866
+ END
867
+ ) NOT VALID;
868
+ END $$;
869
+
870
+ -- Backfill: deals stuck at total=0 whose quotes hold the real number take the
871
+ -- LATEST quote's total (the same sync the provider now does on quote create/
872
+ -- update). Idempotent — once totals are non-zero the predicate no longer bites.
873
+ UPDATE public.orders d SET total = q.total
874
+ FROM (
875
+ SELECT DISTINCT ON ((metadata->>'dealId')) metadata->>'dealId' AS deal_id, total
876
+ FROM public.orders
877
+ WHERE kind = 'quote' AND metadata->>'dealId' IS NOT NULL AND total > 0
878
+ ORDER BY (metadata->>'dealId'), created_at DESC
879
+ ) q
880
+ WHERE d.id::text = q.deal_id AND d.kind = 'deal' AND COALESCE(d.total, 0) = 0;
881
+ `
882
+
883
+ export const MIGRATION_011_AGENT_RPC_UPDATE_LEAD = `-- ============================================================================
884
+ -- plugin-crm 011: agent_crm_update_lead — mover o status de um lead (e corrigir
885
+ -- seus dados) pelo agente.
886
+ --
887
+ -- Lacuna que isso fecha: o CRM não tinha NENHUMA escrita pelo agente. Pedido
888
+ -- real ("acabei de mandar a proposta pra ele, então atualiza o status") caía no
889
+ -- updateRecord genérico, que bate em v_leads — uma view sobre people —, e o
890
+ -- assistente só sabia dizer "essa entidade é somente leitura". Mudar status de
891
+ -- lead é a ação mais frequente de um CRM; sem ela o agente é só um relatório.
892
+ --
893
+ -- Sobre o feature id: \`sales\`, não \`crm.leads\`. Duas razões, ambas medidas em
894
+ -- pool real. (1) agent_guard concatena feature || '.' || action sem normalizar,
895
+ -- e nenhum pool guarda \`crm.leads.edit\` — beauty guarda \`crm_leads.edit\`,
896
+ -- great-djs não guarda nenhum dos dois. (2) \`sales.edit\` existe nos dois, e é o
897
+ -- que a própria tool declara em \`permission\`. Servidor e cliente checando
898
+ -- features diferentes é bug por construção.
899
+ -- ============================================================================
900
+
901
+ CREATE OR REPLACE FUNCTION public.agent_crm_update_lead(
902
+ p_tenant_id uuid,
903
+ p_actor_user_id uuid,
904
+ p_payload jsonb
905
+ ) RETURNS jsonb
906
+ LANGUAGE plpgsql SECURITY DEFINER
907
+ SET search_path = public
908
+ AS $$
909
+ DECLARE
910
+ v_denial jsonb;
911
+ v_id uuid;
912
+ v_row record;
913
+ v_status text;
914
+ v_patch jsonb := '{}'::jsonb;
915
+ v_meta jsonb := '{}'::jsonb;
916
+ v_touched boolean := false;
917
+ BEGIN
918
+ BEGIN
919
+ v_id := (p_payload->>'lead_id')::uuid;
920
+ EXCEPTION WHEN OTHERS THEN
921
+ RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);
922
+ END;
923
+ IF v_id IS NULL THEN
924
+ RETURN jsonb_build_object('ok', false, 'error',
925
+ 'lead_id is required — search the leads first and reuse the id from the result');
926
+ END IF;
927
+
928
+ SELECT p.id, p.name, p.email, p.phone, p.notes, p.metadata, p.kind
929
+ INTO v_row
930
+ FROM people p
931
+ WHERE p.id = v_id AND p.tenant_id = p_tenant_id AND p.kind = 'lead';
932
+ IF NOT FOUND THEN
933
+ RETURN jsonb_build_object('ok', false, 'error', 'unknown lead for this tenant');
934
+ END IF;
935
+
936
+ v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'edit');
937
+ IF v_denial IS NOT NULL THEN
938
+ RETURN jsonb_build_object('ok', false, 'denial', v_denial);
939
+ END IF;
940
+
941
+ -- Status is a CLOSED set. The model reached for 'proposta_enviada', which no
942
+ -- board column renders — an invalid status writes a lead nobody can find, so
943
+ -- the allowed values come back in the error for it to self-correct.
944
+ v_status := nullif(trim(lower(p_payload->>'status')), '');
945
+ IF v_status IS NOT NULL THEN
946
+ IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN
947
+ RETURN jsonb_build_object(
948
+ 'ok', false,
949
+ 'error', format('unknown lead status %L', v_status),
950
+ 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'),
951
+ 'hint', 'A sent proposal is usually "qualified"; a closed sale is "converted".');
952
+ END IF;
953
+ v_meta := v_meta || jsonb_build_object('status', v_status);
954
+ v_touched := true;
955
+ END IF;
956
+
957
+ -- Top-level columns.
958
+ IF p_payload ? 'name' AND nullif(trim(p_payload->>'name'), '') IS NOT NULL THEN
959
+ v_patch := v_patch || jsonb_build_object('name', trim(p_payload->>'name'));
960
+ v_touched := true;
961
+ END IF;
962
+ IF p_payload ? 'email' THEN
963
+ v_patch := v_patch || jsonb_build_object('email', nullif(trim(p_payload->>'email'), ''));
964
+ v_touched := true;
965
+ END IF;
966
+ IF p_payload ? 'phone' THEN
967
+ v_patch := v_patch || jsonb_build_object('phone', nullif(trim(p_payload->>'phone'), ''));
968
+ v_touched := true;
969
+ END IF;
970
+ IF p_payload ? 'notes' THEN
971
+ v_patch := v_patch || jsonb_build_object('notes', left(p_payload->>'notes', 2000));
972
+ v_touched := true;
973
+ END IF;
974
+
975
+ -- Metadata-backed columns of v_leads.
976
+ IF p_payload ? 'company' THEN
977
+ v_meta := v_meta || jsonb_build_object('company', nullif(trim(p_payload->>'company'), ''));
978
+ v_touched := true;
979
+ END IF;
980
+ IF p_payload ? 'value' THEN
981
+ v_meta := v_meta || jsonb_build_object('value', p_payload->>'value');
982
+ v_touched := true;
983
+ END IF;
984
+ IF p_payload ? 'assigned_to_id' THEN
985
+ v_meta := v_meta || jsonb_build_object('assignedToId', nullif(trim(p_payload->>'assigned_to_id'), ''));
986
+ v_touched := true;
987
+ END IF;
988
+
989
+ IF NOT v_touched THEN
990
+ RETURN jsonb_build_object('ok', false, 'error',
991
+ 'nothing to change: send status, name, email, phone, company, value, assigned_to_id or notes');
992
+ END IF;
993
+
994
+ UPDATE people p SET
995
+ name = COALESCE(v_patch->>'name', p.name),
996
+ email = CASE WHEN v_patch ? 'email' THEN v_patch->>'email' ELSE p.email END,
997
+ phone = CASE WHEN v_patch ? 'phone' THEN v_patch->>'phone' ELSE p.phone END,
998
+ notes = CASE WHEN v_patch ? 'notes' THEN v_patch->>'notes' ELSE p.notes END,
999
+ metadata = COALESCE(p.metadata, '{}'::jsonb) || v_meta,
1000
+ updated_at = now()
1001
+ WHERE p.id = v_id AND p.tenant_id = p_tenant_id;
1002
+
1003
+ INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)
1004
+ VALUES (p_tenant_id, p_actor_user_id, 'agent.updateLead', 'lead', v_id::text,
1005
+ jsonb_build_object('payload', p_payload,
1006
+ 'previous', jsonb_build_object(
1007
+ 'name', v_row.name,
1008
+ 'email', v_row.email,
1009
+ 'phone', v_row.phone,
1010
+ 'status', COALESCE(v_row.metadata->>'status', 'new'))));
1011
+
1012
+ SELECT l.id, l.name, l.email, l.phone, l.company, l.status
1013
+ INTO v_row
1014
+ FROM v_leads l WHERE l.id = v_id;
1015
+
1016
+ RETURN jsonb_build_object(
1017
+ 'ok', true,
1018
+ 'id', v_id,
1019
+ 'record', jsonb_build_object(
1020
+ 'ref', jsonb_build_object('id', v_id, 'resource', 'people',
1021
+ 'archetype', 'person:lead', 'entityKey', 'crm:leads'),
1022
+ 'name', v_row.name,
1023
+ 'email', v_row.email,
1024
+ 'phone', v_row.phone,
1025
+ 'company', v_row.company,
1026
+ 'status', v_row.status
1027
+ )
1028
+ );
1029
+ END;
1030
+ $$;
1031
+
1032
+ REVOKE ALL ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM public;
1033
+ REVOKE EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM anon;
1034
+ GRANT EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb)
1035
+ TO authenticated, service_role;
1036
+ `
1037
+
1038
+ export const MIGRATION_012_AGENT_RPC_CREATE_LEAD = `-- ============================================================================
1039
+ -- plugin-crm 012: agent_crm_create_lead — abrir um lead pelo agente.
1040
+ --
1041
+ -- Par do 011. Sem ele, "cria um lead Noronha em stage qualified" caía no
1042
+ -- createRecord genérico, batia no read_only de v_leads, e o modelo — vendo que
1043
+ -- existia updateLead — chamava a tool de EDIÇÃO com \`lead_id: "N/A"\`. Faltando
1044
+ -- o create, ele improvisa com o que tem.
1045
+ --
1046
+ -- Deduplicação é parte do contrato, não extra: e-mail ou telefone que já existem
1047
+ -- no tenant devolvem o lead existente com \`deduped: true\` em vez de abrir um
1048
+ -- segundo. Um CRM com o mesmo contato duas vezes é pior que um CRM vazio.
1049
+ --
1050
+ -- Feature \`sales\` pelo mesmo motivo do 011 — é a que existe em todo pool e a que
1051
+ -- a tool declara.
1052
+ -- ============================================================================
1053
+
1054
+ CREATE OR REPLACE FUNCTION public.agent_crm_create_lead(
1055
+ p_tenant_id uuid,
1056
+ p_actor_user_id uuid,
1057
+ p_payload jsonb
1058
+ ) RETURNS jsonb
1059
+ LANGUAGE plpgsql SECURITY DEFINER
1060
+ SET search_path = public
1061
+ AS $$
1062
+ DECLARE
1063
+ v_denial jsonb;
1064
+ v_used int;
1065
+ v_name text;
1066
+ v_email text;
1067
+ v_phone text;
1068
+ v_status text;
1069
+ v_meta jsonb;
1070
+ v_existing record;
1071
+ v_id uuid;
1072
+ v_row record;
1073
+ BEGIN
1074
+ v_name := nullif(trim(p_payload->>'name'), '');
1075
+ v_email := lower(nullif(trim(p_payload->>'email'), ''));
1076
+ v_phone := nullif(regexp_replace(coalesce(p_payload->>'phone', ''), '\\D', '', 'g'), '');
1077
+ IF v_name IS NULL THEN
1078
+ RETURN jsonb_build_object('ok', false, 'error', 'name is required to open a lead');
1079
+ END IF;
1080
+
1081
+ v_status := coalesce(nullif(trim(lower(p_payload->>'status')), ''), 'new');
1082
+ IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN
1083
+ RETURN jsonb_build_object(
1084
+ 'ok', false,
1085
+ 'error', format('unknown lead status %L', v_status),
1086
+ 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'));
1087
+ END IF;
1088
+
1089
+ -- ── authorization: role → plan → leads cap ───────────────────────────────
1090
+ SELECT count(*) INTO v_used FROM people p
1091
+ WHERE p.tenant_id = p_tenant_id AND p.kind = 'lead';
1092
+ v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'create', 'leads', v_used, 1);
1093
+ IF v_denial IS NOT NULL THEN
1094
+ RETURN jsonb_build_object('ok', false, 'denial', v_denial);
1095
+ END IF;
1096
+
1097
+ -- ── dedupe before writing ────────────────────────────────────────────────
1098
+ IF v_email IS NOT NULL OR v_phone IS NOT NULL THEN
1099
+ SELECT p.id, p.name INTO v_existing
1100
+ FROM people p
1101
+ WHERE p.tenant_id = p_tenant_id
1102
+ AND p.kind = 'lead'
1103
+ AND (
1104
+ (v_email IS NOT NULL AND lower(p.email) = v_email)
1105
+ OR (v_phone IS NOT NULL AND regexp_replace(coalesce(p.phone, ''), '\\D', '', 'g') = v_phone)
1106
+ )
1107
+ LIMIT 1;
1108
+ IF FOUND THEN
1109
+ RETURN jsonb_build_object(
1110
+ 'ok', true,
1111
+ 'deduped', true,
1112
+ 'id', v_existing.id,
1113
+ 'message', format('%L already exists as a lead with that e-mail/phone — returning it instead of creating a second one. Use updateLead to change it.', v_existing.name),
1114
+ 'record', jsonb_build_object(
1115
+ 'ref', jsonb_build_object('id', v_existing.id, 'resource', 'people',
1116
+ 'archetype', 'person:lead', 'entityKey', 'crm:leads'),
1117
+ 'name', v_existing.name));
1118
+ END IF;
1119
+ END IF;
1120
+
1121
+ v_meta := jsonb_strip_nulls(jsonb_build_object(
1122
+ 'status', v_status,
1123
+ 'source', 'agent',
1124
+ 'company', nullif(trim(p_payload->>'company'), ''),
1125
+ 'value', nullif(trim(p_payload->>'value'), ''),
1126
+ 'sourceName', nullif(trim(p_payload->>'source_name'), ''),
1127
+ 'assignedToId', nullif(trim(p_payload->>'assigned_to_id'), '')
1128
+ ));
1129
+
1130
+ INSERT INTO people (tenant_id, kind, name, email, phone, notes, is_active, metadata)
1131
+ VALUES (p_tenant_id, 'lead', v_name,
1132
+ nullif(trim(p_payload->>'email'), ''),
1133
+ nullif(trim(p_payload->>'phone'), ''),
1134
+ left(p_payload->>'notes', 2000),
1135
+ true, v_meta)
1136
+ RETURNING id INTO v_id;
1137
+
1138
+ INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)
1139
+ VALUES (p_tenant_id, p_actor_user_id, 'agent.createLead', 'lead', v_id::text,
1140
+ jsonb_build_object('payload', p_payload));
1141
+
1142
+ SELECT l.id, l.name, l.email, l.phone, l.company, l.status
1143
+ INTO v_row
1144
+ FROM v_leads l WHERE l.id = v_id;
1145
+
1146
+ RETURN jsonb_build_object(
1147
+ 'ok', true,
1148
+ 'id', v_id,
1149
+ 'record', jsonb_build_object(
1150
+ 'ref', jsonb_build_object('id', v_id, 'resource', 'people',
1151
+ 'archetype', 'person:lead', 'entityKey', 'crm:leads'),
1152
+ 'name', v_row.name,
1153
+ 'email', v_row.email,
1154
+ 'phone', v_row.phone,
1155
+ 'company', v_row.company,
1156
+ 'status', v_row.status
1157
+ )
1158
+ );
1159
+ END;
1160
+ $$;
1161
+
1162
+ REVOKE ALL ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM public;
1163
+ REVOKE EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM anon;
1164
+ GRANT EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb)
1165
+ TO authenticated, service_role;
1166
+ `
1167
+
1168
+ export const MIGRATION_013_TAG_SLUGS = `-- plugin-crm 013: tags ganham um SLUG, que passa a ser o contrato.
1169
+ --
1170
+ -- people.tags e orders.tags sempre foram text[] livre, e plg_crm_tags sempre
1171
+ -- foi um cadastro solto: nada ligava um ao outro. Na prática isso dá os dois
1172
+ -- problemas clássicos de tag em CRM — "Live Agosto", "live agosto" e "Live
1173
+ -- Agosto " viram três tags, e renomear a tag no cadastro órfã todo registro que
1174
+ -- já carregava o nome antigo.
1175
+ --
1176
+ -- O slug resolve os dois: o ARRAY guarda slug (estável, normalizado), e o
1177
+ -- cadastro guarda label + cor para exibição. Renomear passa a ser cosmético.
1178
+ --
1179
+ -- Slug DESCONHECIDO continua válido de propósito: uma campanha precisa poder
1180
+ -- marcar leads hoje, sem esperar alguém cadastrar a tag. A UI mostra o slug
1181
+ -- num chip neutro até o cadastro existir. Vocabulário controlado que degrada,
1182
+ -- em vez de vocabulário que bloqueia.
1183
+
1184
+ -- ---------------------------------------------------------------------------
1185
+ -- Normalizador. Sem depender da extensão unaccent (nem todo pool a tem):
1186
+ -- translate() cobre o português, que é o que estas tags carregam.
1187
+ -- IMMUTABLE porque é usado em índice/generated abaixo.
1188
+ -- ---------------------------------------------------------------------------
1189
+ CREATE OR REPLACE FUNCTION public.crm_tag_slug(p_input text)
1190
+ RETURNS text
1191
+ LANGUAGE sql
1192
+ IMMUTABLE
1193
+ SET search_path TO 'public'
1194
+ AS $function$
1195
+ SELECT NULLIF(
1196
+ -- 4. colapsa hífens repetidos e apara as pontas
1197
+ trim(BOTH '-' FROM regexp_replace(
1198
+ -- 3. tudo que não for [a-z0-9:] vira hífen (':' sobrevive: é o separador
1199
+ -- de namespace das tags automáticas, ex. 'camp:black-friday')
1200
+ regexp_replace(
1201
+ -- 2. minúscula
1202
+ lower(
1203
+ -- 1. tira acento
1204
+ translate(
1205
+ COALESCE(p_input, ''),
1206
+ 'áàâãäéèêëíìîïóòôõöúùûüçñÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇÑ',
1207
+ 'aaaaaeeeeiiiiooooouuuucnAAAAAEEEEIIIIOOOOOUUUUCN'
1208
+ )
1209
+ ),
1210
+ '[^a-z0-9:]+', '-', 'g'
1211
+ ),
1212
+ '-{2,}', '-', 'g'
1213
+ )),
1214
+ ''
1215
+ );
1216
+ $function$;
1217
+
1218
+ COMMENT ON FUNCTION public.crm_tag_slug(text) IS
1219
+ 'Normaliza um rótulo de tag para o slug que people.tags/orders.tags guardam. Preserva ":" como separador de namespace (camp:, src:).';
1220
+
1221
+ -- ---------------------------------------------------------------------------
1222
+ -- Cadastro de tags: slug + backfill a partir do nome.
1223
+ -- ---------------------------------------------------------------------------
1224
+ ALTER TABLE public.plg_crm_tags
1225
+ ADD COLUMN IF NOT EXISTS slug text;
1226
+
1227
+ UPDATE public.plg_crm_tags
1228
+ SET slug = public.crm_tag_slug(name)
1229
+ WHERE slug IS NULL;
1230
+
1231
+ -- Duas linhas com o mesmo nome no mesmo tenant colidiriam no índice único.
1232
+ -- Desempata pela mais antiga (a que os registros provavelmente já referenciam)
1233
+ -- e sufixa as demais, em vez de falhar a migration.
1234
+ WITH dupes AS (
1235
+ SELECT id, row_number() OVER (PARTITION BY tenant_id, slug ORDER BY created_at, id) AS rn
1236
+ FROM public.plg_crm_tags
1237
+ WHERE slug IS NOT NULL
1238
+ )
1239
+ UPDATE public.plg_crm_tags t
1240
+ SET slug = t.slug || '-' || d.rn
1241
+ FROM dupes d
1242
+ WHERE d.id = t.id AND d.rn > 1;
1243
+
1244
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_plg_crm_tags_tenant_slug
1245
+ ON public.plg_crm_tags (tenant_id, slug);
1246
+
1247
+ -- Um cadastro sem slug não serve para nada (nunca casa com um registro), então
1248
+ -- o slug passa a ser derivado do nome quando o cliente não manda um.
1249
+ CREATE OR REPLACE FUNCTION public.plg_crm_tags_fill_slug()
1250
+ RETURNS trigger
1251
+ LANGUAGE plpgsql
1252
+ SET search_path TO 'public'
1253
+ AS $function$
1254
+ BEGIN
1255
+ NEW.slug := COALESCE(public.crm_tag_slug(NEW.slug), public.crm_tag_slug(NEW.name));
1256
+ RETURN NEW;
1257
+ END;
1258
+ $function$;
1259
+
1260
+ DROP TRIGGER IF EXISTS trg_plg_crm_tags_fill_slug ON public.plg_crm_tags;
1261
+ CREATE TRIGGER trg_plg_crm_tags_fill_slug
1262
+ BEFORE INSERT OR UPDATE OF name, slug ON public.plg_crm_tags
1263
+ FOR EACH ROW EXECUTE FUNCTION public.plg_crm_tags_fill_slug();
1264
+
1265
+ -- ---------------------------------------------------------------------------
1266
+ -- O cadastro passa a se alimentar do que é REALMENTE usado.
1267
+ --
1268
+ -- Até aqui plg_crm_tags só existia como tela: o \`seedData\` do registry alimenta
1269
+ -- o provider mock, nunca o banco, então /settings/crm/_properties/tags lia uma
1270
+ -- tabela vazia em todo tenant — e continuaria vazia mesmo com campanhas
1271
+ -- marcando leads. Registrar na escrita inverte isso: a tag aparece no cadastro
1272
+ -- porque foi usada, e o operador entra depois só para renomear ou trocar a cor.
1273
+ --
1274
+ -- Alternativa descartada: semear VIP/Hot Lead/Follow-up em todo tenant. Isso
1275
+ -- enche o cadastro de vocabulário que ninguém escolheu e que não corresponde a
1276
+ -- nenhum registro.
1277
+ -- ---------------------------------------------------------------------------
1278
+
1279
+ -- Cor estável por slug: a mesma tag sai da mesma cor em qualquer tenant, e o
1280
+ -- operador pode sobrescrever depois. Paleta com contraste suficiente em chip.
1281
+ CREATE OR REPLACE FUNCTION public.crm_tag_default_color(p_slug text)
1282
+ RETURNS text
1283
+ LANGUAGE sql
1284
+ IMMUTABLE
1285
+ AS $function$
1286
+ SELECT (ARRAY[
1287
+ '#6366f1','#0ea5e9','#10b981','#f59e0b','#ef4444','#ec4899','#8b5cf6','#14b8a6'
1288
+ ])[(abs(hashtext(COALESCE(p_slug, ''))) % 8) + 1];
1289
+ $function$;
1290
+
1291
+ -- Rótulo legível a partir do slug: 'camp:black-friday' -> 'Black Friday'.
1292
+ -- O namespace some do rótulo (a cor e o filtro já o distinguem) — quem lê o
1293
+ -- card quer ver a campanha, não o prefixo.
1294
+ CREATE OR REPLACE FUNCTION public.crm_tag_humanize(p_slug text)
1295
+ RETURNS text
1296
+ LANGUAGE sql
1297
+ IMMUTABLE
1298
+ AS $function$
1299
+ SELECT initcap(replace(regexp_replace(COALESCE(p_slug, ''), '^[a-z]+:', ''), '-', ' '));
1300
+ $function$;
1301
+
1302
+ CREATE OR REPLACE FUNCTION public.crm_register_tags(p_tenant_id uuid, p_slugs text[])
1303
+ RETURNS void
1304
+ LANGUAGE sql
1305
+ SECURITY DEFINER
1306
+ SET search_path TO 'public'
1307
+ AS $function$
1308
+ INSERT INTO public.plg_crm_tags (tenant_id, name, slug, color, is_active)
1309
+ SELECT p_tenant_id,
1310
+ public.crm_tag_humanize(s),
1311
+ s,
1312
+ public.crm_tag_default_color(s),
1313
+ true
1314
+ FROM unnest(COALESCE(p_slugs, '{}'::text[])) AS s
1315
+ WHERE s IS NOT NULL AND s <> ''
1316
+ ON CONFLICT (tenant_id, slug) DO NOTHING;
1317
+ $function$;
1318
+
1319
+ -- INTERNA de propósito: é SECURITY DEFINER e recebe o tenant do caller, então
1320
+ -- exposta ela deixaria qualquer um semear cadastro no tenant alheio. Só é
1321
+ -- alcançável de dentro de outra função DEFINER que já validou o tenant — hoje,
1322
+ -- create_public_lead. O caminho do ADMIN não passa por aqui: ele faz upsert
1323
+ -- direto em plg_crm_tags, onde a RLS da tabela já faz a autorização certa.
1324
+ REVOKE ALL ON FUNCTION public.crm_register_tags(uuid, text[]) FROM public, anon, authenticated;
1325
+
1326
+ -- Backfill: tudo que JÁ está em people.tags / orders.tags vira cadastro, para a
1327
+ -- tela não nascer vazia num tenant que já vinha usando tags.
1328
+ DO $$
1329
+ DECLARE
1330
+ r record;
1331
+ BEGIN
1332
+ FOR r IN
1333
+ SELECT tenant_id, array_agg(DISTINCT public.crm_tag_slug(tag)) AS slugs
1334
+ FROM (
1335
+ SELECT tenant_id, unnest(tags) AS tag FROM public.people WHERE tags IS NOT NULL
1336
+ UNION ALL
1337
+ SELECT tenant_id, unnest(tags) AS tag FROM public.orders WHERE tags IS NOT NULL
1338
+ ) used
1339
+ WHERE public.crm_tag_slug(tag) IS NOT NULL
1340
+ GROUP BY tenant_id
1341
+ LOOP
1342
+ PERFORM public.crm_register_tags(r.tenant_id, r.slugs);
1343
+ END LOOP;
1344
+ END $$;
1345
+ `
1346
+
1347
+ export const MIGRATION_014_PUBLIC_LEAD_TAGS = `-- plugin-crm 014: o formulário público passa a poder marcar o lead.
1348
+ --
1349
+ -- create_public_lead gravava \`ARRAY[]::text[]\` fixo — não existia caminho para
1350
+ -- uma landing page dizer "este lead veio da Turma Delas". Sem isso, tag em CRM
1351
+ -- vira trabalho manual: alguém abre o card e digita de onde veio, que é
1352
+ -- exatamente o que a atribuição automática deveria evitar.
1353
+ --
1354
+ -- O caller é um browser anônimo, então nada do que ele manda é confiável: os
1355
+ -- slugs são normalizados, deduplicados e limitados AQUI. O site pede tags; o
1356
+ -- banco decide o que de fato entra.
1357
+ --
1358
+ -- A propagação para o card do funil já existe: o trigger de
1359
+ -- 006_lead_enters_pipeline copia people.tags para orders.tags ao criar o deal.
1360
+
1361
+ -- A assinatura ganha p_tags. A antiga precisa SAIR: com as duas no catálogo o
1362
+ -- PostgREST não resolve a chamada sem tags (duas candidatas, mesmos nomes de
1363
+ -- parâmetro) e devolve PGRST203.
1364
+ DROP FUNCTION IF EXISTS public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb);
1365
+
1366
+ CREATE OR REPLACE FUNCTION public.create_public_lead(
1367
+ p_tenant_id uuid,
1368
+ p_name text,
1369
+ p_phone text DEFAULT NULL,
1370
+ p_email text DEFAULT NULL,
1371
+ p_form_id text DEFAULT NULL,
1372
+ p_form_name text DEFAULT NULL,
1373
+ p_fields jsonb DEFAULT '{}'::jsonb,
1374
+ p_notes text DEFAULT NULL,
1375
+ p_utm jsonb DEFAULT '{}'::jsonb,
1376
+ p_tags text[] DEFAULT '{}'::text[]
1377
+ )
1378
+ RETURNS TABLE(lead_id uuid, created_at timestamptz)
1379
+ LANGUAGE plpgsql
1380
+ SECURITY DEFINER
1381
+ SET search_path TO 'public'
1382
+ AS $function$
1383
+ DECLARE
1384
+ v_person_id uuid;
1385
+ v_phone text;
1386
+ v_email text;
1387
+ v_fields jsonb;
1388
+ v_utm jsonb;
1389
+ v_tags text[];
1390
+ v_recent int;
1391
+ BEGIN
1392
+ -- ---------------------------------------------------------------------
1393
+ -- validation: anon-callable, so everything is checked here
1394
+ -- ---------------------------------------------------------------------
1395
+ IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN
1396
+ RAISE EXCEPTION 'invalid name';
1397
+ END IF;
1398
+
1399
+ v_phone := NULLIF(regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g'), '');
1400
+ IF v_phone IS NOT NULL AND length(v_phone) NOT BETWEEN 8 AND 15 THEN
1401
+ RAISE EXCEPTION 'invalid phone';
1402
+ END IF;
1403
+
1404
+ v_email := NULLIF(trim(COALESCE(p_email, '')), '');
1405
+ IF v_email IS NOT NULL AND (length(v_email) > 254 OR v_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN
1406
+ RAISE EXCEPTION 'invalid email';
1407
+ END IF;
1408
+
1409
+ -- a lead with no way to reach them back is not a lead
1410
+ IF v_phone IS NULL AND v_email IS NULL THEN
1411
+ RAISE EXCEPTION 'phone or email required';
1412
+ END IF;
1413
+
1414
+ PERFORM 1 FROM tenants t WHERE t.id = p_tenant_id;
1415
+ IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;
1416
+
1417
+ -- ---------------------------------------------------------------------
1418
+ -- custom fields: object-only, bounded, and scalars only.
1419
+ -- ---------------------------------------------------------------------
1420
+ v_fields := COALESCE(p_fields, '{}'::jsonb);
1421
+ IF jsonb_typeof(v_fields) <> 'object' THEN
1422
+ RAISE EXCEPTION 'fields must be an object';
1423
+ END IF;
1424
+ IF length(v_fields::text) > 8000 THEN
1425
+ RAISE EXCEPTION 'fields too large';
1426
+ END IF;
1427
+ IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN
1428
+ RAISE EXCEPTION 'too many fields';
1429
+ END IF;
1430
+
1431
+ v_utm := COALESCE(p_utm, '{}'::jsonb);
1432
+ IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN
1433
+ RAISE EXCEPTION 'invalid utm';
1434
+ END IF;
1435
+
1436
+ -- ---------------------------------------------------------------------
1437
+ -- tags: normalizadas e limitadas aqui. Um slug ruim é DESCARTADO em vez de
1438
+ -- derrubar a submissão — perder um lead por causa de um rótulo de campanha
1439
+ -- mal formatado seria trocar o essencial pelo acessório. Teto de 10 evita
1440
+ -- que uma querystring hostil vire um card com cinquenta chips.
1441
+ -- ---------------------------------------------------------------------
1442
+ SELECT array_agg(s) INTO v_tags FROM (
1443
+ SELECT DISTINCT public.crm_tag_slug(t) AS s
1444
+ FROM unnest(COALESCE(p_tags, '{}'::text[])) AS t
1445
+ WHERE public.crm_tag_slug(t) IS NOT NULL
1446
+ AND length(public.crm_tag_slug(t)) <= 48
1447
+ LIMIT 10
1448
+ ) normalized;
1449
+ v_tags := COALESCE(v_tags, '{}'::text[]);
1450
+
1451
+ -- ---------------------------------------------------------------------
1452
+ -- anti-spam: same tenant + same contact + same form, twice in 5 minutes is
1453
+ -- a double-click or a bot, not two inquiries.
1454
+ -- ---------------------------------------------------------------------
1455
+ SELECT count(*) INTO v_recent
1456
+ FROM people p
1457
+ WHERE p.tenant_id = p_tenant_id
1458
+ AND p.kind = 'lead'
1459
+ AND p.created_at > now() - interval '5 minutes'
1460
+ AND COALESCE(p.metadata->>'formId', '') = COALESCE(p_form_id, '')
1461
+ AND (
1462
+ (v_phone IS NOT NULL AND p.phone = v_phone)
1463
+ OR (v_email IS NOT NULL AND p.email = v_email)
1464
+ );
1465
+ IF v_recent > 0 THEN
1466
+ RAISE EXCEPTION 'duplicate submission';
1467
+ END IF;
1468
+
1469
+ -- burst cap per tenant: a flood is never legitimate marketing traffic
1470
+ IF (
1471
+ SELECT count(*) FROM people p
1472
+ WHERE p.tenant_id = p_tenant_id
1473
+ AND p.kind = 'lead'
1474
+ AND p.created_at > now() - interval '1 minute'
1475
+ ) >= 20 THEN
1476
+ RAISE EXCEPTION 'too many submissions';
1477
+ END IF;
1478
+
1479
+ -- ---------------------------------------------------------------------
1480
+ -- the lead. status/kind are hardcoded — the caller cannot promote itself
1481
+ -- into a customer or land pre-qualified.
1482
+ -- ---------------------------------------------------------------------
1483
+ INSERT INTO people (tenant_id, kind, name, phone, email, notes, tags, is_active, metadata)
1484
+ VALUES (
1485
+ p_tenant_id,
1486
+ 'lead',
1487
+ trim(p_name),
1488
+ v_phone,
1489
+ v_email,
1490
+ left(p_notes, 2000),
1491
+ v_tags,
1492
+ true,
1493
+ jsonb_strip_nulls(
1494
+ jsonb_build_object(
1495
+ 'status', 'new',
1496
+ 'source', 'public_form',
1497
+ 'sourceName', COALESCE(NULLIF(trim(COALESCE(p_form_name, '')), ''), 'Site'),
1498
+ 'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),
1499
+ 'fields', v_fields,
1500
+ 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END
1501
+ )
1502
+ )
1503
+ )
1504
+ RETURNING id, people.created_at INTO v_person_id, created_at;
1505
+
1506
+ -- O cadastro de tags se alimenta do que foi usado, para a tela de settings
1507
+ -- refletir a realidade sem ninguém pré-preencher nada.
1508
+ IF array_length(v_tags, 1) > 0 THEN
1509
+ PERFORM public.crm_register_tags(p_tenant_id, v_tags);
1510
+ END IF;
1511
+
1512
+ lead_id := v_person_id;
1513
+ RETURN NEXT;
1514
+ END;
1515
+ $function$;
1516
+
1517
+ GRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb, text[])
1518
+ TO anon, authenticated;
1519
+ `
1520
+
699
1521
  export const MIGRATIONS: Array<{ id: string; sql: string }> = [
700
1522
  { id: "000_plg_rename", sql: MIGRATION_000_PLG_RENAME },
701
1523
  { id: "001_crm_base", sql: MIGRATION_001_CRM_BASE },
@@ -704,4 +1526,12 @@ export const MIGRATIONS: Array<{ id: string; sql: string }> = [
704
1526
  { id: "004_seed_default_pipeline", sql: MIGRATION_004_SEED_DEFAULT_PIPELINE },
705
1527
  { id: "005_public_lead", sql: MIGRATION_005_PUBLIC_LEAD },
706
1528
  { id: "006_lead_enters_pipeline", sql: MIGRATION_006_LEAD_ENTERS_PIPELINE },
1529
+ { id: "007_activity_log", sql: MIGRATION_007_ACTIVITY_LOG },
1530
+ { id: "008_view_field_aliases", sql: MIGRATION_008_VIEW_FIELD_ALIASES },
1531
+ { id: "009_deal_archived_status", sql: MIGRATION_009_DEAL_ARCHIVED_STATUS },
1532
+ { id: "010_quote_archived_status", sql: MIGRATION_010_QUOTE_ARCHIVED_STATUS },
1533
+ { id: "011_agent_rpc_update_lead", sql: MIGRATION_011_AGENT_RPC_UPDATE_LEAD },
1534
+ { id: "012_agent_rpc_create_lead", sql: MIGRATION_012_AGENT_RPC_CREATE_LEAD },
1535
+ { id: "013_tag_slugs", sql: MIGRATION_013_TAG_SLUGS },
1536
+ { id: "014_public_lead_tags", sql: MIGRATION_014_PUBLIC_LEAD_TAGS },
707
1537
  ]