@aderis-erp/cli 1.1.2 → 1.1.3

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 (138) hide show
  1. package/dist/commands/access-groups.d.ts +11 -2
  2. package/dist/commands/access-groups.js +158 -24
  3. package/dist/commands/account-transaction-allocations.d.ts +11 -2
  4. package/dist/commands/account-transaction-allocations.js +157 -23
  5. package/dist/commands/account-transactions.d.ts +15 -2
  6. package/dist/commands/account-transactions.js +162 -24
  7. package/dist/commands/accounts.d.ts +11 -2
  8. package/dist/commands/accounts.js +158 -24
  9. package/dist/commands/agent-platform.d.ts +11 -3
  10. package/dist/commands/agent-platform.js +157 -32
  11. package/dist/commands/agent-runs.d.ts +11 -2
  12. package/dist/commands/agent-runs.js +157 -23
  13. package/dist/commands/analytics.d.ts +11 -2
  14. package/dist/commands/analytics.js +157 -23
  15. package/dist/commands/api-keys.d.ts +11 -2
  16. package/dist/commands/api-keys.js +157 -23
  17. package/dist/commands/async-jobs.d.ts +11 -2
  18. package/dist/commands/async-jobs.js +158 -24
  19. package/dist/commands/audit-log.d.ts +11 -2
  20. package/dist/commands/audit-log.js +157 -23
  21. package/dist/commands/bank-accounts.d.ts +11 -2
  22. package/dist/commands/bank-accounts.js +158 -24
  23. package/dist/commands/bank-integrations.d.ts +11 -2
  24. package/dist/commands/bank-integrations.js +158 -24
  25. package/dist/commands/business-partners.d.ts +11 -2
  26. package/dist/commands/business-partners.js +158 -24
  27. package/dist/commands/chat.d.ts +11 -2
  28. package/dist/commands/chat.js +158 -24
  29. package/dist/commands/credit-card-accounts.d.ts +11 -2
  30. package/dist/commands/credit-card-accounts.js +158 -24
  31. package/dist/commands/delivery-notes.d.ts +11 -2
  32. package/dist/commands/delivery-notes.js +158 -24
  33. package/dist/commands/dunning-configs.d.ts +11 -2
  34. package/dist/commands/dunning-configs.js +158 -24
  35. package/dist/commands/dunning-reminders.d.ts +11 -2
  36. package/dist/commands/dunning-reminders.js +157 -23
  37. package/dist/commands/dunning-runs.d.ts +11 -2
  38. package/dist/commands/dunning-runs.js +157 -23
  39. package/dist/commands/email-transactions.d.ts +11 -2
  40. package/dist/commands/email-transactions.js +157 -23
  41. package/dist/commands/employees.d.ts +13 -2
  42. package/dist/commands/employees.js +169 -24
  43. package/dist/commands/entity-configurations.d.ts +11 -2
  44. package/dist/commands/entity-configurations.js +157 -23
  45. package/dist/commands/event-mapping-rules.d.ts +56 -0
  46. package/dist/commands/event-mapping-rules.js +1324 -0
  47. package/dist/commands/event-processor-mappings.d.ts +11 -2
  48. package/dist/commands/event-processor-mappings.js +158 -24
  49. package/dist/commands/files.d.ts +11 -2
  50. package/dist/commands/files.js +158 -24
  51. package/dist/commands/health.d.ts +11 -2
  52. package/dist/commands/health.js +157 -23
  53. package/dist/commands/imports.d.ts +11 -2
  54. package/dist/commands/imports.js +157 -23
  55. package/dist/commands/inbox.d.ts +11 -2
  56. package/dist/commands/inbox.js +157 -23
  57. package/dist/commands/integration-identities.d.ts +11 -2
  58. package/dist/commands/integration-identities.js +157 -23
  59. package/dist/commands/integrations.d.ts +11 -2
  60. package/dist/commands/integrations.js +157 -23
  61. package/dist/commands/item-categories.d.ts +11 -2
  62. package/dist/commands/item-categories.js +158 -24
  63. package/dist/commands/items.d.ts +15 -2
  64. package/dist/commands/items.js +163 -24
  65. package/dist/commands/journal-lines.d.ts +11 -2
  66. package/dist/commands/journal-lines.js +157 -23
  67. package/dist/commands/journals.d.ts +15 -2
  68. package/dist/commands/journals.js +163 -24
  69. package/dist/commands/ledgers.d.ts +11 -2
  70. package/dist/commands/ledgers.js +158 -24
  71. package/dist/commands/my-account.d.ts +11 -2
  72. package/dist/commands/my-account.js +157 -23
  73. package/dist/commands/office-locations.d.ts +11 -2
  74. package/dist/commands/office-locations.js +158 -24
  75. package/dist/commands/payment-methods.d.ts +11 -2
  76. package/dist/commands/payment-methods.js +158 -24
  77. package/dist/commands/payment-runs.d.ts +11 -2
  78. package/dist/commands/payment-runs.js +158 -24
  79. package/dist/commands/payment-terms.d.ts +11 -2
  80. package/dist/commands/payment-terms.js +159 -25
  81. package/dist/commands/payments.d.ts +11 -2
  82. package/dist/commands/payments.js +158 -24
  83. package/dist/commands/payroll-runs.d.ts +11 -2
  84. package/dist/commands/payroll-runs.js +158 -24
  85. package/dist/commands/permissions.d.ts +11 -2
  86. package/dist/commands/permissions.js +157 -23
  87. package/dist/commands/price-lists.d.ts +15 -2
  88. package/dist/commands/price-lists.js +164 -24
  89. package/dist/commands/processor-mappings.d.ts +11 -2
  90. package/dist/commands/processor-mappings.js +158 -24
  91. package/dist/commands/processors.d.ts +11 -2
  92. package/dist/commands/processors.js +158 -24
  93. package/dist/commands/purchase-order-types.d.ts +11 -2
  94. package/dist/commands/purchase-order-types.js +158 -24
  95. package/dist/commands/purchase-orders.d.ts +11 -2
  96. package/dist/commands/purchase-orders.js +158 -24
  97. package/dist/commands/reports.d.ts +11 -2
  98. package/dist/commands/reports.js +157 -23
  99. package/dist/commands/roles.d.ts +11 -2
  100. package/dist/commands/roles.js +158 -24
  101. package/dist/commands/salary-types.d.ts +11 -2
  102. package/dist/commands/salary-types.js +158 -24
  103. package/dist/commands/sales-invoices.d.ts +11 -2
  104. package/dist/commands/sales-invoices.js +161 -24
  105. package/dist/commands/sales-orders.d.ts +11 -2
  106. package/dist/commands/sales-orders.js +158 -24
  107. package/dist/commands/saved-views.d.ts +11 -2
  108. package/dist/commands/saved-views.js +157 -23
  109. package/dist/commands/scheduled-processor-mappings.d.ts +11 -2
  110. package/dist/commands/scheduled-processor-mappings.js +158 -24
  111. package/dist/commands/schedules.d.ts +11 -2
  112. package/dist/commands/schedules.js +158 -24
  113. package/dist/commands/tags.d.ts +11 -2
  114. package/dist/commands/tags.js +158 -24
  115. package/dist/commands/tax-codes.d.ts +11 -2
  116. package/dist/commands/tax-codes.js +158 -24
  117. package/dist/commands/tax-matrix.d.ts +11 -2
  118. package/dist/commands/tax-matrix.js +158 -24
  119. package/dist/commands/templates.d.ts +11 -2
  120. package/dist/commands/templates.js +162 -24
  121. package/dist/commands/tenants.d.ts +11 -2
  122. package/dist/commands/tenants.js +158 -24
  123. package/dist/commands/tools.d.ts +11 -2
  124. package/dist/commands/tools.js +157 -23
  125. package/dist/commands/users.d.ts +11 -2
  126. package/dist/commands/users.js +158 -24
  127. package/dist/commands/vat-declarations.d.ts +11 -2
  128. package/dist/commands/vat-declarations.js +158 -24
  129. package/dist/commands/vendor-invoices.d.ts +11 -2
  130. package/dist/commands/vendor-invoices.js +161 -24
  131. package/dist/commands/webhooks.d.ts +11 -2
  132. package/dist/commands/webhooks.js +158 -24
  133. package/dist/commands/workflows.d.ts +11 -2
  134. package/dist/commands/workflows.js +157 -23
  135. package/dist/lib/api-client.d.ts +1 -0
  136. package/dist/lib/api-client.js +3 -0
  137. package/oclif.manifest.json +466 -162
  138. 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 = true;
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 = true;
6
8
  const HAS_EXPORT = true;
