@things-factory/ai-dashboard 10.1.278 → 10.1.279
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/package.json +22 -8
- package/client/bootstrap.ts +0 -25
- package/client/components/card-dialogs.ts +0 -445
- package/client/components/card-library.ts +0 -285
- package/client/components/dashboard-card.ts +0 -411
- package/client/components/proposal-preview.ts +0 -95
- package/client/index.ts +0 -5
- package/client/pages/my-dashboard-page.ts +0 -373
- package/client/route.ts +0 -8
- package/client/tsconfig.json +0 -13
- package/client/utils/card-api.ts +0 -99
- package/client/utils/card-words.ts +0 -91
- package/client/utils/examples.ts +0 -15
- package/dist-client/bootstrap.js.map +0 -1
- package/dist-client/components/card-dialogs.js.map +0 -1
- package/dist-client/components/card-library.js.map +0 -1
- package/dist-client/components/dashboard-card.js.map +0 -1
- package/dist-client/components/proposal-preview.js.map +0 -1
- package/dist-client/index.js.map +0 -1
- package/dist-client/pages/my-dashboard-page.js.map +0 -1
- package/dist-client/route.js.map +0 -1
- package/dist-client/tsconfig.tsbuildinfo +0 -1
- package/dist-client/utils/card-api.js.map +0 -1
- package/dist-client/utils/card-words.js.map +0 -1
- package/dist-client/utils/examples.js.map +0 -1
- package/dist-server/index.js.map +0 -1
- package/dist-server/role-tasks.js.map +0 -1
- package/dist-server/service/card/card-access.js.map +0 -1
- package/dist-server/service/card/card-definition.js.map +0 -1
- package/dist-server/service/card/card-names.js.map +0 -1
- package/dist-server/service/card/card-proposal.js.map +0 -1
- package/dist-server/service/card/card-resolver.js.map +0 -1
- package/dist-server/service/card/card-run.js.map +0 -1
- package/dist-server/service/card/card-tool.js.map +0 -1
- package/dist-server/service/card/card-types.js.map +0 -1
- package/dist-server/service/card/dashboard-card.js.map +0 -1
- package/dist-server/service/card/long-text.js.map +0 -1
- package/dist-server/service/index.js.map +0 -1
- package/dist-server/tsconfig.tsbuildinfo +0 -1
- package/server/index.ts +0 -16
- package/server/role-tasks.ts +0 -12
- package/server/service/card/card-access.test.ts +0 -173
- package/server/service/card/card-access.ts +0 -24
- package/server/service/card/card-definition.ts +0 -468
- package/server/service/card/card-intent.test.ts +0 -285
- package/server/service/card/card-names.ts +0 -12
- package/server/service/card/card-proposal.ts +0 -46
- package/server/service/card/card-resolver.ts +0 -440
- package/server/service/card/card-run.test.ts +0 -237
- package/server/service/card/card-run.ts +0 -302
- package/server/service/card/card-tool.ts +0 -368
- package/server/service/card/card-types.ts +0 -145
- package/server/service/card/card-words.test.ts +0 -72
- package/server/service/card/dashboard-card.ts +0 -303
- package/server/service/card/long-text.ts +0 -25
- package/server/service/index.ts +0 -16
- package/test/card-menu.test.ts +0 -50
- package/test/translations.test.ts +0 -42
- package/test/words-not-codes.test.ts +0 -24
- package/tsconfig.json +0 -9
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* A card is its definition, run as the viewer (ADR-0160) - what it reads, how its rows are shaped and drawn, and what
|
|
3
|
-
* it refuses rather than draws wrong.
|
|
4
|
-
*/
|
|
5
|
-
import { listReadTarget, type DetailRead, type ReadTarget } from '@things-factory/ai-assistant'
|
|
6
|
-
|
|
7
|
-
import { checkDefinition, resolveRelativeDate, resolveWhere, sourceOf, todayIn, type CardDefinition } from './card-definition'
|
|
8
|
-
import { runCard, type CardRunDeps } from './card-run'
|
|
9
|
-
|
|
10
|
-
/* The application, as fakes: a bank ledger behind a list query, and the receivables behind one answer. */
|
|
11
|
-
let ledger: any[]
|
|
12
|
-
const ledgerTarget: ReadTarget = listReadTarget({
|
|
13
|
-
key: 'office.cash-transaction',
|
|
14
|
-
title: 'title.cash',
|
|
15
|
-
name: 'bank lines',
|
|
16
|
-
listQuery: 'cashTransactions',
|
|
17
|
-
selection: 'id transactionDate type amount currency customerName',
|
|
18
|
-
dateField: 'transactionDate',
|
|
19
|
-
columns: [
|
|
20
|
-
{ name: 'transactionDate', type: 'date' },
|
|
21
|
-
{ name: 'type', type: 'string' },
|
|
22
|
-
{ name: 'customerName', type: 'string', labelKey: 'label.customer' },
|
|
23
|
-
{ name: 'currency', type: 'string' },
|
|
24
|
-
{ name: 'amount', type: 'number', total: true, currency: 'currency' }
|
|
25
|
-
]
|
|
26
|
-
})
|
|
27
|
-
let receivables: any
|
|
28
|
-
const receivablesRead: DetailRead = {
|
|
29
|
-
key: 'office.receivables',
|
|
30
|
-
description: 'what is owed.',
|
|
31
|
-
query: 'query ($direction: String!, $staleDays: Int!) { receivables(direction: $direction, staleDays: $staleDays) { rows { id customer remaining currency remainingInWon } } }',
|
|
32
|
-
args: [
|
|
33
|
-
{ name: 'direction', type: 'enum', values: ['SALES', 'PURCHASE'], required: true },
|
|
34
|
-
{ name: 'staleDays', type: 'integer', required: true }
|
|
35
|
-
],
|
|
36
|
-
lists: [
|
|
37
|
-
{
|
|
38
|
-
key: 'by-contract',
|
|
39
|
-
at: 'rows',
|
|
40
|
-
columns: [
|
|
41
|
-
{ name: 'customer', type: 'string' },
|
|
42
|
-
{ name: 'currency', type: 'string' },
|
|
43
|
-
{ name: 'remaining', type: 'number', total: true, currency: 'currency' },
|
|
44
|
-
{ name: 'remainingInWon', type: 'number', total: true }
|
|
45
|
-
]
|
|
46
|
-
}
|
|
47
|
-
]
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const calls: { document: string; variables: any }[] = []
|
|
51
|
-
const run = async (document: string, variables: any) => {
|
|
52
|
-
calls.push({ document, variables })
|
|
53
|
-
if (/receivables/.test(document)) return { data: { receivables } }
|
|
54
|
-
const keep = (row: any) => (variables.filters ?? []).every((f: any) => (f.operator === 'gte' ? row[f.name] >= f.value : f.operator === 'lte' ? row[f.name] <= f.value : f.operator === 'eq' ? row[f.name] === f.value : true))
|
|
55
|
-
const all = ledger.filter(keep)
|
|
56
|
-
const { page, limit } = variables.pagination
|
|
57
|
-
return { data: { cashTransactions: { items: all.slice((page - 1) * limit, page * limit), total: all.length } } }
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const opened: string[] = []
|
|
61
|
-
const deps = (over: Partial<CardRunDeps> = {}): CardRunDeps => ({
|
|
62
|
-
readTargetOf: key => (key === ledgerTarget.key ? ledgerTarget : undefined),
|
|
63
|
-
detailReadOf: key => (key === receivablesRead.key ? receivablesRead : undefined),
|
|
64
|
-
passesDoor: async door => (opened.push(door), true),
|
|
65
|
-
run,
|
|
66
|
-
today: '2026-10-24',
|
|
67
|
-
...over
|
|
68
|
-
})
|
|
69
|
-
|
|
70
|
-
const card = (over: Partial<CardDefinition>): CardDefinition => ({ schemaVersion: 1, source: { read: 'office.receivables', list: 'by-contract', where: { direction: 'SALES', staleDays: 180 } }, view: { kind: 'table' }, ...over })
|
|
71
|
-
|
|
72
|
-
beforeEach(() => {
|
|
73
|
-
calls.length = 0
|
|
74
|
-
opened.length = 0
|
|
75
|
-
receivables = {
|
|
76
|
-
rows: [
|
|
77
|
-
{ id: 'c1', customer: '이썸', remaining: 5000000, currency: 'KRW', remainingInWon: 5000000 },
|
|
78
|
-
{ id: 'c2', customer: '한빛', remaining: 12000000, currency: 'KRW', remainingInWon: 12000000 },
|
|
79
|
-
{ id: 'c3', customer: '이썸', remaining: 3000000, currency: 'KRW', remainingInWon: 3000000 },
|
|
80
|
-
{ id: 'c4', customer: '대성', remaining: 800000, currency: 'KRW', remainingInWon: 800000 },
|
|
81
|
-
{ id: 'c5', customer: '미래', remaining: 0, currency: 'KRW', remainingInWon: 0 }
|
|
82
|
-
]
|
|
83
|
-
}
|
|
84
|
-
ledger = [
|
|
85
|
-
{ id: 'l1', transactionDate: '2026-09-30', type: 'INCOME', amount: 100, currency: 'KRW', customerName: 'A' },
|
|
86
|
-
{ id: 'l2', transactionDate: '2026-10-01', type: 'INCOME', amount: 200, currency: 'KRW', customerName: 'A' },
|
|
87
|
-
{ id: 'l3', transactionDate: '2026-10-15', type: 'EXPENSE', amount: 50, currency: 'KRW', customerName: 'B' },
|
|
88
|
-
{ id: 'l4', transactionDate: '2026-10-31', type: 'INCOME', amount: 70, currency: 'USD', customerName: 'C' },
|
|
89
|
-
{ id: 'l5', transactionDate: '2026-11-01', type: 'INCOME', amount: 999, currency: 'KRW', customerName: 'A' }
|
|
90
|
-
]
|
|
91
|
-
})
|
|
92
|
-
|
|
93
|
-
describe('relative periods stay current (decision 3)', () => {
|
|
94
|
-
it('★ this month, last month, a quarter and a week - from one today', () => {
|
|
95
|
-
expect(resolveRelativeDate('this-month-start', '2026-10-24')).toBe('2026-10-01')
|
|
96
|
-
expect(resolveRelativeDate('this-month-end', '2026-10-24')).toBe('2026-10-31')
|
|
97
|
-
expect(resolveRelativeDate('last-month-end', '2026-03-10')).toBe('2026-02-28')
|
|
98
|
-
expect(resolveRelativeDate('this-quarter-start', '2026-11-05')).toBe('2026-10-01')
|
|
99
|
-
expect(resolveRelativeDate('this-quarter-end', '2026-11-05')).toBe('2026-12-31')
|
|
100
|
-
/* Weeks start on Monday: 2026-10-24 is a Saturday. */
|
|
101
|
-
expect(resolveRelativeDate('this-week-start', '2026-10-24')).toBe('2026-10-19')
|
|
102
|
-
expect(resolveRelativeDate('last-week-end', '2026-10-24')).toBe('2026-10-18')
|
|
103
|
-
expect(resolveRelativeDate('-30d', '2026-10-24')).toBe('2026-09-24')
|
|
104
|
-
expect(resolveRelativeDate('next-year-end', '2026-10-24')).toBe('2027-12-31')
|
|
105
|
-
})
|
|
106
|
-
|
|
107
|
-
it('★ in January, last month with this year is last December - one month gives both', () => {
|
|
108
|
-
expect(resolveWhere({ year: 'this-year', month: 'last-month' }, '2027-01-15')).toEqual({ year: 2026, month: 12 })
|
|
109
|
-
expect(resolveWhere({ year: 'this-year', month: 'this-month' }, '2027-01-15')).toEqual({ year: 2027, month: 1 })
|
|
110
|
-
expect(resolveWhere({ year: 'last-year' }, '2027-01-15')).toEqual({ year: 2026 })
|
|
111
|
-
expect(resolveWhere({ from: 'this-month-start', text: 'A' }, '2027-01-15')).toEqual({ from: '2027-01-01', text: 'A' })
|
|
112
|
-
})
|
|
113
|
-
|
|
114
|
-
it('today is the domain\'s day, and an unknown zone falls back to the system\'s', () => {
|
|
115
|
-
const now = new Date('2026-10-24T20:00:00Z')
|
|
116
|
-
expect(todayIn('Asia/Seoul', now)).toBe('2026-10-25')
|
|
117
|
-
expect(todayIn('America/New_York', now)).toBe('2026-10-24')
|
|
118
|
-
expect(todayIn('Not/AZone', now)).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
|
119
|
-
})
|
|
120
|
-
})
|
|
121
|
-
|
|
122
|
-
describe('a definition names only what its source has (decision 1)', () => {
|
|
123
|
-
const { source } = sourceOf({ read: 'office.receivables', list: 'by-contract' }, deps().readTargetOf, deps().detailReadOf)
|
|
124
|
-
|
|
125
|
-
it('★ an unknown read, a detail read with no list named among several, a list named on a list read are refused', () => {
|
|
126
|
-
expect(sourceOf({ read: 'office.nothing' }, deps().readTargetOf, deps().detailReadOf).issue?.code).toBe('unknown-read')
|
|
127
|
-
expect(sourceOf({ read: 'office.cash-transaction', list: 'x' }, deps().readTargetOf, deps().detailReadOf).issue?.code).toBe('list-of-a-list')
|
|
128
|
-
expect(sourceOf({ read: 'office.receivables', list: 'nope' }, deps().readTargetOf, deps().detailReadOf).issue?.code).toBe('unknown-list')
|
|
129
|
-
/* One list needs no name. */
|
|
130
|
-
expect(sourceOf({ read: 'office.receivables' }, deps().readTargetOf, deps().detailReadOf).source?.list?.key).toBe('by-contract')
|
|
131
|
-
expect(sourceOf({ read: 'office.receivables' }, deps().readTargetOf, key => ({ ...receivablesRead, lists: undefined }) as any).issue?.code).toBe('not-a-card-source')
|
|
132
|
-
})
|
|
133
|
-
|
|
134
|
-
it('★ unknown columns, conditions, operators and views are refused - never passed over', () => {
|
|
135
|
-
const codes = (definition: any) => checkDefinition(definition, source!).map(one => one.code)
|
|
136
|
-
expect(codes(card({ rows: { sortBy: 'debt' } }))).toEqual(['unknown-column'])
|
|
137
|
-
expect(codes(card({ source: { read: 'office.receivables', where: { direction: 'SALES', staleDays: 180, region: 'x' } } }))).toEqual(['unknown-condition'])
|
|
138
|
-
expect(codes(card({ rows: { match: [{ column: 'remaining', op: 'like' as any, value: 1 }] } }))).toEqual(['unknown-operator'])
|
|
139
|
-
expect(codes(card({ view: { kind: 'pie' as any } }))).toEqual(['unknown-view'])
|
|
140
|
-
expect(codes(card({ view: { kind: 'bar', values: ['remaining'] } }))).toEqual(['chart-without-label'])
|
|
141
|
-
expect(codes(card({ view: { kind: 'bar', label: 'customer', values: ['customer'] } }))).toEqual(['value-not-a-number'])
|
|
142
|
-
expect(codes(card({ rows: { limit: 51 }, view: { kind: 'bar', label: 'customer', values: ['remaining'] } }))).toEqual(['limit-out-of-range'])
|
|
143
|
-
expect(codes(card({ schemaVersion: 2 }))).toEqual(['unknown-schema-version'])
|
|
144
|
-
expect(codes(card({ source: { read: 'office.receivables', where: { direction: 'SALES', staleDays: 'this-month-start' } } }))).toEqual(['relative-date-on-non-date'])
|
|
145
|
-
expect(codes(card({ source: { read: 'office.receivables', where: { direction: 'SALES', staleDays: 'this-mnth' } } }))).toEqual(['unknown-relative-value'])
|
|
146
|
-
})
|
|
147
|
-
|
|
148
|
-
it('★ a required argument left out is said before the query runs, with what it takes', () => {
|
|
149
|
-
expect(checkDefinition(card({ source: { read: 'office.receivables', where: { direction: 'SALES' } } }), source!)).toEqual([{ code: 'missing-condition', params: { name: 'staleDays' } }])
|
|
150
|
-
expect(checkDefinition(card({ source: { read: 'office.receivables', where: { staleDays: 180 } } }), source!)).toEqual([{ code: 'missing-condition', params: { name: 'direction', values: ['SALES', 'PURCHASE'] } }])
|
|
151
|
-
})
|
|
152
|
-
|
|
153
|
-
it('★ a column put among the conditions is said to be a column, with the match that filters by it', () => {
|
|
154
|
-
const [issue] = checkDefinition(card({ source: { read: 'office.receivables', where: { direction: 'SALES', staleDays: 180, customer: '이썸' } } }), source!)
|
|
155
|
-
expect(issue).toEqual({ code: 'unknown-condition', params: { name: 'customer', conditions: ['direction', 'staleDays'], isColumn: true, use: `rows.match: [{ column: 'customer', op: 'eq', value: "이썸" }]` } })
|
|
156
|
-
})
|
|
157
|
-
})
|
|
158
|
-
|
|
159
|
-
describe('drawing a card (decisions 4, 5, 6)', () => {
|
|
160
|
-
it('★ top five customers by what they owe - grouped, summed, ordered and cut, drawn as bars', async () => {
|
|
161
|
-
const ran = await runCard(card({ rows: { groupBy: 'customer', sortBy: 'remaining', desc: true, limit: 3 }, view: { kind: 'bar', values: ['remaining'] } }), deps())
|
|
162
|
-
expect(ran.issue).toBeUndefined()
|
|
163
|
-
expect(ran.block).toEqual({ kind: 'chart', chart: 'bar', x: ['한빛', '이썸', '대성'], series: [{ name: 'remaining', values: [12000000, 8000000, 800000] }], unit: 'KRW' })
|
|
164
|
-
expect(ran.counts).toEqual({ read: 5, total: 5, complete: true, shaped: 4, shown: 3 })
|
|
165
|
-
expect(calls[0].variables).toEqual({ direction: 'SALES', staleDays: 180 })
|
|
166
|
-
})
|
|
167
|
-
|
|
168
|
-
it('a group of rows with no value in the grouped column is named, not drawn nameless', async () => {
|
|
169
|
-
receivables.rows.push({ id: 'c6', customer: null, remaining: 700000, currency: 'KRW', remainingInWon: 700000 })
|
|
170
|
-
const ran = await runCard(card({ rows: { groupBy: 'customer', sortBy: 'remaining', desc: true } , view: { kind: 'bar', values: ['remaining'] } }), deps({ words: (key, fallback) => (key === 'ai-dashboard.card.blank' ? '(미지정)' : fallback) }))
|
|
171
|
-
expect((ran.block as any).x).toEqual(['한빛', '이썸', '대성', '(미지정)', '미래'])
|
|
172
|
-
})
|
|
173
|
-
|
|
174
|
-
it('★ the data\'s own door is asked as the viewer before anything is read', async () => {
|
|
175
|
-
const ran = await runCard(card({}), deps({ passesDoor: async door => (opened.push(door), false) }))
|
|
176
|
-
expect(ran.issue).toEqual({ code: 'door-closed' })
|
|
177
|
-
expect(opened).toEqual(['Query.receivables'])
|
|
178
|
-
expect(calls).toHaveLength(0)
|
|
179
|
-
})
|
|
180
|
-
|
|
181
|
-
it('★ a list read with relative dates reads this month only, and filters after reading in order', async () => {
|
|
182
|
-
const ran = await runCard(
|
|
183
|
-
{ schemaVersion: 1, source: { read: 'office.cash-transaction', where: { from: 'this-month-start', to: 'this-month-end' } }, rows: { match: [{ column: 'type', op: 'eq', value: 'INCOME' }] }, view: { kind: 'table', columns: ['transactionDate', 'customerName'] } },
|
|
184
|
-
deps()
|
|
185
|
-
)
|
|
186
|
-
expect(calls[0].variables.filters).toEqual([
|
|
187
|
-
{ name: 'transactionDate', operator: 'gte', value: '2026-10-01' },
|
|
188
|
-
{ name: 'transactionDate', operator: 'lte', value: '2026-10-31T23:59:59.999' }
|
|
189
|
-
])
|
|
190
|
-
expect((ran.block as any).rows).toEqual([
|
|
191
|
-
{ transactionDate: '2026-10-01', customerName: 'A' },
|
|
192
|
-
{ transactionDate: '2026-10-31', customerName: 'C' }
|
|
193
|
-
])
|
|
194
|
-
/* The source held three rows this month; two are drawn after the filter. */
|
|
195
|
-
expect(ran.counts).toEqual({ read: 3, total: 3, complete: true, shaped: 2, shown: 2 })
|
|
196
|
-
})
|
|
197
|
-
|
|
198
|
-
it('★ two currencies are never added: a sum splits by currency, and ranking across them is refused', async () => {
|
|
199
|
-
const where = { from: 'this-month-start', to: 'this-month-end' }
|
|
200
|
-
const number = await runCard({ schemaVersion: 1, source: { read: 'office.cash-transaction', where }, view: { kind: 'number', values: ['amount'] } }, deps())
|
|
201
|
-
expect(number.block).toEqual({ kind: 'metrics', items: [{ label: 'amount (KRW)', value: 250, unit: 'KRW' }, { label: 'amount (USD)', value: 70, unit: 'USD' }] })
|
|
202
|
-
const grouped = await runCard({ schemaVersion: 1, source: { read: 'office.cash-transaction', where }, rows: { groupBy: 'customerName' }, view: { kind: 'bar', values: ['amount'] } }, deps())
|
|
203
|
-
expect((grouped.block as any).series).toEqual([
|
|
204
|
-
{ name: 'amount (KRW)', values: [200, 50, 0] },
|
|
205
|
-
{ name: 'amount (USD)', values: [0, 0, 70] }
|
|
206
|
-
])
|
|
207
|
-
const ranked = await runCard({ schemaVersion: 1, source: { read: 'office.cash-transaction', where }, rows: { groupBy: 'customerName', sortBy: 'amount', desc: true }, view: { kind: 'bar', values: ['amount'] } }, deps())
|
|
208
|
-
expect(ranked.issue).toEqual({ code: 'mixed-currency-order', params: { column: 'amount', currencies: ['KRW', 'USD'] } })
|
|
209
|
-
})
|
|
210
|
-
|
|
211
|
-
it('★ a card that would need a ninth series is refused, never folded into "other"', async () => {
|
|
212
|
-
ledger = Array.from({ length: 9 }, (_, i) => ({ id: `x${i}`, transactionDate: '2026-10-02', type: 'INCOME', amount: 1, currency: `C${i}`, customerName: 'A' }))
|
|
213
|
-
const ran = await runCard({ schemaVersion: 1, source: { read: 'office.cash-transaction' }, rows: { groupBy: 'customerName' }, view: { kind: 'bar', values: ['amount'] } }, deps())
|
|
214
|
-
expect(ran.issue).toEqual({ code: 'too-many-series', params: { series: 9, max: 8 } })
|
|
215
|
-
})
|
|
216
|
-
|
|
217
|
-
it('★ a read cut at the limit says how much of the source the card was drawn from', async () => {
|
|
218
|
-
receivables = { rows: Array.from({ length: 1200 }, (_, i) => ({ id: `r${i}`, customer: `c${i % 7}`, remaining: 1, currency: 'KRW', remainingInWon: 1 })) }
|
|
219
|
-
const ran = await runCard(card({ rows: { groupBy: 'customer' }, view: { kind: 'number' } }), deps())
|
|
220
|
-
expect(ran.counts).toEqual({ read: 1000, total: 1200, complete: false, shaped: 7, shown: 7 })
|
|
221
|
-
})
|
|
222
|
-
|
|
223
|
-
it('an empty list is no rows; a path holding no list, a missing answer and a failed query are each said', async () => {
|
|
224
|
-
receivables = { rows: [] }
|
|
225
|
-
expect((await runCard(card({ view: { kind: 'number' } }), deps())).block).toEqual({ kind: 'metrics', items: [{ label: 'count', value: 0 }] })
|
|
226
|
-
receivables = { other: [] }
|
|
227
|
-
expect((await runCard(card({}), deps())).issue).toEqual({ code: 'list-missing', params: { read: 'office.receivables', list: 'by-contract', at: 'rows' } })
|
|
228
|
-
receivables = null
|
|
229
|
-
expect((await runCard(card({}), deps())).issue).toEqual({ code: 'not-found' })
|
|
230
|
-
expect((await runCard(card({}), deps({ run: async () => ({ errors: [{ message: 'denied' }] }) }))).issue).toEqual({ code: 'query-failed', params: { message: 'denied' } })
|
|
231
|
-
})
|
|
232
|
-
|
|
233
|
-
it('a condition the source cannot read is said, not guessed at', async () => {
|
|
234
|
-
const ran = await runCard(card({ source: { read: 'office.receivables', where: { direction: 'NORTH', staleDays: 180 } } }), deps())
|
|
235
|
-
expect(ran.issue).toEqual({ code: 'condition-unreadable', params: { refused: [{ name: 'direction', code: 'not-in-list' }] } })
|
|
236
|
-
})
|
|
237
|
-
})
|
|
@@ -1,302 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Drawing a card - its definition run as the one looking at it (ADR-0160 decisions 2, 4, 5, 6).
|
|
3
|
-
*
|
|
4
|
-
* The read's door is asked first, with the viewer's request; then the application's query runs with that request,
|
|
5
|
-
* so the rows are those its API gives this person. The rows are filtered, grouped, ordered and cut - in that order -
|
|
6
|
-
* and become one AI 작업 패널 block, already within what the 작업 패널 draws: a card that would need a ninth series or a
|
|
7
|
-
* thirteenth figure is refused, never folded, so two currencies are never added on the way. Nothing is kept.
|
|
8
|
-
*
|
|
9
|
-
* Dependencies come in as arguments - tested without a server.
|
|
10
|
-
*/
|
|
11
|
-
import { filtersOf, MAX_READ_ROWS, readCriteria, readRows, rootFieldOf, rowOf, runDetail, valueAt, wordOf, type ReadColumn } from '@things-factory/ai-assistant'
|
|
12
|
-
|
|
13
|
-
import {
|
|
14
|
-
checkDefinition,
|
|
15
|
-
MAX_CHART_POINTS,
|
|
16
|
-
MAX_FIGURES,
|
|
17
|
-
MAX_SERIES,
|
|
18
|
-
MAX_TABLE_ROWS,
|
|
19
|
-
resolveRelativeDate,
|
|
20
|
-
isRelativeDate,
|
|
21
|
-
resolveWhere,
|
|
22
|
-
shapedColumnNames,
|
|
23
|
-
sourceOf,
|
|
24
|
-
type CardDefinition,
|
|
25
|
-
type CardIssue,
|
|
26
|
-
type CardSource
|
|
27
|
-
} from './card-definition.js'
|
|
28
|
-
|
|
29
|
-
type Row = Record<string, string | number | null>
|
|
30
|
-
type Runner = (document: string, variables: Record<string, unknown>) => Promise<{ data?: any; errors?: readonly { message: string }[] }>
|
|
31
|
-
|
|
32
|
-
export interface CardRunDeps {
|
|
33
|
-
readTargetOf(key: string): any
|
|
34
|
-
detailReadOf(key: string): any
|
|
35
|
-
/** Whether the viewer passes a door (`Query.receivables`) - their request's answer. */
|
|
36
|
-
passesDoor(door: string): Promise<boolean>
|
|
37
|
-
/** The application's API with the viewer's request state. */
|
|
38
|
-
run: Runner
|
|
39
|
-
/** Today in the domain's time zone - `YYYY-MM-DD`. */
|
|
40
|
-
today: string
|
|
41
|
-
/** The domain's time zone - a moment in the rows is read in it. */
|
|
42
|
-
timeZone?: string
|
|
43
|
-
/** The reader's words for a label key. */
|
|
44
|
-
words?(key: string | undefined, fallback: string): string
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** How much of the source the card was drawn from - said on the card (decision 4). */
|
|
48
|
-
export interface CardCounts {
|
|
49
|
-
/** Rows read from the source. */
|
|
50
|
-
read: number
|
|
51
|
-
/** Rows the source holds. */
|
|
52
|
-
total: number
|
|
53
|
-
/** Every row of the source was read. */
|
|
54
|
-
complete: boolean
|
|
55
|
-
/** Rows (or groups) after filtering and grouping, before the cut. */
|
|
56
|
-
shaped: number
|
|
57
|
-
/** Rows (or points) drawn. */
|
|
58
|
-
shown: number
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export interface CardRunResult {
|
|
62
|
-
/** One AI 작업 패널 block - metrics, table or chart. */
|
|
63
|
-
block?: Record<string, unknown>
|
|
64
|
-
issue?: CardIssue
|
|
65
|
-
counts?: CardCounts
|
|
66
|
-
/** The day relative conditions were read for. */
|
|
67
|
-
asOf: string
|
|
68
|
-
source?: { key: string; labelKey?: string }
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** A column of the shaped rows, with the currency its sums are kept in. */
|
|
72
|
-
interface Shaped extends ReadColumn {
|
|
73
|
-
/** Set on a column split by currency: `remaining:USD` holds remaining in USD only. */
|
|
74
|
-
of?: string
|
|
75
|
-
code?: string
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const compare = (a: unknown, b: unknown): number => {
|
|
79
|
-
if (typeof a === 'number' && typeof b === 'number') return a - b
|
|
80
|
-
if (a === null || a === undefined) return b === null || b === undefined ? 0 : 1
|
|
81
|
-
if (b === null || b === undefined) return -1
|
|
82
|
-
return String(a).localeCompare(String(b))
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function matches(row: Row, column: ReadColumn, op: string, given: unknown, today: string): boolean {
|
|
86
|
-
const cell = row[column.name]
|
|
87
|
-
if (op === 'in' || op === 'not_in') {
|
|
88
|
-
const listed = (given as unknown[]).some(one => (column.type === 'number' ? Number(cell) === Number(one) : String(cell ?? '') === String(one)))
|
|
89
|
-
return op === 'in' ? listed : !listed
|
|
90
|
-
}
|
|
91
|
-
const value = column.type === 'date' && isRelativeDate(given) ? resolveRelativeDate(given as string, today) : given
|
|
92
|
-
if (op === 'eq') return column.type === 'number' ? Number(cell) === Number(value) : String(cell ?? '') === String(value)
|
|
93
|
-
if (op === 'ne') return column.type === 'number' ? Number(cell) !== Number(value) : String(cell ?? '') !== String(value)
|
|
94
|
-
if (cell === null || cell === undefined) return false
|
|
95
|
-
/*
|
|
96
|
-
* A date column holds a month, a day or a time - compared as text over the shorter of the two, so a time of
|
|
97
|
-
* 2026-10-01 is within `gte 2026-10-01`, and a pay month 2026-05 is within `gte 2026-05-01` (2026-10-25: compared over
|
|
98
|
-
* the day's length, the first month of 「최근 6개월」 always fell out).
|
|
99
|
-
*/
|
|
100
|
-
const shorter = column.type === 'date' ? Math.min(String(cell).length, String(value).length) : String(value).length
|
|
101
|
-
const order = column.type === 'number' ? Number(cell) - Number(value) : String(cell).slice(0, shorter).localeCompare(String(value).slice(0, shorter))
|
|
102
|
-
return op === 'gt' ? order > 0 : op === 'gte' ? order >= 0 : op === 'lt' ? order < 0 : order <= 0
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** The rows of the source, read as the viewer - or why there are none. */
|
|
106
|
-
async function readSource(source: CardSource, where: Record<string, unknown>, deps: CardRunDeps): Promise<{ rows?: Row[]; total?: number; complete?: boolean; issue?: CardIssue }> {
|
|
107
|
-
if (source.kind === 'list') {
|
|
108
|
-
const { criteria, refused } = readCriteria(source.target!, where)
|
|
109
|
-
if (refused.length) return { issue: { code: 'condition-unreadable', params: { refused } } }
|
|
110
|
-
try {
|
|
111
|
-
const read = await readRows(source.target!, filtersOf(source.target!, criteria), deps.run, typeof criteria.text === 'string' && source.target!.search ? criteria.text : undefined, {
|
|
112
|
-
timeZone: deps.timeZone
|
|
113
|
-
})
|
|
114
|
-
return { rows: read.rows as Row[], total: read.total, complete: read.complete }
|
|
115
|
-
} catch (error: any) {
|
|
116
|
-
return { issue: { code: 'query-failed', params: { message: String(error?.message ?? error) } } }
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
const ran = await runDetail(source.detail!, where, deps.run)
|
|
120
|
-
if (ran.error === 'argument-unreadable') return { issue: { code: 'condition-unreadable', params: { refused: ran.refused } } }
|
|
121
|
-
if (ran.error === 'query-failed') return { issue: { code: 'query-failed', params: { message: ran.message } } }
|
|
122
|
-
if (ran.error === 'not-found') return { issue: { code: 'not-found' } }
|
|
123
|
-
const at = source.list!.at
|
|
124
|
-
const items = at ? valueAt(ran.value, at) : ran.value
|
|
125
|
-
/* An empty list is no rows; a path that holds no list is the declaration's mistake, said as such. */
|
|
126
|
-
if (!Array.isArray(items)) return { issue: { code: 'list-missing', params: { read: source.key, list: source.list!.key, at } } }
|
|
127
|
-
const rows = items.slice(0, MAX_READ_ROWS).map(item => rowOf({ columns: source.columns }, item, { timeZone: deps.timeZone }) as Row)
|
|
128
|
-
return { rows, total: items.length, complete: items.length <= MAX_READ_ROWS }
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** The currencies a currency column's rows hold - `unknown` for a row without one. */
|
|
132
|
-
function currenciesIn(rows: Row[], column: ReadColumn): string[] {
|
|
133
|
-
const codes = new Set<string>()
|
|
134
|
-
for (const row of rows) codes.add(typeof row[column.currency!] === 'string' && row[column.currency!] ? String(row[column.currency!]) : 'unknown')
|
|
135
|
-
return [...codes].sort()
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const round = (n: number) => Math.round(n * 100) / 100
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Grouped rows - the group column, a count and each number column summed. A number with a currency is summed per
|
|
142
|
-
* currency; its column is split into one per currency when the rows hold more than one.
|
|
143
|
-
*/
|
|
144
|
-
function group(rows: Row[], by: ReadColumn, numbers: ReadColumn[]): { rows: Row[]; columns: Shaped[] } {
|
|
145
|
-
const splits = new Map(numbers.filter(one => one.currency).map(one => [one.name, currenciesIn(rows, one)]))
|
|
146
|
-
const columns: Shaped[] = [
|
|
147
|
-
{ ...by, type: by.type === 'date' ? 'string' : by.type },
|
|
148
|
-
{ name: 'count', type: 'number' },
|
|
149
|
-
...numbers.flatMap(one => {
|
|
150
|
-
const codes = splits.get(one.name)
|
|
151
|
-
return codes && codes.length > 1 ? codes.map(code => ({ ...one, name: `${one.name}:${code}`, of: one.name, code })) : [{ ...one, ...(codes ? { code: codes[0] } : {}) }]
|
|
152
|
-
})
|
|
153
|
-
]
|
|
154
|
-
const groups = new Map<string, Row[]>()
|
|
155
|
-
for (const row of rows) {
|
|
156
|
-
const raw = row[by.name]
|
|
157
|
-
const key = raw === null || raw === undefined ? '' : by.type === 'date' ? String(raw).slice(0, 7) : String(raw)
|
|
158
|
-
groups.set(key, [...(groups.get(key) ?? []), row])
|
|
159
|
-
}
|
|
160
|
-
const out = [...groups].map(([key, members]) => {
|
|
161
|
-
const row: Row = { [by.name]: key, count: members.length }
|
|
162
|
-
for (const column of columns.slice(2)) {
|
|
163
|
-
const name = column.of ?? column.name
|
|
164
|
-
const kept = column.of ? members.filter(one => (one[column.currency!] || 'unknown') === column.code) : members
|
|
165
|
-
row[column.name] = round(kept.reduce((sum, one) => sum + (typeof one[name] === 'number' ? (one[name] as number) : 0), 0))
|
|
166
|
-
}
|
|
167
|
-
return row
|
|
168
|
-
})
|
|
169
|
-
return { rows: out, columns }
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/** Ungrouped rows with a number column split by currency when the rows hold more than one - each row in its own. */
|
|
173
|
-
function splitUngrouped(rows: Row[], columns: ReadColumn[]): { rows: Row[]; columns: Shaped[] } {
|
|
174
|
-
const shaped: Shaped[] = []
|
|
175
|
-
const splits: { column: ReadColumn; codes: string[] }[] = []
|
|
176
|
-
for (const column of columns) {
|
|
177
|
-
const codes = column.currency ? currenciesIn(rows, column) : []
|
|
178
|
-
if (codes.length > 1) {
|
|
179
|
-
splits.push({ column, codes })
|
|
180
|
-
shaped.push(...codes.map(code => ({ ...column, name: `${column.name}:${code}`, of: column.name, code })))
|
|
181
|
-
} else shaped.push({ ...column, ...(codes.length ? { code: codes[0] } : {}) })
|
|
182
|
-
}
|
|
183
|
-
if (!splits.length) return { rows, columns: shaped }
|
|
184
|
-
return {
|
|
185
|
-
rows: rows.map(row => {
|
|
186
|
-
const out: Row = { ...row }
|
|
187
|
-
for (const { column, codes } of splits) {
|
|
188
|
-
const mine = (row[column.currency!] as string) || 'unknown'
|
|
189
|
-
for (const code of codes) out[`${column.name}:${code}`] = code === mine ? row[column.name] : null
|
|
190
|
-
}
|
|
191
|
-
return out
|
|
192
|
-
}),
|
|
193
|
-
columns: shaped
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** The shaped columns a definition's name stands for - one, or one per currency when it was split. */
|
|
198
|
-
const expand = (columns: Shaped[], name: string) => columns.filter(one => one.name === name || one.of === name)
|
|
199
|
-
|
|
200
|
-
/** Runs a card's definition as the viewer and draws it as one block. */
|
|
201
|
-
export async function runCard(definition: CardDefinition, deps: CardRunDeps): Promise<CardRunResult> {
|
|
202
|
-
const asOf = deps.today
|
|
203
|
-
const words = deps.words ?? ((_key: string | undefined, fallback: string) => fallback)
|
|
204
|
-
const { source, issue } = sourceOf(definition?.source, deps.readTargetOf, deps.detailReadOf)
|
|
205
|
-
if (!source) return { issue, asOf }
|
|
206
|
-
const about = { key: source.key, ...(source.labelKey ? { labelKey: source.labelKey } : {}) }
|
|
207
|
-
const issues = checkDefinition(definition, source)
|
|
208
|
-
if (issues.length) return { issue: issues[0], asOf, source: about }
|
|
209
|
-
|
|
210
|
-
/* ① The viewer may read this source at all - a shared card gives the definition, never the data (decision 6). */
|
|
211
|
-
if (!(await deps.passesDoor(rootFieldOf(source.query, 'query')))) return { issue: { code: 'door-closed' }, asOf, source: about }
|
|
212
|
-
|
|
213
|
-
const read = await readSource(source, resolveWhere(definition.source.where, asOf, source.conditions), deps)
|
|
214
|
-
if (read.issue) return { issue: read.issue, asOf, source: about }
|
|
215
|
-
const rowsDef = definition.rows ?? {}
|
|
216
|
-
const view = definition.view
|
|
217
|
-
const columns = new Map(source.columns.map(one => [one.name, one]))
|
|
218
|
-
|
|
219
|
-
/* ② Filter → group → order → cut (decision 4). */
|
|
220
|
-
let rows = read.rows!.filter(row => (rowsDef.match ?? []).every(one => matches(row, columns.get(one.column)!, one.op, one.value, asOf)))
|
|
221
|
-
let shaped: { rows: Row[]; columns: Shaped[] }
|
|
222
|
-
if (rowsDef.groupBy) {
|
|
223
|
-
const by = columns.get(rowsDef.groupBy)!
|
|
224
|
-
const numbers = source.columns.filter(one => one.type === 'number' && one.name !== by.name)
|
|
225
|
-
shaped = group(rows, by, numbers)
|
|
226
|
-
} else shaped = splitUngrouped(rows, source.columns)
|
|
227
|
-
/* A group of rows with no value in the grouped column is said as such, never drawn as a bar without a name. */
|
|
228
|
-
if (rowsDef.groupBy) {
|
|
229
|
-
const blank = words('ai-dashboard.card.blank', '(none)')
|
|
230
|
-
shaped.rows = shaped.rows.map(row => (row[rowsDef.groupBy!] === '' ? { ...row, [rowsDef.groupBy!]: blank } : row))
|
|
231
|
-
}
|
|
232
|
-
rows = shaped.rows
|
|
233
|
-
const shapedCount = rows.length
|
|
234
|
-
|
|
235
|
-
if (rowsDef.sortBy) {
|
|
236
|
-
const order = expand(shaped.columns, rowsDef.sortBy)
|
|
237
|
-
/* Two currencies have no common order - ranking them would compare yen with won. */
|
|
238
|
-
if (order.length > 1) return { issue: { code: 'mixed-currency-order', params: { column: rowsDef.sortBy, currencies: order.map(one => one.code) } }, asOf, source: about }
|
|
239
|
-
const by = order[0].name
|
|
240
|
-
rows = [...rows].sort((a, b) => (rowsDef.desc ? -compare(a[by], b[by]) : compare(a[by], b[by])))
|
|
241
|
-
}
|
|
242
|
-
const cap = view.kind === 'table' ? MAX_TABLE_ROWS : view.kind === 'number' ? Infinity : MAX_CHART_POINTS
|
|
243
|
-
const limit = Math.min(rowsDef.limit ?? cap, cap)
|
|
244
|
-
if (view.kind !== 'number') rows = rows.slice(0, limit)
|
|
245
|
-
|
|
246
|
-
const counts: CardCounts = { read: read.rows!.length, total: read.total!, complete: !!read.complete, shaped: shapedCount, shown: view.kind === 'number' ? shapedCount : rows.length }
|
|
247
|
-
const label = (column: Shaped) => {
|
|
248
|
-
const base = column.name === 'count' ? words('ai-dashboard.card.count', 'count') : words(column.labelKey, column.of ?? column.name)
|
|
249
|
-
return column.code && column.of ? `${base} (${column.code})` : base
|
|
250
|
-
}
|
|
251
|
-
/* A unit beside the numbers: a single currency says itself, else the card's own. */
|
|
252
|
-
const unitOf = (drawn: Shaped[]) => {
|
|
253
|
-
const codes = [...new Set(drawn.map(one => one.code).filter(Boolean))]
|
|
254
|
-
return codes.length === 1 && !drawn.some(one => one.of) ? codes[0] : view.unit
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
if (view.kind === 'number') {
|
|
258
|
-
const names = view.values?.length ? view.values : []
|
|
259
|
-
const drawn = names.flatMap(name => expand(shaped.columns, name))
|
|
260
|
-
const items = drawn.length
|
|
261
|
-
? drawn.map(column => ({ label: label(column), value: round(rows.reduce((sum, row) => sum + (typeof row[column.name] === 'number' ? (row[column.name] as number) : 0), 0)), ...(column.code && column.code !== 'unknown' ? { unit: column.code } : view.unit ? { unit: view.unit } : {}) }))
|
|
262
|
-
: [{ label: words('ai-dashboard.card.count', 'count'), value: rowsDef.groupBy ? shapedCount : rows.length, ...(view.unit ? { unit: view.unit } : {}) }]
|
|
263
|
-
if (items.length > MAX_FIGURES) return { issue: { code: 'too-many-figures', params: { figures: items.length, max: MAX_FIGURES } }, asOf, source: about, counts }
|
|
264
|
-
return { block: { kind: 'metrics', items }, counts, asOf, source: about }
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
if (view.kind === 'table') {
|
|
268
|
-
const names = [...(view.columns ?? []), ...(view.values ?? []).filter(one => !(view.columns ?? []).includes(one))]
|
|
269
|
-
const drawn = names.length ? names.flatMap(name => expand(shaped.columns, name)) : shaped.columns
|
|
270
|
-
return {
|
|
271
|
-
block: {
|
|
272
|
-
kind: 'table',
|
|
273
|
-
columns: drawn.map(column => ({ name: column.name, label: label(column), type: column.type })),
|
|
274
|
-
/* A coded value is shown by its word in the viewer's language; the rows were matched and sorted by the code. */
|
|
275
|
-
rows: rows.map(row => Object.fromEntries(drawn.map(column => [column.name, wordOf(column, row[column.name] ?? null, words)])))
|
|
276
|
-
},
|
|
277
|
-
counts,
|
|
278
|
-
asOf,
|
|
279
|
-
source: about
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
const x = (view.label ?? rowsDef.groupBy)!
|
|
284
|
-
const values = view.values?.length ? view.values : ['count']
|
|
285
|
-
const series = values.flatMap(name => expand(shaped.columns, name))
|
|
286
|
-
if (series.length > MAX_SERIES) return { issue: { code: 'too-many-series', params: { series: series.length, max: MAX_SERIES } }, asOf, source: about, counts }
|
|
287
|
-
return {
|
|
288
|
-
block: {
|
|
289
|
-
kind: 'chart',
|
|
290
|
-
chart: view.kind,
|
|
291
|
-
x: rows.map(row => String(wordOf(shaped.columns.find(one => one.name === x), row[x] ?? '', words) ?? '').slice(0, 60)),
|
|
292
|
-
series: series.map(column => ({ name: label(column), values: rows.map(row => (typeof row[column.name] === 'number' ? (row[column.name] as number) : null)) })),
|
|
293
|
-
...(unitOf(series) && unitOf(series) !== 'unknown' ? { unit: unitOf(series) } : {})
|
|
294
|
-
},
|
|
295
|
-
counts,
|
|
296
|
-
asOf,
|
|
297
|
-
source: about
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/** The columns a definition may name after its `rows` - for a refusal that says what there is. */
|
|
302
|
-
export { shapedColumnNames }
|