Files
photoreport/apps/api/test/invoicing.test.ts
spark 78dfd5cc3d
ci / rust (push) Successful in 7m1s
ci / typescript (push) Failing after 9m5s
Invoicing through InvoiceXpress: a certified invoice-receipt for every paid order
With InvoiceXpress set up (account and API key, sealed), a paid order queues an invoice that the worker issues: created as a draft with our id as proprietary_uid (no duplicates), finalized, emailed to the buyer. Retried with backoff; rejected data or a bad key fails at once and notifies admins. Reverse-charged orders carry the exemption code from the settings (M40 by default). The number and link show on the order in the app and on the buyer's order page; Vendas -> Faturas lists them with a retry.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 04:46:09 +01:00

138 lines
7.8 KiB
TypeScript

import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { SecretBox } from "../src/delivery/secrets.js";
import { InvoicingService } from "../src/invoicing/service.js";
import { Notifications } from "../src/notifications/service.js";
import { MemoryBroadcaster } from "../src/realtime.js";
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
const KEY = Buffer.alloc(32, 9).toString("base64");
const quiet = { info: () => {}, warn: () => {} };
describe("invoicing (InvoiceXpress)", () => {
let ctx: TestContext;
const calls: { method: string; url: string; body: unknown }[] = [];
let createStatus = 201;
let state = "draft";
const fakeFetch: typeof fetch = async (input, init) => {
const url = String(input);
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
calls.push({ method: init?.method ?? "GET", url, body });
if (!url.startsWith("https://bitreport.app.invoicexpress.com/")) return new Response("nope", { status: 404 });
if (!url.includes("api_key=ix-secret")) return Response.json({ errors: "unauthorized" }, { status: 401 });
if (url.includes("/invoices.json?per_page=1")) return Response.json({ invoices: [] });
if (init?.method === "POST" && url.includes("/invoice_receipts.json")) {
if (createStatus !== 201) return Response.json({ errors: [{ error: "Client fiscal id is invalid" }] }, { status: createStatus });
return Response.json({ invoice: { id: 4242, status: "draft" } }, { status: 201 });
}
if (url.includes("/invoice_receipts/4242/change-state.json")) {
state = "settled";
return new Response("", { status: 200 });
}
if (url.includes("/invoice_receipts/4242.json")) return Response.json({ invoice: { id: 4242, status: state, sequence_number: state === "draft" ? null : "12/FR", inverted_sequence_number: state === "draft" ? null : "FR 2026/12", permalink: "https://www.app.invoicexpress.com/documents/abc" } });
if (url.includes("/email-document.json")) return new Response("", { status: 200 });
return new Response("unexpected", { status: 500 });
};
beforeAll(async () => {
ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY }, new MemoryBroadcaster(), fakeFetch);
});
afterAll(async () => {
await ctx.app.close();
await ctx.db.$disconnect();
});
beforeEach(async () => {
await resetDb(ctx.db);
calls.length = 0;
createStatus = 201;
state = "draft";
});
async function setup() {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "pr", role: "OWNER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
const put = (body: object) => ctx.app.inject({ method: "PUT", url: `/v1/orgs/${org!.id}/shop-settings`, headers: bearer(token), payload: body });
expect((await put({ invoicingProvider: "invoicexpress", invoicingAccount: "BitReport", invoicingApiKey: "ix-secret", reverseChargeCode: "m40" })).statusCode).toBe(200);
const order = await ctx.db.order.create({
data: {
organizationId: org!.id,
number: "2026-000009",
status: "PAID",
email: "[email protected]",
name: "Comprador",
vatNumber: "ESB12345678",
viesName: "Fotos Madrid SL",
country: "ES",
reverseCharge: true,
netCents: 2000,
vatCents: 0,
totalCents: 2000,
accessToken: "x".repeat(32),
paidAt: new Date("2026-10-13T09:00:00Z"),
items: { create: [{ productName: "Digital 2400 px", kind: "DIGITAL", quantity: 2, unitCents: 1230, vatRate: 0, totalCents: 2000 }] },
},
});
const notifications = new Notifications(ctx.db);
const service = new InvoicingService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fakeFetch, notifications });
return { orgId: org!.id, token, order, service };
}
it("issues a finalized invoice-receipt for a paid order, emails it and shows it on the order", async () => {
const { orgId, token, order, service } = await setup();
const settings = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/shop-settings`, headers: bearer(token) })).json();
expect(settings).toMatchObject({ invoicingProvider: "invoicexpress", invoicingAccount: "bitreport", invoicingConfigured: true, reverseChargeCode: "M40" });
expect(settings).not.toHaveProperty("invoicingApiKey");
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/invoicing/check`, headers: bearer(token) })).json()).toEqual({ ok: true });
expect(await service.queueOrder(order.id)).toBe(true);
expect(await service.queueOrder(order.id)).toBe(false);
const [id] = await service.claim(5);
const issued = await service.issue(id!);
expect(issued).toMatchObject({ status: "ISSUED", number: "FR 2026/12", url: "https://www.app.invoicexpress.com/documents/abc", externalId: "4242" });
const create = calls.find((c) => c.method === "POST")!.body as { invoice: Record<string, unknown> & { client: Record<string, unknown>; items: Record<string, unknown>[] } };
expect(create.invoice).toMatchObject({ date: "13/10/2026", reference: "2026-000009", tax_exemption: "M40", observations: "IVA - autoliquidação", proprietary_uid: id });
expect(create.invoice.client).toMatchObject({ name: "Fotos Madrid SL", code: "ESB12345678", fiscal_id: "ESB12345678", country: "Spain", email: "[email protected]" });
expect(create.invoice.items).toEqual([{ name: "Digital 2400 px", description: "Digital 2400 px", unit_price: 10, quantity: 2, tax: { name: "IVA0" } }]);
expect(calls.some((c) => c.url.includes("/email-document.json"))).toBe(true);
const orders = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/orders`, headers: bearer(token) })).json() as { orders: { invoice: unknown }[] };
expect(orders.orders[0]!.invoice).toEqual({ status: "ISSUED", number: "FR 2026/12", url: "https://www.app.invoicexpress.com/documents/abc" });
});
it("finalizes a draft left by an earlier try instead of creating another, and gives up on rejected data", async () => {
const { orgId, token, order, service } = await setup();
await service.queueOrder(order.id);
const [id] = await service.claim(5);
await ctx.db.invoice.update({ where: { id: id! }, data: { externalId: "4242" } });
expect((await service.issue(id!)).status).toBe("ISSUED");
expect(calls.filter((c) => c.method === "POST")).toHaveLength(0);
// Rejected by the software (422): failed at once, admins told, retried from the app after a fix.
await ctx.db.invoice.deleteMany();
createStatus = 422;
await service.queueOrder(order.id);
const [again] = await service.claim(5);
const failed = await service.issue(again!);
expect(failed).toMatchObject({ status: "FAILED" });
expect(failed.error).toContain("fiscal id");
expect(await ctx.db.notification.count({ where: { type: "invoice_failed" } })).toBe(1);
createStatus = 201;
const retried = (await ctx.app.inject({ method: "POST", url: `/v1/invoices/${again}/retry`, headers: bearer(token) })).json();
expect(retried).toMatchObject({ status: "PENDING", attempts: 0 });
const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/invoices`, headers: bearer(token) })).json() as { invoices: { orderNumber: string }[] };
expect(list.invoices[0]!.orderNumber).toBe("2026-000009");
});
it("tries again later when the software does not answer", async () => {
const { order, service } = await setup();
await service.queueOrder(order.id);
await ctx.db.organization.updateMany({ data: { invoicingAccount: "down" } });
const [id] = await service.claim(5);
const saved = await service.issue(id!);
expect(saved.status).toBe("PENDING");
expect(saved.nextAttemptAt.getTime()).toBeGreaterThan(Date.now() + 30_000);
expect(await service.claim(5)).toEqual([]);
});
});