screen.ts
TypeScript · 80 рядків
1// SCREEN — відповідь на ТСД за контрактом екрана (R-12.11; P2 з R-23 §9.3). Кінцевий блок, як CLIENT_RESPONSE.
2//
3// { "kind": "put", "text": "{{data.line.name}}: поклади {{data.pending.qty}} шт у {{data.box.code}}",
4// "expect": "qty", "tone": "info", "qty": "=data.pending.qty", "value": "", "buttons": ["Пошкоджено", "Немає"] }
5//
6// text — шаблон з {{data.* | task.* | event.*}} або вираз з "=" (як в ACTION); qty і value — літерал або вираз.
7// Відповідь: { screen: { kind, text, expect, tone, qty?, value?, buttons? } } — ТСД показує екран і чекає expect.
8import { actionExpression, evaluateExpression, inferExpressionType } from './condition.ts'
9
10export const SCREEN_EXPECT = ['product', 'qty', 'container', 'pallet', 'location', 'button', 'none']
11export const SCREEN_TONES = ['info', 'ok', 'warn', 'error']
12
13const TEMPLATE = /{{\s*((?:data|task|event)(?:\.[A-Za-z_$][\w$]*)+)\s*}}/g
14
15function read(scopes: any, path: string) {
16 const [root, ...keys] = path.split('.')
17 return keys.reduce((value, key) => value?.[key], scopes[root])
18}
19
20function valueOf(value: any, scopes: any) {
21 const expression = actionExpression(value)
22 return expression === null ? value : evaluateExpression(expression, scopes)
23}
24
25export function renderScreenText(text: any, scopes: any): string {
26 const expression = actionExpression(text)
27 if (expression !== null) return String(evaluateExpression(expression, scopes) ?? '')
28 return String(text ?? '').replace(TEMPLATE, (_, path) => {
29 const value = read(scopes, path)
30 if (value === undefined) throw new Error(`Screen field not found: ${path}`)
31 return typeof value === 'object' ? JSON.stringify(value) : String(value)
32 })
33}
34
35/** Тіло відповіді ТСД. scopes — { data, task, event }. */
36export function screenBody(config: any = {}, scopes: any) {
37 const all = { ...scopes, input: scopes.data }
38 const screen: any = {
39 kind: String(config.kind || 'info'),
40 text: renderScreenText(config.text, all),
41 expect: String(config.expect || 'none'),
42 tone: String(config.tone || 'info'),
43 }
44 if (config.qty !== undefined && config.qty !== '') screen.qty = valueOf(config.qty, all)
45 if (config.value !== undefined && config.value !== '') screen.value = valueOf(config.value, all)
46 if (Array.isArray(config.buttons) && config.buttons.length) screen.buttons = config.buttons.map(String)
47 return { screen }
48}
49
50function schemaAt(schema: any, path: string) {
51 const [root, ...keys] = path.split('.')
52 return keys.reduce((value, key) => value && typeof value === 'object' && !Array.isArray(value) ? value[key] : undefined, schema?.[root])
53}
54
55/** Помилки конфігурації. schema — { data, task, event }. */
56export function validateScreen(config: any = {}, schema: any = {}): string[] {
57 const errors: string[] = []
58 const all = { ...schema, input: schema.data }
59 if (!String(config.kind || '').trim()) errors.push('kind is required')
60 if (!String(config.text || '').trim()) errors.push('text is required')
61 if (!SCREEN_EXPECT.includes(config.expect)) errors.push(`expect must be one of ${SCREEN_EXPECT.join(', ')}`)
62 if (!SCREEN_TONES.includes(config.tone || 'info')) errors.push(`tone must be one of ${SCREEN_TONES.join(', ')}`)
63 const expression = actionExpression(config.text)
64 if (expression !== null) {
65 for (const error of inferExpressionType(expression, all).errors) errors.push(`text: ${error}`)
66 } else {
67 for (const [, path] of String(config.text || '').matchAll(TEMPLATE)) {
68 if (schemaAt(all, path) === undefined) errors.push(`text: unknown field {{${path}}}`)
69 }
70 }
71 for (const field of ['qty', 'value']) {
72 const fieldExpression = actionExpression(config[field])
73 if (fieldExpression !== null) for (const error of inferExpressionType(fieldExpression, all).errors) errors.push(`${field}: ${error}`)
74 }
75 if (config.buttons !== undefined && (!Array.isArray(config.buttons) || config.buttons.some((b: any) => typeof b !== 'string'))) {
76 errors.push('buttons must be an array of strings')
77 }
78 return errors
79}
80