@contractspec/example.crm-pipeline 3.7.6 → 3.7.7

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.
Files changed (105) hide show
  1. package/.turbo/turbo-build.log +8 -8
  2. package/AGENTS.md +51 -33
  3. package/README.md +66 -148
  4. package/dist/browser/events/contact.event.js +1 -1
  5. package/dist/browser/events/deal.event.js +1 -1
  6. package/dist/browser/events/index.js +3 -3
  7. package/dist/browser/events/task.event.js +1 -1
  8. package/dist/browser/index.js +293 -293
  9. package/dist/browser/ui/CrmDashboard.js +221 -221
  10. package/dist/browser/ui/CrmDealCard.js +5 -5
  11. package/dist/browser/ui/CrmPipelineBoard.js +13 -13
  12. package/dist/browser/ui/hooks/index.js +2 -2
  13. package/dist/browser/ui/hooks/useDealList.js +1 -1
  14. package/dist/browser/ui/hooks/useDealMutations.js +1 -1
  15. package/dist/browser/ui/index.js +290 -290
  16. package/dist/browser/ui/modals/CreateDealModal.js +12 -12
  17. package/dist/browser/ui/modals/DealActionsModal.js +21 -21
  18. package/dist/browser/ui/modals/index.js +33 -33
  19. package/dist/browser/ui/renderers/index.js +116 -116
  20. package/dist/browser/ui/renderers/pipeline.renderer.js +97 -97
  21. package/dist/deal/index.d.ts +2 -2
  22. package/dist/events/contact.event.js +1 -1
  23. package/dist/events/deal.event.js +1 -1
  24. package/dist/events/index.js +3 -3
  25. package/dist/events/task.event.js +1 -1
  26. package/dist/handlers/index.d.ts +2 -2
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +293 -293
  29. package/dist/node/events/contact.event.js +1 -1
  30. package/dist/node/events/deal.event.js +1 -1
  31. package/dist/node/events/index.js +3 -3
  32. package/dist/node/events/task.event.js +1 -1
  33. package/dist/node/index.js +293 -293
  34. package/dist/node/ui/CrmDashboard.js +221 -221
  35. package/dist/node/ui/CrmDealCard.js +5 -5
  36. package/dist/node/ui/CrmPipelineBoard.js +13 -13
  37. package/dist/node/ui/hooks/index.js +2 -2
  38. package/dist/node/ui/hooks/useDealList.js +1 -1
  39. package/dist/node/ui/hooks/useDealMutations.js +1 -1
  40. package/dist/node/ui/index.js +290 -290
  41. package/dist/node/ui/modals/CreateDealModal.js +12 -12
  42. package/dist/node/ui/modals/DealActionsModal.js +21 -21
  43. package/dist/node/ui/modals/index.js +33 -33
  44. package/dist/node/ui/renderers/index.js +116 -116
  45. package/dist/node/ui/renderers/pipeline.renderer.js +97 -97
  46. package/dist/operations/index.d.ts +1 -1
  47. package/dist/ui/CrmDashboard.js +221 -221
  48. package/dist/ui/CrmDealCard.js +5 -5
  49. package/dist/ui/CrmPipelineBoard.js +13 -13
  50. package/dist/ui/hooks/index.d.ts +2 -2
  51. package/dist/ui/hooks/index.js +2 -2
  52. package/dist/ui/hooks/useDealList.js +1 -1
  53. package/dist/ui/hooks/useDealMutations.d.ts +9 -0
  54. package/dist/ui/hooks/useDealMutations.js +1 -1
  55. package/dist/ui/index.d.ts +3 -3
  56. package/dist/ui/index.js +290 -290
  57. package/dist/ui/modals/CreateDealModal.js +12 -12
  58. package/dist/ui/modals/DealActionsModal.js +21 -21
  59. package/dist/ui/modals/index.js +33 -33
  60. package/dist/ui/renderers/index.d.ts +1 -1
  61. package/dist/ui/renderers/index.js +116 -116
  62. package/dist/ui/renderers/pipeline.renderer.d.ts +1 -1
  63. package/dist/ui/renderers/pipeline.renderer.js +97 -97
  64. package/package.json +10 -10
  65. package/src/crm-pipeline.feature.ts +86 -86
  66. package/src/deal/deal.enum.ts +8 -8
  67. package/src/deal/deal.operation.ts +255 -255
  68. package/src/deal/deal.schema.ts +92 -92
  69. package/src/deal/deal.test-spec.ts +48 -48
  70. package/src/deal/index.ts +17 -19
  71. package/src/docs/crm-pipeline.docblock.ts +43 -43
  72. package/src/entities/company.entity.ts +52 -52
  73. package/src/entities/contact.entity.ts +67 -67
  74. package/src/entities/deal.entity.ts +134 -134
  75. package/src/entities/index.ts +27 -27
  76. package/src/entities/task.entity.ts +105 -105
  77. package/src/events/contact.event.ts +22 -22
  78. package/src/events/deal.event.ts +77 -77
  79. package/src/events/task.event.ts +19 -19
  80. package/src/example.ts +32 -32
  81. package/src/handlers/crm.handlers.ts +358 -357
  82. package/src/handlers/deal.handlers.ts +179 -179
  83. package/src/handlers/index.ts +18 -19
  84. package/src/handlers/mock-data.ts +167 -167
  85. package/src/index.ts +11 -11
  86. package/src/operations/index.ts +16 -16
  87. package/src/presentations/dashboard.presentation.ts +45 -45
  88. package/src/presentations/pipeline.presentation.ts +90 -90
  89. package/src/seeders/index.ts +26 -26
  90. package/src/shared/overlay-types.ts +23 -23
  91. package/src/ui/CrmDashboard.tsx +256 -256
  92. package/src/ui/CrmDealCard.tsx +64 -64
  93. package/src/ui/CrmPipelineBoard.tsx +105 -105
  94. package/src/ui/hooks/index.ts +3 -3
  95. package/src/ui/hooks/useDealList.ts +85 -85
  96. package/src/ui/hooks/useDealMutations.ts +151 -150
  97. package/src/ui/index.ts +5 -10
  98. package/src/ui/modals/CreateDealModal.tsx +217 -217
  99. package/src/ui/modals/DealActionsModal.tsx +390 -390
  100. package/src/ui/overlays/demo-overlays.ts +43 -43
  101. package/src/ui/renderers/index.ts +4 -3
  102. package/src/ui/renderers/pipeline.markdown.ts +165 -165
  103. package/src/ui/renderers/pipeline.renderer.tsx +17 -16
  104. package/tsconfig.json +7 -8
  105. package/tsdown.config.js +7 -3
