@fayz-ai/plugin-crm 0.8.3 → 0.8.4
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/QuoteStatusDropdown.d.ts.map +1 -1
- 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 +9 -1
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.cjs +698 -103
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +701 -106
- 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 +5 -1
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/public/index.cjs +1 -1
- package/dist/public/index.cjs.map +1 -1
- package/dist/public/index.js +2 -2
- package/dist/public/index.js.map +1 -1
- package/dist/registries.d.ts +11 -0
- package/dist/registries.d.ts.map +1 -1
- package/dist/store.d.ts +5 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/types.d.ts +14 -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 +5 -5
- package/src/CrmPage.tsx +1 -1
- package/src/cascade.ts +2 -0
- package/src/components/QuoteStatusDropdown.tsx +15 -3
- package/src/data/mock.ts +110 -4
- package/src/data/supabase.ts +186 -8
- package/src/data/types.ts +9 -1
- package/src/index.ts +85 -3
- package/src/lib/access.ts +11 -0
- package/src/locales/en.ts +4 -0
- package/src/locales/pt-BR.ts +9 -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/index.ts +191 -3
- package/src/public/data.supabase.ts +2 -2
- package/src/registries.ts +32 -8
- package/src/store.ts +76 -0
- package/src/types.ts +19 -2
- package/src/views/ActivityListView.tsx +79 -11
- package/src/views/DealSidebar.tsx +39 -33
- package/src/views/LeadDetailView.tsx +29 -10
- package/src/views/PipelineView.tsx +22 -4
- package/src/views/QuoteDetailView.tsx +7 -3
- package/src/views/QuoteListView.tsx +26 -12
|
@@ -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;
|
package/src/migrations/index.ts
CHANGED
|
@@ -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 — 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
|
-
|
|
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
|
-
|
|
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,182 @@ 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
|
+
|
|
699
883
|
export const MIGRATIONS: Array<{ id: string; sql: string }> = [
|
|
700
884
|
{ id: "000_plg_rename", sql: MIGRATION_000_PLG_RENAME },
|
|
701
885
|
{ id: "001_crm_base", sql: MIGRATION_001_CRM_BASE },
|
|
@@ -704,4 +888,8 @@ export const MIGRATIONS: Array<{ id: string; sql: string }> = [
|
|
|
704
888
|
{ id: "004_seed_default_pipeline", sql: MIGRATION_004_SEED_DEFAULT_PIPELINE },
|
|
705
889
|
{ id: "005_public_lead", sql: MIGRATION_005_PUBLIC_LEAD },
|
|
706
890
|
{ id: "006_lead_enters_pipeline", sql: MIGRATION_006_LEAD_ENTERS_PIPELINE },
|
|
891
|
+
{ id: "007_activity_log", sql: MIGRATION_007_ACTIVITY_LOG },
|
|
892
|
+
{ id: "008_view_field_aliases", sql: MIGRATION_008_VIEW_FIELD_ALIASES },
|
|
893
|
+
{ id: "009_deal_archived_status", sql: MIGRATION_009_DEAL_ARCHIVED_STATUS },
|
|
894
|
+
{ id: "010_quote_archived_status", sql: MIGRATION_010_QUOTE_ARCHIVED_STATUS },
|
|
707
895
|
]
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// The RPC never reads back — a form writes, it does not query the CRM.
|
|
12
12
|
// ---------------------------------------------------------------------------
|
|
13
13
|
|
|
14
|
-
import {
|
|
14
|
+
import { getSupabaseClientOptional } from '@fayz-ai/core'
|
|
15
15
|
import { LeadSubmitError, type PublicLeadDataProvider } from './types'
|
|
16
16
|
|
|
17
17
|
export interface SupabasePublicLeadOptions {
|
|
@@ -24,7 +24,7 @@ interface SupabaseLikeClient {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
function getClient(): SupabaseLikeClient | null {
|
|
27
|
-
return
|
|
27
|
+
return getSupabaseClientOptional() as SupabaseLikeClient | null
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */
|
package/src/registries.ts
CHANGED
|
@@ -62,11 +62,21 @@ const activityTypeEntity: EntityDef = {
|
|
|
62
62
|
defaultSort: 'name',
|
|
63
63
|
fields: [
|
|
64
64
|
{ key: 'name', label: 'Name', type: 'text', required: true, showInTable: true },
|
|
65
|
-
{ key: '
|
|
65
|
+
{ key: 'icon', label: 'Icon', type: 'text', showInTable: true },
|
|
66
|
+
{ key: 'isActive', label: 'Active', type: 'boolean', showInTable: true, defaultValue: true, inlineToggle: true },
|
|
66
67
|
],
|
|
67
68
|
data: { table: T.activityTypes, tenantScoped: true },
|
|
68
69
|
}
|
|
69
70
|
|
|
71
|
+
export const DEFAULT_ACTIVITY_TYPES: Array<{ value: string; label: string; icon?: string }> = [
|
|
72
|
+
{ value: 'call', label: 'Call', icon: 'Phone' },
|
|
73
|
+
{ value: 'email', label: 'Email', icon: 'Mail' },
|
|
74
|
+
{ value: 'meeting', label: 'Meeting', icon: 'Users' },
|
|
75
|
+
{ value: 'note', label: 'Note', icon: 'FileText' },
|
|
76
|
+
{ value: 'task', label: 'Task', icon: 'CheckSquare' },
|
|
77
|
+
{ value: 'whatsapp', label: 'WhatsApp', icon: 'MessageCircle' },
|
|
78
|
+
]
|
|
79
|
+
|
|
70
80
|
export const crmRegistries: PluginRegistryDef[] = [
|
|
71
81
|
{
|
|
72
82
|
id: 'stages',
|
|
@@ -116,14 +126,28 @@ export const crmRegistries: PluginRegistryDef[] = [
|
|
|
116
126
|
icon: 'MessageCircle',
|
|
117
127
|
description: 'Types of activities and interactions',
|
|
118
128
|
display: 'table',
|
|
119
|
-
|
|
129
|
+
// Tenant-editable (the provider lazily seeds the app's set per tenant);
|
|
130
|
+
// system timeline events (lead_created, stage_changed…) are product-defined
|
|
131
|
+
// and never appear here.
|
|
120
132
|
seedData: [
|
|
121
|
-
{ id:
|
|
122
|
-
{ id: 'at-email', name: 'Email', isActive: true },
|
|
123
|
-
{ id: 'at-meeting', name: 'Meeting', isActive: true },
|
|
124
|
-
{ id: 'at-note', name: 'Note', isActive: true },
|
|
125
|
-
{ id: 'at-task', name: 'Task', isActive: true },
|
|
126
|
-
{ id: 'at-whatsapp', name: 'WhatsApp', isActive: true },
|
|
133
|
+
...DEFAULT_ACTIVITY_TYPES.map((t) => ({ id: `at-${t.value}`, name: t.label, icon: t.icon, isActive: true })),
|
|
127
134
|
],
|
|
128
135
|
},
|
|
129
136
|
]
|
|
137
|
+
|
|
138
|
+
/** Registries with the app's activity-type set replacing the default seed. */
|
|
139
|
+
export function buildCrmRegistries(
|
|
140
|
+
activityTypes?: Array<{ value: string; label: string; icon?: string }>,
|
|
141
|
+
): PluginRegistryDef[] {
|
|
142
|
+
if (!activityTypes?.length) return crmRegistries
|
|
143
|
+
return crmRegistries.map((registry) =>
|
|
144
|
+
registry.id === 'activity-types'
|
|
145
|
+
? {
|
|
146
|
+
...registry,
|
|
147
|
+
seedData: [
|
|
148
|
+
...activityTypes.map((t) => ({ id: `at-${t.value}`, name: t.label, icon: t.icon, isActive: true })),
|
|
149
|
+
],
|
|
150
|
+
}
|
|
151
|
+
: registry,
|
|
152
|
+
)
|
|
153
|
+
}
|
package/src/store.ts
CHANGED
|
@@ -36,6 +36,8 @@ export interface CrmUIState {
|
|
|
36
36
|
fetchDeals(query: DealQuery): Promise<void>
|
|
37
37
|
fetchDealsByStage(pipelineId: string): Promise<void>
|
|
38
38
|
fetchActivities(query: ActivityQuery): Promise<void>
|
|
39
|
+
/** Re-fetch the timeline with the last query — writes append system events. */
|
|
40
|
+
refreshActivities(): Promise<void>
|
|
39
41
|
fetchQuotes(query: QuoteQuery): Promise<void>
|
|
40
42
|
createLead(input: CreateLeadInput): Promise<Lead>
|
|
41
43
|
createDeal(input: CreateDealInput): Promise<Deal>
|
|
@@ -47,9 +49,13 @@ export interface CrmUIState {
|
|
|
47
49
|
rejectQuote(id: string, reason: string): Promise<Quote>
|
|
48
50
|
expireQuote(id: string): Promise<Quote>
|
|
49
51
|
moveDealToStage(dealId: string, stageId: string): Promise<void>
|
|
52
|
+
archiveDeal(dealId: string): Promise<void>
|
|
53
|
+
archiveLead(leadId: string): Promise<void>
|
|
54
|
+
archiveQuote(quoteId: string): Promise<void>
|
|
50
55
|
}
|
|
51
56
|
|
|
52
57
|
export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState> {
|
|
58
|
+
let lastActivitiesQuery: ActivityQuery = {}
|
|
53
59
|
return createStore<CrmUIState>((set, get) => ({
|
|
54
60
|
pipelines: [], stages: [],
|
|
55
61
|
leads: [], leadsTotal: 0, leadsLoading: false,
|
|
@@ -108,6 +114,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
108
114
|
},
|
|
109
115
|
|
|
110
116
|
async fetchActivities(query) {
|
|
117
|
+
lastActivitiesQuery = query
|
|
111
118
|
return dedup('crm:activities:' + JSON.stringify(query), async () => {
|
|
112
119
|
set({ activitiesLoading: true })
|
|
113
120
|
const result = await provider.getActivities(query)
|
|
@@ -115,6 +122,13 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
115
122
|
})
|
|
116
123
|
},
|
|
117
124
|
|
|
125
|
+
async refreshActivities() {
|
|
126
|
+
try {
|
|
127
|
+
const result = await provider.getActivities(lastActivitiesQuery)
|
|
128
|
+
set({ activities: result.data, activitiesTotal: result.total })
|
|
129
|
+
} catch { /* timeline refresh is best-effort */ }
|
|
130
|
+
},
|
|
131
|
+
|
|
118
132
|
async fetchQuotes(query) {
|
|
119
133
|
return dedup('crm:quotes:' + JSON.stringify(query), async () => {
|
|
120
134
|
set({ quotesLoading: true })
|
|
@@ -155,6 +169,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
155
169
|
|
|
156
170
|
const summary = await provider.getSummary()
|
|
157
171
|
set({ summary })
|
|
172
|
+
void get().refreshActivities()
|
|
158
173
|
toast.success('Lead captured')
|
|
159
174
|
return lead
|
|
160
175
|
} catch (err: any) {
|
|
@@ -168,6 +183,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
168
183
|
const deal = await provider.createDeal(input)
|
|
169
184
|
const [summary] = await Promise.all([provider.getSummary()])
|
|
170
185
|
set({ summary })
|
|
186
|
+
void get().refreshActivities()
|
|
171
187
|
toast.success('Deal created')
|
|
172
188
|
return deal
|
|
173
189
|
} catch (err: any) {
|
|
@@ -271,6 +287,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
271
287
|
set({ dealsByStage })
|
|
272
288
|
} catch { /* non-blocking */ }
|
|
273
289
|
}
|
|
290
|
+
void get().refreshActivities()
|
|
274
291
|
toast.success('Quote created')
|
|
275
292
|
return quote
|
|
276
293
|
} catch (err: any) {
|
|
@@ -295,6 +312,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
295
312
|
try {
|
|
296
313
|
const quote = await provider.sendQuote(id)
|
|
297
314
|
set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
|
|
315
|
+
void get().refreshActivities()
|
|
298
316
|
toast.success('Quote sent')
|
|
299
317
|
return quote
|
|
300
318
|
} catch (err: any) {
|
|
@@ -317,6 +335,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
317
335
|
])
|
|
318
336
|
set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
319
337
|
}
|
|
338
|
+
void get().refreshActivities()
|
|
320
339
|
toast.success('Quote approved — invoice created')
|
|
321
340
|
return quote
|
|
322
341
|
} catch (err: any) {
|
|
@@ -338,6 +357,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
338
357
|
])
|
|
339
358
|
set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
340
359
|
}
|
|
360
|
+
void get().refreshActivities()
|
|
341
361
|
toast.success('Quote rejected')
|
|
342
362
|
return quote
|
|
343
363
|
} catch (err: any) {
|
|
@@ -370,6 +390,62 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
|
|
|
370
390
|
])
|
|
371
391
|
set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
372
392
|
}
|
|
393
|
+
void get().refreshActivities()
|
|
394
|
+
},
|
|
395
|
+
|
|
396
|
+
async archiveDeal(dealId) {
|
|
397
|
+
try {
|
|
398
|
+
await provider.archiveDeal(dealId)
|
|
399
|
+
const { pipelines } = get()
|
|
400
|
+
if (pipelines.length > 0) {
|
|
401
|
+
const [dealsByStage, summary] = await Promise.all([
|
|
402
|
+
provider.getDealsByStage(pipelines[0].id),
|
|
403
|
+
provider.getSummary(),
|
|
404
|
+
])
|
|
405
|
+
set({ dealsByStage, summary })
|
|
406
|
+
}
|
|
407
|
+
void get().refreshActivities()
|
|
408
|
+
toast.success('Deal archived')
|
|
409
|
+
} catch (err: any) {
|
|
410
|
+
toast.error('Failed to archive deal', { description: err?.message })
|
|
411
|
+
throw err
|
|
412
|
+
}
|
|
413
|
+
},
|
|
414
|
+
|
|
415
|
+
async archiveLead(leadId) {
|
|
416
|
+
try {
|
|
417
|
+
await provider.archiveLead(leadId)
|
|
418
|
+
const { pipelines } = get()
|
|
419
|
+
const [leadsResult, summary, dealsByStage] = await Promise.all([
|
|
420
|
+
provider.getLeads({}),
|
|
421
|
+
provider.getSummary(),
|
|
422
|
+
pipelines.length > 0 ? provider.getDealsByStage(pipelines[0].id) : Promise.resolve(null),
|
|
423
|
+
])
|
|
424
|
+
set({
|
|
425
|
+
leads: leadsResult.data, leadsTotal: leadsResult.total, summary,
|
|
426
|
+
...(dealsByStage ? { dealsByStage } : {}),
|
|
427
|
+
})
|
|
428
|
+
void get().refreshActivities()
|
|
429
|
+
toast.success('Lead archived')
|
|
430
|
+
} catch (err: any) {
|
|
431
|
+
toast.error('Failed to archive lead', { description: err?.message })
|
|
432
|
+
throw err
|
|
433
|
+
}
|
|
434
|
+
},
|
|
435
|
+
|
|
436
|
+
async archiveQuote(quoteId) {
|
|
437
|
+
try {
|
|
438
|
+
await provider.archiveQuote(quoteId)
|
|
439
|
+
set((state) => ({
|
|
440
|
+
quotes: state.quotes.filter((q) => q.id !== quoteId),
|
|
441
|
+
quotesTotal: Math.max(0, state.quotesTotal - 1),
|
|
442
|
+
}))
|
|
443
|
+
void get().refreshActivities()
|
|
444
|
+
toast.success('Quote archived')
|
|
445
|
+
} catch (err: any) {
|
|
446
|
+
toast.error('Failed to archive quote', { description: err?.message })
|
|
447
|
+
throw err
|
|
448
|
+
}
|
|
373
449
|
},
|
|
374
450
|
}))
|
|
375
451
|
}
|
package/src/types.ts
CHANGED
|
@@ -8,10 +8,27 @@
|
|
|
8
8
|
// ============================================================
|
|
9
9
|
|
|
10
10
|
export type LeadStatus = 'new' | 'contacted' | 'qualified' | 'unqualified' | 'converted' | 'lost'
|
|
11
|
-
export type DealStatus = 'open' | 'won' | 'lost'
|
|
12
|
-
export type QuoteStatus = 'draft' | 'sent' | 'approved' | 'rejected' | 'expired'
|
|
11
|
+
export type DealStatus = 'open' | 'won' | 'lost' | 'archived'
|
|
12
|
+
export type QuoteStatus = 'draft' | 'sent' | 'approved' | 'rejected' | 'expired' | 'archived'
|
|
13
13
|
export type ActivityType = 'call' | 'email' | 'meeting' | 'note' | 'task' | 'whatsapp' | (string & {})
|
|
14
14
|
|
|
15
|
+
/** System timeline events auto-logged by the data provider at every CRM write.
|
|
16
|
+
* Product-defined (not tenant-editable); manual interaction TYPES live in the
|
|
17
|
+
* activity-types registry and are editable in settings. */
|
|
18
|
+
export const SYSTEM_ACTIVITY_TYPES = [
|
|
19
|
+
'lead_created', 'lead_converted', 'lead_archived', 'deal_created', 'stage_changed',
|
|
20
|
+
'deal_won', 'deal_lost', 'deal_archived', 'quote_created', 'quote_sent', 'quote_approved', 'quote_rejected', 'quote_archived',
|
|
21
|
+
] as const
|
|
22
|
+
export type SystemActivityType = (typeof SYSTEM_ACTIVITY_TYPES)[number]
|
|
23
|
+
|
|
24
|
+
/** A tenant-editable manual interaction type (activity-types registry row). */
|
|
25
|
+
export interface ActivityTypeDef {
|
|
26
|
+
id: string
|
|
27
|
+
name: string
|
|
28
|
+
icon?: string
|
|
29
|
+
isActive: boolean
|
|
30
|
+
}
|
|
31
|
+
|
|
15
32
|
// ============================================================
|
|
16
33
|
// CORE ENTITIES
|
|
17
34
|
// ============================================================
|