# Codebase Audit — Fixes > One checkbox per finding from REVIEW_FINDINGS.md, grouped by file with severity. Ticked when the fix is applied AND the gates (tsc -b --noEmit, npm run build, npx vitest run) pass. A finding resolved as intentional/by-design or deferred-needs-migration is annotated and ticked. --- ## PROJECT-LEVEL - [x] [HIGH] No linter anywhere; formatter is unpinned and undeclared - [x] [HIGH] Test sources are never type-checked - [x] [MEDIUM] God-files — a few modules carry far too much - [x] [MEDIUM] ~77 `any` escape hatches erode the strict-mode guarantee - [x] [MEDIUM] Dependency drift + 8 known vulnerabilities (`npm audit`) - [x] [MEDIUM] Dead dependencies (classic multi-AI residue) - [x] [MEDIUM] No committed README; `.env.example` is stale - [x] [LOW] `.gitignore` lets build/junk leak into the working tree - [x] [LOW] Per-request auth does several uncached DB round-trips ## src/server.ts - [x] [LOW] `Function('return import("vite")')()` indirect-eval hack (line 160) to load ESM Vite from the CJS bundle — intentional, brittle. Otherwise clean: plugin order, health check before rate-limit, graceful shutdown. ## src/config/env.ts - [x] [LOW] Global `Date.prototype.toJSON` override (lines 14-22) — documented PHP-compat gotcha; app-wide. Strong boot-time secret/port validation. Clean. ## src/config/database.ts ## src/middleware/security.ts - [x] [LOW] CSP/HSTS prod-only (line 18); `style-src 'unsafe-inline'` required by Emotion; no `report-uri`. Clean. ## src/middleware/auth.ts ## src/utils/response.ts ## src/services/auth.ts - [x] [MEDIUM] Refresh-token rotation rejects replaced/expired tokens but does NOT revoke the token family on detected reuse (lines 273-280) — no breach containment. - [x] [LOW] `loadAuthData` runs on every request (2-3 queries; admin full `permissions.findMany` scan). Strong otherwise (timing-safe, hashed tokens, FOR UPDATE, lockout). ## src/services/ai.service.ts - [x] [LOW] `extractInvoice` `JSON.parse` of model output unguarded (line 351) — low risk with json_schema. Budget/cost ledger correct. ## src/routes/admin/ai.ts - [x] [LOW] `extract-invoices` swallows per-file failure / budget-exhausted-mid-batch into partial success, no truncation signal (lines 130-131). Otherwise clean (guard, parseId/parseBody, per-user ownership, audit). ## src/routes/admin/attendance.ts - [x] [MEDIUM] Many handlers use raw `reply.send` envelope instead of `success()`/`paginated()` (lines 32,108,118,128,142,165-239). - [x] [LOW] `action=project_logs` (line 189) — no ownership check (location path does enforce it); `Number(query.year)` NaN fallbacks. ## src/routes/admin/audit-log.ts - [x] [MEDIUM] `Number(query.user_id)` (line 33) → NaN → Prisma 500 instead of 400. - [x] [LOW] `date_to`+`"T23:59:59"` (line 40) — malformed date → 500. ## src/routes/admin/auth.ts ## src/routes/admin/bank-accounts.ts ## src/routes/admin/company-settings.ts - [x] [LOW] Extra `findFirst` for `has_logo` (302-307, deliberate); request-time `require(package.json)`; PUT `Number()` without NaN re-guard (481). Clean (magic-byte MIME sniff, race-safe create). ## src/routes/admin/customers.ts - [x] [MEDIUM] GET `/` raw `reply.send` envelope (100-104) instead of `paginated()`. Otherwise clean (guards, FK-check before delete, allow-listed sort, parameterized search). ## src/routes/admin/dashboard.ts - [x] [MEDIUM] N+1: `today_plan` per-cell `plan_categories.findUnique` (55-67); bounded but should be one `findMany`. - [x] [LOW] `created_at ?? ""` dead fallback (314). Otherwise clean (gated, Promise.all, parameterized $queryRaw). ## src/routes/admin/leave-requests.ts - [x] [MEDIUM] GET `/` raw `reply.send` envelope (57-61). - [x] [LOW] Approval path drops `reviewer_note` (302-309) though rejection saves it. Otherwise clean (transactional approval, owner+pending cancel, audit). ## src/routes/admin/profile.ts ## src/routes/admin/invoices.ts - [x] [LOW] GET `/` raw `reply.send` envelope (62-66); module-scoped `markOverdueInvoices` throttle can double-run under concurrency (30-39, self-correcting). Otherwise clean. ## src/routes/admin/invoices-pdf.ts - [x] [LOW] `JSON.parse(settings.custom_fields)` (451) has no try/catch → malformed JSON makes whole PDF 500; `save=1` raw envelope (1073); loose typing. Note: `notes` IS DOMPurify+cleanQuillHtml sanitized (521). ## src/routes/admin/offers-pdf.ts - [x] [LOW] `save=1` raw envelope (761); local `cleanQuillHtml` strips only `javascript:` (not data:/vbscript:) — defense-in-depth only (DOMPurify first, 357). Clean. ## src/routes/admin/orders.ts - [x] [MEDIUM] From-quotation multipart parses `fields.quotationId` with raw `parseInt` (123) not schema/parseId. - [x] [LOW] Raw `request.body` casts (203,313); unbounded multipart field/file count (only fileSize limited). Otherwise solid. ## src/routes/admin/orders-pdf.ts - [x] [HIGH] POST renders an official "Order Confirmation" PDF entirely from client-supplied `body.items` (304-312) — `orders.view` holder can fabricate descriptions/prices not reflecting stored data (downloadable, not persisted → limited impact; trust/authz concern). - [x] [LOW] Deprecated `.passthrough()` (30); loose untyped `body.lang`/`applyVat`; `(order as Record).payment_method` cast (387). `notes` sanitized (409). ## src/routes/admin/quotations.ts - [x] [MEDIUM] GET `/:id` second `quotations.findUnique` for lock info right after `getOffer(id)` (123-129) — redundant query per detail view. - [x] [LOW] `(result as any).status` cast (286); empty `catch {}` on NAS PDF delete commented "Non-fatal" but does NOT log (321-323). Lock/heartbeat/unlock scoped to `locked_by=userId` (correct). ## src/routes/admin/received-invoices.ts - [x] [HIGH] JSON single-create computes `vat_amount=(amount*vat_rate)/100` (394-397) — treats GROSS as net, violating gross-VAT convention and INCONSISTENT with multipart (297) + update (467) paths using `vatFromGross`. Same invoice → different VAT by entry path. - [x] [LOW] GET `/` raw envelope (89-93); `stats` `sumCzk` sequential + throws on unknown currency → 500 (135); multipart create loops per-file with no transaction (partial-success on failure). ## src/routes/admin/scope-templates.ts - [x] [MEDIUM] No `logAudit` on ANY mutation (create/update/delete of scope + item templates) — audit-convention violation. - [x] [MEDIUM] DELETE `?action=item&id=X` uses `Number(query.id)` no NaN/existence guard (134-139) → 500; no row-exists/`is_deleted` check. - [x] [LOW] `?action=` dispatch mixes two entities in one handler; `Number(body.id)`/`Number(query.id)` instead of validated ids. ## src/routes/admin/plan.ts - [x] [LOW] `(result.data as any).id`/`(result.oldData as any)` audit casts (256,310,334,361,392,416). Otherwise clean — guards on every route, parseId/parseBody, audit on every mutation, `isAdminLike` reads `roleName`, 92-day range cap. ## src/routes/admin/project-files.ts - [x] [LOW] Folder-create (120) and move (236) read raw `request.body` bypassing parseBody (manually String-coerced). Path traversal delegated to `resolveProjectPath` (sound). Clean. ## src/routes/admin/projects.ts - [x] [MEDIUM] GET `/` raw envelope (44-48). - [x] [LOW] DELETE reads unvalidated body for `delete_files` (182-183); `(result as any).status` casts; POST `/:id/notes` does NOT `logAudit` though note-delete does (126-148) — inconsistent audit. ## src/routes/admin/roles.ts - [x] [HIGH] POST `/` no uniqueness guard on `roles.name` and no admin-only gate — a non-admin `settings.roles` holder can create a role (even named `admin`) and attach ANY permission_ids → privilege escalation (59-98). PUT `/:id` can rewrite the `admin` role's permissions (no `name==="admin"` guard like DELETE) → escalation/lockout (102-138). - [x] [MEDIUM] Role insert + permission assignment in separate transactions (67-73 vs 76-86) — partial failure leaves orphan role. ## src/routes/admin/sessions.ts ## src/routes/admin/totp.ts - [x] [HIGH] `/enable` verifies the new secret with hardcoded SHA1/6/30 (87-94) not `config.totp.*` — config divergence → enrolled secrets verify under different params than login → lockout. - [x] [MEDIUM] `/backup-verify` bcrypt-compares every code, no early-exit on match (307-312) — N bcrypt ops/attempt. - [x] [LOW] `/enable` change-flow (2FA on) needs only a live code, not password (65-76); redundant dynamic re-imports shadow `config` (363-370). ## src/routes/admin/trips.ts - [x] [MEDIUM] GET `/users` (83) guarded only by `requireAuth` — any authenticated user enumerates all active users. Information disclosure. - [x] [MEDIUM] GET `/` raw envelope (73-77). - [x] [LOW] In-handler permission checks run after parseBody; POST create unconditionally sets `vehicle.actual_km=end_km` (244-247) — can regress odometer (PUT/DELETE recompute via MAX). PUT/DELETE ownership checks correct. ## src/routes/admin/users.ts - [x] [LOW] Non-admin escalation guard strips `role_id`/`is_active` (109-114, good); bounded `as Parameters<...>` cast (121); forced logout on pwd change not separately audited. Clean (parseId/parseBody/guard/audit, paginated used). ## src/routes/admin/vehicles.ts - [x] [MEDIUM] GET `/` guarded only by `requireAuth` (15) — any authenticated user lists all vehicles + stats; mutations need `vehicles.manage`. Read should require a view permission. Otherwise clean (single groupBy, delete blocks linked trips). ## src/routes/admin/warehouse.ts - [x] [HIGH] `confirmIssue` locks only the `sklad_issues` row, not item/batch (service:523) — two different draft issues selecting the same FIFO batch confirm concurrently, both read-modify-write `batch.quantity` -> lost update, negative stock, double-issue. Same gap in `confirmInventorySession`. - [x] [HIGH] FIFO batch selection at issue create/update (1496-1499,1622-1625) runs with no lock, persists chosen batch on draft; availability re-checked only at confirm -> wide TOCTOU/oversell. - [x] [HIGH] Reports stock-status/project-consumption/movement-log/below-minimum have NO pagination + per-item N+1 (3 sequential aggregates/item; 629-646,2174-2306). - [x] [MEDIUM] PUT receipts/issues/inventory-sessions do deleteMany+createMany on lines with NO $transaction (1150-1164,1660-1673,2090-2098) -> failure leaves draft with no lines. - [x] [MEDIUM] Attachment save: NAS write then DB insert, no compensating delete (orphan on DB failure); confirm does not verify batch.item_id===line.item_id (wrong item decremented); received_by overwritten at confirm (service:350). - [x] [MEDIUM] 2399-line file bundles 8 sub-entities + inline mid-file multipart register (963) — split per sub-entity. - [x] [LOW] Unvalidated query.status / Number(query.x) filters; pervasive Record-cast querystrings. Every handler guarded, tiers consistent, attachment DELETE ownership-checked — no missing-guard/IDOR. ## src/services/attendance.service.ts - [x] [HIGH] `lockUserRow` uses `tx.$executeRaw` for a bare SELECT ... FOR UPDATE (85) — $executeRaw is for write statements; the punch/switch concurrency lock may not reliably hold. Should be `tx.$queryRaw`. - [x] [HIGH] `getBalances` N+1: one `leave_balances.findFirst` per user in a loop (491), unbounded. - [x] [MEDIUM] `createLeave` books a Dec->Jan range entirely against the start year (getFullYear, 1261); `getStatus` runs 5 independent queries serially. - [x] [LOW] `deleteAttendance` (1694) has no ownership param (unlike updateAttendance); hardcoded 160 vacation default x3; ~1700-line file should be split. ## src/services/audit.ts - [x] [LOW] `safeJsonReplacer` duck-types Prisma Decimal via method presence (14-19) — instanceof would be precise. Failure caught+logged. Clean. ## src/services/exchange-rates.ts - [x] [HIGH] `fetch(url)` (33) has NO timeout/AbortController — a hung CNB endpoint blocks every awaiting caller indefinitely. - [x] [MEDIUM] Global single `rateCacheTime` (14,22-24) — a hit on one key refreshes TTL for ALL keys; date-specific entries can outlive TTL; stale-fallback only checks today. - [x] [LOW] No validation data.rates is an array before iterating (39). ## src/services/invoice-alerts.ts - [x] [MEDIUM] Created-invoice alert amount uses only subtotal (net, 92-95) while received invoices show gross — inconsistent; per-invoice `invoice_alert_log.findUnique` N+1 (81,142). - [x] [LOW] Dead/identical ternary branches (232-239); sequential unguarded create loop can re-fire alerts; escapeHtml omits the apostrophe char. ## src/services/invoices.service.ts - [x] [MEDIUM] Three divergent money/VAT implementations: computeInvoiceTotals (47-74), invoiceTotalWithVat (164-196), stats VAT loop (264-270, no per-line rounding) — inconsistent totals risk. - [x] [MEDIUM] `getInvoiceStats` serializes many toCzk awaits (247-295) — should Promise.all; createInvoice/updateInvoice take body: Record with unchecked `as InvoiceItemInput[]` casts. - [x] [LOW] `deleteInvoice` derives year from invoice_number.split("/")[1] (497) -> wrong sequence released for non-standard numbers; getInvoice returns null not {error,status}; paid_date settable on non-paid invoice (463). ## src/services/leave-notification.ts - [x] [LOW] `formatDate` try/catch ineffective — new Date(invalid) returns Invalid Date, never throws (13-18). Header injection mitigated via sanitizeHeaderValue; send failure logged. Clean. ## src/services/mailer.ts - [x] [MEDIUM] Transport hardcoded to local sendmail /usr/sbin/sendmail (5-9) — Linux-only, no SMTP fallback; on hosts without the binary every send silently fails (console.error only). - [x] [LOW] `to` not validated/sanitized for CRLF (11) — nodemailer guards most. ## src/services/system-settings.ts - [x] [LOW] JSON.parse of vat-rates/currencies (56,61) no shape validation; process-local cache won't propagate cross-instance within 60s TTL. Two empty catches are commented expected-condition guards (OK). Clean. ## src/services/nas-file-manager.ts - [x] [MEDIUM] TOCTOU between resolveProjectPath validation (701-713) and the later fs op on the returned path — a symlink swapped into a path component could bypass the guard (low risk on a trusted share); ".." matched as literal substring (679, contained by prefix check). - [x] [LOW] createProjectFolder sync/non-atomic (idempotent); MIME gate passes type-less files (SVG served as attachment w/ nosniff -> mitigated); collision suffix loop can yield name_1_2. ## src/services/nas-financials-manager.ts - [x] [MEDIUM] Fully synchronous fs over a network share on the request path (39-73,81+) — slow/hung NAS blocks the event loop. - [x] [LOW] isConfigured() does mkdirSync as a predicate side effect (24); saveIssuedInvoicePdf skips isConfigured() (asymmetry). resolveSafePath guard correct. ## src/services/nas-offers-manager.ts - [x] [HIGH] Five fully-silent empty-catch blocks, no log/comment (24,46,59,76,111) — violates never-swallow rule; sibling financials manager logs all of them -> failed offer-PDF save/delete is invisible. - [x] [LOW] deleteOfferPdf readdir/rmdir swallowed (covered above); isConfigured() mkdir side effect. resolveSafePath correct. ## src/services/numbering.service.ts - [x] [MEDIUM] getNextSequence first-of-year INSERT race (61-75) -> @@unique([type,year]) P2002 as 500 instead of retry. - [x] [MEDIUM] releaseSequence (116-158) SELECT-then-UPDATE with no transaction/lock/tx param — concurrent delete+create can lose a decrement or decrement an in-use number (gap/dup). - [x] [LOW] releaseSequence reconstructs highest number from current settings (144-149); changed pattern -> no-op -> gap. ## src/services/offers.service.ts - [x] [MEDIUM] createOffer TOCTOU: isOfferNumberTaken runs BEFORE the tx (162-167), create inside does not re-check -> concurrent dup numbers (orders.service fixed this). - [x] [LOW] deleteOffer never calls deleteOfferPdf -> orphaned PDF on NAS; pervasive any in enrich/list money math. ## src/services/orders.service.ts - [x] [LOW] enrichOrder/getOrder treat projects as array projects?.[0] (60,151) — confirm cardinality; status->project-status sync duplicated verbatim in both update branches (525-538 & 572-585); deleteOrder FK guard runs outside the tx (599,617-634) -> narrow re-intro window. Tx boundaries otherwise correct. ## src/services/plan.service.ts - [x] [MEDIUM] N+1 per mutation: resolvePlanLabels(2q)+resolveCategoryLabel(1q) after each write for the audit description (483-489); bulkCreateEntries multiplies it. - [x] [LOW] createEntry cap check outside any tx (464) — concurrent creates can exceed cap (intentional per comment). UTC date math deliberate. ## src/services/planCategory.service.ts - [x] [LOW] slugifyCategory strips a literal combining-marks range (file-byte fragile); uniqueKey unbounded collision loop + race; sort_order=max+1 outside tx (dup possible). Soft-delete-aware checks correct. ## src/services/projects.service.ts - [x] [LOW] updateProject renames NAS folder after DB commit outside any tx (DB/NAS divergence, failure unlogged at call site, 143); getProject does a synchronous full-base readdirSync on every GET (95); deleteProject removes folder BEFORE the DB delete (218) — inconsistent with orders.service DB-first ordering; Record typing. ## src/services/users.service.ts - [x] [MEDIUM] createUser username/email uniqueness via separate findFirst BEFORE a non-transactional create (116-142) — TOCTOU; duplicate -> unhandled 500 not 409 (updateUser already fixed this in a tx). - [x] [LOW] createUser no in-service min password length (updateUser requires >=8); where: any. Last-admin + self-delete guards correct. ## src/services/warehouse.service.ts - [x] [HIGH] cancelReservation (959-988) has NO row lock and NO transaction — a concurrent confirmIssue fulfilling the same reservation interleaves -> lost fulfillment, double-counted stock. Every other warehouse op locks the parent row; this one was missed. - [x] [MEDIUM] selectFifoBatches orders only by received_at no id tie-break (170) + second-truncated precision -> nondeterministic FIFO; getBelowMinimumItems N+1 (232-261). - [x] [LOW] validateIssueReservationRules N+1; confirmInventorySession negative-diff decrements item_locations independent of consumed batches (drift); surplus enters at unit_price:0 (valuation); dead itemQty/linePrice locals. Lock/FIFO/storno guards otherwise correct. ## src/schemas/common.ts - [x] [HIGH] Contains only parseBody — NO shared coercion helpers despite the convention; the z.union number/string transform idiom is re-implemented ~150x across schemas with no shared home. Root cause of the NaN findings below. - [x] [LOW] Deprecated ZodSchema import (1); Zod 4 prefers z.ZodType. ## src/schemas/ai.schema.ts - [x] [LOW] Message objects plain z.object (not strict); AiBudgetSchema.budget_usd no upper bound (39, but Number.isFinite-guarded). ## src/schemas/attendance.schema.ts - [x] [HIGH] Pervasive unguarded Number(v) transform with NO NaN check on user_id, year, vacation/sick totals, project_id, leave_hours, and all lat/lng/accuracy fields (13-145) — NaN flows to service/Prisma; project_id NaN -> bogus FK. - [x] [MEDIUM] Time fields (arrival/departure/break) unbounded z.string() with no HH:MM regex (45-48 etc.). - [x] [LOW] Plain z.object not strict; minutes not capped at 59. ## src/schemas/auth.schema.ts - [x] [MEDIUM] username/password and TOTP password fields have no .max() (4-5) — unbounded string to bcrypt (file caps backup codes for this exact DoS reason but not password). - [x] [LOW] totp_code .length(6) but not digits-only; plain objects. ## src/schemas/bank-accounts.schema.ts - [x] [MEDIUM] iban/bic/account_number/currency/names all unbounded nullish strings (4-9) — no length caps, no IBAN/BIC/ISO format checks. - [x] [LOW] position unguarded number-from-form (NaN); plain objects. ## src/schemas/customers.schema.ts - [x] [MEDIUM] custom_fields: z.array(z.any()) (11,23) — fully over-permissive, arbitrary nested payload persisted as-is. - [x] [LOW] All address/id strings unbounded, no format checks; plain objects. ## src/schemas/invoices.schema.ts - [x] [LOW] quantity/unit_price throw on NaN (good) but vat_rate/position/order_id/customer_id use the UNGUARDED idiom; status/currency/language free strings (no enum); unbounded text; plain objects. ## src/schemas/leave-requests.schema.ts - [x] [LOW] date_from/date_to min(1) no YYYY-MM-DD regex, no date_to>=date_from cross-check; unbounded notes; plain objects. ## src/schemas/offers.schema.ts - [x] [LOW] Number coercions correctly refine(!isNaN) but re-implement the idiom ~7x; currency/language free strings; unbounded text; plain objects. ## src/schemas/orders.schema.ts - [x] [LOW] Same as offers — refined but duplicated idiom; free currency/language; unbounded text; plain objects. ## src/schemas/plan.schema.ts - [x] [LOW] intFromForm (7-10) is a proper guarded helper but defined locally (belongs in common.ts); project_id coercions (21-102) use the UNGUARDED idiom not intFromForm -> NaN FK; plain objects. ## src/schemas/planCategory.schema.ts ## src/schemas/profile.schema.ts - [x] [MEDIUM] new_password .min(8) no .max() (8); current_password unbounded — unbounded to bcrypt. - [x] [LOW] first_name/last_name no min/max; plain objects. ## src/schemas/projects.schema.ts - [x] [LOW] Create FK fields refine-guard NaN, but Update + quotation_id/order_id use the UNGUARDED idiom (29-44) -> NaN FK on update; status free string (no enum); date strings no regex; plain objects. ## src/schemas/received-invoices.schema.ts - [x] [HIGH] month/year coerce via Number(v) with NO NaN guard AND no range bounds (5-6,53-60) — month not 1-12, year unbounded; flows into the ledger + date logic. - [x] [MEDIUM] amount/vat_rate/vat_amount unguarded idiom (NaN); vat_rate no range bound (negative/>100 accepted) — load-bearing for gross VAT back-calc. - [x] [LOW] Unbounded text; plain objects. ## src/schemas/roles.schema.ts - [x] [LOW] permission_ids: z.array(z.number()) not .int()/positive, no .max() length; name no slug/format; unbounded text; plain objects. ## src/schemas/scope-templates.schema.ts - [x] [LOW] position/id/default_price unguarded number-from-form (NaN); name/title nullish/optional with no .min(1) (nameless template passes); unbounded text; plain objects. ## src/schemas/settings.schema.ts - [x] [MEDIUM] Every numeric setting — incl. security-relevant max_login_attempts, lockout_minutes, max_requests_per_minute (15-62) — uses the unguarded idiom with NO NaN guard and NO range bounds; NaN/0/negative can disable lockout/rate-limit. - [x] [MEDIUM] custom_fields/supplier_field_order: z.array(z.any()); available_vat_rates no int/range; available_currencies no enum. - [x] [LOW] Email-ish fields no .email(); plain objects. ## src/schemas/trips.schema.ts - [x] [HIGH] start_km/end_km/vehicle_id/user_id use the unguarded idiom — NO NaN check; confirmed routes/admin/trips.ts:226 end_km NaN/negative corrupt inventory totals. - [x] [MEDIUM] All FK coercions (item_id/category_id/supplier_id/project_id/location_id/batch_id/reservation_id) unguarded -> NaN FK to Prisma lookups. - [x] [LOW] Supplier email/phone no format check; date strings no regex; unbounded text; plain objects; idiom duplicated dozens of times. ## src/utils/czech-holidays.ts - [x] [LOW] Easter calc parses YYYY-MM-DD as UTC midnight then reads with local getters (50-57) — correct only because Prague is east of UTC; a negative-offset TZ would be a day early (safe today, fragile). Minor formatting duplication. holidayCache bounded by year. ## src/utils/date.ts ## src/utils/encryption.ts - [x] [MEDIUM] Format detection via split(":").length===3 (27-28) — brittle (a malformed TS value falls through to base64 branch). Crypto sound: random IV per encrypt (no reuse), GCM tag verified, raw 32-byte key. A version/prefix tag would be more robust. ## src/utils/html-to-pdf.ts - [x] [MEDIUM] process.env.CHROMIUM_PATH || "/usr/bin/chromium-browser" || "/usr/bin/chromium" (21-24) — third path is dead (second operand always truthy); if only chromium exists, launch fails. Browser lifecycle/finally sound (no leak). Injection safety handled upstream. ## src/utils/pagination.ts - [x] [LOW] sort/search passed through unvalidated (19,22) — trust-boundary note for callers (orderBy field needs an allowlist); page/limit clamping correct. ## src/utils/planAuditDescription.ts ## src/utils/totp.ts - [x] [LOW] console.error logs raw error on decrypt/verify failure (27) — no secret leak; swallow-to-{valid:false} intentional. Correct RFC-6238 (window:1, params from config); replay protection in auth.ts. ## src/types/fastify.d.ts ## src/types/index.ts - [x] [LOW] JwtPayload.role vs AuthData.roleName (51,60) — the documented footgun that invites authData.role==="admin"; no bug here but a hazard. ## prisma/seed.ts - [x] [MEDIUM] main() unconditionally deleteManys ALL role_permissions + permissions (321-322) before re-inserting — prod-destructive if ever misused (custom roles lose all permissions; stale-reconciliation at 351-368 is dead after the wipe). Dev-only by policy. - [x] [LOW] Seeds an admin/admin user hashing the literal "admin" (389) — dev convenience, risk if run on a reachable env. ## scripts/migrate-received-invoices-to-nas.ts - [x] [LOW] Treats saveReceivedInvoice as sync (41) — verify; sets file_data: null after a claimed-success save with no read-back verification (56) — a 0-byte/corrupt write would lose the only DB copy (one-shot migration). ## scripts/rotate-totp-key.ts - [x] [HIGH] Hand-rolled decrypt (6-14) only handles the TS iv:enc:tag format; PHP-legacy base64 secrets (no colon) -> Buffer.from(undefined,'hex') throws inside $transaction with no per-user try/catch (58-65) -> the FIRST legacy secret aborts/rolls back the ENTIRE batch. Should reuse src/utils/encryption.ts dual-format decrypt. - [x] [LOW] Dry-run shows [FAIL] rows for legacy secrets the real run cannot process — operator must not ignore them. ## prisma/schema.prisma - [x] [HIGH] Entire sklad\_\* (warehouse) module declares relations with NO explicit onDelete (780-958) — header->line deletes and master-data deletes get engine-default behavior, inconsistent with the explicit cascade/setNull/restrict used everywhere else; define explicit onDelete (Cascade line->header, Restrict line->master-data). - [x] [MEDIUM] Warehouse document numbers receipt_number/issue_number/session_number (825,877,935) are nullable and NOT unique — unlike every other document-number column (invoice/order/quotation are @unique); two receipts can share a number. - [x] [MEDIUM] invoices.order_id/customer_id, orders.quotation_id/customer_id, quotations.customer_id, project FKs have no explicit onDelete (default Restrict — likely intended but implicit). Several \*\_id are bare Int with no relation/FK -> orphan risk (received_invoices.uploaded_by, quotations.locked_by can point at deleted users). - [x] [MEDIUM] sklad_issues.project_id/issued_by, sklad_receipts.supplier_id/received_by, bank_accounts declare no @@index (MySQL auto-indexes the FK constraint, but non-FK hot filters are uncovered and the schema is inconsistent vs the rest). - [x] [LOW] Most modified_at/updated_at lack @updatedAt (rely on app code -> stale-timestamp footgun); duplicate identical audit_logs created_at indexes (71,73); is_deleted absent on financial/document models (audit_logs compensates); invoice/order/project/quotation status are free strings not Prisma enums; config lists stored as LongText JSON not Json columns. Money is correctly Decimal throughout (good). ## src/admin/ui/Alert.tsx - [x] [LOW] MUI close button gets default English aria-label "Close" amid otherwise-Czech UI (18). Clean otherwise. ## src/admin/ui/AppShell.tsx - [x] [MEDIUM] `setTimeout(()=>logout(),400)` (27) is fire-and-forget, never cleared — fires on an unmounted tree if unmounted within 400ms. - [x] [LOW] Decorative inline SVGs lack aria-hidden. Otherwise clean. ## src/admin/ui/Button.tsx ## src/admin/ui/Card.tsx - [x] [MEDIUM] Always wraps children in CardContent with no opt-out/contentProps — edge-to-edge content (media/table) can't use this primitive. Otherwise clean. ## src/admin/ui/Checkbox.tsx - [x] [MEDIUM] No disabled/name/id/indeterminate/required passthrough — minimal API forces callers to raw MUI. Otherwise clean. ## src/admin/ui/ConfirmDialog.tsx - [x] [MEDIUM] `cancelText` (and `confirmVariant`) not frozen in `shown` while title/message/confirmText/loading are — cancel label can flicker during the close fade. message is plain string (no XSS). Otherwise clean. ## src/admin/ui/DataTable.tsx - [x] [MEDIUM] Mobile card branch (78-173) ignores sortBy/sortDir/onSort — sorting controls vanish on phones with no alternative. - [x] [LOW] Desktop action cells do NOT stopPropagation (237,254-275) — an action button in an `onRowClick` row fires BOTH (potential double-action; HIGH if any table pairs them). `"actions"` column key magically special-cased (undocumented). Status tints correctly channel-alpha. ## src/admin/ui/DateField.tsx - [x] [LOW] Dual-label coexistence (picker label + outer Field); parseISO guarded by isValid. Clean. ## src/admin/ui/EmptyState.tsx - [x] [LOW] icon sized via fontSize:48 — assumes font/SVG-inheriting glyph (an won't scale). Clean. ## src/admin/ui/Field.tsx - [x] [HIGH] `` (24) has NO `htmlFor` and injects no id into children — label not associated with the input (no click-to-focus, screen readers don't announce). System-wide since this is the shared form-label primitive. - [x] [MEDIUM] error/hint not linked via aria-describedby and input gets no aria-invalid (41-49). SwitchField lacks disabled passthrough. ## src/admin/ui/FileUpload.tsx - [x] [LOW] Keys include array index; remove button uses entity glyph with proper aria-label. Clean. ## src/admin/ui/FilterBar.tsx ## src/admin/ui/LoadingState.tsx - [x] [LOW] CircularProgress has no accessible label when `label` omitted (the full-screen AppShell case). Clean otherwise. ## src/admin/ui/Modal.tsx - [x] [MEDIUM] `cancelText` not frozen in `shown` (cancel label flickers on close); DialogContent renders LIVE children (77) so the form body still flashes its cleared state during the fade — the exact issue the freeze targets, unsolved for the body. Otherwise clean. ## src/admin/ui/MonthField.tsx - [x] [LOW] ~90% duplicate of DateField.tsx (low-value to consolidate); parseISO guarded. Clean. ## src/admin/ui/MuiProvider.tsx - [x] [LOW] `defaultMode="dark"` hardcoded (11); verify it agrees with ThemeContext's `data-theme`/`mui-mode` source of truth to avoid a one-frame mismatch. Clean otherwise. ## src/admin/ui/PageEnter.tsx - [x] [LOW] Children keyed by index (animation only); useReducedMotion called before early return (hook order safe). Clean. ## src/admin/ui/PageHeader.tsx ## src/admin/ui/Pagination.tsx ## src/admin/ui/ProgressBar.tsx - [x] [LOW] Determinate LinearProgress has no accessible name (26). ## src/admin/ui/RichText.tsx ## src/admin/ui/Select.tsx - [x] [LOW] `slotProps as {...}` localized sound widening; spread order correct. Clean. ## src/admin/ui/SidebarNav.tsx - [x] [LOW] Logo onError fallback relies on the fallback existing (no infinite loop). `& svg {width:18}` constraint documented; OdinMark overrides via wrapper + 70% !important (verified). Clean. ## src/admin/ui/StatCard.tsx ## src/admin/ui/StatusChip.tsx ## src/admin/ui/Tabs.tsx - [x] [LOW] TabPanel unmounts inactive content with no role="tabpanel"/aria-labelledby wiring (a11y-incomplete). ## src/admin/ui/TextField.tsx ## src/admin/ui/ThemeToggle.tsx ## src/admin/ui/TimeField.tsx - [x] [LOW] Module-level REF Date used read-only by date-fns (safe); validates via isValid. Clean. ## src/admin/ui/index.ts ## src/admin/ui/navData.tsx - [x] [LOW] Non-matchPrefix branch uses bare `pathname.startsWith(item.path)` (no boundary) — fragile if a `/x-foo` route is ever added (items needing exactness set end:true). Verbose inline SVG set. ## src/admin/ui/useDialogScrollLock.ts - [x] [MEDIUM] Module-level lock state — production-safe (balanced [open] dep + cleanup), but a StrictMode/hot-reload double-invoke can transiently skew lockCount. - [x] [LOW] Stale comment references removed base.css (now GlobalStyles.tsx). ## src/admin/pages/Warehouse.tsx - [x] [LOW] Dead/duplicated `MovementRow` type drift (75); redundant per-column `?? 0`; cosmetic isLoading gating. Clean otherwise (read-only). ## src/admin/pages/WarehouseCategories.tsx - [x] [MEDIUM] `sort_order` via `parseInt(...)||0` no radix (308) — drops a legit 0 and truncates "3.9"->3; convention wants Number/NaN-guard. - [x] [LOW] Redundant `saving` state duplicates `submitMutation.isPending`. Broad ["warehouse"] invalidation correct. ## src/admin/pages/WarehouseInventory.tsx - [x] [MEDIUM] `items` column renders `s.items?.length ?? 0` (125) but list endpoint omits items -> always shows 0; should use a \_count. Otherwise clean. ## src/admin/pages/WarehouseInventoryDetail.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (70) precedes `useApiMutation` (72) -> hook-count mismatch crash on permission change. - [x] [LOW] `.../0/confirm` URL fallback is dead (handler guards null). Broad invalidation correct. ## src/admin/pages/WarehouseInventoryForm.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (83) precedes `useApiMutation` (94). - [x] [MEDIUM] `actual_qty` via `Number(e.target.value)` no NaN guard (249) — clearing field -> NaN in payload (receipt/issue forms use parseDecimal). validate() doesn't check qty finite. ## src/admin/pages/WarehouseIssueDetail.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (73) precedes useApiMutation (77,89). - [x] [MEDIUM] Project link uses raw `` (316-330) not RouterLink -> full-page reload, breaks SPA nav. - [x] [LOW] Dead `/0/` URL fallbacks. ## src/admin/pages/WarehouseIssueForm.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (267) precedes useApiMutation/useState (335,347). - [x] [MEDIUM] `confirmIssue` setState(id) then immediately `await mutateAsync`; the url: closure reads pre-update id -> first confirm hits `/0/confirm`. Pass id as mutation variable. - [x] [LOW] Form-seeding effects (238,242) are effect-as-derived-state. ## src/admin/pages/WarehouseIssues.tsx ## src/admin/pages/WarehouseItemDetail.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (157) precedes useApiMutation (164,180). - [x] [MEDIUM] Error-handling effect navigates away (148-153) — effect-as-control-flow (could be a render branch). - [x] [LOW] Form-seed logic duplicated 3x (128/132/248-261); `useModalLock(editing)` (155) locks page scroll for an in-page (non-modal) edit form — likely unintended. ## src/admin/pages/WarehouseItems.tsx ## src/admin/pages/WarehouseLocations.tsx - [x] [LOW] toggleMutation toasts in handler not onSuccess (inconsistent); dead czechPlural ternary. Guard correctly after hooks. Clean otherwise. ## src/admin/pages/WarehouseReceiptDetail.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (97) precedes useApiMutation (101,113,126). - [x] [LOW] Dead `/0/` URL fallbacks; attachment link safe (noopener). Broad invalidation correct. ## src/admin/pages/WarehouseReceiptForm.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (203) precedes useApiMutation/useState (269,281). - [x] [MEDIUM] Same stale-closure confirm bug as IssueForm (307-309) -> `/0/confirm` on first confirm. - [x] [LOW] Uses imperative document.createElement input + hand-rolled dropzone instead of kit FileUpload (620-633). ## src/admin/pages/WarehouseReceipts.tsx ## src/admin/pages/WarehouseReports.tsx - [x] [MEDIUM] Project-consumption & movement-log tabs fetch via raw apiFetch + useState (263-290,386-413) not React Query — results NOT in ["warehouse"] cache, won't refresh on mutations; existing query options unused. - [x] [LOW] Duplicated MovementLogRow type (46); empty `catch {}` -> setData([]) swallows fetch errors (285,408); raw `row.date` not formatDate'd (426). ## src/admin/pages/WarehouseReservations.tsx - [x] [MEDIUM] Create & cancel use raw apiFetch + manual invalidate (170-217) not useApiMutation (broad key correct, but plumbing duplicated). - [x] [LOW] Empty catches don't log; `quantity` via Number() no NaN guard (457) and `NaN<=0` is false so NaN can be submitted. ## src/admin/pages/WarehouseSuppliers.tsx - [x] [MEDIUM] `toggleActive` setState(id) then immediate `await mutateAsync` — url: closure reads null id -> PUT hits the collection root (wrong endpoint) on first toggle. Pass id as mutation variable. - [x] [LOW] Redundant `saving` state. Guard correctly after hooks. Clean otherwise. ## src/admin/pages/Attendance.tsx - [x] [MEDIUM] `calculateBusinessDays` parses YYYY-MM-DD via `new Date()` (UTC midnight) + local `getDay()` (480-488) — can mis-count business days in the evening Prague window. - [x] [LOW] leaveRequestMutation invalidates attendance/leave-requests/users but NOT ["leave"] (303) — approver's pending queue (["leave","pending"]) won't auto-refresh; live clock (676) never ticks; notes synced via effect can clobber unsaved edits (336-340). todayLocalStr used (good). ## src/admin/pages/AttendanceAdmin.tsx ## src/admin/pages/AttendanceBalances.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (171) precedes useApiMutation (173,189). - [x] [LOW] parseFloat on vacation/sick fields -> NaN on empty (770,781,794) into payload. ## src/admin/pages/AttendanceCreate.tsx - [x] [LOW] `leave_hours: parseFloat()` -> NaN on cleared field (190). todayLocalStr used; broad invalidation. Clean otherwise. ## src/admin/pages/AttendanceHistory.tsx - [x] [MEDIUM] ~865-line file with inline print-HTML template + hidden print JSX — split candidate. - [x] [LOW] Duplicates holiday/business-day logic that also exists in attendanceHelpers (84-149). normalizeDateStr used; hooks before guard. Clean otherwise. ## src/admin/pages/AttendanceLocation.tsx - [x] [LOW] Dead LoadingState branch (199 unreachable, `!record` returns null at 187 while pending). Popup via createElement/textContent (no XSS); Leaflet cleanup correct. Clean. ## src/admin/pages/AuditLog.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (185-187) precedes useApiMutation (189). ## src/admin/pages/CompanySettings.tsx - [x] [MEDIUM] ~1503-line file — split candidate (info/banking/numbering/currency-VAT/logo cards). - [x] [MEDIUM] Uses deprecated MUI `inputProps` (1312) — silently ignored in v7 so min/step not applied (rest of file uses slotProps.htmlInput). - [x] [LOW] Doesn't wrap in PageEnter (raw motion.div per card — intentional embedded mode); fieldOrder index logic fragile. Blob cleanup correct. ## src/admin/pages/Dashboard.tsx - [x] [LOW] DashData hand-rolled with `[key]:unknown` index sig + `as DashData` cast (76,88) bypasses query typing; 2FA handlers use raw apiFetch + manual invalidate (179-211) not useApiMutation. getCzechDate used (good); gated sections. Clean otherwise. ## src/admin/pages/InvoiceDetail.tsx - [x] [MEDIUM] ~2243-line file — split candidate (SortableInvoiceRow / paid read-only view / create-edit form). - [x] [MEDIUM] UTC anti-pattern `new Date(...).toISOString().split("T")[0]` for due_date default (494), issue/due/tax dates (645-651) and computedDueDate (818-823) — the latter reaches the saved payload (977), persisting a day-early due date in evening Prague. - [x] [LOW] Editable `notes` state never wired to an input in non-paid mode (only form.notes saved) — confirm intended. DOMPurify correctly applied before the one dangerouslySetInnerHTML (1562) — no XSS. Money math guarded; blob cleanup correct. ## src/admin/pages/Invoices.tsx - [x] [LOW] handleDelete/toggleStatus/handlePdf use raw apiFetch + manual invalidate (broad keys, correct behavior, off-convention); overdue rowSx UTC-vs-local compare off by a day near midnight (506-507, visual only). Clean otherwise. ## src/admin/pages/LeaveApproval.tsx - [x] [HIGH] Rules-of-Hooks: `return ` (158) precedes useApiMutation (160,173). ## src/admin/pages/LeaveRequests.tsx ## src/admin/pages/Login.tsx - [x] [LOW] `verify2FA(loginToken!, ...)` non-null assertion (105) — a null token (server returns requires2FA w/o token) would pass `null!`. Otherwise secure: tokens via useAuth, no persisted token state, TOTP input strips non-digits, autoComplete=one-time-code, renders outside AppShell. ## src/admin/pages/NotFound.tsx ## src/admin/pages/Odin.tsx ## src/admin/pages/OfferDetail.tsx - [x] [HIGH] Heartbeat effect (730) deps omit `isCompleted` though the guard reads it (731) — lock heartbeat keeps running after transition to dokoncena (stale closure). - [x] [MEDIUM] ~2059-line file — split candidate (SortableItemRow / scope-sections / draft logic). - [x] [LOW] `payload: any` (884) and item-update casts; parseInt/parseFloat on qty/price yield NaN on cleared field (rendered until totals guard). Broad invalidation correct; draft parse guarded; blob revoked. ## src/admin/pages/Offers.tsx - [x] [LOW] Expired check uses idiosyncratic `new Date(new Date().toDateString())` (658, functional). Otherwise clean (broad keys, kit, blob revoke, keys). ## src/admin/pages/OffersCustomers.tsx - [x] [LOW] parseInt without radix on `key.split("_")[1]` (239,259,675, harmless decimal). Otherwise clean (custom-field re-key correct, broad invalidation, a11y). ## src/admin/pages/OffersTemplates.tsx - [x] [LOW] openEdit fetches via raw apiFetch (bypasses RQ cache) for on-demand modal. Guard is before a hooks-free body (no violation). Otherwise clean. ## src/admin/pages/OrderDetail.tsx - [x] [CRITICAL] Rules-of-Hooks: 3 useApiMutation (181,187,193) AFTER `return ` (179) — crash when orders.view absent / permission flips. - [x] [LOW] `valid_transitions?.filter(...).length! > 0` (466) misleading non-null assertion. Section rich text DOMPurify-sanitized before dangerouslySetInnerHTML (760) — no XSS. Broad invalidation; blob cleanup. ## src/admin/pages/Orders.tsx - [x] [LOW] vat_rate sent as raw string in JSON create (272, relies on Zod coercion). Otherwise clean — Forbidden return (312) after all hooks; broad invalidation; keys. ## src/admin/pages/PlanWork.tsx - [x] [LOW] Several mutation callbacks use `body: any`/`data: any` (185,395,412,476,491). `isoDate` toISOString().slice(0,10) is correct (Plan UTC convention, not a finding). Forbidden return after hooks; pulse timer cleaned; todayIsoLocal used. Clean otherwise. ## src/admin/pages/ProjectDetail.tsx - [x] [CRITICAL] Rules-of-Hooks: 4 useApiMutation (179,194,203,209) AFTER `return ` (177). - [x] [LOW] formatNoteDate duplicates utils/formatters date logic. Broad invalidation (projects/warehouse); keys. ## src/admin/pages/Projects.tsx - [x] [LOW] List query uses raw `search` not debounced (219) — every keystroke refetches (Offers/Orders debounce). Hooks (useApiMutation 124,173) precede the guard (222) — correct ordering. Broad invalidation; keys. ## src/admin/pages/ReceivedInvoices.tsx - [x] [MEDIUM] `toDateInput` uses `toISOString().split("T")[0]` (453) to seed edit-form dates — forbidden UTC-split (day-early evening Prague). Use normalizeDateStr. - [x] [MEDIUM] ~1237-line file — split candidate (upload modal + edit modal). - [x] [LOW] Render-phase ref mutation `hasLoadedOnce.current=true` (279); loose parseFloat typing (557). VAT-from-gross preserved; broad invalidation; blob cleanup. ## src/admin/pages/Settings.tsx - [x] [HIGH] Rules-of-Hooks: 5 useApiMutation (319,339,354,372,390) AFTER `return ` (315) — useQuery/useMemo/useState are above, mutations are not. - [x] [MEDIUM] ~1354-line file — split candidate (roles / system-settings / system-info). - [x] [LOW] `systemInfo as Record` (679); O(n^2 log n) permission-group sort (1243, negligible). Tab state derived from URL (good); broad invalidation. ## src/admin/pages/Trips.tsx - [x] [HIGH] Rules-of-Hooks: 2 useApiMutation (190,204) AFTER `return ` (188). - [x] [LOW] Dead `[,setLastKm]` state (186, only setter used); parseInt without radix (287,315-316). todayLocalStr used; broad invalidation (trips/vehicles); keys. ## src/admin/pages/TripsAdmin.tsx - [x] [HIGH] Rules-of-Hooks: 2 useApiMutation (236,255) AFTER `return ` (231). - [x] [LOW] handlePrint uses raw printWindow.document.write of app data (344-417) — low XSS surface (React-escaped innerHTML) but fragile; iframe/template safer. Broad invalidation; keys. ## src/admin/pages/TripsHistory.tsx - [x] [LOW] `totals` computed before the Forbidden return (wasteful when unauthorized) — but all hooks precede the return (no violation). Read-only; kit; keys. Clean. ## src/admin/pages/UiKit.tsx ## src/admin/pages/Users.tsx - [x] [HIGH] Rules-of-Hooks: 3 useApiMutation (126,152,162) AFTER `return ` (173). - [x] [LOW] `roles[0]?.id ? ... : ""` default would skip a role id of 0 (never 0 in practice). Shared broad USER_INVALIDATE array (good); self-deactivation guarded; keys. ## src/admin/pages/Vehicles.tsx - [x] [HIGH] Rules-of-Hooks: 3 useApiMutation (121,136,146) AFTER `return ` (162). - [x] [LOW] Raw MUI `` instead of kit StatusChip (264); `select: data as unknown as Vehicle[]` double-cast (100); parseInt without radix (404). Broad invalidation (vehicles/trips); rowInactive; keys. ## src/admin/components/AlertContainer.tsx - [x] [LOW] Stacking offset keyed off array index (15) — removing a middle alert reflows/can overlap with 3+ alerts. Keys use alert.id. Otherwise clean. ## src/admin/components/AttendanceShiftTable.tsx - [x] [LOW] Project-cell key falls back to index when log.id nullish (119); duration math not memoized. Otherwise clean (no any, keys, no effects). ## src/admin/components/BulkAttendanceModal.tsx - [x] [LOW] Select-all label shows "Odznacit vse" when users empty (BulkPlanModal guards this — inconsistent). Otherwise clean. ## src/admin/components/BulkPlanModal.tsx ## src/admin/components/ErrorBoundary.tsx - [x] [LOW] componentDidCatch only console.errors (22) — no telemetry hook. Correct boundary pattern otherwise. ## src/admin/components/Forbidden.tsx ## src/admin/components/OrderConfirmationModal.tsx - [x] [MEDIUM] Local state (step/items/applyVat/lang) never reset on reopen — component is permanently mounted, toggled by isOpen; reopening shows prior step/edits and items captured once via useState(initialItems) go stale. - [x] [MEDIUM] `finally` closes the modal even when onGenerate throws (58-77) — a generation error drops edited items with only a transient toast. - [x] [LOW] Editable rows key={i} — deleting a non-last row shifts indices (focus jumps; data stays correct since controlled). ## src/admin/components/PlanCategoriesModal.tsx - [x] [LOW] Label TextField uncontrolled defaultValue with no key={c.label} (148) — won't re-seed on external rename (color input does add key); inline delete-confirm instead of kit ConfirmDialog. Broad ["plan","dashboard","audit-log"] invalidation correct; onBlur-commit. ## src/admin/components/PlanCellModal.tsx - [x] [MEDIUM] Props onSaveEntry/onUpdateEntry/onSaveOverride/onUpdateOverride typed `any` (77-82) — untyped save payloads on the most bug-prone path. - [x] [LOW] EditForm derives state from `initial` via useState (201-206) relying on parent remount per record (no key reset — fragile if parent swaps entryId same-kind); odd Czech phrasing (415). Discriminated-union mode + kit otherwise strong. ## src/admin/components/PlanGrid.tsx - [x] [LOW] `projects.find(...)` inside per-cell render loop (612-616) O(days*users*cells\*projects) — build a useMemo Map (rarely hit since server embeds label); eachDay/days recomputed every render (not memoized). todayIso uses local Y/M/D (correct); thorough aria-labels. ## src/admin/components/PlanRangeChips.tsx - [x] [LOW] `readonly` prop accepted then discarded via `void readonly` (17) — dead prop (PlanGrid still passes it). className styling intentional (classes defined in PlanGrid root). Otherwise clean. ## src/admin/components/ProjectFileManager.tsx - [x] [MEDIUM] Drag-over has no drag-depth counter — handleDragLeave (377-380) fires on every child boundary -> drop overlay flickers during drag. - [x] [MEDIUM] File ops use raw apiFetch + manual invalidate of sub-key `["projects",id,"files"]` (349-351) not broad ["projects"] (deliberate scope, documented deviation). - [x] [LOW] `catch {}` substitutes a generic toast but never logs the real error (336,408,438,471,508); sequential per-file upload; breadcrumb join breaks if a folder name contains "/". Escape/Enter handling + canManage gating correct. ## src/admin/components/RichEditor.tsx - [x] [LOW] `_delta: any` on the Quill onChange param (91, react-quill-new loose types — could be unknown); useLayoutEffect font-set no-ops if ref not ready (mounts sync in practice). Never injects HTML — consumers DOMPurify-sanitize. No XSS. ## src/admin/components/ShiftFormModal.tsx - [x] [MEDIUM] `leave_hours` via parseFloat (330-331) writes NaN to form state on empty input — serializes to invalid; should fall back to 0 like the Number(...)||0 pattern. - [x] [LOW] Module-level mutable `_logKeyCounter` (20) shared across instances (fragile under StrictMode/concurrent instances) — use a per-instance ref/randomUUID; server-loaded logs may lack \_key -> index-key risk. Derived isWorkType/isCreate + kit otherwise correct. ## src/admin/components/ShortcutsHelp.tsx - [x] [LOW] Entire component is `return null` — dead stub; remove the file + references, or wire it up. ## src/admin/components/dashboard/DashActivityFeed.tsx ## src/admin/components/dashboard/DashAttendanceToday.tsx - [x] [LOW] Key `${u.user_id}-${i}` index-suffixed (75); user_id alone is unique. Clean. ## src/admin/components/dashboard/DashKpiCards.tsx - [x] [LOW] buildKpiCards recomputed every render (124, cheap); framer-motion entrance has no reduced-motion branch (JS-driven animate not stopped by the GlobalStyles CSS reset) — applies to DashQuickActions/DashProfile/DashSessions too. Clean otherwise. ## src/admin/components/dashboard/DashProfile.tsx - [x] [MEDIUM] handleSubmit (175-197) uses raw apiFetch and invalidates NO React Query domain after a profile PUT — anything keyed on user data goes stale. - [x] [LOW] `delete (dataToSave as any).current_password` casts (172-173); magic 300ms sleep before success toast (189); no reduced-motion branch. ## src/admin/components/dashboard/DashQuickActions.tsx - [x] [HIGH] handleTripSubmit (157-176) POSTs a trip via raw apiFetch and NEVER invalidates ["trips"]/["dashboard"] (no useQueryClient imported) — list/dashboard stay stale until manual refetch. - [x] [MEDIUM] `result` from .json() untyped any (96,116,164); last_km assigned into a string field with no String() coercion. - [x] [LOW] Empty catches don't log (104-106,120-122); parseInt without radix. tripDistance derived (good); todayLocalStr used. ## src/admin/components/dashboard/DashSessions.tsx - [x] [LOW] Correctly invalidates ["sessions"]; shared `deleting` flag (one dialog at a time); no reduced-motion branch. Clean. ## src/admin/components/dashboard/DashTodayPlan.tsx - [x] [LOW] key={i} on plans (96, tiny static list); color-mix bgcolor (43, modern-browser only). Clean. ## src/admin/components/odin/InvoiceReviewCard.tsx ## src/admin/components/odin/OdinChat.tsx - [x] [LOW] saveInvoice invalidates ["invoices"] (353) — broad key DOES cover received invoices (keyed ["invoices","received"]), so correct; persist() is fire-and-forget (failure only console.error, user not told history unsaved). Seed/auto-scroll effects are legitimate. Invoice-only guard correct. ## src/admin/components/odin/OdinComposer.tsx - [x] [LOW] `fileRef as RefObject` unnecessary cast (48); Enter-to-send calls onSubmit even when !canSubmit (parent re-guards — no double-send). Clean. ## src/admin/components/odin/OdinMark.tsx ## src/admin/components/odin/OdinSidebar.tsx - [x] [LOW] Conversation row is a clickable (128) — not a button/no role/tabIndex, so not keyboard-focusable (a11y gap); kebab has aria-label. Clean otherwise. ## src/admin/components/odin/OdinThread.tsx - [x] [LOW] Bubble key={i} (174, append-only so stable); content via Typography pre-wrap (no XSS); reduced-motion gated. Clean. ## src/admin/components/odin/types.ts ## src/admin/components/warehouse/ItemPicker.tsx - [x] [MEDIUM] useQuery(warehouseItemListOptions({search: inputValue})) fires on EVERY keystroke with no debounce (30-32) — request spam; useDebounce hook exists. renderOption correctly extracts key (good). ## src/admin/components/warehouse/ReservationPicker.tsx - [x] [MEDIUM] On item/project change, if the selected `value` is no longer in `reservations`, the component doesn't reset/notify the parent — parent can hold a stale reservationId. Redundant Number() casts (41,49). Typed (no any). ## src/admin/AdminApp.tsx - [x] [LOW] No RequireAuth wrapper visible in the router — auth gating delegated to AppShell/pages (a new top-level route outside AppShell would be public by default); Dashboard eagerly imported (not lazy) (13). Clean otherwise. ## src/admin/GlobalStyles.tsx ## src/admin/theme.ts - [x] [LOW] containedPrimary hover/active transform lacks a prefers-reduced-motion guard present on MuiButton.root/MuiOutlinedInput (89-95); iconBadgeSx key cast loses type-safety (248, behavior fine). Clean otherwise. ## src/admin/theme.test.ts - [x] [LOW] Heavy `as any`/`as unknown as ...` to reach theme internals (deliberate test shortcut). Clean. ## src/App.tsx - [x] [LOW] AdminLoader reads data-theme once at render — dark fallback on cold load before ThemeContext sets it (acceptable). Clean otherwise. ## src/main.tsx ## src/vite-env.d.ts ## src/context/ThemeContext.tsx - [x] [MEDIUM] Theme single-source is correct (mui-mode only; legacy boha-theme read-once-then-deleted) BUT the "dark" default is hardcoded twice (here:30 and MuiProvider.tsx:11) — change one without the other and page (MUI) vs toggle desync on first paint; reconcile to one constant. - [x] [LOW] No `storage` event listener — two tabs won't sync theme until reload. View-Transition/flushSync + reduced-motion fallback correct. ## src/admin/context/AlertContext.tsx ## src/admin/context/AuthContext.tsx - [x] [MEDIUM] `apiRequest` (318-350) duplicates the refresh+retry logic of utils/api.ts apiFetch — two parallel 401-retry paths with DIVERGENT behavior (apiRequest ignores abort signals and doesn't set the session-expired flag). Consolidate onto apiFetch. - [x] [MEDIUM] Proactive-refresh timer fires a closure-captured `silentRefresh` (memoized [] + eslint-disable, 117-125); works only because everything is read through refs — fragile cyclic setup. - [x] [LOW] In-flight refresh not cancelled on logout (a resolving refresh could re-setUser); checkSession maps user twice (181-182). Token held in-memory only (secure). Dedup + expires_in proactive refresh otherwise correct. ## src/admin/utils/api.ts - [x] [LOW] Module-singleton `state` with injected getTokenFn/refreshFn couples a module global to React lifecycle (resetApiState for tests); on a 401 with aborted signal returns the 401 response not the 499 sentinel used elsewhere (inconsistent); its refreshPromise dedup is a second single-flight layer alongside AuthContext's. Up-front refresh/abort/FormData handling correct. ## src/admin/utils/attendanceHelpers.ts - [x] [MEDIUM] getTimePart (105-109) uses `new Date(datetime).getHours()` (TZ-dependent) while sibling extractTime parses the string to avoid TZ conversion — can yield a different hour than displayed at DST/offset edges, violating the file's own stated ethos. - [x] [LOW] getLeaveTypeBadgeClass returns badge-\* classes that exist only in AttendanceHistory's print