@aderis-erp/cli 1.0.4 → 1.0.8

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 (123) hide show
  1. package/dist/commands/access-groups.js +5 -5
  2. package/dist/commands/{access-groups 3.d.ts → account-transaction-allocations.d.ts} +1 -1
  3. package/dist/commands/{async-endpoints-internal.js → account-transaction-allocations.js} +19 -15
  4. package/dist/commands/account-transactions.js +7 -7
  5. package/dist/commands/accounts.js +5 -5
  6. package/dist/commands/agent-runs.js +5 -5
  7. package/dist/commands/audit-log.js +5 -5
  8. package/dist/commands/auth/login.js +1 -2
  9. package/dist/commands/auth/tenant.d.ts +1 -1
  10. package/dist/commands/auth/tenant.js +11 -11
  11. package/dist/commands/auth.js +1 -1
  12. package/dist/commands/bank-accounts.js +5 -5
  13. package/dist/commands/bank-integrations.js +5 -5
  14. package/dist/commands/business-partners---contacts.js +5 -5
  15. package/dist/commands/business-partners.js +5 -5
  16. package/dist/commands/credit-card-accounts.js +5 -5
  17. package/dist/commands/documents.js +5 -5
  18. package/dist/commands/dunning-configs.js +5 -5
  19. package/dist/commands/dunning-reminders.js +5 -5
  20. package/dist/commands/dunning-runs.js +5 -5
  21. package/dist/commands/employees.js +5 -5
  22. package/dist/commands/event-processor-mappings.js +5 -5
  23. package/dist/commands/files-internal.js +5 -5
  24. package/dist/commands/health.js +5 -5
  25. package/dist/commands/inbox.js +5 -5
  26. package/dist/commands/integrations.js +5 -5
  27. package/dist/commands/item-categories.js +5 -5
  28. package/dist/commands/items.js +5 -5
  29. package/dist/commands/journal-lines.js +5 -5
  30. package/dist/commands/journals.js +5 -5
  31. package/dist/commands/ledgers.js +5 -5
  32. package/dist/commands/office-locations.js +5 -5
  33. package/dist/commands/payment-method-ledger-mappings.js +5 -5
  34. package/dist/commands/payment-methods.js +5 -5
  35. package/dist/commands/payment-runs.js +5 -5
  36. package/dist/commands/payment-terms.js +5 -5
  37. package/dist/commands/price-lists.js +5 -5
  38. package/dist/commands/processor-mappings.js +5 -5
  39. package/dist/commands/processors.js +5 -5
  40. package/dist/commands/reports.js +5 -5
  41. package/dist/commands/salary-types.js +5 -5
  42. package/dist/commands/sales-invoices.js +5 -5
  43. package/dist/commands/sales-orders.js +5 -5
  44. package/dist/commands/tags.js +5 -5
  45. package/dist/commands/tax-codes.js +5 -5
  46. package/dist/commands/tax-matrix.js +5 -5
  47. package/dist/commands/tenants.js +5 -5
  48. package/dist/commands/text-templates.js +5 -5
  49. package/dist/commands/tools.js +5 -5
  50. package/dist/commands/{price-lists 3.d.ts → vat-declaration.d.ts} +2 -2
  51. package/dist/commands/{webhooks 3.js → vat-declaration.js} +33 -25
  52. package/dist/commands/vendor-invoices.js +5 -5
  53. package/dist/commands/webhooks.js +5 -5
  54. package/dist/commands/workflows.js +5 -5
  55. package/dist/lib/api-client.d.ts +3 -2
  56. package/dist/lib/api-client.js +4 -0
  57. package/dist/lib/auth.js +1 -0
  58. package/oclif.manifest.json +696 -6069
  59. package/package.json +15 -13
  60. package/dist/commands/access-groups 3.js +0 -1072
  61. package/dist/commands/accounts 2.d.ts +0 -41
  62. package/dist/commands/accounts 2.js +0 -1078
  63. package/dist/commands/async-endpoints-internal 3.d.ts +0 -40
  64. package/dist/commands/async-endpoints-internal 3.js +0 -1062
  65. package/dist/commands/async-endpoints-internal.d.ts +0 -40
  66. package/dist/commands/audit-log 3.d.ts +0 -40
  67. package/dist/commands/audit-log 3.js +0 -1066
  68. package/dist/commands/business-partners 3.d.ts +0 -41
  69. package/dist/commands/business-partners 3.js +0 -1078
  70. package/dist/commands/business-partners---contacts 3.d.ts +0 -42
  71. package/dist/commands/business-partners---contacts 3.js +0 -1072
  72. package/dist/commands/credit-card-accounts 3.d.ts +0 -42
  73. package/dist/commands/credit-card-accounts 3.js +0 -1084
  74. package/dist/commands/dunning-configs 3.d.ts +0 -40
  75. package/dist/commands/dunning-configs 3.js +0 -1072
  76. package/dist/commands/dunning-runs 3.d.ts +0 -40
  77. package/dist/commands/dunning-runs 3.js +0 -1061
  78. package/dist/commands/event-processor-mappings 3.d.ts +0 -40
  79. package/dist/commands/event-processor-mappings 3.js +0 -1071
  80. package/dist/commands/files-internal 3.d.ts +0 -40
  81. package/dist/commands/files-internal 3.js +0 -1073
  82. package/dist/commands/health 3.d.ts +0 -40
  83. package/dist/commands/health 3.js +0 -1067
  84. package/dist/commands/inbox 3.d.ts +0 -40
  85. package/dist/commands/inbox 3.js +0 -1065
  86. package/dist/commands/integrations 3.d.ts +0 -41
  87. package/dist/commands/integrations 3.js +0 -1067
  88. package/dist/commands/item-categories 3.d.ts +0 -40
  89. package/dist/commands/item-categories 3.js +0 -1072
  90. package/dist/commands/items 3.d.ts +0 -40
  91. package/dist/commands/items 3.js +0 -1072
  92. package/dist/commands/journals 3.d.ts +0 -42
  93. package/dist/commands/journals 3.js +0 -1088
  94. package/dist/commands/office-locations 3.d.ts +0 -40
  95. package/dist/commands/office-locations 3.js +0 -1072
  96. package/dist/commands/payment-method-ledger-mappings 3.d.ts +0 -41
  97. package/dist/commands/payment-method-ledger-mappings 3.js +0 -1066
  98. package/dist/commands/payment-methods 3.d.ts +0 -40
  99. package/dist/commands/payment-methods 3.js +0 -1072
  100. package/dist/commands/payment-runs 3.d.ts +0 -42
  101. package/dist/commands/payment-runs 3.js +0 -1087
  102. package/dist/commands/payment-terms 3.d.ts +0 -40
  103. package/dist/commands/payment-terms 3.js +0 -1073
  104. package/dist/commands/price-lists 3.js +0 -1078
  105. package/dist/commands/processor-mappings 2.d.ts +0 -40
  106. package/dist/commands/processor-mappings 2.js +0 -1070
  107. package/dist/commands/reconciliation 3.d.ts +0 -40
  108. package/dist/commands/reconciliation 3.js +0 -1069
  109. package/dist/commands/reconciliation.d.ts +0 -40
  110. package/dist/commands/reconciliation.js +0 -1071
  111. package/dist/commands/salary-types 3.d.ts +0 -40
  112. package/dist/commands/salary-types 3.js +0 -1072
  113. package/dist/commands/sales-invoices 3.d.ts +0 -43
  114. package/dist/commands/sales-invoices 3.js +0 -1100
  115. package/dist/commands/sales-orders 3.d.ts +0 -43
  116. package/dist/commands/sales-orders 3.js +0 -1098
  117. package/dist/commands/tags 3.d.ts +0 -40
  118. package/dist/commands/tags 3.js +0 -1072
  119. package/dist/commands/tax-codes 3.d.ts +0 -40
  120. package/dist/commands/tax-codes 3.js +0 -1075
  121. package/dist/commands/text-templates 3.d.ts +0 -40
  122. package/dist/commands/text-templates 3.js +0 -1072
  123. package/dist/commands/webhooks 3.d.ts +0 -40