@@ -7,80 +7,81 @@
7
7
  import type { DatabasePort, DbRow } from '@contractspec/lib.runtime-sandbox';
8
8
  /* eslint-disable @typescript-eslint/no-non-null-assertion */
9
9
  import { web } from '@contractspec/lib.runtime-sandbox';
10
+
10
11
  const { generateId } = web;
11
12
 
12
13
  // ============ Types ============
13
14
 
14
15
  export interface Deal {
15
- id: string;
16
- projectId: string;
17
- name: string;
18
- value: number;
19
- currency: string;
20
- pipelineId: string;
21
- stageId: string;
22
- status: 'OPEN' | 'WON' | 'LOST' | 'STALE';
23
- contactId?: string;
24
- companyId?: string;
25
- ownerId: string;
26
- expectedCloseDate?: Date;
27
- wonSource?: string;
28
- lostReason?: string;
29
- notes?: string;
30
- createdAt: Date;
31
- updatedAt: Date;
16
+ id: string;
17
+ projectId: string;
18
+ name: string;
19
+ value: number;
20
+ currency: string;
21
+ pipelineId: string;
22
+ stageId: string;
23
+ status: 'OPEN' | 'WON' | 'LOST' | 'STALE';
24
+ contactId?: string;
25
+ companyId?: string;
26
+ ownerId: string;
27
+ expectedCloseDate?: Date;
28
+ wonSource?: string;
29
+ lostReason?: string;
30
+ notes?: string;
31
+ createdAt: Date;
32
+ updatedAt: Date;
32
33
  }
33
34
 
34
35
  export interface Stage {
35
- id: string;
36
- pipelineId: string;
37
- name: string;
38
- position: number;
36
+ id: string;
37
+ pipelineId: string;
38
+ name: string;
39
+ position: number;
39
40
  }
40
41
 
41
42
  export interface CreateDealInput {
42
- name: string;
43
- value: number;
44
- currency?: string;
45
- pipelineId: string;
46
- stageId: string;
47
- contactId?: string;
48
- companyId?: string;
49
- expectedCloseDate?: Date;
43
+ name: string;
44
+ value: number;
45
+ currency?: string;
46
+ pipelineId: string;
47
+ stageId: string;
48
+ contactId?: string;
49
+ companyId?: string;
50
+ expectedCloseDate?: Date;
50
51
  }
