@aderis-erp/cli 1.1.3 → 1.1.5

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 (99) hide show
  1. package/README.md +1 -0
  2. package/dist/commands/access-groups.js +42 -8
  3. package/dist/commands/account-transaction-allocations.js +38 -4
  4. package/dist/commands/account-transactions.d.ts +2 -0
  5. package/dist/commands/account-transactions.js +68 -32
  6. package/dist/commands/accounts.js +46 -12
  7. package/dist/commands/agent-platform.js +37 -3
  8. package/dist/commands/agent-runs.js +49 -15
  9. package/dist/commands/analytics.js +39 -5
  10. package/dist/commands/api-clients.d.ts +58 -0
  11. package/dist/commands/api-clients.js +1375 -0
  12. package/dist/commands/api-keys.js +40 -6
  13. package/dist/commands/async-jobs.js +45 -11
  14. package/dist/commands/audit-log.js +38 -4
  15. package/dist/commands/bank-accounts.js +54 -20
  16. package/dist/commands/bank-integrations.js +56 -22
  17. package/dist/commands/business-partners.js +77 -43
  18. package/dist/commands/chat.js +43 -9
  19. package/dist/commands/credit-card-accounts.d.ts +4 -0
  20. package/dist/commands/credit-card-accounts.js +64 -25
  21. package/dist/commands/currencies.d.ts +56 -0
  22. package/dist/commands/currencies.js +1361 -0
  23. package/dist/commands/custody-accounts.d.ts +56 -0
  24. package/dist/commands/custody-accounts.js +1369 -0
  25. package/dist/commands/{integration-identities.d.ts → dashboards.d.ts} +3 -3
  26. package/dist/commands/dashboards.js +1381 -0
  27. package/dist/commands/delivery-notes.js +69 -35
  28. package/dist/commands/document-checksums.d.ts +57 -0
  29. package/dist/commands/{integration-identities.js → document-checksums.js} +48 -21
  30. package/dist/commands/dunning-configs.js +41 -7
  31. package/dist/commands/dunning-reminders.js +44 -10
  32. package/dist/commands/dunning-runs.js +37 -3
  33. package/dist/commands/email-transactions.js +39 -5
  34. package/dist/commands/employees.js +77 -43
  35. package/dist/commands/entity-configurations.js +39 -5
  36. package/dist/commands/event-mapping-rules.js +37 -3
  37. package/dist/commands/event-processor-mappings.js +41 -7
  38. package/dist/commands/files.js +48 -14
  39. package/dist/commands/financial-instrument-transactions.d.ts +56 -0
  40. package/dist/commands/financial-instrument-transactions.js +1369 -0
  41. package/dist/commands/financial-instrument-types.d.ts +56 -0
  42. package/dist/commands/financial-instrument-types.js +1369 -0
  43. package/dist/commands/financial-instruments.d.ts +56 -0
  44. package/dist/commands/financial-instruments.js +1369 -0
  45. package/dist/commands/health.js +41 -7
  46. package/dist/commands/imports.js +39 -5
  47. package/dist/commands/inbox.js +42 -8
  48. package/dist/commands/integrations.js +39 -5
  49. package/dist/commands/item-categories.js +41 -7
  50. package/dist/commands/items.js +42 -8
  51. package/dist/commands/journal-lines.js +37 -3
  52. package/dist/commands/journals.js +61 -27
  53. package/dist/commands/{workflows.d.ts → kpis.d.ts} +1 -1
  54. package/dist/commands/kpis.js +1371 -0
  55. package/dist/commands/ledgers.js +83 -49
  56. package/dist/commands/my-account.js +54 -20
  57. package/dist/commands/notifications.d.ts +56 -0
  58. package/dist/commands/notifications.js +1360 -0
  59. package/dist/commands/office-locations.js +41 -7
  60. package/dist/commands/payment-methods.js +46 -12
  61. package/dist/commands/payment-runs.js +54 -20
  62. package/dist/commands/payment-terms.js +42 -8
  63. package/dist/commands/payments.js +43 -9
  64. package/dist/commands/payroll-runs.js +71 -37
  65. package/dist/commands/permissions.js +37 -3
  66. package/dist/commands/price-lists.js +48 -14
  67. package/dist/commands/processor-mappings.js +40 -6
  68. package/dist/commands/processors.js +46 -12
  69. package/dist/commands/purchase-order-types.js +41 -7
  70. package/dist/commands/purchase-orders.js +60 -26
  71. package/dist/commands/reports.js +43 -8
  72. package/dist/commands/roles.js +40 -6
  73. package/dist/commands/salary-types.js +41 -7
  74. package/dist/commands/sales-invoices.js +85 -51
  75. package/dist/commands/sales-orders.js +69 -35
  76. package/dist/commands/saved-views.js +39 -5
  77. package/dist/commands/scheduled-processor-mappings.js +41 -7
  78. package/dist/commands/schedules.js +45 -11
  79. package/dist/commands/settings.d.ts +56 -0
  80. package/dist/commands/settings.js +1361 -0
  81. package/dist/commands/tags.js +42 -8
  82. package/dist/commands/tax-codes.js +44 -10
  83. package/dist/commands/tax-matrix.js +41 -7
  84. package/dist/commands/templates.js +50 -15
  85. package/dist/commands/tenants.js +44 -10
  86. package/dist/commands/tools.js +38 -4
  87. package/dist/commands/users.js +58 -24
  88. package/dist/commands/vat-declarations.js +61 -27
  89. package/dist/commands/vendor-invoices.js +82 -47
  90. package/dist/commands/webhooks.js +43 -9
  91. package/dist/commands/work-summary.d.ts +56 -0
  92. package/dist/commands/{workflows.js → work-summary.js} +49 -18
  93. package/dist/lib/auth/index.js +5 -0
  94. package/dist/lib/paths.d.ts +8 -0
  95. package/dist/lib/paths.js +16 -0
  96. package/dist/lib/production-guard.d.ts +42 -0
  97. package/dist/lib/production-guard.js +94 -0
  98. package/oclif.manifest.json +2142 -333
  99. package/package.json +9 -3
