306 lines
9.9 KiB
TypeScript
306 lines
9.9 KiB
TypeScript
import { expect, test, vi } from "vitest";
|
|
|
|
import {
|
|
createReportService,
|
|
type ReportRepository,
|
|
type SelectedUsage,
|
|
type StoredReport,
|
|
ReportConflictError,
|
|
} from "./reports";
|
|
import type { BillingReportAddress, BillingReportRepeatDownload } from "./types";
|
|
import type { BillingPeriod } from "./period";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Fixtures
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const period: BillingPeriod = {
|
|
fromUtc: new Date("2026-08-01T22:00:00.000Z"),
|
|
toUtcExclusive: new Date("2026-09-01T22:00:00.000Z"),
|
|
};
|
|
|
|
const validSelection = {
|
|
editorialId: "e1",
|
|
usageIds: ["u1", "u2"],
|
|
period,
|
|
adminUserId: "a1",
|
|
flatrateCentsSnapshot: null,
|
|
};
|
|
|
|
const address: BillingReportAddress = {
|
|
companyName: "Redaktion Beispiel GmbH",
|
|
contactName: "Anna Schmidt",
|
|
addressLine1: "Musterstraße 12",
|
|
addressLine2: null,
|
|
postalCode: "10115",
|
|
city: "Berlin",
|
|
countryCode: "DE",
|
|
};
|
|
|
|
function selectedUsage(id: string, status: "open" | "reopened" = "open"): SelectedUsage {
|
|
return {
|
|
id,
|
|
immichAssetId: `asset-${id}`,
|
|
filenameSnapshot: `file-${id}.jpg`,
|
|
albumNameSnapshot: "Presse 2026",
|
|
purpose: "Titelgeschichte",
|
|
internalReference: null,
|
|
priceCents: 3_000,
|
|
billingStatus: status,
|
|
createdAt: new Date("2026-08-05T10:00:00.000Z"),
|
|
editorialAccountId: "e1",
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// In-memory mock repository
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function createMockRepo(options?: { flatratePriceCents?: number | null }) {
|
|
const usageStatuses = new Map<string, string>([
|
|
["u1", "open"],
|
|
["u2", "open"],
|
|
]);
|
|
const reports = new Map<string, StoredReport & { pdf?: Buffer; pdfSha256?: string }>();
|
|
const reportItems = new Map<string, string[]>();
|
|
let nextReportNumber = 1;
|
|
|
|
const repo: ReportRepository = {
|
|
async getCurrentAddress() {
|
|
return address;
|
|
},
|
|
|
|
async getEditorialFlatrate() {
|
|
const flatratePriceCents = options?.flatratePriceCents ?? null;
|
|
return {
|
|
flatrateActive: flatratePriceCents !== null,
|
|
flatratePriceCents,
|
|
flatrateAssetLimit: null,
|
|
};
|
|
},
|
|
|
|
async getSelectedUsages(_editorialId, usageIds) {
|
|
return usageIds.map((id) => selectedUsage(id, usageStatuses.get(id) as "open" | "reopened"));
|
|
},
|
|
|
|
async getRepeatDownloads() {
|
|
return [] as BillingReportRepeatDownload[];
|
|
},
|
|
|
|
async allocateReportNumber() {
|
|
return nextReportNumber++;
|
|
},
|
|
|
|
async finalizeInTransaction(input) {
|
|
// Re-check eligibility inside the "transaction"
|
|
for (const usage of input.selectedUsages) {
|
|
const status = usageStatuses.get(usage.id);
|
|
if (status !== "open" && status !== "reopened") {
|
|
throw new ReportConflictError("USAGE_NOT_ELIGIBLE");
|
|
}
|
|
}
|
|
// Check report number collision
|
|
for (const report of reports.values()) {
|
|
if (report.reportNumber === input.reportNumber) {
|
|
throw new ReportConflictError("REPORT_NUMBER_COLLISION");
|
|
}
|
|
}
|
|
|
|
const reportId = `r${reports.size + 1}`;
|
|
reports.set(reportId, {
|
|
id: reportId,
|
|
reportNumber: input.reportNumber,
|
|
invoiceNumber: input.invoiceNumber,
|
|
status: "final",
|
|
editorialAccountId: input.editorialId,
|
|
netTotalCents: input.netTotalCents,
|
|
cancellationReason: null,
|
|
});
|
|
reportItems.set(reportId, input.selectedUsages.map((u) => u.id));
|
|
for (const usage of input.selectedUsages) {
|
|
usageStatuses.set(usage.id, "billed");
|
|
}
|
|
return {
|
|
reportId,
|
|
reportNumber: input.reportNumber,
|
|
invoiceNumber: input.invoiceNumber,
|
|
};
|
|
},
|
|
|
|
async getReportWithItemUsageIds(reportId) {
|
|
const report = reports.get(reportId);
|
|
if (!report) return null;
|
|
return { status: report.status, usageIds: reportItems.get(reportId) ?? [] };
|
|
},
|
|
|
|
async cancelReportInTransaction(reportId, reason, adminUserId, usageIds) {
|
|
const report = reports.get(reportId);
|
|
if (!report) throw new Error("Report not found");
|
|
reports.set(reportId, {
|
|
...report,
|
|
status: "cancelled",
|
|
cancellationReason: reason,
|
|
cancelledByUserId: adminUserId,
|
|
} as StoredReport & { pdf?: Buffer; pdfSha256?: string; cancelledByUserId?: string });
|
|
for (const id of usageIds) {
|
|
usageStatuses.set(id, "reopened");
|
|
}
|
|
},
|
|
|
|
async getFinalReportPdf(reportId) {
|
|
const report = reports.get(reportId);
|
|
if (!report || report.status !== "final") return null;
|
|
return {
|
|
bytes: report.pdf ?? Buffer.from("pdf"),
|
|
reportNumber: report.reportNumber,
|
|
invoiceNumber: report.invoiceNumber ?? "",
|
|
};
|
|
},
|
|
|
|
async getUsageStatuses(usageIds) {
|
|
return usageIds.map((id) => usageStatuses.get(id) ?? "open");
|
|
},
|
|
|
|
async getReport(reportId) {
|
|
const report = reports.get(reportId);
|
|
if (!report) return null;
|
|
const { pdf, pdfSha256, ...rest } = report;
|
|
return rest;
|
|
},
|
|
};
|
|
|
|
return { repo, usageStatuses, reports, reportItems };
|
|
}
|
|
|
|
function createService(repo: ReportRepository) {
|
|
const render = vi.fn().mockResolvedValue({
|
|
bytes: Buffer.from("mock-pdf"),
|
|
sha256: "a".repeat(64),
|
|
});
|
|
const service = createReportService({ repo, render });
|
|
return { service, render };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tests (from the brief — exact assertions)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("does not bill positions when PDF rendering fails", async () => {
|
|
const { repo } = createMockRepo();
|
|
const { service, render } = createService(repo);
|
|
render.mockRejectedValue(new Error("render failed"));
|
|
|
|
await expect(service.finalizeReport(validSelection)).rejects.toThrow("render failed");
|
|
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["open", "open"]);
|
|
});
|
|
|
|
test("cancellation reopens positions and preserves the cancelled report", async () => {
|
|
const mock = createMockRepo();
|
|
const { repo, reports, reportItems } = mock;
|
|
|
|
// Set up a finalized report with one billed usage
|
|
reports.set("r1", {
|
|
id: "r1",
|
|
reportNumber: 1,
|
|
invoiceNumber: "NN-2026-0001",
|
|
status: "final",
|
|
editorialAccountId: "e1",
|
|
netTotalCents: 3_000,
|
|
cancellationReason: null,
|
|
});
|
|
reportItems.set("r1", ["u1"]);
|
|
mock.usageStatuses.set("u1", "billed");
|
|
|
|
const { service } = createService(repo);
|
|
|
|
await service.cancelReport({ reportId: "r1", reason: "Falscher Zeitraum", adminUserId: "a1" });
|
|
await expect(repo.getReport("r1")).resolves.toMatchObject({ status: "cancelled" });
|
|
await expect(repo.getUsageStatuses(["u1"])).resolves.toEqual(["reopened"]);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Additional tests for preview, happy-path finalize, and conflict behavior
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("finalizeReport creates a final report and marks usages billed", async () => {
|
|
const { repo, reports } = createMockRepo();
|
|
const { service } = createService(repo);
|
|
|
|
const result = await service.finalizeReport(validSelection);
|
|
|
|
expect(result.reportNumber).toBe("1");
|
|
expect(result.reportId).toBeTruthy();
|
|
const report = await repo.getReport(result.reportId);
|
|
expect(report).toMatchObject({ status: "final", netTotalCents: 6_000 });
|
|
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["billed", "billed"]);
|
|
});
|
|
|
|
test("previewReport returns PDF bytes without persisting or billing", async () => {
|
|
const { repo, reports } = createMockRepo();
|
|
const { service, render } = createService(repo);
|
|
|
|
const bytes = await service.previewReport({
|
|
editorialId: validSelection.editorialId,
|
|
usageIds: validSelection.usageIds,
|
|
period: validSelection.period,
|
|
flatrateCentsSnapshot: null,
|
|
});
|
|
|
|
expect(bytes).toBeInstanceOf(Buffer);
|
|
expect(render).toHaveBeenCalledTimes(1);
|
|
expect(reports.size).toBe(0);
|
|
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["open", "open"]);
|
|
});
|
|
|
|
test("uses the server-read flatrate snapshot consistently in PDF, total, and persistence", async () => {
|
|
const { repo, reports } = createMockRepo({ flatratePriceCents: 12_500 });
|
|
const finalizeInTransaction = vi.spyOn(repo, "finalizeInTransaction");
|
|
const { service, render } = createService(repo);
|
|
|
|
const result = await service.finalizeReport(validSelection);
|
|
|
|
expect(render).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
flatrateCentsSnapshot: 12_500,
|
|
netTotalCents: 18_500,
|
|
}),
|
|
);
|
|
expect(finalizeInTransaction).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
flatrateCentsSnapshot: 12_500,
|
|
netTotalCents: 18_500,
|
|
}),
|
|
);
|
|
await expect(repo.getReport(result.reportId)).resolves.toMatchObject({
|
|
netTotalCents: 18_500,
|
|
});
|
|
});
|
|
|
|
test("finalizeReport rejects when a selected usage is already billed", async () => {
|
|
const mock = createMockRepo();
|
|
const { repo } = mock;
|
|
mock.usageStatuses.set("u1", "billed");
|
|
const { service } = createService(repo);
|
|
|
|
await expect(service.finalizeReport(validSelection)).rejects.toBeInstanceOf(ReportConflictError);
|
|
await expect(repo.getUsageStatuses(["u2"])).resolves.toEqual(["open"]);
|
|
});
|
|
|
|
test("cancelReport rejects a reason shorter than 5 characters", async () => {
|
|
const { repo } = createMockRepo();
|
|
const { service } = createService(repo);
|
|
|
|
await expect(
|
|
service.cancelReport({ reportId: "r1", reason: "abc", adminUserId: "a1" }),
|
|
).rejects.toThrow();
|
|
});
|
|
|
|
test("cancelReport rejects a reason longer than 500 characters", async () => {
|
|
const { repo } = createMockRepo();
|
|
const { service } = createService(repo);
|
|
|
|
await expect(
|
|
service.cancelReport({ reportId: "r1", reason: "x".repeat(501), adminUserId: "a1" }),
|
|
).rejects.toThrow();
|
|
});
|