@svgrid/enterprise 2.2.1 → 2.3.0

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 (101) hide show
  1. package/README.md +95 -81
  2. package/dist/cdn/svgrid-enterprise.svelte-external.js +22468 -10459
  3. package/dist/node/studio.js +11590 -2907
  4. package/package.json +31 -10
  5. package/src/SvAlertRuleEditor.svelte +294 -0
  6. package/src/SvAlertsManager.svelte +210 -0
  7. package/src/SvAlertsPanel.svelte +129 -0
  8. package/src/SvBoard.svelte +3 -1
  9. package/src/SvExpressionEditor.svelte +341 -0
  10. package/src/SvGridAlerts.dom.test.ts +113 -0
  11. package/src/SvGridAlerts.svelte +265 -0
  12. package/src/SvGridBoard.svelte +2355 -0
  13. package/src/SvGridEditPanel.svelte +849 -794
  14. package/src/SvGridScheduler.svelte +5334 -4410
  15. package/src/SvPivotDesigner.svelte +3 -3
  16. package/src/SvRecordDetail.svelte +6 -2
  17. package/src/SvSchedule.svelte +3 -1
  18. package/src/{ai-export-pdf.test.ts → ai-export-pdf.dom.test.ts} +4 -1
  19. package/src/{ai-export-xlsx.test.ts → ai-export-xlsx.dom.test.ts} +4 -1
  20. package/src/{ai-export.test.ts → ai-export.dom.test.ts} +5 -1
  21. package/src/alerts/alert-engine-attach.ts +165 -0
  22. package/src/alerts/alert-engine.test.ts +135 -0
  23. package/src/alerts/alert-engine.ts +260 -0
  24. package/src/alerts/alert-formats.test.ts +87 -0
  25. package/src/alerts/alert-formats.ts +77 -0
  26. package/src/alerts/alert-observer.test.ts +189 -0
  27. package/src/alerts/alert-observer.ts +208 -0
  28. package/src/alerts/alert-scheduler.ts +96 -0
  29. package/src/alerts/alert-storage.test.ts +54 -0
  30. package/src/alerts/alert-storage.ts +116 -0
  31. package/src/alerts/alert-store.svelte.ts +80 -0
  32. package/src/alerts/alert-types.ts +94 -0
  33. package/src/alerts.ts +28 -0
  34. package/src/board.dom.test.ts +941 -0
  35. package/src/board.ts +36 -0
  36. package/src/export.ts +6 -0
  37. package/src/expressions/evaluate.test.ts +111 -0
  38. package/src/expressions/evaluate.ts +228 -0
  39. package/src/expressions/expression-columns.ts +133 -0
  40. package/src/expressions/expression-types.ts +84 -0
  41. package/src/expressions/parse.test.ts +106 -0
  42. package/src/expressions/parse.ts +610 -0
  43. package/src/import.ts +2 -0
  44. package/src/index.ts +180 -46
  45. package/src/install.ts +12 -2
  46. package/src/pivot-enable.ts +44 -0
  47. package/src/scheduler-assignments.test.ts +97 -0
  48. package/src/scheduler-assignments.ts +134 -0
  49. package/src/scheduler-axis.test.ts +108 -0
  50. package/src/scheduler-axis.ts +238 -0
  51. package/src/scheduler-booking.test.ts +57 -0
  52. package/src/scheduler-booking.ts +63 -0
  53. package/src/scheduler-config.ts +179 -0
  54. package/src/scheduler-dependencies.test.ts +155 -0
  55. package/src/scheduler-dependencies.ts +223 -0
  56. package/src/scheduler-freebusy.test.ts +41 -0
  57. package/src/scheduler-freebusy.ts +36 -0
  58. package/src/scheduler-heatmap.test.ts +39 -0
  59. package/src/scheduler-heatmap.ts +55 -0
  60. package/src/scheduler-resource-tree.test.ts +84 -0
  61. package/src/scheduler-resource-tree.ts +107 -0
  62. package/src/scheduler-slots.test.ts +53 -0
  63. package/src/scheduler-slots.ts +94 -0
  64. package/src/scheduler-summary.test.ts +47 -0
  65. package/src/scheduler-summary.ts +81 -0
  66. package/src/sources/index.ts +1 -1
  67. package/src/sources/introspect-supabase.test.ts +13 -1
  68. package/src/sources/introspect-supabase.ts +20 -0
  69. package/src/studio/copilot-core.test.ts +45 -0
  70. package/src/studio/copilot-core.ts +65 -0
  71. package/src/studio/deploy-cli.test.ts +56 -0
  72. package/src/studio/deploy-cli.ts +100 -0
  73. package/src/studio/emit-project.test.ts +503 -18
  74. package/src/studio/emit-project.ts +829 -111
  75. package/src/studio/emit-schema.test.ts +17 -0
  76. package/src/studio/emit-schema.ts +166 -35
  77. package/src/studio/index.ts +25 -1
  78. package/src/studio/introspect-openapi.test.ts +84 -0
  79. package/src/studio/introspect-openapi.ts +252 -0
  80. package/src/studio/project.test.ts +57 -0
  81. package/src/studio/project.ts +193 -6
  82. package/src/studio/samples/crm.ts +282 -258
  83. package/src/studio/samples/fleet.ts +213 -186
  84. package/src/studio/samples/insurance.ts +223 -195
  85. package/src/studio/samples/inventory.ts +213 -182
  86. package/src/studio/samples/live-data.test.ts +99 -98
  87. package/src/studio/samples/live-data.ts +8 -10
  88. package/src/studio/samples/projects.ts +212 -190
  89. package/src/studio/samples/samples.test.ts +52 -0
  90. package/src/studio/samples/shared.ts +26 -6
  91. package/src/studio/samples/starter.ts +251 -0
  92. package/src/studio/samples/support.ts +209 -184
  93. package/src/studio/ui-components-surface.test.ts +185 -0
  94. package/src/studio/ui-components.generated.ts +5617 -0
  95. package/src/studio/ui-components.ts +641 -472
  96. package/src/sveltekit/sql-source.test.ts +13 -0
  97. package/src/sveltekit/sql-source.ts +11 -6
  98. package/src/upgrade-prompt.ts +2 -2
  99. package/src/watermark.ts +2 -2
  100. package/src/ai.test.ts +0 -522
  101. package/src/ai.ts +0 -1388
