fix: resolve all 28 findings from the 2026-06-12 full audit (TDD-pinned)

Critical (data integrity):
- warehouse inventory confirm: throw (not return) inside $transaction so a
  failed deficit line rolls back the surplus corrective receipt — retries
  no longer accumulate phantom stock
- warehouse issue confirm: validate batches against the COMBINED quantity
  of all lines (duplicate FIFO-resolved lines drove batches negative)
- attendance delete: restore vacation_used/sick_used for the deleted day
  (in-transaction, clamped at 0)

High:
- auth refresh: terminated sessions (replaced_at only) get a plain 401 —
  the theft branch (family revocation) now fires only on replaced_by_hash
- POST /users strips role_id for non-admin callers (mirrors PUT guard)
- issued-order transition flushes unsaved edits via the full save payload
  when dirty; server contract (items+status in one PUT) pinned
- received-invoices list: usePaginatedQuery + pager (rows 26+ unreachable)
- received-invoice dates: nullableIsoDateString + NaN guard before NAS save
  (Czech-format dates corrupted month/year, orphaned NAS files)
- leave approval skips Czech public holidays and books each calendar year's
  hours against its own balance (mirrors createLeave)

Medium/Low (classes):
- 52 Zod caps aligned to DB column widths across 7 schemas (over-cap input
  500ed at Prisma instead of a Czech 400)
- FK pre-validation: projects update + warehouse receipts/issues return
  Czech 400s instead of P2003 500s
- invoice PDF degrades gracefully when the CNB rate is unavailable
  (recap omitted instead of 500 + lost NAS archival)
- date boundaries: local-day filters (warehouse lists/reports, audit-log),
  @db.Date coercion on invoice dates
- plan updateEntry re-checks the per-cell cap (self-excluding)
- {id} tiebreaks on customers/received-invoices/warehouse-items sorts;
  /items honors the client sort param
- htmlToPdf relaunches once when the shared browser died mid-render
- offer number release parses the year from the document number (cross-year
  finalize+delete left permanent sequence gaps)
- trips/vehicles km fields integer-coerced; AI budget regated to
  settings.company|settings.system; Settings System tab no longer clobbers
  Firma numbering patterns; draft invoices hide the dead PDF button;
  dashboard quick-trip invalidates ["vehicles"]; TOTP secret cap 64;
  audit-log + invoice month buckets day-shift fixes

Docs: corrected the stale "Chromium has no CSS margin-box footers" claim
(html-to-pdf.ts + CLAUDE.md — margin boxes render since Chrome 131); audit
report M3 withdrawn accordingly.

~65 new pinning tests; every finding reproduced RED against the real test
DB before its fix. Suite: 58 files / 634 tests green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-06-12 23:00:19 +02:00
parent 8f74efba97
commit e11765bf0e
56 changed files with 3968 additions and 265 deletions

View File

@@ -0,0 +1,115 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { z } from "zod";
import Fastify from "fastify";
import jwt from "jsonwebtoken";
import prisma from "../config/database";
import { config } from "../config/env";
import receivedInvoicesRoutes from "../routes/admin/received-invoices";
import { CreateReceivedInvoiceSchema } from "../schemas/received-invoices.schema";
/**
* Pinning tests for audit finding H5: Czech-format dates in the received-
* invoice upload metadata must be rejected with a clean Czech 400 BEFORE any
* NAS side effect — "15.03.2026" used to parse to Invalid Date (NaN
* month/year written after the NAS save → 500 + orphaned file) and
* "12.6.2026" silently filed under December (US month-first parsing).
*/
let app: ReturnType<typeof Fastify>;
let adminToken: string;
beforeAll(async () => {
app = Fastify({ logger: false });
await app.register(receivedInvoicesRoutes, {
prefix: "/api/admin/received-invoices",
});
const admin = await prisma.users.findFirst({
where: { roles: { name: "admin" } },
});
if (!admin) throw new Error("Test setup: admin user not found");
adminToken = jwt.sign(
{ sub: admin.id, username: admin.username, role: "admin" },
config.jwt.secret,
{ expiresIn: "15m" },
);
});
afterAll(async () => {
if (app) await app.close();
await prisma.$disconnect();
});
function multipartUpload(meta: Record<string, unknown>) {
const boundary = "----vitestboundary";
const payload = [
`--${boundary}`,
'Content-Disposition: form-data; name="invoices"',
"",
JSON.stringify([meta]),
`--${boundary}`,
'Content-Disposition: form-data; name="files"; filename="test.pdf"',
"Content-Type: application/pdf",
"",
"%PDF-1.4 test",
`--${boundary}--`,
"",
].join("\r\n");
return app.inject({
method: "POST",
url: "/api/admin/received-invoices",
headers: {
Authorization: `Bearer ${adminToken}`,
"content-type": `multipart/form-data; boundary=${boundary}`,
},
payload,
});
}
describe("received-invoice date handling (audit H5)", () => {
const partialSchema = z.array(CreateReceivedInvoiceSchema.partial());
it("schema rejects Czech-format dates", () => {
expect(
partialSchema.safeParse([{ issue_date: "15.03.2026" }]).success,
).toBe(false);
expect(partialSchema.safeParse([{ issue_date: "12.6.2026" }]).success).toBe(
false,
);
});
it("schema strips a trailing time part and normalizes '' to null", () => {
const withTime = partialSchema.safeParse([
{ issue_date: "2098-05-03T00:00:00" },
]);
expect(withTime.success).toBe(true);
if (withTime.success)
expect(withTime.data[0].issue_date).toBe("2098-05-03");
const empty = partialSchema.safeParse([{ issue_date: "" }]);
expect(empty.success).toBe(true);
if (empty.success) expect(empty.data[0].issue_date).toBeNull();
});
it("upload with a Czech-format issue_date returns 400 before any NAS write", async () => {
const res = await multipartUpload({
supplier_name: "Test s.r.o.",
amount: 121,
vat_rate: 21,
issue_date: "15.03.2026",
});
expect(res.statusCode).toBe(400);
expect(res.json().error).toContain("Datum");
});
it("upload with an impossible regex-passing date returns 400, not NaN month", async () => {
const res = await multipartUpload({
supplier_name: "Test s.r.o.",
amount: 121,
vat_rate: 21,
issue_date: "2098-99-99",
});
expect(res.statusCode).toBe(400);
expect(res.json().error).toContain("datum");
});
});