@fayz-ai/plugin-crm 0.9.0-next.1 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/components/AutomationBolt.d.ts +22 -0
- package/dist/components/AutomationBolt.d.ts.map +1 -0
- package/dist/{CrmContext.d.ts → context.d.ts} +4 -2
- package/dist/context.d.ts.map +1 -0
- package/dist/data/registries.d.ts.map +1 -0
- package/dist/index.d.ts +16 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +573 -488
- package/dist/index.js.map +1 -1
- package/dist/{cascade.d.ts → lib/cascade.d.ts} +1 -1
- package/dist/lib/cascade.d.ts.map +1 -0
- package/dist/lib/message-events.d.ts +13 -0
- package/dist/lib/message-events.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/public/context.d.ts +1 -1
- package/dist/public/context.d.ts.map +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
- package/dist/public/{data.supabase.d.ts → data/supabase.d.ts} +2 -2
- package/dist/public/data/supabase.d.ts.map +1 -0
- package/dist/public/index.d.ts +6 -6
- package/dist/public/index.d.ts.map +1 -1
- package/dist/public/index.js +2 -2
- package/dist/public/index.js.map +1 -1
- package/dist/public/{inbox.d.ts → lib/inbox.d.ts} +1 -1
- package/dist/public/lib/inbox.d.ts.map +1 -0
- package/dist/public/{uploads.d.ts → lib/uploads.d.ts} +1 -1
- package/dist/public/lib/uploads.d.ts.map +1 -0
- package/dist/store.d.ts +9 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/views/ActivityListView.d.ts.map +1 -1
- package/dist/{CrmPage.d.ts → views/CrmPage.d.ts} +3 -3
- package/dist/views/CrmPage.d.ts.map +1 -0
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadListView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts +3 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/dist/views/QuoteDetailView.d.ts.map +1 -1
- package/dist/views/QuoteFormView.d.ts.map +1 -1
- package/dist/views/QuoteListView.d.ts.map +1 -1
- package/dist/views/dashboardWidgets.d.ts +1 -1
- package/dist/views/dashboardWidgets.d.ts.map +1 -1
- package/package.json +6 -10
- package/dist/CrmContext.d.ts.map +0 -1
- package/dist/CrmPage.d.ts.map +0 -1
- package/dist/cascade.d.ts.map +0 -1
- package/dist/public/data.supabase.d.ts.map +0 -1
- package/dist/public/inbox.d.ts.map +0 -1
- package/dist/public/uploads.d.ts.map +0 -1
- package/dist/registries.d.ts.map +0 -1
- package/src/CrmContext.tsx +0 -30
- package/src/CrmPage.tsx +0 -150
- package/src/README.md +0 -97
- package/src/cascade.ts +0 -26
- package/src/components/BoardFilters.tsx +0 -190
- package/src/components/CrmGeneralSettings.tsx +0 -56
- package/src/components/CrmOnboarding.tsx +0 -52
- package/src/components/LeadAttachments.tsx +0 -140
- package/src/components/PipelineSettings.tsx +0 -45
- package/src/components/QuoteStatusDropdown.tsx +0 -226
- package/src/components/TagChips.tsx +0 -80
- package/src/data/index.ts +0 -2
- package/src/data/mock.ts +0 -559
- package/src/data/supabase.ts +0 -928
- package/src/data/tables.ts +0 -11
- package/src/data/types.ts +0 -61
- package/src/index.ts +0 -429
- package/src/lib/access.ts +0 -11
- package/src/lib/form-answers.tsx +0 -80
- package/src/lib/relative-time.ts +0 -84
- package/src/lib/tenant.ts +0 -4
- package/src/locales/en.ts +0 -307
- package/src/locales/index.ts +0 -7
- package/src/locales/pt-BR.ts +0 -307
- package/src/migrations/000_plg_rename.sql +0 -28
- package/src/migrations/001_crm_base.sql +0 -73
- package/src/migrations/002_activities.sql +0 -33
- package/src/migrations/003_crm_views_rls.sql +0 -69
- package/src/migrations/004_seed_default_pipeline.sql +0 -31
- package/src/migrations/005_public_lead.sql +0 -189
- package/src/migrations/006_lead_enters_pipeline.sql +0 -265
- package/src/migrations/007_activity_log.sql +0 -55
- package/src/migrations/008_view_field_aliases.sql +0 -43
- package/src/migrations/009_deal_archived_status.sql +0 -30
- package/src/migrations/010_quote_archived_status.sql +0 -40
- package/src/migrations/011_agent_rpc_update_lead.sql +0 -153
- package/src/migrations/012_agent_rpc_create_lead.sql +0 -128
- package/src/migrations/013_tag_slugs.sql +0 -177
- package/src/migrations/014_public_lead_tags.sql +0 -172
- package/src/migrations/015_lead_attachments.sql +0 -357
- package/src/migrations/016_public_lead_activity.sql +0 -123
- package/src/migrations/index.ts +0 -2023
- package/src/public/context.tsx +0 -150
- package/src/public/createPublicFormsPlugin.ts +0 -282
- package/src/public/data.supabase.ts +0 -92
- package/src/public/inbox.ts +0 -143
- package/src/public/index.ts +0 -51
- package/src/public/types.ts +0 -173
- package/src/public/uploads.ts +0 -205
- package/src/registries.ts +0 -162
- package/src/schema/index.ts +0 -104
- package/src/store.ts +0 -472
- package/src/types.ts +0 -337
- package/src/views/ActivityListView.tsx +0 -264
- package/src/views/DashboardView.tsx +0 -12
- package/src/views/DealSidebar.tsx +0 -482
- package/src/views/LeadDetailView.tsx +0 -378
- package/src/views/LeadFormView.tsx +0 -66
- package/src/views/LeadListView.tsx +0 -100
- package/src/views/PipelineView.tsx +0 -446
- package/src/views/QuoteDetailView.tsx +0 -412
- package/src/views/QuoteFormView.tsx +0 -494
- package/src/views/QuoteListView.tsx +0 -115
- package/src/views/dashboardWidgets.tsx +0 -248
- /package/dist/{registries.d.ts → data/registries.d.ts} +0 -0
|
@@ -1,265 +0,0 @@
|
|
|
1
|
-
-- plugin-crm 006: every lead lands on the board, guaranteed by the database.
|
|
2
|
-
--
|
|
3
|
-
-- The bug this closes: the leads LIST reads v_leads (public.people WHERE
|
|
4
|
-
-- kind='lead') while the PIPELINE reads v_deals (public.orders WHERE kind='deal'
|
|
5
|
-
-- + plg_crm_deal_extensions). A lead is a person; a card is an order. Nothing
|
|
6
|
-
-- created the second from the first — create_public_lead never touches orders —
|
|
7
|
-
-- so form leads landed in the list and the board stayed empty. Forever, not
|
|
8
|
-
-- intermittently. plg_crm_deal_extensions.lead_id has existed since 001 and was
|
|
9
|
-
-- NULL on every row in the pool: the link was designed and never wired.
|
|
10
|
-
--
|
|
11
|
-
-- Why a TRIGGER and not application code: a lead reaches people through at
|
|
12
|
-
-- least four independent writers today — the anon RPC create_public_lead, the
|
|
13
|
-
-- agent's generic createRecord, CSV import, and the CRM's own form. Putting the
|
|
14
|
-
-- board insert in any one of them leaves the other three silently broken, and
|
|
15
|
-
-- the next writer added leaves a fifth. Here it cannot be forgotten or bypassed,
|
|
16
|
-
-- including by a direct SQL insert.
|
|
17
|
-
--
|
|
18
|
-
-- Idempotent by construction: a UNIQUE index on deal_extensions.lead_id means a
|
|
19
|
-
-- second attempt for the same lead is a no-op, so re-running the backfill or
|
|
20
|
-
-- replaying the migration cannot double-card anyone.
|
|
21
|
-
|
|
22
|
-
-- ---------------------------------------------------------------------------
|
|
23
|
-
-- 1. One card per lead, enforced by the database rather than by the trigger
|
|
24
|
-
-- remembering to check.
|
|
25
|
-
-- ---------------------------------------------------------------------------
|
|
26
|
-
CREATE UNIQUE INDEX IF NOT EXISTS plg_crm_deal_extensions_lead_idx
|
|
27
|
-
ON public.plg_crm_deal_extensions (lead_id) WHERE lead_id IS NOT NULL;
|
|
28
|
-
|
|
29
|
-
-- ---------------------------------------------------------------------------
|
|
30
|
-
-- 1b. The default board, as a callable function instead of 004's one-shot loop.
|
|
31
|
-
-- Same pipeline and stages 004 seeds; idempotent per tenant.
|
|
32
|
-
-- ---------------------------------------------------------------------------
|
|
33
|
-
CREATE OR REPLACE FUNCTION public.crm_seed_default_pipeline(p_tenant_id uuid)
|
|
34
|
-
RETURNS uuid
|
|
35
|
-
LANGUAGE plpgsql
|
|
36
|
-
SECURITY DEFINER
|
|
37
|
-
SET search_path TO 'public'
|
|
38
|
-
AS $$
|
|
39
|
-
DECLARE
|
|
40
|
-
v_pipeline uuid;
|
|
41
|
-
BEGIN
|
|
42
|
-
SELECT id INTO v_pipeline
|
|
43
|
-
FROM public.plg_crm_pipelines
|
|
44
|
-
WHERE tenant_id = p_tenant_id
|
|
45
|
-
ORDER BY is_default DESC, created_at ASC
|
|
46
|
-
LIMIT 1;
|
|
47
|
-
IF v_pipeline IS NOT NULL THEN
|
|
48
|
-
RETURN v_pipeline;
|
|
49
|
-
END IF;
|
|
50
|
-
|
|
51
|
-
INSERT INTO public.plg_crm_pipelines (tenant_id, name, is_default, is_active)
|
|
52
|
-
VALUES (p_tenant_id, 'Sales Pipeline', true, true)
|
|
53
|
-
RETURNING id INTO v_pipeline;
|
|
54
|
-
|
|
55
|
-
INSERT INTO public.plg_crm_pipeline_stages
|
|
56
|
-
(tenant_id, pipeline_id, name, "order", color, probability, is_won, is_lost)
|
|
57
|
-
VALUES
|
|
58
|
-
(p_tenant_id, v_pipeline, 'New', 0, '#6366f1', 10, false, false),
|
|
59
|
-
(p_tenant_id, v_pipeline, 'Contacted', 1, '#3b82f6', 25, false, false),
|
|
60
|
-
(p_tenant_id, v_pipeline, 'Qualified', 2, '#f59e0b', 50, false, false),
|
|
61
|
-
(p_tenant_id, v_pipeline, 'Proposal', 3, '#f97316', 75, false, false),
|
|
62
|
-
(p_tenant_id, v_pipeline, 'Negotiation', 4, '#8b5cf6', 90, false, false),
|
|
63
|
-
(p_tenant_id, v_pipeline, 'Won', 5, '#22c55e', 100, true, false),
|
|
64
|
-
(p_tenant_id, v_pipeline, 'Lost', 6, '#ef4444', 0, false, true);
|
|
65
|
-
|
|
66
|
-
RETURN v_pipeline;
|
|
67
|
-
END;
|
|
68
|
-
$$;
|
|
69
|
-
|
|
70
|
-
-- ---------------------------------------------------------------------------
|
|
71
|
-
-- 2. The lead → card projection, shared by the trigger and the backfill so the
|
|
72
|
-
-- two can never drift apart.
|
|
73
|
-
--
|
|
74
|
-
-- Placement is the tenant's DEFAULT pipeline, lowest `order` stage that is
|
|
75
|
-
-- neither won nor lost (the "New" column). A tenant with no pipeline yet is
|
|
76
|
-
-- skipped rather than failing: the lead must still be captured — losing a
|
|
77
|
-
-- real customer enquiry because a board was not configured would be a far
|
|
78
|
-
-- worse bug than a missing card. 004 seeds a default pipeline for every
|
|
79
|
-
-- tenant, so this is the empty-tenant edge, not the normal path.
|
|
80
|
-
-- ---------------------------------------------------------------------------
|
|
81
|
-
CREATE OR REPLACE FUNCTION public.crm_place_lead_on_board(p_lead_id uuid)
|
|
82
|
-
RETURNS uuid
|
|
83
|
-
LANGUAGE plpgsql
|
|
84
|
-
SECURITY DEFINER
|
|
85
|
-
SET search_path TO 'public'
|
|
86
|
-
AS $$
|
|
87
|
-
DECLARE
|
|
88
|
-
v_lead public.people%ROWTYPE;
|
|
89
|
-
v_pipeline uuid;
|
|
90
|
-
v_stage uuid;
|
|
91
|
-
v_prob numeric;
|
|
92
|
-
v_order_id uuid;
|
|
93
|
-
BEGIN
|
|
94
|
-
SELECT * INTO v_lead FROM public.people WHERE id = p_lead_id;
|
|
95
|
-
IF NOT FOUND OR v_lead.kind <> 'lead' THEN
|
|
96
|
-
RETURN NULL;
|
|
97
|
-
END IF;
|
|
98
|
-
|
|
99
|
-
-- Already on the board (re-run, or a card made by hand): nothing to do.
|
|
100
|
-
IF EXISTS (SELECT 1 FROM public.plg_crm_deal_extensions WHERE lead_id = p_lead_id) THEN
|
|
101
|
-
RETURN NULL;
|
|
102
|
-
END IF;
|
|
103
|
-
|
|
104
|
-
SELECT id INTO v_pipeline
|
|
105
|
-
FROM public.plg_crm_pipelines
|
|
106
|
-
WHERE tenant_id = v_lead.tenant_id
|
|
107
|
-
ORDER BY is_default DESC, created_at ASC
|
|
108
|
-
LIMIT 1;
|
|
109
|
-
|
|
110
|
-
-- No board yet? Build the default one and carry on.
|
|
111
|
-
--
|
|
112
|
-
-- 004 seeds the default pipeline as a ONE-SHOT backfill with no trigger, so
|
|
113
|
-
-- every tenant created after it ran has none — 3 of the 8 tenants in this pool
|
|
114
|
-
-- were in that state. Their board renders blank no matter how many leads
|
|
115
|
-
-- arrive, and it would punch a hole straight through the guarantee this
|
|
116
|
-
-- migration exists to make: a lead in such a tenant would be captured and then
|
|
117
|
-
-- silently skipped for want of a stage to sit in.
|
|
118
|
-
--
|
|
119
|
-
-- Seeded here, on demand, rather than from a trigger on public.tenants: the
|
|
120
|
-
-- board is the CRM's own concern, and a plugin has no business attaching
|
|
121
|
-
-- itself to tenant creation in a core table.
|
|
122
|
-
IF v_pipeline IS NULL THEN
|
|
123
|
-
v_pipeline := public.crm_seed_default_pipeline(v_lead.tenant_id);
|
|
124
|
-
END IF;
|
|
125
|
-
IF v_pipeline IS NULL THEN
|
|
126
|
-
RETURN NULL;
|
|
127
|
-
END IF;
|
|
128
|
-
|
|
129
|
-
SELECT id, probability INTO v_stage, v_prob
|
|
130
|
-
FROM public.plg_crm_pipeline_stages
|
|
131
|
-
WHERE pipeline_id = v_pipeline AND NOT is_won AND NOT is_lost
|
|
132
|
-
ORDER BY "order" ASC
|
|
133
|
-
LIMIT 1;
|
|
134
|
-
IF v_stage IS NULL THEN
|
|
135
|
-
RETURN NULL;
|
|
136
|
-
END IF;
|
|
137
|
-
|
|
138
|
-
-- The card's money value comes from the lead when the form captured one;
|
|
139
|
-
-- 0 otherwise. `notes` is the deal TITLE (v_deals maps o.notes -> title), so
|
|
140
|
-
-- it carries the lead's name, not the lead's message.
|
|
141
|
-
INSERT INTO public.orders (
|
|
142
|
-
tenant_id, kind, status, total, currency, party_id, notes, tags, metadata
|
|
143
|
-
) VALUES (
|
|
144
|
-
v_lead.tenant_id,
|
|
145
|
-
'deal',
|
|
146
|
-
'open',
|
|
147
|
-
COALESCE((v_lead.metadata ->> 'value')::numeric, 0),
|
|
148
|
-
'BRL',
|
|
149
|
-
v_lead.id,
|
|
150
|
-
v_lead.name,
|
|
151
|
-
COALESCE(v_lead.tags, '{}'),
|
|
152
|
-
jsonb_build_object(
|
|
153
|
-
'contactName', v_lead.name,
|
|
154
|
-
'createdFrom', 'lead',
|
|
155
|
-
-- Which form produced it, when there was one: lets the board be filtered
|
|
156
|
-
-- by campaign without re-joining people.
|
|
157
|
-
'formId', v_lead.metadata ->> 'formId'
|
|
158
|
-
)
|
|
159
|
-
)
|
|
160
|
-
RETURNING id INTO v_order_id;
|
|
161
|
-
|
|
162
|
-
INSERT INTO public.plg_crm_deal_extensions (
|
|
163
|
-
order_id, tenant_id, pipeline_id, stage_id, probability, lead_id
|
|
164
|
-
) VALUES (
|
|
165
|
-
v_order_id, v_lead.tenant_id, v_pipeline, v_stage, COALESCE(v_prob, 0), v_lead.id
|
|
166
|
-
)
|
|
167
|
-
-- Concurrent inserts for the same lead: the unique index above turns the
|
|
168
|
-
-- loser into a no-op instead of an error the trigger would propagate back to
|
|
169
|
-
-- the form submission.
|
|
170
|
-
ON CONFLICT (lead_id) WHERE lead_id IS NOT NULL DO NOTHING;
|
|
171
|
-
|
|
172
|
-
RETURN v_order_id;
|
|
173
|
-
END;
|
|
174
|
-
$$;
|
|
175
|
-
|
|
176
|
-
COMMENT ON FUNCTION public.crm_place_lead_on_board(uuid) IS
|
|
177
|
-
'Projects a people row of kind=lead onto the tenant default pipeline as an orders(kind=deal) + deal_extension. Idempotent per lead.';
|
|
178
|
-
|
|
179
|
-
-- ---------------------------------------------------------------------------
|
|
180
|
-
-- 3. The trigger. AFTER INSERT so a failure here can never roll back the lead
|
|
181
|
-
-- itself, and EXCEPTION-guarded for the same reason: capturing the enquiry
|
|
182
|
-
-- is the part that must not fail. A board that missed a card is recoverable
|
|
183
|
-
-- (step 4 re-runs); a lost lead is not.
|
|
184
|
-
-- ---------------------------------------------------------------------------
|
|
185
|
-
CREATE OR REPLACE FUNCTION public.crm_lead_to_board()
|
|
186
|
-
RETURNS trigger
|
|
187
|
-
LANGUAGE plpgsql
|
|
188
|
-
SECURITY DEFINER
|
|
189
|
-
SET search_path TO 'public'
|
|
190
|
-
AS $$
|
|
191
|
-
BEGIN
|
|
192
|
-
IF NEW.kind = 'lead' THEN
|
|
193
|
-
BEGIN
|
|
194
|
-
PERFORM public.crm_place_lead_on_board(NEW.id);
|
|
195
|
-
EXCEPTION WHEN OTHERS THEN
|
|
196
|
-
RAISE WARNING 'crm_lead_to_board: lead % captured but not placed on the board: %', NEW.id, SQLERRM;
|
|
197
|
-
END;
|
|
198
|
-
END IF;
|
|
199
|
-
RETURN NULL;
|
|
200
|
-
END;
|
|
201
|
-
$$;
|
|
202
|
-
|
|
203
|
-
DROP TRIGGER IF EXISTS people_lead_to_board ON public.people;
|
|
204
|
-
CREATE TRIGGER people_lead_to_board
|
|
205
|
-
AFTER INSERT ON public.people
|
|
206
|
-
FOR EACH ROW
|
|
207
|
-
WHEN (NEW.kind = 'lead')
|
|
208
|
-
EXECUTE FUNCTION public.crm_lead_to_board();
|
|
209
|
-
|
|
210
|
-
-- A person PROMOTED to lead later (kind edited from contact/customer) must land
|
|
211
|
-
-- on the board too — otherwise the guarantee holds only for the insert path.
|
|
212
|
-
DROP TRIGGER IF EXISTS people_promoted_to_lead_to_board ON public.people;
|
|
213
|
-
CREATE TRIGGER people_promoted_to_lead_to_board
|
|
214
|
-
AFTER UPDATE OF kind ON public.people
|
|
215
|
-
FOR EACH ROW
|
|
216
|
-
WHEN (NEW.kind = 'lead' AND OLD.kind IS DISTINCT FROM 'lead')
|
|
217
|
-
EXECUTE FUNCTION public.crm_lead_to_board();
|
|
218
|
-
|
|
219
|
-
-- ---------------------------------------------------------------------------
|
|
220
|
-
-- 4. Realtime, so an open board updates itself instead of waiting for a reload.
|
|
221
|
-
--
|
|
222
|
-
-- The trigger above writes the card with no client involved, so the browser
|
|
223
|
-
-- has nothing to react to unless the change is streamed. The pool's
|
|
224
|
-
-- supabase_realtime publication was EMPTY — every .subscribe() in the SDK
|
|
225
|
-
-- was silently receiving nothing — so the table is added explicitly rather
|
|
226
|
-
-- than assumed. FOR EACH ROW replica identity stays default (PK): the
|
|
227
|
-
-- handler refetches the board, so the payload's contents are irrelevant.
|
|
228
|
-
-- ---------------------------------------------------------------------------
|
|
229
|
-
DO $$
|
|
230
|
-
BEGIN
|
|
231
|
-
IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN
|
|
232
|
-
CREATE PUBLICATION supabase_realtime;
|
|
233
|
-
END IF;
|
|
234
|
-
IF NOT EXISTS (
|
|
235
|
-
SELECT 1 FROM pg_publication_tables
|
|
236
|
-
WHERE pubname = 'supabase_realtime'
|
|
237
|
-
AND schemaname = 'public'
|
|
238
|
-
AND tablename = 'plg_crm_deal_extensions'
|
|
239
|
-
) THEN
|
|
240
|
-
ALTER PUBLICATION supabase_realtime ADD TABLE public.plg_crm_deal_extensions;
|
|
241
|
-
END IF;
|
|
242
|
-
END $$;
|
|
243
|
-
|
|
244
|
-
-- ---------------------------------------------------------------------------
|
|
245
|
-
-- 5. Backfill every lead that predates the trigger. Idempotent via step 2's
|
|
246
|
-
-- own guard, so replaying this migration adds nothing.
|
|
247
|
-
-- ---------------------------------------------------------------------------
|
|
248
|
-
DO $$
|
|
249
|
-
DECLARE
|
|
250
|
-
r record;
|
|
251
|
-
n int := 0;
|
|
252
|
-
BEGIN
|
|
253
|
-
FOR r IN
|
|
254
|
-
SELECT p.id
|
|
255
|
-
FROM public.people p
|
|
256
|
-
LEFT JOIN public.plg_crm_deal_extensions de ON de.lead_id = p.id
|
|
257
|
-
WHERE p.kind = 'lead' AND de.id IS NULL
|
|
258
|
-
ORDER BY p.created_at
|
|
259
|
-
LOOP
|
|
260
|
-
IF public.crm_place_lead_on_board(r.id) IS NOT NULL THEN
|
|
261
|
-
n := n + 1;
|
|
262
|
-
END IF;
|
|
263
|
-
END LOOP;
|
|
264
|
-
RAISE NOTICE 'crm 006 backfill: % lead(s) placed on the board', n;
|
|
265
|
-
END $$;
|
|
@@ -1,55 +0,0 @@
|
|
|
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
|
-
);
|
|
@@ -1,43 +0,0 @@
|
|
|
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;
|
|
@@ -1,30 +0,0 @@
|
|
|
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 $$;
|
|
@@ -1,40 +0,0 @@
|
|
|
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;
|
|
@@ -1,153 +0,0 @@
|
|
|
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;
|