Files
app/src/__tests__/pagination-tiebreak.test.ts
BOHA e11765bf0e 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>
2026-06-12 23:00:19 +02:00

127 lines
3.9 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll } from "vitest";
import Fastify from "fastify";
import jwt from "jsonwebtoken";
import prisma from "../config/database";
import { config } from "../config/env";
import customersRoutes from "../routes/admin/customers";
import receivedInvoicesRoutes from "../routes/admin/received-invoices";
/**
* Pinning tests for audit finding L3: offset pagination over a non-unique
* sort column needs an `{ id }` tiebreak, or rows sharing the sort value can
* reorder between page queries — duplicating one row and skipping another.
* (Documented determinism convention; siblings issued-orders/trips already
* use compound orderings.)
*
* NOTE: without the tiebreak the misbehavior is probabilistic (MySQL may
* return a stable order by luck), so the paging assertion is primarily a
* REGRESSION GUARD pinning the exactly-once contract.
*/
const N = "tiebreak_test_";
let app: ReturnType<typeof Fastify>;
let adminToken: string;
let customerIds: number[] = [];
let invoiceIds: number[] = [];
async function cleanup() {
await prisma.customers.deleteMany({ where: { name: { startsWith: N } } });
await prisma.received_invoices.deleteMany({
where: { supplier_name: { startsWith: N } },
});
}
beforeAll(async () => {
await cleanup();
app = Fastify({ logger: false });
await app.register(customersRoutes, { prefix: "/api/admin/customers" });
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" },
);
// 5 customers sharing one city (the sort key) so every page boundary
// falls inside a duplicate-key run.
customerIds = [];
for (let i = 0; i < 5; i++) {
const c = await prisma.customers.create({
data: { name: `${N}c${i}`, city: "Tiebreakov" },
});
customerIds.push(c.id);
}
// 5 received invoices sharing supplier_name in one far-future month.
invoiceIds = [];
for (let i = 0; i < 5; i++) {
const inv = await prisma.received_invoices.create({
data: {
supplier_name: `${N}supplier`,
month: 7,
year: 2098,
amount: 100 + i,
currency: "CZK",
vat_rate: 21,
vat_amount: 17.36,
status: "unpaid",
},
});
invoiceIds.push(inv.id);
}
});
afterAll(async () => {
if (app) await app.close();
await cleanup();
await prisma.$disconnect();
});
async function collectPages(urlBase: string, pages: number) {
const seen: number[] = [];
for (let page = 1; page <= pages; page++) {
const res = await app.inject({
method: "GET",
url: `${urlBase}&page=${page}&limit=2`,
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(res.statusCode).toBe(200);
for (const row of res.json().data as Array<{ id: number }>) {
seen.push(row.id);
}
}
return seen;
}
describe("offset pagination exactly-once (audit L3)", () => {
it("customers sorted by a duplicate city appear exactly once across pages", async () => {
const seen = (
await collectPages("/api/admin/customers?sort=city&search=" + N, 3)
).filter((id) => customerIds.includes(id));
expect([...new Set(seen)].sort()).toEqual([...customerIds].sort());
expect(seen.length).toBe(customerIds.length);
});
it("received invoices sorted by a duplicate supplier appear exactly once across pages", async () => {
const seen = (
await collectPages(
"/api/admin/received-invoices?sort=supplier_name&month=7&year=2098",
3,
)
).filter((id) => invoiceIds.includes(id));
expect([...new Set(seen)].sort()).toEqual([...invoiceIds].sort());
expect(seen.length).toBe(invoiceIds.length);
});
});