import axios from "axios"; import { CustomError } from "@nimee/error-handler"; const port = process.env.INVOICES_PORT || "3009"; // default keeps IS_LOCAL dev working without env setup const basePath = process.env.IS_LOCAL === "true" ? `http://127.0.0.1:${port}` : "http://invoices"; /** * Client for the invoices microservice (Nimi self-issued fiscal documents). * doc/create and doc/cancel are internal-only routes gated to the fixed * JWT_ADMIN service token - always call them with jwt: process.env.JWT_ADMIN. */ export class InvoiceClient { /** Create a fiscal document (invoice / receipt / credit note). Idempotent on body.sanity_string. */ async createDoc(params: { jwt: string; body: Record }) { const { jwt, body } = params; if (!jwt || !body) { throw new CustomError("params_missing_invoice_create_doc", 400, "jwt and body are required"); } const response = await axios.post(`${basePath}/invoices-internal/doc/create`, body, { headers: { jwt } }); return response?.data; } /** Cancel a document by issuing a reversing credit note. */ async cancelDoc(params: { jwt: string; body: { sellerId: string; doctype: string; docnum: number; reason?: string } }) { const { jwt, body } = params; if (!jwt || !body) { throw new CustomError("params_missing_invoice_cancel_doc", 400, "jwt and body are required"); } const response = await axios.post(`${basePath}/invoices-internal/doc/cancel`, body, { headers: { jwt } }); return response?.data; } /** * Internal: render + store the group-order document PDF (non-fiscal, not PKCS#7-signed). * body = { sellerId, orderId, payload, signatureImageBase64?, logoUrl? }; returns { pdfKey, signatureKey?, pdfUrl }. */ async renderGroupOrderPdf(params: { jwt: string; body: Record }) { const { jwt, body } = params; if (!jwt || !body) { throw new CustomError("params_missing_invoice_render_group_order", 400, "jwt and body are required"); } const response = await axios.post(`${basePath}/invoices-internal/group-order/render`, body, { headers: { jwt } }); return response?.data; } /** Internal: presigned (1h) URL for a stored group-order file key; returns { url }. */ async getFileUrl(params: { jwt: string; key: string }) { const { jwt, key } = params; if (!jwt || !key) { throw new CustomError("params_missing_invoice_file_url", 400, "jwt and key are required"); } const response = await axios.get(`${basePath}/invoices-internal/file-url`, { params: { key }, headers: { jwt } }); return response?.data; } }