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