-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathuser-table.test.ts
More file actions
508 lines (459 loc) · 16.3 KB
/
Copy pathuser-table.test.ts
File metadata and controls
508 lines (459 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/**
* @vitest-environment node
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { TableDefinition } from '@/lib/table'
const {
mockResolveWorkspaceFileReference,
mockDownloadWorkspaceFile,
mockGetTableById,
mockBatchInsertRows,
mockReplaceTableRows,
mockAddWorkflowGroup,
mockCreateTable,
mockDeleteTable,
mockGetWorkspaceTableLimits,
fakeEnrichment,
} = vi.hoisted(() => ({
mockResolveWorkspaceFileReference: vi.fn(),
mockDownloadWorkspaceFile: vi.fn(),
mockGetTableById: vi.fn(),
mockBatchInsertRows: vi.fn(),
mockReplaceTableRows: vi.fn(),
mockAddWorkflowGroup: vi.fn(),
mockCreateTable: vi.fn(),
mockDeleteTable: vi.fn(),
mockGetWorkspaceTableLimits: vi.fn(),
fakeEnrichment: {
id: 'work-email',
name: 'Work Email',
description: 'Find work email',
icon: () => null,
inputs: [
{ id: 'fullName', name: 'Full name', type: 'string', required: true },
{ id: 'companyDomain', name: 'Company domain', type: 'string', required: true },
],
outputs: [{ id: 'email', name: 'email', type: 'string' }],
providers: [],
},
}))
vi.mock('@sim/utils/id', () => ({
generateId: vi.fn().mockReturnValue('deadbeefcafef00d'),
generateShortId: vi.fn().mockReturnValue('short-id'),
}))
vi.mock('@/lib/uploads/contexts/workspace/workspace-file-manager', () => ({
resolveWorkspaceFileReference: mockResolveWorkspaceFileReference,
fetchWorkspaceFileBuffer: mockDownloadWorkspaceFile,
}))
vi.mock('@/enrichments/registry', () => ({
ALL_ENRICHMENTS: [fakeEnrichment],
getEnrichment: (id: string) => (id === fakeEnrichment.id ? fakeEnrichment : undefined),
}))
vi.mock('@/lib/table/service', () => ({
createTable: mockCreateTable,
deleteTable: mockDeleteTable,
getTableById: mockGetTableById,
renameTable: vi.fn(),
}))
vi.mock('@/lib/table/workflow-groups/service', () => ({
addWorkflowGroup: mockAddWorkflowGroup,
addWorkflowGroupOutput: vi.fn(),
deleteWorkflowGroup: vi.fn(),
deleteWorkflowGroupOutput: vi.fn(),
updateWorkflowGroup: vi.fn(),
}))
vi.mock('@/lib/table/columns/service', () => ({
addTableColumn: vi.fn(),
deleteColumn: vi.fn(),
deleteColumns: vi.fn(),
renameColumn: vi.fn(),
updateColumnConstraints: vi.fn(),
updateColumnType: vi.fn(),
}))
vi.mock('@/lib/table/rows/service', () => ({
batchInsertRows: mockBatchInsertRows,
batchUpdateRows: vi.fn(),
deleteRow: vi.fn(),
deleteRowsByFilter: vi.fn(),
deleteRowsByIds: vi.fn(),
getRowById: vi.fn(),
insertRow: vi.fn(),
queryRows: vi.fn(),
replaceTableRows: mockReplaceTableRows,
updateRow: vi.fn(),
updateRowsByFilter: vi.fn(),
}))
vi.mock('@/lib/table/billing', () => ({
getWorkspaceTableLimits: mockGetWorkspaceTableLimits,
}))
import { userTableServerTool } from '@/lib/copilot/tools/server/table/user-table'
function buildTable(overrides: Partial<TableDefinition> = {}): TableDefinition {
return {
id: 'tbl_1',
name: 'People',
description: null,
schema: {
columns: [
{ name: 'name', type: 'string', required: true },
{ name: 'age', type: 'number' },
],
},
metadata: null,
rowCount: 0,
maxRows: 100,
workspaceId: 'workspace-1',
createdBy: 'user-1',
archivedAt: null,
createdAt: new Date('2024-01-01'),
updatedAt: new Date('2024-01-01'),
...overrides,
}
}
describe('userTableServerTool.import_file', () => {
beforeEach(() => {
vi.clearAllMocks()
mockResolveWorkspaceFileReference.mockResolvedValue({
name: 'people.csv',
type: 'text/csv',
})
mockDownloadWorkspaceFile.mockResolvedValue(Buffer.from('name,age\nAlice,30\nBob,40'))
mockGetTableById.mockResolvedValue(buildTable())
mockBatchInsertRows.mockImplementation(async (data: { rows: unknown[] }) =>
data.rows.map((_, i) => ({ id: `row_${i}` }))
)
mockReplaceTableRows.mockResolvedValue({ deletedCount: 0, insertedCount: 0 })
})
it('appends rows using auto-mapping by default', async () => {
const result = await userTableServerTool.execute(
{
operation: 'import_file',
args: { tableId: 'tbl_1', fileId: 'file-1' },
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(result.data?.mode).toBe('append')
expect(result.data?.rowCount).toBe(2)
expect(mockBatchInsertRows).toHaveBeenCalledTimes(1)
expect(mockReplaceTableRows).not.toHaveBeenCalled()
const call = mockBatchInsertRows.mock.calls[0][0] as { rows: unknown[] }
expect(call.rows).toEqual([
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 40 },
])
})
it('replaces rows in replace mode', async () => {
mockReplaceTableRows.mockResolvedValueOnce({ deletedCount: 3, insertedCount: 2 })
const result = await userTableServerTool.execute(
{
operation: 'import_file',
args: { tableId: 'tbl_1', fileId: 'file-1', mode: 'replace' },
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(result.data?.mode).toBe('replace')
expect(result.data?.deletedCount).toBe(3)
expect(result.data?.insertedCount).toBe(2)
expect(mockReplaceTableRows).toHaveBeenCalledTimes(1)
expect(mockBatchInsertRows).not.toHaveBeenCalled()
})
it('uses the caller-provided mapping', async () => {
mockDownloadWorkspaceFile.mockResolvedValueOnce(
Buffer.from('Full Name,Years\nAlice,30\nBob,40')
)
const result = await userTableServerTool.execute(
{
operation: 'import_file',
args: {
tableId: 'tbl_1',
fileId: 'file-1',
mapping: { 'Full Name': 'name', Years: 'age' },
},
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
const call = mockBatchInsertRows.mock.calls[0][0] as { rows: unknown[] }
expect(call.rows).toEqual([
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 40 },
])
})
it('rejects unknown modes', async () => {
const result = await userTableServerTool.execute(
{
operation: 'import_file',
args: { tableId: 'tbl_1', fileId: 'file-1', mode: 'merge' },
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(result.message).toMatch(/Invalid mode/)
expect(mockBatchInsertRows).not.toHaveBeenCalled()
})
it('refuses to import into an archived table', async () => {
mockGetTableById.mockResolvedValueOnce(buildTable({ archivedAt: new Date('2024-02-01') }))
const result = await userTableServerTool.execute(
{
operation: 'import_file',
args: { tableId: 'tbl_1', fileId: 'file-1' },
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(result.message).toMatch(/archived/i)
})
it('refuses to import when the table belongs to a different workspace', async () => {
mockGetTableById.mockResolvedValueOnce(buildTable({ workspaceId: 'workspace-other' }))
const result = await userTableServerTool.execute(
{
operation: 'import_file',
args: { tableId: 'tbl_1', fileId: 'file-1' },
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(result.message).toMatch(/not found/i)
expect(mockBatchInsertRows).not.toHaveBeenCalled()
})
it('reports missing required columns instead of inserting', async () => {
mockDownloadWorkspaceFile.mockResolvedValueOnce(Buffer.from('age\n30'))
const result = await userTableServerTool.execute(
{
operation: 'import_file',
args: { tableId: 'tbl_1', fileId: 'file-1' },
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(result.message).toMatch(/missing required columns/i)
expect(mockBatchInsertRows).not.toHaveBeenCalled()
})
})
describe('userTableServerTool.create_from_file', () => {
beforeEach(() => {
vi.clearAllMocks()
mockResolveWorkspaceFileReference.mockResolvedValue({ name: 'people.csv', type: 'text/csv' })
mockDownloadWorkspaceFile.mockResolvedValue(Buffer.from('name,age\nAlice,30\nBob,40'))
mockGetWorkspaceTableLimits.mockResolvedValue({ maxRowsPerTable: 1000, maxTables: 3 })
mockCreateTable.mockResolvedValue(buildTable({ id: 'tbl_new', name: 'people' }))
mockDeleteTable.mockResolvedValue(undefined)
mockBatchInsertRows.mockImplementation(async (data: { rows: unknown[] }) =>
data.rows.map((_, i) => ({ id: `row_${i}` }))
)
})
it('stamps the workspace plan limits on the created table', async () => {
const result = await userTableServerTool.execute(
{ operation: 'create_from_file', args: { fileId: 'file-1' } },
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(mockGetWorkspaceTableLimits).toHaveBeenCalledWith('workspace-1')
expect(mockCreateTable).toHaveBeenCalledTimes(1)
const createArgs = mockCreateTable.mock.calls[0][0] as { maxRows: number; maxTables: number }
expect(createArgs.maxRows).toBe(1000)
expect(createArgs.maxTables).toBe(3)
})
it('truncates to the plan row limit and reports dropped rows', async () => {
// File has 2 data rows (Alice, Bob); plan cap is 1.
mockGetWorkspaceTableLimits.mockResolvedValueOnce({ maxRowsPerTable: 1, maxTables: 3 })
const result = await userTableServerTool.execute(
{ operation: 'create_from_file', args: { fileId: 'file-1' } },
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(mockCreateTable).toHaveBeenCalledTimes(1)
const insertCall = mockBatchInsertRows.mock.calls[0][0] as { rows: unknown[] }
expect(insertCall.rows).toHaveLength(1)
expect(result.data?.rowCount).toBe(1)
expect(result.message).toMatch(/dropped 1 row/i)
expect(mockDeleteTable).not.toHaveBeenCalled()
})
it('rolls back the created table and reports the reason when row insertion fails', async () => {
mockBatchInsertRows.mockRejectedValueOnce(new Error('Row 2: Column "email" must be unique'))
const result = await userTableServerTool.execute(
{ operation: 'create_from_file', args: { fileId: 'file-1' } },
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(mockDeleteTable).toHaveBeenCalledWith('tbl_new', expect.any(String))
expect(result.message).toMatch(/rolled back/i)
expect(result.message).toMatch(/must be unique/i)
})
})
describe('userTableServerTool.create', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetWorkspaceTableLimits.mockResolvedValue({ maxRowsPerTable: 1000, maxTables: 3 })
mockCreateTable.mockResolvedValue(buildTable({ id: 'tbl_new', name: 'People' }))
})
it('stamps the workspace plan limits on the created table', async () => {
const result = await userTableServerTool.execute(
{
operation: 'create',
args: {
name: 'People',
schema: { columns: [{ name: 'name', type: 'string', required: true }] },
},
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(mockGetWorkspaceTableLimits).toHaveBeenCalledWith('workspace-1')
const createArgs = mockCreateTable.mock.calls[0][0] as { maxRows: number; maxTables: number }
expect(createArgs.maxRows).toBe(1000)
expect(createArgs.maxTables).toBe(3)
})
})
describe('userTableServerTool.list_enrichments', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns the enrichment catalog metadata', async () => {
const result = await userTableServerTool.execute(
{ operation: 'list_enrichments', args: {} },
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(result.data?.enrichments).toEqual([
{
id: 'work-email',
name: 'Work Email',
description: 'Find work email',
inputs: [
{ id: 'fullName', name: 'Full name', type: 'string', required: true },
{ id: 'companyDomain', name: 'Company domain', type: 'string', required: true },
],
outputs: [{ id: 'email', name: 'email', type: 'string' }],
},
])
})
})
describe('userTableServerTool.add_enrichment', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetTableById.mockResolvedValue(
buildTable({
schema: {
columns: [
{ name: 'name', type: 'string' },
{ name: 'company', type: 'string' },
],
},
})
)
mockAddWorkflowGroup.mockResolvedValue(buildTable())
})
it('creates an enrichment group with mapped inputs and derived output columns', async () => {
const result = await userTableServerTool.execute(
{
operation: 'add_enrichment',
args: {
tableId: 'tbl_1',
enrichmentId: 'work-email',
inputMappings: [
{ inputName: 'fullName', columnName: 'name' },
{ inputName: 'companyDomain', columnName: 'company' },
],
},
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(result.data?.groupId).toBe('deadbeefcafef00d')
expect(mockAddWorkflowGroup).toHaveBeenCalledTimes(1)
const call = mockAddWorkflowGroup.mock.calls[0][0]
expect(call.autoRun).toBe(false)
expect(call.group).toMatchObject({
type: 'enrichment',
enrichmentId: 'work-email',
workflowId: '',
autoRun: false,
dependencies: { columns: ['name', 'company'] },
inputMappings: [
{ inputName: 'fullName', columnName: 'name' },
{ inputName: 'companyDomain', columnName: 'company' },
],
outputs: [{ blockId: '', path: '', outputId: 'email', columnName: 'email' }],
})
expect(call.outputColumns).toEqual([
{
name: 'email',
type: 'string',
required: false,
unique: false,
workflowGroupId: 'deadbeefcafef00d',
},
])
})
it('enables auto-run when explicitly requested', async () => {
const result = await userTableServerTool.execute(
{
operation: 'add_enrichment',
args: {
tableId: 'tbl_1',
enrichmentId: 'work-email',
inputMappings: [
{ inputName: 'fullName', columnName: 'name' },
{ inputName: 'companyDomain', columnName: 'company' },
],
autoRun: true,
},
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(true)
expect(result.message).toMatch(/auto-run enabled/)
const call = mockAddWorkflowGroup.mock.calls[0][0]
expect(call.autoRun).toBe(true)
expect(call.group.autoRun).toBe(true)
})
it('rejects an unknown enrichment id', async () => {
const result = await userTableServerTool.execute(
{
operation: 'add_enrichment',
args: { tableId: 'tbl_1', enrichmentId: 'nope', inputMappings: [] },
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(result.message).toMatch(/Unknown enrichment/)
expect(mockAddWorkflowGroup).not.toHaveBeenCalled()
})
it('rejects when a required input is unmapped', async () => {
const result = await userTableServerTool.execute(
{
operation: 'add_enrichment',
args: {
tableId: 'tbl_1',
enrichmentId: 'work-email',
inputMappings: [{ inputName: 'fullName', columnName: 'name' }],
},
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(result.message).toMatch(/requires input "companyDomain"/)
expect(mockAddWorkflowGroup).not.toHaveBeenCalled()
})
it('rejects when a mapped column does not exist on the table', async () => {
const result = await userTableServerTool.execute(
{
operation: 'add_enrichment',
args: {
tableId: 'tbl_1',
enrichmentId: 'work-email',
inputMappings: [
{ inputName: 'fullName', columnName: 'name' },
{ inputName: 'companyDomain', columnName: 'missing_col' },
],
},
},
{ userId: 'user-1', workspaceId: 'workspace-1' }
)
expect(result.success).toBe(false)
expect(result.message).toMatch(/does not exist/)
expect(mockAddWorkflowGroup).not.toHaveBeenCalled()
})
})