import { createHash, randomUUID } from 'node:crypto';
import { readFile } from 'node:fs/promises';
const me = await api('/public/v1/me', { client: false });
if (!me.scopes.includes('import') || !me.scopes.includes('ncts')) {
throw new Error('This import needs the import and ncts modules.');
}
const shipment = await api('/public/v1/shipments', {
method: 'POST',
idempotencyKey: randomUUID(),
body: {
shipmentNumber: 'SHP-2026-0142',
shipmentType: 'IMPORT',
enabledServices: ['clearance'],
clientReference: 'PO-44821',
},
});
const templates = await api('/public/v1/manifest-templates?shipmentType=IMPORT');
const manifestTemplateId = templates.data[0].id;
const fileBytes = await readFile('./manifest.csv');
const created = await api('/public/v1/uploads', {
method: 'POST',
idempotencyKey: randomUUID(),
body: {
purpose: 'shipment_manifest',
filename: 'manifest.csv',
contentType: 'text/csv',
byteLength: fileBytes.byteLength,
sha256: createHash('sha256').update(fileBytes).digest('hex'),
},
});
const put = await fetch(created.upload.url, {
method: 'PUT',
headers: created.upload.requiredHeaders,
body: fileBytes,
});
if (!put.ok) throw new Error(`Storage upload failed: ${put.status}`);
const ready = await api(`/public/v1/uploads/${created.id}/complete`, {
method: 'POST',
idempotencyKey: randomUUID(),
});
const accepted = await api(`/public/v1/shipments/${shipment.id}/details/import`, {
method: 'POST',
idempotencyKey: randomUUID(),
body: { uploadId: ready.id, manifestTemplateId, mode: 'INITIAL' },
});
const operation = await api(`/public/v1/operations/${accepted.operationId}`);
if (operation.status === 'succeeded') {
const declarations = await api(`/public/v1/shipments/${shipment.id}/declarations`);
const declarationId = declarations.data[0].id;
await api(`/public/v1/declarations/${declarationId}/goods-items`);
}