@aderis-erp/cli 1.1.2 → 1.1.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 (160) hide show
  1. package/README.md +1 -0
  2. package/dist/commands/access-groups.d.ts +11 -2
  3. package/dist/commands/access-groups.js +158 -24
  4. package/dist/commands/account-transaction-allocations.d.ts +11 -2
  5. package/dist/commands/account-transaction-allocations.js +157 -23
  6. package/dist/commands/account-transactions.d.ts +15 -2
  7. package/dist/commands/account-transactions.js +162 -24
  8. package/dist/commands/accounts.d.ts +11 -2
  9. package/dist/commands/accounts.js +158 -24
  10. package/dist/commands/agent-platform.d.ts +11 -3
  11. package/dist/commands/agent-platform.js +157 -32
  12. package/dist/commands/agent-runs.d.ts +11 -2
  13. package/dist/commands/agent-runs.js +157 -23
  14. package/dist/commands/analytics.d.ts +11 -2
  15. package/dist/commands/analytics.js +157 -23
  16. package/dist/commands/api-clients.d.ts +58 -0
  17. package/dist/commands/api-clients.js +1341 -0
  18. package/dist/commands/api-keys.d.ts +11 -2
  19. package/dist/commands/api-keys.js +157 -23
  20. package/dist/commands/async-jobs.d.ts +11 -2
  21. package/dist/commands/async-jobs.js +158 -24
  22. package/dist/commands/audit-log.d.ts +11 -2
  23. package/dist/commands/audit-log.js +157 -23
  24. package/dist/commands/bank-accounts.d.ts +11 -2
  25. package/dist/commands/bank-accounts.js +159 -25
  26. package/dist/commands/bank-integrations.d.ts +11 -2
  27. package/dist/commands/bank-integrations.js +158 -24
  28. package/dist/commands/business-partners.d.ts +11 -2
  29. package/dist/commands/business-partners.js +158 -24
  30. package/dist/commands/chat.d.ts +11 -2
  31. package/dist/commands/chat.js +158 -24
  32. package/dist/commands/credit-card-accounts.d.ts +15 -2
  33. package/dist/commands/credit-card-accounts.js +163 -24
  34. package/dist/commands/currencies.d.ts +56 -0
  35. package/dist/commands/currencies.js +1327 -0
  36. package/dist/commands/custody-accounts.d.ts +56 -0
  37. package/dist/commands/custody-accounts.js +1335 -0
  38. package/dist/commands/dashboards.d.ts +57 -0
  39. package/dist/commands/dashboards.js +1347 -0
  40. package/dist/commands/delivery-notes.d.ts +11 -2
  41. package/dist/commands/delivery-notes.js +158 -24
  42. package/dist/commands/{integration-identities.d.ts → document-checksums.d.ts} +12 -4
  43. package/dist/commands/{integration-identities.js → document-checksums.js} +162 -36
  44. package/dist/commands/dunning-configs.d.ts +11 -2
  45. package/dist/commands/dunning-configs.js +158 -24
  46. package/dist/commands/dunning-reminders.d.ts +11 -2
  47. package/dist/commands/dunning-reminders.js +157 -23
  48. package/dist/commands/dunning-runs.d.ts +11 -2
  49. package/dist/commands/dunning-runs.js +157 -23
  50. package/dist/commands/email-transactions.d.ts +11 -2
  51. package/dist/commands/email-transactions.js +157 -23
  52. package/dist/commands/employees.d.ts +13 -2
  53. package/dist/commands/employees.js +169 -24
  54. package/dist/commands/entity-configurations.d.ts +11 -2
  55. package/dist/commands/entity-configurations.js +157 -23
  56. package/dist/commands/event-mapping-rules.d.ts +56 -0
  57. package/dist/commands/event-mapping-rules.js +1324 -0
  58. package/dist/commands/event-processor-mappings.d.ts +11 -2
  59. package/dist/commands/event-processor-mappings.js +158 -24
  60. package/dist/commands/files.d.ts +11 -2
  61. package/dist/commands/files.js +158 -24
  62. package/dist/commands/financial-instrument-types.d.ts +56 -0
  63. package/dist/commands/financial-instrument-types.js +1335 -0
  64. package/dist/commands/financial-instruments.d.ts +56 -0
  65. package/dist/commands/financial-instruments.js +1335 -0
  66. package/dist/commands/health.d.ts +11 -2
  67. package/dist/commands/health.js +157 -23
  68. package/dist/commands/imports.d.ts +11 -2
  69. package/dist/commands/imports.js +157 -23
  70. package/dist/commands/inbox.d.ts +11 -2
  71. package/dist/commands/inbox.js +157 -23
  72. package/dist/commands/integrations.d.ts +11 -2
  73. package/dist/commands/integrations.js +157 -23
  74. package/dist/commands/item-categories.d.ts +11 -2
  75. package/dist/commands/item-categories.js +158 -24
  76. package/dist/commands/items.d.ts +15 -2
  77. package/dist/commands/items.js +165 -26
  78. package/dist/commands/journal-lines.d.ts +11 -2
  79. package/dist/commands/journal-lines.js +157 -23
  80. package/dist/commands/journals.d.ts +15 -2
  81. package/dist/commands/journals.js +163 -24
  82. package/dist/commands/{workflows.d.ts → kpis.d.ts} +12 -3
  83. package/dist/commands/kpis.js +1337 -0
  84. package/dist/commands/ledgers.d.ts +11 -2
  85. package/dist/commands/ledgers.js +159 -25
  86. package/dist/commands/my-account.d.ts +11 -2
  87. package/dist/commands/my-account.js +157 -23
  88. package/dist/commands/notifications.d.ts +56 -0
  89. package/dist/commands/notifications.js +1326 -0
  90. package/dist/commands/office-locations.d.ts +11 -2
  91. package/dist/commands/office-locations.js +158 -24
  92. package/dist/commands/payment-methods.d.ts +11 -2
  93. package/dist/commands/payment-methods.js +158 -24
  94. package/dist/commands/payment-runs.d.ts +11 -2
  95. package/dist/commands/payment-runs.js +158 -24
  96. package/dist/commands/payment-terms.d.ts +11 -2
  97. package/dist/commands/payment-terms.js +159 -25
  98. package/dist/commands/payments.d.ts +11 -2
  99. package/dist/commands/payments.js +158 -24
  100. package/dist/commands/payroll-runs.d.ts +11 -2
  101. package/dist/commands/payroll-runs.js +158 -24
  102. package/dist/commands/permissions.d.ts +11 -2
  103. package/dist/commands/permissions.js +157 -23
  104. package/dist/commands/price-lists.d.ts +15 -2
  105. package/dist/commands/price-lists.js +164 -24
  106. package/dist/commands/processor-mappings.d.ts +11 -2
  107. package/dist/commands/processor-mappings.js +158 -24
  108. package/dist/commands/processors.d.ts +11 -2
  109. package/dist/commands/processors.js +158 -24
  110. package/dist/commands/purchase-order-types.d.ts +11 -2
  111. package/dist/commands/purchase-order-types.js +158 -24
  112. package/dist/commands/purchase-orders.d.ts +11 -2
  113. package/dist/commands/purchase-orders.js +158 -24
  114. package/dist/commands/reports.d.ts +11 -2
  115. package/dist/commands/reports.js +157 -23
  116. package/dist/commands/roles.d.ts +11 -2
  117. package/dist/commands/roles.js +158 -24
  118. package/dist/commands/salary-types.d.ts +11 -2
  119. package/dist/commands/salary-types.js +158 -24
  120. package/dist/commands/sales-invoices.d.ts +11 -2
  121. package/dist/commands/sales-invoices.js +161 -24
  122. package/dist/commands/sales-orders.d.ts +11 -2
  123. package/dist/commands/sales-orders.js +159 -25
  124. package/dist/commands/saved-views.d.ts +11 -2
  125. package/dist/commands/saved-views.js +157 -23
  126. package/dist/commands/scheduled-processor-mappings.d.ts +11 -2
  127. package/dist/commands/scheduled-processor-mappings.js +158 -24
  128. package/dist/commands/schedules.d.ts +11 -2
  129. package/dist/commands/schedules.js +158 -24
  130. package/dist/commands/settings.d.ts +56 -0
  131. package/dist/commands/settings.js +1327 -0
  132. package/dist/commands/tags.d.ts +11 -2
  133. package/dist/commands/tags.js +158 -24
  134. package/dist/commands/tax-codes.d.ts +11 -2
  135. package/dist/commands/tax-codes.js +158 -24
  136. package/dist/commands/tax-matrix.d.ts +11 -2
  137. package/dist/commands/tax-matrix.js +158 -24
  138. package/dist/commands/templates.d.ts +11 -2
  139. package/dist/commands/templates.js +163 -24
  140. package/dist/commands/tenants.d.ts +11 -2
  141. package/dist/commands/tenants.js +158 -24
  142. package/dist/commands/tools.d.ts +11 -2
  143. package/dist/commands/tools.js +157 -23
  144. package/dist/commands/users.d.ts +11 -2
  145. package/dist/commands/users.js +158 -24
  146. package/dist/commands/vat-declarations.d.ts +11 -2
  147. package/dist/commands/vat-declarations.js +158 -24
  148. package/dist/commands/vendor-invoices.d.ts +11 -2
  149. package/dist/commands/vendor-invoices.js +162 -24
  150. package/dist/commands/webhooks.d.ts +11 -2
  151. package/dist/commands/webhooks.js +158 -24
  152. package/dist/commands/work-summary.d.ts +56 -0
  153. package/dist/commands/{workflows.js → work-summary.js} +164 -33
  154. package/dist/lib/api-client.d.ts +1 -0
  155. package/dist/lib/api-client.js +3 -0
  156. package/dist/lib/auth/index.js +5 -0
  157. package/dist/lib/production-guard.d.ts +42 -0
  158. package/dist/lib/production-guard.js +92 -0
  159. package/oclif.manifest.json +2358 -442
  160. package/package.json +1 -1