7
9
  const HAS_CAMT053 = false;
8
- const NESTED_IMPORTS = ["ledger-mappings", "notes", "cards"];
9
- const SUBCOMMANDS = [...["list", "create", "get", "update", "delete", "list-ledger-mappings", "create-ledger-mappings", "get-ledger-mappings", "update-ledger-mappings", "delete-ledger-mappings", "list-notes", "create-notes", "get-notes", "update-notes", "delete-notes", "list-cards", "create-cards", "get-cards", "update-cards", "delete-cards"], ...(HAS_IMPORT ? ['import'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_IMPORTS.map(n => `import-${n}`)];
10
+ const SERVER_IMPORTS = [];
11
+ const NESTED_UPSERTS = ["ledger-mappings", "notes", "cards"];
12
+ const SUBCOMMANDS = [...["list", "create", "get", "update", "delete", "list-ledger-mappings", "create-ledger-mappings", "get-ledger-mappings", "update-ledger-mappings", "delete-ledger-mappings", "list-notes", "create-notes", "get-notes", "update-notes", "delete-notes", "list-cards", "create-cards", "get-cards", "update-cards", "delete-cards"], ...(HAS_UPSERT ? ['upsert'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_UPSERTS.map(n => `upsert-${n}`)];
10
13
  const ENDPOINTS = {
11
14
  'list': { method: 'GET', path: '/v1/credit-card-accounts', summary: 'Get all credit card accounts with pagination', pathParams: [], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
12
15
  'create': { method: 'POST', path: '/v1/credit-card-accounts', summary: 'Create a new credit card account (with optional notes)', pathParams: [], hasBody: true, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: ['notes'] },
@@ -36,7 +39,7 @@ export default class CreditCardAccounts extends Command {
36
39
  '<%= config.bin %> credit-card-accounts get <id>',
37
40
  '<%= config.bin %> credit-card-accounts create --data \'{...}\'',
38
41
  '<%= config.bin %> credit-card-accounts update <id> --set field=value',
39
- '<%= config.bin %> credit-card-accounts import --file data.json',
42
+ '<%= config.bin %> credit-card-accounts upsert --file data.json',
40
43
  '<%= config.bin %> credit-card-accounts export --csv > credit-card-accounts.csv',
41
44
  ];
42
45
  static args = {
@@ -45,7 +48,7 @@ export default class CreditCardAccounts extends Command {
45
48
  };
46
49
  static flags = {
47
50
  context: Flags.string({ char: 'c', aliases: ['config'], env: 'ADERIS_CONTEXT', description: 'Context to use for this command, overriding the current context (alias: --config)' }),
48
- output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
51
+ output: Flags.string({ char: 'o', description: 'Output format (default: table for upsert, json for other commands)', options: ['json', 'table', 'csv'] }),
49
52
  table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
50
53
  csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
51
54
  data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
@@ -68,11 +71,26 @@ export default class CreditCardAccounts extends Command {
68
71
  };
69
72
  async run() {
70
73
  const { args, flags } = await this.parse(CreditCardAccounts);
71
- // Handle import action specially
72
- if (args.action === 'import') {
73
- if (!HAS_IMPORT)
74
- this.error('Import not available for this resource');
75
- await this.runImport(flags);
74
+ // Bulk actions. 'import' is the API's own endpoint: one request, answered
75
+ // by a run that records what happened to every record. 'upsert' is the CLI
76
+ // looping create/update. A resource has one or the other, never both.
77
+ if (args.action === 'upsert') {
78
+ if (!HAS_UPSERT) {
79
+ this.error(SERVER_IMPORTS.includes('import')
80
+ ? 'This resource is imported by the API. Use: aderis credit-card-accounts import --file data.json'
81
+ : 'Upsert needs both a create and an update endpoint, which this resource does not have');
82
+ }
83
+ await this.runUpsert(flags);
84
+ return;
85
+ }
86
+ if (args.action.startsWith('upsert-')) {
87
+ const suffix = args.action.replace('upsert-', '');
88
+ if (!NESTED_UPSERTS.includes(suffix)) {
89
+ this.error(SERVER_IMPORTS.includes('import-' + suffix)
90
+ ? `That resource is imported by the API. Use: aderis credit-card-accounts import-${suffix} <id> --file data.json`
91
+ : `Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
92
+ }
93
+ await this.runNestedUpsert(suffix, args.id, flags);
76
94
  return;
77
95
  }
78
96
  // Handle export action specially
@@ -89,12 +107,17 @@ export default class CreditCardAccounts extends Command {
89
107
  await this.runCamt053Import(flags);
90
108
  return;
91
109
  }
92
- // Handle nested resource imports (e.g., import-prices)
93
- if (args.action.startsWith('import-')) {
94
- const suffix = args.action.replace('import-', '');
95
- if (NESTED_IMPORTS.includes(suffix)) {
96
- await this.runNestedImport(suffix, args.id, flags);
97
- return;
110
+ if (SERVER_IMPORTS.includes(args.action)) {
111
+ await this.runServerImport(args.action, args.id, flags);
112
+ return;
113
+ }
114
+ // 'import' used to name the CLI's create/update loop on every resource. It
115
+ // now names the API endpoint, which most resources do not have.
116
+ if (args.action === 'import' || args.action.startsWith('import-')) {
117
+ const suffix = args.action === 'import' ? '' : '-' + args.action.replace('import-', '');
118
+ const loops = args.action === 'import' ? HAS_UPSERT : NESTED_UPSERTS.includes(args.action.replace('import-', ''));
119
+ if (loops) {
120
+ this.error(`This resource has no import endpoint. Use: aderis credit-card-accounts upsert${suffix}${suffix ? ' <id>' : ''} --file data.json`);
98
121
  }
99
122
  }
100
123
  const endpoint = ENDPOINTS[args.action];
@@ -409,7 +432,7 @@ export default class CreditCardAccounts extends Command {
409
432
  throw error;
410
433
  }
411
434
  }
412
- async runImport(flags) {
435
+ async runUpsert(flags) {
413
436
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
414
437
  if (!context)
415
438
  this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
@@ -473,12 +496,12 @@ export default class CreditCardAccounts extends Command {
473
496
  items = [item];
474
497
  }
475
498
  else {
476
- this.error('Import requires --file, --data, or --set flags');
499
+ this.error('Upsert requires --file, --data, or --set flags');
477
500
  }
478
501
  const createEndpoint = ENDPOINTS['create'];
479
502
  const updateEndpoint = ENDPOINTS['update'];
480
503
  if (!createEndpoint || !updateEndpoint) {
481
- this.error('Import requires both create and update endpoints');
504
+ this.error('Upsert requires both create and update endpoints');
482
505
  }
483
506
  // Helper to extract identifier from item (id, code, or xxxCode)
484
507
  const getItemIdentifier = (item) => {
@@ -621,6 +644,117 @@ export default class CreditCardAccounts extends Command {
621
644
  this.log('');
622
645
  this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
623
646
  }
647
+ /**
648
+ * The API's own import: the whole array goes up in one request and comes
649
+ * back as an import run, which records what happened to every record. A bad
650
+ * record lands in errorLog and the rest are still applied, and the run stays
651
+ * readable afterwards with: aderis imports get <id>.
652
+ */
653
+ async runServerImport(action, parentId, flags) {
654
+ const endpoint = ENDPOINTS[action];
655
+ if (!endpoint)
656
+ this.error(`Unknown action: ${action}. Available: ${SUBCOMMANDS.join(', ')}`);
657
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
658
+ if (!context)
659
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
660
+ if (!hasCredentials(context))
661
+ this.error(missingCredentialsMessage(context));
662
+ let apiPath = endpoint.path;
663
+ if (endpoint.pathParams.length > 0) {
664
+ if (!parentId)
665
+ this.error(`Missing required argument: id. Usage: aderis credit-card-accounts ${action} <parent-id> --file data.json`);
666
+ apiPath = apiPath.replace(`{${endpoint.pathParams[0]}}`, parentId);
667
+ }
668
+ // The endpoint takes an array. A single object is wrapped, so importing
669
+ // one record reads the same as importing many.
670
+ let records = [];
671
+ if (flags.file) {
672
+ const fsModule = await import('node:fs');
673
+ try {
674
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
675
+ records = Array.isArray(content) ? content : [content];
676
+ }
677
+ catch {
678
+ this.error(`Failed to read file: ${flags.file}`);
679
+ }
680
+ }
681
+ else if (flags.data) {
682
+ try {
683
+ const content = JSON.parse(flags.data);
684
+ records = Array.isArray(content) ? content : [content];
685
+ }
686
+ catch {
687
+ this.error('Invalid JSON in --data');
688
+ }
689
+ }
690
+ else {
691
+ this.error('Import requires --file or --data holding a JSON array of records');
692
+ }
693
+ if (records.length === 0)
694
+ this.error('Nothing to import: the input is an empty array');
695
+ const params = { format: 'json' };
696
+ if (flags.mode)
697
+ params.mode = flags.mode;
698
+ if (flags.reference)
699
+ params.reference = flags.reference;
700
+ if (flags.async)
701
+ params.async = true;
702
+ const headers = {};
703
+ if (flags['idempotency-key'])
704
+ headers['Idempotency-Key'] = flags['idempotency-key'];
705
+ if (flags['show-http-request']) {
706
+ const baseUrls = getBaseUrls(context.environment);
707
+ const queryString = '?' + Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&');
708
+ process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
709
+ process.stderr.write(`Body: [${records.length} record${records.length === 1 ? '' : 's'}]\n\n`);
710
+ }
711
+ try {
712
+ const response = await apiRequest(endpoint.method, apiPath, {
713
+ contextName: flags.context,
714
+ data: records,
715
+ headers,
716
+ params,
717
+ });
718
+ this.printImportRun(response.data, flags);
719
+ }
720
+ catch (error) {
721
+ if (error instanceof ApiError) {
722
+ this.error(`API Error (${error.status}): ${error.message}`);
723
+ }
724
+ throw error;
725
+ }
726
+ }
727
+ /** Renders an import run: its counts, then whatever the server refused. */
728
+ printImportRun(run, flags) {
729
+ if (flags.output === 'json') {
730
+ this.log(JSON.stringify(run, null, 2));
731
+ return;
732
+ }
733
+ const record = (run ?? {});
734
+ const count = (key) => (typeof record[key] === 'number' ? record[key] : 0);
735
+ const id = record.id ? String(record.id) : '';
736
+ this.log(`Import ${id} - ${String(record.status ?? 'UNKNOWN')}${record.async ? ' (background)' : ''}`);
737
+ this.log(` ${count('inputSize')} submitted, ${count('createdCount')} created, ${count('updatedCount')} updated, ${count('unchangedCount')} unchanged`);
738
+ if (count('errorCount') > 0)
739
+ this.log(` ${count('errorCount')} not applied: ${count('refusedCount')} refused, ${count('failedCount')} failed`);
740
+ if (count('warningCount') > 0)
741
+ this.log(` ${count('warningCount')} applied with a warning`);
742
+ // errorLog is keyed by the record's identifier, then by field name.
743
+ const errorLog = record.errorLog;
744
+ if (errorLog && Object.keys(errorLog).length > 0) {
745
+ this.log('');
746
+ for (const [key, fields] of Object.entries(errorLog)) {
747
+ for (const [field, messages] of Object.entries(fields ?? {})) {
748
+ for (const message of messages ?? [])
749
+ this.log(` ${key} ${field}: ${message}`);
750
+ }
751
+ }
752
+ }
753
+ if (record.async && id) {
754
+ this.log('');
755
+ this.log(`Follow it with: aderis imports get ${id}`);
756
+ }
757
+ }
624
758
  async runExport(flags) {
625
759
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
626
760
  if (!context)
@@ -799,9 +933,9 @@ export default class CreditCardAccounts extends Command {
799
933
  throw error;
800
934
  }
801
935
  }
802
- async runNestedImport(suffix, parentId, flags) {
936
+ async runNestedUpsert(suffix, parentId, flags) {
803
937
  if (!parentId) {
804
- this.error(`Missing required argument: id. Usage: aderis credit-card-accounts import-${suffix} <parent-id> --file data.json`);
938
+ this.error(`Missing required argument: id. Usage: aderis credit-card-accounts upsert-${suffix} <parent-id> --file data.json`);
805
939
  }
806
940
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
807
941
  if (!context)
@@ -866,12 +1000,12 @@ export default class CreditCardAccounts extends Command {
866
1000
  items = [item];
867
1001
  }
868
1002
  else {
869
- this.error(`Import requires --file, --data, or --set flags`);
1003
+ this.error('Upsert requires --file, --data, or --set flags');
870
1004
  }
871
1005
  const createEndpoint = ENDPOINTS[`create-${suffix}`];
872
1006
  const updateEndpoint = ENDPOINTS[`update-${suffix}`];
873
1007
  if (!createEndpoint || !updateEndpoint) {
874
- this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
1008
+ this.error(`Upsert requires both create-${suffix} and update-${suffix} endpoints`);
875
1009
  }
876
1010
  // Build the base path with parent ID (first path param)
877
1011
  const firstParam = createEndpoint.pathParams[0];
@@ -30,10 +30,19 @@ export default class DeliveryNotes extends Command {
30
30
  'show-http-request': import("@oclif/core/interfaces").BooleanFlag<boolean>;
31
31
  };
32
32
  run(): Promise<void>;
33
- private runImport;
33
+ private runUpsert;
34
+ /**
35
+ * The API's own import: the whole array goes up in one request and comes
36
+ * back as an import run, which records what happened to every record. A bad
37
+ * record lands in errorLog and the rest are still applied, and the run stays
38
+ * readable afterwards with: aderis imports get <id>.
39
+ */
40
+ private runServerImport;
41
+ /** Renders an import run: its counts, then whatever the server refused. */
42
+ private printImportRun;
34
43
  private runExport;
35
44
  private runCamt053Import;
36
- private runNestedImport;
45
+ private runNestedUpsert;
37
46
  private parseFilterValue;
38
47
  /** The page line under a table: which page, how many, and any sums the API returned. */
39
48
  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 = true;
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 = true;
6
8
  const HAS_EXPORT = true;
7
9
  const HAS_CAMT053 = false;
8
- const NESTED_IMPORTS = ["line-items", "notes", "files"];
9
- const SUBCOMMANDS = [...["list", "create", "create-from-orders", "create-from-invoice", "create-invoice", "get", "update", "delete", "get-pdf", "create-pdf", "submit", "approve", "cancel", "replace", "copy", "deliver", "ship", "send", "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 SERVER_IMPORTS = [];
11
+ const NESTED_UPSERTS = ["line-items", "notes", "files"];
12
+ const SUBCOMMANDS = [...["list", "create", "create-from-orders", "create-from-invoice", "create-invoice", "get", "update", "delete", "get-pdf", "create-pdf", "submit", "approve", "cancel", "replace", "copy", "deliver", "ship", "send", "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_UPSERT ? ['upsert'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_UPSERTS.map(n => `upsert-${n}`)];
10
13
  const ENDPOINTS = {
11
14
  'list': { method: 'GET', path: '/v1/delivery-notes', summary: 'Get all delivery notes with pagination', pathParams: [], hasBody: false, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: [] },
12
15
  'create': { method: 'POST', path: '/v1/delivery-notes', summary: 'Create a new delivery note', pathParams: [], hasBody: true, isMultipart: false, isBinaryResponse: false, hasBinaryVariant: false, bodyArrayFields: ['files', 'notes', 'tagIds', 'tagCodes', 'lineItems'] },
@@ -49,7 +52,7 @@ export default class DeliveryNotes extends Command {
49
52
  '<%= config.bin %> delivery-notes get <id>',
50
53
  '<%= config.bin %> delivery-notes create --data \'{...}\'',
51
54
  '<%= config.bin %> delivery-notes update <id> --set field=value',
52
- '<%= config.bin %> delivery-notes import --file data.json',
55
+ '<%= config.bin %> delivery-notes upsert --file data.json',
53
56
  '<%= config.bin %> delivery-notes export --csv > delivery-notes.csv',
54
57
  ];
55
58
  static args = {
@@ -58,7 +61,7 @@ export default class DeliveryNotes extends Command {
58
61
  };
59
62
  static flags = {
60
63
  context: Flags.string({ char: 'c', aliases: ['config'], env: 'ADERIS_CONTEXT', description: 'Context to use for this command, overriding the current context (alias: --config)' }),
61
- output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
64
+ output: Flags.string({ char: 'o', description: 'Output format (default: table for upsert, json for other commands)', options: ['json', 'table', 'csv'] }),
62
65
  table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
63
66
  csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
64
67
  data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
@@ -81,11 +84,26 @@ export default class DeliveryNotes extends Command {
81
84
  };
82
85
  async run() {
83
86
  const { args, flags } = await this.parse(DeliveryNotes);
84
- // Handle import action specially
85
- if (args.action === 'import') {
86
- if (!HAS_IMPORT)
87
- this.error('Import not available for this resource');
88
- await this.runImport(flags);
87
+ // Bulk actions. 'import' is the API's own endpoint: one request, answered
88
+ // by a run that records what happened to every record. 'upsert' is the CLI
89
+ // looping create/update. A resource has one or the other, never both.
90
+ if (args.action === 'upsert') {
91
+ if (!HAS_UPSERT) {
92
+ this.error(SERVER_IMPORTS.includes('import')
93
+ ? 'This resource is imported by the API. Use: aderis delivery-notes import --file data.json'
94
+ : 'Upsert needs both a create and an update endpoint, which this resource does not have');
95
+ }
96
+ await this.runUpsert(flags);
97
+ return;
98
+ }
99
+ if (args.action.startsWith('upsert-')) {
100
+ const suffix = args.action.replace('upsert-', '');
101
+ if (!NESTED_UPSERTS.includes(suffix)) {
102
+ this.error(SERVER_IMPORTS.includes('import-' + suffix)
103
+ ? `That resource is imported by the API. Use: aderis delivery-notes import-${suffix} <id> --file data.json`
104
+ : `Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
105
+ }
106
+ await this.runNestedUpsert(suffix, args.id, flags);
89
107
  return;
90
108
  }
91
109
  // Handle export action specially
@@ -102,12 +120,17 @@ export default class DeliveryNotes extends Command {
102
120
  await this.runCamt053Import(flags);
103
121
  return;
104
122
  }
105
- // Handle nested resource imports (e.g., import-prices)
106
- if (args.action.startsWith('import-')) {
107
- const suffix = args.action.replace('import-', '');
108
- if (NESTED_IMPORTS.includes(suffix)) {
109
- await this.runNestedImport(suffix, args.id, flags);
110
- return;
123
+ if (SERVER_IMPORTS.includes(args.action)) {
124
+ await this.runServerImport(args.action, args.id, flags);
125
+ return;
126
+ }
127
+ // 'import' used to name the CLI's create/update loop on every resource. It
128
+ // now names the API endpoint, which most resources do not have.
129
+ if (args.action === 'import' || args.action.startsWith('import-')) {
130
+ const suffix = args.action === 'import' ? '' : '-' + args.action.replace('import-', '');
131
+ const loops = args.action === 'import' ? HAS_UPSERT : NESTED_UPSERTS.includes(args.action.replace('import-', ''));
132
+ if (loops) {
133
+ this.error(`This resource has no import endpoint. Use: aderis delivery-notes upsert${suffix}${suffix ? ' <id>' : ''} --file data.json`);
111
134
  }
112
135
  }
113
136
  const endpoint = ENDPOINTS[args.action];
@@ -422,7 +445,7 @@ export default class DeliveryNotes extends Command {
422
445
  throw error;
423
446
  }
424
447
  }
425
- async runImport(flags) {
448
+ async runUpsert(flags) {
426
449
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
427
450
  if (!context)
428
451
  this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
@@ -486,12 +509,12 @@ export default class DeliveryNotes extends Command {
486
509
  items = [item];
487
510
  }
488
511
  else {
489
- this.error('Import requires --file, --data, or --set flags');
512
+ this.error('Upsert requires --file, --data, or --set flags');
490
513
  }
491
514
  const createEndpoint = ENDPOINTS['create'];
492
515
  const updateEndpoint = ENDPOINTS['update'];
493
516
  if (!createEndpoint || !updateEndpoint) {
494
- this.error('Import requires both create and update endpoints');
517
+ this.error('Upsert requires both create and update endpoints');
495
518
  }
496
519
  // Helper to extract identifier from item (id, code, or xxxCode)
497
520
  const getItemIdentifier = (item) => {
@@ -634,6 +657,117 @@ export default class DeliveryNotes extends Command {
634
657
  this.log('');
635
658
  this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
636
659
  }
660
+ /**
661
+ * The API's own import: the whole array goes up in one request and comes
662
+ * back as an import run, which records what happened to every record. A bad
663
+ * record lands in errorLog and the rest are still applied, and the run stays
664
+ * readable afterwards with: aderis imports get <id>.
665
+ */
666
+ async runServerImport(action, parentId, flags) {
667
+ const endpoint = ENDPOINTS[action];
668
+ if (!endpoint)
669
+ this.error(`Unknown action: ${action}. Available: ${SUBCOMMANDS.join(', ')}`);
670
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
671
+ if (!context)
672
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
673
+ if (!hasCredentials(context))
674
+ this.error(missingCredentialsMessage(context));
675
+ let apiPath = endpoint.path;
676
+ if (endpoint.pathParams.length > 0) {
677
+ if (!parentId)
678
+ this.error(`Missing required argument: id. Usage: aderis delivery-notes ${action} <parent-id> --file data.json`);
679
+ apiPath = apiPath.replace(`{${endpoint.pathParams[0]}}`, parentId);
680
+ }
681
+ // The endpoint takes an array. A single object is wrapped, so importing
682
+ // one record reads the same as importing many.
683
+ let records = [];
684
+ if (flags.file) {
685
+ const fsModule = await import('node:fs');
686
+ try {
687
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
688
+ records = Array.isArray(content) ? content : [content];
689
+ }
690
+ catch {
691
+ this.error(`Failed to read file: ${flags.file}`);
692
+ }
693
+ }
694
+ else if (flags.data) {
695
+ try {
696
+ const content = JSON.parse(flags.data);
697
+ records = Array.isArray(content) ? content : [content];
698
+ }
699
+ catch {
700
+ this.error('Invalid JSON in --data');
701
+ }
702
+ }
703
+ else {
704
+ this.error('Import requires --file or --data holding a JSON array of records');
705
+ }
706
+ if (records.length === 0)
707
+ this.error('Nothing to import: the input is an empty array');
708
+ const params = { format: 'json' };
709
+ if (flags.mode)
710
+ params.mode = flags.mode;
711
+ if (flags.reference)
712
+ params.reference = flags.reference;
713
+ if (flags.async)
714
+ params.async = true;
715
+ const headers = {};
716
+ if (flags['idempotency-key'])
717
+ headers['Idempotency-Key'] = flags['idempotency-key'];
718
+ if (flags['show-http-request']) {
719
+ const baseUrls = getBaseUrls(context.environment);
720
+ const queryString = '?' + Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&');
721
+ process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
722
+ process.stderr.write(`Body: [${records.length} record${records.length === 1 ? '' : 's'}]\n\n`);
723
+ }
724
+ try {
725
+ const response = await apiRequest(endpoint.method, apiPath, {
726
+ contextName: flags.context,
727
+ data: records,
728
+ headers,
729
+ params,
730
+ });
731
+ this.printImportRun(response.data, flags);
732
+ }
733
+ catch (error) {
734
+ if (error instanceof ApiError) {
735
+ this.error(`API Error (${error.status}): ${error.message}`);
736
+ }
737
+ throw error;
738
+ }
739
+ }
740
+ /** Renders an import run: its counts, then whatever the server refused. */
741
+ printImportRun(run, flags) {
742
+ if (flags.output === 'json') {
743
+ this.log(JSON.stringify(run, null, 2));
744
+ return;
745
+ }
746
+ const record = (run ?? {});
747
+ const count = (key) => (typeof record[key] === 'number' ? record[key] : 0);
748
+ const id = record.id ? String(record.id) : '';
749
+ this.log(`Import ${id} - ${String(record.status ?? 'UNKNOWN')}${record.async ? ' (background)' : ''}`);
750
+ this.log(` ${count('inputSize')} submitted, ${count('createdCount')} created, ${count('updatedCount')} updated, ${count('unchangedCount')} unchanged`);
751
+ if (count('errorCount') > 0)
752
+ this.log(` ${count('errorCount')} not applied: ${count('refusedCount')} refused, ${count('failedCount')} failed`);
753
+ if (count('warningCount') > 0)
754
+ this.log(` ${count('warningCount')} applied with a warning`);
755
+ // errorLog is keyed by the record's identifier, then by field name.
756
+ const errorLog = record.errorLog;
757
+ if (errorLog && Object.keys(errorLog).length > 0) {
758
+ this.log('');
759
+ for (const [key, fields] of Object.entries(errorLog)) {
760
+ for (const [field, messages] of Object.entries(fields ?? {})) {
761
+ for (const message of messages ?? [])
762
+ this.log(` ${key} ${field}: ${message}`);
763
+ }
764
+ }
765
+ }
766
+ if (record.async && id) {
767
+ this.log('');
768
+ this.log(`Follow it with: aderis imports get ${id}`);
769
+ }
770
+ }
637
771
  async runExport(flags) {
638
772
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
639
773
  if (!context)
@@ -812,9 +946,9 @@ export default class DeliveryNotes extends Command {
812
946
  throw error;
813
947
  }
814
948
  }
815
- async runNestedImport(suffix, parentId, flags) {
949
+ async runNestedUpsert(suffix, parentId, flags) {
816
950
  if (!parentId) {
817
- this.error(`Missing required argument: id. Usage: aderis delivery-notes import-${suffix} <parent-id> --file data.json`);
951
+ this.error(`Missing required argument: id. Usage: aderis delivery-notes upsert-${suffix} <parent-id> --file data.json`);
818
952
  }
819
953
  const context = flags.context ? getContext(flags.context) : getCurrentContext();
820
954
  if (!context)
@@ -879,12 +1013,12 @@ export default class DeliveryNotes extends Command {
879
1013
  items = [item];
880
1014
  }
881
1015
  else {
882
- this.error(`Import requires --file, --data, or --set flags`);
1016
+ this.error('Upsert requires --file, --data, or --set flags');
883
1017
  }
884
1018
  const createEndpoint = ENDPOINTS[`create-${suffix}`];
885
1019
  const updateEndpoint = ENDPOINTS[`update-${suffix}`];
886
1020
  if (!createEndpoint || !updateEndpoint) {
887
- this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
1021
+ this.error(`Upsert requires both create-${suffix} and update-${suffix} endpoints`);
888
1022
  }
889
1023
  // Build the base path with parent ID (first path param)
890
1024
  const firstParam = createEndpoint.pathParams[0];
@@ -27,10 +27,19 @@ export default class DunningConfigs 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;