@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.
- package/dist/cascade.d.ts.map +1 -1
- package/dist/components/BoardFilters.d.ts +23 -0
- package/dist/components/BoardFilters.d.ts.map +1 -0
- package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
- package/dist/components/TagChips.d.ts +16 -0
- package/dist/components/TagChips.d.ts.map +1 -0
- package/dist/data/mock.d.ts +5 -0
- package/dist/data/mock.d.ts.map +1 -1
- package/dist/data/supabase.d.ts +6 -0
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/data/types.d.ts +12 -2
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1136 -164
- package/dist/index.js.map +1 -1
- package/dist/lib/access.d.ts +8 -0
- package/dist/lib/access.d.ts.map +1 -0
- package/dist/locales/en.d.ts.map +1 -1
- package/dist/locales/pt-BR.d.ts.map +1 -1
- package/dist/migrations/index.d.ts +9 -1
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/public/context.d.ts +3 -3
- package/dist/public/context.d.ts.map +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts +18 -2
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
- package/dist/public/data.supabase.d.ts.map +1 -1
- package/dist/public/index.js +31 -7
- package/dist/public/index.js.map +1 -1
- package/dist/public/types.d.ts +27 -0
- package/dist/public/types.d.ts.map +1 -1
- package/dist/registries.d.ts +11 -0
- package/dist/registries.d.ts.map +1 -1
- package/dist/store.d.ts +12 -2
- package/dist/store.d.ts.map +1 -1
- package/dist/types.d.ts +51 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/views/ActivityListView.d.ts +6 -1
- package/dist/views/ActivityListView.d.ts.map +1 -1
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadDetailView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/dist/views/QuoteDetailView.d.ts.map +1 -1
- package/dist/views/QuoteListView.d.ts.map +1 -1
- package/package.json +15 -14
- package/src/CrmPage.tsx +1 -1
- package/src/cascade.ts +2 -0
- package/src/components/BoardFilters.tsx +190 -0
- package/src/components/QuoteStatusDropdown.tsx +15 -3
- package/src/components/TagChips.tsx +80 -0
- package/src/data/mock.ts +140 -7
- package/src/data/supabase.ts +256 -11
- package/src/data/types.ts +14 -3
- package/src/index.ts +179 -3
- package/src/lib/access.ts +11 -0
- package/src/locales/en.ts +13 -0
- package/src/locales/pt-BR.ts +18 -5
- package/src/migrations/003_crm_views_rls.sql +10 -2
- package/src/migrations/007_activity_log.sql +55 -0
- package/src/migrations/008_view_field_aliases.sql +43 -0
- package/src/migrations/009_deal_archived_status.sql +30 -0
- package/src/migrations/010_quote_archived_status.sql +40 -0
- package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
- package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
- package/src/migrations/013_tag_slugs.sql +177 -0
- package/src/migrations/014_public_lead_tags.sql +172 -0
- package/src/migrations/index.ts +833 -3
- package/src/public/context.tsx +4 -4
- package/src/public/createPublicFormsPlugin.ts +72 -2
- package/src/public/data.supabase.ts +3 -2
- package/src/public/types.ts +28 -0
- package/src/registries.ts +44 -11
- package/src/store.ts +135 -38
- package/src/types.ts +59 -2
- package/src/views/ActivityListView.tsx +79 -11
- package/src/views/DealSidebar.tsx +48 -39
- package/src/views/LeadDetailView.tsx +29 -10
- package/src/views/PipelineView.tsx +112 -11
- package/src/views/QuoteDetailView.tsx +7 -3
- package/src/views/QuoteListView.tsx +26 -12
- package/dist/index.cjs +0 -4759
- package/dist/index.cjs.map +0 -1
- package/dist/public/index.cjs +0 -306
- package/dist/public/index.cjs.map +0 -1
package/src/locales/en.ts
CHANGED
|
@@ -10,6 +10,7 @@ export const en: Record<string, string> = {
|
|
|
10
10
|
"crm.activities.overdueLabel": "Overdue",
|
|
11
11
|
"crm.activities.pending": "pending",
|
|
12
12
|
"crm.activities.pendingFilter": "Pending",
|
|
13
|
+
"crm.activities.systemEvents": "Events",
|
|
13
14
|
"crm.activities.title": "Activities",
|
|
14
15
|
"crm.dashboard.activeDeals": "{{count}} active deals",
|
|
15
16
|
"crm.dashboard.avgDealValue": "Avg deal value",
|
|
@@ -56,6 +57,7 @@ export const en: Record<string, string> = {
|
|
|
56
57
|
"crm.dealSidebar.value": "Value",
|
|
57
58
|
"crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
|
|
58
59
|
"crm.leadDetail.assignedTo": "Assigned to",
|
|
60
|
+
"crm.leadDetail.archive": "Archive",
|
|
59
61
|
"crm.leadDetail.backToList": "Back to list",
|
|
60
62
|
"crm.leadDetail.formAnswers": "Form answers",
|
|
61
63
|
"crm.leadDetail.company": "Company",
|
|
@@ -114,7 +116,17 @@ export const en: Record<string, string> = {
|
|
|
114
116
|
"crm.page.newQuoteDesc": "Send a proposal",
|
|
115
117
|
"crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
|
|
116
118
|
"crm.page.settingsTitle": "Sales & CRM Settings",
|
|
119
|
+
"crm.filters.period": "Period",
|
|
120
|
+
"crm.filters.periodAll": "All",
|
|
121
|
+
"crm.filters.period24h": "24 hours",
|
|
122
|
+
"crm.filters.period7d": "7 days",
|
|
123
|
+
"crm.filters.periodCustom": "Custom",
|
|
124
|
+
"crm.filters.tags": "Tags",
|
|
125
|
+
"crm.filters.tagsSelected": "{{count}} tag(s)",
|
|
126
|
+
"crm.filters.clearTags": "Clear tags",
|
|
127
|
+
"crm.filters.noResults": "No deals match the current filter",
|
|
117
128
|
"crm.pipeline.dropHere": "Drop here",
|
|
129
|
+
"crm.pipeline.archive": "Archive",
|
|
118
130
|
"crm.pipeline.moveFailed": "Failed to move deal",
|
|
119
131
|
"crm.pipeline.movedTo": "Moved to {{stage}}",
|
|
120
132
|
"crm.pipeline.noDeals": "No deals",
|
|
@@ -193,6 +205,7 @@ export const en: Record<string, string> = {
|
|
|
193
205
|
"crm.quoteForm.unitPrice": "Unit Price",
|
|
194
206
|
"crm.quoteForm.validUntil": "Valid Until",
|
|
195
207
|
"crm.quotes.amount": "Amount",
|
|
208
|
+
"crm.quotes.archive": "Archive",
|
|
196
209
|
"crm.quotes.contact": "Contact",
|
|
197
210
|
"crm.quotes.createFirst": "Create your first quote",
|
|
198
211
|
"crm.quotes.date": "Date",
|
package/src/locales/pt-BR.ts
CHANGED
|
@@ -10,6 +10,7 @@ export const ptBR: Record<string, string> = {
|
|
|
10
10
|
"crm.activities.overdueLabel": "Atrasada",
|
|
11
11
|
"crm.activities.pending": "pendente",
|
|
12
12
|
"crm.activities.pendingFilter": "Pendentes",
|
|
13
|
+
"crm.activities.systemEvents": "Eventos",
|
|
13
14
|
"crm.activities.title": "Atividades",
|
|
14
15
|
"crm.dashboard.activeDeals": "{{count}} negócios ativos",
|
|
15
16
|
"crm.dashboard.avgDealValue": "Valor médio do negócio",
|
|
@@ -56,6 +57,7 @@ export const ptBR: Record<string, string> = {
|
|
|
56
57
|
"crm.dealSidebar.value": "Valor",
|
|
57
58
|
"crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
|
|
58
59
|
"crm.leadDetail.assignedTo": "Atribuído a",
|
|
60
|
+
"crm.leadDetail.archive": "Arquivar",
|
|
59
61
|
"crm.leadDetail.backToList": "Voltar à lista",
|
|
60
62
|
"crm.leadDetail.formAnswers": "Dados do formulário",
|
|
61
63
|
"crm.leadDetail.company": "Empresa",
|
|
@@ -111,10 +113,20 @@ export const ptBR: Record<string, string> = {
|
|
|
111
113
|
"crm.page.newLead": "Novo Lead",
|
|
112
114
|
"crm.page.newLeadDesc": "Capturar um novo lead",
|
|
113
115
|
"crm.page.newQuote": "Novo Orçamento",
|
|
114
|
-
"crm.page.newQuoteDesc": "Enviar
|
|
116
|
+
"crm.page.newQuoteDesc": "Enviar um orçamento",
|
|
115
117
|
"crm.page.settingsSubtitle": "Configure pipeline, gestão de leads e cadastros",
|
|
116
118
|
"crm.page.settingsTitle": "Configurações de Vendas e CRM",
|
|
119
|
+
"crm.filters.period": "Período",
|
|
120
|
+
"crm.filters.periodAll": "Tudo",
|
|
121
|
+
"crm.filters.period24h": "24 horas",
|
|
122
|
+
"crm.filters.period7d": "7 dias",
|
|
123
|
+
"crm.filters.periodCustom": "Personalizado",
|
|
124
|
+
"crm.filters.tags": "Tags",
|
|
125
|
+
"crm.filters.tagsSelected": "{{count}} tag(s)",
|
|
126
|
+
"crm.filters.clearTags": "Limpar tags",
|
|
127
|
+
"crm.filters.noResults": "Nenhum negócio no filtro atual",
|
|
117
128
|
"crm.pipeline.dropHere": "Solte aqui",
|
|
129
|
+
"crm.pipeline.archive": "Arquivar",
|
|
118
130
|
"crm.pipeline.moveFailed": "Falha ao mover negócio",
|
|
119
131
|
"crm.pipeline.movedTo": "Movido para {{stage}}",
|
|
120
132
|
"crm.pipeline.noDeals": "Nenhum negócio",
|
|
@@ -160,12 +172,12 @@ export const ptBR: Record<string, string> = {
|
|
|
160
172
|
"crm.quoteForm.description": "Descrição",
|
|
161
173
|
"crm.quoteForm.discount": "Desconto",
|
|
162
174
|
"crm.quoteForm.done": "Concluído",
|
|
163
|
-
"crm.quoteForm.editSubtitle": "Atualizar
|
|
175
|
+
"crm.quoteForm.editSubtitle": "Atualizar este orçamento",
|
|
164
176
|
"crm.quoteForm.editTitle": "Editar Orçamento",
|
|
165
177
|
"crm.quoteForm.itemCount": "{{count}} itens",
|
|
166
178
|
"crm.quoteForm.itemDescriptionPlaceholder": "Descrição do item",
|
|
167
179
|
"crm.quoteForm.loading": "Carregando...",
|
|
168
|
-
"crm.quoteForm.newSubtitle": "Criar
|
|
180
|
+
"crm.quoteForm.newSubtitle": "Criar um orçamento para seu cliente",
|
|
169
181
|
"crm.quoteForm.newTitle": "Novo Orçamento",
|
|
170
182
|
"crm.quoteForm.noDescription": "Sem descrição",
|
|
171
183
|
"crm.quoteForm.noItems": "Nenhum item adicionado",
|
|
@@ -193,6 +205,7 @@ export const ptBR: Record<string, string> = {
|
|
|
193
205
|
"crm.quoteForm.unitPrice": "Preço Unitário",
|
|
194
206
|
"crm.quoteForm.validUntil": "Válido Até",
|
|
195
207
|
"crm.quotes.amount": "Valor",
|
|
208
|
+
"crm.quotes.archive": "Arquivar",
|
|
196
209
|
"crm.quotes.contact": "Contato",
|
|
197
210
|
"crm.quotes.createFirst": "Crie seu primeiro orçamento",
|
|
198
211
|
"crm.quotes.date": "Data",
|
|
@@ -206,7 +219,7 @@ export const ptBR: Record<string, string> = {
|
|
|
206
219
|
"crm.quickActions.newDeal": "Novo Negócio",
|
|
207
220
|
"crm.quickActions.newDealDesc": "Criar um negócio no pipeline",
|
|
208
221
|
"crm.quickActions.newQuote": "Novo Orçamento",
|
|
209
|
-
"crm.quickActions.newQuoteDesc": "Enviar
|
|
222
|
+
"crm.quickActions.newQuoteDesc": "Enviar um orçamento",
|
|
210
223
|
"crm.quickActions.logActivity": "Registrar Atividade",
|
|
211
224
|
"crm.quickActions.logActivityDesc": "Registrar ligação, e-mail ou nota",
|
|
212
225
|
"crm.settingsPage.title": "Configurações de Vendas e CRM",
|
|
@@ -243,7 +256,7 @@ export const ptBR: Record<string, string> = {
|
|
|
243
256
|
"crm.settings.weightedPipeline": "Valor ponderado do pipeline",
|
|
244
257
|
"crm.settings.weightedPipelineDesc": "Calcular valor do pipeline usando probabilidade do estágio",
|
|
245
258
|
"crm.settings.quotes": "Orçamentos",
|
|
246
|
-
"crm.settings.quotesDesc": "Comportamento de orçamentos
|
|
259
|
+
"crm.settings.quotesDesc": "Comportamento de orçamentos",
|
|
247
260
|
"crm.settings.autoNumberQuotes": "Numeração automática de orçamentos",
|
|
248
261
|
"crm.settings.autoNumberQuotesDesc": "Gerar automaticamente números sequenciais de orçamentos",
|
|
249
262
|
"crm.settings.defaultValidity": "Validade padrão (30 dias)",
|
|
@@ -29,7 +29,12 @@ BEGIN
|
|
|
29
29
|
END $$;
|
|
30
30
|
|
|
31
31
|
-- v_leads: public.people (kind='lead')
|
|
32
|
-
|
|
32
|
+
-- DROP first: 005 widens this view (form_id/custom_fields/utm), and CREATE OR
|
|
33
|
+
-- REPLACE cannot narrow a live view — replaying 003 on a pool that already ran
|
|
34
|
+
-- 005 would fail with "cannot drop columns from view". 005 replays right after
|
|
35
|
+
-- and widens it again, so the net result is unchanged.
|
|
36
|
+
DROP VIEW IF EXISTS public.v_leads;
|
|
37
|
+
CREATE VIEW public.v_leads WITH (security_invoker=true) AS
|
|
33
38
|
SELECT
|
|
34
39
|
p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,
|
|
35
40
|
p.metadata->>'company' AS company,
|
|
@@ -44,7 +49,10 @@ WHERE p.kind = 'lead';
|
|
|
44
49
|
GRANT SELECT ON public.v_leads TO authenticated;
|
|
45
50
|
|
|
46
51
|
-- v_deals: public.orders (kind='deal') JOIN plg_crm_deal_extensions JOIN plg_crm_pipeline_stages
|
|
47
|
-
|
|
52
|
+
-- DROP first for the same reason as v_leads above: 008 appends the `stage`
|
|
53
|
+
-- alias, and CREATE OR REPLACE cannot narrow a live view on replay.
|
|
54
|
+
DROP VIEW IF EXISTS public.v_deals;
|
|
55
|
+
CREATE VIEW public.v_deals WITH (security_invoker=true) AS
|
|
48
56
|
SELECT
|
|
49
57
|
o.id, o.tenant_id, o.status,
|
|
50
58
|
o.total AS value, o.notes AS title,
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
-- CRM plugin — activity log foundation.
|
|
2
|
+
-- Activity types become tenant-editable (icon column) and upsertable by the
|
|
3
|
+
-- provider's lazy per-tenant seed (unique tenant+name). System timeline events
|
|
4
|
+
-- (lead_created, stage_changed, quote_*…) are written by the data provider
|
|
5
|
+
-- into plg_crm_activities with completed_at = now(); they are product-defined
|
|
6
|
+
-- and do NOT live in the types catalog.
|
|
7
|
+
-- Idempotent / replay-safe.
|
|
8
|
+
|
|
9
|
+
ALTER TABLE public.plg_crm_activity_types ADD COLUMN IF NOT EXISTS icon text;
|
|
10
|
+
|
|
11
|
+
-- Guarded: a pre-existing pool could hold duplicate names; skip rather than fail.
|
|
12
|
+
DO $$
|
|
13
|
+
BEGIN
|
|
14
|
+
CREATE UNIQUE INDEX IF NOT EXISTS uq_plg_crm_activity_types_tenant_name
|
|
15
|
+
ON public.plg_crm_activity_types(tenant_id, name);
|
|
16
|
+
EXCEPTION WHEN OTHERS THEN
|
|
17
|
+
RAISE NOTICE 'skipping uq_plg_crm_activity_types_tenant_name: %', SQLERRM;
|
|
18
|
+
END $$;
|
|
19
|
+
|
|
20
|
+
-- Backfill: records created BEFORE auto-logging existed get their timeline
|
|
21
|
+
-- events retroactively (stamped at the record's created_at), so the Activities
|
|
22
|
+
-- view isn't empty on day one. Idempotent via NOT EXISTS per record+type.
|
|
23
|
+
INSERT INTO public.plg_crm_activities
|
|
24
|
+
(tenant_id, lead_id, contact_name, activity_type, title, completed_at, created_at)
|
|
25
|
+
SELECT p.tenant_id, p.id, p.name, 'lead_created', p.name, p.created_at, p.created_at
|
|
26
|
+
FROM public.people p
|
|
27
|
+
WHERE p.kind = 'lead'
|
|
28
|
+
AND NOT EXISTS (
|
|
29
|
+
SELECT 1 FROM public.plg_crm_activities a
|
|
30
|
+
WHERE a.lead_id = p.id AND a.activity_type = 'lead_created'
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
INSERT INTO public.plg_crm_activities
|
|
34
|
+
(tenant_id, deal_id, contact_name, activity_type, title, completed_at, created_at)
|
|
35
|
+
SELECT o.tenant_id, o.id, o.metadata->>'contactName', 'deal_created',
|
|
36
|
+
COALESCE(NULLIF(o.notes, ''), 'Deal'), o.created_at, o.created_at
|
|
37
|
+
FROM public.orders o
|
|
38
|
+
WHERE o.kind = 'deal'
|
|
39
|
+
AND NOT EXISTS (
|
|
40
|
+
SELECT 1 FROM public.plg_crm_activities a
|
|
41
|
+
WHERE a.deal_id = o.id AND a.activity_type = 'deal_created'
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
INSERT INTO public.plg_crm_activities
|
|
45
|
+
(tenant_id, contact_name, activity_type, title, description, completed_at, created_at)
|
|
46
|
+
SELECT o.tenant_id, o.metadata->>'contactName', 'quote_created',
|
|
47
|
+
COALESCE(o.reference_number, 'Quote'), o.metadata->>'contactName',
|
|
48
|
+
o.created_at, o.created_at
|
|
49
|
+
FROM public.orders o
|
|
50
|
+
WHERE o.kind = 'quote'
|
|
51
|
+
AND NOT EXISTS (
|
|
52
|
+
SELECT 1 FROM public.plg_crm_activities a
|
|
53
|
+
WHERE a.activity_type = 'quote_created' AND a.title = COALESCE(o.reference_number, 'Quote')
|
|
54
|
+
AND a.tenant_id = o.tenant_id
|
|
55
|
+
);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
-- CRM plugin — agent-ergonomic view aliases.
|
|
2
|
+
-- The assistant's first guess for a groupBy/filter field is the natural name
|
|
3
|
+
-- ('stage', 'status'), not the qualified one ('stage_name', 'lead_status') —
|
|
4
|
+
-- each miss costs a failed tool round. CREATE OR REPLACE can only APPEND
|
|
5
|
+
-- columns, so the aliases land at the end; existing consumers are untouched.
|
|
6
|
+
-- Idempotent.
|
|
7
|
+
|
|
8
|
+
CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS
|
|
9
|
+
SELECT
|
|
10
|
+
o.id, o.tenant_id, o.status,
|
|
11
|
+
o.total AS value, o.notes AS title,
|
|
12
|
+
o.party_id AS contact_id, o.assignee_id AS assigned_to_id, o.tags,
|
|
13
|
+
o.metadata->>'contactName' AS contact_name,
|
|
14
|
+
o.created_at, o.updated_at,
|
|
15
|
+
de.pipeline_id, de.stage_id, de.probability, de.expected_close_date,
|
|
16
|
+
de.lead_id, de.lost_reason,
|
|
17
|
+
ps.name AS stage_name, ps.color AS stage_color, ps."order" AS stage_order,
|
|
18
|
+
ps.name AS stage
|
|
19
|
+
FROM public.orders o
|
|
20
|
+
LEFT JOIN public.plg_crm_deal_extensions de ON de.order_id = o.id
|
|
21
|
+
LEFT JOIN public.plg_crm_pipeline_stages ps ON ps.id = de.stage_id
|
|
22
|
+
WHERE o.kind = 'deal';
|
|
23
|
+
GRANT SELECT ON public.v_deals TO authenticated;
|
|
24
|
+
|
|
25
|
+
-- v_leads: current definition is 005's widened shape — append `status`.
|
|
26
|
+
CREATE OR REPLACE VIEW public.v_leads
|
|
27
|
+
WITH (security_invoker = true) AS
|
|
28
|
+
SELECT
|
|
29
|
+
p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,
|
|
30
|
+
p.metadata->>'company' AS company,
|
|
31
|
+
p.metadata->>'sourceId' AS source_id,
|
|
32
|
+
p.metadata->>'sourceName' AS source_name,
|
|
33
|
+
COALESCE(p.metadata->>'status','new') AS lead_status,
|
|
34
|
+
p.metadata->>'value' AS lead_value,
|
|
35
|
+
p.metadata->>'assignedToId' AS assigned_to_id,
|
|
36
|
+
p.created_at, p.updated_at,
|
|
37
|
+
p.metadata->>'formId' AS form_id,
|
|
38
|
+
COALESCE(p.metadata->'fields', '{}'::jsonb) AS custom_fields,
|
|
39
|
+
COALESCE(p.metadata->'utm', '{}'::jsonb) AS utm,
|
|
40
|
+
COALESCE(p.metadata->>'status','new') AS status
|
|
41
|
+
FROM public.people p
|
|
42
|
+
WHERE p.kind = 'lead';
|
|
43
|
+
GRANT SELECT ON public.v_leads TO authenticated;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
-- CRM plugin — allow status='archived' for deals.
|
|
2
|
+
-- A beauty-era legacy migration (20260617000006) added orders_kind_status_valid
|
|
3
|
+
-- whitelisting per-kind statuses; the deal branch predates archiving and
|
|
4
|
+
-- rejected the soft-remove write. Recreate the check with 'archived' included,
|
|
5
|
+
-- ONLY where the constraint exists (other pools: no-op). NOT VALID kept from
|
|
6
|
+
-- the original — existing rows are not re-validated. Idempotent via the
|
|
7
|
+
-- 'archived' probe.
|
|
8
|
+
|
|
9
|
+
DO $$
|
|
10
|
+
DECLARE def text;
|
|
11
|
+
BEGIN
|
|
12
|
+
SELECT pg_get_constraintdef(oid) INTO def
|
|
13
|
+
FROM pg_constraint
|
|
14
|
+
WHERE conname = 'orders_kind_status_valid' AND conrelid = 'public.orders'::regclass;
|
|
15
|
+
IF def IS NULL OR def LIKE '%archived%' THEN RETURN; END IF;
|
|
16
|
+
|
|
17
|
+
ALTER TABLE public.orders DROP CONSTRAINT orders_kind_status_valid;
|
|
18
|
+
ALTER TABLE public.orders ADD CONSTRAINT orders_kind_status_valid CHECK (
|
|
19
|
+
status IS NULL OR
|
|
20
|
+
CASE kind
|
|
21
|
+
WHEN 'quote' THEN status IN ('draft', 'sent', 'approved', 'rejected', 'expired', 'converted')
|
|
22
|
+
WHEN 'deal' THEN status IN ('open', 'won', 'lost', 'archived')
|
|
23
|
+
WHEN 'appointment' THEN status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid')
|
|
24
|
+
WHEN 'service_order' THEN status IN ('draft', 'scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'invoiced', 'paid')
|
|
25
|
+
WHEN 'invoice_receivable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
|
|
26
|
+
WHEN 'invoice_payable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
|
|
27
|
+
ELSE true
|
|
28
|
+
END
|
|
29
|
+
) NOT VALID;
|
|
30
|
+
END $$;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
-- CRM plugin — allow status='archived' for quotes (follow-up to 009, which
|
|
2
|
+
-- covered deals). Recreates orders_kind_status_valid with 'archived' in BOTH
|
|
3
|
+
-- branches, only where the constraint exists (other pools: no-op). Idempotent:
|
|
4
|
+
-- skips when 'archived' already appears twice (deal + quote branches).
|
|
5
|
+
|
|
6
|
+
DO $$
|
|
7
|
+
DECLARE def text;
|
|
8
|
+
BEGIN
|
|
9
|
+
SELECT pg_get_constraintdef(oid) INTO def
|
|
10
|
+
FROM pg_constraint
|
|
11
|
+
WHERE conname = 'orders_kind_status_valid' AND conrelid = 'public.orders'::regclass;
|
|
12
|
+
IF def IS NULL THEN RETURN; END IF;
|
|
13
|
+
IF (length(def) - length(replace(def, 'archived', ''))) / length('archived') >= 2 THEN RETURN; END IF;
|
|
14
|
+
|
|
15
|
+
ALTER TABLE public.orders DROP CONSTRAINT orders_kind_status_valid;
|
|
16
|
+
ALTER TABLE public.orders ADD CONSTRAINT orders_kind_status_valid CHECK (
|
|
17
|
+
status IS NULL OR
|
|
18
|
+
CASE kind
|
|
19
|
+
WHEN 'quote' THEN status IN ('draft', 'sent', 'approved', 'rejected', 'expired', 'converted', 'archived')
|
|
20
|
+
WHEN 'deal' THEN status IN ('open', 'won', 'lost', 'archived')
|
|
21
|
+
WHEN 'appointment' THEN status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid')
|
|
22
|
+
WHEN 'service_order' THEN status IN ('draft', 'scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'invoiced', 'paid')
|
|
23
|
+
WHEN 'invoice_receivable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
|
|
24
|
+
WHEN 'invoice_payable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')
|
|
25
|
+
ELSE true
|
|
26
|
+
END
|
|
27
|
+
) NOT VALID;
|
|
28
|
+
END $$;
|
|
29
|
+
|
|
30
|
+
-- Backfill: deals stuck at total=0 whose quotes hold the real number take the
|
|
31
|
+
-- LATEST quote's total (the same sync the provider now does on quote create/
|
|
32
|
+
-- update). Idempotent — once totals are non-zero the predicate no longer bites.
|
|
33
|
+
UPDATE public.orders d SET total = q.total
|
|
34
|
+
FROM (
|
|
35
|
+
SELECT DISTINCT ON ((metadata->>'dealId')) metadata->>'dealId' AS deal_id, total
|
|
36
|
+
FROM public.orders
|
|
37
|
+
WHERE kind = 'quote' AND metadata->>'dealId' IS NOT NULL AND total > 0
|
|
38
|
+
ORDER BY (metadata->>'dealId'), created_at DESC
|
|
39
|
+
) q
|
|
40
|
+
WHERE d.id::text = q.deal_id AND d.kind = 'deal' AND COALESCE(d.total, 0) = 0;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
-- ============================================================================
|
|
2
|
+
-- plugin-crm 011: agent_crm_update_lead — mover o status de um lead (e corrigir
|
|
3
|
+
-- seus dados) pelo agente.
|
|
4
|
+
--
|
|
5
|
+
-- Lacuna que isso fecha: o CRM não tinha NENHUMA escrita pelo agente. Pedido
|
|
6
|
+
-- real ("acabei de mandar a proposta pra ele, então atualiza o status") caía no
|
|
7
|
+
-- updateRecord genérico, que bate em v_leads — uma view sobre people —, e o
|
|
8
|
+
-- assistente só sabia dizer "essa entidade é somente leitura". Mudar status de
|
|
9
|
+
-- lead é a ação mais frequente de um CRM; sem ela o agente é só um relatório.
|
|
10
|
+
--
|
|
11
|
+
-- Sobre o feature id: `sales`, não `crm.leads`. Duas razões, ambas medidas em
|
|
12
|
+
-- pool real. (1) agent_guard concatena feature || '.' || action sem normalizar,
|
|
13
|
+
-- e nenhum pool guarda `crm.leads.edit` — beauty guarda `crm_leads.edit`,
|
|
14
|
+
-- great-djs não guarda nenhum dos dois. (2) `sales.edit` existe nos dois, e é o
|
|
15
|
+
-- que a própria tool declara em `permission`. Servidor e cliente checando
|
|
16
|
+
-- features diferentes é bug por construção.
|
|
17
|
+
-- ============================================================================
|
|
18
|
+
|
|
19
|
+
CREATE OR REPLACE FUNCTION public.agent_crm_update_lead(
|
|
20
|
+
p_tenant_id uuid,
|
|
21
|
+
p_actor_user_id uuid,
|
|
22
|
+
p_payload jsonb
|
|
23
|
+
) RETURNS jsonb
|
|
24
|
+
LANGUAGE plpgsql SECURITY DEFINER
|
|
25
|
+
SET search_path = public
|
|
26
|
+
AS $$
|
|
27
|
+
DECLARE
|
|
28
|
+
v_denial jsonb;
|
|
29
|
+
v_id uuid;
|
|
30
|
+
v_row record;
|
|
31
|
+
v_status text;
|
|
32
|
+
v_patch jsonb := '{}'::jsonb;
|
|
33
|
+
v_meta jsonb := '{}'::jsonb;
|
|
34
|
+
v_touched boolean := false;
|
|
35
|
+
BEGIN
|
|
36
|
+
BEGIN
|
|
37
|
+
v_id := (p_payload->>'lead_id')::uuid;
|
|
38
|
+
EXCEPTION WHEN OTHERS THEN
|
|
39
|
+
RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);
|
|
40
|
+
END;
|
|
41
|
+
IF v_id IS NULL THEN
|
|
42
|
+
RETURN jsonb_build_object('ok', false, 'error',
|
|
43
|
+
'lead_id is required — search the leads first and reuse the id from the result');
|
|
44
|
+
END IF;
|
|
45
|
+
|
|
46
|
+
SELECT p.id, p.name, p.email, p.phone, p.notes, p.metadata, p.kind
|
|
47
|
+
INTO v_row
|
|
48
|
+
FROM people p
|
|
49
|
+
WHERE p.id = v_id AND p.tenant_id = p_tenant_id AND p.kind = 'lead';
|
|
50
|
+
IF NOT FOUND THEN
|
|
51
|
+
RETURN jsonb_build_object('ok', false, 'error', 'unknown lead for this tenant');
|
|
52
|
+
END IF;
|
|
53
|
+
|
|
54
|
+
v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'edit');
|
|
55
|
+
IF v_denial IS NOT NULL THEN
|
|
56
|
+
RETURN jsonb_build_object('ok', false, 'denial', v_denial);
|
|
57
|
+
END IF;
|
|
58
|
+
|
|
59
|
+
-- Status is a CLOSED set. The model reached for 'proposta_enviada', which no
|
|
60
|
+
-- board column renders — an invalid status writes a lead nobody can find, so
|
|
61
|
+
-- the allowed values come back in the error for it to self-correct.
|
|
62
|
+
v_status := nullif(trim(lower(p_payload->>'status')), '');
|
|
63
|
+
IF v_status IS NOT NULL THEN
|
|
64
|
+
IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN
|
|
65
|
+
RETURN jsonb_build_object(
|
|
66
|
+
'ok', false,
|
|
67
|
+
'error', format('unknown lead status %L', v_status),
|
|
68
|
+
'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'),
|
|
69
|
+
'hint', 'A sent proposal is usually "qualified"; a closed sale is "converted".');
|
|
70
|
+
END IF;
|
|
71
|
+
v_meta := v_meta || jsonb_build_object('status', v_status);
|
|
72
|
+
v_touched := true;
|
|
73
|
+
END IF;
|
|
74
|
+
|
|
75
|
+
-- Top-level columns.
|
|
76
|
+
IF p_payload ? 'name' AND nullif(trim(p_payload->>'name'), '') IS NOT NULL THEN
|
|
77
|
+
v_patch := v_patch || jsonb_build_object('name', trim(p_payload->>'name'));
|
|
78
|
+
v_touched := true;
|
|
79
|
+
END IF;
|
|
80
|
+
IF p_payload ? 'email' THEN
|
|
81
|
+
v_patch := v_patch || jsonb_build_object('email', nullif(trim(p_payload->>'email'), ''));
|
|
82
|
+
v_touched := true;
|
|
83
|
+
END IF;
|
|
84
|
+
IF p_payload ? 'phone' THEN
|
|
85
|
+
v_patch := v_patch || jsonb_build_object('phone', nullif(trim(p_payload->>'phone'), ''));
|
|
86
|
+
v_touched := true;
|
|
87
|
+
END IF;
|
|
88
|
+
IF p_payload ? 'notes' THEN
|
|
89
|
+
v_patch := v_patch || jsonb_build_object('notes', left(p_payload->>'notes', 2000));
|
|
90
|
+
v_touched := true;
|
|
91
|
+
END IF;
|
|
92
|
+
|
|
93
|
+
-- Metadata-backed columns of v_leads.
|
|
94
|
+
IF p_payload ? 'company' THEN
|
|
95
|
+
v_meta := v_meta || jsonb_build_object('company', nullif(trim(p_payload->>'company'), ''));
|
|
96
|
+
v_touched := true;
|
|
97
|
+
END IF;
|
|
98
|
+
IF p_payload ? 'value' THEN
|
|
99
|
+
v_meta := v_meta || jsonb_build_object('value', p_payload->>'value');
|
|
100
|
+
v_touched := true;
|
|
101
|
+
END IF;
|
|
102
|
+
IF p_payload ? 'assigned_to_id' THEN
|
|
103
|
+
v_meta := v_meta || jsonb_build_object('assignedToId', nullif(trim(p_payload->>'assigned_to_id'), ''));
|
|
104
|
+
v_touched := true;
|
|
105
|
+
END IF;
|
|
106
|
+
|
|
107
|
+
IF NOT v_touched THEN
|
|
108
|
+
RETURN jsonb_build_object('ok', false, 'error',
|
|
109
|
+
'nothing to change: send status, name, email, phone, company, value, assigned_to_id or notes');
|
|
110
|
+
END IF;
|
|
111
|
+
|
|
112
|
+
UPDATE people p SET
|
|
113
|
+
name = COALESCE(v_patch->>'name', p.name),
|
|
114
|
+
email = CASE WHEN v_patch ? 'email' THEN v_patch->>'email' ELSE p.email END,
|
|
115
|
+
phone = CASE WHEN v_patch ? 'phone' THEN v_patch->>'phone' ELSE p.phone END,
|
|
116
|
+
notes = CASE WHEN v_patch ? 'notes' THEN v_patch->>'notes' ELSE p.notes END,
|
|
117
|
+
metadata = COALESCE(p.metadata, '{}'::jsonb) || v_meta,
|
|
118
|
+
updated_at = now()
|
|
119
|
+
WHERE p.id = v_id AND p.tenant_id = p_tenant_id;
|
|
120
|
+
|
|
121
|
+
INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)
|
|
122
|
+
VALUES (p_tenant_id, p_actor_user_id, 'agent.updateLead', 'lead', v_id::text,
|
|
123
|
+
jsonb_build_object('payload', p_payload,
|
|
124
|
+
'previous', jsonb_build_object(
|
|
125
|
+
'name', v_row.name,
|
|
126
|
+
'email', v_row.email,
|
|
127
|
+
'phone', v_row.phone,
|
|
128
|
+
'status', COALESCE(v_row.metadata->>'status', 'new'))));
|
|
129
|
+
|
|
130
|
+
SELECT l.id, l.name, l.email, l.phone, l.company, l.status
|
|
131
|
+
INTO v_row
|
|
132
|
+
FROM v_leads l WHERE l.id = v_id;
|
|
133
|
+
|
|
134
|
+
RETURN jsonb_build_object(
|
|
135
|
+
'ok', true,
|
|
136
|
+
'id', v_id,
|
|
137
|
+
'record', jsonb_build_object(
|
|
138
|
+
'ref', jsonb_build_object('id', v_id, 'resource', 'people',
|
|
139
|
+
'archetype', 'person:lead', 'entityKey', 'crm:leads'),
|
|
140
|
+
'name', v_row.name,
|
|
141
|
+
'email', v_row.email,
|
|
142
|
+
'phone', v_row.phone,
|
|
143
|
+
'company', v_row.company,
|
|
144
|
+
'status', v_row.status
|
|
145
|
+
)
|
|
146
|
+
);
|
|
147
|
+
END;
|
|
148
|
+
$$;
|
|
149
|
+
|
|
150
|
+
REVOKE ALL ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM public;
|
|
151
|
+
REVOKE EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM anon;
|
|
152
|
+
GRANT EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb)
|
|
153
|
+
TO authenticated, service_role;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
-- ============================================================================
|
|
2
|
+
-- plugin-crm 012: agent_crm_create_lead — abrir um lead pelo agente.
|
|
3
|
+
--
|
|
4
|
+
-- Par do 011. Sem ele, "cria um lead Noronha em stage qualified" caía no
|
|
5
|
+
-- createRecord genérico, batia no read_only de v_leads, e o modelo — vendo que
|
|
6
|
+
-- existia updateLead — chamava a tool de EDIÇÃO com `lead_id: "N/A"`. Faltando
|
|
7
|
+
-- o create, ele improvisa com o que tem.
|
|
8
|
+
--
|
|
9
|
+
-- Deduplicação é parte do contrato, não extra: e-mail ou telefone que já existem
|
|
10
|
+
-- no tenant devolvem o lead existente com `deduped: true` em vez de abrir um
|
|
11
|
+
-- segundo. Um CRM com o mesmo contato duas vezes é pior que um CRM vazio.
|
|
12
|
+
--
|
|
13
|
+
-- Feature `sales` pelo mesmo motivo do 011 — é a que existe em todo pool e a que
|
|
14
|
+
-- a tool declara.
|
|
15
|
+
-- ============================================================================
|
|
16
|
+
|
|
17
|
+
CREATE OR REPLACE FUNCTION public.agent_crm_create_lead(
|
|
18
|
+
p_tenant_id uuid,
|
|
19
|
+
p_actor_user_id uuid,
|
|
20
|
+
p_payload jsonb
|
|
21
|
+
) RETURNS jsonb
|
|
22
|
+
LANGUAGE plpgsql SECURITY DEFINER
|
|
23
|
+
SET search_path = public
|
|
24
|
+
AS $$
|
|
25
|
+
DECLARE
|
|
26
|
+
v_denial jsonb;
|
|
27
|
+
v_used int;
|
|
28
|
+
v_name text;
|
|
29
|
+
v_email text;
|
|
30
|
+
v_phone text;
|
|
31
|
+
v_status text;
|
|
32
|
+
v_meta jsonb;
|
|
33
|
+
v_existing record;
|
|
34
|
+
v_id uuid;
|
|
35
|
+
v_row record;
|
|
36
|
+
BEGIN
|
|
37
|
+
v_name := nullif(trim(p_payload->>'name'), '');
|
|
38
|
+
v_email := lower(nullif(trim(p_payload->>'email'), ''));
|
|
39
|
+
v_phone := nullif(regexp_replace(coalesce(p_payload->>'phone', ''), '\D', '', 'g'), '');
|
|
40
|
+
IF v_name IS NULL THEN
|
|
41
|
+
RETURN jsonb_build_object('ok', false, 'error', 'name is required to open a lead');
|
|
42
|
+
END IF;
|
|
43
|
+
|
|
44
|
+
v_status := coalesce(nullif(trim(lower(p_payload->>'status')), ''), 'new');
|
|
45
|
+
IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN
|
|
46
|
+
RETURN jsonb_build_object(
|
|
47
|
+
'ok', false,
|
|
48
|
+
'error', format('unknown lead status %L', v_status),
|
|
49
|
+
'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'));
|
|
50
|
+
END IF;
|
|
51
|
+
|
|
52
|
+
-- ── authorization: role → plan → leads cap ───────────────────────────────
|
|
53
|
+
SELECT count(*) INTO v_used FROM people p
|
|
54
|
+
WHERE p.tenant_id = p_tenant_id AND p.kind = 'lead';
|
|
55
|
+
v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'create', 'leads', v_used, 1);
|
|
56
|
+
IF v_denial IS NOT NULL THEN
|
|
57
|
+
RETURN jsonb_build_object('ok', false, 'denial', v_denial);
|
|
58
|
+
END IF;
|
|
59
|
+
|
|
60
|
+
-- ── dedupe before writing ────────────────────────────────────────────────
|
|
61
|
+
IF v_email IS NOT NULL OR v_phone IS NOT NULL THEN
|
|
62
|
+
SELECT p.id, p.name INTO v_existing
|
|
63
|
+
FROM people p
|
|
64
|
+
WHERE p.tenant_id = p_tenant_id
|
|
65
|
+
AND p.kind = 'lead'
|
|
66
|
+
AND (
|
|
67
|
+
(v_email IS NOT NULL AND lower(p.email) = v_email)
|
|
68
|
+
OR (v_phone IS NOT NULL AND regexp_replace(coalesce(p.phone, ''), '\D', '', 'g') = v_phone)
|
|
69
|
+
)
|
|
70
|
+
LIMIT 1;
|
|
71
|
+
IF FOUND THEN
|
|
72
|
+
RETURN jsonb_build_object(
|
|
73
|
+
'ok', true,
|
|
74
|
+
'deduped', true,
|
|
75
|
+
'id', v_existing.id,
|
|
76
|
+
'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),
|
|
77
|
+
'record', jsonb_build_object(
|
|
78
|
+
'ref', jsonb_build_object('id', v_existing.id, 'resource', 'people',
|
|
79
|
+
'archetype', 'person:lead', 'entityKey', 'crm:leads'),
|
|
80
|
+
'name', v_existing.name));
|
|
81
|
+
END IF;
|
|
82
|
+
END IF;
|
|
83
|
+
|
|
84
|
+
v_meta := jsonb_strip_nulls(jsonb_build_object(
|
|
85
|
+
'status', v_status,
|
|
86
|
+
'source', 'agent',
|
|
87
|
+
'company', nullif(trim(p_payload->>'company'), ''),
|
|
88
|
+
'value', nullif(trim(p_payload->>'value'), ''),
|
|
89
|
+
'sourceName', nullif(trim(p_payload->>'source_name'), ''),
|
|
90
|
+
'assignedToId', nullif(trim(p_payload->>'assigned_to_id'), '')
|
|
91
|
+
));
|
|
92
|
+
|
|
93
|
+
INSERT INTO people (tenant_id, kind, name, email, phone, notes, is_active, metadata)
|
|
94
|
+
VALUES (p_tenant_id, 'lead', v_name,
|
|
95
|
+
nullif(trim(p_payload->>'email'), ''),
|
|
96
|
+
nullif(trim(p_payload->>'phone'), ''),
|
|
97
|
+
left(p_payload->>'notes', 2000),
|
|
98
|
+
true, v_meta)
|
|
99
|
+
RETURNING id INTO v_id;
|
|
100
|
+
|
|
101
|
+
INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)
|
|
102
|
+
VALUES (p_tenant_id, p_actor_user_id, 'agent.createLead', 'lead', v_id::text,
|
|
103
|
+
jsonb_build_object('payload', p_payload));
|
|
104
|
+
|
|
105
|
+
SELECT l.id, l.name, l.email, l.phone, l.company, l.status
|
|
106
|
+
INTO v_row
|
|
107
|
+
FROM v_leads l WHERE l.id = v_id;
|
|
108
|
+
|
|
109
|
+
RETURN jsonb_build_object(
|
|
110
|
+
'ok', true,
|
|
111
|
+
'id', v_id,
|
|
112
|
+
'record', jsonb_build_object(
|
|
113
|
+
'ref', jsonb_build_object('id', v_id, 'resource', 'people',
|
|
114
|
+
'archetype', 'person:lead', 'entityKey', 'crm:leads'),
|
|
115
|
+
'name', v_row.name,
|
|
116
|
+
'email', v_row.email,
|
|
117
|
+
'phone', v_row.phone,
|
|
118
|
+
'company', v_row.company,
|
|
119
|
+
'status', v_row.status
|
|
120
|
+
)
|
|
121
|
+
);
|
|
122
|
+
END;
|
|
123
|
+
$$;
|
|
124
|
+
|
|
125
|
+
REVOKE ALL ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM public;
|
|
126
|
+
REVOKE EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM anon;
|
|
127
|
+
GRANT EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb)
|
|
128
|
+
TO authenticated, service_role;
|