@@ -1,12 +1,15 @@
1
1
  import { Command, Args, Flags } from '@oclif/core';
2
2
  import { apiRequest, ApiError, isTextualMediaType, normalizeSortBy } from '../lib/api-client.js';
3
3
  import { getCurrentContext, getContext, getBaseUrls, hasCredentials, missingCredentialsMessage } from '../lib/config.js';
4
- // Add 'import' action if both create and update exist
5
- const HAS_IMPORT = false;
4
+ // 'upsert' loops create/update from the CLI, one request per record. It exists
5
+ // only where the API has no import endpoint of its own; those keep the name
6
+ // 'import' and are listed in SERVER_IMPORTS.
7
+ const HAS_UPSERT = false;
6
8
  const HAS_EXPORT = false;
7
9
  const HAS_CAMT053 = false;
8
- const NESTED_IMPORTS = [];
9
- const SUBCOMMANDS = [...["create-upload", "email-webhook", "document-types", "uploads-files-content", "list-processing-logs", "processing-logs"], ...(HAS_IMPORT ? ['import'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_IMPORTS.map(n => `import-${n}`)];
10
+ const SERVER_IMPORTS = [];
11
+ const NESTED_UPSERTS = [];
12
+ const SUBCOMMANDS = [...["create-upload", "email-webhook", "document-types", "uploads-files-content", "list-processing-logs", "processing-logs"], ...(HAS_UPSERT ? ['upsert'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_UPSERTS.map(n => `upsert-${n}`)];
10
13
  const ENDPOINTS = {
11
14
  'create-upload': { method: 'POST', path: '/v1/inbox/upload', summary: 'Upload document(s) to inbox for processing', pathParams: [], hasBody: false, isMultipart: true, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
12
15
  'email-webhook': { method: 'POST', path: '/v1/inbox/email-webhook/{secret}', summary: 'Email webhook for document ingestion (SendGrid inbound-parse)', pathParams: ['secret'], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
@@ -24,7 +27,7 @@ export default class Inbox extends Command {
24
27
  };
25
28
  static flags = {
26
29
  context: Flags.string({ char: 'c', aliases: ['config'], env: 'ADERIS_CONTEXT', description: 'Context to use for this command, overriding the current context (alias: --config)' }),
27
- output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
30
+ output: Flags.string({ char: 'o', description: 'Output format (default: table for upsert, json for other commands)', options: ['json', 'table', 'csv'] }),
28
31
  table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
29
32
  csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
30
33
  data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
@@ -45,11 +48,26 @@ export default class Inbox extends Command {
45
48
  };
46
49
  async run() {
47
50
  const { args, flags } = await this.parse(Inbox);
48
- // Handle import action specially
49
- if (args.action === 'import') {
50
- if (!HAS_IMPORT)
51
- this.error('Import not available for this resource');
52
- await this.runImport(flags);
51
+ // Bulk actions. 'import' is the API's own endpoint: one request, answered
52
+ // by a run that records what happened to every record. 'upsert' is the CLI
53
+ // looping create/update. A resource has one or the other, never both.
54
+ if (args.action === 'upsert') {
55
+ if (!HAS_UPSERT) {
56
+ this.error(SERVER_IMPORTS.includes('import')
57
+ ? 'This resource is imported by the API. Use: aderis inbox import --file data.json'
58
+ : 'Upsert needs both a create and an update endpoint, which this resource does not have');
59
+ }
60
+ await this.runUpsert(flags);
61
+ return;
62
+ }
63
+ if (args.action.startsWith('upsert-')) {
64
+ const suffix = args.action.replace('upsert-', '');
65
+ if (!NESTED_UPSERTS.includes(suffix)) {
66
+ this.error(SERVER_IMPORTS.includes('import-' + suffix)
67
+ ? `That resource is imported by the API. Use: aderis inbox import-${suffix} <id> --file data.json`
68
+ : `Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
69
+ }
70
+ await this.runNestedUpsert(suffix, args.id, flags);
53
71
  return;
54
72
  }
55
73
  // Handle export action specially
@@ -66,12 +84,17 @@ export default class Inbox extends Command {
66
84
  await this.runCamt053Import(flags);
67
85
  return;
68
86
  }
69
- // Handle nested resource imports (e.g., import-prices)
70
- if (args.action.startsWith('import-')) {
71
- const suffix = args.action.replace('import-', '');
72
- if (NESTED_IMPORTS.includes(suffix)) {
73
- await this.runNestedImport(suffix, args.id, flags);
74
- return;
87
+ if (SERVER_IMPORTS.includes(args.action)) {
88
+ await this.runServerImport(args.action, args.id, flags);
89
+ return;
90
+ }
91
+ // 'import' used to name the CLI's create/update loop on every resource. It
92
+ // now names the API endpoint, which most resources do not have.
93
+ if (args.action === 'import' || args.action.startsWith('import-')) {
94
+ const suffix = args.action === 'import' ? '' : '-' + args.action.replace('import-', '');
95
+ const loops = args.action === 'import' ? HAS_UPSERT : NESTED_UPSERTS.includes(args.action.replace('import-', ''));
96
+ if (loops) {
97
+ this.error(`This resource has no import endpoint. Use: aderis inbox upsert${suffix}${suffix ? ' <id>' : ''} --file data.json`);
75
98
  }
76
99
  }
77
100
  const endpoint = ENDPOINTS[args.action];
@@ -386,7 +409,7 @@ export default class Inbox extends Command {
386
409
  throw error;
387
410
  }
388
411
  }
389
- async runImport(flags) {
412
+ async runUpsert(flags) {
390
413
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
391
414
  if (!context)
392
415
  this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
@@ -450,12 +473,12 @@ export default class Inbox extends Command {
450
473
  items = [item];
451
474
  }
452
475
  else {
453
- this.error('Import requires --file, --data, or --set flags');
476
+ this.error('Upsert requires --file, --data, or --set flags');
454
477
  }
455
478
  const createEndpoint = ENDPOINTS['create'];
456
479
  const updateEndpoint = ENDPOINTS['update'];
457
480
  if (!createEndpoint || !updateEndpoint) {
458
- this.error('Import requires both create and update endpoints');
481
+ this.error('Upsert requires both create and update endpoints');
459
482
  }
460
483
  // Helper to extract identifier from item (id, code, or xxxCode)
461
484
  const getItemIdentifier = (item) => {
@@ -598,6 +621,117 @@ export default class Inbox extends Command {
598
621
  this.log('');
599
622
  this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
600
623
  }
624
+ /**
625
+ * The API's own import: the whole array goes up in one request and comes
626
+ * back as an import run, which records what happened to every record. A bad
627
+ * record lands in errorLog and the rest are still applied, and the run stays
628
+ * readable afterwards with: aderis imports get <id>.
629
+ */
630
+ async runServerImport(action, parentId, flags) {
631
+ const endpoint = ENDPOINTS[action];
632
+ if (!endpoint)
633
+ this.error(`Unknown action: ${action}. Available: ${SUBCOMMANDS.join(', ')}`);
634
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
635
+ if (!context)
636
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
637
+ if (!hasCredentials(context))
638
+ this.error(missingCredentialsMessage(context));
639
+ let apiPath = endpoint.path;
640
+ if (endpoint.pathParams.length > 0) {
641
+ if (!parentId)
642
+ this.error(`Missing required argument: id. Usage: aderis inbox ${action} <parent-id> --file data.json`);
643
+ apiPath = apiPath.replace(`{${endpoint.pathParams[0]}}`, parentId);
644
+ }
645
+ // The endpoint takes an array. A single object is wrapped, so importing
646
+ // one record reads the same as importing many.
647
+ let records = [];
648
+ if (flags.file) {
649
+ const fsModule = await import('node:fs');
650
+ try {
651
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
652
+ records = Array.isArray(content) ? content : [content];
653
+ }
654
+ catch {
655
+ this.error(`Failed to read file: ${flags.file}`);
656
+ }
657
+ }
658
+ else if (flags.data) {
659
+ try {
660
+ const content = JSON.parse(flags.data);
661
+ records = Array.isArray(content) ? content : [content];
662
+ }
663
+ catch {
664
+ this.error('Invalid JSON in --data');
665
+ }
666
+ }
667
+ else {
668
+ this.error('Import requires --file or --data holding a JSON array of records');
669
+ }
670
+ if (records.length === 0)
671
+ this.error('Nothing to import: the input is an empty array');
672
+ const params = { format: 'json' };
673
+ if (flags.mode)
674
+ params.mode = flags.mode;
675
+ if (flags.reference)
676
+ params.reference = flags.reference;
677
+ if (flags.async)
678
+ params.async = true;
679
+ const headers = {};
680
+ if (flags['idempotency-key'])
681
+ headers['Idempotency-Key'] = flags['idempotency-key'];
682
+ if (flags['show-http-request']) {
683
+ const baseUrls = getBaseUrls(context.environment);
684
+ const queryString = '?' + Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&');
685
+ process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
686
+ process.stderr.write(`Body: [${records.length} record${records.length === 1 ? '' : 's'}]\n\n`);
687
+ }
688
+ try {
689
+ const response = await apiRequest(endpoint.method, apiPath, {
690
+ contextName: flags.context,
691
+ data: records,
692
+ headers,
693
+ params,
694
+ });
695
+ this.printImportRun(response.data, flags);
696
+ }
697
+ catch (error) {
698
+ if (error instanceof ApiError) {
699
+ this.error(`API Error (${error.status}): ${error.message}`);
700
+ }
701
+ throw error;
702
+ }
703
+ }
704
+ /** Renders an import run: its counts, then whatever the server refused. */
705
+ printImportRun(run, flags) {
706
+ if (flags.output === 'json') {
707
+ this.log(JSON.stringify(run, null, 2));
708
+ return;
709
+ }
710
+ const record = (run ?? {});
711
+ const count = (key) => (typeof record[key] === 'number' ? record[key] : 0);
712
+ const id = record.id ? String(record.id) : '';
713
+ this.log(`Import ${id} - ${String(record.status ?? 'UNKNOWN')}${record.async ? ' (background)' : ''}`);
714
+ this.log(` ${count('inputSize')} submitted, ${count('createdCount')} created, ${count('updatedCount')} updated, ${count('unchangedCount')} unchanged`);
715
+ if (count('errorCount') > 0)
716
+ this.log(` ${count('errorCount')} not applied: ${count('refusedCount')} refused, ${count('failedCount')} failed`);
717
+ if (count('warningCount') > 0)
718
+ this.log(` ${count('warningCount')} applied with a warning`);
719
+ // errorLog is keyed by the record's identifier, then by field name.
720
+ const errorLog = record.errorLog;
721
+ if (errorLog && Object.keys(errorLog).length > 0) {
722
+ this.log('');
723
+ for (const [key, fields] of Object.entries(errorLog)) {
724
+ for (const [field, messages] of Object.entries(fields ?? {})) {
725
+ for (const message of messages ?? [])
726
+ this.log(` ${key} ${field}: ${message}`);
727
+ }
728
+ }
729
+ }
730
+ if (record.async && id) {
731
+ this.log('');
732
+ this.log(`Follow it with: aderis imports get ${id}`);
733
+ }
734
+ }
601
735
  async runExport(flags) {
602
736
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
603
737
  if (!context)
@@ -776,9 +910,9 @@ export default class Inbox extends Command {
776
910
  throw error;
777
911
  }
778
912
  }
779
- async runNestedImport(suffix, parentId, flags) {
913
+ async runNestedUpsert(suffix, parentId, flags) {
780
914
  if (!parentId) {
781
- this.error(`Missing required argument: id. Usage: aderis inbox import-${suffix} <parent-id> --file data.json`);
915
+ this.error(`Missing required argument: id. Usage: aderis inbox upsert-${suffix} <parent-id> --file data.json`);
782
916
  }
783
917
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
784
918
  if (!context)
@@ -843,12 +977,12 @@ export default class Inbox extends Command {
843
977
  items = [item];
844
978
  }
845
979
  else {
846
- this.error(`Import requires --file, --data, or --set flags`);
980
+ this.error('Upsert requires --file, --data, or --set flags');
847
981
  }
848
982
  const createEndpoint = ENDPOINTS[`create-${suffix}`];
849
983
  const updateEndpoint = ENDPOINTS[`update-${suffix}`];
850
984
  if (!createEndpoint || !updateEndpoint) {
851
- this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
985
+ this.error(`Upsert requires both create-${suffix} and update-${suffix} endpoints`);
852
986
  }
853
987
  // Build the base path with parent ID (first path param)
854
988
  const firstParam = createEndpoint.pathParams[0];
@@ -28,10 +28,19 @@ export default class Integrations extends Command {
28
28
  'show-http-request': import("@oclif/core/interfaces").BooleanFlag<boolean>;
29
29
  };
30
30
  run(): Promise<void>;
31
- private runImport;
31
+ private runUpsert;
32
+ /**
33
+ * The API's own import: the whole array goes up in one request and comes
34
+ * back as an import run, which records what happened to every record. A bad
35
+ * record lands in errorLog and the rest are still applied, and the run stays
36
+ * readable afterwards with: aderis imports get <id>.
37
+ */
38
+ private runServerImport;
39
+ /** Renders an import run: its counts, then whatever the server refused. */
40
+ private printImportRun;
32
41
  private runExport;
33
42
  private runCamt053Import;
34
- private runNestedImport;
43
+ private runNestedUpsert;
35
44
  private parseFilterValue;
36
45
  /** The page line under a table: which page, how many, and any sums the API returned. */
37
46
  private printPageSummary;
@@ -1,12 +1,15 @@
1
1
  import { Command, Args, Flags } from '@oclif/core';
2
2
  import { apiRequest, ApiError, isTextualMediaType, normalizeSortBy } from '../lib/api-client.js';
3
3
  import { getCurrentContext, getContext, getBaseUrls, hasCredentials, missingCredentialsMessage } from '../lib/config.js';
4
- // Add 'import' action if both create and update exist
5
- const HAS_IMPORT = false;
4
+ // 'upsert' loops create/update from the CLI, one request per record. It exists
5
+ // only where the API has no import endpoint of its own; those keep the name
6
+ // 'import' and are listed in SERVER_IMPORTS.
7
+ const HAS_UPSERT = false;
6
8
  const HAS_EXPORT = false;
7
9
  const HAS_CAMT053 = false;
8
- const NESTED_IMPORTS = [];
9
- const SUBCOMMANDS = [...["get", "update", "delete"], ...(HAS_IMPORT ? ['import'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_IMPORTS.map(n => `import-${n}`)];
10
+ const SERVER_IMPORTS = [];
11
+ const NESTED_UPSERTS = [];
12
+ const SUBCOMMANDS = [...["get", "update", "delete"], ...(HAS_UPSERT ? ['upsert'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_UPSERTS.map(n => `upsert-${n}`)];
10
13
  const ENDPOINTS = {
11
14
  'get': { method: 'GET', path: '/v1/integrations/{integrationName}/{configKey}', summary: 'Get integration configuration', pathParams: ['integrationName', 'configKey'], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
12
15
  'update': { method: 'PUT', path: '/v1/integrations/{integrationName}/{configKey}', summary: 'Create or update integration configuration', pathParams: ['integrationName', 'configKey'], hasBody: true, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
@@ -24,7 +27,7 @@ export default class Integrations extends Command {
24
27
  };
25
28
  static flags = {
26
29
  context: Flags.string({ char: 'c', aliases: ['config'], env: 'ADERIS_CONTEXT', description: 'Context to use for this command, overriding the current context (alias: --config)' }),
27
- output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
30
+ output: Flags.string({ char: 'o', description: 'Output format (default: table for upsert, json for other commands)', options: ['json', 'table', 'csv'] }),
28
31
  table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
29
32
  csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
30
33
  data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
@@ -45,11 +48,26 @@ export default class Integrations extends Command {
45
48
  };
46
49
  async run() {
47
50
  const { args, flags } = await this.parse(Integrations);
48
- // Handle import action specially
49
- if (args.action === 'import') {
50
- if (!HAS_IMPORT)
51
- this.error('Import not available for this resource');
52
- await this.runImport(flags);
51
+ // Bulk actions. 'import' is the API's own endpoint: one request, answered
52
+ // by a run that records what happened to every record. 'upsert' is the CLI
53
+ // looping create/update. A resource has one or the other, never both.
54
+ if (args.action === 'upsert') {
55
+ if (!HAS_UPSERT) {
56
+ this.error(SERVER_IMPORTS.includes('import')
57
+ ? 'This resource is imported by the API. Use: aderis integrations import --file data.json'
58
+ : 'Upsert needs both a create and an update endpoint, which this resource does not have');
59
+ }
60
+ await this.runUpsert(flags);
61
+ return;
62
+ }
63
+ if (args.action.startsWith('upsert-')) {
64
+ const suffix = args.action.replace('upsert-', '');
65
+ if (!NESTED_UPSERTS.includes(suffix)) {
66
+ this.error(SERVER_IMPORTS.includes('import-' + suffix)
67
+ ? `That resource is imported by the API. Use: aderis integrations import-${suffix} <id> --file data.json`
68
+ : `Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
69
+ }
70
+ await this.runNestedUpsert(suffix, args.id, flags);
53
71
  return;
54
72
  }
55
73
  // Handle export action specially
@@ -66,12 +84,17 @@ export default class Integrations extends Command {
66
84
  await this.runCamt053Import(flags);
67
85
  return;
68
86
  }
69
- // Handle nested resource imports (e.g., import-prices)
70
- if (args.action.startsWith('import-')) {
71
- const suffix = args.action.replace('import-', '');
72
- if (NESTED_IMPORTS.includes(suffix)) {
73
- await this.runNestedImport(suffix, args.id, flags);
74
- return;
87
+ if (SERVER_IMPORTS.includes(args.action)) {
88
+ await this.runServerImport(args.action, args.id, flags);
89
+ return;
90
+ }
91
+ // 'import' used to name the CLI's create/update loop on every resource. It
92
+ // now names the API endpoint, which most resources do not have.
93
+ if (args.action === 'import' || args.action.startsWith('import-')) {
94
+ const suffix = args.action === 'import' ? '' : '-' + args.action.replace('import-', '');
95
+ const loops = args.action === 'import' ? HAS_UPSERT : NESTED_UPSERTS.includes(args.action.replace('import-', ''));
96
+ if (loops) {
97
+ this.error(`This resource has no import endpoint. Use: aderis integrations upsert${suffix}${suffix ? ' <id>' : ''} --file data.json`);
75
98
  }
76
99
  }
77
100
  const endpoint = ENDPOINTS[args.action];
@@ -386,7 +409,7 @@ export default class Integrations extends Command {
386
409
  throw error;
387
410
  }
388
411
  }
389
- async runImport(flags) {
412
+ async runUpsert(flags) {
390
413
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
391
414
  if (!context)
392
415
  this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
@@ -450,12 +473,12 @@ export default class Integrations extends Command {
450
473
  items = [item];
451
474
  }
452
475
  else {
453
- this.error('Import requires --file, --data, or --set flags');
476
+ this.error('Upsert requires --file, --data, or --set flags');
454
477
  }
455
478
  const createEndpoint = ENDPOINTS['create'];
456
479
  const updateEndpoint = ENDPOINTS['update'];
457
480
  if (!createEndpoint || !updateEndpoint) {
458
- this.error('Import requires both create and update endpoints');
481
+ this.error('Upsert requires both create and update endpoints');
459
482
  }
460
483
  // Helper to extract identifier from item (id, code, or xxxCode)
461
484
  const getItemIdentifier = (item) => {
@@ -598,6 +621,117 @@ export default class Integrations extends Command {
598
621
  this.log('');
599
622
  this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
600
623
  }
624
+ /**
625
+ * The API's own import: the whole array goes up in one request and comes
626
+ * back as an import run, which records what happened to every record. A bad
627
+ * record lands in errorLog and the rest are still applied, and the run stays
628
+ * readable afterwards with: aderis imports get <id>.
629
+ */
630
+ async runServerImport(action, parentId, flags) {
631
+ const endpoint = ENDPOINTS[action];
632
+ if (!endpoint)
633
+ this.error(`Unknown action: ${action}. Available: ${SUBCOMMANDS.join(', ')}`);
634
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
635
+ if (!context)
636
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
637
+ if (!hasCredentials(context))
638
+ this.error(missingCredentialsMessage(context));
639
+ let apiPath = endpoint.path;
640
+ if (endpoint.pathParams.length > 0) {
641
+ if (!parentId)
642
+ this.error(`Missing required argument: id. Usage: aderis integrations ${action} <parent-id> --file data.json`);
643
+ apiPath = apiPath.replace(`{${endpoint.pathParams[0]}}`, parentId);
644
+ }
645
+ // The endpoint takes an array. A single object is wrapped, so importing
646
+ // one record reads the same as importing many.
647
+ let records = [];
648
+ if (flags.file) {
649
+ const fsModule = await import('node:fs');
650
+ try {
651
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
652
+ records = Array.isArray(content) ? content : [content];
653
+ }
654
+ catch {
655
+ this.error(`Failed to read file: ${flags.file}`);
656
+ }
657
+ }
658
+ else if (flags.data) {
659
+ try {
660
+ const content = JSON.parse(flags.data);
661
+ records = Array.isArray(content) ? content : [content];
662
+ }
663
+ catch {
664
+ this.error('Invalid JSON in --data');
665
+ }
666
+ }
667
+ else {
668
+ this.error('Import requires --file or --data holding a JSON array of records');
669
+ }
670
+ if (records.length === 0)
671
+ this.error('Nothing to import: the input is an empty array');
672
+ const params = { format: 'json' };
673
+ if (flags.mode)
674
+ params.mode = flags.mode;
675
+ if (flags.reference)
676
+ params.reference = flags.reference;
677
+ if (flags.async)
678
+ params.async = true;
679
+ const headers = {};
680
+ if (flags['idempotency-key'])
681
+ headers['Idempotency-Key'] = flags['idempotency-key'];
682
+ if (flags['show-http-request']) {
683
+ const baseUrls = getBaseUrls(context.environment);
684
+ const queryString = '?' + Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&');
685
+ process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
686
+ process.stderr.write(`Body: [${records.length} record${records.length === 1 ? '' : 's'}]\n\n`);
687
+ }
688
+ try {
689
+ const response = await apiRequest(endpoint.method, apiPath, {
690
+ contextName: flags.context,
691
+ data: records,
692
+ headers,
693
+ params,
694
+ });
695
+ this.printImportRun(response.data, flags);
696
+ }
697
+ catch (error) {
698
+ if (error instanceof ApiError) {
699
+ this.error(`API Error (${error.status}): ${error.message}`);
700
+ }
701
+ throw error;
702
+ }
703
+ }
704
+ /** Renders an import run: its counts, then whatever the server refused. */
705
+ printImportRun(run, flags) {
706
+ if (flags.output === 'json') {
707
+ this.log(JSON.stringify(run, null, 2));
708
+ return;
709
+ }
710
+ const record = (run ?? {});
711
+ const count = (key) => (typeof record[key] === 'number' ? record[key] : 0);
712
+ const id = record.id ? String(record.id) : '';
713
+ this.log(`Import ${id} - ${String(record.status ?? 'UNKNOWN')}${record.async ? ' (background)' : ''}`);
714
+ this.log(` ${count('inputSize')} submitted, ${count('createdCount')} created, ${count('updatedCount')} updated, ${count('unchangedCount')} unchanged`);
715
+ if (count('errorCount') > 0)
716
+ this.log(` ${count('errorCount')} not applied: ${count('refusedCount')} refused, ${count('failedCount')} failed`);
717
+ if (count('warningCount') > 0)
718
+ this.log(` ${count('warningCount')} applied with a warning`);
719
+ // errorLog is keyed by the record's identifier, then by field name.
720
+ const errorLog = record.errorLog;
721
+ if (errorLog && Object.keys(errorLog).length > 0) {
722
+ this.log('');
723
+ for (const [key, fields] of Object.entries(errorLog)) {
724
+ for (const [field, messages] of Object.entries(fields ?? {})) {
725
+ for (const message of messages ?? [])
726
+ this.log(` ${key} ${field}: ${message}`);
727
+ }
728
+ }
729
+ }
730
+ if (record.async && id) {
731
+ this.log('');
732
+ this.log(`Follow it with: aderis imports get ${id}`);
733
+ }
734
+ }
601
735
  async runExport(flags) {
602
736
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
603
737
  if (!context)
@@ -776,9 +910,9 @@ export default class Integrations extends Command {
776
910
  throw error;
777
911
  }
778
912
  }
779
- async runNestedImport(suffix, parentId, flags) {
913
+ async runNestedUpsert(suffix, parentId, flags) {
780
914
  if (!parentId) {
781
- this.error(`Missing required argument: id. Usage: aderis integrations import-${suffix} <parent-id> --file data.json`);
915
+ this.error(`Missing required argument: id. Usage: aderis integrations upsert-${suffix} <parent-id> --file data.json`);
782
916
  }
783
917
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
784
918
  if (!context)
@@ -843,12 +977,12 @@ export default class Integrations extends Command {
843
977
  items = [item];
844
978
  }
845
979
  else {
846
- this.error(`Import requires --file, --data, or --set flags`);
980
+ this.error('Upsert requires --file, --data, or --set flags');
847
981
  }
848
982
  const createEndpoint = ENDPOINTS[`create-${suffix}`];
849
983
  const updateEndpoint = ENDPOINTS[`update-${suffix}`];
850
984
  if (!createEndpoint || !updateEndpoint) {
851
- this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
985
+ this.error(`Upsert requires both create-${suffix} and update-${suffix} endpoints`);
852
986
  }
853
987
  // Build the base path with parent ID (first path param)
854
988
  const firstParam = createEndpoint.pathParams[0];
@@ -27,10 +27,19 @@ export default class ItemCategories extends Command {
27
27
  'show-http-request': import("@oclif/core/interfaces").BooleanFlag<boolean>;
28
28
  };
29
29
  run(): Promise<void>;
30
- private runImport;
30
+ private runUpsert;
31
+ /**
32
+ * The API's own import: the whole array goes up in one request and comes
33
+ * back as an import run, which records what happened to every record. A bad
34
+ * record lands in errorLog and the rest are still applied, and the run stays
35
+ * readable afterwards with: aderis imports get <id>.
36
+ */
37
+ private runServerImport;
38
+ /** Renders an import run: its counts, then whatever the server refused. */
39
+ private printImportRun;
31
40
  private runExport;
32
41
  private runCamt053Import;
33
- private runNestedImport;
42
+ private runNestedUpsert;
34
43
  private parseFilterValue;
35
44
  /** The page line under a table: which page, how many, and any sums the API returned. */
36
45
  private printPageSummary;