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