@genesislcap/mock-server 15.74.0 → 15.75.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 (100) hide show
  1. package/README.md +296 -58
  2. package/dist/db/schema.d.ts +9 -1
  3. package/dist/db/schema.js +40 -11
  4. package/dist/db/store.d.ts +1 -0
  5. package/dist/db/store.js +4 -0
  6. package/dist/handlers/auth.d.ts +15 -6
  7. package/dist/handlers/auth.js +152 -33
  8. package/dist/handlers/commitEvent.js +43 -20
  9. package/dist/handlers/crudEvents.d.ts +3 -1
  10. package/dist/handlers/crudEvents.js +3 -2
  11. package/dist/handlers/eventValidation.js +6 -3
  12. package/dist/handlers/http.d.ts +2 -2
  13. package/dist/handlers/http.js +66 -43
  14. package/dist/handlers/jsonSchema.d.ts +1 -0
  15. package/dist/handlers/jsonSchema.js +72 -21
  16. package/dist/handlers/meta.d.ts +1 -1
  17. package/dist/handlers/meta.js +59 -10
  18. package/dist/handlers/requestReply.js +36 -9
  19. package/dist/index.d.ts +1 -1
  20. package/dist/presets/auth.d.ts +25 -0
  21. package/dist/presets/auth.js +855 -0
  22. package/dist/presets/cronExpression.d.ts +1 -0
  23. package/dist/presets/cronExpression.js +429 -0
  24. package/dist/presets/fileServer.d.ts +13 -0
  25. package/dist/presets/fileServer.js +399 -0
  26. package/dist/presets/gsf.d.ts +24 -0
  27. package/dist/presets/gsf.js +450 -0
  28. package/dist/presets/index.d.ts +1 -0
  29. package/dist/presets/index.js +1 -0
  30. package/dist/presets/javaTime.d.ts +7 -0
  31. package/dist/presets/javaTime.js +322 -0
  32. package/dist/presets/multipart.d.ts +14 -0
  33. package/dist/presets/multipart.js +91 -0
  34. package/dist/presets/notify.d.ts +27 -0
  35. package/dist/presets/notify.js +250 -0
  36. package/dist/presets/notifyDispatch.d.ts +28 -0
  37. package/dist/presets/notifyDispatch.js +570 -0
  38. package/dist/presets/notifyRules.d.ts +9 -0
  39. package/dist/presets/notifyRules.js +754 -0
  40. package/dist/presets/platform/backing.json +8058 -217
  41. package/dist/presets/platform/criteria-model.json +362 -0
  42. package/dist/presets/platform/time-zones.json +608 -0
  43. package/dist/presets/platform.d.ts +7 -0
  44. package/dist/presets/platform.js +145 -103
  45. package/dist/presets/products.d.ts +9 -7
  46. package/dist/presets/products.js +89 -21
  47. package/dist/presets/reconciliation.d.ts +18 -0
  48. package/dist/presets/reconciliation.js +721 -0
  49. package/dist/presets/reporting.d.ts +14 -0
  50. package/dist/presets/reporting.js +862 -0
  51. package/dist/protocol/connection.d.ts +2 -0
  52. package/dist/protocol/connection.js +4 -0
  53. package/dist/protocol/dtoTypes.d.ts +30 -0
  54. package/dist/protocol/dtoTypes.js +250 -0
  55. package/dist/protocol/errors.d.ts +3 -1
  56. package/dist/protocol/errors.js +2 -0
  57. package/dist/protocol/fieldTypes.js +5 -0
  58. package/dist/protocol/router.d.ts +1 -0
  59. package/dist/protocol/router.js +3 -3
  60. package/dist/protocol/schemaValidation.d.ts +1 -1
  61. package/dist/protocol/schemaValidation.js +53 -8
  62. package/dist/server.js +34 -2
  63. package/dist/types.d.ts +50 -2
  64. package/package.json +1 -1
  65. package/src/db/schema.ts +56 -13
  66. package/src/db/store.ts +5 -0
  67. package/src/handlers/auth.ts +211 -37
  68. package/src/handlers/commitEvent.ts +44 -19
  69. package/src/handlers/crudEvents.ts +9 -2
  70. package/src/handlers/eventValidation.ts +6 -3
  71. package/src/handlers/http.ts +83 -42
  72. package/src/handlers/jsonSchema.ts +86 -23
  73. package/src/handlers/meta.ts +77 -9
  74. package/src/handlers/requestReply.ts +42 -6
  75. package/src/index.ts +7 -0
  76. package/src/presets/auth.ts +961 -0
  77. package/src/presets/cronExpression.ts +445 -0
  78. package/src/presets/fileServer.ts +475 -0
  79. package/src/presets/gsf.ts +475 -0
  80. package/src/presets/index.ts +5 -0
  81. package/src/presets/javaTime.ts +354 -0
  82. package/src/presets/multipart.ts +110 -0
  83. package/src/presets/notify.ts +312 -0
  84. package/src/presets/notifyDispatch.ts +685 -0
  85. package/src/presets/notifyRules.ts +866 -0
  86. package/src/presets/platform/backing.json +8058 -217
  87. package/src/presets/platform/criteria-model.json +362 -0
  88. package/src/presets/platform/time-zones.json +608 -0
  89. package/src/presets/platform.ts +204 -115
  90. package/src/presets/products.ts +125 -19
  91. package/src/presets/reconciliation.ts +824 -0
  92. package/src/presets/reporting.ts +953 -0
  93. package/src/protocol/connection.ts +4 -0
  94. package/src/protocol/dtoTypes.ts +310 -0
  95. package/src/protocol/errors.ts +13 -1
  96. package/src/protocol/fieldTypes.ts +5 -0
  97. package/src/protocol/router.ts +3 -3
  98. package/src/protocol/schemaValidation.ts +61 -8
  99. package/src/server.ts +38 -2
  100. package/src/types.ts +147 -3