51
52
 
52
53
  export interface MoveDealInput {
53
- dealId: string;
54
- stageId: string;
54
+ dealId: string;
55
+ stageId: string;
55
56
  }
56
57
 
57
58
  export interface WinDealInput {
58
- dealId: string;
59
- wonSource?: string;
60
- notes?: string;
59
+ dealId: string;
60
+ wonSource?: string;
61
+ notes?: string;
61
62
  }
62
63
 
63
64
  export interface LoseDealInput {
64
- dealId: string;
65
- lostReason: string;
66
- notes?: string;
65
+ dealId: string;
66
+ lostReason: string;
67
+ notes?: string;
67
68
  }
68
69
 
69
70
  export interface ListDealsInput {
70
- projectId: string;
71
- pipelineId?: string;
72
- stageId?: string;
73
- status?: 'OPEN' | 'WON' | 'LOST' | 'all';
74
- ownerId?: string;
75
- search?: string;
76
- limit?: number;
77
- offset?: number;
71
+ projectId: string;
72
+ pipelineId?: string;
73
+ stageId?: string;
74
+ status?: 'OPEN' | 'WON' | 'LOST' | 'all';
75
+ ownerId?: string;
76
+ search?: string;
77
+ limit?: number;
78
+ offset?: number;
78
79
  }
79
80
 
80
81
  export interface ListDealsOutput {
81
- deals: Deal[];
82
- total: number;
83
- totalValue: number;
82
+ deals: Deal[];
83
+ total: number;
84
+ totalValue: number;
84
85
  }
85
86
 
86
87
  // ============ Row Type ============
