@fayz-ai/plugin-crm 0.9.0 → 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
package/src/schema/index.ts
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
// Builders come from @fayz-ai/db (single drizzle-orm instance) — never import
|
|
2
|
-
// pgTable/uuid directly from drizzle-orm/pg-core. See MIGRATION-ARCHITECTURE §6.
|
|
3
|
-
import {
|
|
4
|
-
pgTable, uuid, text, boolean, integer, numeric, date, timestamp, index,
|
|
5
|
-
tenantId, timestamps, createdAt, people, orders,
|
|
6
|
-
} from '@fayz-ai/db'
|
|
7
|
-
|
|
8
|
-
// ---------------------------------------------------------------------------
|
|
9
|
-
// CRM plugin — Ring-1 schema (schema-as-code).
|
|
10
|
-
//
|
|
11
|
-
// Leads live on public.people (kind='lead'); deals/quotes on public.orders.
|
|
12
|
-
// These tables extend that spine with pipeline, tagging and activity data.
|
|
13
|
-
// RLS policies, grants and the v_leads/v_deals read-views are companion SQL
|
|
14
|
-
// (Drizzle doesn't diff grants/views) — see the app's drizzle/companion/.
|
|
15
|
-
// ---------------------------------------------------------------------------
|
|
16
|
-
|
|
17
|
-
export const pipelines = pgTable('plg_crm_pipelines', {
|
|
18
|
-
id: uuid('id').primaryKey().defaultRandom(),
|
|
19
|
-
tenantId: tenantId(),
|
|
20
|
-
name: text('name').notNull(),
|
|
21
|
-
isDefault: boolean('is_default').default(false),
|
|
22
|
-
isActive: boolean('is_active').notNull().default(true),
|
|
23
|
-
...timestamps,
|
|
24
|
-
}, (t) => [index('idx_plg_crm_pipelines_tenant').on(t.tenantId)])
|
|
25
|
-
|
|
26
|
-
export const pipelineStages = pgTable('plg_crm_pipeline_stages', {
|
|
27
|
-
id: uuid('id').primaryKey().defaultRandom(),
|
|
28
|
-
tenantId: tenantId(),
|
|
29
|
-
pipelineId: uuid('pipeline_id').notNull().references(() => pipelines.id, { onDelete: 'cascade' }),
|
|
30
|
-
name: text('name').notNull(),
|
|
31
|
-
order: integer('order').notNull().default(0),
|
|
32
|
-
color: text('color').default('#6366f1'),
|
|
33
|
-
probability: numeric('probability', { precision: 5, scale: 2 }).default('0'),
|
|
34
|
-
isWon: boolean('is_won').default(false),
|
|
35
|
-
isLost: boolean('is_lost').default(false),
|
|
36
|
-
...createdAt,
|
|
37
|
-
}, (t) => [
|
|
38
|
-
index('idx_plg_crm_pipeline_stages_tenant').on(t.tenantId),
|
|
39
|
-
index('idx_plg_crm_pipeline_stages_pipeline').on(t.pipelineId),
|
|
40
|
-
])
|
|
41
|
-
|
|
42
|
-
export const leadSources = pgTable('plg_crm_lead_sources', {
|
|
43
|
-
id: uuid('id').primaryKey().defaultRandom(),
|
|
44
|
-
tenantId: tenantId(),
|
|
45
|
-
name: text('name').notNull(),
|
|
46
|
-
isActive: boolean('is_active').notNull().default(true),
|
|
47
|
-
...createdAt,
|
|
48
|
-
}, (t) => [index('idx_plg_crm_lead_sources_tenant').on(t.tenantId)])
|
|
49
|
-
|
|
50
|
-
export const crmTags = pgTable('plg_crm_tags', {
|
|
51
|
-
id: uuid('id').primaryKey().defaultRandom(),
|
|
52
|
-
tenantId: tenantId(),
|
|
53
|
-
name: text('name').notNull(),
|
|
54
|
-
color: text('color').default('#6366f1'),
|
|
55
|
-
isActive: boolean('is_active').notNull().default(true),
|
|
56
|
-
...createdAt,
|
|
57
|
-
}, (t) => [index('idx_plg_crm_tags_tenant').on(t.tenantId)])
|
|
58
|
-
|
|
59
|
-
export const dealExtensions = pgTable('plg_crm_deal_extensions', {
|
|
60
|
-
id: uuid('id').primaryKey().defaultRandom(),
|
|
61
|
-
orderId: uuid('order_id').notNull().references(() => orders.id, { onDelete: 'cascade' }),
|
|
62
|
-
tenantId: tenantId(),
|
|
63
|
-
pipelineId: uuid('pipeline_id').references(() => pipelines.id),
|
|
64
|
-
stageId: uuid('stage_id').references(() => pipelineStages.id),
|
|
65
|
-
probability: numeric('probability', { precision: 5, scale: 2 }).default('0'),
|
|
66
|
-
expectedCloseDate: date('expected_close_date'),
|
|
67
|
-
leadId: uuid('lead_id').references(() => people.id),
|
|
68
|
-
lostReason: text('lost_reason'),
|
|
69
|
-
...timestamps,
|
|
70
|
-
}, (t) => [
|
|
71
|
-
index('idx_plg_crm_deal_extensions_tenant').on(t.tenantId),
|
|
72
|
-
index('idx_plg_crm_deal_extensions_order').on(t.orderId),
|
|
73
|
-
index('idx_plg_crm_deal_extensions_stage').on(t.stageId),
|
|
74
|
-
])
|
|
75
|
-
|
|
76
|
-
export const crmActivityTypes = pgTable('plg_crm_activity_types', {
|
|
77
|
-
id: uuid('id').primaryKey().defaultRandom(),
|
|
78
|
-
tenantId: tenantId(),
|
|
79
|
-
name: text('name').notNull(),
|
|
80
|
-
isActive: boolean('is_active').notNull().default(true),
|
|
81
|
-
...createdAt,
|
|
82
|
-
}, (t) => [index('idx_plg_crm_activity_types_tenant').on(t.tenantId)])
|
|
83
|
-
|
|
84
|
-
export const crmActivities = pgTable('plg_crm_activities', {
|
|
85
|
-
id: uuid('id').primaryKey().defaultRandom(),
|
|
86
|
-
tenantId: tenantId(),
|
|
87
|
-
dealId: uuid('deal_id').references(() => orders.id),
|
|
88
|
-
leadId: uuid('lead_id').references(() => people.id),
|
|
89
|
-
contactId: uuid('contact_id').references(() => people.id),
|
|
90
|
-
contactName: text('contact_name'),
|
|
91
|
-
activityType: text('activity_type').notNull(),
|
|
92
|
-
title: text('title').notNull(),
|
|
93
|
-
description: text('description'),
|
|
94
|
-
dueDate: date('due_date'),
|
|
95
|
-
completedAt: timestamp('completed_at', { withTimezone: true }),
|
|
96
|
-
assignedToId: uuid('assigned_to_id'),
|
|
97
|
-
assignedToName: text('assigned_to_name'),
|
|
98
|
-
...createdAt,
|
|
99
|
-
}, (t) => [
|
|
100
|
-
index('idx_plg_crm_activities_tenant').on(t.tenantId),
|
|
101
|
-
index('idx_plg_crm_activities_deal').on(t.dealId),
|
|
102
|
-
index('idx_plg_crm_activities_lead').on(t.leadId),
|
|
103
|
-
index('idx_plg_crm_activities_due').on(t.tenantId, t.dueDate),
|
|
104
|
-
])
|
package/src/store.ts
DELETED
|
@@ -1,472 +0,0 @@
|
|
|
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, TagDef, BoardFilter,
|
|
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
|
-
/** Cadastro de tags, por slug — rótulo e cor dos chips. */
|
|
32
|
-
tagDefs: Map<string, TagDef>
|
|
33
|
-
|
|
34
|
-
fetchPipelines(): Promise<void>
|
|
35
|
-
fetchTagDefs(): Promise<void>
|
|
36
|
-
fetchSummary(): Promise<void>
|
|
37
|
-
fetchFunnel(pipelineId: string): Promise<void>
|
|
38
|
-
fetchLeads(query: LeadQuery): Promise<void>
|
|
39
|
-
fetchDeals(query: DealQuery): Promise<void>
|
|
40
|
-
fetchDealsByStage(pipelineId: string, filter?: BoardFilter): Promise<void>
|
|
41
|
-
/** Recarrega o quadro no MESMO recorte do último fetchDealsByStage. */
|
|
42
|
-
refreshBoard(): Promise<void>
|
|
43
|
-
fetchActivities(query: ActivityQuery): Promise<void>
|
|
44
|
-
/** Re-fetch the timeline with the last query — writes append system events. */
|
|
45
|
-
refreshActivities(): Promise<void>
|
|
46
|
-
fetchQuotes(query: QuoteQuery): Promise<void>
|
|
47
|
-
createLead(input: CreateLeadInput): Promise<Lead>
|
|
48
|
-
createDeal(input: CreateDealInput): Promise<Deal>
|
|
49
|
-
createActivity(input: CreateActivityInput): Promise<Activity>
|
|
50
|
-
createQuote(input: CreateQuoteInput): Promise<Quote>
|
|
51
|
-
updateQuote(id: string, input: CreateQuoteInput): Promise<Quote>
|
|
52
|
-
sendQuote(id: string): Promise<Quote>
|
|
53
|
-
approveQuote(id: string): Promise<Quote>
|
|
54
|
-
rejectQuote(id: string, reason: string): Promise<Quote>
|
|
55
|
-
expireQuote(id: string): Promise<Quote>
|
|
56
|
-
moveDealToStage(dealId: string, stageId: string): Promise<void>
|
|
57
|
-
archiveDeal(dealId: string): Promise<void>
|
|
58
|
-
archiveLead(leadId: string): Promise<void>
|
|
59
|
-
archiveQuote(quoteId: string): Promise<void>
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState> {
|
|
63
|
-
let lastActivitiesQuery: ActivityQuery = {}
|
|
64
|
-
/** Pipeline + recorte do último carregamento do quadro (ver refreshBoard). */
|
|
65
|
-
let lastBoard: { pipelineId: string; filter?: BoardFilter } | null = null
|
|
66
|
-
return createStore<CrmUIState>((set, get) => ({
|
|
67
|
-
pipelines: [], stages: [],
|
|
68
|
-
leads: [], leadsTotal: 0, leadsLoading: false,
|
|
69
|
-
deals: [], dealsTotal: 0, dealsLoading: false,
|
|
70
|
-
dealsByStage: new Map(),
|
|
71
|
-
activities: [], activitiesTotal: 0, activitiesLoading: false,
|
|
72
|
-
quotes: [], quotesTotal: 0, quotesLoading: false,
|
|
73
|
-
summary: null, summaryLoading: false,
|
|
74
|
-
funnel: [],
|
|
75
|
-
tagDefs: new Map(),
|
|
76
|
-
|
|
77
|
-
async fetchPipelines() {
|
|
78
|
-
return dedup('crm:pipelines', async () => {
|
|
79
|
-
const pipelines = await provider.getPipelines()
|
|
80
|
-
const stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : []
|
|
81
|
-
set({ pipelines, stages })
|
|
82
|
-
})
|
|
83
|
-
},
|
|
84
|
-
|
|
85
|
-
async fetchTagDefs() {
|
|
86
|
-
return dedup('crm:tag-defs', async () => {
|
|
87
|
-
// Só apresentação: uma tag sem linha de cadastro ainda renderiza (chip
|
|
88
|
-
// neutro com o slug humanizado), então falhar aqui não pode esconder o
|
|
89
|
-
// card. Por isso o catch silencioso — ao contrário dos outros fetches,
|
|
90
|
-
// não há nada para o operador fazer com este erro.
|
|
91
|
-
try {
|
|
92
|
-
const defs = await provider.getTagDefs()
|
|
93
|
-
set({ tagDefs: new Map(defs.map((d) => [d.slug, d])) })
|
|
94
|
-
} catch {
|
|
95
|
-
/* chips caem no rótulo derivado do slug */
|
|
96
|
-
}
|
|
97
|
-
})
|
|
98
|
-
},
|
|
99
|
-
|
|
100
|
-
async fetchSummary() {
|
|
101
|
-
return dedup('crm:summary', async () => {
|
|
102
|
-
set({ summaryLoading: true })
|
|
103
|
-
const summary = await provider.getSummary()
|
|
104
|
-
set({ summary, summaryLoading: false })
|
|
105
|
-
})
|
|
106
|
-
},
|
|
107
|
-
|
|
108
|
-
async fetchFunnel(pipelineId) {
|
|
109
|
-
return dedup('crm:funnel:' + pipelineId, async () => {
|
|
110
|
-
const funnel = await provider.getFunnel(pipelineId)
|
|
111
|
-
set({ funnel })
|
|
112
|
-
})
|
|
113
|
-
},
|
|
114
|
-
|
|
115
|
-
async fetchLeads(query) {
|
|
116
|
-
return dedup('crm:leads:' + JSON.stringify(query), async () => {
|
|
117
|
-
set({ leadsLoading: true })
|
|
118
|
-
const result = await provider.getLeads(query)
|
|
119
|
-
set({ leads: result.data, leadsTotal: result.total, leadsLoading: false })
|
|
120
|
-
})
|
|
121
|
-
},
|
|
122
|
-
|
|
123
|
-
async fetchDeals(query) {
|
|
124
|
-
return dedup('crm:deals:' + JSON.stringify(query), async () => {
|
|
125
|
-
set({ dealsLoading: true })
|
|
126
|
-
const result = await provider.getDeals(query)
|
|
127
|
-
set({ deals: result.data, dealsTotal: result.total, dealsLoading: false })
|
|
128
|
-
})
|
|
129
|
-
},
|
|
130
|
-
|
|
131
|
-
async fetchDealsByStage(pipelineId, filter) {
|
|
132
|
-
// Guardado para o refreshBoard: quem recarrega depois de uma escrita não
|
|
133
|
-
// sabe (nem deveria saber) qual recorte está na tela.
|
|
134
|
-
lastBoard = { pipelineId, filter }
|
|
135
|
-
// A chave do dedup inclui o filtro: sem isso, trocar o período enquanto a
|
|
136
|
-
// busca anterior está no ar seria descartado como duplicata e o quadro
|
|
137
|
-
// ficaria mostrando o recorte antigo.
|
|
138
|
-
const key = 'crm:dealsByStage:' + pipelineId + ':' + JSON.stringify(filter ?? {})
|
|
139
|
-
return dedup(key, async () => {
|
|
140
|
-
set({ dealsLoading: true })
|
|
141
|
-
const dealsByStage = await provider.getDealsByStage(pipelineId, filter)
|
|
142
|
-
set({ dealsByStage, dealsLoading: false })
|
|
143
|
-
})
|
|
144
|
-
},
|
|
145
|
-
|
|
146
|
-
async refreshBoard() {
|
|
147
|
-
// O ÚNICO caminho de recarga do quadro depois de uma escrita. Cada ação
|
|
148
|
-
// chamava `getDealsByStage(pipelines[0].id)` na mão, sem filtro: mover um
|
|
149
|
-
// card devolvia o quadro inteiro por cima do recorte que a pessoa tinha
|
|
150
|
-
// escolhido, e o filtro parecia ter se perdido sozinho.
|
|
151
|
-
if (!lastBoard) return
|
|
152
|
-
return get().fetchDealsByStage(lastBoard.pipelineId, lastBoard.filter)
|
|
153
|
-
},
|
|
154
|
-
|
|
155
|
-
async fetchActivities(query) {
|
|
156
|
-
lastActivitiesQuery = query
|
|
157
|
-
return dedup('crm:activities:' + JSON.stringify(query), async () => {
|
|
158
|
-
set({ activitiesLoading: true })
|
|
159
|
-
const result = await provider.getActivities(query)
|
|
160
|
-
set({ activities: result.data, activitiesTotal: result.total, activitiesLoading: false })
|
|
161
|
-
})
|
|
162
|
-
},
|
|
163
|
-
|
|
164
|
-
async refreshActivities() {
|
|
165
|
-
try {
|
|
166
|
-
const result = await provider.getActivities(lastActivitiesQuery)
|
|
167
|
-
set({ activities: result.data, activitiesTotal: result.total })
|
|
168
|
-
} catch { /* timeline refresh is best-effort */ }
|
|
169
|
-
},
|
|
170
|
-
|
|
171
|
-
async fetchQuotes(query) {
|
|
172
|
-
return dedup('crm:quotes:' + JSON.stringify(query), async () => {
|
|
173
|
-
set({ quotesLoading: true })
|
|
174
|
-
const result = await provider.getQuotes(query)
|
|
175
|
-
set({ quotes: result.data, quotesTotal: result.total, quotesLoading: false })
|
|
176
|
-
})
|
|
177
|
-
},
|
|
178
|
-
|
|
179
|
-
async createLead(input) {
|
|
180
|
-
try {
|
|
181
|
-
const lead = await provider.createLead(input)
|
|
182
|
-
|
|
183
|
-
// Auto-create a deal in the first pipeline stage so it appears in the kanban
|
|
184
|
-
// Fetch pipelines if not loaded yet
|
|
185
|
-
let { pipelines, stages } = get()
|
|
186
|
-
if (pipelines.length === 0) {
|
|
187
|
-
pipelines = await provider.getPipelines()
|
|
188
|
-
stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : []
|
|
189
|
-
set({ pipelines, stages })
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0]
|
|
193
|
-
const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0]
|
|
194
|
-
if (defaultPipeline && firstStage) {
|
|
195
|
-
try {
|
|
196
|
-
await provider.createDeal({
|
|
197
|
-
leadId: lead.id,
|
|
198
|
-
title: lead.name,
|
|
199
|
-
value: input.value ?? 0,
|
|
200
|
-
pipelineId: defaultPipeline.id,
|
|
201
|
-
stageId: firstStage.id,
|
|
202
|
-
contactName: lead.name,
|
|
203
|
-
})
|
|
204
|
-
} catch {
|
|
205
|
-
// Deal creation failed — lead is still created, just won't appear in pipeline
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
const summary = await provider.getSummary()
|
|
210
|
-
set({ summary })
|
|
211
|
-
void get().refreshActivities()
|
|
212
|
-
toast.success('Lead captured')
|
|
213
|
-
return lead
|
|
214
|
-
} catch (err: any) {
|
|
215
|
-
toast.error('Failed to create lead', { description: err?.message })
|
|
216
|
-
throw err
|
|
217
|
-
}
|
|
218
|
-
},
|
|
219
|
-
|
|
220
|
-
async createDeal(input) {
|
|
221
|
-
try {
|
|
222
|
-
const deal = await provider.createDeal(input)
|
|
223
|
-
const [summary] = await Promise.all([provider.getSummary()])
|
|
224
|
-
set({ summary })
|
|
225
|
-
void get().refreshActivities()
|
|
226
|
-
toast.success('Deal created')
|
|
227
|
-
return deal
|
|
228
|
-
} catch (err: any) {
|
|
229
|
-
toast.error('Failed to create deal', { description: err?.message })
|
|
230
|
-
throw err
|
|
231
|
-
}
|
|
232
|
-
},
|
|
233
|
-
|
|
234
|
-
async createActivity(input) {
|
|
235
|
-
try {
|
|
236
|
-
const activity = await provider.createActivity(input)
|
|
237
|
-
toast.success('Activity logged')
|
|
238
|
-
return activity
|
|
239
|
-
} catch (err: any) {
|
|
240
|
-
toast.error('Failed to log activity', { description: err?.message })
|
|
241
|
-
throw err
|
|
242
|
-
}
|
|
243
|
-
},
|
|
244
|
-
|
|
245
|
-
async createQuote(input) {
|
|
246
|
-
try {
|
|
247
|
-
let { pipelines, stages } = get()
|
|
248
|
-
if (pipelines.length === 0) {
|
|
249
|
-
pipelines = await provider.getPipelines()
|
|
250
|
-
stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : []
|
|
251
|
-
set({ pipelines, stages })
|
|
252
|
-
}
|
|
253
|
-
const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0]
|
|
254
|
-
|
|
255
|
-
let leadId = input.leadId
|
|
256
|
-
let dealId = input.dealId
|
|
257
|
-
const contactId = input.contactId
|
|
258
|
-
const contactName = input.contactName
|
|
259
|
-
|
|
260
|
-
// Step 1: Resolve or create a lead
|
|
261
|
-
if (!leadId && contactId) {
|
|
262
|
-
// contactId might be a lead (e.g., from "Add as Lead" in the form)
|
|
263
|
-
// Check if this person is a lead
|
|
264
|
-
try {
|
|
265
|
-
const lead = await provider.getLeadById(contactId)
|
|
266
|
-
if (lead) leadId = lead.id
|
|
267
|
-
} catch { /* not a lead, that's OK */ }
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
if (!leadId && contactName) {
|
|
271
|
-
// No lead found — create one
|
|
272
|
-
try {
|
|
273
|
-
const lead = await provider.createLead({ name: contactName })
|
|
274
|
-
leadId = lead.id
|
|
275
|
-
if (!contactId) input = { ...input, contactId: lead.id }
|
|
276
|
-
} catch { /* ignore */ }
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// Step 2: Resolve or create a deal for this lead
|
|
280
|
-
if (leadId && !dealId) {
|
|
281
|
-
try {
|
|
282
|
-
const existingDeal = await provider.getDealByLeadId(leadId)
|
|
283
|
-
if (existingDeal) {
|
|
284
|
-
dealId = existingDeal.id
|
|
285
|
-
} else if (defaultPipeline) {
|
|
286
|
-
// No deal exists — create one
|
|
287
|
-
const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0]
|
|
288
|
-
if (firstStage) {
|
|
289
|
-
const deal = await provider.createDeal({
|
|
290
|
-
leadId, title: contactName ?? 'Deal',
|
|
291
|
-
value: input.items?.reduce((s, i) => s + (i.totalAmount ?? 0), 0) ?? 0,
|
|
292
|
-
pipelineId: defaultPipeline.id, stageId: firstStage.id,
|
|
293
|
-
contactName: contactName ?? '',
|
|
294
|
-
})
|
|
295
|
-
dealId = deal.id
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
} catch { /* ignore */ }
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// Create the quote with proper links
|
|
302
|
-
const enrichedInput = { ...input, leadId, dealId }
|
|
303
|
-
const quote = await provider.createQuote(enrichedInput)
|
|
304
|
-
|
|
305
|
-
// If we have a deal, advance it to Proposal stage (only forward)
|
|
306
|
-
if (dealId && defaultPipeline) {
|
|
307
|
-
try {
|
|
308
|
-
const deal = await provider.getDealById(dealId)
|
|
309
|
-
if (deal && deal.status === 'open') {
|
|
310
|
-
const currentStage = stages.find((s) => s.id === deal.stageId)
|
|
311
|
-
const proposalStage = stages.find((s) => s.name === 'Proposal')
|
|
312
|
-
?? stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0]
|
|
313
|
-
// Only advance forward
|
|
314
|
-
if (proposalStage && currentStage && proposalStage.order > currentStage.order) {
|
|
315
|
-
await provider.moveDealToStage(dealId, proposalStage.id)
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
} catch { /* ignore */ }
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
// Refresh local state — quotes + pipeline
|
|
322
|
-
set((state) => ({ quotes: [quote, ...state.quotes], quotesTotal: state.quotesTotal + 1 }))
|
|
323
|
-
try {
|
|
324
|
-
await get().refreshBoard()
|
|
325
|
-
} catch { /* non-blocking */ }
|
|
326
|
-
void get().refreshActivities()
|
|
327
|
-
toast.success('Quote created')
|
|
328
|
-
return quote
|
|
329
|
-
} catch (err: any) {
|
|
330
|
-
toast.error('Failed to create quote', { description: err?.message })
|
|
331
|
-
throw err
|
|
332
|
-
}
|
|
333
|
-
},
|
|
334
|
-
|
|
335
|
-
async updateQuote(id, input) {
|
|
336
|
-
try {
|
|
337
|
-
const quote = await provider.updateQuote(id, input)
|
|
338
|
-
set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
|
|
339
|
-
toast.success('Quote updated')
|
|
340
|
-
return quote
|
|
341
|
-
} catch (err: any) {
|
|
342
|
-
toast.error('Failed to update quote', { description: err?.message })
|
|
343
|
-
throw err
|
|
344
|
-
}
|
|
345
|
-
},
|
|
346
|
-
|
|
347
|
-
async sendQuote(id) {
|
|
348
|
-
try {
|
|
349
|
-
const quote = await provider.sendQuote(id)
|
|
350
|
-
set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
|
|
351
|
-
void get().refreshActivities()
|
|
352
|
-
toast.success('Quote sent')
|
|
353
|
-
return quote
|
|
354
|
-
} catch (err: any) {
|
|
355
|
-
toast.error('Failed to send quote', { description: err?.message })
|
|
356
|
-
throw err
|
|
357
|
-
}
|
|
358
|
-
},
|
|
359
|
-
|
|
360
|
-
async approveQuote(id) {
|
|
361
|
-
try {
|
|
362
|
-
const quote = await provider.approveQuote(id)
|
|
363
|
-
// Full refresh — cascades touch deals, leads, quotes, creates invoice.
|
|
364
|
-
// O quadro entra pelo refreshBoard para não perder o recorte da tela.
|
|
365
|
-
const [summary, leadsResult, quotesResult] = await Promise.all([
|
|
366
|
-
provider.getSummary(),
|
|
367
|
-
provider.getLeads({}),
|
|
368
|
-
provider.getQuotes({}),
|
|
369
|
-
get().refreshBoard(),
|
|
370
|
-
])
|
|
371
|
-
set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
372
|
-
void get().refreshActivities()
|
|
373
|
-
toast.success('Quote approved — invoice created')
|
|
374
|
-
return quote
|
|
375
|
-
} catch (err: any) {
|
|
376
|
-
toast.error('Failed to approve quote', { description: err?.message })
|
|
377
|
-
throw err
|
|
378
|
-
}
|
|
379
|
-
},
|
|
380
|
-
|
|
381
|
-
async rejectQuote(id, reason) {
|
|
382
|
-
try {
|
|
383
|
-
const quote = await provider.rejectQuote(id, reason)
|
|
384
|
-
const [summary, leadsResult, quotesResult] = await Promise.all([
|
|
385
|
-
provider.getSummary(),
|
|
386
|
-
provider.getLeads({}),
|
|
387
|
-
provider.getQuotes({}),
|
|
388
|
-
get().refreshBoard(),
|
|
389
|
-
])
|
|
390
|
-
set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
|
|
391
|
-
void get().refreshActivities()
|
|
392
|
-
toast.success('Quote rejected')
|
|
393
|
-
return quote
|
|
394
|
-
} catch (err: any) {
|
|
395
|
-
toast.error('Failed to reject quote', { description: err?.message })
|
|
396
|
-
throw err
|
|
397
|
-
}
|
|
398
|
-
},
|
|
399
|
-
|
|
400
|
-
async expireQuote(id) {
|
|
401
|
-
try {
|
|
402
|
-
const quote = await provider.expireQuote(id)
|
|
403
|
-
set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
|
|
404
|
-
toast.success('Quote expired')
|
|
405
|
-
return quote
|
|
406
|
-
} catch (err: any) {
|
|
407
|
-
toast.error('Failed to expire quote', { description: err?.message })
|
|
408
|
-
throw err
|
|
409
|
-
}
|
|
410
|
-
},
|
|
411
|
-
|
|
412
|
-
async moveDealToStage(dealId, stageId) {
|
|
413
|
-
await provider.moveDealToStage(dealId, stageId)
|
|
414
|
-
// Só o quadro. Arrastar um card entre etapas não muda a lista de leads nem
|
|
415
|
-
// a de orçamentos, e o resumo não está na tela — buscar os quatro fazia de
|
|
416
|
-
// cada arrastar quatro viagens, três delas para dados que ninguém olhava.
|
|
417
|
-
// Quem renderiza aquelas listas as recarrega ao montar.
|
|
418
|
-
await get().refreshBoard()
|
|
419
|
-
void get().refreshActivities()
|
|
420
|
-
},
|
|
421
|
-
|
|
422
|
-
async archiveDeal(dealId) {
|
|
423
|
-
try {
|
|
424
|
-
await provider.archiveDeal(dealId)
|
|
425
|
-
const [, summary] = await Promise.all([
|
|
426
|
-
get().refreshBoard(),
|
|
427
|
-
provider.getSummary(),
|
|
428
|
-
])
|
|
429
|
-
set({ summary })
|
|
430
|
-
void get().refreshActivities()
|
|
431
|
-
toast.success('Deal archived')
|
|
432
|
-
} catch (err: any) {
|
|
433
|
-
toast.error('Failed to archive deal', { description: err?.message })
|
|
434
|
-
throw err
|
|
435
|
-
}
|
|
436
|
-
},
|
|
437
|
-
|
|
438
|
-
async archiveLead(leadId) {
|
|
439
|
-
try {
|
|
440
|
-
await provider.archiveLead(leadId)
|
|
441
|
-
// Arquivar um lead tira o card do quadro também — mas no recorte que
|
|
442
|
-
// está na tela, não no quadro inteiro.
|
|
443
|
-
const [leadsResult, summary] = await Promise.all([
|
|
444
|
-
provider.getLeads({}),
|
|
445
|
-
provider.getSummary(),
|
|
446
|
-
get().refreshBoard(),
|
|
447
|
-
])
|
|
448
|
-
set({ leads: leadsResult.data, leadsTotal: leadsResult.total, summary })
|
|
449
|
-
void get().refreshActivities()
|
|
450
|
-
toast.success('Lead archived')
|
|
451
|
-
} catch (err: any) {
|
|
452
|
-
toast.error('Failed to archive lead', { description: err?.message })
|
|
453
|
-
throw err
|
|
454
|
-
}
|
|
455
|
-
},
|
|
456
|
-
|
|
457
|
-
async archiveQuote(quoteId) {
|
|
458
|
-
try {
|
|
459
|
-
await provider.archiveQuote(quoteId)
|
|
460
|
-
set((state) => ({
|
|
461
|
-
quotes: state.quotes.filter((q) => q.id !== quoteId),
|
|
462
|
-
quotesTotal: Math.max(0, state.quotesTotal - 1),
|
|
463
|
-
}))
|
|
464
|
-
void get().refreshActivities()
|
|
465
|
-
toast.success('Quote archived')
|
|
466
|
-
} catch (err: any) {
|
|
467
|
-
toast.error('Failed to archive quote', { description: err?.message })
|
|
468
|
-
throw err
|
|
469
|
-
}
|
|
470
|
-
},
|
|
471
|
-
}))
|
|
472
|
-
}
|