@@ -63,6 +63,19 @@ describe('createSqlDataSource reads', () => {
63
63
  expect(calls[1]!.params).toEqual([20])
64
64
  })
65
65
 
66
+ it('schema-qualifies the table as "schema"."table" when dbSchema is set', async () => {
67
+ const { execute, calls } = recorder([[{ id: '1' }], [{ count: 1 }]])
68
+ const src = createSqlDataSource({ schema, table: 'customers', dbSchema: 'analytics', execute })
69
+ await src.getRows(req({}))
70
+ expect(calls[0]!.sql).toContain('FROM "analytics"."customers"')
71
+ expect(calls[1]!.sql).toContain('FROM "analytics"."customers"')
72
+ // Writes are qualified too.
73
+ const { execute: ex2, calls: c2 } = recorder([[{ id: '9' }]])
74
+ const src2 = createSqlDataSource({ schema, table: 'customers', dbSchema: 'analytics', execute: ex2 })
75
+ await src2.createRow({ name: 'Zed' } as never)
76
+ expect(c2[0]!.sql).toContain('INSERT INTO "analytics"."customers"')
77
+ })
78
+
66
79
  it('honors the Postgres dialect ($ placeholders)', async () => {
67
80
  const { execute, calls } = recorder([[], [{ count: 0 }]])
68
81
  const src = createSqlDataSource({
@@ -41,6 +41,9 @@ export type SqlDataSourceConfig<TData extends RowData> = {
41
41
  schema: EntitySchema<TData>
42
42
  /** Table (or view) name. Quoted per the dialect; not interpolated raw. */
43
43
  table: string
44
+ /** DB schema / namespace (e.g. Postgres `public`, SQL Server `dbo`). When set,
45
+ * the table is addressed as `"schema"."table"`. Each part is quoted separately. */
46
+ dbSchema?: string
44
47
  execute: SqlExecutor
45
48
  dialect?: SqlDialect
46
49
  /**
@@ -76,6 +79,8 @@ export function createSqlDataSource<TData extends RowData>(
76
79
  const returning = config.returning ?? true
77
80
  const id = quoter(dialect)
78
81
  const idField = resolveIdField(schema)
82
+ // Optionally schema-qualify the table: "schema"."table" (each part quoted separately).
83
+ const qtable = config.dbSchema ? `${id(config.dbSchema)}.${id(config.table)}` : id(config.table)
79
84
 
80
85
  // Column mapping: when a field has a `dbColumn` (e.g. Drizzle `created_at` vs
81
86
  // key `createdAt`), read/write the real column and alias it back to the field.
@@ -94,7 +99,7 @@ export function createSqlDataSource<TData extends RowData>(
94
99
  async getRows(request: ServerRequest): Promise<ServerResult<TData>> {
95
100
  const plan = planQuery(schema, request)
96
101
  const sql = planToSql(plan, planDialect)
97
- const t = id(table)
102
+ const t = qtable
98
103
  const rowsSql = squish(
99
104
  `SELECT ${projection} FROM ${t} ${sql.whereText} ${sql.orderByText} LIMIT ${sql.limit} OFFSET ${sql.offset}`,
100
105
  )
@@ -112,7 +117,7 @@ export function createSqlDataSource<TData extends RowData>(
112
117
  const bind = binder(dialect, params)
113
118
  const values = cols.map((c) => bind((input as RowData)[c]))
114
119
  const sql = squish(
115
- `INSERT INTO ${id(table)} (${cols.map(col).join(', ')}) VALUES (${values.join(', ')})${RET}`,
120
+ `INSERT INTO ${qtable} (${cols.map(col).join(', ')}) VALUES (${values.join(', ')})${RET}`,
116
121
  )
117
122
  const rows = await execute(sql, params)
118
123
  return (rows[0] ?? input) as TData
@@ -125,7 +130,7 @@ export function createSqlDataSource<TData extends RowData>(
125
130
  const bind = binder(dialect, params)
126
131
  const sets = cols.map((c) => `${col(c)} = ${bind((patch as RowData)[c])}`)
127
132
  const where = `${col(idField)} = ${bind(rowIdValue)}`
128
- const sql = squish(`UPDATE ${id(table)} SET ${sets.join(', ')} WHERE ${where}${RET}`)
133
+ const sql = squish(`UPDATE ${qtable} SET ${sets.join(', ')} WHERE ${where}${RET}`)
129
134
  const rows = await execute(sql, params)
130
135
  return (rows[0] ?? { ...patch, [idField]: rowIdValue }) as TData
131
136
  },
@@ -133,7 +138,7 @@ export function createSqlDataSource<TData extends RowData>(
133
138
  async deleteRow(rowIdValue: string): Promise<void> {
134
139
  const params: unknown[] = []
135
140
  const bind = binder(dialect, params)
136
- const sql = squish(`DELETE FROM ${id(table)} WHERE ${col(idField)} = ${bind(rowIdValue)}`)
141
+ const sql = squish(`DELETE FROM ${qtable} WHERE ${col(idField)} = ${bind(rowIdValue)}`)
137
142
  await execute(sql, params)
138
143
  },
139
144
 
@@ -151,13 +156,13 @@ export function createSqlDataSource<TData extends RowData>(
151
156
  : `${SQL_AGG[request.reduce]}(${col(request.measure)})`
152
157
  // No dimension -> a single grand total (a KPI), no GROUP BY.
153
158
  if (!request.dimension) {
154
- const text = squish(`SELECT ${fn} AS value FROM ${id(table)} ${sql.whereText}`)
159
+ const text = squish(`SELECT ${fn} AS value FROM ${qtable} ${sql.whereText}`)
155
160
  const rows = await execute(text, sql.params)
156
161
  return [{ category: '', value: Number(rows[0]?.value ?? 0) }]
157
162
  }
158
163
  const dim = col(request.dimension)
159
164
  const text = squish(
160
- `SELECT ${dim} AS category, ${fn} AS value FROM ${id(table)} ${sql.whereText} GROUP BY ${dim} ORDER BY value DESC`,
165
+ `SELECT ${dim} AS category, ${fn} AS value FROM ${qtable} ${sql.whereText} GROUP BY ${dim} ORDER BY value DESC`,
161
166
  )
162
167
  const rows = await execute(text, sql.params)
163
168
  return rows.map((r) => ({ category: String(r.category ?? ''), value: Number(r.value ?? 0) }))
@@ -18,10 +18,10 @@
18
18
  // bundle, works in any host app regardless of its styling.
19
19
 
20
20
  const CARD_ATTR = 'data-svgrid-enterprise-upgrade'
21
- const PRICING_URL = 'https://www.svgrid.com/pricing'
21
+ const PRICING_URL = 'https://svgrid.com/pricing'
22
22
  // ?ref=in-app lets us measure how many trials start from this exact prompt
23
23
  // vs. the pricing page itself - the whole point of a moment-of-intent CTA.
24
- const TRIAL_URL = 'https://www.svgrid.com/pricing?ref=in-app&utm_source=svgrid-enterprise&utm_medium=upgrade-prompt'
24
+ const TRIAL_URL = 'https://svgrid.com/pricing?ref=in-app&utm_source=svgrid-enterprise&utm_medium=upgrade-prompt'
25
25
 
26
26
  let shownThisSession = false
27
27
 
package/src/watermark.ts CHANGED
@@ -9,8 +9,8 @@ const WATERMARK_ATTR = 'data-svgrid-enterprise-watermark'
9
9
  // Marks a grid that has already shown (and faded) its watermark, so the
10
10
  // MutationObserver doesn't re-add it once it fades out and is removed.
11
11
  const NUDGED_ATTR = 'data-svgrid-enterprise-nudged'
12
- const HOMEPAGE_URL = 'https://www.svgrid.com'
13
- const LICENSE_URL = 'https://www.svgrid.com/pricing'
12
+ const HOMEPAGE_URL = 'https://svgrid.com'
13
+ const LICENSE_URL = 'https://svgrid.com/pricing/'
14
14
  const WATERMARK_LABEL = 'www.svgrid.com'
15
15
 
16
16
  // How long the watermark stays fully visible before it starts fading, and how
package/src/ai.test.ts DELETED
@@ -1,522 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
- import {
3
- setAIProvider, getAIProvider, hasAIProvider,
4
- mockAIProvider,
5
- aiFilter, aiSmartFill, aiSummarize, aiClassify,
6
- type AIProvider, type AIRequest,
7
- } from './ai'
8
- import { clearLicenseKey, setLicenseKey } from './license'
9
-
10
- // ---------------------------------------------------------------------------
11
- // Test helpers
12
- // ---------------------------------------------------------------------------
13
-
14
- /**
15
- * Minimal stub of the SvGridApi surface our AI helpers depend on. We don't
16
- * mock the entire grid - the AI helpers only read `getData()` and (for
17
- * the `apply` branch of aiFilter) call setFilter/setSort/clearAllFilters/
18
- * clearSort. Everything else stays a no-op.
19
- */
20
- function fakeApi<T extends Record<string, unknown>>(data: T[]) {
21
- const calls: Array<{ method: string; args: unknown[] }> = []
22
- const log = (method: string) => (...args: unknown[]) => {
23
- calls.push({ method, args })
24
- }
25
- const api = {
26
- getData: () => data,
27
- getDisplayedRows: () => data,
28
- setFilter: log('setFilter'),
29
- clearAllFilters: log('clearAllFilters'),
30
- setSort: log('setSort'),
31
- clearSort: log('clearSort'),
32
- setColumnVisible: log('setColumnVisible'),
33
- isColumnVisible: () => true,
34
- getCellValue: () => undefined,
35
- setCellValue: log('setCellValue'),
36
- addRow: log('addRow'),
37
- addRows: log('addRows'),
38
- removeRow: log('removeRow'),
39
- removeRows: log('removeRows'),
40
- addColumn: log('addColumn'),
41
- addColumns: log('addColumns'),
42
- removeColumn: log('removeColumn'),
43
- setGroupBy: log('setGroupBy'),
44
- clearFilter: log('clearFilter'),
45
- getFilters: () => ({}),
46
- clearRowSelection: log('clearRowSelection'),
47
- }
48
- return { api: api as any, calls }
49
- }
50
-
51
- /**
52
- * Build a provider that records every request it sees and replies with a
53
- * caller-chosen response. Used for the deterministic-shape tests where we
54
- * need to assert what the helper put into the prompt or what it does with
55
- * the model's reply.
56
- */
57
- function recordingProvider(reply: string | ((req: AIRequest) => string)) {
58
- const seen: AIRequest[] = []
59
- const fn: AIProvider = async (req) => {
60
- seen.push(req)
61
- return typeof reply === 'function' ? reply(req) : reply
62
- }
63
- return { provider: fn, seen }
64
- }
65
-
66
- // Make sure each test starts from a known state. The provider, license, and
67
- // any persistent flags in the AI module are global, so we reset them.
68
- beforeEach(() => {
69
- setAIProvider(null)
70
- // Default to a licensed state so the soft-gate doesn't dump noise on the
71
- // console during expected-failure tests. Individual cases clear it when
72
- // they want to assert soft-gate behaviour.
73
- setLicenseKey('SVENTERPRISE-DEV-TEST')
74
- })
75
- afterEach(() => {
76
- setAIProvider(null)
77
- clearLicenseKey()
78
- })
79
-
80
- // ---------------------------------------------------------------------------
81
- // Provider plumbing
82
- // ---------------------------------------------------------------------------
83
-
84
- describe('AI provider registration', () => {
85
- it('setAIProvider stores the function and hasAIProvider reflects it', () => {
86
- expect(hasAIProvider()).toBe(false)
87
- expect(getAIProvider()).toBeNull()
88
-
89
- const fn: AIProvider = async () => '{}'
90
- setAIProvider(fn)
91
- expect(hasAIProvider()).toBe(true)
92
- expect(getAIProvider()).toBe(fn)
93
- })
94
-
95
- it('setAIProvider(null) clears the registration', () => {
96
- setAIProvider(async () => '{}')
97
- setAIProvider(null)
98
- expect(hasAIProvider()).toBe(false)
99
- })
100
-
101
- it('throws a typed NoProviderError when no provider is registered', async () => {
102
- const { api } = fakeApi([{ id: 1, value: 10 }])
103
- await expect(aiFilter(api, 'anything')).rejects.toThrow(/no AI provider registered/i)
104
- })
105
-
106
- it('throws on non-JSON when a json-format helper gets back prose', async () => {
107
- const { provider } = recordingProvider('this is not JSON at all')
108
- setAIProvider(provider)
109
- const { api } = fakeApi([{ id: 1, value: 10 }])
110
- await expect(aiFilter(api, 'find rows')).rejects.toThrow(/non-JSON/i)
111
- })
112
-
113
- it('strips a markdown ```json fence before parsing', async () => {
114
- const { provider } = recordingProvider(
115
- '```json\n{"filters": [], "sort": [], "rationale": "ok"}\n```',
116
- )
117
- setAIProvider(provider)
118
- const { api } = fakeApi([{ id: 1, value: 10 }])
119
- const r = await aiFilter(api, 'anything')
120
- expect(r.rationale).toBe('ok')
121
- })
122
- })
123
-
124
- // ---------------------------------------------------------------------------
125
- // aiFilter
126
- // ---------------------------------------------------------------------------
127
-
128
- describe('aiFilter', () => {
129
- it('passes the column schema to the prompt and tags the task', async () => {
130
- const { provider, seen } = recordingProvider(
131
- JSON.stringify({ filters: [], sort: [], rationale: 'x' }),
132
- )
133
- setAIProvider(provider)
134
- const { api } = fakeApi([
135
- { id: 'A1', amount: 100, region: 'EMEA' },
136
- { id: 'A2', amount: 250, region: 'NA' },
137
- ])
138
- await aiFilter(api, 'show big EMEA deals')
139
-
140
- expect(seen).toHaveLength(1)
141
- const req = seen[0]!
142
- expect(req.task).toBe('filter')
143
- expect(req.responseFormat).toBe('json')
144
- // The schema block must mention every column.
145
- expect(req.prompt).toMatch(/id \(string\)/)
146
- expect(req.prompt).toMatch(/amount \(number\)/)
147
- expect(req.prompt).toMatch(/region \(string\)/)
148
- // The user's query is forwarded verbatim.
149
- expect(req.prompt).toMatch(/show big EMEA deals/)
150
- })
151
-
152
- it('drops filter / sort clauses that reference a column the grid does not have', async () => {
153
- // The model hallucinates "made_up_field" - the helper must silently drop
154
- // it rather than pass it through to setFilter, which would otherwise
155
- // throw.
156
- const reply = {
157
- filters: [
158
- { field: 'amount', operator: 'greaterThan', value: '100' },
159
- { field: 'made_up_field', operator: 'contains', value: 'foo' },
160
- ],
161
- sort: [
162
- { field: 'amount', desc: true },
163
- { field: 'imaginary', desc: false },
164
- ],
165
- rationale: 'amount > 100',
166
- }
167
- setAIProvider(recordingProvider(JSON.stringify(reply)).provider)
168
- const { api } = fakeApi([{ amount: 100, region: 'NA' }])
169
- const r = await aiFilter(api, 'anything')
170
-
171
- expect(r.filters).toHaveLength(1)
172
- expect(r.filters[0]?.field).toBe('amount')
173
- expect(r.sort).toHaveLength(1)
174
- expect(r.sort[0]?.field).toBe('amount')
175
- })
176
-
177
- it('with apply=true applies filters and the last sort clause to the grid', async () => {
178
- const reply = {
179
- filters: [{ field: 'amount', operator: 'greaterThan', value: '100' }],
180
- sort: [
181
- { field: 'amount', desc: false }, // earlier - should be overridden
182
- { field: 'amount', desc: true }, // last - this is the one applied
183
- ],
184
- rationale: '',
185
- }
186
- setAIProvider(recordingProvider(JSON.stringify(reply)).provider)
187
- const { api, calls } = fakeApi([{ amount: 100, region: 'NA' }])
188
- await aiFilter(api, 'q', { apply: true })
189
-
190
- const methods = calls.map((c) => c.method)
191
- expect(methods).toContain('clearAllFilters')
192
- expect(methods).toContain('clearSort')
193
- const setFilter = calls.find((c) => c.method === 'setFilter')!
194
- expect(setFilter.args[0]).toBe('amount')
195
- expect((setFilter.args[1] as any).operator).toBe('greaterThan')
196
- const setSort = calls.find((c) => c.method === 'setSort')!
197
- expect(setSort.args[0]).toBe('amount')
198
- expect(setSort.args[1]).toBe('desc')
199
- })
200
-
201
- it('does NOT apply when apply is omitted (preview-only mode)', async () => {
202
- const reply = {
203
- filters: [{ field: 'amount', operator: 'greaterThan', value: '100' }],
204
- sort: [{ field: 'amount', desc: true }],
205
- rationale: '',
206
- }
207
- setAIProvider(recordingProvider(JSON.stringify(reply)).provider)
208
- const { api, calls } = fakeApi([{ amount: 100, region: 'NA' }])
209
- const r = await aiFilter(api, 'q')
210
-
211
- expect(calls.find((c) => c.method === 'setFilter')).toBeUndefined()
212
- expect(calls.find((c) => c.method === 'setSort')).toBeUndefined()
213
- // But the result still contains the plan so the caller can render a preview.
214
- expect(r.filters).toHaveLength(1)
215
- expect(r.sort).toHaveLength(1)
216
- })
217
- })
218
-
219
- // ---------------------------------------------------------------------------
220
- // aiSmartFill
221
- // ---------------------------------------------------------------------------
222
-
223
- describe('aiSmartFill', () => {
224
- it('throws when no examples are provided', async () => {
225
- setAIProvider(recordingProvider('{}').provider)
226
- const { api } = fakeApi([{ id: 1, tier: '' }])
227
- await expect(
228
- aiSmartFill(api, { field: 'tier', examples: [] }),
229
- ).rejects.toThrow(/requires at least one example/i)
230
- })
231
-
232
- it('auto-selects empty rows when targetRowIndices is omitted', async () => {
233
- const { provider, seen } = recordingProvider(
234
- JSON.stringify({
235
- predictions: [{ rowIndex: 1, value: 'auto', confidence: 0.9 }],
236
- rationale: '',
237
- }),
238
- )
239
- setAIProvider(provider)
240
- const { api } = fakeApi([
241
- { id: 1, tier: 'enterprise' }, // already filled
242
- { id: 2, tier: '' }, // empty -> picked
243
- { id: 3, tier: null as unknown as string }, // null -> picked
244
- { id: 4, tier: 'starter' }, // already filled
245
- ])
246
- await aiSmartFill(api, {
247
- field: 'tier',
248
- examples: [{ input: { id: 999 }, output: 'starter' }],
249
- })
250
-
251
- const prompt = seen[0]!.prompt
252
- // Rows 1 and 2 (0-indexed) are the empty ones.
253
- expect(prompt).toMatch(/Row 1: /)
254
- expect(prompt).toMatch(/Row 2: /)
255
- // Rows 0 and 3 are already filled - should NOT appear.
256
- expect(prompt).not.toMatch(/Row 0: /)
257
- expect(prompt).not.toMatch(/Row 3: /)
258
- })
259
-
260
- it('returns an empty prediction list when there are no empty cells', async () => {
261
- setAIProvider(recordingProvider('{"predictions":[],"rationale":""}').provider)
262
- const { api } = fakeApi([
263
- { id: 1, tier: 'enterprise' },
264
- { id: 2, tier: 'starter' },
265
- ])
266
- const r = await aiSmartFill(api, {
267
- field: 'tier',
268
- examples: [{ input: { id: 1 }, output: 'enterprise' }],
269
- })
270
- expect(r.predictions).toHaveLength(0)
271
- expect(r.rationale).toMatch(/no empty/i)
272
- })
273
-
274
- it('respects explicit targetRowIndices', async () => {
275
- const { provider, seen } = recordingProvider(
276
- JSON.stringify({
277
- predictions: [{ rowIndex: 0, value: 'x', confidence: 0.5 }],
278
- rationale: '',
279
- }),
280
- )
281
- setAIProvider(provider)
282
- const { api } = fakeApi([
283
- { id: 1, tier: 'enterprise' },
284
- { id: 2, tier: 'starter' },
285
- ])
286
- await aiSmartFill(api, {
287
- field: 'tier',
288
- targetRowIndices: [0],
289
- examples: [{ input: { id: 1 }, output: 'override' }],
290
- })
291
- expect(seen[0]!.prompt).toMatch(/Row 0: /)
292
- expect(seen[0]!.prompt).not.toMatch(/Row 1: /)
293
- })
294
- })
295
-
296
- // ---------------------------------------------------------------------------
297
- // aiSummarize
298
- // ---------------------------------------------------------------------------
299
-
300
- describe('aiSummarize', () => {
301
- it('returns a safe empty result when the slice is empty', async () => {
302
- // Use a non-empty dataset but a row target that doesn't exist - the
303
- // helper must short-circuit BEFORE calling the provider.
304
- let calls = 0
305
- setAIProvider(async () => { calls += 1; return '{}' })
306
- const { api } = fakeApi([{ id: 1 }])
307
- const r = await aiSummarize(api, { target: { kind: 'row', rowIndex: 99 } })
308
- expect(r.text).toBe('No rows in scope.')
309
- expect(r.bullets).toEqual([])
310
- expect(calls).toBe(0)
311
- })
312
-
313
- it('groups by field value when target.kind = "group"', async () => {
314
- const { provider, seen } = recordingProvider(
315
- JSON.stringify({ text: 'ok', bullets: [], highlightedFields: [] }),
316
- )
317
- setAIProvider(provider)
318
- const { api } = fakeApi([
319
- { id: 1, region: 'NA' },
320
- { id: 2, region: 'NA' },
321
- { id: 3, region: 'EMEA' },
322
- ])
323
- const r = await aiSummarize(api, {
324
- target: { kind: 'group', field: 'region', value: 'NA' },
325
- })
326
- expect(r.text).toBe('ok')
327
- // Only the two NA rows should appear in the prompt.
328
- const prompt = seen[0]!.prompt
329
- expect(prompt).toMatch(/"id":1/)
330
- expect(prompt).toMatch(/"id":2/)
331
- expect(prompt).not.toMatch(/"id":3/)
332
- })
333
-
334
- it('samples large slices uniformly so the prompt stays under budget', async () => {
335
- const { provider, seen } = recordingProvider(
336
- JSON.stringify({ text: 'ok', bullets: [], highlightedFields: [] }),
337
- )
338
- setAIProvider(provider)
339
- const rows = Array.from({ length: 200 }, (_, i) => ({ id: i }))
340
- const { api } = fakeApi(rows)
341
- await aiSummarize(api, { target: { kind: 'all' } })
342
-
343
- // Default sample cap is 25. We can't easily inspect the exact sample
344
- // count without parsing, but the prompt should advertise the FULL
345
- // slice size while only sampling a subset (so the rendered JSON line
346
- // count is ~25 rather than ~200).
347
- const prompt = seen[0]!.prompt
348
- expect(prompt).toMatch(/Slice size: 200 row/)
349
- const jsonLines = (prompt.match(/\{"id":/g) ?? []).length
350
- expect(jsonLines).toBeLessThanOrEqual(30)
351
- })
352
-
353
- it('includes the user question in the prompt when provided', async () => {
354
- const { provider, seen } = recordingProvider(
355
- JSON.stringify({ text: 'ok', bullets: [], highlightedFields: [] }),
356
- )
357
- setAIProvider(provider)
358
- const { api } = fakeApi([{ id: 1 }])
359
- await aiSummarize(api, {
360
- target: { kind: 'all' },
361
- question: 'Which accounts are at risk?',
362
- })
363
- expect(seen[0]!.prompt).toMatch(/Which accounts are at risk\?/)
364
- })
365
- })
366
-
367
- // ---------------------------------------------------------------------------
368
- // aiClassify
369
- // ---------------------------------------------------------------------------
370
-
371
- describe('aiClassify', () => {
372
- it('drops predictions whose value is not in the allowed class set', async () => {
373
- setAIProvider(
374
- recordingProvider(JSON.stringify({
375
- predictions: [
376
- { rowIndex: 0, value: 'at-risk', confidence: 0.9 },
377
- { rowIndex: 1, value: 'expanding', confidence: 0.8 },
378
- // Hallucinated label - must be dropped.
379
- { rowIndex: 2, value: 'something-else', confidence: 0.95 },
380
- ],
381
- })).provider,
382
- )
383
- const { api } = fakeApi([
384
- { notes: 'losing momentum' },
385
- { notes: 'expanding fast' },
386
- { notes: 'unclear' },
387
- ])
388
- const r = await aiClassify(api, {
389
- inputField: 'notes',
390
- outputField: 'sentiment',
391
- classes: ['at-risk', 'expanding', 'steady'],
392
- })
393
- expect(r.predictions).toHaveLength(2)
394
- expect(r.predictions.find((p) => p.value === 'something-else')).toBeUndefined()
395
- })
396
-
397
- it('includes the rubric in the prompt when classDescriptions is provided', async () => {
398
- const { provider, seen } = recordingProvider('{"predictions":[]}')
399
- setAIProvider(provider)
400
- const { api } = fakeApi([{ notes: 'x' }])
401
- await aiClassify(api, {
402
- inputField: 'notes',
403
- outputField: 'sentiment',
404
- classes: ['at-risk', 'steady'],
405
- classDescriptions: {
406
- 'at-risk': 'churn signals',
407
- steady: 'no signals',
408
- },
409
- })
410
- expect(seen[0]!.prompt).toMatch(/- at-risk: churn signals/)
411
- expect(seen[0]!.prompt).toMatch(/- steady: no signals/)
412
- })
413
- })
414
-
415
- // ---------------------------------------------------------------------------
416
- // mockAIProvider end-to-end
417
- // ---------------------------------------------------------------------------
418
-
419
- describe('mockAIProvider', () => {
420
- it('round-trips through aiFilter with at least one sensible clause', async () => {
421
- setAIProvider(mockAIProvider)
422
- const { api } = fakeApi([
423
- { id: 'A1', arr: 100_000, region: 'EMEA', owner: 'Sasha' },
424
- { id: 'A2', arr: 250_000, region: 'NA', owner: 'Jamie' },
425
- { id: 'A3', arr: 50_000, region: 'APAC', owner: 'Casey' },
426
- ])
427
- const r = await aiFilter(api, 'show accounts over $80k in EMEA, highest first')
428
- // Should have inferred something about "over $80k", "EMEA", and a sort.
429
- const fields = r.filters.map((f) => f.field)
430
- expect(fields).toContain('arr')
431
- expect(fields).toContain('region')
432
- expect(r.sort.length).toBeGreaterThan(0)
433
- expect(r.rationale).toMatch(/Interpreted/i)
434
- })
435
-
436
- it('round-trips through aiClassify and returns labels from the allowed set', async () => {
437
- setAIProvider(mockAIProvider)
438
- const { api } = fakeApi([
439
- { id: 1, notes: 'champion left, ARR at risk' },
440
- { id: 2, notes: 'expanding into two new regions' },
441
- { id: 3, notes: 'steady usage no surprises' },
442
- ])
443
- const r = await aiClassify(api, {
444
- inputField: 'notes',
445
- outputField: 'sentiment',
446
- classes: ['at-risk', 'expanding', 'steady'],
447
- })
448
- expect(r.predictions.length).toBeGreaterThan(0)
449
- for (const p of r.predictions) {
450
- expect(['at-risk', 'expanding', 'steady']).toContain(p.value)
451
- expect(p.confidence).toBeGreaterThan(0)
452
- expect(p.confidence).toBeLessThanOrEqual(1)
453
- }
454
- })
455
-
456
- it('summarises the whole view via the mock', async () => {
457
- setAIProvider(mockAIProvider)
458
- const { api } = fakeApi(Array.from({ length: 12 }, (_, i) => ({ id: i, value: i * 100 })))
459
- const r = await aiSummarize(api, { target: { kind: 'all' } })
460
- expect(r.text).toMatch(/12 rows in scope/i)
461
- expect(r.bullets.length).toBeGreaterThan(0)
462
- })
463
- })
464
-
465
- // ---------------------------------------------------------------------------
466
- // License soft-gate
467
- // ---------------------------------------------------------------------------
468
-
469
- describe('license interaction', () => {
470
- it('AI calls still succeed without a license key (soft-gate)', async () => {
471
- clearLicenseKey()
472
- setAIProvider(mockAIProvider)
473
- const { api } = fakeApi([{ id: 1 }])
474
- // Should NOT throw - the soft-gate emits a console nudge then proceeds.
475
- const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
476
- try {
477
- const r = await aiFilter(api, 'anything')
478
- expect(r).toBeDefined()
479
- } finally {
480
- consoleSpy.mockRestore()
481
- }
482
- })
483
-
484
- it('AI calls throw on a malformed license prefix', async () => {
485
- setLicenseKey('NOT-A-VALID-PREFIX-AT-ALL')
486
- setAIProvider(mockAIProvider)
487
- const { api } = fakeApi([{ id: 1 }])
488
- await expect(aiFilter(api, 'q')).rejects.toThrow(/invalid license/i)
489
- })
490
- })
491
-
492
- // ---------------------------------------------------------------------------
493
- // Abort + cancellation
494
- // ---------------------------------------------------------------------------
495
-
496
- describe('cancellation', () => {
497
- it('forwards the AbortSignal to the provider for aiFilter', async () => {
498
- let receivedSignal: AbortSignal | undefined
499
- const provider: AIProvider = async (req) => {
500
- receivedSignal = req.signal
501
- return JSON.stringify({ filters: [], sort: [], rationale: '' })
502
- }
503
- setAIProvider(provider)
504
- const controller = new AbortController()
505
- const { api } = fakeApi([{ id: 1 }])
506
- await aiFilter(api, 'q', { signal: controller.signal })
507
- expect(receivedSignal).toBe(controller.signal)
508
- })
509
-
510
- it('forwards the AbortSignal for aiSummarize', async () => {
511
- let receivedSignal: AbortSignal | undefined
512
- const provider: AIProvider = async (req) => {
513
- receivedSignal = req.signal
514
- return JSON.stringify({ text: '', bullets: [], highlightedFields: [] })
515
- }
516
- setAIProvider(provider)
517
- const controller = new AbortController()
518
- const { api } = fakeApi([{ id: 1 }])
519
- await aiSummarize(api, { target: { kind: 'all' }, signal: controller.signal })
520
- expect(receivedSignal).toBe(controller.signal)
521
- })
522
- })