@@ -89,327 +90,327 @@ export interface ListDealsOutput {
89
90
  // to the expected types since we know the schema
90
91
 
91
92
  interface DealRow {
92
- id: string;
93
- projectId: string;
94
- name: string;
95
- value: number;
96
- currency: string;
97
- pipelineId: string;
98
- stageId: string;
99
- status: string;
100
- contactId: string | null;
101
- companyId: string | null;
102
- ownerId: string;
103
- expectedCloseDate: string | null;
104
- wonSource: string | null;
105
- lostReason: string | null;
106
- notes: string | null;
107
- createdAt: string;
108
- updatedAt: string;
93
+ id: string;
94
+ projectId: string;
95
+ name: string;
96
+ value: number;
97
+ currency: string;
98
+ pipelineId: string;
99
+ stageId: string;
100
+ status: string;
101
+ contactId: string | null;
102
+ companyId: string | null;
103
+ ownerId: string;
104
+ expectedCloseDate: string | null;
105
+ wonSource: string | null;
106
+ lostReason: string | null;
107
+ notes: string | null;
108
+ createdAt: string;
109
+ updatedAt: string;
109
110
  }
110
111
 
111
112
  interface StageRow {
112
- id: string;
113
- pipelineId: string;
114
- name: string;
115
- position: number;
113
+ id: string;
114
+ pipelineId: string;
115
+ name: string;
116
+ position: number;
116
117
  }
117
118
 
118
119
  function rowToDeal(row: DealRow): Deal {
119
- return {
120
- id: row.id,
121
- projectId: row.projectId,
122
- name: row.name,
123
- value: row.value,
124
- currency: row.currency,
125
- pipelineId: row.pipelineId,
126
- stageId: row.stageId,
127
- status: row.status as Deal['status'],
128
- contactId: row.contactId ?? undefined,
129
- companyId: row.companyId ?? undefined,
130
- ownerId: row.ownerId,
131
- expectedCloseDate: row.expectedCloseDate
132
- ? new Date(row.expectedCloseDate)
133
- : undefined,
134
- wonSource: row.wonSource ?? undefined,
135
- lostReason: row.lostReason ?? undefined,
136
- notes: row.notes ?? undefined,
137
- createdAt: new Date(row.createdAt),
138
- updatedAt: new Date(row.updatedAt),
139
- };
120
+ return {
121
+ id: row.id,
122
+ projectId: row.projectId,
123
+ name: row.name,
124
+ value: row.value,
125
+ currency: row.currency,
126
+ pipelineId: row.pipelineId,
127
+ stageId: row.stageId,
128
+ status: row.status as Deal['status'],
129
+ contactId: row.contactId ?? undefined,
130
+ companyId: row.companyId ?? undefined,
131
+ ownerId: row.ownerId,
132
+ expectedCloseDate: row.expectedCloseDate
133
+ ? new Date(row.expectedCloseDate)
134
+ : undefined,
135
+ wonSource: row.wonSource ?? undefined,
136
+ lostReason: row.lostReason ?? undefined,
137
+ notes: row.notes ?? undefined,
138
+ createdAt: new Date(row.createdAt),
139
+ updatedAt: new Date(row.updatedAt),
140
+ };
140
141
  }
141
142
 
142
143
  // ============ Handler Factory ============
143
144
 
144
145
  export function createCrmHandlers(db: DatabasePort) {
145
- /**
146
- * List deals with filtering
147
- */
148
- async function listDeals(input: ListDealsInput): Promise<ListDealsOutput> {
149
- const {
150
- projectId,
151
- pipelineId,
152
- stageId,
153
- status,
154
- ownerId,
155
- search,
156
- limit = 20,
157
- offset = 0,
158
- } = input;
159
-
160
- let whereClause = 'WHERE projectId = ?';
161
- const params: (string | number)[] = [projectId];
162
-
163
- if (pipelineId) {
164
- whereClause += ' AND pipelineId = ?';
165
- params.push(pipelineId);
166
- }
167
-
168
- if (stageId) {
169
- whereClause += ' AND stageId = ?';
170
- params.push(stageId);
171
- }
172
-
173
- if (status && status !== 'all') {
174
- whereClause += ' AND status = ?';
175
- params.push(status);
176
- }
177
-
178
- if (ownerId) {
179
- whereClause += ' AND ownerId = ?';
180
- params.push(ownerId);
181
- }
182
-
183
- if (search) {
184
- whereClause += ' AND name LIKE ?';
185
- params.push(`%${search}%`);
186
- }
187
-
188
- // Get total count
189
- const countResult = (
190
- await db.query(
191
- `SELECT COUNT(*) as count FROM crm_deal ${whereClause}`,
192
- params
193
- )
194
- ).rows as DbRow[];
195
- const total = (countResult[0]?.count as number) ?? 0;
196
-
197
- // Get total value
198
- const valueResult = (
199
- await db.query(
200
- `SELECT COALESCE(SUM(value), 0) as total FROM crm_deal ${whereClause}`,
201
- params
202
- )
203
- ).rows as DbRow[];
204
- const totalValue = (valueResult[0]?.total as number) ?? 0;
205
-
206
- // Get paginated deals
207
- const dealRows = (
208
- await db.query(
209
- `SELECT * FROM crm_deal ${whereClause} ORDER BY value DESC LIMIT ? OFFSET ?`,
210
- [...params, limit, offset]
211
- )
212
- ).rows as unknown as DealRow[];
213
-
214
- return {
215
- deals: dealRows.map(rowToDeal),
216
- total,
217
- totalValue,
218
- };
219
- }
220
-
221
- /**
222
- * Create a new deal
223
- */
224
- async function createDeal(
225
- input: CreateDealInput,
226
- context: { projectId: string; ownerId: string }
227
- ): Promise<Deal> {
228
- const id = generateId('deal');
229
- const now = new Date().toISOString();
230
-
231
- await db.execute(
232
- `INSERT INTO crm_deal (id, projectId, pipelineId, stageId, name, value, currency, status, contactId, companyId, ownerId, expectedCloseDate, createdAt, updatedAt)
146
+ /**
147
+ * List deals with filtering
148
+ */
149
+ async function listDeals(input: ListDealsInput): Promise<ListDealsOutput> {
150
+ const {
151
+ projectId,
152
+ pipelineId,
153
+ stageId,
154
+ status,
155
+ ownerId,
156
+ search,
157
+ limit = 20,
158
+ offset = 0,
159
+ } = input;
160
+
161
+ let whereClause = 'WHERE projectId = ?';
162
+ const params: (string | number)[] = [projectId];
163
+
164
+ if (pipelineId) {
165
+ whereClause += ' AND pipelineId = ?';
166
+ params.push(pipelineId);
167
+ }
168
+
169
+ if (stageId) {
170
+ whereClause += ' AND stageId = ?';
171
+ params.push(stageId);
172
+ }
173
+
174
+ if (status && status !== 'all') {
175
+ whereClause += ' AND status = ?';
176
+ params.push(status);
177
+ }
178
+
179
+ if (ownerId) {
180
+ whereClause += ' AND ownerId = ?';
181
+ params.push(ownerId);
182
+ }
183
+
184
+ if (search) {
185
+ whereClause += ' AND name LIKE ?';
186
+ params.push(`%${search}%`);
187
+ }
188
+
189
+ // Get total count
190
+ const countResult = (
191
+ await db.query(
192
+ `SELECT COUNT(*) as count FROM crm_deal ${whereClause}`,
193
+ params
194
+ )
195
+ ).rows as DbRow[];
196
+ const total = (countResult[0]?.count as number) ?? 0;
197
+
198
+ // Get total value
199
+ const valueResult = (
200
+ await db.query(
201
+ `SELECT COALESCE(SUM(value), 0) as total FROM crm_deal ${whereClause}`,
202
+ params
203
+ )
204
+ ).rows as DbRow[];
205
+ const totalValue = (valueResult[0]?.total as number) ?? 0;
206
+
207
+ // Get paginated deals
208
+ const dealRows = (
209
+ await db.query(
210
+ `SELECT * FROM crm_deal ${whereClause} ORDER BY value DESC LIMIT ? OFFSET ?`,
211
+ [...params, limit, offset]
212
+ )
213
+ ).rows as unknown as DealRow[];
214
+
215
+ return {
216
+ deals: dealRows.map(rowToDeal),
217
+ total,
218
+ totalValue,
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Create a new deal
224
+ */
225
+ async function createDeal(
226
+ input: CreateDealInput,
227
+ context: { projectId: string; ownerId: string }
228
+ ): Promise<Deal> {
229
+ const id = generateId('deal');
230
+ const now = new Date().toISOString();
231
+
232
+ await db.execute(
233
+ `INSERT INTO crm_deal (id, projectId, pipelineId, stageId, name, value, currency, status, contactId, companyId, ownerId, expectedCloseDate, createdAt, updatedAt)
233
234
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
234
- [
235
- id,
236
- context.projectId,
237
- input.pipelineId,
238
- input.stageId,
239
- input.name,
240
- input.value,
241
- input.currency ?? 'USD',
242
- 'OPEN',
243
- input.contactId ?? null,
244
- input.companyId ?? null,
245
- context.ownerId,
246
- input.expectedCloseDate?.toISOString() ?? null,
247
- now,
248
- now,
249
- ]
250
- );
251
-
252
- const rows = (await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [id]))
253
- .rows as unknown as DealRow[];
254
-
255
- if (!rows[0]) {
256
- throw new Error('Failed to create deal');
257
- }
258
-
259
- return rowToDeal(rows[0]);
260
- }
261
-
262
- /**
263
- * Move a deal to a different stage
264
- */
265
- async function moveDeal(input: MoveDealInput): Promise<Deal> {
266
- const now = new Date().toISOString();
267
-
268
- // Verify deal exists
269
- const existing = (
270
- await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
271
- ).rows as unknown as DealRow[];
272
-
273
- if (!existing[0]) {
274
- throw new Error('NOT_FOUND');
275
- }
276
-
277
- // Verify stage exists
278
- const stage = (
279
- await db.query(`SELECT * FROM crm_stage WHERE id = ?`, [input.stageId])
280
- ).rows as unknown as StageRow[];
281
-
282
- if (!stage[0]) {
283
- throw new Error('INVALID_STAGE');
284
- }
285
-
286
- await db.execute(
287
- `UPDATE crm_deal SET stageId = ?, updatedAt = ? WHERE id = ?`,
288
- [input.stageId, now, input.dealId]
289
- );
290
-
291
- const rows = (
292
- await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
293
- ).rows as unknown as DealRow[];
294
-
295
- return rowToDeal(rows[0]!);
296
- }
297
-
298
- /**
299
- * Mark a deal as won
300
- */
301
- async function winDeal(input: WinDealInput): Promise<Deal> {
302
- const now = new Date().toISOString();
303
-
304
- // Verify deal exists
305
- const existing = (
306
- await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
307
- ).rows as unknown as DealRow[];
308
-
309
- if (!existing[0]) {
310
- throw new Error('NOT_FOUND');
311
- }
312
-
313
- await db.execute(
314
- `UPDATE crm_deal SET status = 'WON', wonSource = ?, notes = ?, updatedAt = ? WHERE id = ?`,
315
- [input.wonSource ?? null, input.notes ?? null, now, input.dealId]
316
- );
317
-
318
- const rows = (
319
- await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
320
- ).rows as unknown as DealRow[];
321
-
322
- return rowToDeal(rows[0]!);
323
- }
324
-
325
- /**
326
- * Mark a deal as lost
327
- */
328
- async function loseDeal(input: LoseDealInput): Promise<Deal> {
329
- const now = new Date().toISOString();
330
-
331
- // Verify deal exists
332
- const existing = (
333
- await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
334
- ).rows as unknown as DealRow[];
335
-
336
- if (!existing[0]) {
337
- throw new Error('NOT_FOUND');
338
- }
339
-
340
- await db.execute(
341
- `UPDATE crm_deal SET status = 'LOST', lostReason = ?, notes = ?, updatedAt = ? WHERE id = ?`,
342
- [input.lostReason, input.notes ?? null, now, input.dealId]
343
- );
344
-
345
- const rows = (
346
- await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
347
- ).rows as unknown as DealRow[];
348
-
349
- return rowToDeal(rows[0]!);
350
- }
351
-
352
- /**
353
- * Get deals grouped by stage
354
- */
355
- async function getDealsByStage(input: {
356
- projectId: string;
357
- pipelineId: string;
358
- }): Promise<Record<string, Deal[]>> {
359
- const deals = (
360
- await db.query(
361
- `SELECT * FROM crm_deal WHERE projectId = ? AND pipelineId = ? AND status = 'OPEN' ORDER BY value DESC`,
362
- [input.projectId, input.pipelineId]
363
- )
364
- ).rows as unknown as DealRow[];
365
-
366
- const stages = (
367
- await db.query(
368
- `SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position`,
369
- [input.pipelineId]
370
- )
371
- ).rows as unknown as StageRow[];
372
-
373
- const grouped: Record<string, Deal[]> = {};
374
- for (const stage of stages) {
375
- grouped[stage.id] = deals
376
- .filter((d) => d.stageId === stage.id)
377
- .map(rowToDeal);
378
- }
379
-
380
- return grouped;
381
- }
382
-
383
- /**
384
- * Get pipeline stages
385
- */
386
- async function getPipelineStages(input: {
387
- pipelineId: string;
388
- }): Promise<Stage[]> {
389
- const rows = (
390
- await db.query(
391
- `SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position`,
392
- [input.pipelineId]
393
- )
394
- ).rows as unknown as StageRow[];
395
-
396
- return rows.map((row) => ({
397
- id: row.id,
398
- pipelineId: row.pipelineId,
399
- name: row.name,
400
- position: row.position,
401
- }));
402
- }
403
-
404
- return {
405
- listDeals,
406
- createDeal,
407
- moveDeal,
408
- winDeal,
409
- loseDeal,
410
- getDealsByStage,
411
- getPipelineStages,
412
- };
235
+ [
236
+ id,
237
+ context.projectId,
238
+ input.pipelineId,
239
+ input.stageId,
240
+ input.name,
241
+ input.value,
242
+ input.currency ?? 'USD',
243
+ 'OPEN',
244
+ input.contactId ?? null,
245
+ input.companyId ?? null,
246
+ context.ownerId,
247
+ input.expectedCloseDate?.toISOString() ?? null,
248
+ now,
249
+ now,
250
+ ]
251
+ );
252
+
253
+ const rows = (await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [id]))
254
+ .rows as unknown as DealRow[];
255
+
256
+ if (!rows[0]) {
257
+ throw new Error('Failed to create deal');
258
+ }
259
+
260
+ return rowToDeal(rows[0]);
261
+ }
262
+
263
+ /**
264
+ * Move a deal to a different stage
265
+ */
266
+ async function moveDeal(input: MoveDealInput): Promise<Deal> {
267
+ const now = new Date().toISOString();
268
+
269
+ // Verify deal exists
270
+ const existing = (
271
+ await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
272
+ ).rows as unknown as DealRow[];
273
+
274
+ if (!existing[0]) {
275
+ throw new Error('NOT_FOUND');
276
+ }
277
+
278
+ // Verify stage exists
279
+ const stage = (
280
+ await db.query(`SELECT * FROM crm_stage WHERE id = ?`, [input.stageId])
281
+ ).rows as unknown as StageRow[];
282
+
283
+ if (!stage[0]) {
284
+ throw new Error('INVALID_STAGE');
285
+ }
286
+
287
+ await db.execute(
288
+ `UPDATE crm_deal SET stageId = ?, updatedAt = ? WHERE id = ?`,
289
+ [input.stageId, now, input.dealId]
290
+ );
291
+
292
+ const rows = (
293
+ await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
294
+ ).rows as unknown as DealRow[];
295
+
296
+ return rowToDeal(rows[0]!);
297
+ }
298
+
299
+ /**
300
+ * Mark a deal as won
301
+ */
302
+ async function winDeal(input: WinDealInput): Promise<Deal> {
303
+ const now = new Date().toISOString();
304
+
305
+ // Verify deal exists
306
+ const existing = (
307
+ await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
308
+ ).rows as unknown as DealRow[];
309
+
310
+ if (!existing[0]) {
311
+ throw new Error('NOT_FOUND');
312
+ }
313
+
314
+ await db.execute(
315
+ `UPDATE crm_deal SET status = 'WON', wonSource = ?, notes = ?, updatedAt = ? WHERE id = ?`,
316
+ [input.wonSource ?? null, input.notes ?? null, now, input.dealId]
317
+ );
318
+
319
+ const rows = (
320
+ await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
321
+ ).rows as unknown as DealRow[];
322
+
323
+ return rowToDeal(rows[0]!);
324
+ }
325
+
326
+ /**
327
+ * Mark a deal as lost
328
+ */
329
+ async function loseDeal(input: LoseDealInput): Promise<Deal> {
330
+ const now = new Date().toISOString();
331
+
332
+ // Verify deal exists
333
+ const existing = (
334
+ await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
335
+ ).rows as unknown as DealRow[];
336
+
337
+ if (!existing[0]) {
338
+ throw new Error('NOT_FOUND');
339
+ }
340
+
341
+ await db.execute(
342
+ `UPDATE crm_deal SET status = 'LOST', lostReason = ?, notes = ?, updatedAt = ? WHERE id = ?`,
343
+ [input.lostReason, input.notes ?? null, now, input.dealId]
344
+ );
345
+
346
+ const rows = (
347
+ await db.query(`SELECT * FROM crm_deal WHERE id = ?`, [input.dealId])
348
+ ).rows as unknown as DealRow[];
349
+
350
+ return rowToDeal(rows[0]!);
351
+ }
352
+
353
+ /**
354
+ * Get deals grouped by stage
355
+ */
356
+ async function getDealsByStage(input: {
357
+ projectId: string;
358
+ pipelineId: string;
359
+ }): Promise<Record<string, Deal[]>> {
360
+ const deals = (
361
+ await db.query(
362
+ `SELECT * FROM crm_deal WHERE projectId = ? AND pipelineId = ? AND status = 'OPEN' ORDER BY value DESC`,
363
+ [input.projectId, input.pipelineId]
364
+ )
365
+ ).rows as unknown as DealRow[];
366
+
367
+ const stages = (
368
+ await db.query(
369
+ `SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position`,
370
+ [input.pipelineId]
371
+ )
372
+ ).rows as unknown as StageRow[];
373
+
374
+ const grouped: Record<string, Deal[]> = {};
375
+ for (const stage of stages) {
376
+ grouped[stage.id] = deals
377
+ .filter((d) => d.stageId === stage.id)
378
+ .map(rowToDeal);
379
+ }
380
+
381
+ return grouped;
382
+ }
383
+
384
+ /**
385
+ * Get pipeline stages
386
+ */
387
+ async function getPipelineStages(input: {
388
+ pipelineId: string;
389
+ }): Promise<Stage[]> {
390
+ const rows = (
391
+ await db.query(
392
+ `SELECT * FROM crm_stage WHERE pipelineId = ? ORDER BY position`,
393
+ [input.pipelineId]
394
+ )
395
+ ).rows as unknown as StageRow[];
396
+
397
+ return rows.map((row) => ({
398
+ id: row.id,
399
+ pipelineId: row.pipelineId,
400
+ name: row.name,
401
+ position: row.position,
402
+ }));
403
+ }
404
+
405
+ return {
406
+ listDeals,
407
+ createDeal,
408
+ moveDeal,
409
+ winDeal,
410
+ loseDeal,
411
+ getDealsByStage,
412
+ getPipelineStages,
413
+ };
413
414
  }
414
415
 
415
416
  export type CrmHandlers = ReturnType<typeof createCrmHandlers>;