@@ -0,0 +1,1360 @@
1
+ import { Command, Args, Flags } from '@oclif/core';
2
+ import { apiRequest, ApiError, isTextualMediaType, normalizeSortBy } from '../lib/api-client.js';
3
+ import { getCurrentContext, getContext, getBaseUrls, hasCredentials, missingCredentialsMessage } from '../lib/config.js';
4
+ import { resolveUserPath } from '../lib/paths.js';
5
+ // 'upsert' loops create/update from the CLI, one request per record. It exists
6
+ // only where the API has no import endpoint of its own; those keep the name
7
+ // 'import' and are listed in SERVER_IMPORTS.
8
+ const HAS_UPSERT = false;
9
+ const HAS_EXPORT = false;
10
+ const HAS_CAMT053 = false;
11
+ const SERVER_IMPORTS = [];
12
+ const NESTED_UPSERTS = [];
13
+ const SUBCOMMANDS = [...["create"], ...(HAS_UPSERT ? ['upsert'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_UPSERTS.map(n => `upsert-${n}`)];
14
+ const ENDPOINTS = {
15
+ 'create': { method: 'POST', path: '/v1/notifications', summary: 'Send a live message to the readers of a record', pathParams: [], hasBody: true, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: ['onlyUserIds'], bodyMediaType: '', specParams: [] },
16
+ };
17
+ export default class Notifications extends Command {
18
+ static description = 'Manage notifications';
19
+ static examples = [
20
+ '<%= config.bin %> notifications create --data \'{...}\'',
21
+ ];
22
+ static args = {
23
+ action: Args.string({ description: 'Action: ' + SUBCOMMANDS.join(', '), required: true }),
24
+ id: Args.string({ description: 'Resource ID (for get, update, delete operations)', required: false }),
25
+ };
26
+ static flags = {
27
+ context: Flags.string({ char: 'c', aliases: ['config'], env: 'ADERIS_CONTEXT', description: 'Context to use for this command, overriding the current context (alias: --config)' }),
28
+ output: Flags.string({ char: 'o', description: 'Output format (default: table for upsert, json for other commands)', options: ['json', 'table', 'csv'] }),
29
+ table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
30
+ csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
31
+ data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
32
+ file: Flags.string({ char: 'f', description: 'Read request body from file', parse: async (input) => resolveUserPath(input) }),
33
+ set: Flags.string({ char: 's', description: 'Set individual field (e.g. --set firstName=John)', multiple: true }),
34
+ page: Flags.string({ description: 'Page number' }),
35
+ limit: Flags.string({ description: 'Items per page' }),
36
+ include: Flags.string({ description: 'Relations to include' }),
37
+ search: Flags.string({ description: 'Search term' }),
38
+ 'sort-by': Flags.string({ description: 'Sort field(s), comma-separated. Direction (:ASC/:DESC) is optional; date-like fields default to DESC, others to ASC.' }),
39
+ filter: Flags.string({ description: 'Filter (e.g. --filter status=ACTIVE). Operators: in:A,B, like:%, gt:, lt:, null:', multiple: true }),
40
+ query: Flags.string({ description: 'Additional query params as JSON' }),
41
+ fields: Flags.string({ description: 'Comma-separated list of fields to return, applied by the API (e.g. --fields=id,name,status)' }),
42
+ sanitize: Flags.boolean({ description: 'Remove null values, audit fields, and duplicate UUIDs from output' }),
43
+ meta: Flags.boolean({ description: 'Keep the API envelope in JSON output: data plus page, totals and sums' }),
44
+ 'show-http-request': Flags.boolean({ description: 'Show HTTP request details (method, URL, body)' }),
45
+ };
46
+ async run() {
47
+ const { args, flags } = await this.parse(Notifications);
48
+ // Bulk actions. 'import' is the API's own endpoint: one request, answered
49
+ // by a run that records what happened to every record. 'upsert' is the CLI
50
+ // looping create/update. A resource has one or the other, never both.
51
+ if (args.action === 'upsert') {
52
+ if (!HAS_UPSERT) {
53
+ this.error(SERVER_IMPORTS.includes('import')
54
+ ? 'This resource is imported by the API. Use: aderis notifications import --file data.json'
55
+ : 'Upsert needs both a create and an update endpoint, which this resource does not have');
56
+ }
57
+ await this.runUpsert(flags);
58
+ return;
59
+ }
60
+ if (args.action.startsWith('upsert-')) {
61
+ const suffix = args.action.replace('upsert-', '');
62
+ if (!NESTED_UPSERTS.includes(suffix)) {
63
+ this.error(SERVER_IMPORTS.includes('import-' + suffix)
64
+ ? `That resource is imported by the API. Use: aderis notifications import-${suffix} <id> --file data.json`
65
+ : `Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
66
+ }
67
+ await this.runNestedUpsert(suffix, args.id, flags);
68
+ return;
69
+ }
70
+ // Handle export action specially
71
+ if (args.action === 'export') {
72
+ if (!HAS_EXPORT)
73
+ this.error('Export not available for this resource');
74
+ await this.runExport(flags);
75
+ return;
76
+ }
77
+ // Handle CAMT.053 import specially - sends raw XML
78
+ if (args.action === 'import-camt053') {
79
+ if (!HAS_CAMT053)
80
+ this.error('CAMT.053 import not available for this resource');
81
+ await this.runCamt053Import(flags);
82
+ return;
83
+ }
84
+ if (SERVER_IMPORTS.includes(args.action)) {
85
+ await this.runServerImport(args.action, args.id, flags);
86
+ return;
87
+ }
88
+ // 'import' used to name the CLI's create/update loop on every resource. It
89
+ // now names the API endpoint, which most resources do not have.
90
+ if (args.action === 'import' || args.action.startsWith('import-')) {
91
+ const suffix = args.action === 'import' ? '' : '-' + args.action.replace('import-', '');
92
+ const loops = args.action === 'import' ? HAS_UPSERT : NESTED_UPSERTS.includes(args.action.replace('import-', ''));
93
+ if (loops) {
94
+ this.error(`This resource has no import endpoint. Use: aderis notifications upsert${suffix}${suffix ? ' <id>' : ''} --file data.json`);
95
+ }
96
+ }
97
+ const endpoint = ENDPOINTS[args.action];
98
+ if (!endpoint)
99
+ this.error(`Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
100
+ let apiPath = endpoint.path;
101
+ for (let i = 0; i < endpoint.pathParams.length; i++) {
102
+ const param = endpoint.pathParams[i];
103
+ let value;
104
+ if (i === 0) {
105
+ // First path param always comes from positional argument
106
+ value = args.id;
107
+ if (!value)
108
+ this.error('Missing required argument: id. Usage: aderis notifications <action> <id>');
109
+ }
110
+ else {
111
+ const flagName = param.replace(/\./g, '-').replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
112
+ value = flags[flagName];
113
+ if (!value)
114
+ this.error(`Missing required parameter: --${flagName}`);
115
+ }
116
+ apiPath = apiPath.replace(`{${param}}`, String(value));
117
+ }
118
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
119
+ if (!context)
120
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
121
+ if (!hasCredentials(context))
122
+ this.error(missingCredentialsMessage(context));
123
+ const queryParams = {};
124
+ if (flags.page)
125
+ queryParams.page = flags.page;
126
+ if (flags.limit)
127
+ queryParams.limit = flags.limit;
128
+ if (flags.include)
129
+ queryParams.include = flags.include;
130
+ if (flags.search)
131
+ queryParams.search = flags.search;
132
+ if (flags['sort-by'])
133
+ queryParams.sortBy = normalizeSortBy(flags['sort-by']);
134
+ if (flags.fields)
135
+ queryParams.fields = flags.fields;
136
+ if (flags.query) {
137
+ try {
138
+ Object.assign(queryParams, JSON.parse(flags.query));
139
+ }
140
+ catch {
141
+ this.error('Invalid JSON in --query');
142
+ }
143
+ }
144
+ // Parse --filter flags (e.g., --filter status=ACTIVE becomes filter.status=$eq:ACTIVE)
145
+ if (flags.filter && flags.filter.length > 0) {
146
+ for (const f of flags.filter) {
147
+ const eqIndex = f.indexOf('=');
148
+ if (eqIndex === -1)
149
+ this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
150
+ const key = f.slice(0, eqIndex);
151
+ const value = this.parseFilterValue(f.slice(eqIndex + 1));
152
+ const filterKey = `filter.${key}`;
153
+ if (filterKey in queryParams) {
154
+ // Multiple filters on same field: collect as array
155
+ const existing = queryParams[filterKey];
156
+ queryParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
157
+ }
158
+ else {
159
+ queryParams[filterKey] = value;
160
+ }
161
+ }
162
+ }
163
+ // Flags generated from this endpoint's own parameters. Raw-body endpoints
164
+ // have them: their body is not JSON, so --set cannot carry a value there.
165
+ for (const param of endpoint.specParams) {
166
+ const value = flags[param.flag];
167
+ if (value === undefined || value === '') {
168
+ if (param.required)
169
+ this.error(`Missing required flag: --${param.flag}`);
170
+ continue;
171
+ }
172
+ queryParams[param.name] = value;
173
+ }
174
+ let data;
175
+ if (endpoint.isMultipart) {
176
+ if (!flags.file)
177
+ this.error('Missing required --file flag for file upload');
178
+ const fsModule = await import('node:fs');
179
+ const pathModule = await import('node:path');
180
+ const FormDataLib = (await import('form-data')).default;
181
+ const form = new FormDataLib();
182
+ form.append('file', fsModule.createReadStream(flags.file), pathModule.basename(flags.file));
183
+ // Append --set fields as extra form fields (e.g. --set type=CREDIT_CARD_STATEMENT)
184
+ if (flags.set && flags.set.length > 0) {
185
+ for (const pair of flags.set) {
186
+ const eqIndex = pair.indexOf('=');
187
+ if (eqIndex === -1)
188
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
189
+ form.append(pair.slice(0, eqIndex), pair.slice(eqIndex + 1));
190
+ }
191
+ }
192
+ data = form;
193
+ }
194
+ else if (endpoint.bodyMediaType) {
195
+ // The body is not JSON (today only application/x-ndjson): it is sent
196
+ // verbatim, under the content type the endpoint asks for.
197
+ if (flags.file) {
198
+ const fsModule = await import('node:fs');
199
+ try {
200
+ data = fsModule.readFileSync(flags.file, 'utf-8');
201
+ }
202
+ catch {
203
+ this.error(`Failed to read file: ${flags.file}`);
204
+ }
205
+ }
206
+ else if (flags.data) {
207
+ data = flags.data;
208
+ }
209
+ else {
210
+ this.error(`This endpoint takes its body as ${endpoint.bodyMediaType}. Pass the file with -f / --file, or the text with --data.`);
211
+ }
212
+ }
213
+ else if (endpoint.hasBody) {
214
+ // For binary-response endpoints, --file is the output path, not a JSON
215
+ // input file — skip the read-as-body branch.
216
+ if (flags.file && !endpoint.isBinaryResponse) {
217
+ const fsModule = await import('node:fs');
218
+ try {
219
+ data = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
220
+ }
221
+ catch {
222
+ this.error(`Failed to read file: ${flags.file}`);
223
+ }
224
+ }
225
+ else if (flags.data) {
226
+ try {
227
+ data = JSON.parse(flags.data);
228
+ }
229
+ catch {
230
+ this.error('Invalid JSON in --data');
231
+ }
232
+ }
233
+ // Apply --set flags (can be combined with --data or --file)
234
+ if (flags.set && flags.set.length > 0) {
235
+ if (!data)
236
+ data = {};
237
+ const body = data;
238
+ const arrayFields = new Set(endpoint.bodyArrayFields);
239
+ for (const pair of flags.set) {
240
+ const eqIndex = pair.indexOf('=');
241
+ if (eqIndex === -1)
242
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
243
+ const key = pair.slice(0, eqIndex);
244
+ let value = pair.slice(eqIndex + 1);
245
+ // Try to parse as JSON for numbers, booleans, arrays, objects
246
+ try {
247
+ value = JSON.parse(value);
248
+ }
249
+ catch { /* keep as string */ }
250
+ // For top-level keys typed as array in the API schema, split bare
251
+ // comma-separated input (e.g. "1171,1170" -> ["1171","1170"]) and
252
+ // wrap a lone scalar in a single-element array. Skips when --set
253
+ // already provided a JSON array.
254
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
255
+ if (isArrayField && !Array.isArray(value)) {
256
+ if (typeof value === 'string') {
257
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
258
+ }
259
+ else if (value !== undefined && value !== null) {
260
+ value = [value];
261
+ }
262
+ }
263
+ // Support nested keys like "address.city"
264
+ const keys = key.split('.');
265
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
266
+ this.error(`Invalid --set key: ${key}`);
267
+ }
268
+ let obj = body;
269
+ for (let i = 0; i < keys.length - 1; i++) {
270
+ if (!(keys[i] in obj) || typeof obj[keys[i]] !== 'object') {
271
+ obj[keys[i]] = {};
272
+ }
273
+ obj = obj[keys[i]];
274
+ }
275
+ obj[keys[keys.length - 1]] = value;
276
+ }
277
+ }
278
+ }
279
+ else if (flags.set && flags.set.length > 0) {
280
+ // For GET endpoints, --set adds query params
281
+ for (const pair of flags.set) {
282
+ const eqIndex = pair.indexOf('=');
283
+ if (eqIndex === -1)
284
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
285
+ const key = pair.slice(0, eqIndex);
286
+ let value = pair.slice(eqIndex + 1);
287
+ try {
288
+ value = JSON.parse(value);
289
+ }
290
+ catch { /* keep as string */ }
291
+ queryParams[key] = value;
292
+ }
293
+ }
294
+ // Show HTTP request details if --show-http-request flag is set
295
+ if (flags['show-http-request']) {
296
+ const baseUrls = getBaseUrls(context.environment);
297
+ const queryString = Object.keys(queryParams).length > 0
298
+ ? '?' + Object.entries(queryParams).flatMap(([k, v]) => {
299
+ const vals = Array.isArray(v) ? v : [v];
300
+ return vals.map(val => `${encodeURIComponent(k)}=${encodeURIComponent(String(val))}`);
301
+ }).join('&')
302
+ : '';
303
+ process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
304
+ if (endpoint.isMultipart) {
305
+ process.stderr.write(`Body: [multipart/form-data file upload]\n`);
306
+ }
307
+ else if (data) {
308
+ process.stderr.write(`Body: ${typeof data === 'string' ? data : JSON.stringify(data, null, 2)}\n`);
309
+ }
310
+ process.stderr.write('\n');
311
+ }
312
+ try {
313
+ // Binary response: to -f / --file, or to stdout when it is redirected.
314
+ if (endpoint.isBinaryResponse) {
315
+ const toStdout = !flags.file;
316
+ if (toStdout && process.stdout.isTTY) {
317
+ this.error(`Endpoint returns a binary file. Specify the output path with -f / --file (e.g. -f report.xlsx), or redirect stdout to a file.`);
318
+ }
319
+ const binResponse = await apiRequest(endpoint.method, apiPath, {
320
+ params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
321
+ data,
322
+ contentType: endpoint.bodyMediaType || undefined,
323
+ contextName: flags.context,
324
+ binary: true,
325
+ });
326
+ const binData = binResponse.data;
327
+ const buffer = Buffer.isBuffer(binData)
328
+ ? binData
329
+ : Buffer.from(binData);
330
+ if (toStdout) {
331
+ // Nothing else may reach stdout here — it is the file.
332
+ process.stdout.write(buffer);
333
+ return;
334
+ }
335
+ const fsModule = await import('node:fs');
336
+ fsModule.writeFileSync(flags.file, buffer);
337
+ this.log(`Saved ${buffer.length} bytes to ${flags.file}`);
338
+ return;
339
+ }
340
+ let response;
341
+ if (endpoint.hasBinaryVariant) {
342
+ // This route answers JSON or a file depending on the request body, so the
343
+ // bytes are read first and the response's own content-type decides. Asking
344
+ // for text here would corrupt an xlsx/pdf before anything could inspect it.
345
+ const raw = await apiRequest(endpoint.method, apiPath, {
346
+ params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
347
+ data,
348
+ contentType: endpoint.bodyMediaType || undefined,
349
+ contextName: flags.context,
350
+ binary: true,
351
+ });
352
+ const rawType = String(raw.headers['content-type'] || '').toLowerCase();
353
+ const rawData = raw.data;
354
+ const buffer = Buffer.isBuffer(rawData) ? rawData : Buffer.from(rawData);
355
+ if (!isTextualMediaType(rawType)) {
356
+ if (process.stdout.isTTY) {
357
+ this.error(`The API returned ${rawType || 'binary data'}. Redirect stdout to a file, e.g. ... > report.xlsx`);
358
+ }
359
+ // Nothing else may reach stdout here — it is the file.
360
+ process.stdout.write(buffer);
361
+ return;
362
+ }
363
+ response = { data: buffer.toString('utf8'), headers: raw.headers, status: raw.status };
364
+ }
365
+ else {
366
+ response = await apiRequest(endpoint.method, apiPath, {
367
+ params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
368
+ data,
369
+ contentType: endpoint.bodyMediaType || undefined,
370
+ contextName: flags.context,
371
+ acceptAny: true,
372
+ });
373
+ }
374
+ // Check content-type for non-JSON responses (XML, text, etc.)
375
+ const contentType = (response.headers['content-type'] || '').toLowerCase();
376
+ if (isTextualMediaType(contentType) && !contentType.startsWith('application/json')) {
377
+ // Output raw content for XML/text responses (CSV, plain, HTML, etc.)
378
+ this.log(String(response.data));
379
+ return;
380
+ }
381
+ // Parse JSON if response came as string (due to acceptAny)
382
+ let output = response.data;
383
+ if (typeof output === 'string') {
384
+ try {
385
+ output = JSON.parse(output);
386
+ }
387
+ catch { /* keep as string */ }
388
+ }
389
+ // A paginated answer is { data, meta, links, totals }. The records are
390
+ // unwrapped for output, but what the API said about the page is kept:
391
+ // dropping it silently let a script read one page as the whole result
392
+ // (AderisERP/product#61).
393
+ let envelope;
394
+ if (output && typeof output === 'object' && !Array.isArray(output) && 'data' in output && Array.isArray(output.data)) {
395
+ const page = output;
396
+ envelope = page;
397
+ output = page.data;
398
+ }
399
+ // For table/csv on non-array responses, auto-extract the primary array
400
+ // e.g., { payments: [...], total: 3 } → extract payments array
401
+ if ((flags.table || flags.output === 'table' || flags.csv || flags.output === 'csv')
402
+ && output && typeof output === 'object' && !Array.isArray(output)) {
403
+ const obj = output;
404
+ const arrayKeys = Object.keys(obj).filter(k => Array.isArray(obj[k]));
405
+ if (arrayKeys.length === 1) {
406
+ output = obj[arrayKeys[0]];
407
+ }
408
+ }
409
+ // Sanitize output if requested
410
+ if (flags.sanitize) {
411
+ output = this.sanitizeOutput(output);
412
+ }
413
+ const fieldList = flags.fields?.split(',').map(f => f.trim());
414
+ if (envelope)
415
+ this.warnShortPage(envelope, flags.limit);
416
+ if (flags.csv || flags.output === 'csv') {
417
+ this.printCsv(output, fieldList);
418
+ }
419
+ else if (flags.table || flags.output === 'table') {
420
+ this.printTable(output, fieldList);
421
+ if (envelope)
422
+ this.printPageSummary(envelope);
423
+ }
424
+ else if (envelope && flags.meta) {
425
+ // The whole envelope, for a caller that asked for it; the default stays
426
+ // a bare array so existing scripts are unaffected.
427
+ this.log(JSON.stringify({ ...envelope, data: output }, null, 2));
428
+ }
429
+ else {
430
+ this.log(JSON.stringify(output, null, 2));
431
+ }
432
+ }
433
+ catch (error) {
434
+ if (error instanceof ApiError) {
435
+ if (error.status === 404)
436
+ this.error(error.message);
437
+ this.error(`API Error (${error.status}): ${error.message}`);
438
+ }
439
+ throw error;
440
+ }
441
+ }
442
+ async runUpsert(flags) {
443
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
444
+ if (!context)
445
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
446
+ if (!hasCredentials(context))
447
+ this.error(missingCredentialsMessage(context));
448
+ // Get data from file, --data, or --set flags
449
+ let items = [];
450
+ if (flags.file) {
451
+ const fsModule = await import('node:fs');
452
+ try {
453
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
454
+ items = Array.isArray(content) ? content : [content];
455
+ }
456
+ catch {
457
+ this.error(`Failed to read file: ${flags.file}`);
458
+ }
459
+ }
460
+ else if (flags.data) {
461
+ try {
462
+ const content = JSON.parse(flags.data);
463
+ items = Array.isArray(content) ? content : [content];
464
+ }
465
+ catch {
466
+ this.error('Invalid JSON in --data');
467
+ }
468
+ }
469
+ else if (flags.set && flags.set.length > 0) {
470
+ const item = {};
471
+ const arrayFields = new Set(ENDPOINTS['create']?.bodyArrayFields ?? []);
472
+ for (const pair of flags.set) {
473
+ const eqIndex = pair.indexOf('=');
474
+ if (eqIndex === -1)
475
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
476
+ const key = pair.slice(0, eqIndex);
477
+ let value = pair.slice(eqIndex + 1);
478
+ try {
479
+ value = JSON.parse(value);
480
+ }
481
+ catch { /* keep as string */ }
482
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
483
+ if (isArrayField && !Array.isArray(value)) {
484
+ if (typeof value === 'string') {
485
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
486
+ }
487
+ else if (value !== undefined && value !== null) {
488
+ value = [value];
489
+ }
490
+ }
491
+ const keys = key.split('.');
492
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
493
+ this.error(`Invalid --set key: ${key}`);
494
+ }
495
+ let obj = item;
496
+ for (let i = 0; i < keys.length - 1; i++) {
497
+ if (!(keys[i] in obj))
498
+ obj[keys[i]] = {};
499
+ obj = obj[keys[i]];
500
+ }
501
+ obj[keys[keys.length - 1]] = value;
502
+ }
503
+ items = [item];
504
+ }
505
+ else {
506
+ this.error('Upsert requires --file, --data, or --set flags');
507
+ }
508
+ const createEndpoint = ENDPOINTS['create'];
509
+ const updateEndpoint = ENDPOINTS['update'];
510
+ if (!createEndpoint || !updateEndpoint) {
511
+ this.error('Upsert requires both create and update endpoints');
512
+ }
513
+ // Helper to extract identifier from item (id, code, or xxxCode)
514
+ const getItemIdentifier = (item) => {
515
+ if (item.id)
516
+ return String(item.id);
517
+ if (item.code)
518
+ return String(item.code);
519
+ // Look for xxxCode fields (e.g., ledgerCode, accountCode)
520
+ for (const key of Object.keys(item)) {
521
+ if (key.endsWith('Code') && item[key])
522
+ return String(item[key]);
523
+ }
524
+ // Look for name as fallback
525
+ if (item.name)
526
+ return String(item.name).slice(0, 30);
527
+ return '';
528
+ };
529
+ const results = [];
530
+ // Stream output row-by-row so progress is visible during long imports.
531
+ // Pre-compute the identifier column width from the input items so the
532
+ // table stays aligned without buffering all rows.
533
+ // When stdout is piped (IDE terminals, tee, CI), Node switches to async-buffered
534
+ // mode and rows accumulate in the pipe buffer until it fills. Force blocking
535
+ // mode so each \n-terminated write flushes immediately.
536
+ const stdoutHandle = process.stdout._handle;
537
+ if (stdoutHandle?.setBlocking)
538
+ stdoutHandle.setBlocking(true);
539
+ const outputFormat = flags.output || 'table';
540
+ const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
541
+ const useJson = outputFormat === 'json';
542
+ const statusWidth = 8;
543
+ const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
544
+ if (useCsv) {
545
+ this.log('status,identifier,id,error');
546
+ }
547
+ else if (!useJson) {
548
+ this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
549
+ this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
550
+ }
551
+ const emitRow = (r) => {
552
+ if (useJson)
553
+ return;
554
+ if (useCsv) {
555
+ const err = (r.error || '').replace(/"/g, '""');
556
+ this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
557
+ }
558
+ else {
559
+ this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
560
+ }
561
+ };
562
+ // Server-managed fields the API rejects in create/update bodies. Stripped
563
+ // before every request so re-importing a previously-exported payload Just Works.
564
+ const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
565
+ const stripServerFields = (item) => {
566
+ const out = {};
567
+ for (const [k, v] of Object.entries(item)) {
568
+ if (!STRIP_FIELDS.has(k))
569
+ out[k] = v;
570
+ }
571
+ return out;
572
+ };
573
+ const processItem = async (item) => {
574
+ const identifier = getItemIdentifier(item);
575
+ const body = stripServerFields(item);
576
+ // If the payload carries an id (e.g. re-importing an export), PATCH directly.
577
+ // Fall through to POST only on 404 (so a missing record still gets created).
578
+ const itemId = typeof item.id === 'string' ? item.id : undefined;
579
+ if (itemId) {
580
+ try {
581
+ const updatePath = updateEndpoint.path.replace('{id}', itemId);
582
+ await apiRequest('PATCH', updatePath, {
583
+ data: body,
584
+ contextName: flags.context,
585
+ });
586
+ return { status: 'updated', id: itemId, identifier };
587
+ }
588
+ catch (error) {
589
+ if (!(error instanceof ApiError && error.status === 404)) {
590
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
591
+ return { status: 'error', id: itemId, identifier, error: msg };
592
+ }
593
+ // 404 → record gone, try create below
594
+ }
595
+ }
596
+ try {
597
+ const response = await apiRequest('POST', createEndpoint.path, {
598
+ data: body,
599
+ contextName: flags.context,
600
+ });
601
+ const id = response.data?.id;
602
+ return { status: 'created', id: id ? String(id) : undefined, identifier };
603
+ }
604
+ catch (error) {
605
+ if (error instanceof ApiError && error.status === 409) {
606
+ const errorData = error.data;
607
+ const existingId = errorData?.existingId;
608
+ if (existingId) {
609
+ try {
610
+ const updatePath = updateEndpoint.path.replace('{id}', existingId);
611
+ await apiRequest('PATCH', updatePath, {
612
+ data: body,
613
+ contextName: flags.context,
614
+ });
615
+ return { status: 'updated', id: existingId, identifier };
616
+ }
617
+ catch (updateError) {
618
+ const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
619
+ return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
620
+ }
621
+ }
622
+ return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
623
+ }
624
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
625
+ return { status: 'error', identifier, error: msg };
626
+ }
627
+ };
628
+ // Worker pool: keep N requests in flight at all times. Rows are emitted as
629
+ // each request resolves (so output order may differ from input order). The
630
+ // summary at the end remains accurate regardless.
631
+ const concurrency = 4;
632
+ const queue = [...items];
633
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
634
+ for (;;) {
635
+ const item = queue.shift();
636
+ if (!item)
637
+ return;
638
+ const r = await processItem(item);
639
+ results.push(r);
640
+ emitRow(r);
641
+ }
642
+ }));
643
+ // Summary counts
644
+ const created = results.filter(r => r.status === 'created').length;
645
+ const updated = results.filter(r => r.status === 'updated').length;
646
+ const errors = results.filter(r => r.status === 'error');
647
+ if (useJson) {
648
+ this.log(JSON.stringify(results, null, 2));
649
+ }
650
+ // Always show summary at the end
651
+ this.log('');
652
+ this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
653
+ }
654
+ /**
655
+ * The API's own import: the whole array goes up in one request and comes
656
+ * back as an import run, which records what happened to every record. A bad
657
+ * record lands in errorLog and the rest are still applied, and the run stays
658
+ * readable afterwards with: aderis imports get <id>.
659
+ */
660
+ async runServerImport(action, parentId, flags) {
661
+ const endpoint = ENDPOINTS[action];
662
+ if (!endpoint)
663
+ this.error(`Unknown action: ${action}. Available: ${SUBCOMMANDS.join(', ')}`);
664
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
665
+ if (!context)
666
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
667
+ if (!hasCredentials(context))
668
+ this.error(missingCredentialsMessage(context));
669
+ let apiPath = endpoint.path;
670
+ if (endpoint.pathParams.length > 0) {
671
+ if (!parentId)
672
+ this.error(`Missing required argument: id. Usage: aderis notifications ${action} <parent-id> --file data.json`);
673
+ apiPath = apiPath.replace(`{${endpoint.pathParams[0]}}`, parentId);
674
+ }
675
+ // The endpoint takes an array. A single object is wrapped, so importing
676
+ // one record reads the same as importing many.
677
+ let records = [];
678
+ if (flags.file) {
679
+ const fsModule = await import('node:fs');
680
+ try {
681
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
682
+ records = Array.isArray(content) ? content : [content];
683
+ }
684
+ catch {
685
+ this.error(`Failed to read file: ${flags.file}`);
686
+ }
687
+ }
688
+ else if (flags.data) {
689
+ try {
690
+ const content = JSON.parse(flags.data);
691
+ records = Array.isArray(content) ? content : [content];
692
+ }
693
+ catch {
694
+ this.error('Invalid JSON in --data');
695
+ }
696
+ }
697
+ else {
698
+ this.error('Import requires --file or --data holding a JSON array of records');
699
+ }
700
+ if (records.length === 0)
701
+ this.error('Nothing to import: the input is an empty array');
702
+ const params = { format: 'json' };
703
+ if (flags.mode)
704
+ params.mode = flags.mode;
705
+ if (flags.reference)
706
+ params.reference = flags.reference;
707
+ if (flags.async)
708
+ params.async = true;
709
+ const headers = {};
710
+ if (flags['idempotency-key'])
711
+ headers['Idempotency-Key'] = flags['idempotency-key'];
712
+ if (flags['show-http-request']) {
713
+ const baseUrls = getBaseUrls(context.environment);
714
+ const queryString = '?' + Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&');
715
+ process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
716
+ process.stderr.write(`Body: [${records.length} record${records.length === 1 ? '' : 's'}]\n\n`);
717
+ }
718
+ try {
719
+ const response = await apiRequest(endpoint.method, apiPath, {
720
+ contextName: flags.context,
721
+ data: records,
722
+ headers,
723
+ params,
724
+ });
725
+ this.printImportRun(response.data, flags);
726
+ }
727
+ catch (error) {
728
+ if (error instanceof ApiError) {
729
+ this.error(`API Error (${error.status}): ${error.message}`);
730
+ }
731
+ throw error;
732
+ }
733
+ }
734
+ /** Renders an import run: its counts, then whatever the server refused. */
735
+ printImportRun(run, flags) {
736
+ if (flags.output === 'json') {
737
+ this.log(JSON.stringify(run, null, 2));
738
+ return;
739
+ }
740
+ const record = (run ?? {});
741
+ const count = (key) => (typeof record[key] === 'number' ? record[key] : 0);
742
+ const id = record.id ? String(record.id) : '';
743
+ this.log(`Import ${id} - ${String(record.status ?? 'UNKNOWN')}${record.async ? ' (background)' : ''}`);
744
+ this.log(` ${count('inputSize')} submitted, ${count('createdCount')} created, ${count('updatedCount')} updated, ${count('unchangedCount')} unchanged`);
745
+ if (count('errorCount') > 0)
746
+ this.log(` ${count('errorCount')} not applied: ${count('refusedCount')} refused, ${count('failedCount')} failed`);
747
+ if (count('warningCount') > 0)
748
+ this.log(` ${count('warningCount')} applied with a warning`);
749
+ // errorLog is keyed by the record's identifier, then by field name.
750
+ const errorLog = record.errorLog;
751
+ if (errorLog && Object.keys(errorLog).length > 0) {
752
+ this.log('');
753
+ for (const [key, fields] of Object.entries(errorLog)) {
754
+ for (const [field, messages] of Object.entries(fields ?? {})) {
755
+ for (const message of messages ?? [])
756
+ this.log(` ${key} ${field}: ${message}`);
757
+ }
758
+ }
759
+ }
760
+ if (record.async && id) {
761
+ this.log('');
762
+ this.log(`Follow it with: aderis imports get ${id}`);
763
+ }
764
+ }
765
+ async runExport(flags) {
766
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
767
+ if (!context)
768
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
769
+ if (!hasCredentials(context))
770
+ this.error(missingCredentialsMessage(context));
771
+ const listEndpoint = ENDPOINTS['list'];
772
+ if (!listEndpoint)
773
+ this.error('Export requires a list endpoint');
774
+ const allItems = [];
775
+ let page = 1;
776
+ const limit = 100;
777
+ let hasMore = true;
778
+ // Build base query params
779
+ const baseParams = {};
780
+ if (flags.search)
781
+ baseParams.search = flags.search;
782
+ if (flags['sort-by'])
783
+ baseParams.sortBy = normalizeSortBy(flags['sort-by']);
784
+ if (flags.include)
785
+ baseParams.include = flags.include;
786
+ if (flags.fields)
787
+ baseParams.fields = flags.fields;
788
+ if (flags.query) {
789
+ try {
790
+ Object.assign(baseParams, JSON.parse(flags.query));
791
+ }
792
+ catch {
793
+ this.error('Invalid JSON in --query');
794
+ }
795
+ }
796
+ // Parse --filter flags (auto-prepend $eq: if no operator specified)
797
+ if (flags.filter && flags.filter.length > 0) {
798
+ for (const f of flags.filter) {
799
+ const eqIndex = f.indexOf('=');
800
+ if (eqIndex === -1)
801
+ this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
802
+ const key = f.slice(0, eqIndex);
803
+ const value = this.parseFilterValue(f.slice(eqIndex + 1));
804
+ const filterKey = `filter.${key}`;
805
+ if (filterKey in baseParams) {
806
+ const existing = baseParams[filterKey];
807
+ baseParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
808
+ }
809
+ else {
810
+ baseParams[filterKey] = value;
811
+ }
812
+ }
813
+ }
814
+ // Fetch all pages
815
+ process.stderr.write('Exporting...');
816
+ while (hasMore) {
817
+ const params = { ...baseParams, page, limit };
818
+ const response = await apiRequest('GET', listEndpoint.path, {
819
+ params,
820
+ contextName: flags.context,
821
+ });
822
+ let items = [];
823
+ const data = response.data;
824
+ // Handle paginated response format
825
+ if (data && typeof data === 'object' && 'data' in data && Array.isArray(data.data)) {
826
+ items = data.data;
827
+ }
828
+ else if (Array.isArray(response.data)) {
829
+ items = response.data;
830
+ }
831
+ allItems.push(...items);
832
+ process.stderr.write(` ${allItems.length}`);
833
+ // Check if there are more pages
834
+ if (items.length < limit) {
835
+ hasMore = false;
836
+ }
837
+ else {
838
+ page++;
839
+ }
840
+ }
841
+ process.stderr.write(' done\n');
842
+ let output = allItems;
843
+ // Sanitize output if requested
844
+ if (flags.sanitize) {
845
+ output = this.sanitizeOutput(output);
846
+ }
847
+ // Output in requested format
848
+ const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
849
+ if (flags.csv || flags.output === 'csv') {
850
+ this.printCsv(output, fieldList);
851
+ }
852
+ else {
853
+ this.log(JSON.stringify(output, null, 2));
854
+ }
855
+ }
856
+ async runCamt053Import(flags) {
857
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
858
+ if (!context)
859
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
860
+ if (!hasCredentials(context))
861
+ this.error(missingCredentialsMessage(context));
862
+ if (!flags.file) {
863
+ this.error('CAMT.053 import requires --file (-f) flag with path to XML file');
864
+ }
865
+ const fsModule = await import('node:fs');
866
+ let xmlContent;
867
+ try {
868
+ xmlContent = fsModule.readFileSync(flags.file, 'utf-8');
869
+ }
870
+ catch {
871
+ this.error(`Failed to read file: ${flags.file}`);
872
+ }
873
+ const endpoint = ENDPOINTS['import-camt053'];
874
+ try {
875
+ const response = await apiRequest(endpoint.method, endpoint.path, {
876
+ data: xmlContent,
877
+ contextName: flags.context,
878
+ contentType: 'application/xml',
879
+ });
880
+ // Extract transactions array and counts from response
881
+ let transactions = [];
882
+ let imported = 0;
883
+ let skipped = 0;
884
+ if (response.data && typeof response.data === 'object') {
885
+ const data = response.data;
886
+ if ('data' in data && Array.isArray(data.data)) {
887
+ transactions = data.data;
888
+ }
889
+ else if ('transactions' in data && Array.isArray(data.transactions)) {
890
+ transactions = data.transactions;
891
+ }
892
+ else if (Array.isArray(response.data)) {
893
+ transactions = response.data;
894
+ }
895
+ if (typeof data.imported === 'number')
896
+ imported = data.imported;
897
+ if (typeof data.skipped === 'number')
898
+ skipped = data.skipped;
899
+ }
900
+ else if (Array.isArray(response.data)) {
901
+ transactions = response.data;
902
+ }
903
+ if (imported === 0 && skipped === 0 && transactions.length > 0) {
904
+ for (const tx of transactions) {
905
+ const t = tx;
906
+ if (t.status === 'skipped' || t.skipped === true) {
907
+ skipped++;
908
+ }
909
+ else {
910
+ imported++;
911
+ }
912
+ }
913
+ if (imported === 0 && skipped === 0) {
914
+ imported = transactions.length;
915
+ }
916
+ }
917
+ let output = transactions;
918
+ if (flags.sanitize) {
919
+ output = this.sanitizeOutput(transactions);
920
+ }
921
+ const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
922
+ if (flags.csv || flags.output === 'csv') {
923
+ this.printCsv(output, fieldList);
924
+ }
925
+ else if (flags.table || flags.output === 'table') {
926
+ this.printTable(output, fieldList);
927
+ }
928
+ else {
929
+ this.log(JSON.stringify(output, null, 2));
930
+ }
931
+ this.log('');
932
+ this.log(`Summary: ${imported} imported, ${skipped} skipped`);
933
+ }
934
+ catch (error) {
935
+ if (error instanceof ApiError) {
936
+ if (error.status === 404)
937
+ this.error(error.message);
938
+ this.error(`API Error (${error.status}): ${error.message}`);
939
+ }
940
+ throw error;
941
+ }
942
+ }
943
+ async runNestedUpsert(suffix, parentId, flags) {
944
+ if (!parentId) {
945
+ this.error(`Missing required argument: id. Usage: aderis notifications upsert-${suffix} <parent-id> --file data.json`);
946
+ }
947
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
948
+ if (!context)
949
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
950
+ if (!hasCredentials(context))
951
+ this.error(missingCredentialsMessage(context));
952
+ // Get data from file, --data, or --set flags
953
+ let items = [];
954
+ if (flags.file) {
955
+ const fsModule = await import('node:fs');
956
+ try {
957
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
958
+ items = Array.isArray(content) ? content : [content];
959
+ }
960
+ catch {
961
+ this.error(`Failed to read file: ${flags.file}`);
962
+ }
963
+ }
964
+ else if (flags.data) {
965
+ try {
966
+ const content = JSON.parse(flags.data);
967
+ items = Array.isArray(content) ? content : [content];
968
+ }
969
+ catch {
970
+ this.error('Invalid JSON in --data');
971
+ }
972
+ }
973
+ else if (flags.set && flags.set.length > 0) {
974
+ const item = {};
975
+ const arrayFields = new Set(ENDPOINTS[`create-${suffix}`]?.bodyArrayFields ?? []);
976
+ for (const pair of flags.set) {
977
+ const eqIndex = pair.indexOf('=');
978
+ if (eqIndex === -1)
979
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
980
+ const key = pair.slice(0, eqIndex);
981
+ let value = pair.slice(eqIndex + 1);
982
+ try {
983
+ value = JSON.parse(value);
984
+ }
985
+ catch { /* keep as string */ }
986
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
987
+ if (isArrayField && !Array.isArray(value)) {
988
+ if (typeof value === 'string') {
989
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
990
+ }
991
+ else if (value !== undefined && value !== null) {
992
+ value = [value];
993
+ }
994
+ }
995
+ const keys = key.split('.');
996
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
997
+ this.error(`Invalid --set key: ${key}`);
998
+ }
999
+ let obj = item;
1000
+ for (let i = 0; i < keys.length - 1; i++) {
1001
+ if (!(keys[i] in obj))
1002
+ obj[keys[i]] = {};
1003
+ obj = obj[keys[i]];
1004
+ }
1005
+ obj[keys[keys.length - 1]] = value;
1006
+ }
1007
+ items = [item];
1008
+ }
1009
+ else {
1010
+ this.error('Upsert requires --file, --data, or --set flags');
1011
+ }
1012
+ const createEndpoint = ENDPOINTS[`create-${suffix}`];
1013
+ const updateEndpoint = ENDPOINTS[`update-${suffix}`];
1014
+ if (!createEndpoint || !updateEndpoint) {
1015
+ this.error(`Upsert requires both create-${suffix} and update-${suffix} endpoints`);
1016
+ }
1017
+ // Build the base path with parent ID (first path param)
1018
+ const firstParam = createEndpoint.pathParams[0];
1019
+ const basePath = createEndpoint.path.replace(`{${firstParam}}`, parentId);
1020
+ // Helper to extract identifier from item
1021
+ const getItemIdentifier = (item) => {
1022
+ if (item.id)
1023
+ return String(item.id);
1024
+ if (item.itemId)
1025
+ return String(item.itemId);
1026
+ if (item.code)
1027
+ return String(item.code);
1028
+ for (const key of Object.keys(item)) {
1029
+ if (key.endsWith('Id') && item[key])
1030
+ return String(item[key]);
1031
+ if (key.endsWith('Code') && item[key])
1032
+ return String(item[key]);
1033
+ }
1034
+ return '';
1035
+ };
1036
+ const results = [];
1037
+ const stdoutHandle = process.stdout._handle;
1038
+ if (stdoutHandle?.setBlocking)
1039
+ stdoutHandle.setBlocking(true);
1040
+ const outputFormat = flags.output || 'table';
1041
+ const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
1042
+ const useJson = outputFormat === 'json';
1043
+ const statusWidth = 8;
1044
+ const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
1045
+ if (useCsv) {
1046
+ this.log('status,identifier,id,error');
1047
+ }
1048
+ else if (!useJson) {
1049
+ this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
1050
+ this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
1051
+ }
1052
+ const emitRow = (r) => {
1053
+ if (useJson)
1054
+ return;
1055
+ if (useCsv) {
1056
+ const err = (r.error || '').replace(/"/g, '""');
1057
+ this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
1058
+ }
1059
+ else {
1060
+ this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
1061
+ }
1062
+ };
1063
+ const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
1064
+ const stripServerFields = (item) => {
1065
+ const out = {};
1066
+ for (const [k, v] of Object.entries(item)) {
1067
+ if (!STRIP_FIELDS.has(k))
1068
+ out[k] = v;
1069
+ }
1070
+ return out;
1071
+ };
1072
+ const buildUpdatePath = (existingId) => {
1073
+ const firstUpdateParam = updateEndpoint.pathParams[0];
1074
+ const nestedIdParam = updateEndpoint.pathParams.find((p, i) => i > 0);
1075
+ let updatePath = updateEndpoint.path.replace(`{${firstUpdateParam}}`, parentId);
1076
+ if (nestedIdParam) {
1077
+ updatePath = updatePath.replace(`{${nestedIdParam}}`, existingId);
1078
+ }
1079
+ return updatePath;
1080
+ };
1081
+ const processItem = async (item) => {
1082
+ const identifier = getItemIdentifier(item);
1083
+ const body = stripServerFields(item);
1084
+ const itemId = typeof item.id === 'string' ? item.id : undefined;
1085
+ if (itemId) {
1086
+ try {
1087
+ await apiRequest('PATCH', buildUpdatePath(itemId), {
1088
+ data: body,
1089
+ contextName: flags.context,
1090
+ });
1091
+ return { status: 'updated', id: itemId, identifier };
1092
+ }
1093
+ catch (error) {
1094
+ if (!(error instanceof ApiError && error.status === 404)) {
1095
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
1096
+ return { status: 'error', id: itemId, identifier, error: msg };
1097
+ }
1098
+ // 404 → fall through and try create
1099
+ }
1100
+ }
1101
+ try {
1102
+ const response = await apiRequest('POST', basePath, {
1103
+ data: body,
1104
+ contextName: flags.context,
1105
+ });
1106
+ const id = response.data?.id;
1107
+ return { status: 'created', id: id ? String(id) : undefined, identifier };
1108
+ }
1109
+ catch (error) {
1110
+ if (error instanceof ApiError && error.status === 409) {
1111
+ const errorData = error.data;
1112
+ const existingId = errorData?.existingId || item.id;
1113
+ if (existingId) {
1114
+ try {
1115
+ await apiRequest('PATCH', buildUpdatePath(existingId), {
1116
+ data: body,
1117
+ contextName: flags.context,
1118
+ });
1119
+ return { status: 'updated', id: existingId, identifier };
1120
+ }
1121
+ catch (updateError) {
1122
+ const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
1123
+ return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
1124
+ }
1125
+ }
1126
+ return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
1127
+ }
1128
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
1129
+ return { status: 'error', identifier, error: msg };
1130
+ }
1131
+ };
1132
+ // Worker pool: 4 requests in flight at a time. Rows are emitted as each
1133
+ // request resolves so output order may differ from input order.
1134
+ const concurrency = 4;
1135
+ const queue = [...items];
1136
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
1137
+ for (;;) {
1138
+ const item = queue.shift();
1139
+ if (!item)
1140
+ return;
1141
+ const r = await processItem(item);
1142
+ results.push(r);
1143
+ emitRow(r);
1144
+ }
1145
+ }));
1146
+ // Summary counts
1147
+ const created = results.filter(r => r.status === 'created').length;
1148
+ const updated = results.filter(r => r.status === 'updated').length;
1149
+ const errors = results.filter(r => r.status === 'error');
1150
+ if (useJson) {
1151
+ this.log(JSON.stringify(results, null, 2));
1152
+ }
1153
+ this.log('');
1154
+ this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
1155
+ }
1156
+ parseFilterValue(value) {
1157
+ // Recognises the nestjs-paginate operator set (with or without the leading $)
1158
+ // and recursively unwraps chained operators like 'not:null' -> '$not:$null'
1159
+ // or 'not:like:John' -> '$not:$like:John'. Falls back to '$eq:<value>' when
1160
+ // no operator prefix is present.
1161
+ const opRe = /^\$?(and|or|not|eq|gt|gte|in|null|lt|lte|btw|ne|ilike|like|sw|contains)(?::|$)/;
1162
+ const m = value.match(opRe);
1163
+ if (!m)
1164
+ return `\$eq:${value}`;
1165
+ const op = m[1];
1166
+ const rest = value.slice(m[0].length);
1167
+ if (rest === '')
1168
+ return `\$${op}`;
1169
+ return opRe.test(rest) ? `\$${op}:${this.parseFilterValue(rest)}` : `\$${op}:${rest}`;
1170
+ }
1171
+ /** The page line under a table: which page, how many, and any sums the API returned. */
1172
+ printPageSummary(envelope) {
1173
+ const meta = envelope.meta;
1174
+ if (meta && typeof meta.currentPage === 'number' && typeof meta.totalPages === 'number') {
1175
+ const shown = Array.isArray(envelope.data) ? envelope.data.length : 0;
1176
+ this.log(`
1177
+ Page ${meta.currentPage}/${meta.totalPages} — ${shown} of ${meta.totalItems ?? '?'} records`);
1178
+ }
1179
+ for (const total of envelope.totals ?? []) {
1180
+ const { currency, ...sums } = total;
1181
+ const parts = Object.entries(sums).map(([column, value]) => `${column} ${value}`).join(', ');
1182
+ this.log(`Total ${currency ?? ''}: ${parts}`.trim());
1183
+ }
1184
+ }
1185
+ /**
1186
+ * The API caps how many records a page may hold. Asking for more and getting
1187
+ * fewer looks like "that is everything" unless it is said out loud.
1188
+ */
1189
+ warnShortPage(envelope, requestedLimit) {
1190
+ const asked = requestedLimit === undefined ? undefined : Number(requestedLimit);
1191
+ const perPage = envelope.meta?.itemsPerPage;
1192
+ if (asked === undefined || Number.isNaN(asked) || typeof perPage !== 'number' || perPage >= asked)
1193
+ return;
1194
+ const pages = envelope.meta?.totalPages;
1195
+ const more = typeof pages === 'number' && pages > 1 ? ` Use --page, or the export action for every page.` : '';
1196
+ process.stderr.write(`! Asked for ${asked} records per page; the API returned at most ${perPage}.${more}
1197
+ `);
1198
+ }
1199
+ sanitizeOutput(data) {
1200
+ const auditFields = ['_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy'];
1201
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1202
+ const sanitize = (obj, parentUuids = new Set()) => {
1203
+ if (obj === null || obj === undefined)
1204
+ return undefined;
1205
+ if (Array.isArray(obj)) {
1206
+ const result = obj.map(item => sanitize(item, new Set(parentUuids))).filter(item => item !== undefined);
1207
+ return result.length > 0 ? result : undefined;
1208
+ }
1209
+ if (typeof obj === 'object') {
1210
+ const input = obj;
1211
+ // Use a Map to avoid any prototype-pollution risk on the result object
1212
+ const collected = new Map();
1213
+ // Collect UUIDs from this level to pass to children
1214
+ const currentUuids = new Set(parentUuids);
1215
+ for (const [, value] of Object.entries(input)) {
1216
+ if (typeof value === 'string' && uuidRegex.test(value)) {
1217
+ currentUuids.add(value);
1218
+ }
1219
+ }
1220
+ for (const [key, value] of Object.entries(input)) {
1221
+ // Skip prototype-pollution keys
1222
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
1223
+ continue;
1224
+ // Skip audit fields
1225
+ if (auditFields.includes(key))
1226
+ continue;
1227
+ // Skip null/undefined values
1228
+ if (value === null || value === undefined)
1229
+ continue;
1230
+ // Skip UUID values that exist in parent
1231
+ if (typeof value === 'string' && uuidRegex.test(value) && parentUuids.has(value))
1232
+ continue;
1233
+ // Recursively sanitize nested objects/arrays
1234
+ const sanitized = sanitize(value, currentUuids);
1235
+ if (sanitized !== undefined) {
1236
+ collected.set(key, sanitized);
1237
+ }
1238
+ }
1239
+ if (collected.size === 0)
1240
+ return undefined;
1241
+ return Object.fromEntries(collected);
1242
+ }
1243
+ return obj;
1244
+ };
1245
+ return sanitize(data) ?? (Array.isArray(data) ? [] : {});
1246
+ }
1247
+ getColumns(data, fields, flatten = false) {
1248
+ const items = Array.isArray(data) ? data : [data];
1249
+ if (items.length === 0)
1250
+ return { cols: [], items: [] };
1251
+ const first = items[0];
1252
+ const hiddenFields = ['tenantId', '_type'];
1253
+ if (fields) {
1254
+ return { cols: fields, items: items };
1255
+ }
1256
+ // Recursively collect all column paths, flattening objects (but not arrays)
1257
+ const collectPaths = (obj, prefix = '') => {
1258
+ const paths = [];
1259
+ for (const key of Object.keys(obj)) {
1260
+ const fullKey = prefix ? `${prefix}.${key}` : key;
1261
+ if (hiddenFields.includes(key))
1262
+ continue;
1263
+ const val = obj[key];
1264
+ if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
1265
+ // Flatten nested objects (but not arrays)
1266
+ if (flatten) {
1267
+ paths.push(...collectPaths(val, fullKey));
1268
+ }
1269
+ // Skip objects when not flattening
1270
+ }
1271
+ else if (!Array.isArray(val)) {
1272
+ // Include primitives (and null)
1273
+ paths.push(fullKey);
1274
+ }
1275
+ // Skip arrays entirely
1276
+ }
1277
+ return paths;
1278
+ };
1279
+ // Scan multiple items to discover all columns (handles fields absent/null in first item)
1280
+ const cols = collectPaths(first);
1281
+ const colSet = new Set(cols);
1282
+ const scanCount = Math.min(items.length, 50);
1283
+ for (let i = 1; i < scanCount; i++) {
1284
+ for (const p of collectPaths(items[i])) {
1285
+ if (!colSet.has(p)) {
1286
+ cols.push(p);
1287
+ colSet.add(p);
1288
+ }
1289
+ }
1290
+ }
1291
+ return { cols: flatten ? cols : cols.slice(0, 8), items: items };
1292
+ }
1293
+ getValue(row, col) {
1294
+ if (!col.includes('.'))
1295
+ return String(row[col] ?? '');
1296
+ const parts = col.split('.');
1297
+ // Walk the dot-path; descending through an array branches into every
1298
+ // element so leaf values get collected from each one. Multiple leaves are
1299
+ // joined with ';' (e.g. dunningReminders.id -> "uuid1;uuid2").
1300
+ const walk = (o, idx) => {
1301
+ if (idx >= parts.length)
1302
+ return [o];
1303
+ if (o == null)
1304
+ return [];
1305
+ if (Array.isArray(o))
1306
+ return o.flatMap(item => walk(item, idx));
1307
+ if (typeof o === 'object')
1308
+ return walk(o[parts[idx]], idx + 1);
1309
+ return [];
1310
+ };
1311
+ return walk(row, 0).filter(v => v !== undefined && v !== null).map(v => String(v)).join(';');
1312
+ }
1313
+ printTable(data, fields) {
1314
+ const { cols, items } = this.getColumns(data, fields);
1315
+ if (items.length === 0) {
1316
+ this.log('No results');
1317
+ return;
1318
+ }
1319
+ // Calculate column widths
1320
+ const widths = cols.map(c => c.length);
1321
+ for (const item of items) {
1322
+ cols.forEach((col, i) => {
1323
+ const val = this.getValue(item, col).slice(0, 40);
1324
+ widths[i] = Math.max(widths[i], val.length);
1325
+ });
1326
+ }
1327
+ // Print header
1328
+ const header = cols.map((c, i) => c.padEnd(widths[i])).join(' ');
1329
+ this.log(header);
1330
+ this.log(widths.map(w => '-'.repeat(w)).join(' '));
1331
+ // Print rows
1332
+ for (const item of items) {
1333
+ const row = cols.map((col, i) => {
1334
+ const val = this.getValue(item, col).slice(0, 40);
1335
+ return val.padEnd(widths[i]);
1336
+ }).join(' ');
1337
+ this.log(row);
1338
+ }
1339
+ }
1340
+ printCsv(data, fields) {
1341
+ const { cols, items } = this.getColumns(data, fields, true); // flatten=true for CSV
1342
+ if (items.length === 0) {
1343
+ this.log('No results');
1344
+ return;
1345
+ }
1346
+ const escape = (val) => {
1347
+ if (val.includes(',') || val.includes('"') || val.includes('\n')) {
1348
+ return '"' + val.replace(/"/g, '""') + '"';
1349
+ }
1350
+ return val;
1351
+ };
1352
+ // Print header
1353
+ this.log(cols.map(escape).join(','));
1354
+ // Print rows
1355
+ for (const item of items) {
1356
+ const row = cols.map(col => escape(this.getValue(item, col)));
1357
+ this.log(row.join(','));
1358
+ }
1359
+ }
1360
+ }