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