@aderis-erp/cli 1.0.3 → 1.0.4

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