@fayz-ai/plugin-crm 0.1.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/dist/CrmContext.d.ts +32 -0
- package/dist/CrmContext.d.ts.map +1 -0
- package/dist/CrmPage.d.ts +13 -0
- package/dist/CrmPage.d.ts.map +1 -0
- package/dist/cascade.d.ts +13 -0
- package/dist/cascade.d.ts.map +1 -0
- package/dist/components/CrmGeneralSettings.d.ts +3 -0
- package/dist/components/CrmGeneralSettings.d.ts.map +1 -0
- package/dist/components/CrmOnboarding.d.ts +5 -0
- package/dist/components/CrmOnboarding.d.ts.map +1 -0
- package/dist/components/PipelineSettings.d.ts +3 -0
- package/dist/components/PipelineSettings.d.ts.map +1 -0
- package/dist/components/QuoteStatusDropdown.d.ts +8 -0
- package/dist/components/QuoteStatusDropdown.d.ts.map +1 -0
- package/dist/data/index.d.ts +3 -0
- package/dist/data/index.d.ts.map +1 -0
- package/dist/data/mock.d.ts +9 -0
- package/dist/data/mock.d.ts.map +1 -0
- package/dist/data/supabase.d.ts +9 -0
- package/dist/data/supabase.d.ts.map +1 -0
- package/dist/data/types.d.ts +32 -0
- package/dist/data/types.d.ts.map +1 -0
- package/dist/index.cjs +4601 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +72 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4595 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/tenant.d.ts +3 -0
- package/dist/lib/tenant.d.ts.map +1 -0
- package/dist/locales/en.d.ts +2 -0
- package/dist/locales/en.d.ts.map +1 -0
- package/dist/locales/index.d.ts +2 -0
- package/dist/locales/index.d.ts.map +1 -0
- package/dist/locales/pt-BR.d.ts +2 -0
- package/dist/locales/pt-BR.d.ts.map +1 -0
- package/dist/registries.d.ts +3 -0
- package/dist/registries.d.ts.map +1 -0
- package/dist/schema/index.d.ts +1036 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/store.d.ts +43 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/types.d.ts +238 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/views/ActivityListView.d.ts +3 -0
- package/dist/views/ActivityListView.d.ts.map +1 -0
- package/dist/views/DashboardView.d.ts +9 -0
- package/dist/views/DashboardView.d.ts.map +1 -0
- package/dist/views/DealSidebar.d.ts +9 -0
- package/dist/views/DealSidebar.d.ts.map +1 -0
- package/dist/views/LeadDetailView.d.ts +8 -0
- package/dist/views/LeadDetailView.d.ts.map +1 -0
- package/dist/views/LeadFormView.d.ts +5 -0
- package/dist/views/LeadFormView.d.ts.map +1 -0
- package/dist/views/LeadListView.d.ts +6 -0
- package/dist/views/LeadListView.d.ts.map +1 -0
- package/dist/views/PipelineView.d.ts +8 -0
- package/dist/views/PipelineView.d.ts.map +1 -0
- package/dist/views/QuoteDetailView.d.ts +8 -0
- package/dist/views/QuoteDetailView.d.ts.map +1 -0
- package/dist/views/QuoteFormView.d.ts +7 -0
- package/dist/views/QuoteFormView.d.ts.map +1 -0
- package/dist/views/QuoteListView.d.ts +7 -0
- package/dist/views/QuoteListView.d.ts.map +1 -0
- package/dist/views/dashboardWidgets.d.ts +11 -0
- package/dist/views/dashboardWidgets.d.ts.map +1 -0
- package/package.json +55 -0
- package/src/CrmContext.tsx +30 -0
- package/src/CrmPage.tsx +152 -0
- package/src/README.md +97 -0
- package/src/cascade.ts +24 -0
- package/src/components/CrmGeneralSettings.tsx +36 -0
- package/src/components/CrmOnboarding.tsx +52 -0
- package/src/components/PipelineSettings.tsx +45 -0
- package/src/components/QuoteStatusDropdown.tsx +214 -0
- package/src/data/index.ts +2 -0
- package/src/data/mock.ts +426 -0
- package/src/data/supabase.ts +634 -0
- package/src/data/types.ts +50 -0
- package/src/index.ts +240 -0
- package/src/lib/tenant.ts +4 -0
- package/src/locales/en.ts +292 -0
- package/src/locales/index.ts +7 -0
- package/src/locales/pt-BR.ts +292 -0
- package/src/migrations/001_crm_base.sql +73 -0
- package/src/migrations/002_activities.sql +33 -0
- package/src/migrations/003_crm_views_rls.sql +61 -0
- package/src/migrations/004_seed_default_pipeline.sql +31 -0
- package/src/registries.ts +88 -0
- package/src/schema/index.ts +102 -0
- package/src/store.ts +375 -0
- package/src/types.ts +280 -0
- package/src/views/ActivityListView.tsx +183 -0
- package/src/views/DashboardView.tsx +12 -0
- package/src/views/DealSidebar.tsx +414 -0
- package/src/views/LeadDetailView.tsx +264 -0
- package/src/views/LeadFormView.tsx +56 -0
- package/src/views/LeadListView.tsx +81 -0
- package/src/views/PipelineView.tsx +299 -0
- package/src/views/QuoteDetailView.tsx +408 -0
- package/src/views/QuoteFormView.tsx +489 -0
- package/src/views/QuoteListView.tsx +101 -0
- package/src/views/dashboardWidgets.tsx +248 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import {
|
|
2
|
+
pgTable, uuid, text, boolean, integer, numeric, date, timestamp, index,
|
|
3
|
+
} from 'drizzle-orm/pg-core'
|
|
4
|
+
import { tenantId, timestamps, createdAt, persons, orders } from '@fayz-ai/db'
|
|
5
|
+
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
// CRM plugin — Ring-1 schema (schema-as-code).
|
|
8
|
+
//
|
|
9
|
+
// Leads live on saas_core.persons (kind='lead'); deals/quotes on saas_core.orders.
|
|
10
|
+
// These tables extend that spine with pipeline, tagging and activity data.
|
|
11
|
+
// RLS policies, grants and the v_leads/v_deals read-views are companion SQL
|
|
12
|
+
// (Drizzle doesn't diff grants/views) — see the app's drizzle/companion/.
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
export const pipelines = pgTable('pipelines', {
|
|
16
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
17
|
+
tenantId: tenantId(),
|
|
18
|
+
name: text('name').notNull(),
|
|
19
|
+
isDefault: boolean('is_default').default(false),
|
|
20
|
+
isActive: boolean('is_active').notNull().default(true),
|
|
21
|
+
...timestamps,
|
|
22
|
+
}, (t) => [index('idx_pipelines_tenant').on(t.tenantId)])
|
|
23
|
+
|
|
24
|
+
export const pipelineStages = pgTable('pipeline_stages', {
|
|
25
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
26
|
+
tenantId: tenantId(),
|
|
27
|
+
pipelineId: uuid('pipeline_id').notNull().references(() => pipelines.id, { onDelete: 'cascade' }),
|
|
28
|
+
name: text('name').notNull(),
|
|
29
|
+
order: integer('order').notNull().default(0),
|
|
30
|
+
color: text('color').default('#6366f1'),
|
|
31
|
+
probability: numeric('probability', { precision: 5, scale: 2 }).default('0'),
|
|
32
|
+
isWon: boolean('is_won').default(false),
|
|
33
|
+
isLost: boolean('is_lost').default(false),
|
|
34
|
+
...createdAt,
|
|
35
|
+
}, (t) => [
|
|
36
|
+
index('idx_pipeline_stages_tenant').on(t.tenantId),
|
|
37
|
+
index('idx_pipeline_stages_pipeline').on(t.pipelineId),
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
export const leadSources = pgTable('lead_sources', {
|
|
41
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
42
|
+
tenantId: tenantId(),
|
|
43
|
+
name: text('name').notNull(),
|
|
44
|
+
isActive: boolean('is_active').notNull().default(true),
|
|
45
|
+
...createdAt,
|
|
46
|
+
}, (t) => [index('idx_lead_sources_tenant').on(t.tenantId)])
|
|
47
|
+
|
|
48
|
+
export const crmTags = pgTable('crm_tags', {
|
|
49
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
50
|
+
tenantId: tenantId(),
|
|
51
|
+
name: text('name').notNull(),
|
|
52
|
+
color: text('color').default('#6366f1'),
|
|
53
|
+
isActive: boolean('is_active').notNull().default(true),
|
|
54
|
+
...createdAt,
|
|
55
|
+
}, (t) => [index('idx_crm_tags_tenant').on(t.tenantId)])
|
|
56
|
+
|
|
57
|
+
export const dealExtensions = pgTable('deal_extensions', {
|
|
58
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
59
|
+
orderId: uuid('order_id').notNull().references(() => orders.id, { onDelete: 'cascade' }),
|
|
60
|
+
tenantId: tenantId(),
|
|
61
|
+
pipelineId: uuid('pipeline_id').references(() => pipelines.id),
|
|
62
|
+
stageId: uuid('stage_id').references(() => pipelineStages.id),
|
|
63
|
+
probability: numeric('probability', { precision: 5, scale: 2 }).default('0'),
|
|
64
|
+
expectedCloseDate: date('expected_close_date'),
|
|
65
|
+
leadId: uuid('lead_id').references(() => persons.id),
|
|
66
|
+
lostReason: text('lost_reason'),
|
|
67
|
+
...timestamps,
|
|
68
|
+
}, (t) => [
|
|
69
|
+
index('idx_deal_extensions_tenant').on(t.tenantId),
|
|
70
|
+
index('idx_deal_extensions_order').on(t.orderId),
|
|
71
|
+
index('idx_deal_extensions_stage').on(t.stageId),
|
|
72
|
+
])
|
|
73
|
+
|
|
74
|
+
export const crmActivityTypes = pgTable('crm_activity_types', {
|
|
75
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
76
|
+
tenantId: tenantId(),
|
|
77
|
+
name: text('name').notNull(),
|
|
78
|
+
isActive: boolean('is_active').notNull().default(true),
|
|
79
|
+
...createdAt,
|
|
80
|
+
}, (t) => [index('idx_crm_activity_types_tenant').on(t.tenantId)])
|
|
81
|
+
|
|
82
|
+
export const crmActivities = pgTable('crm_activities', {
|
|
83
|
+
id: uuid('id').primaryKey().defaultRandom(),
|
|
84
|
+
tenantId: tenantId(),
|
|
85
|
+
dealId: uuid('deal_id').references(() => orders.id),
|
|
86
|
+
leadId: uuid('lead_id').references(() => persons.id),
|
|
87
|
+
contactId: uuid('contact_id').references(() => persons.id),
|
|
88
|
+
contactName: text('contact_name'),
|
|
89
|
+
activityType: text('activity_type').notNull(),
|
|
90
|
+
title: text('title').notNull(),
|
|
91
|
+
description: text('description'),
|
|
92
|
+
dueDate: date('due_date'),
|
|
93
|
+
completedAt: timestamp('completed_at', { withTimezone: true }),
|
|
94
|
+
assignedToId: uuid('assigned_to_id'),
|
|
95
|
+
assignedToName: text('assigned_to_name'),
|
|
96
|
+
...createdAt,
|
|
97
|
+
}, (t) => [
|
|
98
|
+
index('idx_crm_activities_tenant').on(t.tenantId),
|
|
99
|
+
index('idx_crm_activities_deal').on(t.dealId),
|
|
100
|
+
index('idx_crm_activities_lead').on(t.leadId),
|
|
101
|
+
index('idx_crm_activities_due').on(t.tenantId, t.dueDate),
|
|
102
|
+
])
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
import { createStore, type StoreApi } from 'zustand/vanilla'
|
|
2
|
+
import { dedup } from '@fayz-ai/saas'
|
|
3
|
+
import { toast } from '@fayz-ai/ui'
|
|
4
|
+
import type { CrmDataProvider } from './data/types'
|
|
5
|
+
import type {
|
|
6
|
+
Pipeline, PipelineStage, Lead, Deal, Activity, Quote,
|
|
7
|
+
CrmSummary, FunnelStage,
|
|
8
|
+
LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
|
|
9
|
+
CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
|
|
10
|
+
} from './types'
|
|
11
|
+
|
|
12
|
+
export interface CrmUIState {
|
|
13
|
+
pipelines: Pipeline[]
|
|
14
|
+
stages: PipelineStage[]
|
|
15
|
+
leads: Lead[]
|
|
16
|
+
leadsTotal: number
|
|
17
|
+
leadsLoading: boolean
|
|
18
|
+
deals: Deal[]
|
|
19
|
+
dealsTotal: number
|
|
20
|
+
dealsLoading: boolean
|
|
21
|
+
dealsByStage: Map<string, Deal[]>
|
|
22
|
+
activities: Activity[]
|
|
23
|
+
activitiesTotal: number
|
|
24
|
+
activitiesLoading: boolean
|
|
25
|
+
quotes: Quote[]
|
|
26
|
+
quotesTotal: number
|
|
27
|
+
quotesLoading: boolean
|
|
28
|
+
summary: CrmSummary | null
|
|
29
|
+
summaryLoading: boolean
|
|
30
|
+
funnel: FunnelStage[]
|
|
31
|
+
|
|
32
|
+
fetchPipelines(): Promise<void>
|
|
33
|
+
fetchSummary(): Promise<void>
|
|
34
|
+
fetchFunnel(pipelineId: string): Promise<void>
|
|
35
|
+
fetchLeads(query: LeadQuery): Promise<void>
|
|
36
|
+
fetchDeals(query: DealQuery): Promise<void>
|
|
37
|
+
fetchDealsByStage(pipelineId: string): Promise<void>
|
|
38
|
+
fetchActivities(query: ActivityQuery): Promise<void>
|
|
39
|
+
fetchQuotes(query: QuoteQuery): Promise<void>
|
|
40
|
+
createLead(input: CreateLeadInput): Promise<Lead>
|
|
41
|
+
createDeal(input: CreateDealInput): Promise<Deal>
|
|
42
|
+
createActivity(input: CreateActivityInput): Promise<Activity>
|
|
43
|
+
createQuote(input: CreateQuoteInput): Promise<Quote>
|
|
44
|
+
updateQuote(id: string, input: CreateQuoteInput): Promise<Quote>
|
|
45
|
+
sendQuote(id: string): Promise<Quote>
|
|
46
|
+
approveQuote(id: string): Promise<Quote>
|
|
47
|
+
rejectQuote(id: string, reason: string): Promise<Quote>
|
|
48
|
+
expireQuote(id: string): Promise<Quote>
|
|
49
|
+
moveDealToStage(dealId: string, stageId: string): Promise<void>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState> {
|
|
53
|
+
return createStore<CrmUIState>((set, get) => ({
|
|
54
|
+
pipelines: [], stages: [],
|
|
55
|
+
leads: [], leadsTotal: 0, leadsLoading: false,
|
|
56
|
+
deals: [], dealsTotal: 0, dealsLoading: false,
|
|
57
|
+
dealsByStage: new Map(),
|
|
58
|
+
activities: [], activitiesTotal: 0, activitiesLoading: false,
|
|
59
|
+
quotes: [], quotesTotal: 0, quotesLoading: false,
|
|
60
|
+
summary: null, summaryLoading: false,
|
|
61
|
+
funnel: [],
|
|
62
|
+
|
|
63
|
+
async fetchPipelines() {
|
|
64
|
+
return dedup('crm:pipelines', async () => {
|
|
65
|
+
const pipelines = await provider.getPipelines()
|
|
66
|
+
const stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : []
|
|
67
|
+
set({ pipelines, stages })
|
|
68
|
+
})
|
|
69
|
+
},
|
|
70
|
+
|
|
71
|
+
async fetchSummary() {
|
|
72
|
+
return dedup('crm:summary', async () => {
|
|
73
|
+
set({ summaryLoading: true })
|
|
74
|
+
const summary = await provider.getSummary()
|
|
75
|
+
set({ summary, summaryLoading: false })
|
|
76
|
+
})
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
async fetchFunnel(pipelineId) {
|
|
80
|
+
return dedup('crm:funnel:' + pipelineId, async () => {
|
|
81
|
+
const funnel = await provider.getFunnel(pipelineId)
|
|
82
|
+
set({ funnel })
|
|
83
|
+
})
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
async fetchLeads(query) {
|
|
87
|
+
return dedup('crm:leads:' + JSON.stringify(query), async () => {
|
|
88
|
+
set({ leadsLoading: true })
|
|
89
|
+
const result = await provider.getLeads(query)
|
|
90
|
+
set({ leads: result.data, leadsTotal: result.total, leadsLoading: false })
|
|
91
|
+
})
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
async fetchDeals(query) {
|
|
95
|
+
return dedup('crm:deals:' + JSON.stringify(query), async () => {
|
|
96
|
+
set({ dealsLoading: true })
|
|
97
|
+
const result = await provider.getDeals(query)
|
|
98
|
+
set({ deals: result.data, dealsTotal: result.total, dealsLoading: false })
|
|
99
|
+
})
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
async fetchDealsByStage(pipelineId) {
|
|
103
|
+
return dedup('crm:dealsByStage:' + pipelineId, async () => {
|
|
104
|
+
set({ dealsLoading: true })
|
|
105
|
+
const dealsByStage = await provider.getDealsByStage(pipelineId)
|
|
106
|
+
set({ dealsByStage, dealsLoading: false })
|
|
107
|
+
})
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
async fetchActivities(query) {
|
|
111
|
+
return dedup('crm:activities:' + JSON.stringify(query), async () => {
|
|
112
|
+
set({ activitiesLoading: true })
|
|
113
|
+
const result = await provider.getActivities(query)
|
|
114
|
+
set({ activities: result.data, activitiesTotal: result.total, activitiesLoading: false })
|
|
115
|
+
})
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
async fetchQuotes(query) {
|
|
119
|
+
return dedup('crm:quotes:' + JSON.stringify(query), async () => {
|
|
120
|
+
set({ quotesLoading: true })
|
|
121
|
+
const result = await provider.getQuotes(query)
|
|
122
|
+
set({ quotes: result.data, quotesTotal: result.total, quotesLoading: false })
|
|
123
|
+
})
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
async createLead(input) {
|
|
127
|
+
try {
|
|
128
|
+
const lead = await provider.createLead(input)
|
|
129
|
+
|
|
130
|
+
// Auto-create a deal in the first pipeline stage so it appears in the kanban
|
|
131
|
+
// Fetch pipelines if not loaded yet
|
|
132
|
+
let { pipelines, stages } = get()
|
|
133
|
+
if (pipelines.length === 0) {
|
|
134
|
+
pipelines = await provider.getPipelines()
|
|
135
|
+
stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : []
|
|
136
|
+
set({ pipelines, stages })
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0]
|
|
140
|
+
const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0]
|
|
141
|
+
if (defaultPipeline && firstStage) {
|
|
142
|
+
try {
|
|
143
|
+
await provider.createDeal({
|
|
144
|
+
leadId: lead.id,
|
|
145
|
+
title: lead.name,
|
|
146
|
+
value: input.value ?? 0,
|
|
147
|
+
pipelineId: defaultPipeline.id,
|
|
148
|
+
stageId: firstStage.id,
|
|
149
|
+
contactName: lead.name,
|
|
150
|
+
})
|
|
151
|
+
} catch {
|
|
152
|
+
// Deal creation failed — lead is still created, just won't appear in pipeline
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const summary = await provider.getSummary()
|
|
157
|
+
set({ summary })
|
|
158
|
+
toast.success('Lead captured')
|
|
159
|
+
return lead
|
|
160
|
+
} catch (err: any) {
|
|
161
|
+
toast.error('Failed to create lead', { description: err?.message })
|
|
162
|
+
throw err
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
async createDeal(input) {
|
|
167
|
+
try {
|
|
168
|
+
const deal = await provider.createDeal(input)
|
|
169
|
+
const [summary] = await Promise.all([provider.getSummary()])
|
|
170
|
+
set({ summary })
|
|
171
|
+
toast.success('Deal created')
|
|
172
|
+
return deal
|
|
173
|
+
} catch (err: any) {
|
|
174
|
+
toast.error('Failed to create deal', { description: err?.message })
|
|
175
|
+
throw err
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
|
|
179
|
+
async createActivity(input) {
|
|
180
|
+
try {
|
|
181
|
+
const activity = await provider.createActivity(input)
|
|
182
|
+
toast.success('Activity logged')
|
|
183
|
+
return activity
|
|
184
|
+
} catch (err: any) {
|
|
185
|
+
toast.error('Failed to log activity', { description: err?.message })
|
|
186
|
+
throw err
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
|
|
190
|
+
async createQuote(input) {
|
|
191
|
+
try {
|
|
192
|
+
let { pipelines, stages } = get()
|
|
193
|
+
if (pipelines.length === 0) {
|
|
194
|
+
pipelines = await provider.getPipelines()
|
|
195
|
+
stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : []
|
|
196
|
+
set({ pipelines, stages })
|
|
197
|
+
}
|
|
198
|
+
const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0]
|
|
199
|
+
|
|
200
|
+
let leadId = input.leadId
|
|
201
|
+
let dealId = input.dealId
|
|
202
|
+
const contactId = input.contactId
|
|
203
|
+
const contactName = input.contactName
|
|
204
|
+
|
|
205
|
+
// Step 1: Resolve or create a lead
|
|
206
|
+
if (!leadId && contactId) {
|
|
207
|
+
// contactId might be a lead (e.g., from "Add as Lead" in the form)
|
|
208
|
+
// Check if this person is a lead
|
|
209
|
+
try {
|
|
210
|
+
const lead = await provider.getLeadById(contactId)
|
|
211
|
+
if (lead) leadId = lead.id
|
|
212
|
+
} catch { /* not a lead, that's OK */ }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (!leadId && contactName) {
|
|
216
|
+
// No lead found — create one
|
|
217
|
+
try {
|
|
218
|
+
const lead = await provider.createLead({ name: contactName })
|
|
219
|
+
leadId = lead.id
|
|
220
|
+
if (!contactId) input = { ...input, contactId: lead.id }
|
|
221
|
+
} catch { /* ignore */ }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Step 2: Resolve or create a deal for this lead
|
|
225
|
+
if (leadId && !dealId) {
|
|
226
|
+
try {
|
|
227
|
+
const existingDeal = await provider.getDealByLeadId(leadId)
|
|
228
|
+
if (existingDeal) {
|
|
229
|
+
dealId = existingDeal.id
|
|
230
|
+
} else if (defaultPipeline) {
|
|
231
|
+
// No deal exists — create one
|
|
232
|
+
const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0]
|
|
233
|
+
if (firstStage) {
|
|
234
|
+
const deal = await provider.createDeal({
|
|
235
|
+
leadId, title: contactName ?? 'Deal',
|
|
236
|
+
value: input.items?.reduce((s, i) => s + (i.totalAmount ?? 0), 0) ?? 0,
|
|
237
|
+
pipelineId: defaultPipeline.id, stageId: firstStage.id,
|
|
238
|
+
contactName: contactName ?? '',
|
|
239
|
+
})
|
|
240
|
+
dealId = deal.id
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
} catch { /* ignore */ }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Create the quote with proper links
|
|
247
|
+
const enrichedInput = { ...input, leadId, dealId }
|
|
248
|
+
const quote = await provider.createQuote(enrichedInput)
|
|
249
|
+
|
|
250
|
+
// If we have a deal, advance it to Proposal stage (only forward)
|
|
251
|
+
if (dealId && defaultPipeline) {
|
|
252
|
+
try {
|
|
253
|
+
const deal = await provider.getDealById(dealId)
|
|
254
|
+
if (deal && deal.status === 'open') {
|
|
255
|
+
const currentStage = stages.find((s) => s.id === deal.stageId)
|
|
256
|
+
const proposalStage = stages.find((s) => s.name === 'Proposal')
|
|
257
|
+
?? stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0]
|
|
258
|
+
// Only advance forward
|
|
259
|
+
if (proposalStage && currentStage && proposalStage.order > currentStage.order) {
|
|
260
|
+
await provider.moveDealToStage(dealId, proposalStage.id)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
} catch { /* ignore */ }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Refresh local state — quotes + pipeline
|
|
267
|
+
set((state) => ({ quotes: [quote, ...state.quotes], quotesTotal: state.quotesTotal + 1 }))
|
|
268
|
+
if (defaultPipeline) {
|
|
269
|
+
try {
|
|
270
|
+
const dealsByStage = await provider.getDealsByStage(defaultPipeline.id)
|
|
271
|
+
set({ dealsByStage })
|
|
272
|
+
} catch { /* non-blocking */ }
|
|
273
|
+
}
|
|
274
|
+
toast.success('Quote created')
|
|
275
|
+
return quote
|
|
276
|
+
} catch (err: any) {
|
|
277
|
+
toast.error('Failed to create quote', { description: err?.message })
|
|
278
|
+
throw err
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
|
|
282
|
+
async updateQuote(id, input) {
|
|
283
|
+
try {
|
|
284
|
+
const quote = await provider.updateQuote(id, input)
|
|
285
|
+
set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
|
|
286
|
+
toast.success('Quote updated')
|
|
287
|
+
return quote
|
|
288
|
+
} catch (err: any) {
|
|
289
|
+
toast.error('Failed to update quote', { description: err?.message })
|
|
290
|
+
throw err
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
|
|
294
|
+
async sendQuote(id) {
|
|
295
|
+
try {
|
|
296
|
+
const quote = await provider.sendQuote(id)
|
|
297
|
+
set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
|
|
298
|
+
toast.success('Quote sent')
|
|
299
|
+
return quote
|
|
300
|
+
} catch (err: any) {
|
|
301
|
+
toast.error('Failed to send quote', { description: err?.message })
|
|
302
|
+
throw err
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
async approveQuote(id) {
|
|
307
|
+
try {
|
|
308
|
+
const quote = await provider.approveQuote(id)
|
|
309
|
+
// Full refresh — cascades touch deals, leads, quotes, creates invoice
|
|
310
|
+
const { pipelines } = get()
|
|
311
|
+
if (pipelines.length > 0) {
|
|
312
|
+
const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
|
|
313
|
+
provider.getDealsByStage(pipelines[0].id),
|
|
314
|
+
provider.getSummary(),
|
|
315
|
+
provider.getLeads({}),
|
|
316
|
+
provider.getQuotes({}),
|
|
317
|
+
])
|
|
318
|
+
set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
319
|
+
}
|
|
320
|
+
toast.success('Quote approved — invoice created')
|
|
321
|
+
return quote
|
|
322
|
+
} catch (err: any) {
|
|
323
|
+
toast.error('Failed to approve quote', { description: err?.message })
|
|
324
|
+
throw err
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
|
|
328
|
+
async rejectQuote(id, reason) {
|
|
329
|
+
try {
|
|
330
|
+
const quote = await provider.rejectQuote(id, reason)
|
|
331
|
+
const { pipelines } = get()
|
|
332
|
+
if (pipelines.length > 0) {
|
|
333
|
+
const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
|
|
334
|
+
provider.getDealsByStage(pipelines[0].id),
|
|
335
|
+
provider.getSummary(),
|
|
336
|
+
provider.getLeads({}),
|
|
337
|
+
provider.getQuotes({}),
|
|
338
|
+
])
|
|
339
|
+
set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
340
|
+
}
|
|
341
|
+
toast.success('Quote rejected')
|
|
342
|
+
return quote
|
|
343
|
+
} catch (err: any) {
|
|
344
|
+
toast.error('Failed to reject quote', { description: err?.message })
|
|
345
|
+
throw err
|
|
346
|
+
}
|
|
347
|
+
},
|
|
348
|
+
|
|
349
|
+
async expireQuote(id) {
|
|
350
|
+
try {
|
|
351
|
+
const quote = await provider.expireQuote(id)
|
|
352
|
+
set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
|
|
353
|
+
toast.success('Quote expired')
|
|
354
|
+
return quote
|
|
355
|
+
} catch (err: any) {
|
|
356
|
+
toast.error('Failed to expire quote', { description: err?.message })
|
|
357
|
+
throw err
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
|
|
361
|
+
async moveDealToStage(dealId, stageId) {
|
|
362
|
+
await provider.moveDealToStage(dealId, stageId)
|
|
363
|
+
const { pipelines } = get()
|
|
364
|
+
if (pipelines.length > 0) {
|
|
365
|
+
const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
|
|
366
|
+
provider.getDealsByStage(pipelines[0].id),
|
|
367
|
+
provider.getSummary(),
|
|
368
|
+
provider.getLeads({}),
|
|
369
|
+
provider.getQuotes({}),
|
|
370
|
+
])
|
|
371
|
+
set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
372
|
+
}
|
|
373
|
+
},
|
|
374
|
+
}))
|
|
375
|
+
}
|