@@ -0,0 +1,953 @@
1
+ // The reporting product's events and computed request servers, as its scripts
2
+ // at the version the showcase pins run them (reporting v8.15.3,
3
+ // scripts/platform-preset/seeds/reporting@8.15.3/scripts:
4
+ // reporting-eventhandler.kts below as EH, reporting-reqrep.kts as RR), with
5
+ // what they call in the product's ReportingManager (reporting-app 8.15.3).
6
+ //
7
+ // A report run writes its GENERATED_REPORT row, with the file name, the
8
+ // status and a file id, but no file: the datasources aren't run and nothing
9
+ // is rendered. Delivering it to a notify destination raises the notification
10
+ // genesis-notify routes; an SFTP destination fails, as the product's TODO()
11
+ // does.
12
+ import { randomUUID } from 'node:crypto';
13
+ import { compareRecordIds, compareValues } from '../db/ordering.ts';
14
+ import { primaryKeyIndexName } from '../db/schema.ts';
15
+ import { checkUnique } from '../handlers/crudEvents.ts';
16
+ import { requestServerReplyProperties } from '../handlers/jsonSchema.ts';
17
+ import { listResources } from '../handlers/resources.ts';
18
+ import { NackError } from '../protocol/errors.ts';
19
+ import type {
20
+ EventHandler,
21
+ EventHandlerCtx,
22
+ EventSchemaOverride,
23
+ FieldDef,
24
+ RequestReplyDef,
25
+ Row,
26
+ } from '../types.ts';
27
+ import { cronExpressionError } from './cronExpression.ts';
28
+ import { newFileStorageId } from './fileServer.ts';
29
+ import {
30
+ hostZone,
31
+ knownZone,
32
+ jodaFormat,
33
+ jodaIso,
34
+ JVM_ZONE_IDS,
35
+ kotlinString,
36
+ zoneIdError,
37
+ } from './javaTime.ts';
38
+ import { dto, nullable } from './notify.ts';
39
+ import type { RaisedNotification } from './notifyDispatch.ts';
40
+
41
+ // --- schemas ---------------------------------------------------------------------
42
+
43
+ const EVENT_CLASS = 'global.genesis.reporting.message.event';
44
+ const DAO_EVENT_CLASS = 'global.genesis.gen.dao.event';
45
+ // The product's enums are its tables' own: InputType is
46
+ // global.genesis.gen.dao.enums.reporting.report_datasource.InputType.
47
+ const enumOf = (table: string, name: string, values: string[], more: Partial<FieldDef> = {}) =>
48
+ dto(name, 'ENUM', {
49
+ values,
50
+ enumClass: `global.genesis.gen.dao.enums.reporting.${table}.${name
51
+ .toLowerCase()
52
+ .replace(/(^|_)([a-z])/g, (_match, _sep, letter: string) => letter.toUpperCase())}`,
53
+ ...more,
54
+ });
55
+ const optional = { optional: true };
56
+ const text = (name: string) => dto(name, 'STRING', nullable);
57
+
58
+ // DatasourceConfigurationInsert: the transformer configuration (any object
59
+ // here: its expression tree isn't described) and ReportDatasourceInsert
60
+ // unwrapped.
61
+ const DATASOURCE: FieldDef = dto('DATA_SOURCES', 'ARRAY', {
62
+ items: {
63
+ type: 'OBJECT',
64
+ className: `${EVENT_CLASS}.DatasourceConfigurationInsert`,
65
+ nullable: false,
66
+ fields: [
67
+ dto('TRANSFORMER_CONFIGURATION', 'MAP', nullable),
68
+ dto('KEY', 'STRING'),
69
+ dto('NAME', 'STRING'),
70
+ enumOf('report_datasource', 'INPUT_TYPE', ['REQ_REP', 'DATA_PIPELINE'], optional),
71
+ enumOf('report_datasource', 'OUTPUT_TYPE', ['TABLE', 'RECORD_STREAM', 'CHART'], optional),
72
+ text('GROUP_KEY'),
73
+ enumOf(
74
+ 'report_datasource',
75
+ 'GROUPING_STRATEGY',
76
+ ['NONE', 'MULTI_SHEET', 'LOOKUP_TABLE'],
77
+ optional,
78
+ ),
79
+ ],
80
+ },
81
+ });
82
+ const DESTINATION_IDS = dto('DESTINATION_IDS', 'ARRAY', { items: { type: 'STRING' }, ...optional });
83
+ const PARAMETERS = dto('PARAMETERS', 'ARRAY', {
84
+ ...optional,
85
+ items: {
86
+ type: 'OBJECT',
87
+ className: `${DAO_EVENT_CLASS}.ReportParameterInsert`,
88
+ nullable: false,
89
+ fields: [
90
+ dto('PARAMETER_NAME', 'STRING'),
91
+ text('REPORT_DATASOURCE'),
92
+ text('REFERENCE_FIELD'),
93
+ enumOf('report_parameter', 'SOURCE', ['User Input', 'Lookup'], optional),
94
+ text('LOOKUP_RESOURCE'),
95
+ text('LOOKUP_DATA_FIELD'),
96
+ text('LOOKUP_DISPLAY_FIELD'),
97
+ ],
98
+ },
99
+ });
100
+ const SCHEDULES = dto('SCHEDULES', 'ARRAY', {
101
+ ...optional,
102
+ items: {
103
+ type: 'OBJECT',
104
+ className: 'global.genesis.reporting.message.common.ReportSchedule',
105
+ nullable: false,
106
+ fields: [dto('CRON_EXPRESSION', 'STRING'), dto('TIME_ZONE', 'STRING')],
107
+ },
108
+ });
109
+ const OUTPUT_FORMATS = ['CSV', 'PDF', 'HTML', 'XLSX'];
110
+ // The fields of a generated DAO event class (global.genesis.gen.dao.event) a
111
+ // DTO unwraps: described with the DAO's annotations, its STRING lengths
112
+ // (reporting-tables-dictionary.kts) checked.
113
+ const fromDao =
114
+ (lengths: Record<string, number>) =>
115
+ (field: FieldDef): FieldDef => ({
116
+ ...field,
117
+ dao: true,
118
+ ...(lengths[field.name] ? { maxSize: lengths[field.name] } : {}),
119
+ });
120
+ const REPORT_CONFIG_LENGTHS: Record<string, number> = {
121
+ NAME: 256,
122
+ DESCRIPTION: 10_000,
123
+ FILE_NAME: 256,
124
+ OUTPUT_DIRECTORY: 1024,
125
+ };
126
+ const savedReport = fromDao({
127
+ REPORT_COLUMNS: 10_000,
128
+ REPORT_DATASOURCE: 200,
129
+ REPORT_DESCRIPTION: 10_000,
130
+ });
131
+ // ReportConfigInsert unwrapped: defaults everywhere but FILE_NAME and NAME.
132
+ const CONFIG_INSERT: FieldDef[] = [
133
+ dto('AUTO_DISPATCH', 'BOOLEAN', optional),
134
+ text('DESCRIPTION'),
135
+ text('DOCUMENT_TEMPLATE_ID'),
136
+ dto('FILE_NAME', 'STRING'),
137
+ text('ID'),
138
+ dto('NAME', 'STRING'),
139
+ text('OUTPUT_DIRECTORY'),
140
+ enumOf('report_config', 'OUTPUT_FORMAT', OUTPUT_FORMATS, optional),
141
+ ].map(fromDao(REPORT_CONFIG_LENGTHS));
142
+ // ReportConfigModify unwrapped: a modify class has no defaults.
143
+ const CONFIG_MODIFY: FieldDef[] = [
144
+ dto('AUTO_DISPATCH', 'BOOLEAN'),
145
+ dto('DESCRIPTION', 'STRING', { nullable: true }),
146
+ dto('DOCUMENT_TEMPLATE_ID', 'STRING', { nullable: true }),
147
+ dto('FILE_NAME', 'STRING'),
148
+ dto('ID', 'STRING'),
149
+ dto('NAME', 'STRING'),
150
+ dto('OUTPUT_DIRECTORY', 'STRING', { nullable: true }),
151
+ enumOf('report_config', 'OUTPUT_FORMAT', OUTPUT_FORMATS),
152
+ ].map(fromDao(REPORT_CONFIG_LENGTHS));
153
+ const byId = (table: string, className: string): EventSchemaOverride => ({
154
+ table,
155
+ pkOnly: true,
156
+ className: `global.genesis.gen.dao.${className}`,
157
+ });
158
+
159
+ const SCHEMAS: Record<string, EventSchemaOverride> = {
160
+ // SavedReportsInsertWrapper: its own REPORT_DATA_SOURCE, SavedReportsInsert
161
+ // unwrapped.
162
+ EVENT_SAVED_REPORTS_INSERT: {
163
+ className: `${EVENT_CLASS}.SavedReportsInsertWrapper`,
164
+ fields: [
165
+ text('REPORT_DATA_SOURCE'),
166
+ ...[
167
+ text('REPORT_COLUMNS'),
168
+ text('REPORT_DATASOURCE'),
169
+ text('REPORT_DESCRIPTION'),
170
+ text('REPORT_ID'),
171
+ dto('REPORT_NAME', 'STRING'),
172
+ ].map(savedReport),
173
+ ],
174
+ },
175
+ EVENT_SAVED_REPORTS_UPDATE: {
176
+ className: `${EVENT_CLASS}.SavedReportsModifyWrapper`,
177
+ fields: [
178
+ savedReport(dto('REPORT_COLUMNS', 'STRING', { nullable: true })),
179
+ text('REPORT_DATA_SOURCE'),
180
+ savedReport(text('REPORT_DATASOURCE')),
181
+ savedReport(dto('REPORT_DESCRIPTION', 'STRING', { nullable: true })),
182
+ savedReport(dto('REPORT_ID', 'STRING')),
183
+ savedReport(dto('REPORT_NAME', 'STRING')),
184
+ ],
185
+ },
186
+ EVENT_SAVED_REPORTS_DELETE: byId('SAVED_REPORTS', 'SavedReports.ByReportId'),
187
+ EVENT_REPORT_CONFIG_INSERT: {
188
+ className: `${EVENT_CLASS}.ReportingConfigurationInsert`,
189
+ fields: [DATASOURCE, DESTINATION_IDS, PARAMETERS, ...CONFIG_INSERT, SCHEDULES],
190
+ },
191
+ EVENT_REPORT_CONFIG_UPDATE: {
192
+ className: `${EVENT_CLASS}.ReportingConfigurationModify`,
193
+ fields: [DATASOURCE, DESTINATION_IDS, PARAMETERS, ...CONFIG_MODIFY, SCHEDULES],
194
+ },
195
+ EVENT_REPORT_CONFIG_DELETE: byId('REPORT_CONFIG', 'ReportConfig.ById'),
196
+ EVENT_NOTIFY_DESTINATION_INSERT: {
197
+ className: `${EVENT_CLASS}.NotifyDestinationInsert`,
198
+ fields: [dto('NAME', 'STRING'), dto('TOPIC', 'STRING')],
199
+ },
200
+ EVENT_NOTIFY_DESTINATION_UPDATE: {
201
+ className: `${EVENT_CLASS}.NotifyDestinationUpdate`,
202
+ fields: [dto('ID', 'STRING'), dto('NAME', 'STRING'), dto('TOPIC', 'STRING')],
203
+ },
204
+ EVENT_NOTIFY_DESTINATION_DELETE: byId('REPORT_DESTINATION', 'ReportDestination.ById'),
205
+ // SMTP in the names, SFTP in the classes and tables.
206
+ EVENT_SMTP_DESTINATION_INSERT: {
207
+ className: `${EVENT_CLASS}.SftpDestinationInsert`,
208
+ fields: [dto('NAME', 'STRING'), dto('OUTPUT_DIRECTORY', 'STRING')],
209
+ },
210
+ EVENT_SMTP_DESTINATION_UPDATE: {
211
+ className: `${EVENT_CLASS}.SftpDestinationUpdate`,
212
+ fields: [dto('ID', 'STRING'), dto('NAME', 'STRING'), dto('OUTPUT_DIRECTORY', 'STRING')],
213
+ },
214
+ EVENT_SMTP_DESTINATION_DELETE: byId('REPORT_DESTINATION', 'ReportDestination.ById'),
215
+ EVENT_GENERATE_REPORT: {
216
+ className: `${EVENT_CLASS}.GenerateReport`,
217
+ fields: [dto('ID', 'STRING'), dto('PARAMETERS', 'MAP', optional)],
218
+ },
219
+ EVENT_DISPATCH_REPORT: byId('GENERATED_REPORT', 'GeneratedReport.ById'),
220
+ EVENT_GENERATED_REPORT_DELETE: byId('GENERATED_REPORT', 'GeneratedReport.ById'),
221
+ };
222
+
223
+ // --- writes ------------------------------------------------------------------------
224
+
225
+ // entityDb's writes: unique indexes checked (DUPLICATE_KEY), a missing row
226
+ // RECORD_NOT_FOUND, each change pushed live.
227
+ function insert(ctx: EventHandlerCtx, table: string, row: Row): Row {
228
+ checkUnique(table, ctx.config.tables![table], row, ctx.store);
229
+ const written = ctx.store.insertRow(table, row);
230
+ ctx.broadcastTableChange(table, 'INSERT', ctx.store.rowKey(table, written));
231
+ return written;
232
+ }
233
+ function modify(ctx: EventHandlerCtx, table: string, key: string, patch: Row): Row {
234
+ const def = ctx.config.tables![table];
235
+ const existing = ctx.store.getRow(table, key);
236
+ if (!existing) throw NackError.recordNotFound(table, primaryKeyIndexName(table, def));
237
+ checkUnique(table, def, { ...existing, ...patch }, ctx.store, key);
238
+ const written = ctx.store.updateRow(table, key, patch)!;
239
+ ctx.broadcastTableChange(table, 'MODIFY', key);
240
+ return written;
241
+ }
242
+ function remove(ctx: EventHandlerCtx, table: string, key: string): Row {
243
+ const existing = ctx.store.getRow(table, key);
244
+ if (!existing || !ctx.store.deleteRow(table, key)) throw NackError.recordNotFound(table);
245
+ ctx.broadcastTableChange(table, 'DELETE', key);
246
+ return existing;
247
+ }
248
+ // A configuration's rows of a table. Its destinations come in DESTINATION_ID
249
+ // order, as the range read over ByReportConfigIdDestinationId gives them.
250
+ const rowsOf = (ctx: { store: EventHandlerCtx['store'] }, table: string, configId: string) => {
251
+ const rows = ctx.store.getAllRows(table).filter((row) => row.REPORT_CONFIG_ID === configId);
252
+ return table === 'REPORT_CONFIG_DESTINATION_MAP'
253
+ ? rows.sort((a, b) => compareValues(a.DESTINATION_ID, b.DESTINATION_ID))
254
+ : rows;
255
+ };
256
+ const removeAll = (ctx: EventHandlerCtx, table: string, configId: string) => {
257
+ for (const row of rowsOf(ctx, table, configId)) remove(ctx, table, ctx.store.rowKey(table, row));
258
+ };
259
+
260
+ // --- report configurations ---------------------------------------------------------
261
+
262
+ // TransformerConfiguration (genesis-transform): every property defaulted, so
263
+ // it's stored, and read back, whole.
264
+ const transformerDefaults = (): Row => ({
265
+ ROW_FILTERS: { OPERATION: 'AND', EXPRESSIONS: [], TYPE: 'PREDICATE_EXPRESSION' },
266
+ INCLUDE_COLUMNS: [],
267
+ COLUMN_TRANSFORMS: {},
268
+ DERIVED_FIELDS: {},
269
+ GROUP_BY_COLUMNS: { COLUMNS: [], AGGREGATION_OPERATIONS: [] },
270
+ SORT_BY_COLUMNS: { DIRECTION: 'ASCENDING', COLUMNS: [] },
271
+ COLUMN_FORMATS: {},
272
+ COLUMN_RENAMES: {},
273
+ DATE_TIME_FORMAT_TIMEZONE: null,
274
+ });
275
+ const isObject = (value: unknown): value is Row =>
276
+ typeof value === 'object' && value !== null && !Array.isArray(value);
277
+ function transformerConfiguration(sent: unknown): Row {
278
+ const defaults = transformerDefaults();
279
+ if (!isObject(sent)) return defaults;
280
+ return Object.fromEntries(
281
+ Object.entries(defaults).map(([key, fallback]) => {
282
+ const value = sent[key];
283
+ if (value === undefined || value === null) return [key, fallback];
284
+ return [
285
+ key,
286
+ isObject(fallback) && isObject(value) && !('TYPE' in fallback)
287
+ ? { ...fallback, ...value }
288
+ : value,
289
+ ];
290
+ }),
291
+ );
292
+ }
293
+ // The stored column: the configuration as Jackson writes it, "null" for an
294
+ // explicit null.
295
+ const storedTransformer = (sent: unknown) =>
296
+ sent === null ? 'null' : JSON.stringify(transformerConfiguration(sent));
297
+ // RR :119: the stored string read back, a null or "null" the defaults.
298
+ function readTransformer(stored: unknown): Row {
299
+ if (typeof stored !== 'string') return transformerDefaults();
300
+ try {
301
+ return transformerConfiguration(JSON.parse(stored));
302
+ } catch {
303
+ return transformerDefaults();
304
+ }
305
+ }
306
+
307
+ // validateSchedules (EH :42-67): each schedule's cron expression (log4j's
308
+ // CronExpression) and zone (ZoneId.of), every failure in one NACK.
309
+ function scheduleErrors(schedules: Row[]): string[] {
310
+ const errors: string[] = [];
311
+ schedules.forEach((schedule, index) => {
312
+ const cron = cronExpressionError(String(schedule.CRON_EXPRESSION));
313
+ if (cron !== undefined) {
314
+ errors.push(
315
+ `Cron expression ${schedule.CRON_EXPRESSION} in schedule at position ${index} in list is invalid: ${cron}`,
316
+ );
317
+ }
318
+ const zone = zoneIdError(String(schedule.TIME_ZONE));
319
+ if (zone !== undefined) {
320
+ errors.push(
321
+ `Timezone ID ${schedule.TIME_ZONE} in schedule at position ${index} in list is invalid: ${zone}`,
322
+ );
323
+ }
324
+ });
325
+ return errors;
326
+ }
327
+ function checkSchedules(details: Row): void {
328
+ const errors = scheduleErrors(details.SCHEDULES ?? []);
329
+ if (errors.length) {
330
+ throw new NackError(
331
+ errors.map((TEXT) => ({ '@type': 'StandardError', CODE: 'VALIDATION_ERROR', TEXT })),
332
+ );
333
+ }
334
+ }
335
+
336
+ // The rows a configuration's DATA_SOURCES, DESTINATION_IDS, PARAMETERS and
337
+ // SCHEDULES make (EH :157-192).
338
+ function writeDatasources(ctx: EventHandlerCtx, configId: string, details: Row) {
339
+ for (const source of (details.DATA_SOURCES as Row[] | undefined) ?? []) {
340
+ insert(ctx, 'REPORT_DATASOURCE', {
341
+ REPORT_CONFIG_ID: configId,
342
+ KEY: source.KEY,
343
+ NAME: source.NAME,
344
+ INPUT_TYPE: source.INPUT_TYPE ?? 'REQ_REP',
345
+ OUTPUT_TYPE: source.OUTPUT_TYPE ?? 'TABLE',
346
+ TRANSFORMER_CONFIGURATION: storedTransformer(source.TRANSFORMER_CONFIGURATION),
347
+ GROUP_KEY: source.GROUP_KEY ?? null,
348
+ GROUPING_STRATEGY: source.GROUPING_STRATEGY ?? 'NONE',
349
+ });
350
+ }
351
+ }
352
+ function writeDestinations(ctx: EventHandlerCtx, configId: string, details: Row) {
353
+ for (const DESTINATION_ID of (details.DESTINATION_IDS as string[] | undefined) ?? []) {
354
+ insert(ctx, 'REPORT_CONFIG_DESTINATION_MAP', { REPORT_CONFIG_ID: configId, DESTINATION_ID });
355
+ }
356
+ }
357
+ function writeParameters(ctx: EventHandlerCtx, configId: string, details: Row) {
358
+ for (const parameter of (details.PARAMETERS as Row[] | undefined) ?? []) {
359
+ insert(ctx, 'REPORT_PARAMETER', {
360
+ REPORT_CONFIG_ID: configId,
361
+ PARAMETER_NAME: parameter.PARAMETER_NAME,
362
+ REPORT_DATASOURCE: parameter.REPORT_DATASOURCE ?? null,
363
+ REFERENCE_FIELD: parameter.REFERENCE_FIELD ?? null,
364
+ SOURCE: parameter.SOURCE ?? 'User Input',
365
+ LOOKUP_RESOURCE: parameter.LOOKUP_RESOURCE ?? null,
366
+ LOOKUP_DATA_FIELD: parameter.LOOKUP_DATA_FIELD ?? null,
367
+ LOOKUP_DISPLAY_FIELD: parameter.LOOKUP_DISPLAY_FIELD ?? null,
368
+ });
369
+ }
370
+ }
371
+ // createCronRule (EH :69-95): a rule the cron scheduler would fire
372
+ // EVENT_GENERATE_REPORT {ID} on; the mock has no scheduler.
373
+ function writeSchedules(ctx: EventHandlerCtx, configId: string, details: Row, user: string) {
374
+ ((details.SCHEDULES as Row[] | undefined) ?? []).forEach((schedule, index) => {
375
+ const rule = insert(ctx, 'CRON_RULE', {
376
+ NAME: randomUUID(),
377
+ DESCRIPTION: `Schedule rule #${index} for Report Config '${details.NAME}'`,
378
+ USER_NAME: user,
379
+ CRON_EXPRESSION: schedule.CRON_EXPRESSION,
380
+ TIME_ZONE: schedule.TIME_ZONE,
381
+ RULE_STATUS: 'ENABLED',
382
+ MESSAGE_TYPE: 'EVENT_GENERATE_REPORT',
383
+ RESULT_EXPRESSION: `((ID = "${configId}"))`,
384
+ PROCESS_NAME: null,
385
+ RULE_TYPE: null,
386
+ });
387
+ insert(ctx, 'REPORT_CONFIG_CRON_RULE_MAP', {
388
+ REPORT_CONFIG_ID: configId,
389
+ CRON_RULE_NAME: rule.NAME,
390
+ });
391
+ });
392
+ }
393
+ // A configuration's schedules: its cron-map rows and the rules they name.
394
+ function removeSchedules(ctx: EventHandlerCtx, configId: string) {
395
+ const maps = rowsOf(ctx, 'REPORT_CONFIG_CRON_RULE_MAP', configId);
396
+ for (const map of maps)
397
+ remove(
398
+ ctx,
399
+ 'REPORT_CONFIG_CRON_RULE_MAP',
400
+ ctx.store.rowKey('REPORT_CONFIG_CRON_RULE_MAP', map),
401
+ );
402
+ // filterNotNull (EH :253-255, :290-292): a rule that's gone is skipped.
403
+ for (const map of maps) {
404
+ if (ctx.store.getRow('CRON_RULE', map.CRON_RULE_NAME)) {
405
+ remove(ctx, 'CRON_RULE', map.CRON_RULE_NAME);
406
+ }
407
+ }
408
+ }
409
+
410
+ // The configuration's columns an insert or a modify writes.
411
+ const configColumns = (details: Row, now: number, user: string): Row => ({
412
+ NAME: details.NAME,
413
+ DESCRIPTION: details.DESCRIPTION ?? null,
414
+ LAST_UPDATED_AT: now,
415
+ LAST_UPDATED_BY: user,
416
+ OUTPUT_FORMAT: details.OUTPUT_FORMAT ?? 'CSV',
417
+ FILE_NAME: details.FILE_NAME,
418
+ OUTPUT_DIRECTORY: details.OUTPUT_DIRECTORY ?? null,
419
+ DOCUMENT_TEMPLATE_ID: details.DOCUMENT_TEMPLATE_ID ?? null,
420
+ AUTO_DISPATCH: details.AUTO_DISPATCH ?? false,
421
+ });
422
+
423
+ // --- saved reports (EH :28-40) -------------------------------------------------------
424
+
425
+ // createSavedReports: every value a string, a null "null", the columns under
426
+ // REPORT_COLUMN, the time as Joda's DateTime.toString() in the JVM's zone.
427
+ const savedReportReply = (row: Row): Row[] => [
428
+ {
429
+ REPORT_ID: row.REPORT_ID,
430
+ REPORT_NAME: row.REPORT_NAME,
431
+ CREATED_BY: row.CREATED_BY ?? 'null',
432
+ REPORT_DESCRIPTION: row.REPORT_DESCRIPTION ?? 'null',
433
+ REPORT_COLUMN: row.REPORT_COLUMNS ?? 'null',
434
+ REPORT_CREATED_ON: jodaIso(Number(row.REPORT_CREATED_ON), hostZone()),
435
+ REPORT_DATASOURCE: row.REPORT_DATASOURCE ?? 'null',
436
+ },
437
+ ];
438
+
439
+ // --- runs ----------------------------------------------------------------------------
440
+
441
+ // kotlin.NotImplementedError, which TODO() throws: an Error, not an
442
+ // Exception, so generateReport's catch lets it through.
443
+ class NotImplemented extends Error {}
444
+ // A Kotlin `!!` on null (Intrinsics.checkNotNull): an exception with no
445
+ // message.
446
+ class NullPointer extends Error {}
447
+
448
+ // The report's status, from STATUS's labels.
449
+ const PENDING = 'Pending';
450
+ const GENERATED = 'Generated';
451
+ const DELIVERED = 'Delivered';
452
+ const PARTIALLY_DELIVERED = 'Partially Delivered';
453
+ const FAILED = 'Failed';
454
+
455
+ const SUBSTITUTION = /\$\(([^:)]+)(?::([^)]*))?\)/g;
456
+
457
+ export interface ReportingOptions {
458
+ // Who an event runs as.
459
+ userOf(ctx: EventHandlerCtx): string;
460
+ // The sysdef's REPORTING_DEFAULT_TIMEZONE: the zone `$(timestamp:...)` in a
461
+ // file name is written in. Unset: the JVM's, which is the host's here.
462
+ timeZone?: string;
463
+ // The sysdef's REPORTING_DATASOURCE_LIST: the request servers
464
+ // ALL_REPORT_DATASOURCES offers. Unset or empty: all of them.
465
+ datasources?: string[];
466
+ // NotificationService, when genesis-notify is in the app.
467
+ notify?: (ctx: EventHandlerCtx, user: string, notification: RaisedNotification) => void;
468
+ }
469
+
470
+ export interface ReportingBacking {
471
+ eventHandlers: Record<string, EventHandler>;
472
+ eventSchemas: Record<string, EventSchemaOverride>;
473
+ requestReplies: Record<string, RequestReplyDef>;
474
+ }
475
+
476
+ export function reportingBacking(options: ReportingOptions): ReportingBacking {
477
+ // DateTimeZone.forID of the sysdef's zone; one it can't resolve is logged
478
+ // ("Unable to resolve timezone") and the JVM's used instead.
479
+ const zone = () =>
480
+ options.timeZone !== undefined && knownZone(options.timeZone) ? options.timeZone : hostZone();
481
+
482
+ // resolveSubstitutions (reporting-app core/UtilsKt): $(timestamp:<Joda
483
+ // pattern>), $(parameter:<key>); anything else left as written.
484
+ const substitute = (template: unknown, parameters: Row, now: number) =>
485
+ template === null || template === undefined
486
+ ? template
487
+ : String(template).replace(SUBSTITUTION, (match, type: string, argument?: string) => {
488
+ if (type === 'timestamp') {
489
+ return (
490
+ (argument === undefined ? undefined : jodaFormat(argument, now, zone())) ??
491
+ jodaIso(now, zone())
492
+ );
493
+ }
494
+ if (type === 'parameter') {
495
+ // The parameters are a Map: a key it doesn't have is null, and
496
+ // `$(parameter)` names none (`!!`).
497
+ if (argument === undefined) throw new NullPointer();
498
+ const value = Object.hasOwn(parameters, argument) ? parameters[argument] : undefined;
499
+ return value === undefined || value === null ? 'null' : kotlinString(value);
500
+ }
501
+ return match;
502
+ });
503
+
504
+ // buildParameters (ReportingManager): a parameter linked to a datasource
505
+ // names one the configuration has, and the field it reads.
506
+ function checkParameters(ctx: EventHandlerCtx, configId: string, sent: Row, keys: Set<string>) {
507
+ if (!Object.keys(sent).length) return;
508
+ const defined = new Map(
509
+ rowsOf(ctx, 'REPORT_PARAMETER', configId).map((row) => [row.PARAMETER_NAME as string, row]),
510
+ );
511
+ for (const name of Object.keys(sent)) {
512
+ const definition = defined.get(name);
513
+ if (
514
+ !definition ||
515
+ definition.REPORT_DATASOURCE === null ||
516
+ definition.REPORT_DATASOURCE === undefined
517
+ )
518
+ continue;
519
+ if (!keys.has(definition.REPORT_DATASOURCE)) {
520
+ throw new NackError(
521
+ `Could not find datasource ${definition.REPORT_DATASOURCE} referenced by parameter ${definition.PARAMETER_NAME}`,
522
+ );
523
+ }
524
+ if (definition.REFERENCE_FIELD === null || definition.REFERENCE_FIELD === undefined) {
525
+ throw new NackError('A parameter linked to a datasource must specify a reference field.');
526
+ }
527
+ }
528
+ }
529
+
530
+ // A request-server datasource the cluster doesn't serve (ReqRepMetadataCache).
531
+ function checkDatasources(ctx: EventHandlerCtx, sources: Row[]) {
532
+ const served = new Set(
533
+ listResources(ctx.config)
534
+ .filter((resource) => resource.RESOURCE_TYPE === 'REQUEST_SERVER')
535
+ .map((resource) => resource.RESOURCE_NAME),
536
+ );
537
+ for (const source of sources) {
538
+ if (source.INPUT_TYPE === 'REQ_REP' && !served.has(source.NAME)) {
539
+ throw new NackError(
540
+ `Unable to resolve client for feature ${source.NAME}, unable to generate report`,
541
+ );
542
+ }
543
+ }
544
+ }
545
+
546
+ // dispatchReport (ReportingManager): DELIVERED unless a destination is
547
+ // gone or has no notify record; a notify one gets the report's
548
+ // notification, an SFTP one TODO().
549
+ function dispatch(ctx: EventHandlerCtx, report: Row, config: Row, user: string): string {
550
+ let status = DELIVERED;
551
+ for (const map of rowsOf(ctx, 'REPORT_CONFIG_DESTINATION_MAP', config.ID)) {
552
+ const destination = ctx.store.getRow('REPORT_DESTINATION', map.DESTINATION_ID);
553
+ if (!destination) {
554
+ status = PARTIALLY_DELIVERED;
555
+ continue;
556
+ }
557
+ if (destination.TYPE === 'SFTP') throw new NotImplemented();
558
+ const notifyDestination = ctx.store
559
+ .getViewRows('NOTIFY_REPORT_DESTINATION')
560
+ .find((row) => row.ID === destination.ID);
561
+ if (!notifyDestination) {
562
+ status = PARTIALLY_DELIVERED;
563
+ continue;
564
+ }
565
+ // NotifyDispatcher.send.
566
+ if (!report.REPORT_FILE_STORAGE_ID) {
567
+ throw new NackError('Unable to dispatch report with no file storage ID');
568
+ }
569
+ options.notify?.(ctx, user, {
570
+ HEADER: `New Report Generated: ${config.DESCRIPTION ?? 'null'}`,
571
+ BODY: `A new report has been generated with name ${config.FILE_NAME}`,
572
+ NOTIFY_SEVERITY: 'Information',
573
+ ROUTING_TYPE: 'TOPIC',
574
+ ROUTING_DATA: notifyDestination.TOPIC ?? null,
575
+ NOTIFY_ATTACHMENTS: [report.REPORT_FILE_STORAGE_ID],
576
+ });
577
+ }
578
+ return status;
579
+ }
580
+
581
+ // GENERATE_REPORT isn't transactional: what generateReport wrote before
582
+ // failing stays, though the event NACKs. The engine rolls the event back,
583
+ // so the row is written again once it has.
584
+ function keepAfterNack(ctx: EventHandlerCtx, report: Row, patch: Row) {
585
+ const { GENERATED_REPORT_ID, RECORD_ID, TIMESTAMP, ...columns } = report;
586
+ setImmediate(() => {
587
+ const { store } = ctx;
588
+ if (store.getRow('GENERATED_REPORT', GENERATED_REPORT_ID)) {
589
+ store.updateRow('GENERATED_REPORT', GENERATED_REPORT_ID, patch);
590
+ ctx.broadcastTableChange('GENERATED_REPORT', 'MODIFY', GENERATED_REPORT_ID);
591
+ return;
592
+ }
593
+ // The row the event wrote, its id included.
594
+ const kept = store.insertRow('GENERATED_REPORT', {
595
+ GENERATED_REPORT_ID,
596
+ ...columns,
597
+ ...patch,
598
+ });
599
+ ctx.broadcastTableChange('GENERATED_REPORT', 'INSERT', kept.GENERATED_REPORT_ID);
600
+ });
601
+ }
602
+
603
+ const userOf = options.userOf;
604
+
605
+ const eventHandlers: Record<string, EventHandler> = {
606
+ // EH :99-113: REPORT_DATASOURCE, else the legacy REPORT_DATA_SOURCE.
607
+ EVENT_SAVED_REPORTS_INSERT: (details, ctx) => {
608
+ if (ctx.validate) return {};
609
+ const row = insert(ctx, 'SAVED_REPORTS', {
610
+ ...(details.REPORT_ID === undefined || details.REPORT_ID === null
611
+ ? {}
612
+ : { REPORT_ID: details.REPORT_ID }),
613
+ REPORT_NAME: details.REPORT_NAME,
614
+ REPORT_DESCRIPTION: details.REPORT_DESCRIPTION ?? null,
615
+ REPORT_DATASOURCE: details.REPORT_DATASOURCE ?? details.REPORT_DATA_SOURCE ?? null,
616
+ REPORT_COLUMNS: details.REPORT_COLUMNS ?? null,
617
+ CREATED_BY: userOf(ctx),
618
+ REPORT_CREATED_ON: Date.now(),
619
+ });
620
+ return { generated: savedReportReply(row) };
621
+ },
622
+ // EH :116-129: the editor becomes the creator, now the creation time.
623
+ EVENT_SAVED_REPORTS_UPDATE: (details, ctx) => {
624
+ if (ctx.validate) return {};
625
+ if (!ctx.store.getRow('SAVED_REPORTS', details.REPORT_ID)) {
626
+ throw NackError.nack(`Report with id ${details.REPORT_ID} does not exist`);
627
+ }
628
+ const row = modify(ctx, 'SAVED_REPORTS', details.REPORT_ID, {
629
+ REPORT_NAME: details.REPORT_NAME,
630
+ REPORT_DESCRIPTION: details.REPORT_DESCRIPTION ?? null,
631
+ REPORT_DATASOURCE: details.REPORT_DATASOURCE ?? details.REPORT_DATA_SOURCE ?? null,
632
+ REPORT_COLUMNS: details.REPORT_COLUMNS ?? null,
633
+ CREATED_BY: userOf(ctx),
634
+ REPORT_CREATED_ON: Date.now(),
635
+ });
636
+ return { generated: savedReportReply(row) };
637
+ },
638
+ EVENT_SAVED_REPORTS_DELETE: (details, ctx) => {
639
+ if (ctx.validate) return {};
640
+ remove(ctx, 'SAVED_REPORTS', details.REPORT_ID);
641
+ return {};
642
+ },
643
+ // EH :139-201
644
+ EVENT_REPORT_CONFIG_INSERT: (details, ctx) => {
645
+ checkSchedules(details);
646
+ if (ctx.validate) return {};
647
+ const user = userOf(ctx);
648
+ const now = Date.now();
649
+ const config = insert(ctx, 'REPORT_CONFIG', {
650
+ ...(details.ID === undefined || details.ID === null ? {} : { ID: details.ID }),
651
+ ...configColumns(details, now, user),
652
+ CREATED_ON: now,
653
+ CREATED_BY: user,
654
+ });
655
+ writeDatasources(ctx, config.ID, details);
656
+ writeDestinations(ctx, config.ID, details);
657
+ writeParameters(ctx, config.ID, details);
658
+ writeSchedules(ctx, config.ID, details, user);
659
+ return { generated: [{ REPORT_CONFIG_ID: config.ID }] };
660
+ },
661
+ // EH :204-278: the configuration modified, everything under it replaced.
662
+ EVENT_REPORT_CONFIG_UPDATE: (details, ctx) => {
663
+ checkSchedules(details);
664
+ if (ctx.validate) return {};
665
+ const user = userOf(ctx);
666
+ const id = details.ID;
667
+ modify(ctx, 'REPORT_CONFIG', id, configColumns(details, Date.now(), user));
668
+ removeAll(ctx, 'REPORT_DATASOURCE', id);
669
+ writeDatasources(ctx, id, details);
670
+ removeAll(ctx, 'REPORT_PARAMETER', id);
671
+ writeParameters(ctx, id, details);
672
+ removeAll(ctx, 'REPORT_CONFIG_DESTINATION_MAP', id);
673
+ writeDestinations(ctx, id, details);
674
+ removeSchedules(ctx, id);
675
+ writeSchedules(ctx, id, details, user);
676
+ return {};
677
+ },
678
+ // EH :281-297: its destination maps and generated reports are left.
679
+ EVENT_REPORT_CONFIG_DELETE: (details, ctx) => {
680
+ if (ctx.validate) return {};
681
+ remove(ctx, 'REPORT_CONFIG', details.ID);
682
+ removeAll(ctx, 'REPORT_DATASOURCE', details.ID);
683
+ removeAll(ctx, 'REPORT_PARAMETER', details.ID);
684
+ removeSchedules(ctx, details.ID);
685
+ return {};
686
+ },
687
+ ...destinationHandlers('NOTIFY', 'NOTIFY_DESTINATION', 'TOPIC'),
688
+ ...destinationHandlers('SMTP', 'SFTP_DESTINATION', 'OUTPUT_DIRECTORY'),
689
+ // EH :394-408, ReportingManager.generateReport.
690
+ EVENT_GENERATE_REPORT: (details, ctx) => {
691
+ if (ctx.validate) return {};
692
+ const config = ctx.store.getRow('REPORT_CONFIG', details.ID);
693
+ if (!config) {
694
+ throw new NackError(
695
+ `ID ${details.ID} did not correspond to any known report configuration`,
696
+ );
697
+ }
698
+ const sources = rowsOf(ctx, 'REPORT_DATASOURCE', config.ID);
699
+ if (!sources.length) {
700
+ throw new NackError(
701
+ 'Report configuration must have at least one source of data configured',
702
+ );
703
+ }
704
+ const user = userOf(ctx);
705
+ const now = Date.now();
706
+ const report = insert(ctx, 'GENERATED_REPORT', {
707
+ REPORT_CONFIG_ID: config.ID,
708
+ CREATED_BY: user,
709
+ CREATED_ON: now,
710
+ STATUS: PENDING,
711
+ FILE_NAME: null,
712
+ REPORT_FILE_STORAGE_ID: null,
713
+ MESSAGE: null,
714
+ });
715
+ try {
716
+ const parameters = (details.PARAMETERS as Row | undefined) ?? {};
717
+ checkParameters(ctx, config.ID, parameters, new Set(sources.map((source) => source.KEY)));
718
+ const fileName = substitute(config.FILE_NAME, parameters, now);
719
+ // Resolved too (generateReport), though the mock writes no file there.
720
+ substitute(config.OUTPUT_DIRECTORY, parameters, now);
721
+ checkDatasources(ctx, sources);
722
+ // What file-server would give the stored file.
723
+ const stored = { ...report, REPORT_FILE_STORAGE_ID: newFileStorageId() };
724
+ const destinations = rowsOf(ctx, 'REPORT_CONFIG_DESTINATION_MAP', config.ID);
725
+ let status = GENERATED;
726
+ if (destinations.length)
727
+ status = config.AUTO_DISPATCH === true ? dispatch(ctx, stored, config, user) : PENDING;
728
+ modify(ctx, 'GENERATED_REPORT', report.GENERATED_REPORT_ID, {
729
+ FILE_NAME: `${fileName}.${String(config.OUTPUT_FORMAT).toLowerCase()}`,
730
+ REPORT_FILE_STORAGE_ID: stored.REPORT_FILE_STORAGE_ID,
731
+ STATUS: status,
732
+ });
733
+ return { generated: [{ GENERATED_REPORT_ID: report.GENERATED_REPORT_ID }] };
734
+ } catch (error) {
735
+ if (error instanceof NotImplemented) {
736
+ keepAfterNack(ctx, report, {});
737
+ throw NackError.standard('INTERNAL_ERROR', 'An operation is not implemented.');
738
+ }
739
+ if (error instanceof NullPointer) {
740
+ keepAfterNack(ctx, report, { STATUS: FAILED, MESSAGE: null });
741
+ throw NackError.standard('INTERNAL_ERROR');
742
+ }
743
+ const message =
744
+ error instanceof NackError ? error.errors[0]?.TEXT : (error as Error).message;
745
+ keepAfterNack(ctx, report, { STATUS: FAILED, MESSAGE: message ?? null });
746
+ throw error;
747
+ }
748
+ },
749
+ // EH :417-461: checked even under VALIDATE.
750
+ EVENT_DISPATCH_REPORT: (details, ctx) => {
751
+ const id = details.GENERATED_REPORT_ID;
752
+ const report = ctx.store.getRow('GENERATED_REPORT', id);
753
+ if (!report)
754
+ throw new NackError(`GENERATED_REPORT ById(generatedReportId=${id}) not found in database`);
755
+ if (report.STATUS !== PENDING) throw new NackError('Failed requirement.');
756
+ const config = ctx.store.getRow('REPORT_CONFIG', report.REPORT_CONFIG_ID);
757
+ if (!config)
758
+ throw new NackError(
759
+ `REPORT_CONFIG ById(id=${report.REPORT_CONFIG_ID}) not found in database`,
760
+ );
761
+ if (!rowsOf(ctx, 'REPORT_CONFIG_DESTINATION_MAP', config.ID).length) {
762
+ throw new NackError('Unable to dispatch report with no destinations configured');
763
+ }
764
+ if (ctx.validate) return {};
765
+ let status: string;
766
+ try {
767
+ status = dispatch(ctx, report, config, userOf(ctx));
768
+ } catch (error) {
769
+ if (error instanceof NotImplemented) {
770
+ throw NackError.standard('INTERNAL_ERROR', 'An operation is not implemented.');
771
+ }
772
+ throw error;
773
+ }
774
+ modify(ctx, 'GENERATED_REPORT', id, { STATUS: status });
775
+ return {};
776
+ },
777
+ // EH :465-476. The file it names isn't deleted: the mock stored none.
778
+ EVENT_GENERATED_REPORT_DELETE: (details, ctx) => {
779
+ if (ctx.validate) return {};
780
+ remove(ctx, 'GENERATED_REPORT', details.GENERATED_REPORT_ID);
781
+ return {};
782
+ },
783
+ };
784
+
785
+ // --- request servers --------------------------------------------------------------
786
+
787
+ // REPORT_CONFIG_DETAILS (RR :112-152): the configuration flattened, with
788
+ // what's under it; nothing for an unknown id.
789
+ const configDetails: RequestReplyDef['resolver'] = ({ request, store }) => {
790
+ const config = store.getRow('REPORT_CONFIG', request.ID);
791
+ if (!config) return [];
792
+ const under = (table: string) => rowsOf({ store }, table, config.ID);
793
+ return [
794
+ {
795
+ DATA_SOURCES: under('REPORT_DATASOURCE').map(
796
+ ({ TRANSFORMER_CONFIGURATION, ...source }) => ({
797
+ TRANSFORMER_CONFIGURATION: readTransformer(TRANSFORMER_CONFIGURATION),
798
+ ...source,
799
+ }),
800
+ ),
801
+ DESTINATION_IDS: under('REPORT_CONFIG_DESTINATION_MAP').map((map) => map.DESTINATION_ID),
802
+ SCHEDULES: under('REPORT_CONFIG_CRON_RULE_MAP').flatMap((map) => {
803
+ const rule = store.getRow('CRON_RULE', map.CRON_RULE_NAME);
804
+ return rule
805
+ ? [{ CRON_EXPRESSION: rule.CRON_EXPRESSION ?? '', TIME_ZONE: rule.TIME_ZONE ?? '' }]
806
+ : [];
807
+ }),
808
+ PARAMETERS: under('REPORT_PARAMETER'),
809
+ ...config,
810
+ },
811
+ ];
812
+ };
813
+
814
+ // REPORT_PARAMETER_DETAILS (RR :156-190): the parameters, and a JSON schema
815
+ // for their values: a string each, or the type of the datasource field a
816
+ // linked one names (dropped when there's none).
817
+ const parameterDetails: RequestReplyDef['resolver'] = ({ request, store, config }) => {
818
+ const parameters = rowsOf({ store }, 'REPORT_PARAMETER', request.ID);
819
+ const sources = new Map(
820
+ rowsOf({ store }, 'REPORT_DATASOURCE', request.ID).map((row) => [row.KEY, row]),
821
+ );
822
+ // A LinkedHashMap: in the parameters' order (an object would put
823
+ // integer-like names first; `required` keeps it).
824
+ const properties = new Map<string, Row>();
825
+ for (const parameter of parameters) {
826
+ if (parameter.REPORT_DATASOURCE === null || parameter.REPORT_DATASOURCE === undefined) {
827
+ properties.set(parameter.PARAMETER_NAME, { type: 'string' });
828
+ continue;
829
+ }
830
+ const source = sources.get(parameter.REPORT_DATASOURCE);
831
+ if (source?.INPUT_TYPE !== 'REQ_REP') continue;
832
+ const replyProperties = requestServerReplyProperties(source.NAME, config, store);
833
+ if (!replyProperties) {
834
+ throw new Error(
835
+ `Unable to resolve client for feature ${source.NAME}, unable to generate report`,
836
+ );
837
+ }
838
+ const field = String(parameter.REFERENCE_FIELD);
839
+ if (Object.hasOwn(replyProperties, field)) {
840
+ properties.set(parameter.PARAMETER_NAME, replyProperties[field]);
841
+ }
842
+ }
843
+ return [
844
+ {
845
+ PARAMETERS: parameters,
846
+ SCHEMA: {
847
+ properties: Object.fromEntries(properties),
848
+ required: [...properties.keys()],
849
+ type: 'object',
850
+ },
851
+ },
852
+ ];
853
+ };
854
+
855
+ return {
856
+ eventHandlers,
857
+ eventSchemas: SCHEMAS,
858
+ requestReplies: {
859
+ // RR :90-110: every request server the cluster lists, or the sysdef's.
860
+ ALL_REPORT_DATASOURCES: {
861
+ requestFields: [],
862
+ resolver: ({ config }) =>
863
+ listResources(config)
864
+ .filter((resource) => resource.RESOURCE_TYPE === 'REQUEST_SERVER')
865
+ .map((resource) => resource.RESOURCE_NAME)
866
+ .filter((name) => !options.datasources?.length || options.datasources.includes(name))
867
+ .map((DATASOURCE_NAME) => ({ DATASOURCE_NAME })),
868
+ metadataRows: [{ DATASOURCE_NAME: '' }],
869
+ },
870
+ // RR :78-88: the reporting process's pipeline scripts define none.
871
+ REPORTING_DATA_PIPELINES: {
872
+ requestFields: [],
873
+ resolver: () => [],
874
+ fieldTypes: { NAME: 'STRING' },
875
+ },
876
+ REPORT_CONFIG_DETAILS: {
877
+ requestFields: ['ID'],
878
+ resolver: configDetails,
879
+ metadataRows: [
880
+ {
881
+ DATA_SOURCES: [],
882
+ DESTINATION_IDS: [],
883
+ PARAMETERS: [],
884
+ AUTO_DISPATCH: false,
885
+ CREATED_BY: '',
886
+ CREATED_ON: 0,
887
+ DESCRIPTION: '',
888
+ DOCUMENT_TEMPLATE_ID: '',
889
+ FILE_NAME: '',
890
+ ID: '',
891
+ LAST_UPDATED_AT: 0,
892
+ LAST_UPDATED_BY: '',
893
+ NAME: '',
894
+ OUTPUT_DIRECTORY: '',
895
+ OUTPUT_FORMAT: 'CSV',
896
+ SCHEDULES: [],
897
+ },
898
+ ],
899
+ },
900
+ REPORT_PARAMETER_DETAILS: {
901
+ requestFields: ['ID'],
902
+ resolver: parameterDetails,
903
+ metadataRows: [{ PARAMETERS: [], SCHEMA: {} }],
904
+ },
905
+ // RR :192-198: the JVM's zone ids.
906
+ VALID_TIME_ZONE: {
907
+ requestFields: [],
908
+ resolver: () => JVM_ZONE_IDS.map((ZONE_ID) => ({ ZONE_ID })),
909
+ fieldTypes: { ZONE_ID: 'STRING' },
910
+ },
911
+ // RR :53-65: getRangeFromEnd's third argument is the number of key
912
+ // fields, not a limit, so every report, newest first, up to MAX_ROWS.
913
+ GENERATED_REPORTS: {
914
+ source: 'GENERATED_REPORT_VIEW',
915
+ requestFields: [],
916
+ order: (a, b) => compareRecordIds(b.TIMESTAMP, a.TIMESTAMP),
917
+ },
918
+ },
919
+ };
920
+ }
921
+
922
+ // The destination events (EH :300-389), notify ones over NOTIFY_DESTINATION
923
+ // and TOPIC, "SMTP" ones over SFTP_DESTINATION and OUTPUT_DIRECTORY.
924
+ function destinationHandlers(
925
+ name: 'NOTIFY' | 'SMTP',
926
+ table: string,
927
+ column: string,
928
+ ): Record<string, EventHandler> {
929
+ const type = name === 'NOTIFY' ? 'NOTIFY' : 'SFTP';
930
+ return {
931
+ [`EVENT_${name}_DESTINATION_INSERT`]: (details, ctx) => {
932
+ if (ctx.validate) return {};
933
+ const destination = insert(ctx, 'REPORT_DESTINATION', { NAME: details.NAME, TYPE: type });
934
+ insert(ctx, table, { DESTINATION_ID: destination.ID, [column]: details[column] });
935
+ return {};
936
+ },
937
+ // Both write TYPE NOTIFY: SMTP_DESTINATION_UPDATE re-types an SFTP
938
+ // destination (EH :371).
939
+ [`EVENT_${name}_DESTINATION_UPDATE`]: (details, ctx) => {
940
+ if (ctx.validate) return {};
941
+ modify(ctx, 'REPORT_DESTINATION', details.ID, { NAME: details.NAME, TYPE: 'NOTIFY' });
942
+ modify(ctx, table, details.ID, { [column]: details[column] });
943
+ return {};
944
+ },
945
+ // The configurations' maps to it are left.
946
+ [`EVENT_${name}_DESTINATION_DELETE`]: (details, ctx) => {
947
+ if (ctx.validate) return {};
948
+ remove(ctx, 'REPORT_DESTINATION', details.ID);
949
+ remove(ctx, table, details.ID);
950
+ return {};
951
+ },
952
+ };
953
+ }