@@ -1,1061 +0,0 @@
1
- import { Command, Args, Flags } from '@oclif/core';
2
- import { apiRequest, ApiError } from '../lib/api-client.js';
3
- import { getCurrentContext, getContext, getBaseUrls } from '../lib/config.js';
4
- // Add 'import' action if both create and update exist
5
- const HAS_IMPORT = false;
6
- const HAS_EXPORT = false;
7
- const HAS_CAMT053 = false;
8
- const NESTED_IMPORTS = [];
9
- const SUBCOMMANDS = [...["trigger"], ...(HAS_IMPORT ? ['import'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_IMPORTS.map(n => `import-${n}`)];
10
- const ENDPOINTS = {
11
- 'trigger': { method: 'POST', path: '/v1/dunning-runs/trigger', summary: 'Manually trigger a dunning run', pathParams: [], hasBody: true, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
12
- };
13
- export default class DunningRuns extends Command {
14
- static description = 'Manage dunning runs';
15
- static examples = [];
16
- static args = {
17
- action: Args.string({ description: 'Action: ' + SUBCOMMANDS.join(', '), required: true }),
18
- id: Args.string({ description: 'Resource ID (for get, update, delete operations)', required: false }),
19
- };
20
- static flags = {
21
- context: Flags.string({ char: 'c', description: 'Context to use' }),
22
- output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
23
- table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
24
- csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
25
- data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
26
- file: Flags.string({ char: 'f', description: 'Read request body from file' }),
27
- set: Flags.string({ char: 's', description: 'Set individual field (e.g. --set firstName=John)', multiple: true }),
28
- page: Flags.string({ description: 'Page number' }),
29
- limit: Flags.string({ description: 'Items per page' }),
30
- include: Flags.string({ description: 'Relations to include' }),
31
- search: Flags.string({ description: 'Search term' }),
32
- 'sort-by': Flags.string({ description: 'Sort field' }),
33
- filter: Flags.string({ description: 'Filter (e.g. --filter status=ACTIVE). Operators: in:A,B, like:%, gt:, lt:, null:', multiple: true }),
34
- query: Flags.string({ description: 'Additional query params as JSON' }),
35
- fields: Flags.string({ description: 'Comma-separated list of fields to show (e.g. --fields=id,name,status)' }),
36
- sanitize: Flags.boolean({ description: 'Remove null values, audit fields, and duplicate UUIDs from output' }),
37
- 'show-http-request': Flags.boolean({ description: 'Show HTTP request details (method, URL, body)' }),
38
- };
39
- async run() {
40
- const { args, flags } = await this.parse(DunningRuns);
41
- // Handle import action specially
42
- if (args.action === 'import') {
43
- if (!HAS_IMPORT)
44
- this.error('Import not available for this resource');
45
- await this.runImport(flags);
46
- return;
47
- }
48
- // Handle export action specially
49
- if (args.action === 'export') {
50
- if (!HAS_EXPORT)
51
- this.error('Export not available for this resource');
52
- await this.runExport(flags);
53
- return;
54
- }
55
- // Handle CAMT.053 import specially - sends raw XML
56
- if (args.action === 'import-camt053') {
57
- if (!HAS_CAMT053)
58
- this.error('CAMT.053 import not available for this resource');
59
- await this.runCamt053Import(flags);
60
- return;
61
- }
62
- // Handle nested resource imports (e.g., import-prices)
63
- if (args.action.startsWith('import-')) {
64
- const suffix = args.action.replace('import-', '');
65
- if (NESTED_IMPORTS.includes(suffix)) {
66
- await this.runNestedImport(suffix, args.id, flags);
67
- return;
68
- }
69
- }
70
- const endpoint = ENDPOINTS[args.action];
71
- if (!endpoint)
72
- this.error(`Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
73
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
74
- if (!context)
75
- this.error('No context configured. Run: aderis auth login --new');
76
- if (!context.tokens)
77
- this.error('Not logged in. Run: aderis auth login');
78
- let apiPath = endpoint.path;
79
- for (let i = 0; i < endpoint.pathParams.length; i++) {
80
- const param = endpoint.pathParams[i];
81
- let value;
82
- if (i === 0) {
83
- // First path param always comes from positional argument
84
- value = args.id;
85
- if (!value)
86
- this.error('Missing required argument: id. Usage: aderis dunning-runs <action> <id>');
87
- }
88
- else {
89
- const flagName = param.replace(/\./g, '-').replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
90
- value = flags[flagName];
91
- if (!value)
92
- this.error(`Missing required parameter: --${flagName}`);
93
- }
94
- apiPath = apiPath.replace(`{${param}}`, String(value));
95
- }
96
- const queryParams = {};
97
- if (flags.page)
98
- queryParams.page = flags.page;
99
- if (flags.limit)
100
- queryParams.limit = flags.limit;
101
- if (flags.include)
102
- queryParams.include = flags.include;
103
- if (flags.search)
104
- queryParams.search = flags.search;
105
- if (flags['sort-by'])
106
- queryParams.sortBy = flags['sort-by'];
107
- if (flags.query) {
108
- try {
109
- Object.assign(queryParams, JSON.parse(flags.query));
110
- }
111
- catch {
112
- this.error('Invalid JSON in --query');
113
- }
114
- }
115
- // Parse --filter flags (e.g., --filter status=ACTIVE becomes filter.status=$eq:ACTIVE)
116
- if (flags.filter && flags.filter.length > 0) {
117
- for (const f of flags.filter) {
118
- const eqIndex = f.indexOf('=');
119
- if (eqIndex === -1)
120
- this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
121
- const key = f.slice(0, eqIndex);
122
- const value = this.parseFilterValue(f.slice(eqIndex + 1));
123
- const filterKey = `filter.${key}`;
124
- if (filterKey in queryParams) {
125
- // Multiple filters on same field: collect as array
126
- const existing = queryParams[filterKey];
127
- queryParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
128
- }
129
- else {
130
- queryParams[filterKey] = value;
131
- }
132
- }
133
- }
134
- let data;
135
- if (endpoint.isMultipart) {
136
- if (!flags.file)
137
- this.error('Missing required --file flag for file upload');
138
- const fsModule = await import('node:fs');
139
- const pathModule = await import('node:path');
140
- const FormDataLib = (await import('form-data')).default;
141
- const form = new FormDataLib();
142
- form.append('file', fsModule.createReadStream(flags.file), pathModule.basename(flags.file));
143
- // Append --set fields as extra form fields (e.g. --set type=CREDIT_CARD_STATEMENT)
144
- if (flags.set && flags.set.length > 0) {
145
- for (const pair of flags.set) {
146
- const eqIndex = pair.indexOf('=');
147
- if (eqIndex === -1)
148
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
149
- form.append(pair.slice(0, eqIndex), pair.slice(eqIndex + 1));
150
- }
151
- }
152
- data = form;
153
- }
154
- else if (endpoint.hasBody) {
155
- if (flags.file) {
156
- const fsModule = await import('node:fs');
157
- try {
158
- data = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
159
- }
160
- catch {
161
- this.error(`Failed to read file: ${flags.file}`);
162
- }
163
- }
164
- else if (flags.data) {
165
- try {
166
- data = JSON.parse(flags.data);
167
- }
168
- catch {
169
- this.error('Invalid JSON in --data');
170
- }
171
- }
172
- // Apply --set flags (can be combined with --data or --file)
173
- if (flags.set && flags.set.length > 0) {
174
- if (!data)
175
- data = {};
176
- const body = data;
177
- const arrayFields = new Set(endpoint.bodyArrayFields);
178
- for (const pair of flags.set) {
179
- const eqIndex = pair.indexOf('=');
180
- if (eqIndex === -1)
181
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
182
- const key = pair.slice(0, eqIndex);
183
- let value = pair.slice(eqIndex + 1);
184
- // Try to parse as JSON for numbers, booleans, arrays, objects
185
- try {
186
- value = JSON.parse(value);
187
- }
188
- catch { /* keep as string */ }
189
- // For top-level keys typed as array in the API schema, split bare
190
- // comma-separated input (e.g. "1171,1170" -> ["1171","1170"]) and
191
- // wrap a lone scalar in a single-element array. Skips when --set
192
- // already provided a JSON array.
193
- const isArrayField = !key.includes('.') && arrayFields.has(key);
194
- if (isArrayField && !Array.isArray(value)) {
195
- if (typeof value === 'string') {
196
- value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
197
- }
198
- else if (value !== undefined && value !== null) {
199
- value = [value];
200
- }
201
- }
202
- // Support nested keys like "address.city"
203
- const keys = key.split('.');
204
- if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
205
- this.error(`Invalid --set key: ${key}`);
206
- }
207
- let obj = body;
208
- for (let i = 0; i < keys.length - 1; i++) {
209
- if (!(keys[i] in obj) || typeof obj[keys[i]] !== 'object') {
210
- obj[keys[i]] = {};
211
- }
212
- obj = obj[keys[i]];
213
- }
214
- obj[keys[keys.length - 1]] = value;
215
- }
216
- }
217
- }
218
- else if (flags.set && flags.set.length > 0) {
219
- // For GET endpoints, --set adds query params
220
- for (const pair of flags.set) {
221
- const eqIndex = pair.indexOf('=');
222
- if (eqIndex === -1)
223
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
224
- const key = pair.slice(0, eqIndex);
225
- let value = pair.slice(eqIndex + 1);
226
- try {
227
- value = JSON.parse(value);
228
- }
229
- catch { /* keep as string */ }
230
- queryParams[key] = value;
231
- }
232
- }
233
- // Show HTTP request details if --show-http-request flag is set
234
- if (flags['show-http-request']) {
235
- const baseUrls = getBaseUrls(context.environment);
236
- const queryString = Object.keys(queryParams).length > 0
237
- ? '?' + Object.entries(queryParams).flatMap(([k, v]) => {
238
- const vals = Array.isArray(v) ? v : [v];
239
- return vals.map(val => `${encodeURIComponent(k)}=${encodeURIComponent(String(val))}`);
240
- }).join('&')
241
- : '';
242
- process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
243
- if (endpoint.isMultipart) {
244
- process.stderr.write(`Body: [multipart/form-data file upload]\n`);
245
- }
246
- else if (data) {
247
- process.stderr.write(`Body: ${JSON.stringify(data, null, 2)}\n`);
248
- }
249
- process.stderr.write('\n');
250
- }
251
- try {
252
- // Binary response: download to file
253
- if (endpoint.isBinaryResponse) {
254
- if (!flags.file) {
255
- this.error(`Endpoint returns a binary file. Specify the output path with -f / --file (e.g. -f report.xlsx).`);
256
- }
257
- const binResponse = await apiRequest(endpoint.method, apiPath, {
258
- params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
259
- data,
260
- contextName: flags.context,
261
- binary: true,
262
- });
263
- const fsModule = await import('node:fs');
264
- const binData = binResponse.data;
265
- const buffer = Buffer.isBuffer(binData)
266
- ? binData
267
- : Buffer.from(binData);
268
- fsModule.writeFileSync(flags.file, buffer);
269
- this.log(`Saved ${buffer.length} bytes to ${flags.file}`);
270
- return;
271
- }
272
- const response = await apiRequest(endpoint.method, apiPath, {
273
- params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
274
- data,
275
- contextName: flags.context,
276
- acceptAny: true,
277
- });
278
- // Check content-type for non-JSON responses (XML, text, etc.)
279
- const contentType = (response.headers['content-type'] || '').toLowerCase();
280
- if (contentType.includes('xml') || contentType.includes('text/')) {
281
- // Output raw content for XML/text responses (CSV, plain, HTML, etc.)
282
- this.log(String(response.data));
283
- return;
284
- }
285
- // Parse JSON if response came as string (due to acceptAny)
286
- let output = response.data;
287
- if (typeof output === 'string') {
288
- try {
289
- output = JSON.parse(output);
290
- }
291
- catch { /* keep as string */ }
292
- }
293
- // Extract data array from paginated wrapper (e.g., { data: [...], total: 3 })
294
- if (output && typeof output === 'object' && !Array.isArray(output) && 'data' in output && Array.isArray(output.data)) {
295
- output = output.data;
296
- }
297
- // For table/csv on non-array responses, auto-extract the primary array
298
- // e.g., { payments: [...], total: 3 } → extract payments array
299
- if ((flags.table || flags.output === 'table' || flags.csv || flags.output === 'csv')
300
- && output && typeof output === 'object' && !Array.isArray(output)) {
301
- const obj = output;
302
- const arrayKeys = Object.keys(obj).filter(k => Array.isArray(obj[k]));
303
- if (arrayKeys.length === 1) {
304
- output = obj[arrayKeys[0]];
305
- }
306
- }
307
- // Filter fields if --fields flag is provided
308
- if (flags.fields) {
309
- const fieldList = flags.fields.split(',').map(f => f.trim());
310
- output = this.filterFields(output, fieldList);
311
- }
312
- // Sanitize output if requested
313
- if (flags.sanitize) {
314
- output = this.sanitizeOutput(output);
315
- }
316
- const fieldList = flags.fields?.split(',').map(f => f.trim());
317
- if (flags.csv || flags.output === 'csv')
318
- this.printCsv(output, fieldList);
319
- else if (flags.table || flags.output === 'table')
320
- this.printTable(output, fieldList);
321
- else
322
- this.log(JSON.stringify(output, null, 2));
323
- }
324
- catch (error) {
325
- if (error instanceof ApiError) {
326
- if (error.status === 404)
327
- this.error(error.message);
328
- this.error(`API Error (${error.status}): ${error.message}`);
329
- }
330
- throw error;
331
- }
332
- }
333
- async runImport(flags) {
334
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
335
- if (!context)
336
- this.error('No context configured. Run: aderis auth login --new');
337
- if (!context.tokens)
338
- this.error('Not logged in. Run: aderis auth login');
339
- // Get data from file, --data, or --set flags
340
- let items = [];
341
- if (flags.file) {
342
- const fsModule = await import('node:fs');
343
- try {
344
- const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
345
- items = Array.isArray(content) ? content : [content];
346
- }
347
- catch {
348
- this.error(`Failed to read file: ${flags.file}`);
349
- }
350
- }
351
- else if (flags.data) {
352
- try {
353
- const content = JSON.parse(flags.data);
354
- items = Array.isArray(content) ? content : [content];
355
- }
356
- catch {
357
- this.error('Invalid JSON in --data');
358
- }
359
- }
360
- else if (flags.set && flags.set.length > 0) {
361
- const item = {};
362
- const arrayFields = new Set(ENDPOINTS['create']?.bodyArrayFields ?? []);
363
- for (const pair of flags.set) {
364
- const eqIndex = pair.indexOf('=');
365
- if (eqIndex === -1)
366
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
367
- const key = pair.slice(0, eqIndex);
368
- let value = pair.slice(eqIndex + 1);
369
- try {
370
- value = JSON.parse(value);
371
- }
372
- catch { /* keep as string */ }
373
- const isArrayField = !key.includes('.') && arrayFields.has(key);
374
- if (isArrayField && !Array.isArray(value)) {
375
- if (typeof value === 'string') {
376
- value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
377
- }
378
- else if (value !== undefined && value !== null) {
379
- value = [value];
380
- }
381
- }
382
- const keys = key.split('.');
383
- if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
384
- this.error(`Invalid --set key: ${key}`);
385
- }
386
- let obj = item;
387
- for (let i = 0; i < keys.length - 1; i++) {
388
- if (!(keys[i] in obj))
389
- obj[keys[i]] = {};
390
- obj = obj[keys[i]];
391
- }
392
- obj[keys[keys.length - 1]] = value;
393
- }
394
- items = [item];
395
- }
396
- else {
397
- this.error('Import requires --file, --data, or --set flags');
398
- }
399
- const createEndpoint = ENDPOINTS['create'];
400
- const updateEndpoint = ENDPOINTS['update'];
401
- if (!createEndpoint || !updateEndpoint) {
402
- this.error('Import requires both create and update endpoints');
403
- }
404
- // Helper to extract identifier from item (id, code, or xxxCode)
405
- const getItemIdentifier = (item) => {
406
- if (item.id)
407
- return String(item.id);
408
- if (item.code)
409
- return String(item.code);
410
- // Look for xxxCode fields (e.g., ledgerCode, accountCode)
411
- for (const key of Object.keys(item)) {
412
- if (key.endsWith('Code') && item[key])
413
- return String(item[key]);
414
- }
415
- // Look for name as fallback
416
- if (item.name)
417
- return String(item.name).slice(0, 30);
418
- return '';
419
- };
420
- const results = [];
421
- for (const item of items) {
422
- const identifier = getItemIdentifier(item);
423
- try {
424
- // Try to create
425
- const response = await apiRequest('POST', createEndpoint.path, {
426
- data: item,
427
- contextName: flags.context,
428
- });
429
- const id = response.data?.id;
430
- results.push({ status: 'created', id: id ? String(id) : undefined, identifier });
431
- }
432
- catch (error) {
433
- if (error instanceof ApiError && error.status === 409) {
434
- // Conflict - try to update existing
435
- const errorData = error.data;
436
- const existingId = errorData?.existingId;
437
- if (existingId) {
438
- try {
439
- const updatePath = updateEndpoint.path.replace('{id}', existingId);
440
- await apiRequest('PATCH', updatePath, {
441
- data: item,
442
- contextName: flags.context,
443
- });
444
- results.push({ status: 'updated', id: existingId, identifier });
445
- }
446
- catch (updateError) {
447
- const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
448
- results.push({ status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` });
449
- }
450
- }
451
- else {
452
- results.push({ status: 'error', identifier, error: 'Conflict but no existingId returned' });
453
- }
454
- }
455
- else {
456
- const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
457
- results.push({ status: 'error', identifier, error: msg });
458
- }
459
- }
460
- }
461
- // Summary counts
462
- const created = results.filter(r => r.status === 'created').length;
463
- const updated = results.filter(r => r.status === 'updated').length;
464
- const errors = results.filter(r => r.status === 'error');
465
- // Output results based on format (default: table)
466
- const outputFormat = flags.output || 'table';
467
- if (outputFormat === 'json') {
468
- this.log(JSON.stringify(results, null, 2));
469
- }
470
- else if (outputFormat === 'csv' || flags.csv) {
471
- // CSV output
472
- this.log('status,identifier,id,error');
473
- for (const r of results) {
474
- const err = (r.error || '').replace(/"/g, '""');
475
- this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
476
- }
477
- }
478
- else {
479
- // Table output (default)
480
- if (results.length > 0) {
481
- const statusWidth = 8;
482
- const identifierWidth = Math.max(10, ...results.map(r => (r.identifier || '').length));
483
- this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
484
- this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
485
- for (const r of results) {
486
- const status = r.status === 'created' ? 'created' : r.status === 'updated' ? 'updated' : 'error';
487
- this.log(`${status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
488
- }
489
- }
490
- }
491
- // Always show summary at the end
492
- this.log('');
493
- this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
494
- }
495
- async runExport(flags) {
496
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
497
- if (!context)
498
- this.error('No context configured. Run: aderis auth login --new');
499
- if (!context.tokens)
500
- this.error('Not logged in. Run: aderis auth login');
501
- const listEndpoint = ENDPOINTS['list'];
502
- if (!listEndpoint)
503
- this.error('Export requires a list endpoint');
504
- const allItems = [];
505
- let page = 1;
506
- const limit = 100;
507
- let hasMore = true;
508
- // Build base query params
509
- const baseParams = {};
510
- if (flags.search)
511
- baseParams.search = flags.search;
512
- if (flags['sort-by'])
513
- baseParams.sortBy = flags['sort-by'];
514
- if (flags.include)
515
- baseParams.include = flags.include;
516
- if (flags.query) {
517
- try {
518
- Object.assign(baseParams, JSON.parse(flags.query));
519
- }
520
- catch {
521
- this.error('Invalid JSON in --query');
522
- }
523
- }
524
- // Parse --filter flags (auto-prepend $eq: if no operator specified)
525
- if (flags.filter && flags.filter.length > 0) {
526
- for (const f of flags.filter) {
527
- const eqIndex = f.indexOf('=');
528
- if (eqIndex === -1)
529
- this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
530
- const key = f.slice(0, eqIndex);
531
- const value = this.parseFilterValue(f.slice(eqIndex + 1));
532
- const filterKey = `filter.${key}`;
533
- if (filterKey in baseParams) {
534
- const existing = baseParams[filterKey];
535
- baseParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
536
- }
537
- else {
538
- baseParams[filterKey] = value;
539
- }
540
- }
541
- }
542
- // Fetch all pages
543
- process.stderr.write('Exporting...');
544
- while (hasMore) {
545
- const params = { ...baseParams, page, limit };
546
- const response = await apiRequest('GET', listEndpoint.path, {
547
- params,
548
- contextName: flags.context,
549
- });
550
- let items = [];
551
- const data = response.data;
552
- // Handle paginated response format
553
- if (data && typeof data === 'object' && 'data' in data && Array.isArray(data.data)) {
554
- items = data.data;
555
- }
556
- else if (Array.isArray(response.data)) {
557
- items = response.data;
558
- }
559
- allItems.push(...items);
560
- process.stderr.write(` ${allItems.length}`);
561
- // Check if there are more pages
562
- if (items.length < limit) {
563
- hasMore = false;
564
- }
565
- else {
566
- page++;
567
- }
568
- }
569
- process.stderr.write(' done\n');
570
- // Filter fields if specified
571
- let output = allItems;
572
- if (flags.fields) {
573
- const fieldList = flags.fields.split(',').map(f => f.trim());
574
- output = this.filterFields(allItems, fieldList);
575
- }
576
- // Sanitize output if requested
577
- if (flags.sanitize) {
578
- output = this.sanitizeOutput(output);
579
- }
580
- // Output in requested format
581
- const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
582
- if (flags.csv || flags.output === 'csv') {
583
- this.printCsv(output, fieldList);
584
- }
585
- else {
586
- this.log(JSON.stringify(output, null, 2));
587
- }
588
- }
589
- async runCamt053Import(flags) {
590
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
591
- if (!context)
592
- this.error('No context configured. Run: aderis auth login --new');
593
- if (!context.tokens)
594
- this.error('Not logged in. Run: aderis auth login');
595
- if (!flags.file) {
596
- this.error('CAMT.053 import requires --file (-f) flag with path to XML file');
597
- }
598
- const fsModule = await import('node:fs');
599
- let xmlContent;
600
- try {
601
- xmlContent = fsModule.readFileSync(flags.file, 'utf-8');
602
- }
603
- catch {
604
- this.error(`Failed to read file: ${flags.file}`);
605
- }
606
- const endpoint = ENDPOINTS['import-camt053'];
607
- try {
608
- const response = await apiRequest(endpoint.method, endpoint.path, {
609
- data: xmlContent,
610
- contextName: flags.context,
611
- contentType: 'application/xml',
612
- });
613
- // Extract transactions array and counts from response
614
- let transactions = [];
615
- let imported = 0;
616
- let skipped = 0;
617
- if (response.data && typeof response.data === 'object') {
618
- const data = response.data;
619
- if ('data' in data && Array.isArray(data.data)) {
620
- transactions = data.data;
621
- }
622
- else if ('transactions' in data && Array.isArray(data.transactions)) {
623
- transactions = data.transactions;
624
- }
625
- else if (Array.isArray(response.data)) {
626
- transactions = response.data;
627
- }
628
- if (typeof data.imported === 'number')
629
- imported = data.imported;
630
- if (typeof data.skipped === 'number')
631
- skipped = data.skipped;
632
- }
633
- else if (Array.isArray(response.data)) {
634
- transactions = response.data;
635
- }
636
- if (imported === 0 && skipped === 0 && transactions.length > 0) {
637
- for (const tx of transactions) {
638
- const t = tx;
639
- if (t.status === 'skipped' || t.skipped === true) {
640
- skipped++;
641
- }
642
- else {
643
- imported++;
644
- }
645
- }
646
- if (imported === 0 && skipped === 0) {
647
- imported = transactions.length;
648
- }
649
- }
650
- let output = transactions;
651
- if (flags.sanitize) {
652
- output = this.sanitizeOutput(transactions);
653
- }
654
- const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
655
- if (flags.csv || flags.output === 'csv') {
656
- this.printCsv(output, fieldList);
657
- }
658
- else if (flags.table || flags.output === 'table') {
659
- this.printTable(output, fieldList);
660
- }
661
- else {
662
- this.log(JSON.stringify(output, null, 2));
663
- }
664
- this.log('');
665
- this.log(`Summary: ${imported} imported, ${skipped} skipped`);
666
- }
667
- catch (error) {
668
- if (error instanceof ApiError) {
669
- if (error.status === 404)
670
- this.error(error.message);
671
- this.error(`API Error (${error.status}): ${error.message}`);
672
- }
673
- throw error;
674
- }
675
- }
676
- async runNestedImport(suffix, parentId, flags) {
677
- if (!parentId) {
678
- this.error(`Missing required argument: id. Usage: aderis dunning-runs import-${suffix} <parent-id> --file data.json`);
679
- }
680
- const context = flags.context ? getContext(flags.context) : getCurrentContext();
681
- if (!context)
682
- this.error('No context configured. Run: aderis auth login --new');
683
- if (!context.tokens)
684
- this.error('Not logged in. Run: aderis auth login');
685
- // Get data from file, --data, or --set flags
686
- let items = [];
687
- if (flags.file) {
688
- const fsModule = await import('node:fs');
689
- try {
690
- const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
691
- items = Array.isArray(content) ? content : [content];
692
- }
693
- catch {
694
- this.error(`Failed to read file: ${flags.file}`);
695
- }
696
- }
697
- else if (flags.data) {
698
- try {
699
- const content = JSON.parse(flags.data);
700
- items = Array.isArray(content) ? content : [content];
701
- }
702
- catch {
703
- this.error('Invalid JSON in --data');
704
- }
705
- }
706
- else if (flags.set && flags.set.length > 0) {
707
- const item = {};
708
- const arrayFields = new Set(ENDPOINTS[`create-${suffix}`]?.bodyArrayFields ?? []);
709
- for (const pair of flags.set) {
710
- const eqIndex = pair.indexOf('=');
711
- if (eqIndex === -1)
712
- this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
713
- const key = pair.slice(0, eqIndex);
714
- let value = pair.slice(eqIndex + 1);
715
- try {
716
- value = JSON.parse(value);
717
- }
718
- catch { /* keep as string */ }
719
- const isArrayField = !key.includes('.') && arrayFields.has(key);
720
- if (isArrayField && !Array.isArray(value)) {
721
- if (typeof value === 'string') {
722
- value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
723
- }
724
- else if (value !== undefined && value !== null) {
725
- value = [value];
726
- }
727
- }
728
- const keys = key.split('.');
729
- if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
730
- this.error(`Invalid --set key: ${key}`);
731
- }
732
- let obj = item;
733
- for (let i = 0; i < keys.length - 1; i++) {
734
- if (!(keys[i] in obj))
735
- obj[keys[i]] = {};
736
- obj = obj[keys[i]];
737
- }
738
- obj[keys[keys.length - 1]] = value;
739
- }
740
- items = [item];
741
- }
742
- else {
743
- this.error(`Import requires --file, --data, or --set flags`);
744
- }
745
- const createEndpoint = ENDPOINTS[`create-${suffix}`];
746
- const updateEndpoint = ENDPOINTS[`update-${suffix}`];
747
- if (!createEndpoint || !updateEndpoint) {
748
- this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
749
- }
750
- // Build the base path with parent ID (first path param)
751
- const firstParam = createEndpoint.pathParams[0];
752
- const basePath = createEndpoint.path.replace(`{${firstParam}}`, parentId);
753
- // Helper to extract identifier from item
754
- const getItemIdentifier = (item) => {
755
- if (item.id)
756
- return String(item.id);
757
- if (item.itemId)
758
- return String(item.itemId);
759
- if (item.code)
760
- return String(item.code);
761
- for (const key of Object.keys(item)) {
762
- if (key.endsWith('Id') && item[key])
763
- return String(item[key]);
764
- if (key.endsWith('Code') && item[key])
765
- return String(item[key]);
766
- }
767
- return '';
768
- };
769
- const results = [];
770
- for (const item of items) {
771
- const identifier = getItemIdentifier(item);
772
- try {
773
- // Try to create
774
- const response = await apiRequest('POST', basePath, {
775
- data: item,
776
- contextName: flags.context,
777
- });
778
- const id = response.data?.id;
779
- results.push({ status: 'created', id: id ? String(id) : undefined, identifier });
780
- }
781
- catch (error) {
782
- if (error instanceof ApiError && error.status === 409) {
783
- // Conflict - try to update existing
784
- const errorData = error.data;
785
- const existingId = errorData?.existingId || item.id;
786
- if (existingId) {
787
- try {
788
- // Find the nested ID param name (e.g., 'priceId' for prices)
789
- const firstUpdateParam = updateEndpoint.pathParams[0];
790
- const nestedIdParam = updateEndpoint.pathParams.find((p, i) => i > 0);
791
- let updatePath = updateEndpoint.path.replace(`{${firstUpdateParam}}`, parentId);
792
- if (nestedIdParam) {
793
- updatePath = updatePath.replace(`{${nestedIdParam}}`, existingId);
794
- }
795
- await apiRequest('PATCH', updatePath, {
796
- data: item,
797
- contextName: flags.context,
798
- });
799
- results.push({ status: 'updated', id: existingId, identifier });
800
- }
801
- catch (updateError) {
802
- const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
803
- results.push({ status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` });
804
- }
805
- }
806
- else {
807
- results.push({ status: 'error', identifier, error: 'Conflict but no existingId returned' });
808
- }
809
- }
810
- else {
811
- const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
812
- results.push({ status: 'error', identifier, error: msg });
813
- }
814
- }
815
- }
816
- // Summary counts
817
- const created = results.filter(r => r.status === 'created').length;
818
- const updated = results.filter(r => r.status === 'updated').length;
819
- const errors = results.filter(r => r.status === 'error');
820
- // Output results based on format (default: table)
821
- const outputFormat = flags.output || 'table';
822
- if (outputFormat === 'json') {
823
- this.log(JSON.stringify(results, null, 2));
824
- }
825
- else if (outputFormat === 'csv' || flags.csv) {
826
- this.log('status,identifier,id,error');
827
- for (const r of results) {
828
- const err = (r.error || '').replace(/"/g, '""');
829
- this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
830
- }
831
- }
832
- else {
833
- if (results.length > 0) {
834
- const statusWidth = 8;
835
- const identifierWidth = Math.max(10, ...results.map(r => (r.identifier || '').length));
836
- this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
837
- this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
838
- for (const r of results) {
839
- const status = r.status === 'created' ? 'created' : r.status === 'updated' ? 'updated' : 'error';
840
- this.log(`${status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
841
- }
842
- }
843
- }
844
- this.log('');
845
- this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
846
- }
847
- parseFilterValue(value) {
848
- // Recognises the nestjs-paginate operator set (with or without the leading $)
849
- // and recursively unwraps chained operators like 'not:null' -> '$not:$null'
850
- // or 'not:like:John' -> '$not:$like:John'. Falls back to '$eq:<value>' when
851
- // no operator prefix is present.
852
- const opRe = /^\$?(and|or|not|eq|gt|gte|in|null|lt|lte|btw|ne|ilike|like|sw|contains)(?::|$)/;
853
- const m = value.match(opRe);
854
- if (!m)
855
- return `\$eq:${value}`;
856
- const op = m[1];
857
- const rest = value.slice(m[0].length);
858
- if (rest === '')
859
- return `\$${op}`;
860
- return opRe.test(rest) ? `\$${op}:${this.parseFilterValue(rest)}` : `\$${op}:${rest}`;
861
- }
862
- filterFields(data, fields) {
863
- const isUnsafeKey = (k) => k === '__proto__' || k === 'constructor' || k === 'prototype';
864
- const pick = (obj, keys) => {
865
- // Group keys by their first segment so sibling sub-paths
866
- // (e.g. 'items.amount' + 'items._type') resolve in one recursive pass
867
- // and don't clobber each other on merge.
868
- const directKeys = new Set();
869
- const nestedKeys = new Map();
870
- for (const key of keys) {
871
- if (key.split('.').some(isUnsafeKey))
872
- continue;
873
- if (key.includes('.')) {
874
- const [first, ...rest] = key.split('.');
875
- if (isUnsafeKey(first))
876
- continue;
877
- const list = nestedKeys.get(first);
878
- if (list) {
879
- list.push(rest.join('.'));
880
- }
881
- else {
882
- nestedKeys.set(first, [rest.join('.')]);
883
- }
884
- }
885
- else {
886
- directKeys.add(key);
887
- }
888
- }
889
- const result = {};
890
- for (const key of directKeys) {
891
- if (key in obj)
892
- result[key] = obj[key];
893
- }
894
- for (const [first, restKeys] of nestedKeys) {
895
- const val = obj[first];
896
- if (!val || typeof val !== 'object')
897
- continue;
898
- if (Array.isArray(val)) {
899
- result[first] = val.map(item => pick(item, restKeys));
900
- }
901
- else {
902
- result[first] = pick(val, restKeys);
903
- }
904
- }
905
- return result;
906
- };
907
- if (Array.isArray(data)) {
908
- return data.map(item => pick(item, fields));
909
- }
910
- return pick(data, fields);
911
- }
912
- sanitizeOutput(data) {
913
- const auditFields = ['_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy'];
914
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
915
- const sanitize = (obj, parentUuids = new Set()) => {
916
- if (obj === null || obj === undefined)
917
- return undefined;
918
- if (Array.isArray(obj)) {
919
- const result = obj.map(item => sanitize(item, new Set(parentUuids))).filter(item => item !== undefined);
920
- return result.length > 0 ? result : undefined;
921
- }
922
- if (typeof obj === 'object') {
923
- const input = obj;
924
- // Use a Map to avoid any prototype-pollution risk on the result object
925
- const collected = new Map();
926
- // Collect UUIDs from this level to pass to children
927
- const currentUuids = new Set(parentUuids);
928
- for (const [, value] of Object.entries(input)) {
929
- if (typeof value === 'string' && uuidRegex.test(value)) {
930
- currentUuids.add(value);
931
- }
932
- }
933
- for (const [key, value] of Object.entries(input)) {
934
- // Skip prototype-pollution keys
935
- if (key === '__proto__' || key === 'constructor' || key === 'prototype')
936
- continue;
937
- // Skip audit fields
938
- if (auditFields.includes(key))
939
- continue;
940
- // Skip null/undefined values
941
- if (value === null || value === undefined)
942
- continue;
943
- // Skip UUID values that exist in parent
944
- if (typeof value === 'string' && uuidRegex.test(value) && parentUuids.has(value))
945
- continue;
946
- // Recursively sanitize nested objects/arrays
947
- const sanitized = sanitize(value, currentUuids);
948
- if (sanitized !== undefined) {
949
- collected.set(key, sanitized);
950
- }
951
- }
952
- if (collected.size === 0)
953
- return undefined;
954
- return Object.fromEntries(collected);
955
- }
956
- return obj;
957
- };
958
- return sanitize(data) ?? (Array.isArray(data) ? [] : {});
959
- }
960
- getColumns(data, fields, flatten = false) {
961
- const items = Array.isArray(data) ? data : [data];
962
- if (items.length === 0)
963
- return { cols: [], items: [] };
964
- const first = items[0];
965
- const hiddenFields = ['tenantId', '_type'];
966
- if (fields) {
967
- return { cols: fields, items: items };
968
- }
969
- // Recursively collect all column paths, flattening objects (but not arrays)
970
- const collectPaths = (obj, prefix = '') => {
971
- const paths = [];
972
- for (const key of Object.keys(obj)) {
973
- const fullKey = prefix ? `${prefix}.${key}` : key;
974
- if (hiddenFields.includes(key))
975
- continue;
976
- const val = obj[key];
977
- if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
978
- // Flatten nested objects (but not arrays)
979
- if (flatten) {
980
- paths.push(...collectPaths(val, fullKey));
981
- }
982
- // Skip objects when not flattening
983
- }
984
- else if (!Array.isArray(val)) {
985
- // Include primitives (and null)
986
- paths.push(fullKey);
987
- }
988
- // Skip arrays entirely
989
- }
990
- return paths;
991
- };
992
- // Scan multiple items to discover all columns (handles fields absent/null in first item)
993
- const cols = collectPaths(first);
994
- const colSet = new Set(cols);
995
- const scanCount = Math.min(items.length, 50);
996
- for (let i = 1; i < scanCount; i++) {
997
- for (const p of collectPaths(items[i])) {
998
- if (!colSet.has(p)) {
999
- cols.push(p);
1000
- colSet.add(p);
1001
- }
1002
- }
1003
- }
1004
- return { cols: flatten ? cols : cols.slice(0, 8), items: items };
1005
- }
1006
- getValue(row, col) {
1007
- let val = row[col];
1008
- if (col.includes('.')) {
1009
- const parts = col.split('.');
1010
- val = parts.reduce((o, k) => (o && typeof o === 'object' ? o[k] : undefined), row);
1011
- }
1012
- return String(val ?? '');
1013
- }
1014
- printTable(data, fields) {
1015
- const { cols, items } = this.getColumns(data, fields);
1016
- if (items.length === 0) {
1017
- this.log('No results');
1018
- return;
1019
- }
1020
- // Calculate column widths
1021
- const widths = cols.map(c => c.length);
1022
- for (const item of items) {
1023
- cols.forEach((col, i) => {
1024
- const val = this.getValue(item, col).slice(0, 40);
1025
- widths[i] = Math.max(widths[i], val.length);
1026
- });
1027
- }
1028
- // Print header
1029
- const header = cols.map((c, i) => c.padEnd(widths[i])).join(' ');
1030
- this.log(header);
1031
- this.log(widths.map(w => '-'.repeat(w)).join(' '));
1032
- // Print rows
1033
- for (const item of items) {
1034
- const row = cols.map((col, i) => {
1035
- const val = this.getValue(item, col).slice(0, 40);
1036
- return val.padEnd(widths[i]);
1037
- }).join(' ');
1038
- this.log(row);
1039
- }
1040
- }
1041
- printCsv(data, fields) {
1042
- const { cols, items } = this.getColumns(data, fields, true); // flatten=true for CSV
1043
- if (items.length === 0) {
1044
- this.log('No results');
1045
- return;
1046
- }
1047
- const escape = (val) => {
1048
- if (val.includes(',') || val.includes('"') || val.includes('\n')) {
1049
- return '"' + val.replace(/"/g, '""') + '"';
1050
- }
1051
- return val;
1052
- };
1053
- // Print header
1054
- this.log(cols.map(escape).join(','));
1055
- // Print rows
1056
- for (const item of items) {
1057
- const row = cols.map(col => escape(this.getValue(item, col)));
1058
- this.log(row.join(','));
1059
- }
1060
- }
1061
- }