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

@@ -36,6 +36,43 @@ export function applyPattern(
});
}
/**
* Extract the {YYYY}/{YY} year embedded in a generated document number by
* turning its pattern into a capture regex. Returns null when the pattern
* carries no year token or the number doesn't match it (changed pattern,
* legacy data) — callers then fall back to their own year.
*/
export function yearFromGeneratedNumber(
number: string,
pattern: string,
vars: { prefix: string; code: string },
): number | null {
let yearKind: "YYYY" | "YY" | null = null;
const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regexSrc = pattern.replace(
/\{(\w+)\}|[^{]+/g,
(match, key: string | undefined) => {
if (key === undefined) return escapeRe(match);
if (key === "YYYY" && yearKind === null) {
yearKind = "YYYY";
return "(\\d{4})";
}
if (key === "YY" && yearKind === null) {
yearKind = "YY";
return "(\\d{2})";
}
if (key === "PREFIX") return escapeRe(vars.prefix);
if (key === "CODE") return escapeRe(vars.code);
if (/^N+$/.test(key)) return "\\d+";
return escapeRe(match);
},
);
if (yearKind === null) return null;
const m = new RegExp(`^${regexSrc}$`).exec(number);
if (!m) return null;
return yearKind === "YYYY" ? Number(m[1]) : 2000 + Number(m[1]);
}
async function getSettings() {
return prisma.company_settings.findFirst({
select: {
@@ -174,6 +211,14 @@ async function releaseSequence(
: "";
const prefix = type === "offer" ? settings?.quotation_prefix || "NA" : "";
// The number itself embeds the year it was CONSUMED in (the finalize
// year). Prefer that over the caller-supplied year — deleteOffer used to
// pass the created_at year, so a draft created in December and finalized
// in January released against the wrong year's sequence (never matched,
// permanent gap).
const effectiveYear =
yearFromGeneratedNumber(deletedNumber, pattern, { prefix, code }) ?? year;
// Lock the sequence row for the duration of the decrement so a concurrent
// getNextSequence (which also takes FOR UPDATE) can't read-modify-write the
// same row in between — that interleaving could otherwise lose a decrement or
@@ -181,13 +226,13 @@ async function releaseSequence(
await prisma.$transaction(async (tx) => {
const existing = await tx.$queryRaw<Array<{ last_number: number }>>`
SELECT last_number FROM number_sequences
WHERE \`type\` = ${type} AND \`year\` = ${year}
WHERE \`type\` = ${type} AND \`year\` = ${effectiveYear}
FOR UPDATE
`;
if (existing.length === 0) return;
const highestNumber = applyPattern(pattern, {
year,
year: effectiveYear,
prefix,
code,
seq: existing[0].last_number,
@@ -197,7 +242,7 @@ async function releaseSequence(
await tx.$executeRaw`
UPDATE number_sequences
SET \`last_number\` = ${existing[0].last_number - 1}
WHERE \`type\` = ${type} AND \`year\` = ${year}
WHERE \`type\` = ${type} AND \`year\` = ${effectiveYear}
`;
}
});