Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
719d1f2659 | ||
|
|
3787cc4dd0 | ||
|
|
1ee59b54bc | ||
|
|
907ee574e6 | ||
|
|
b51ea2505e | ||
|
|
fd2e613aa5 | ||
|
|
1f2aff8325 | ||
|
|
e11765bf0e |
334
AUDIT-2026-06-12.md
Normal file
334
AUDIT-2026-06-12.md
Normal file
@@ -0,0 +1,334 @@
|
||||
# Codebase Audit — boha-app-ts — 2026-06-12
|
||||
|
||||
## Summary
|
||||
|
||||
| Severity | Count |
|
||||
| ------------ | ----: |
|
||||
| **Critical** | 3 |
|
||||
| **High** | 6 |
|
||||
| **Medium** | 11 |
|
||||
| **Low** | 8 |
|
||||
| **Total** | 28 |
|
||||
|
||||
> 2026-06-12: M3 (offer PDF footer) withdrawn as a false positive after user
|
||||
> verification — see the struck section below. Counts updated 12→11 / 29→28.
|
||||
|
||||
## Methodology
|
||||
|
||||
- **Fan-out discovery:** 27 independent finder passes swept the codebase across domain modules (auth/sessions, attendance/leave, documents — offers/orders/issued-orders/invoices, warehouse, projects, trips/vehicles, plan, users/roles, AI/Odin, settings) and cross-cutting dimensions (Zod-cap-vs-DB-column alignment, date/timezone boundaries, pagination determinism, React Query cache invalidation, transaction atomicity, FK-error→4xx mapping, privilege boundaries).
|
||||
- **Dedupe vs prior backlog:** candidate findings were de-duplicated against the existing audit backlog (`docs/codebase-audit-findings-2026-06-06.md`, `docs/cross-module-consistency-audit-2026-06-09.md`, `REVIEW_FINDINGS.md`). Already-fixed items (e.g. the 2026-06-06 sessions audit-logging finding) and already-tracked duplicates were dropped; only net-new defects survived.
|
||||
- **3-lens adversarial verification:** every surviving finding was independently re-checked through three lenses — (1) **trace-to-refute** (follow the full code path end-to-end and try to break each step), (2) **convention veto** (confirm it genuinely VIOLATES a documented `CLAUDE.md` convention and is NOT one of the deliberate "looks-like-a-bug" decisions: local-time `toJSON`, local-noon `@db.Date` writes, lenient date schemas, net-only documents, gross `received_invoices.amount`, shared `orders.*` permission family), and (3) **executable repro** (a concrete, developer-runnable reproduction with observable wrong output). A finding ships only with three independent `real` verdicts. Findings the convention lens vetoed (e.g. one warehouse over-issue variant whose exact numbers are blocked by an upstream aggregate guard — kept only after a corrected, reachable repro was supplied) were re-scoped, not waved through.
|
||||
|
||||
Order below is by severity, then by blast radius within a severity.
|
||||
|
||||
---
|
||||
|
||||
## CRITICAL
|
||||
|
||||
### C1. Deleting a vacation/sick attendance record never restores the leave balance — `vacation_used` stays permanently inflated
|
||||
|
||||
- **Severity:** Critical
|
||||
- **File:** `src/services/attendance.service.ts:1751`
|
||||
- **Failure scenario:** `createLeave` increments `leave_balances.vacation_used`/`sick_used` when booking leave (lines 1304–1331), but `deleteAttendance` (1751–1772) only runs `prisma.attendance.delete` — it never decrements the balance. `getStatus` (line 246) and `getBalances` (line 530) derive `vacation_remaining = vacation_total - vacation_used` from the stored counter, so cancelling a booked leave by deleting its rows permanently removes entitlement the employee never actually took. The leave-request approval path (`leave-requests.ts`) has the identical asymmetric increment-on-approve / no-decrement-on-delete.
|
||||
- **Repro:**
|
||||
1. As an admin (`attendance.manage`), `POST /api/admin/attendance?action=leave` for user 5, `date_from=2026-07-06`, `date_to=2026-07-10`, `leave_type=vacation`, `leave_hours=8` → creates 5 rows and adds 40h to `vacation_used`.
|
||||
2. Read balances: `vacation_used=40`, `vacation_remaining = total-40`.
|
||||
3. `DELETE /api/admin/attendance/:id` for each of the 5 rows.
|
||||
4. Read balances again: rows are gone but `vacation_used` is still 40 and `vacation_remaining` is still down 40h. Only a manual admin `handleBalances` reset fixes it.
|
||||
- **Pinning test:** Book a 5-day vacation, assert `vacation_used` rose by 40h, delete all 5 attendance rows, then assert `vacation_used` returned to its pre-booking value (fails today: stays 40).
|
||||
|
||||
### C2. `confirmIssue`: duplicate issue lines on the same batch pass per-line validation but decrement cumulatively, driving batch quantity negative (silent over-issue)
|
||||
|
||||
- **Severity:** Critical
|
||||
- **File:** `src/services/warehouse.service.ts:626`
|
||||
- **Failure scenario:** The confirm path validates and decrements stock **per line**, re-reading the batch fresh each iteration with no cross-line running tally and no `if (newBatchQty < 0) throw` guard. Two issue lines for the same item that resolve to the same batch each pass the independent `batch.quantity >= line.quantity` check, then the decrement loop accumulates: line A leaves the batch at 3, line B re-reads 3 and writes `3-5 = -2`, flagging `is_consumed=true`. The negative/consumed batch drops out of `getItemTotalStock` (`is_consumed:false` filter), so the over-issue is silently hidden from all stock totals. No `(issue_id, batch_id)` unique constraint exists on `sklad_issue_lines`.
|
||||
- **Repro (corrected — the single-batch case is blocked by the per-item aggregate guard in `validateIssueReservationRules`; use two batches so the per-item total check passes while one batch still goes negative):**
|
||||
1. Seed item X with two unconsumed batches B1(qty 8, older) and B2(qty 8). Total stock = 16.
|
||||
2. `POST /issues` with two lines, both `item_id=X`, no `batch_id`, each `quantity=5`. `selectFifoBatches` is called once per line against the live DB with nothing persisted, so both resolve to B1; the per-item availability check (16 < 10 is false) passes. Draft stores two lines both `batch_id=B1`.
|
||||
3. `POST /issues/:id/confirm` → 200. B1 validated 8≥5 twice (both see original 8), then decremented to 3, then to `-2` with `is_consumed=true`.
|
||||
4. 10 units issued from a batch that held 8; B1 persists at `quantity=-2`, drops from stock totals — 2 units leave with no accounting trail and FIFO is broken, with no error raised.
|
||||
- **Pinning test:** Confirm an issue containing two same-item lines whose combined quantity exceeds a single resolved batch; assert the confirm is rejected (400) and no batch row is left with `quantity < 0`.
|
||||
|
||||
### C3. `confirmInventorySession` swallows an in-transaction throw with `return` instead of `throw`, committing partial stock writes the route reports as failed
|
||||
|
||||
- **Severity:** Critical
|
||||
- **File:** `src/services/warehouse.service.ts:1275`
|
||||
- **Failure scenario:** The function body is `return prisma.$transaction(async (tx) => { ... })` (line 1108). A single loop over `session.items` interleaves real writes with a throwing op: the surplus branch (diff>0) creates a corrective receipt, receipt line, batch, and upserts `sklad_item_locations`; a later deficit line makes `selectFifoBatches` throw. The catch at line 1275 **returns** `{ error, status: 400 }` from inside the transaction callback. In an interactive Prisma transaction, returning a value (rather than throwing) **commits** — so the surplus item's writes persist while the session→CONFIRMED update (line 1293) is skipped, leaving the session DRAFT. The route sees `"error" in result` and returns HTTP 400 ("nothing changed"). Re-confirming the still-DRAFT session re-runs the loop and re-creates the same surplus batch — repeatable phantom inventory and corrupted valuation on every retry.
|
||||
- **Repro:**
|
||||
1. ItemA exists; ItemB has a location row `quantity=10` but fewer unconsumed batches (documented location/batch drift at lines 1244–1250 — also reproducible by consuming batches between session create and confirm).
|
||||
2. `POST /admin/inventory-sessions` with items ordered `[{ItemA surplus, actual_qty 5}, {ItemB deficit, actual_qty 0}]` (ItemA's line gets the lower id, processed first).
|
||||
3. `POST /admin/inventory-sessions/<id>/confirm` → HTTP 400 "Nedostatečné množství na skladě", BUT ItemA now has a permanent +5 corrective batch + bumped `item_location`, and the session is still DRAFT.
|
||||
4. Re-confirm → another +5 for ItemA, fails on ItemB again. Each retry adds +5 phantom stock while the API reports failure.
|
||||
- **Pinning test:** Confirm an inventory session whose item list has a valid surplus line before an over-deficit line; assert the response is an error AND no `sklad_receipts`/`sklad_batches` rows were created (transaction rolled back) and the session is unchanged.
|
||||
|
||||
---
|
||||
|
||||
## HIGH
|
||||
|
||||
### H1. Terminating one session force-logs-out ALL of the user's sessions on the terminated device's next refresh
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/services/auth.ts:280`
|
||||
- **Failure scenario:** Session termination (`sessions.ts:94-97` DELETE `/:id`, `sessions.ts:124-131` action=all, `profile.ts:98-101` password-change) sets ONLY `replaced_at` (no `replaced_by_hash`, row not deleted). Legitimate rotation (`auth.ts:315-318`) sets BOTH. The reuse-detection condition at `auth.ts:280-282` is `storedToken.replaced_at || storedToken.replaced_by_hash`, evaluated BEFORE the expiry check at line 292 — so a manually-terminated token presented on a later refresh is misclassified as theft and runs `tx.refresh_tokens.deleteMany({ where: { user_id } })` (line 285), wiping every session for that user, including the laptop the user is actively on, plus a false "reuse detected" warning.
|
||||
- **Repro:**
|
||||
1. Log in from two devices → Session A (laptop), Session B (phone), both `replaced_at=null`.
|
||||
2. From the laptop, `DELETE /api/admin/sessions/<B.id>` → B gets `replaced_at` set only.
|
||||
3. After B's access token expires (~15 min), the phone calls `POST /api/admin/refresh` with B's still-present cookie.
|
||||
4. `refreshAccessToken` hits the reuse branch (B's `replaced_at` truthy), deletes ALL of the user's tokens including A. Laptop is silently logged out on its next refresh.
|
||||
- **Pinning test:** Create two refresh-token sessions, terminate one via the sessions DELETE route, present the terminated token to `refreshAccessToken`; assert the OTHER session's row still exists (fails today: it is deleted).
|
||||
|
||||
### H2. `order_items.description` Zod cap (8000) far exceeds DB column `VarChar(500)` → Prisma 500 on long descriptions
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/schemas/orders.schema.ts:12`
|
||||
- **Failure scenario:** `OrderItemSchema.description = z.string().max(8000)` but `order_items.description` is `@db.VarChar(500)` (`schema.prisma:327`). `createOrder`/`updateOrder` map the value straight into `tx.order_items.createMany` with no truncation. A 501–8000 char description passes Zod, overflows the column under MySQL strict mode (P2000), and `createOrder`'s catch only re-maps errors carrying a `status` property — so it surfaces as HTTP 500 "Interní chyba serveru" instead of a clean Czech 400, with the whole order transaction rolled back.
|
||||
- **Repro:** `POST /api/admin/orders` (Content-Type application/json so the manual-JSON branch runs), `items:[{ description: "x".repeat(600), quantity:1, unit_price:100 }]` → HTTP 500 instead of 400; no order persisted. Same on `PUT /api/admin/orders/:id` for an order in `prijata`/`v_realizaci`.
|
||||
- **Pinning test:** `parseBody(OrderItemSchema, { description: "x".repeat(600), ... })` should fail Zod with a 400-class error (fails today: passes, then 500s at Prisma). Fix: `.max(500)`.
|
||||
|
||||
### H3. Issued-order status transition silently discards unsaved item/section edits and marks them clean
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/admin/pages/IssuedOrderDetail.tsx:524`
|
||||
- **Failure scenario:** A `sent` issued order is both editable AND has valid transitions. `handleStatusChange` (line 516) sends ONLY `{ status: newStatus }`; the server's `replaceItems = editable && Array.isArray(body.items)` is false for a status-only payload, so edited items/sections are never persisted. Worse, line 524 calls `markClean({ form, items, sections })` with the in-memory UNSAVED edits, re-baselining the unsaved-changes guard so `isDirty` flips false and the `beforeunload` warning never fires. After the transition the order is `confirmed` → read-only, so the lost edits cannot be re-applied. (Contrast: `OfferDetail`/`InvoiceDetail` do NOT call `markClean` on transition.)
|
||||
- **Repro:** Open a `sent` issued order with `orders.edit`, edit a line item / section / supplier (form dirty), click "Potvrdit" and confirm. The transition succeeds, the edits are silently dropped, and on refetch the items/sections revert to stored values with no warning.
|
||||
- **Pinning test:** Render `IssuedOrderDetail` for a `sent` order, mutate an item, invoke a status transition; assert the PUT payload includes the edited `items` (or that the guard stays dirty / a warning is shown) — fails today.
|
||||
|
||||
### H4. Received-invoices list is paginated server-side (25/page) but the UI sends no `page` param and renders no Pagination control — rows 26+ are permanently hidden
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/admin/pages/ReceivedInvoices.tsx:265`
|
||||
- **Failure scenario:** `receivedInvoiceListOptions` hits `/received-invoices`, which applies `skip`/`take` with `parsePagination`'s default limit of 25. The component builds the query with no `page`/`perPage`, reads only `listQuery.data?.data` (the first 25 rows), and renders NO `<Pagination>`. The "Celkem" footer is sourced from the separate `/received-invoices/list-totals` over the FULL filtered set, so with 26+ rows the displayed total visibly disagrees with the on-screen rows. The sibling issued-invoices tab (`Invoices.tsx`) correctly uses `usePaginatedQuery` + `<Pagination>`.
|
||||
- **Repro:** Seed 26 CZK received invoices in one month. `GET /received-invoices?month=6&year=2026` returns `data.length=25`, `pagination.total=26`; `GET /received-invoices/list-totals?...` returns 26000 CZK. In the UI (Faktury → Přijaté, June 2026) the table shows 25 rows summing to 25000 while the footer shows 26000 — and the 26th invoice is unreachable.
|
||||
- **Pinning test:** With 26 received invoices in a month, assert the page requests page 2 (or renders a pager) and that all 26 are reachable — fails today.
|
||||
|
||||
### H5. Odin invoice import: Czech-format dates silently corrupt month/year (wrong month or NaN) in `received_invoices`
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/admin/components/odin/InvoiceReviewCard.tsx:79`
|
||||
- **Failure scenario:** The review card exposes "Datum vystavení"/"Datum splatnosti" as free-text fields; `OdinChat.saveInvoice` sends the raw string. The multipart schema validates `issue_date` only as `z.string().max(255).nullish()`, so it passes. The route derives `invoiceMonth = new Date(issue_date).getMonth()+1` / `getFullYear()` with no validity guard. `new Date("15.03.2026")` → Invalid Date → `NaN` (day>12); `new Date("12.6.2026")` → December 2026 (wrong month). NAS save (line 410) runs BEFORE the DB create (line 420), so for the NaN case Prisma rejects into the `UnsignedTinyInt`/`UnsignedSmallInt` columns → HTTP 500 with an orphaned NAS file; for day≤12 it silently files under the wrong month/year.
|
||||
- **Repro:** In Odin, edit an extracted invoice's issue date to `15.03.2026` and Save → 500 + orphaned NAS file. Use `12.6.2026` → invoice silently filed under month 12. Equivalent: `POST /api/admin/received-invoices` (multipart) with `issue_date:"15.03.2026"`.
|
||||
- **Pinning test:** `POST /received-invoices` with `issue_date="15.03.2026"` should return a 400 (or normalize) — fails today (500 + NaN write). Fix: use `isoDateString` coercion / validity guard.
|
||||
|
||||
### H6. Leave-request approval charges vacation/sick balance for Czech public holidays that fall inside the range
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/routes/admin/leave-requests.ts:222`
|
||||
- **Failure scenario:** Both the request-creation loop (lines 90–97) and the approval loop (lines 222–244) count business days with a weekend-only filter (`dow !== 0 && dow !== 6`); the file never imports `isHoliday`. So weekday Czech public holidays inside the range are counted as charged leave days, and approval increments `vacation_used`/`sick_used` by `totalBusinessDays * 8` including them. The sibling `attendance.service.createLeave` (line 1270) correctly skips `isHoliday(...)`, and `getBusinessDaysInMonth` excludes holidays from the work fund — so the deduction is a double charge for a day already paid/free.
|
||||
- **Repro:** Employee `POST /api/admin/leave-requests` `{leave_type:"vacation", date_from:"2026-05-01", date_to:"2026-05-09"}` (1.5. and 8.5. are weekday holidays in 2026) → `total_hours=48`. Approver `PUT /.../{id}` `{status:"approved"}` → `vacation_used` grows by 48h instead of 32h; holiday dates are recorded as consumed vacation in `attendance`.
|
||||
- **Pinning test:** Approve a vacation request spanning a weekday public holiday; assert `vacation_used` increased only by the non-holiday business hours (fails today: includes the holiday).
|
||||
|
||||
---
|
||||
|
||||
## MEDIUM
|
||||
|
||||
### M1. Invoice date fields accept arbitrary strings and write a day early to `@db.Date` when a datetime value is submitted
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/services/invoices.service.ts:533`
|
||||
- **Failure scenario:** `CreateInvoiceSchema`/`UpdateInvoiceSchema` type `issue_date`/`due_date`/`tax_date`/`paid_date` as plain `z.string().max(255).nullish()` (not `isoDateString`). `createInvoice`/`updateInvoice` do `new Date(String(...))` straight into the `@db.Date` columns. A round-tripped API value like `"2025-03-15T00:00:00"` (the `toJSON` override emits local time, no `Z`) parses as local Prague → `2025-03-14 22:00 UTC` → Prisma truncates to `2025-03-14`. The invoice then also lands in the wrong month bucket in `getInvoiceStats`/`buildInvoiceWhere`. Every other `@db.Date`-writing module uses `isoDateString` (which slices the time off); invoices is the lone outlier.
|
||||
- **Repro:** `POST /api/admin/invoices` with `issue_date:"2025-03-01T00:00:00"` → DB stores `2025-02-28`; `GET .../stats?month=3&year=2025` excludes it and inflates February.
|
||||
- **Pinning test:** Create an invoice with `issue_date="2025-03-01T00:00:00"`; assert the stored date is `2025-03-01` (fails today: `2025-02-28`). Fix: `isoDateString.nullish()`.
|
||||
|
||||
### M2. `order_items.unit` Zod cap (255) exceeds DB column `VarChar(20)` → Prisma 500 on long unit strings
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/schemas/orders.schema.ts:15`
|
||||
- **Failure scenario:** `unit: z.string().max(255)` vs `order_items.unit @db.VarChar(20)` (`schema.prisma:330`). A 21–255 char unit passes Zod, overflows the column (P2000), and surfaces as 500 (the create catch only re-maps `status`-bearing errors; update has no try/catch). The sibling offers/issued-orders schemas correctly use `.max(20)`.
|
||||
- **Repro:** `POST /api/admin/orders` (JSON) `items:[{ description:"Test", quantity:1, unit_price:100, unit:"abcdefghijklmnopqrstuvwxyz" }]` → HTTP 500 instead of 400. (The MUI form enforces `maxLength:20` client-side, so this is an API/non-browser vector.)
|
||||
- **Pinning test:** `parseBody(OrderItemSchema, { unit: "x".repeat(21), ... })` should 400 at Zod — fails today. Fix: `.max(20)`.
|
||||
|
||||
### ~~M3. Offer PDF page footer ("Strana X z Y") never renders~~ — WITHDRAWN 2026-06-12 (false positive)
|
||||
|
||||
- **Status:** **Withdrawn** — user verified the footer DOES render in production.
|
||||
- **Why the audit got it wrong:** the finding (and all three verification lenses) trusted the repo's own documentation — the `html-to-pdf.ts:68-74` comment and the CLAUDE.md line "Chromium has no CSS margin-box footers". That fact has been stale since **Chrome 131 (Nov 2024), which implemented CSS `@page` margin boxes**; the project runs Puppeteer 24.40 (bundled Chrome 146 locally) and prod renders with system Chromium 149, both far past 131, so the offer's `@bottom-center { counter(page) }` footer renders fine. No lens rendered an actual PDF — documentation poisoning, not a code bug.
|
||||
- **Real follow-up (doc-only, Low):** correct the outdated claim in `html-to-pdf.ts` and CLAUDE.md so future work doesn't repeat this; the `footerTemplate` mechanism and the CSS margin-box mechanism are now BOTH valid, coexisting approaches.
|
||||
|
||||
### M4. `customer_order_number` Zod cap (255) exceeds DB column `VarChar(100)` → Prisma 500
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/schemas/orders.schema.ts:54`
|
||||
- **Failure scenario:** `customer_order_number: z.string().max(255)` vs `orders.customer_order_number @db.VarChar(100)` (`schema.prisma:356`). A 101–255 char value passes Zod, overflows the column (P2000 under strict mode), and surfaces as 500 instead of 400 (no P2003/P2000 mapping; create catch only handles `status`-bearing errors).
|
||||
- **Repro:** `POST /api/admin/orders` (JSON) `{ customer_order_number: "A".repeat(150), currency:"CZK", language:"cs", status:"prijata" }` → HTTP 500; no order created. Same on `PUT /api/admin/orders/:id`.
|
||||
- **Pinning test:** `parseBody(CreateOrderSchema, { customer_order_number: "A".repeat(150), ... })` should 400 — fails today. Fix: `.max(100)` on both schemas.
|
||||
|
||||
### M5. Foreign-currency invoice PDF returns HTTP 500 (and fails to archive) when the CNB rate lookup throws
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/invoices-pdf.ts:411`
|
||||
- **Failure scenario:** For a EUR invoice, `const cnbRate = isForeign ? await getRate(currency, issueDateStr) : 1.0` is unguarded. When CNB is unreachable and no cached entry exists for the issue date, `getRate` throws "Nepodařilo se získat aktuální kurzy z ČNB", which propagates to the route's catch and returns the 500 error page — blocking BOTH preview and NAS archival, even though the rate only feeds the cosmetic CZK-conversion footnote. Sibling consumers (`received-invoices` stats, `ai-tools`) wrap `toCzk` and degrade per-row; the PDF path has no fallback.
|
||||
- **Repro:** EUR invoice with a back-dated/never-fetched issue date, CNB unreachable → `GET /api/admin/invoices-pdf/:id` (preview) or `?save=1` (archive) returns 500; the `save=1` archival is silently swallowed client-side, leaving no NAS copy.
|
||||
- **Pinning test:** Mock `getRate` to throw, render a foreign-currency invoice PDF; assert a non-error response (PDF rendered with the conversion line omitted) — fails today (500).
|
||||
|
||||
### M6. `updateProject` sets FK fields with no existence check → FK violation 500
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/services/projects.service.ts:115`
|
||||
- **Failure scenario:** `updateProject` writes `customer_id`/`responsible_user_id`/`quotation_id`/`order_id` straight into `prisma.projects.update` with only int coercion and no `findUnique`. The FKs are `onDelete: Restrict`, so a non-existent id raises P2003 → generic 500. `createProject` validates `customer_id`/`responsible_user_id` and returns clean Czech 400s; the update path is the inconsistent gap.
|
||||
- **Repro:** `PUT /api/admin/projects/1` `{ "customer_id": 999999 }` → HTTP 500 "Interní chyba serveru" instead of "Zákazník nenalezen" 400. Same for the other three FK fields.
|
||||
- **Pinning test:** `PUT /projects/:id` with a non-existent `customer_id`; assert a 400 with a Czech "nenalezen" message — fails today (500). Fix: mirror `createProject`'s existence checks.
|
||||
|
||||
### M7. Date-range filters/reports exclude the whole `date_to` day (`lte` against UTC-midnight) — inclusive end date silently drops same-day records
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/warehouse.ts:1038`
|
||||
- **Failure scenario:** Receipts/issues filters and the project-consumption / movement-log reports build `created_at: { lte: new Date(date_to) }`. `new Date("2026-06-12")` parses as UTC midnight = 02:00 Prague; `created_at` is `@db.DateTime(0)` storing local-time instants, so a receipt at 09:00 Prague (07:00Z) is `> 00:00Z` and excluded. The entire requested end day disappears from filtered lists and report totals.
|
||||
- **Repro:** Confirm a receipt today at 09:00 Prague. `GET /admin/warehouse/receipts?date_from=2026-06-12&date_to=2026-06-12` returns zero rows. Reports for a period ending 2026-06-12 under-report the last day.
|
||||
- **Pinning test:** Create a same-day receipt at 09:00 local, filter `date_to` = that date; assert the receipt is returned — fails today. Fix: half-open `lt utcMidnightOfLocalDay(date_to + 1 day)`.
|
||||
|
||||
### M8. POST/PUT receipts & issues 500 on nonexistent or deleted FK ids instead of a clean Czech 400
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/warehouse.ts:1117`
|
||||
- **Failure scenario:** The receipts/issues create+update handlers write rows directly with no FK-existence pre-check and no try/catch; schemas only int-coerce ids. A deleted/nonexistent `supplier_id`/`location_id`/`item_id`/`project_id`/`batch_id` raises P2003/P2025 → generic 500. The document modules (offers/orders/issued-orders) and `trips.ts` all pre-validate FK existence precisely to avoid this; warehouse omits the guard.
|
||||
- **Repro:** `POST /receipts` `{ items:[{ item_id: 99999999, quantity:1, unit_price:10 }] }` → 500. `POST /issues` `{ project_id: 99999999, items:[{ item_id:<in-stock>, quantity:1 }] }` → 500. `POST /issues` with a valid item + nonexistent explicit `batch_id` → 500.
|
||||
- **Pinning test:** `POST /receipts` with a nonexistent `item_id`; assert a 400 ("Položka nenalezena") — fails today (500).
|
||||
|
||||
### M9. `updateEntry` never re-checks the per-cell cap, so expanding an entry's range pushes a day past `MAX_RECORDS_PER_CELL` and silently hides existing records
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/services/plan.service.ts:597`
|
||||
- **Failure scenario:** `createEntry`/`bulkCreateEntries`/`createOverride` all guard the per-cell cap of 3 via `assertEntryCapAvailable`, but `updateEntry` does not. Expanding an entry's `date_from`/`date_to` onto a day that already holds 3 active entries succeeds, producing 4. `resolveCell`/`resolveGrid` cap display at 3 (newest-first), so the oldest entry silently vanishes from the grid while remaining active in the DB.
|
||||
- **Repro:** Create 3 active entries on 2099-07-01 for user 5; create a 4th on 2099-07-02; `PATCH /plan/entries/<4th>` `{ date_from:"2099-07-01", date_to:"2099-07-01" }` → 200; the grid for that day now shows only 3 of the 4 entries.
|
||||
- **Pinning test:** Fill a day to the cap, then `PATCH` another entry to overlap that day; assert the update is rejected with the cap error — fails today.
|
||||
|
||||
### M10. `POST /users` does not strip `role_id` for non-admins — a `users.create` holder can grant any non-admin role
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/users.ts:63`
|
||||
- **Failure scenario:** The POST handler forwards `role_id` straight to `createUser`; `createUser` only rejects the literal `admin` role. The PUT handler explicitly strips `role_id`/`is_active` for non-admin callers ("Privilege-escalation guard"), so create is an inconsistent escalation surface: a `users.create` holder can mint an account on any high-privilege non-admin role (e.g. one bundling `settings.roles` or `users.edit`) the caller itself lacks. Violates the documented "Role-management writes are admin-only and re-checked" rule.
|
||||
- **Repro:** As account M with only `users.create`, `POST /api/admin/users` `{ ..., role_id: N }` where N is a non-admin role bundling `settings.roles`/`users.edit` → 201; the new account holds permissions M never had.
|
||||
- **Pinning test:** As a non-admin `users.create` caller, POST a user with a privileged `role_id`; assert the created user's role is NOT the privileged one (role stripped, as on PUT) — fails today.
|
||||
|
||||
### M11. `route_from`/`route_to` Zod cap (255) exceeds DB column `VarChar(100)` — 500 or silent truncation
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/schemas/trips.schema.ts:17`
|
||||
- **Failure scenario:** `route_from`/`route_to` cap at `.max(255)` (create lines 17–18, update 29–30) vs `trips.route_from/route_to @db.VarChar(100)` (`schema.prisma:668-669`). The route writes `String(body.route_from)` directly. A 101–255 char route passes Zod, then either 500s (P2000 strict mode, no global Prisma mapping) or silently truncates to 100 chars (data loss). The frontend TextFields have no `maxLength`, so the UI triggers it too.
|
||||
- **Repro:** `POST /api/admin/trips` with a 150-char `route_from` → 500 (or truncated 201). Same on `PUT`.
|
||||
- **Pinning test:** `parseBody(CreateTripSchema, { route_from: "x".repeat(101), ... })` should 400 — fails today. Fix: `.max(100)`.
|
||||
|
||||
### M12. Shared Puppeteer browser disconnecting mid-render fails concurrent PDF requests (no re-acquire/retry)
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/utils/html-to-pdf.ts:92`
|
||||
- **Failure scenario:** `getBrowser()` returns the cached module-level browser after a point-in-time `connected` check; `htmlToPdf` immediately does `b.newPage()` with no re-check. Two concurrent renders capture the same handle; if Chromium crashes (OOM/killed) after the guard, both reject. A's finally nulls the shared handle out from under B. Both return 500 even though an immediate retry would relaunch and succeed — there is no re-acquire/retry wrapper.
|
||||
- **Repro:** Fire two simultaneous `GET /api/admin/orders-pdf/5` (always renders, no NAS short-circuit), then `pkill -9 chrome` during the render window → both requests 500; the next request succeeds.
|
||||
- **Pinning test:** Stub the cached browser so `connected` is true at guard time and false at `newPage` time; assert `htmlToPdf` re-acquires and resolves (or both concurrent calls succeed on retry) — fails today.
|
||||
|
||||
---
|
||||
|
||||
## LOW
|
||||
|
||||
### L1. Client-supplied TOTP secret up to 255 chars overflows `VarChar(255)` after encryption, yielding a 500 instead of a 400
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/schemas/auth.schema.ts:30`
|
||||
- **Failure scenario:** `TotpEnableSchema.secret` caps at `.max(255)` on the plaintext, but the stored value is the AES-256-GCM ciphertext (`base64(IV[12] + ciphertext + tag[16])`), which exceeds 255 chars for any plaintext over ~164 chars. `users.totp_secret` is `@db.VarChar(255)`. The pre-write `totp.validate` does not bound secret length, and the attacker controls both `secret` and `code`, so a long secret reaches the write → P2000 → 500 (strict mode) or silent ciphertext truncation that permanently locks the account out.
|
||||
- **Repro:** Authenticated, 2FA-not-enabled user: generate a 250-char base32 secret + matching TOTP code, `POST /api/admin/totp/enable` with the correct password → 500 (or corrupted secret).
|
||||
- **Pinning test:** Enable TOTP with a 250-char secret; assert a 400 (not 500) — fails today. Fix: `.max(64)` (real secrets are 16–32 chars).
|
||||
|
||||
### L2. Offer number sequence is never released on delete when created and finalized in different calendar years
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/services/offers.service.ts:522`
|
||||
- **Failure scenario:** `generateOfferNumber` keys on `new Date().getFullYear()` (finalize year), assigning e.g. `2026/NA/001`. `deleteOffer` derives the release year from `existing.created_at.getFullYear()` (2025) and calls `releaseOfferNumber(2025, "2026/NA/001")`; `releaseSequence` reconstructs the highest as `2025/NA/<n>`, which never equals `2026/NA/001`, so the `deletedNumber === highestNumber` guard is false and the 2026 counter keeps a permanent gap. `invoices.service.ts` solves the same problem correctly by parsing the year out of the document number.
|
||||
- **Repro:** Create a draft `2025-12-30`, finalize it `2026-01-02` → `2026/NA/001`. Delete it → next finalized 2026 offer is `2026/NA/002` (gap; no `2026/NA/001`).
|
||||
- **Pinning test:** Create a draft in year Y, finalize+delete it in year Y+1; assert the Y+1 sequence counter was released — fails today. Fix: parse the year from the assigned number.
|
||||
|
||||
### L3. `customers` list paginates with non-unique sort columns and no `id` tiebreak → unstable pagination
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/routes/admin/customers.ts:54`
|
||||
- **Failure scenario:** `orderBy: { [sortField]: order }` over allow-listed fields (`name`/`city`/`country`/`company_id`, all non-unique) with no `{ id }` tiebreak, used with offset pagination. Rows sharing a sort-key value that straddle a page boundary can reorder between the page-1 and page-2 queries, duplicating one and skipping another. Violates the documented determinism rule; siblings (`issued-orders.ts`, `trips.ts`) use compound `[..., { id }]` orderings. (The same defect exists at `received-invoices.ts:144`.)
|
||||
- **Repro:** Seed customers with a shared `city` straddling a `limit=2` boundary; page through `?sort=city` and observe a customer appearing on two pages while another is skipped.
|
||||
- **Pinning test:** Paginate a sort over duplicate-`city` customers; assert the concatenated pages contain every customer exactly once — fails today. Fix: `orderBy: [{ [sortField]: order }, { id: order }]`.
|
||||
|
||||
### L4. Invoice month navigation does not reset the page index → switching to a sparser month shows an empty table
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/admin/pages/Invoices.tsx:244`
|
||||
- **Failure scenario:** `prevMonth`/`nextMonth` mutate `statsMonth`/`statsYear` but never `setPage(1)` (unlike the status/search handlers). The list query keys on `page` + month, and the server never clamps page to `total_pages`, so paging to page 3 of a busy month then switching to a 1-page month requests `?page=3&month=...` and gets an empty `data` array — empty table for a populated month, with the pager reading "3 of 1".
|
||||
- **Repro:** Open a month with 60+ invoices, go to page 3, click the previous-month chevron to a month with a handful → empty "Zatím nejsou žádné faktury" table. API: `GET /api/admin/invoices?page=3&month=<sparse>&year=<y>` returns `data:[]` with non-zero `total`.
|
||||
- **Pinning test (component):** With `page=3`, fire `nextMonth`; assert `page` resets to 1 — fails today.
|
||||
|
||||
### L5. Issued-orders sub-list keeps its page index when the parent Orders page changes month → empty list for sparser months
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/admin/pages/IssuedOrders.tsx:135`
|
||||
- **Failure scenario:** `IssuedOrders` receives `month`/`year` as props and holds `page` in local state with no effect/key resetting it on prop change (the child is not keyed by month/year, so it doesn't remount). Paging to page 2 of a busy month then moving the parent to a sparse month requests page 2 of the new month → empty `data` → "Zatím žádné vydané objednávky." for a month that has orders on page 1.
|
||||
- **Repro:** Objednávky → Vydané: navigate to a month with ≥26 issued orders, click page 2, then use the parent month chevron to a month with 1–25 orders → empty sub-list. API equivalent: `GET /api/admin/issued-orders?page=2&month=<1..25 orders>&year=<y>` → `data:[]` with non-zero `total`.
|
||||
- **Pinning test (component):** With `page=2`, change the `month` prop; assert `page` resets to 1 (or is clamped to `total_pages`) — fails today.
|
||||
|
||||
### L6. Settings "System" tab save clobbers freshly-saved "Firma" numbering patterns with stale values
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/admin/pages/Settings.tsx:297`
|
||||
- **Failure scenario:** Both tabs edit the same singleton `company_settings` row via `PUT /company-settings`. `sysForm` carries `offer_number_pattern`/`order_number_pattern`/`invoice_number_pattern` (populated once, gated by a never-reset `sysFormInitialized` flag). After editing numbering in the Firma tab (which invalidates `["company-settings"]`), `sysForm` stays stale; saving the System tab sends the whole stale form, and the backend applies every `!== undefined` field, silently reverting the Firma-tab change.
|
||||
- **Repro:** Init the System tab; in the Firma tab change `offer_number_pattern` and save; return to System and save any unrelated field → `offer_number_pattern` reverts to its pre-edit value, with a success toast.
|
||||
- **Pinning test:** PUT the offer pattern, then PUT a stale sysForm carrying the old pattern; assert the offer pattern is NOT reverted (or that System-tab saves omit the numbering fields) — fails today.
|
||||
|
||||
### L7. `start_km`/`end_km` accept decimals but DB columns are `Int` — non-integer odometer reading errors or truncates
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/schemas/trips.schema.ts:15`
|
||||
- **Failure scenario:** `start_km`/`end_km` use `nonNegativeNumberFromForm` (only `Number.isFinite && >=0`, no integer refine), but the columns are `Int`. A decimal passes Zod, reaches the `Int` column → Prisma validation 500 or MySQL truncation (corrupting the reading and derived distance, propagated into `vehicles.actual_km`). Same mismatch for `vehicles.initial_km`/`actual_km`. The UI's `parseInt` is used only for the distance widget, not the submitted payload, so the browser is vulnerable too.
|
||||
- **Repro:** `POST /api/admin/trips` `{ vehicle_id, trip_date:"2098-01-15", start_km:100.5, end_km:1200.7, route_from:"A", route_to:"B" }` → 500 (or truncated values).
|
||||
- **Pinning test:** `parseBody(CreateTripSchema, { start_km: 100.5, ... })` should 400 — fails today. Fix: `nonNegativeIntFromForm` for the four km fields.
|
||||
|
||||
### L8. AI monthly budget control: severity-mismatched permission, date asymmetry, dead UI button, currency overflow, audit-log boundary (grouped low-severity cluster)
|
||||
|
||||
These five independently-confirmed low-severity findings share the "minor blast radius / narrow trigger" profile. Each is real and pinnable.
|
||||
|
||||
- **L8a. Company-wide AI monthly budget is mutable by any `ai.use` holder (not admin/settings).** `src/routes/admin/ai.ts:58`. `PUT /api/admin/ai/budget` is gated only by `requirePermission("ai.use")`, an ordinary grantable permission. Setting `budget_usd=0` makes `assertBudgetAvailable` return 402 for everyone (admins included) → company-wide AI DoS; setting `1000000` removes the cost cap. The parallel `company-settings` writes are gated behind `settings.company`/`settings.system`.
|
||||
- **Repro:** As any `ai.use` holder, `PUT /api/admin/ai/budget {"budget_usd":0}` → all `ai/chat` and `extract-invoices` calls 402.
|
||||
- **Pinning test:** Call `PUT /ai/budget` as a non-admin `ai.use`-only user; assert 403 — fails today. Fix: gate behind `settings.company`/admin.
|
||||
|
||||
- **L8b. Audit-log `date_from` filter boundary shifted ~2h vs `date_to` (UTC vs local parsing).** `src/routes/admin/audit-log.ts:46`. `from = new Date(date_from)` parses as UTC midnight (02:00 Prague), while `to = new Date(date_to + "T23:59:59")` parses as local — so events between 00:00 and 02:00 Prague on the from-date are silently excluded.
|
||||
- **Repro:** `GET /api/admin/audit-log?date_from=2026-06-12&date_to=2026-06-12` omits a row logged at 01:30 Prague that day.
|
||||
- **Pinning test:** Insert an audit row at 01:30 local, filter for that day; assert it's returned — fails today.
|
||||
|
||||
- **L8c. Draft invoice shows a non-functional "Zobrazit fakturu" PDF button that always errors.** `src/admin/pages/InvoiceDetail.tsx:1805`. The button render guard lacks the `status !== "draft"` check that `OfferDetail`/`IssuedOrderDetail` have; clicking it on a draft opens a blank tab, 404s `/file`, closes the tab, and toasts an error.
|
||||
- **Repro:** Open a draft invoice, click "Zobrazit fakturu" → blank tab flash + "PDF soubor nenalezen" toast.
|
||||
- **Pinning test:** Render `InvoiceDetail` for a draft; assert the PDF button is not rendered — fails today. Fix: add `&& invoice.invoice_number` (or non-draft) to the guard.
|
||||
|
||||
- **L8d. Odin "Měna" / received-invoice currency over 3 chars 500s the save (`VarChar(3)` vs schema `max(20)`).** `src/components/odin/InvoiceReviewCard.tsx:67` / `src/schemas/received-invoices.schema.ts:11`. A free-text currency like "Koruna" passes Zod (`max(20)`) but overflows `received_invoices.currency @db.VarChar(3)` (P2000 → 500), AND because the NAS write precedes the DB create, the uploaded file is orphaned. The same module's `description` (`max(8000)` vs `VarChar(500)`) and `invoice_number` (`max(255)` vs `VarChar(100)`) are also misaligned.
|
||||
- **Repro:** Save an Odin invoice with `currency:"Koruna"` → 500 + orphaned NAS file. Equivalent: `POST /received-invoices` multipart with `currency:"Koruna"`.
|
||||
- **Pinning test:** `parseBody(CreateReceivedInvoiceSchema, { currency:"Koruna", ... })` should 400 — fails today. Fix: `currency .max(3)`, `description .max(500)`, `invoice_number .max(100)`.
|
||||
|
||||
- **L8e. Warehouse supplier `ico`/`dic` Zod caps (255) exceed `VarChar(20)` columns.** `src/schemas/warehouse.schema.ts:34`. A >20-char `ico`/`dic` (bad paste) passes Zod and 500s at Prisma. Low realism (real IČO=8 digits) but a genuine 500-vs-400 defect; the customers schema (`company_id`/`vat_id`) shares it.
|
||||
- **Repro:** `POST /api/admin/warehouse/suppliers` `{ name:"Test", ico:"123456789012345678901" }` → 500.
|
||||
- **Pinning test:** `parseBody(CreateSupplierSchema, { ico:"x".repeat(21), ... })` should 400 — fails today. Fix: `.max(20)`.
|
||||
|
||||
> **Adjacent uncited Zod-cap mismatches confirmed during verification** (same bug class, fix alongside the above so the gap is closed once): invoice line-item `description` (`max(8000)` vs `VarChar(500)`) and `unit` (`max(255)` vs `VarChar(20)`) — `src/schemas/invoices.schema.ts:13,16`, **High** blast radius (whole invoice save rolls back); invoice bank/payment fields `payment_method`/`constant_symbol`/`bank_swift`/`bank_iban`/`bank_account` (caps 255 vs `VarChar(50)/VarChar(20)`) — `src/schemas/invoices.schema.ts:30-35`, **Medium**; warehouse `/items` list ignores the client `sort` param and sorts by non-unique `name` with no `id` tiebreak — `src/routes/admin/warehouse.ts:662`, **Low**; year-spanning leave request books all hours against the start year's balance only — `src/routes/admin/leave-requests.ts:195`, **Medium**; Dashboard "Přidat jízdu" quick action omits `["vehicles"]` invalidation — `src/admin/components/dashboard/DashQuickActions.tsx:184`, **Low**. These were verified `real` but fall outside the 29-item cited set; treat them as a fast-follow batch.
|
||||
|
||||
---
|
||||
|
||||
## Recommended Fix Order (dependencies considered)
|
||||
|
||||
**Phase 0 — Data-integrity criticals first (financial/stock corruption, silent & cumulative).** These corrupt persisted state and worsen on retry; fix before anything cosmetic.
|
||||
|
||||
1. **C3** `confirmInventorySession` `return`→`throw` (one-line change; stops repeatable phantom inventory). Trivial, highest leverage.
|
||||
2. **C2** `confirmIssue` cross-line over-issue guard (add a running per-batch tally / up-front availability pass, mirroring the existing `confirmIssue` validation-first pattern; consider a `(issue_id, batch_id)` unique constraint as a backstop).
|
||||
3. **C1** leave-balance restore on attendance delete — but **do C1 together with H6 and the year-spanning leave finding**, since all three live in the leave/attendance balance code and a single corrected helper (per-day, holiday-aware, per-year accumulation, with an inverse on delete) resolves them coherently. Fix the holiday-counting (H6) and per-year split first, then route delete through the same helper.
|
||||
|
||||
**Phase 1 — Security / privilege & session correctness.** 4. **H1** session-reuse misclassification (gate the reuse branch on `replaced_by_hash` alone; reorder vs the expiry check). Self-contained; high user impact. 5. **M10** `POST /users` role-strip for non-admins; **L8a** AI budget permission gate. Both are permission-boundary one-liners.
|
||||
|
||||
**Phase 2 — The Zod-cap-vs-DB-column batch (single coordinated sweep).** All of **H2, M2, M4, M11, L1, L8d, L8e** plus the adjacent invoice item/bank caps share one mechanism and one fix shape (`.max()` alignment + optionally a global P2000→400 mapping in `server.ts`). Do them in one pass with a shared "cap-must-fit-column" test helper so the class is closed, not whacked one at a time. Highest blast radius within the batch (whole-save rollback): invoice item caps, then H2.
|
||||
|
||||
> **Phase 2 follow-ups (2026-06-12, deliberately deferred):** (1) the optional
|
||||
> global P2000→400 mapping in the `server.ts` error handler was NOT added —
|
||||
> `server.ts` exports no app builder, so the mapping would be untestable
|
||||
> without first extracting an exported `buildApp()`; do the refactor + backstop
|
||||
> together. (2) Frontend `maxLength` attributes on the trips (odkud/kam) and
|
||||
> invoice bank/payment form fields — pure UX polish now that Zod 400s
|
||||
> over-length input with a Czech message; add when next touching those forms.
|
||||
|
||||
**Phase 3 — FK-existence & error-mapping consistency.** **M6** (projects update), **M8** (warehouse receipts/issues), **M5** (CNB graceful degradation). These align the lagging modules with the established offers/orders pre-validation pattern; a shared P2003→Czech-400 mapping (added in Phase 2 if you choose the global-handler route) reduces the per-site work.
|
||||
|
||||
**Phase 4 — Date/timezone boundaries.** **M1** (invoice date `isoDateString`), **M7** (warehouse `date_to` half-open), **H5** (Odin Czech-date), **L8b** (audit-log `from`). Group because they share the documented date-boundary helpers (`isoDateString`, `utcMidnightOfLocalDay`); fixing M1/H5 also removes a day-shift class.
|
||||
|
||||
**Phase 5 — Pagination determinism & frontend state.** **H4** (received-invoices pager — add the missing `usePaginatedQuery`/`<Pagination>`), **L3** (customers + received-invoices `id` tiebreak), **L4/L5** (page-reset on month change), **M9** (plan update cap), **H3** (issued-order transition flush edits + don't `markClean` stale state). H4 is the largest UI change; the rest are small, independent guards.
|
||||
|
||||
**Phase 6 — Cosmetic / low-blast cleanup (parallelizable, no dependencies).** ~~M3~~ (withdrawn; only the stale Chromium-footer comment in `html-to-pdf.ts`/CLAUDE.md remains as a doc fix), **M12** (Puppeteer re-acquire/retry), **L2** (offer number release year), **L6** (Settings System/Firma clobber), **L7** (km integer coercion), **L8c** (draft PDF button guard), warehouse `/items` sort param + tiebreak, and the Dashboard `["vehicles"]` invalidation.
|
||||
|
||||
Rationale for ordering: persisted-data corruption (Phase 0) cannot be allowed to accumulate; security boundaries (Phase 1) are cheap and high-impact; the cap batch (Phase 2) and FK/error mapping (Phase 3) are most efficient done as coordinated sweeps that share a fix shape and tests; date boundaries (Phase 4) share helpers; UI/pagination (Phase 5) depend on nothing earlier but benefit from the cleaner backend; everything in Phase 6 is independent and can be parallelized across contributors.
|
||||
@@ -204,8 +204,11 @@ descriptions for unnumbered drafts. Audit failures are non-fatal.
|
||||
a deterministic path and **overwrite in place** — never uniquePath `_N`
|
||||
suffixes. The issued-order PDF gets language from the document's `language`
|
||||
column and carries a Puppeteer `footerTemplate` footer on every page
|
||||
("Vystavil" left, "Strana X z Y"/"Page X of Y" centered) — Chromium has no
|
||||
CSS margin-box footers; use `htmlToPdf(html, { footerTemplate })`.
|
||||
("Vystavil" left, "Strana X z Y"/"Page X of Y" centered). Two repeating-
|
||||
footer mechanisms coexist and BOTH work: Puppeteer `footerTemplate`
|
||||
(invoices + issued orders — `htmlToPdf(html, { footerTemplate })`) and CSS
|
||||
`@page` margin boxes (`@bottom-center` + `counter(page)`, offer PDF —
|
||||
supported since Chrome 131, Nov 2024). Don't migrate one to the other.
|
||||
- **Shared modules — extend, never fork local copies:**
|
||||
`src/admin/components/document/` (DocumentItemsEditor, SectionsEditor,
|
||||
LockBanner), hooks `useDocumentLock` / `useUnsavedChangesGuard` /
|
||||
|
||||
52
docs/superpowers/specs/2026-06-12-sidebar-icons-design.md
Normal file
52
docs/superpowers/specs/2026-06-12-sidebar-icons-design.md
Normal file
@@ -0,0 +1,52 @@
|
||||
# Sidebar icon refresh — design
|
||||
|
||||
**Date:** 2026-06-12 · **Status:** approved (visual companion session, 3 screens)
|
||||
|
||||
## Problem
|
||||
|
||||
All 31 sidebar items have icons, but 13 share a glyph with another item
|
||||
(3× "people", 3× "sliders", 2× grid/bar-chart/box/history-clock) and Faktury
|
||||
uses a dollar sign in an app that bills in Kč/EUR. Duplicated glyphs defeat
|
||||
the purpose of icons as unique visual anchors.
|
||||
|
||||
## Decisions (user-approved)
|
||||
|
||||
1. **Full refresh** of all items (option B over targeted fix).
|
||||
2. **Tile language (option B of 3 rendered directions):** every item's glyph
|
||||
sits in a rounded-square tile (border-radius 32%, echoing OdinMark), as a
|
||||
**soft color wash — one muted hue per menu section**:
|
||||
Přehled `primary` (red) · Docházka `info` (blue) · Kniha jízd `teal` ·
|
||||
Administrativa `warning` (amber) · Sklad `violet` · Systém `slate`.
|
||||
3. **Odin stays unique:** the only **solid** (gradient) tile and the only
|
||||
animated icon. No animation anywhere else. Red stays reserved for
|
||||
Odin/primary.
|
||||
4. **Glyph set** approved on the full-set screen: receipt for Faktury,
|
||||
business card for Zákazníci, truck for Dodavatelé, stamp for Schvalování,
|
||||
ledger ± for Správa bilancí, route/pin/car for Kniha jízd, barcode for
|
||||
Inventura, shelf rack for Lokace, arrows into/out of a box for
|
||||
Příjmy/Výdeje, warehouse hall for Sklad přehled, tag/cart/folder for
|
||||
Nabídky/Objednávky/Projekty, gauge for Přehled, paper plane for Žádosti,
|
||||
timesheet for Moje historie (docházka), shapes for Kategorie, chart frame
|
||||
for Reporty, magnifier-over-list for Audit log. Kept concepts (now unique
|
||||
in the set): clock (Záznam docházky), calendar (Plán prací), people
|
||||
(Uživatelé), gear (Nastavení), box (Položky).
|
||||
|
||||
## Implementation
|
||||
|
||||
- `theme.ts`: add `teal`, `violet`, `slate` palette entries (light + dark
|
||||
mains, full main/light/dark/contrastText so cssVariables emits `*Channel`
|
||||
tokens) + TS module augmentation.
|
||||
- `navData.tsx`: `MenuSection.hue` (palette key), new glyph SVGs
|
||||
(stroke, 24-viewBox, width 2, round caps), `MenuItem.rawIcon` flag for
|
||||
Odin (its icon ships its own tile).
|
||||
- `SidebarNav.tsx`: renders the tile (26 px, radius 32%, `bgcolor:
|
||||
rgba(<hue>.mainChannel / 0.12)`, glyph color `<hue>.main`, svg 16 px)
|
||||
around every non-`rawIcon` item. No hardcoded hex; washes are
|
||||
channel-alpha so both schemes work.
|
||||
- Pinning test `navdata-icons.test.ts`: every non-raw icon renders to unique
|
||||
static markup (no two items may ever share a glyph again).
|
||||
|
||||
## Out of scope
|
||||
|
||||
Animation for non-Odin icons (explicitly rejected), page-level icons,
|
||||
mobile drawer changes (it reuses SidebarNav).
|
||||
@@ -0,0 +1,98 @@
|
||||
# Per-item Sleva (% discount) — Offers + Invoices
|
||||
|
||||
**Date:** 2026-06-13
|
||||
**Status:** Approved → implementing
|
||||
**Scope:** Add a per-line-item percentage discount ("Sleva") to **offers**
|
||||
(nabídky) and **issued invoices** (Faktury), on both the detail-page item
|
||||
editor and the PDF. Received invoices, issued orders and orders are NOT
|
||||
touched.
|
||||
|
||||
## Decisions (from brainstorming)
|
||||
|
||||
- **Type:** percentage per item (0–100), not an absolute amount.
|
||||
- **Totals/VAT:** the discount reduces the line **net**; on invoices VAT is
|
||||
computed on the **discounted** net. `net = qty × unit_price × (1 − discount/100)`.
|
||||
- **PDF column is conditional:** render the Sleva column only when at least one
|
||||
(included) item has `discount > 0`; otherwise the table is identical to today.
|
||||
- **Detail-page column is always visible** (it's the input).
|
||||
|
||||
## Data model
|
||||
|
||||
Add to `quotation_items` and `invoice_items`:
|
||||
|
||||
```
|
||||
discount Decimal? @default(0.00) @db.Decimal(5, 2) // percent, 0–100
|
||||
```
|
||||
|
||||
Nullable with default `0`, matching the existing money columns. "No sleva" =
|
||||
`0` or null. One tracked migration; apply to dev `app` and `app_test`, then
|
||||
`prisma generate`.
|
||||
|
||||
## Line math (single rule)
|
||||
|
||||
`lineNet = qty × unit_price × (1 − clamp(discount,0,100)/100)`
|
||||
|
||||
Add a shared backend helper so every site is identical:
|
||||
|
||||
```ts
|
||||
// src/utils/money.ts (new)
|
||||
export const lineNet = (qty: number, unitPrice: number, discountPct: number) =>
|
||||
qty * unitPrice * (1 - (discountPct || 0) / 100);
|
||||
```
|
||||
|
||||
## Backend
|
||||
|
||||
- **Schemas (Zod):** add `discount` to the offer-item and invoice-item schemas
|
||||
via `numberInRange(0, 100)` (shared coercer in `common.ts`), optional, default
|
||||
`0`.
|
||||
- **offers.service** (`enrichQuotation`): line total uses `lineNet`; document
|
||||
net ("Celkem bez DPH") sums discounted included lines. Persist `discount` on
|
||||
item create/update.
|
||||
- **invoices.service**: every `computeMoney` `getBase` callback
|
||||
(`computeInvoiceTotals`, monthly-stats `invoiceMonthlyAmount`, per-rate
|
||||
`vatMap`) returns `lineNet(...)` so subtotal **and** VAT use the discounted
|
||||
net. Persist `discount` on item create/update.
|
||||
- **DocumentItemsEditor's `documentItemsTotal`** (frontend) mirrors the same
|
||||
discounted net.
|
||||
|
||||
## Frontend (Section 1 — detail-page editor)
|
||||
|
||||
- **Offers** → shared `src/admin/components/document/DocumentItemsEditor.tsx`:
|
||||
`DocumentItem` gains `discount`; add a **"Sleva %"** numeric column (0–100);
|
||||
per-line total and the footer net total apply it. Mobile card layout gets the
|
||||
field. `emptyDocumentItem` defaults `discount: 0`. Hydration + save payloads
|
||||
carry `discount`.
|
||||
- **Invoices** → `src/admin/pages/InvoiceDetail.tsx` own editor
|
||||
(`SortableInvoiceRow` + create/edit rows): `InvoiceItem` gains `discount`;
|
||||
same column; net/VAT/gross totals apply it. Mobile layout too.
|
||||
|
||||
## PDF (Section 2 — conditional column)
|
||||
|
||||
`src/routes/admin/offers-pdf.ts` and `src/routes/admin/invoices-pdf.ts`:
|
||||
|
||||
- `const hasDiscount = items.some(i => includedInTotal(i) && Number(i.discount) > 0)`.
|
||||
- When `hasDiscount`: add a column — header **"Sleva"** (cs) / **"Discount"**
|
||||
(en, from the document's `language`), cell renders `"<n> %"` (escaped); adjust
|
||||
colspans of any full-width rows accordingly.
|
||||
- Line net / document total / VAT always use the discounted net regardless of
|
||||
`hasDiscount`.
|
||||
- `escapeHtml` every interpolation (string-built PDF templates).
|
||||
|
||||
## Tests
|
||||
|
||||
- `offer-invoice-totals` / invoice totals: net, VAT and gross with discounts
|
||||
(incl. a 100% line = 0, and VAT-on-discounted-net).
|
||||
- Schema: `discount` rejects <0 and >100, coerces form strings, defaults 0.
|
||||
- PDF: column present when an item has a discount; absent when none; values
|
||||
escaped.
|
||||
|
||||
## Non-goals (YAGNI)
|
||||
|
||||
- No separate "total discount" summary line, no document-level discount.
|
||||
- No changes to received invoices, issued orders, or orders.
|
||||
|
||||
## Migration etiquette
|
||||
|
||||
DB change → user stops the dev server first; create the migration via the
|
||||
non-interactive `prisma migrate diff` recipe, `migrate deploy` + `generate` on
|
||||
dev and `app_test`, commit schema + migration folder together.
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.4.30",
|
||||
"version": "2.4.36",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "app-ts",
|
||||
"version": "2.4.30",
|
||||
"version": "2.4.36",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.102.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.4.30",
|
||||
"version": "2.4.36",
|
||||
"description": "",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `audit_logs` MODIFY `created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0);
|
||||
|
||||
|
||||
-- Stock invariants enforced by the database itself: a future cumulative-
|
||||
-- decrement bug (the C2 class — duplicate issue lines driving a batch
|
||||
-- negative and silently vanishing from stock totals) becomes a loud error
|
||||
-- instead of hidden corruption. All databases verified clean of negative
|
||||
-- rows before this migration (2026-06-12).
|
||||
ALTER TABLE `sklad_batches`
|
||||
ADD CONSTRAINT `chk_sklad_batches_quantity_nonneg` CHECK (`quantity` >= 0);
|
||||
|
||||
ALTER TABLE `sklad_item_locations`
|
||||
ADD CONSTRAINT `chk_sklad_item_locations_quantity_nonneg` CHECK (`quantity` >= 0);
|
||||
@@ -0,0 +1,6 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `invoice_items` ADD COLUMN `discount` DECIMAL(5, 2) NULL DEFAULT 0.00;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `quotation_items` ADD COLUMN `discount` DECIMAL(5, 2) NULL DEFAULT 0.00;
|
||||
|
||||
@@ -65,7 +65,9 @@ model audit_logs {
|
||||
new_values String? @db.LongText
|
||||
user_agent String? @db.Text
|
||||
session_id String? @db.VarChar(128)
|
||||
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
// DATETIME, not TIMESTAMP — TIMESTAMP dies in 2038 and converts through
|
||||
// the session timezone (2026-06-12 hardening migration).
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
|
||||
@@index([action], map: "idx_audit_logs_action")
|
||||
@@index([created_at], map: "idx_audit_logs_created")
|
||||
@@ -206,6 +208,7 @@ model invoice_items {
|
||||
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
||||
unit String? @db.VarChar(20)
|
||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||
discount Decimal? @default(0.00) @db.Decimal(5, 2)
|
||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
position Int? @default(0)
|
||||
invoices invoices @relation(fields: [invoice_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "invoice_items_ibfk_1")
|
||||
@@ -503,6 +506,7 @@ model quotation_items {
|
||||
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
||||
unit String? @db.VarChar(20)
|
||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||
discount Decimal? @default(0.00) @db.Decimal(5, 2)
|
||||
is_included_in_total Boolean? @default(true)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "quotation_items_ibfk_1")
|
||||
|
||||
@@ -391,12 +391,12 @@ async function main() {
|
||||
console.log(` Admin role now has all ${allPerms.length} permissions`);
|
||||
|
||||
// 4. Ensure admin user exists
|
||||
let adminUser = await prisma.users.findFirst({
|
||||
const adminUser = await prisma.users.findFirst({
|
||||
where: { username: "admin" },
|
||||
});
|
||||
if (!adminUser) {
|
||||
const hash = bcrypt.hashSync("admin", 10);
|
||||
adminUser = await prisma.users.create({
|
||||
await prisma.users.create({
|
||||
data: {
|
||||
username: "admin",
|
||||
email: "admin@boha.local",
|
||||
|
||||
@@ -59,7 +59,7 @@ async function main() {
|
||||
// fails we KEEP file_data and report the row as failed.
|
||||
const expectedSize = rec.file_data.length;
|
||||
const readBack = nasFinancialsManager.readReceivedInvoice(result.filePath);
|
||||
let writtenSize = -1;
|
||||
let writtenSize: number;
|
||||
if (readBack) {
|
||||
writtenSize = readBack.data.length;
|
||||
} else {
|
||||
|
||||
374
src/__tests__/__snapshots__/attendance-print-html.test.ts.snap
Normal file
374
src/__tests__/__snapshots__/attendance-print-html.test.ts.snap
Normal file
@@ -0,0 +1,374 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`buildUserSectionHtml > produces a stable per-user section (full output pinned) 1`] = `
|
||||
"<div class="user-section">
|
||||
<div class="user-header">
|
||||
<h3>Jan Novák</h3>
|
||||
<span class="total">Odpracováno: 8:00 h</span>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th style="width:55px">Datum</th>
|
||||
<th style="width:55px">Den</th>
|
||||
<th style="width:60px">Typ</th>
|
||||
<th class="text-center" style="width:55px">Příchod</th>
|
||||
<th class="text-center" style="width:80px">Pauza</th>
|
||||
<th class="text-center" style="width:55px">Odchod</th>
|
||||
<th class="text-center" style="width:85px">Hodiny</th>
|
||||
<th>Projekty</th>
|
||||
<th>Poznámka</th>
|
||||
</tr></thead>
|
||||
<tbody><tr class="weekend">
|
||||
<td>1. 3. 2098</td>
|
||||
<td>Sobota</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>2. 3. 2098</td>
|
||||
<td>Neděle</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>3. 3. 2098</td>
|
||||
<td>Pondělí</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>4. 3. 2098</td>
|
||||
<td>Úterý</td>
|
||||
<td>Práce</td>
|
||||
<td class="text-center">08:00</td>
|
||||
<td class="text-center">12:00 - 12:30</td>
|
||||
<td class="text-center">16:30</td>
|
||||
<td class="text-center">8:00 (8,00)</td>
|
||||
<td style="font-size:8px"><div>Alpha (8:00h)</div></td>
|
||||
<td>Poznámka <b></td>
|
||||
</tr><tr class="vacation">
|
||||
<td>5. 3. 2098</td>
|
||||
<td>Středa</td>
|
||||
<td>Dovolená</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">8,00</td>
|
||||
<td style="font-size:8px">—</td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>6. 3. 2098</td>
|
||||
<td>Čtvrtek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>7. 3. 2098</td>
|
||||
<td>Pátek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>8. 3. 2098</td>
|
||||
<td>Sobota</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>9. 3. 2098</td>
|
||||
<td>Neděle</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>10. 3. 2098</td>
|
||||
<td>Pondělí</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>11. 3. 2098</td>
|
||||
<td>Úterý</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>12. 3. 2098</td>
|
||||
<td>Středa</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>13. 3. 2098</td>
|
||||
<td>Čtvrtek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>14. 3. 2098</td>
|
||||
<td>Pátek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>15. 3. 2098</td>
|
||||
<td>Sobota</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>16. 3. 2098</td>
|
||||
<td>Neděle</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>17. 3. 2098</td>
|
||||
<td>Pondělí</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>18. 3. 2098</td>
|
||||
<td>Úterý</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>19. 3. 2098</td>
|
||||
<td>Středa</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>20. 3. 2098</td>
|
||||
<td>Čtvrtek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>21. 3. 2098</td>
|
||||
<td>Pátek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>22. 3. 2098</td>
|
||||
<td>Sobota</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>23. 3. 2098</td>
|
||||
<td>Neděle</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>24. 3. 2098</td>
|
||||
<td>Pondělí</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>25. 3. 2098</td>
|
||||
<td>Úterý</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>26. 3. 2098</td>
|
||||
<td>Středa</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>27. 3. 2098</td>
|
||||
<td>Čtvrtek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>28. 3. 2098</td>
|
||||
<td>Pátek</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>29. 3. 2098</td>
|
||||
<td>Sobota</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="weekend">
|
||||
<td>30. 3. 2098</td>
|
||||
<td>Neděle</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>31. 3. 2098</td>
|
||||
<td>Pondělí</td>
|
||||
<td>—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
</tr></tbody>
|
||||
</table>
|
||||
<div class="user-summary">
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Odpracováno:</span>
|
||||
<span class="summary-value">8,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Odpracováno včetně svátků a přesčasů:</span>
|
||||
<span class="summary-value">16,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Dovolená:</span>
|
||||
<span class="summary-value">8,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Přesčas:</span>
|
||||
<span class="summary-value">8,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Svátek:</span>
|
||||
<span class="summary-value">0,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">So/Ne:</span>
|
||||
<span class="summary-value">0,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Práce v noci:</span>
|
||||
<span class="summary-value">0,00h</span>
|
||||
</div>
|
||||
<div class="summary-row summary-fund">
|
||||
<span class="summary-label">Fond měsíce:</span>
|
||||
<span class="summary-value">168,00h (21 dnů)</span>
|
||||
</div>
|
||||
<div class="legend">
|
||||
<span class="legend-item"><span class="legend-swatch weekend"></span>Víkend (So/Ne)</span>
|
||||
<span class="legend-item"><span class="legend-swatch holiday"></span>Svátek</span>
|
||||
<span class="legend-item"><span class="legend-swatch weekend-holiday"></span>Víkend + svátek</span>
|
||||
<span class="legend-item"><span class="legend-swatch vacation"></span>Dovolená</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>"
|
||||
`;
|
||||
137
src/__tests__/ai-budget-permission.test.ts
Normal file
137
src/__tests__/ai-budget-permission.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import aiRoutes from "../routes/admin/ai";
|
||||
import { getBudgetUsd, setBudgetUsd } from "../services/ai.service";
|
||||
|
||||
/**
|
||||
* Pinning test for audit finding L8a: the company-wide AI monthly budget must
|
||||
* NOT be mutable by an ordinary ai.use holder (budget_usd=0 is a company-wide
|
||||
* AI DoS; a huge value removes the cost cap). It is a company setting —
|
||||
* settings.company / settings.system / admin only.
|
||||
*/
|
||||
|
||||
const N = "ai_budget_perm_";
|
||||
const stamp = Date.now().toString(36);
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let aiUserToken: string;
|
||||
let aiRoleId: number;
|
||||
let savedBudget: number;
|
||||
|
||||
function token(user: { id: number; username: string; roleName: string }) {
|
||||
return jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: user.roleName },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.users.deleteMany({ where: { username: { startsWith: N } } });
|
||||
const roles = await prisma.roles.findMany({
|
||||
where: { name: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const roleIds = roles.map((r) => r.id);
|
||||
if (roleIds.length > 0) {
|
||||
await prisma.role_permissions.deleteMany({
|
||||
where: { role_id: { in: roleIds } },
|
||||
});
|
||||
await prisma.roles.deleteMany({ where: { id: { in: roleIds } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
savedBudget = await getBudgetUsd();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(cookie);
|
||||
await app.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
app.addHook("onRequest", securityHeaders);
|
||||
await app.register(aiRoutes, { prefix: "/api/admin/ai" });
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = token({
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
roleName: "admin",
|
||||
});
|
||||
|
||||
// Ordinary ai.use holder — may chat, must NOT control the budget.
|
||||
const role = await prisma.roles.create({
|
||||
data: { name: `${N}aiuse_${stamp}`, display_name: "AI Use Only" },
|
||||
});
|
||||
aiRoleId = role.id;
|
||||
const perm = await prisma.permissions.findFirst({
|
||||
where: { name: "ai.use" },
|
||||
});
|
||||
if (!perm) throw new Error("Test setup: ai.use permission missing");
|
||||
await prisma.role_permissions.create({
|
||||
data: { role_id: aiRoleId, permission_id: perm.id },
|
||||
});
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user_${stamp}`,
|
||||
email: `${N}${stamp}@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
first_name: "AiUse",
|
||||
last_name: "Only",
|
||||
is_active: true,
|
||||
role_id: aiRoleId,
|
||||
},
|
||||
});
|
||||
aiUserToken = token({
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
roleName: role.name,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await setBudgetUsd(savedBudget); // restore whatever the test DB had
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("PUT /ai/budget permission gate (audit L8a)", () => {
|
||||
it("rejects an ordinary ai.use holder with 403", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/admin/ai/budget",
|
||||
headers: {
|
||||
Authorization: `Bearer ${aiUserToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { budget_usd: 0 },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
// ...and the budget must be untouched.
|
||||
expect(await getBudgetUsd()).toBe(savedBudget);
|
||||
});
|
||||
|
||||
it("allows an admin to set the budget", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/admin/ai/budget",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { budget_usd: savedBudget },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
139
src/__tests__/attendance-delete-balance.test.ts
Normal file
139
src/__tests__/attendance-delete-balance.test.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { createLeave, deleteAttendance } from "../services/attendance.service";
|
||||
import { localDateStr } from "../utils/date";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding C1: deleting a vacation/sick attendance
|
||||
* record must restore the hours it charged to leave_balances. Without the
|
||||
* restore, cancelling booked leave by deleting its rows permanently inflates
|
||||
* vacation_used/sick_used.
|
||||
*/
|
||||
|
||||
const N = "att_delbal_";
|
||||
|
||||
let userId: number;
|
||||
|
||||
/** First Monday of March in the given year — always before the earliest
|
||||
* possible Easter holiday and clear of all fixed Czech holidays, so a
|
||||
* Mon-Fri range books exactly 5 days. (Far-future year per fixture hygiene.) */
|
||||
function firstMondayOfMarch(year: number): Date {
|
||||
const d = new Date(year, 2, 1, 12, 0, 0);
|
||||
while (d.getDay() !== 1) d.setDate(d.getDate() + 1);
|
||||
return d;
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
const users = await prisma.users.findMany({
|
||||
where: { username: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const ids = users.map((u) => u.id);
|
||||
if (ids.length > 0) {
|
||||
await prisma.attendance.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.leave_balances.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.users.deleteMany({ where: { id: { in: ids } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const adminRole = await prisma.roles.findFirst({ where: { name: "admin" } });
|
||||
if (!adminRole)
|
||||
throw new Error("Admin role not found — seed the database first");
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash:
|
||||
"$2a$12$LJ3m4ys3Lg4oLBFnYP2amuPBzJnJBbGzCl5Y6X9Y8r0q5.s3L6OyO",
|
||||
first_name: "Delete",
|
||||
last_name: "Balance",
|
||||
is_active: true,
|
||||
role_id: adminRole.id,
|
||||
},
|
||||
});
|
||||
userId = user.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
async function balance(year: number) {
|
||||
return prisma.leave_balances.findFirst({ where: { user_id: userId, year } });
|
||||
}
|
||||
|
||||
describe("deleteAttendance leave-balance restore (audit C1)", () => {
|
||||
it("restores vacation_used when booked vacation rows are deleted", async () => {
|
||||
const monday = firstMondayOfMarch(2098);
|
||||
const friday = new Date(monday);
|
||||
friday.setDate(friday.getDate() + 4);
|
||||
|
||||
const created = await createLeave(
|
||||
{
|
||||
user_id: userId,
|
||||
date_from: localDateStr(monday),
|
||||
date_to: localDateStr(friday),
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
expect("created" in created && created.created).toBe(5);
|
||||
expect(Number((await balance(2098))?.vacation_used)).toBe(40);
|
||||
|
||||
const rows = await prisma.attendance.findMany({
|
||||
where: { user_id: userId, leave_type: "vacation" },
|
||||
});
|
||||
expect(rows).toHaveLength(5);
|
||||
for (const row of rows) {
|
||||
const res = await deleteAttendance(row.id);
|
||||
expect("success" in res && res.success).toBe(true);
|
||||
}
|
||||
|
||||
expect(Number((await balance(2098))?.vacation_used)).toBe(0);
|
||||
});
|
||||
|
||||
it("restores sick_used when a booked sick day is deleted", async () => {
|
||||
const monday = firstMondayOfMarch(2099);
|
||||
await createLeave(
|
||||
{
|
||||
user_id: userId,
|
||||
date_from: localDateStr(monday),
|
||||
leave_type: "sick",
|
||||
leave_hours: 8,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
expect(Number((await balance(2099))?.sick_used)).toBe(8);
|
||||
|
||||
const row = await prisma.attendance.findFirst({
|
||||
where: { user_id: userId, leave_type: "sick" },
|
||||
});
|
||||
expect(row).not.toBeNull();
|
||||
await deleteAttendance(row!.id);
|
||||
|
||||
expect(Number((await balance(2099))?.sick_used)).toBe(0);
|
||||
});
|
||||
|
||||
it("does not touch balances when deleting a plain work shift", async () => {
|
||||
const wednesday = firstMondayOfMarch(2098);
|
||||
wednesday.setDate(wednesday.getDate() + 9); // a weekday a week later
|
||||
const shift = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
shift_date: wednesday,
|
||||
leave_type: "work",
|
||||
},
|
||||
});
|
||||
|
||||
const before = await balance(2098);
|
||||
await deleteAttendance(shift.id);
|
||||
const after = await balance(2098);
|
||||
|
||||
expect(Number(after?.vacation_used)).toBe(Number(before?.vacation_used));
|
||||
expect(Number(after?.sick_used)).toBe(Number(before?.sick_used));
|
||||
});
|
||||
});
|
||||
155
src/__tests__/attendance-print-html.test.ts
Normal file
155
src/__tests__/attendance-print-html.test.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
buildProjectLogsHtml,
|
||||
buildUserSectionHtml,
|
||||
buildPrintHtml,
|
||||
} from "../admin/hooks/useAttendanceAdmin";
|
||||
|
||||
/**
|
||||
* Characterization test for the attendance print-HTML builders.
|
||||
*
|
||||
* These builders had `any`-typed params; this pins their CURRENT output so the
|
||||
* follow-up retyping (precise AttendanceRecord/UserTotal/PrintData types) is
|
||||
* provably behavior-preserving. The only runtime touch in that retype is
|
||||
* `parseInt(log.hours)` → `parseInt(String(log.hours))` to satisfy the typed
|
||||
* `string | number | null` shape — the cases below exercise both string and
|
||||
* numeric hours/minutes precisely so that equivalence is locked in.
|
||||
*
|
||||
* Fixtures are cast through `Parameters<typeof fn>` so the test compiles both
|
||||
* before and after the param types tighten.
|
||||
*/
|
||||
|
||||
type RecordArg = Parameters<typeof buildProjectLogsHtml>[0];
|
||||
type UserDataArg = Parameters<typeof buildUserSectionHtml>[1];
|
||||
type PrintDataArg = Parameters<typeof buildUserSectionHtml>[2];
|
||||
const asRecord = (o: unknown) => o as unknown as RecordArg;
|
||||
const asUserData = (o: unknown) => o as unknown as UserDataArg;
|
||||
const asPrintData = (o: unknown) => o as unknown as PrintDataArg;
|
||||
|
||||
describe("buildProjectLogsHtml", () => {
|
||||
it("formats hours/minutes given as strings", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({
|
||||
project_logs: [
|
||||
{ project_id: 1, project_name: "Alpha", hours: "2", minutes: "30" },
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe("<div>Alpha (2:30h)</div>");
|
||||
});
|
||||
|
||||
it("formats hours/minutes given as numbers (parseInt-of-number path)", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({
|
||||
project_logs: [
|
||||
{ project_id: 2, project_name: "Beta", hours: 1, minutes: 5 },
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe("<div>Beta (1:05h)</div>");
|
||||
});
|
||||
|
||||
it("derives duration from started_at/ended_at when hours are absent", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({
|
||||
project_logs: [
|
||||
{
|
||||
project_id: 3,
|
||||
project_name: "Gamma",
|
||||
started_at: "2098-01-05T08:00:00",
|
||||
ended_at: "2098-01-05T10:30:00",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe("<div>Gamma (2:30h)</div>");
|
||||
});
|
||||
|
||||
it("falls back to '#id' and 0:00 when name and times are missing", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(asRecord({ project_logs: [{ project_id: 7 }] })),
|
||||
).toBe("<div>#7 (0:00h)</div>");
|
||||
});
|
||||
|
||||
it("renders the bare project name when there are no logs", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({ project_name: "Solo & <Co>", project_logs: [] }),
|
||||
),
|
||||
).toBe("Solo & <Co>");
|
||||
});
|
||||
});
|
||||
|
||||
// Deterministic fixture: a fixed far-future month, one work day (with a numeric
|
||||
// project log so the snapshot also guards the parseInt path in context) and one
|
||||
// vacation day.
|
||||
const workRecord = {
|
||||
id: 1,
|
||||
user_id: 5,
|
||||
shift_date: "2098-03-04",
|
||||
leave_type: "work",
|
||||
arrival_time: "2098-03-04T08:00:00",
|
||||
departure_time: "2098-03-04T16:30:00",
|
||||
break_start: "2098-03-04T12:00:00",
|
||||
break_end: "2098-03-04T12:30:00",
|
||||
notes: "Poznámka <b>",
|
||||
project_logs: [
|
||||
{ project_id: 1, project_name: "Alpha", hours: 8, minutes: 0 },
|
||||
],
|
||||
};
|
||||
const leaveRecord = {
|
||||
id: 2,
|
||||
user_id: 5,
|
||||
shift_date: "2098-03-05",
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
};
|
||||
const userData = {
|
||||
name: "Jan Novák",
|
||||
minutes: 480,
|
||||
records: [workRecord, leaveRecord],
|
||||
};
|
||||
const printData = {
|
||||
month: "2098-03",
|
||||
month_name: "Březen 2098",
|
||||
selected_user_name: null,
|
||||
user_totals: { "5": userData },
|
||||
};
|
||||
|
||||
describe("buildUserSectionHtml", () => {
|
||||
it("produces a stable per-user section (full output pinned)", () => {
|
||||
const html = buildUserSectionHtml(
|
||||
"5",
|
||||
asUserData(userData),
|
||||
asPrintData(printData),
|
||||
);
|
||||
expect(html).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPrintHtml", () => {
|
||||
// NB: the document footer embeds `new Date()`, so assert stable fragments
|
||||
// rather than snapshotting the whole (non-deterministic) output.
|
||||
it("wraps the user sections in a stable document shell", () => {
|
||||
const section = buildUserSectionHtml(
|
||||
"5",
|
||||
asUserData(userData),
|
||||
asPrintData(printData),
|
||||
);
|
||||
const html = buildPrintHtml(
|
||||
asPrintData(printData),
|
||||
section,
|
||||
"",
|
||||
"",
|
||||
"Firma s.r.o.",
|
||||
);
|
||||
expect(html).toContain("<title>Docházka - Březen 2098</title>");
|
||||
expect(html).toContain("EVIDENCE DOCHÁZKY");
|
||||
expect(html).toContain('<div class="period">Březen 2098</div>');
|
||||
expect(html).toContain("Firma s.r.o.");
|
||||
expect(html).toContain(section);
|
||||
});
|
||||
});
|
||||
96
src/__tests__/audit-log-date-filter.test.ts
Normal file
96
src/__tests__/audit-log-date-filter.test.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
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 auditLogRoutes from "../routes/admin/audit-log";
|
||||
|
||||
/**
|
||||
* Pinning test for audit finding L8b: the audit-log date_from boundary must
|
||||
* be the LOCAL midnight of the requested day, symmetric with the date_to
|
||||
* side (which already parses "T23:59:59" as local). The old
|
||||
* `new Date(date_from)` was UTC midnight = 01:00/02:00 Prague, silently
|
||||
* excluding events logged in the first morning hours of the from-day.
|
||||
*
|
||||
* NOTE: audit_logs.created_at is @db.Timestamp(0) — capped at 2038, so the
|
||||
* far-future fixture year is 2037, not 2098.
|
||||
*/
|
||||
|
||||
const N = "auditlog_datefilter_";
|
||||
const DAY = "2037-04-09";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let earlyId: number; // 00:30 local — inside the old excluded window
|
||||
let middayId: number; // 12:00 local
|
||||
let prevDayId: number; // 23:30 local the day BEFORE — must stay excluded
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.audit_logs.deleteMany({
|
||||
where: { description: { contains: N } },
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(auditLogRoutes, { prefix: "/api/admin/audit-log" });
|
||||
|
||||
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" },
|
||||
);
|
||||
|
||||
const early = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}early`,
|
||||
created_at: new Date(2037, 3, 9, 0, 30, 0),
|
||||
},
|
||||
});
|
||||
earlyId = early.id;
|
||||
const midday = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}midday`,
|
||||
created_at: new Date(2037, 3, 9, 12, 0, 0),
|
||||
},
|
||||
});
|
||||
middayId = midday.id;
|
||||
const prevDay = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}prevday`,
|
||||
created_at: new Date(2037, 3, 8, 23, 30, 0),
|
||||
},
|
||||
});
|
||||
prevDayId = prevDay.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("audit-log date_from boundary (audit L8b)", () => {
|
||||
it("includes events from the first morning hours of the from-day", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/audit-log?date_from=${DAY}&date_to=${DAY}&limit=100`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const ids = (res.json().data as Array<{ id: number }>).map((r) => r.id);
|
||||
|
||||
expect(ids).toContain(earlyId); // 00:30 — dropped by the old UTC from-bound
|
||||
expect(ids).toContain(middayId);
|
||||
expect(ids).not.toContain(prevDayId); // previous evening stays out
|
||||
});
|
||||
});
|
||||
136
src/__tests__/db-constraints.test.ts
Normal file
136
src/__tests__/db-constraints.test.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
|
||||
/**
|
||||
* Pins the 2026-06-12 DB hardening migration:
|
||||
* 1. CHECK (quantity >= 0) on sklad_batches + sklad_item_locations — the DB
|
||||
* itself rejects negative stock, so a future C2-class bug (cumulative
|
||||
* decrements driving a batch negative) becomes a loud error instead of
|
||||
* silently hidden corruption.
|
||||
* 2. audit_logs.created_at is DATETIME, not TIMESTAMP — no 2038 cap.
|
||||
*/
|
||||
|
||||
const N = "db_constraints_";
|
||||
|
||||
let itemId: number;
|
||||
let locationId: number;
|
||||
let receiptId: number;
|
||||
let lineAId: number;
|
||||
let lineBId: number;
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.sklad_batches.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_item_locations.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipt_lines.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipts.deleteMany({ where: { notes: { contains: N } } });
|
||||
await prisma.sklad_items.deleteMany({ where: { name: { contains: N } } });
|
||||
await prisma.sklad_locations.deleteMany({
|
||||
where: { name: { contains: N } },
|
||||
});
|
||||
await prisma.audit_logs.deleteMany({
|
||||
where: { description: { contains: N } },
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const item = await prisma.sklad_items.create({
|
||||
data: { name: `${N}item`, unit: "ks" },
|
||||
});
|
||||
itemId = item.id;
|
||||
const location = await prisma.sklad_locations.create({
|
||||
data: { code: `DBC${Date.now() % 100000}`, name: `${N}loc` },
|
||||
});
|
||||
locationId = location.id;
|
||||
const receipt = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}receipt`, status: "CONFIRMED" },
|
||||
});
|
||||
receiptId = receipt.id;
|
||||
const lineA = await prisma.sklad_receipt_lines.create({
|
||||
data: {
|
||||
receipt_id: receiptId,
|
||||
item_id: itemId,
|
||||
quantity: 5,
|
||||
unit_price: 1,
|
||||
},
|
||||
});
|
||||
lineAId = lineA.id;
|
||||
const lineB = await prisma.sklad_receipt_lines.create({
|
||||
data: {
|
||||
receipt_id: receiptId,
|
||||
item_id: itemId,
|
||||
quantity: 5,
|
||||
unit_price: 1,
|
||||
},
|
||||
});
|
||||
lineBId = lineB.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("stock CHECK constraints", () => {
|
||||
it("rejects inserting a negative batch quantity", async () => {
|
||||
await expect(
|
||||
prisma.sklad_batches.create({
|
||||
data: {
|
||||
item_id: itemId,
|
||||
receipt_line_id: lineAId,
|
||||
quantity: -1,
|
||||
original_qty: 5,
|
||||
unit_price: 1,
|
||||
is_consumed: false,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rejects updating a batch quantity below zero", async () => {
|
||||
const batch = await prisma.sklad_batches.create({
|
||||
data: {
|
||||
item_id: itemId,
|
||||
receipt_line_id: lineBId,
|
||||
quantity: 5,
|
||||
original_qty: 5,
|
||||
unit_price: 1,
|
||||
is_consumed: false,
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
prisma.$executeRaw`UPDATE sklad_batches SET quantity = -2 WHERE id = ${batch.id}`,
|
||||
).rejects.toThrow();
|
||||
const fresh = await prisma.sklad_batches.findUnique({
|
||||
where: { id: batch.id },
|
||||
});
|
||||
expect(Number(fresh?.quantity)).toBe(5);
|
||||
});
|
||||
|
||||
it("rejects a negative item_location quantity", async () => {
|
||||
await expect(
|
||||
prisma.sklad_item_locations.create({
|
||||
data: { item_id: itemId, location_id: locationId, quantity: -1 },
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("audit_logs.created_at has no 2038 cap", () => {
|
||||
it("accepts a far-future timestamp (DATETIME, not TIMESTAMP)", async () => {
|
||||
const row = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}future`,
|
||||
created_at: new Date(Date.UTC(2098, 0, 15, 12, 0, 0)),
|
||||
},
|
||||
});
|
||||
expect(row.created_at?.getUTCFullYear()).toBe(2098);
|
||||
});
|
||||
});
|
||||
73
src/__tests__/html-to-pdf-retry.test.ts
Normal file
73
src/__tests__/html-to-pdf-retry.test.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M12: a shared Puppeteer browser that
|
||||
* disconnects between getBrowser()'s point-in-time `connected` check and the
|
||||
* actual render must be re-acquired once — instead of failing the request
|
||||
* with a 500 that an immediate retry would have served fine.
|
||||
*/
|
||||
|
||||
const { launchMock } = vi.hoisted(() => ({ launchMock: vi.fn() }));
|
||||
|
||||
vi.mock("puppeteer", () => ({ default: { launch: launchMock } }));
|
||||
|
||||
function healthyBrowser(pdfBytes = new Uint8Array([1, 2, 3])) {
|
||||
return {
|
||||
connected: true,
|
||||
newPage: vi.fn(async () => ({
|
||||
setContent: vi.fn(async () => undefined),
|
||||
pdf: vi.fn(async () => pdfBytes),
|
||||
close: vi.fn(async () => undefined),
|
||||
})),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
}
|
||||
|
||||
/** Browser whose connection dies the moment a page is requested — the
|
||||
* post-guard crash window from the finding. */
|
||||
function dyingBrowser() {
|
||||
const b = {
|
||||
connected: true,
|
||||
newPage: vi.fn(async () => {
|
||||
b.connected = false;
|
||||
throw new Error("Protocol error (Target.createTarget): Session closed.");
|
||||
}),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
return b;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
launchMock.mockReset();
|
||||
});
|
||||
|
||||
describe("htmlToPdf browser re-acquire (audit M12)", () => {
|
||||
it("relaunches once and resolves when the cached browser died mid-acquire", async () => {
|
||||
launchMock
|
||||
.mockResolvedValueOnce(dyingBrowser())
|
||||
.mockResolvedValueOnce(healthyBrowser());
|
||||
|
||||
const { htmlToPdf } = await import("../utils/html-to-pdf");
|
||||
const pdf = await htmlToPdf("<html><body>retry</body></html>");
|
||||
|
||||
expect(Buffer.isBuffer(pdf)).toBe(true);
|
||||
expect(launchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does NOT retry a genuine render error on a healthy browser", async () => {
|
||||
const browser = healthyBrowser();
|
||||
browser.newPage = vi.fn(async () => ({
|
||||
setContent: vi.fn(async () => {
|
||||
throw new Error("Render timeout");
|
||||
}),
|
||||
pdf: vi.fn(async () => new Uint8Array()),
|
||||
close: vi.fn(async () => undefined),
|
||||
}));
|
||||
launchMock.mockResolvedValue(browser);
|
||||
|
||||
const { htmlToPdf } = await import("../utils/html-to-pdf");
|
||||
await expect(htmlToPdf("<html></html>")).rejects.toThrow("Render timeout");
|
||||
expect(launchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
91
src/__tests__/invoice-date-coercion.test.ts
Normal file
91
src/__tests__/invoice-date-coercion.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
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 invoicesRoutes from "../routes/admin/invoices";
|
||||
import {
|
||||
CreateInvoiceSchema,
|
||||
UpdateInvoiceSchema,
|
||||
} from "../schemas/invoices.schema";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M1: invoice date fields must go through the
|
||||
* lenient ISO-date coercion. A round-tripped datetime string like
|
||||
* "2026-03-02T00:00:00" (the toJSON override emits LOCAL time, no Z) parses
|
||||
* as local Prague midnight = 23:00Z of the PREVIOUS day, and Prisma truncates
|
||||
* @db.Date columns to the UTC date part — the invoice lands a day early and
|
||||
* in the wrong month bucket.
|
||||
*/
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
const createdInvoiceIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(invoicesRoutes, { prefix: "/api/admin/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 () => {
|
||||
for (const id of createdInvoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
if (app) await app.close();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("invoice @db.Date coercion (audit M1)", () => {
|
||||
it("stores the submitted calendar day when issue_date carries a time part", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/invoices",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
status: "draft",
|
||||
issue_date: "2026-03-02T00:00:00",
|
||||
items: [],
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const id = res.json().data.id as number;
|
||||
createdInvoiceIds.push(id);
|
||||
|
||||
const row = await prisma.invoices.findUnique({ where: { id } });
|
||||
// @db.Date reads back as UTC midnight of the stored calendar day.
|
||||
expect(row?.issue_date?.toISOString().slice(0, 10)).toBe("2026-03-02");
|
||||
});
|
||||
|
||||
it("schema rejects a Czech-format date", () => {
|
||||
const result = CreateInvoiceSchema.safeParse({
|
||||
issue_date: "15.03.2026",
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("schema normalizes an empty string to null (edit forms clear with '')", () => {
|
||||
const result = CreateInvoiceSchema.safeParse({ issue_date: "" });
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) expect(result.data.issue_date).toBeNull();
|
||||
});
|
||||
|
||||
it("update schema strips the time part from tax_date", () => {
|
||||
const result = UpdateInvoiceSchema.safeParse({
|
||||
tax_date: "2026-03-02T00:00:00",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) expect(result.data.tax_date).toBe("2026-03-02");
|
||||
});
|
||||
});
|
||||
108
src/__tests__/invoice-pdf-cnb-degrade.test.ts
Normal file
108
src/__tests__/invoice-pdf-cnb-degrade.test.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import invoicesPdfRoutes from "../routes/admin/invoices-pdf";
|
||||
import { createInvoice } from "../services/invoices.service";
|
||||
import { getRate } from "../services/exchange-rates";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M5: a foreign-currency invoice PDF must
|
||||
* degrade gracefully when the CNB rate lookup fails — render WITHOUT the CZK
|
||||
* VAT recap/conversion footnote instead of 500ing the whole preview AND the
|
||||
* NAS archival. The rate only feeds the recap conversion; the document itself
|
||||
* is renderable without it.
|
||||
*/
|
||||
|
||||
vi.mock("../services/exchange-rates", async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import("../services/exchange-rates")>();
|
||||
return { ...actual, getRate: vi.fn() };
|
||||
});
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
const createdInvoiceIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(invoicesPdfRoutes, { prefix: "/api/admin/invoices-pdf" });
|
||||
|
||||
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 () => {
|
||||
for (const id of createdInvoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
if (app) await app.close();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
async function makeEurInvoice() {
|
||||
// Draft → no number consumed; EUR → triggers the CNB rate lookup.
|
||||
const invoice = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "EUR",
|
||||
apply_vat: true,
|
||||
vat_rate: 21,
|
||||
items: [
|
||||
{
|
||||
description: "CNB-DEGRADE-MARKER",
|
||||
quantity: 1,
|
||||
unit_price: 100,
|
||||
vat_rate: 21,
|
||||
},
|
||||
],
|
||||
});
|
||||
createdInvoiceIds.push(invoice.id);
|
||||
return invoice;
|
||||
}
|
||||
|
||||
describe("invoice PDF vs unreachable CNB (audit M5)", () => {
|
||||
it("renders the invoice without the CZK recap when the rate lookup throws", async () => {
|
||||
vi.mocked(getRate).mockRejectedValue(
|
||||
new Error("Nepodařilo se získat aktuální kurzy z ČNB"),
|
||||
);
|
||||
const invoice = await makeEurInvoice();
|
||||
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/invoices-pdf/${invoice.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const html = res.body;
|
||||
expect(html).toContain("CNB-DEGRADE-MARKER");
|
||||
// The CZK recap and the conversion footnote are omitted — their numbers
|
||||
// cannot be computed without the rate.
|
||||
expect(html).not.toContain("Rekapitulace DPH v Kč");
|
||||
expect(html).not.toContain("Přepočet kurzem ČNB");
|
||||
});
|
||||
|
||||
it("still renders the recap + conversion footnote when the rate is available", async () => {
|
||||
vi.mocked(getRate).mockResolvedValue(25.0);
|
||||
const invoice = await makeEurInvoice();
|
||||
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/invoices-pdf/${invoice.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const html = res.body;
|
||||
expect(html).toContain("Rekapitulace DPH v Kč");
|
||||
expect(html).toContain("Přepočet kurzem ČNB");
|
||||
expect(html).toContain("25,000");
|
||||
});
|
||||
});
|
||||
@@ -539,6 +539,40 @@ describe("PUT /api/admin/issued-orders/:id editable-state guard (HTTP)", () => {
|
||||
expect(res.json().error).toBe("Objednávku v tomto stavu nelze upravovat");
|
||||
});
|
||||
|
||||
it("persists item edits sent WITH a sent→confirmed transition (the H3 flush contract)", async () => {
|
||||
// The IssuedOrderDetail transition flushes unsaved edits by sending the
|
||||
// full payload + status in ONE PUT while the order is still editable
|
||||
// (sent). The server must apply the items AND the transition together.
|
||||
const order = await mkIssued({});
|
||||
await updateIssuedOrder(order.id, { status: "sent" });
|
||||
|
||||
const res = await app!.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/issued-orders/${order.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
payload: {
|
||||
status: "confirmed",
|
||||
items: [
|
||||
{
|
||||
description: "Flushnutá položka",
|
||||
quantity: 2,
|
||||
unit_price: 50,
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const row = await prisma.issued_orders.findUnique({
|
||||
where: { id: order.id },
|
||||
include: { issued_order_items: true },
|
||||
});
|
||||
expect(row!.status).toBe("confirmed");
|
||||
expect(row!.issued_order_items.map((i) => i.description)).toContain(
|
||||
"Flushnutá položka",
|
||||
);
|
||||
});
|
||||
|
||||
it("a status-only transition payload keeps working (confirmed -> completed)", async () => {
|
||||
const order = await mkIssued({});
|
||||
await updateIssuedOrder(order.id, { status: "sent" });
|
||||
|
||||
130
src/__tests__/item-discount-pdf.test.ts
Normal file
130
src/__tests__/item-discount-pdf.test.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
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 offersPdfRoutes from "../routes/admin/offers-pdf";
|
||||
import invoicesPdfRoutes from "../routes/admin/invoices-pdf";
|
||||
import { createInvoice } from "../services/invoices.service";
|
||||
|
||||
/**
|
||||
* The per-item Sleva column is CONDITIONAL on the PDF: render it only when at
|
||||
* least one item carries a discount > 0; otherwise the table looks exactly as
|
||||
* before. The discounted net always flows into the line/grand totals.
|
||||
*/
|
||||
|
||||
let app: ReturnType<typeof Fastify> | null = null;
|
||||
let adminToken = "";
|
||||
const quotationIds: number[] = [];
|
||||
const invoiceIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(offersPdfRoutes, { prefix: "/api/admin/offers-pdf" });
|
||||
await app.register(invoicesPdfRoutes, { prefix: "/api/admin/invoices-pdf" });
|
||||
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 () => {
|
||||
for (const id of quotationIds)
|
||||
await prisma.quotations.deleteMany({ where: { id } });
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
const offerHtml = async (discount: number): Promise<string> => {
|
||||
const q = await prisma.quotations.create({
|
||||
data: {
|
||||
quotation_number: `Q-SLEVA-${discount}-${Date.now()}`,
|
||||
status: "active",
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
quotation_items: {
|
||||
create: [
|
||||
{
|
||||
description: "Položka",
|
||||
quantity: 2,
|
||||
unit: "ks",
|
||||
unit_price: 100,
|
||||
discount,
|
||||
is_included_in_total: true,
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
quotationIds.push(q.id);
|
||||
const res = await app!.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/offers-pdf/${q.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return res.body;
|
||||
};
|
||||
|
||||
describe("offer PDF Sleva column", () => {
|
||||
it("renders a Sleva column + discounted total when an item has a discount", async () => {
|
||||
const html = await offerHtml(10);
|
||||
expect(html).toContain("Sleva");
|
||||
// 2 × 100 with 10% off => 180,00 (no thousands separator at this size).
|
||||
expect(html).toContain("180,00");
|
||||
expect(html).not.toContain("200,00");
|
||||
});
|
||||
|
||||
it("omits the Sleva column when no item has a discount", async () => {
|
||||
const html = await offerHtml(0);
|
||||
expect(html).not.toContain("Sleva");
|
||||
expect(html).toContain("200,00");
|
||||
});
|
||||
});
|
||||
|
||||
const invoiceHtml = async (discount: number): Promise<string> => {
|
||||
const inv = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
apply_vat: true,
|
||||
vat_rate: 21,
|
||||
language: "cs",
|
||||
items: [
|
||||
{
|
||||
description: "Položka",
|
||||
quantity: 2,
|
||||
unit_price: 1000,
|
||||
discount,
|
||||
vat_rate: 21,
|
||||
},
|
||||
],
|
||||
});
|
||||
invoiceIds.push(inv.id);
|
||||
const res = await app!.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/invoices-pdf/${inv.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return res.body;
|
||||
};
|
||||
|
||||
describe("invoice PDF Sleva column", () => {
|
||||
it("renders a Sleva column when an item has a discount", async () => {
|
||||
const html = await invoiceHtml(10);
|
||||
expect(html).toContain("Sleva");
|
||||
expect(html).toContain("10");
|
||||
});
|
||||
|
||||
it("omits the Sleva column when no item has a discount", async () => {
|
||||
const html = await invoiceHtml(0);
|
||||
expect(html).not.toContain("Sleva");
|
||||
});
|
||||
});
|
||||
55
src/__tests__/item-discount-schema.test.ts
Normal file
55
src/__tests__/item-discount-schema.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { CreateQuotationSchema } from "../schemas/offers.schema";
|
||||
import { CreateInvoiceSchema } from "../schemas/invoices.schema";
|
||||
|
||||
/**
|
||||
* The per-item Sleva is a percentage: the offer- and invoice-item schemas must
|
||||
* accept 0–100, default to 0 when absent, and reject out-of-range values.
|
||||
*/
|
||||
|
||||
describe("offer item discount schema", () => {
|
||||
it("accepts a 0–100 discount", () => {
|
||||
const r = CreateQuotationSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100, discount: 15 }],
|
||||
});
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.success && r.data.items?.[0].discount).toBe(15);
|
||||
});
|
||||
|
||||
it("defaults discount to 0 when absent", () => {
|
||||
const r = CreateQuotationSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100 }],
|
||||
});
|
||||
expect(r.success && r.data.items?.[0].discount).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects a discount above 100", () => {
|
||||
const r = CreateQuotationSchema.safeParse({
|
||||
items: [
|
||||
{ description: "X", quantity: 1, unit_price: 100, discount: 150 },
|
||||
],
|
||||
});
|
||||
expect(r.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("invoice item discount schema", () => {
|
||||
it("accepts a 0–100 discount and defaults to 0", () => {
|
||||
const ok = CreateInvoiceSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100, discount: 10 }],
|
||||
});
|
||||
expect(ok.success && ok.data.items?.[0].discount).toBe(10);
|
||||
|
||||
const def = CreateInvoiceSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100 }],
|
||||
});
|
||||
expect(def.success && def.data.items?.[0].discount).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects a negative discount", () => {
|
||||
const r = CreateInvoiceSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100, discount: -5 }],
|
||||
});
|
||||
expect(r.success).toBe(false);
|
||||
});
|
||||
});
|
||||
94
src/__tests__/item-discount-totals.test.ts
Normal file
94
src/__tests__/item-discount-totals.test.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { createOffer, getOfferTotals } from "../services/offers.service";
|
||||
import {
|
||||
createInvoice,
|
||||
getInvoiceListTotals,
|
||||
} from "../services/invoices.service";
|
||||
|
||||
/**
|
||||
* Per-item Sleva (% discount) must reduce the line NET — and on invoices the
|
||||
* VAT is computed on the discounted net. Hits the real `app_test` DB through the
|
||||
* service layer (suite convention), mirroring offer-invoice-totals.test.ts.
|
||||
*/
|
||||
|
||||
const MARKER = "SLEVA-TOTALS-2096";
|
||||
const YEAR = 2096;
|
||||
const MONTH = 8; // invoice issue_date window [2096-08-01, 2096-09-01)
|
||||
const dateStr = `${YEAR}-0${MONTH}-15`;
|
||||
|
||||
const offerIds: number[] = [];
|
||||
const invoiceIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of offerIds)
|
||||
await prisma.quotations.deleteMany({ where: { id } });
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
offerIds.length = 0;
|
||||
invoiceIds.length = 0;
|
||||
await prisma.number_sequences.deleteMany({
|
||||
where: { type: { in: ["offer", "invoice"] } },
|
||||
});
|
||||
});
|
||||
|
||||
const amountFor = (
|
||||
totals: { currency: string; amount: number }[],
|
||||
currency: string,
|
||||
): number | undefined => totals.find((t) => t.currency === currency)?.amount;
|
||||
|
||||
describe("offer per-item discount", () => {
|
||||
it("reduces the offer NET total by the per-item percentage", async () => {
|
||||
// 2 × 1000 with 10% off => 1800 net.
|
||||
const res = await createOffer({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
project_code: MARKER,
|
||||
items: [
|
||||
{ description: "X", quantity: 2, unit_price: 1000, discount: 10 },
|
||||
],
|
||||
});
|
||||
if ("error" in res) throw new Error(JSON.stringify(res));
|
||||
offerIds.push(res.id);
|
||||
|
||||
const { totals } = await getOfferTotals({ search: MARKER });
|
||||
expect(amountFor(totals, "CZK")).toBe(1800);
|
||||
});
|
||||
});
|
||||
|
||||
describe("invoice per-item discount", () => {
|
||||
it("computes VAT on the discounted net (gross = discounted net + VAT)", async () => {
|
||||
// 2 × 1000 with 10% off => net 1800, VAT@21% = 378, gross 2178.
|
||||
const inv = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
vat_rate: 21,
|
||||
apply_vat: true,
|
||||
issue_date: dateStr,
|
||||
items: [
|
||||
{ description: "X", quantity: 2, unit_price: 1000, discount: 10 },
|
||||
],
|
||||
});
|
||||
invoiceIds.push(inv.id);
|
||||
|
||||
const { totals } = await getInvoiceListTotals({ month: MONTH, year: YEAR });
|
||||
expect(amountFor(totals, "CZK")).toBe(2178);
|
||||
});
|
||||
|
||||
it("treats a 100% discount line as zero", async () => {
|
||||
const inv = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
vat_rate: 21,
|
||||
apply_vat: true,
|
||||
issue_date: dateStr,
|
||||
items: [
|
||||
{ description: "Free", quantity: 5, unit_price: 200, discount: 100 },
|
||||
],
|
||||
});
|
||||
invoiceIds.push(inv.id);
|
||||
|
||||
const { totals } = await getInvoiceListTotals({ month: MONTH, year: YEAR });
|
||||
expect(amountFor(totals, "CZK")).toBeUndefined(); // zero totals are dropped
|
||||
});
|
||||
});
|
||||
202
src/__tests__/leave-requests-holidays.test.ts
Normal file
202
src/__tests__/leave-requests-holidays.test.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
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 leaveRequestsRoutes from "../routes/admin/leave-requests";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding H6 + the year-spanning fast-follow:
|
||||
* leave-request creation and approval must mirror attendance.service
|
||||
* createLeave — skip Czech public holidays (a weekday holiday is already
|
||||
* paid/free; charging it double-deducts) and book each day's hours against
|
||||
* ITS OWN calendar year's balance (a Dec→Jan request used to charge
|
||||
* everything to the start year).
|
||||
*
|
||||
* Fixture math (verified): 2098-05-01 (Thu) and 2098-05-08 (Thu) are both
|
||||
* weekday holidays → the 05-01..05-08 range has 4 chargeable days (32h),
|
||||
* not 6 (48h). 2098-12-28 (Sun)..2099-01-05 (Mon) has 3 chargeable days in
|
||||
* 2098 (29/30/31 = 24h) and 2 in 2099 (Jan 2 + Jan 5 = 16h; Jan 1 is a
|
||||
* holiday).
|
||||
*/
|
||||
|
||||
const N = "leave_holiday_";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let userToken: string;
|
||||
let userId: number;
|
||||
|
||||
async function cleanup() {
|
||||
const users = await prisma.users.findMany({
|
||||
where: { username: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const ids = users.map((u) => u.id);
|
||||
if (ids.length > 0) {
|
||||
await prisma.attendance.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.leave_requests.deleteMany({
|
||||
where: { user_id: { in: ids } },
|
||||
});
|
||||
await prisma.leave_balances.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.users.deleteMany({ where: { id: { in: ids } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(leaveRequestsRoutes, {
|
||||
prefix: "/api/admin/leave-requests",
|
||||
});
|
||||
|
||||
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" },
|
||||
);
|
||||
|
||||
const role = await prisma.roles.findFirst();
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
first_name: "Leave",
|
||||
last_name: "Holiday",
|
||||
is_active: true,
|
||||
role_id: role!.id,
|
||||
},
|
||||
});
|
||||
userId = user.id;
|
||||
userToken = jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: role!.name },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
|
||||
for (const year of [2098, 2099]) {
|
||||
await prisma.leave_balances.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
year,
|
||||
vacation_total: 200,
|
||||
vacation_used: 0,
|
||||
sick_used: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
async function balance(year: number) {
|
||||
return prisma.leave_balances.findFirst({
|
||||
where: { user_id: userId, year },
|
||||
});
|
||||
}
|
||||
|
||||
describe("leave requests vs Czech holidays (audit H6)", () => {
|
||||
it("creation excludes weekday public holidays from the charged total", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/leave-requests",
|
||||
headers: {
|
||||
Authorization: `Bearer ${userToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
leave_type: "vacation",
|
||||
date_from: "2098-05-01",
|
||||
date_to: "2098-05-08",
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const row = await prisma.leave_requests.findFirst({
|
||||
where: { id: res.json().data.id },
|
||||
});
|
||||
expect(row?.total_days).toBe(4);
|
||||
expect(Number(row?.total_hours)).toBe(32);
|
||||
// Leave it cancelled so the approval test's range stays free.
|
||||
await prisma.leave_requests.update({
|
||||
where: { id: row!.id },
|
||||
data: { status: "cancelled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("approval charges only non-holiday business days and skips holiday attendance rows", async () => {
|
||||
// Stored totals mimic a PRE-FIX request (weekend-only counting) — the
|
||||
// approval must recompute, not trust them.
|
||||
const req = await prisma.leave_requests.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
leave_type: "vacation",
|
||||
date_from: new Date(Date.UTC(2098, 4, 1)),
|
||||
date_to: new Date(Date.UTC(2098, 4, 8)),
|
||||
total_hours: 48,
|
||||
total_days: 6,
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/leave-requests/${req.id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { status: "approved" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
expect(Number((await balance(2098))?.vacation_used)).toBe(32);
|
||||
|
||||
const rows = await prisma.attendance.findMany({
|
||||
where: { user_id: userId, leave_type: "vacation" },
|
||||
});
|
||||
const days = rows.map((r) => r.shift_date.toISOString().slice(0, 10));
|
||||
expect(rows).toHaveLength(4);
|
||||
expect(days).not.toContain("2098-05-01");
|
||||
expect(days).not.toContain("2098-05-08");
|
||||
});
|
||||
|
||||
it("a year-spanning approval books each day against its own year's balance", async () => {
|
||||
const req = await prisma.leave_requests.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
leave_type: "sick",
|
||||
date_from: new Date(Date.UTC(2098, 11, 28)),
|
||||
date_to: new Date(Date.UTC(2099, 0, 5)),
|
||||
total_hours: 48,
|
||||
total_days: 6,
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/leave-requests/${req.id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { status: "approved" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// 29/30/31 Dec 2098 = 24h; Jan 2 + Jan 5 2099 = 16h (Jan 1 is a holiday).
|
||||
expect(Number((await balance(2098))?.sick_used)).toBe(24);
|
||||
expect(Number((await balance(2099))?.sick_used)).toBe(16);
|
||||
});
|
||||
});
|
||||
117
src/__tests__/modal-duplicate-close.test.ts
Normal file
117
src/__tests__/modal-duplicate-close.test.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
/**
|
||||
* Guards against the "two Zavřít buttons" bug class.
|
||||
*
|
||||
* The shared <Modal> (src/admin/ui/Modal.tsx) ALWAYS renders a primary submit
|
||||
* button (text = `submitText`) and — unless `hideCancel` is set — a secondary
|
||||
* cancel button (text = `cancelText`, default "Zrušit"). A close-only modal
|
||||
* therefore sets `submitText="Zavřít"`; if it ALSO leaves the cancel button on,
|
||||
* the user sees two buttons that both just close the dialog — and when
|
||||
* `cancelText` is "Zavřít" too, two literally-identical "Zavřít" buttons
|
||||
* (the production bug found on the "paid received invoice" detail modal).
|
||||
*
|
||||
* Rule enforced: any <Modal> whose `submitText` is a "Zavřít…" label (i.e. its
|
||||
* only action is to close) MUST pass `hideCancel`. Close-only modals get a
|
||||
* single button. See PlanCellModal / PlanCategoriesModal for the correct shape.
|
||||
*/
|
||||
|
||||
const ADMIN_DIR = join(__dirname, "..", "admin");
|
||||
|
||||
function tsxFiles(dir: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) out.push(...tsxFiles(full));
|
||||
else if (entry.name.endsWith(".tsx")) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract every `<Modal …>` opening-tag substring from a source string.
|
||||
* Brace- and string-aware so arrow functions (`=>`) and conditional props
|
||||
* (`{cond ? "a" : "b"}`) inside the tag don't terminate it early.
|
||||
*/
|
||||
function modalOpeningTags(src: string): string[] {
|
||||
const tags: string[] = [];
|
||||
let i = 0;
|
||||
while ((i = src.indexOf("<Modal", i)) !== -1) {
|
||||
const after = src[i + 6];
|
||||
// Must be the <Modal> component, not <ModalSomething>.
|
||||
if (after && !/[\s>/]/.test(after)) {
|
||||
i += 6;
|
||||
continue;
|
||||
}
|
||||
let depth = 0;
|
||||
let quote: string | null = null;
|
||||
let j = i + 6;
|
||||
for (; j < src.length; j++) {
|
||||
const c = src[j];
|
||||
if (quote) {
|
||||
if (c === quote && src[j - 1] !== "\\") quote = null;
|
||||
continue;
|
||||
}
|
||||
if (c === '"' || c === "'" || c === "`") quote = c;
|
||||
else if (c === "{") depth++;
|
||||
else if (c === "}") depth--;
|
||||
else if (c === ">" && depth === 0) break;
|
||||
}
|
||||
tags.push(src.slice(i, j + 1));
|
||||
i = j + 1;
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/** Value of a JSX prop: `name="..."`, `name={...}` (balanced), or boolean. */
|
||||
function propValue(tag: string, name: string): string | null {
|
||||
const re = new RegExp(`\\b${name}\\b`);
|
||||
const m = re.exec(tag);
|
||||
if (!m) return null;
|
||||
let k = m.index + m[0].length;
|
||||
while (k < tag.length && /\s/.test(tag[k])) k++;
|
||||
if (tag[k] !== "=") return ""; // boolean prop (e.g. `hideCancel`)
|
||||
k++;
|
||||
while (k < tag.length && /\s/.test(tag[k])) k++;
|
||||
if (tag[k] === '"' || tag[k] === "'") {
|
||||
const q = tag[k];
|
||||
const end = tag.indexOf(q, k + 1);
|
||||
return tag.slice(k + 1, end);
|
||||
}
|
||||
if (tag[k] === "{") {
|
||||
let depth = 0;
|
||||
for (let p = k; p < tag.length; p++) {
|
||||
if (tag[p] === "{") depth++;
|
||||
else if (tag[p] === "}" && --depth === 0) return tag.slice(k, p + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
describe("Modal close-only buttons", () => {
|
||||
const offenders: string[] = [];
|
||||
|
||||
for (const file of tsxFiles(ADMIN_DIR)) {
|
||||
const src = readFileSync(file, "utf8");
|
||||
for (const tag of modalOpeningTags(src)) {
|
||||
const submit = propValue(tag, "submitText");
|
||||
const isCloseOnly = submit != null && submit.includes("Zavřít");
|
||||
const hasHideCancel = propValue(tag, "hideCancel") != null;
|
||||
if (isCloseOnly && !hasHideCancel) {
|
||||
const title = propValue(tag, "title") ?? "(no title)";
|
||||
offenders.push(`${file.replace(ADMIN_DIR, "admin")} — ${title}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it("close-only modals (submitText='Zavřít') set hideCancel — no duplicate close button", () => {
|
||||
expect(
|
||||
offenders,
|
||||
`These <Modal>s render a close-only 'Zavřít' submit alongside a redundant ` +
|
||||
`cancel button (two buttons that both just close). Add hideCancel:\n` +
|
||||
offenders.map((o) => ` • ${o}`).join("\n"),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
22
src/__tests__/money.test.ts
Normal file
22
src/__tests__/money.test.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { lineNet } from "../utils/money";
|
||||
|
||||
describe("lineNet (per-item discounted net)", () => {
|
||||
it("returns qty × unit_price when there is no discount", () => {
|
||||
expect(lineNet(2, 1000, 0)).toBe(2000);
|
||||
});
|
||||
|
||||
it("applies a percentage discount to the line net", () => {
|
||||
expect(lineNet(2, 1000, 10)).toBe(1800);
|
||||
});
|
||||
|
||||
it("treats a 100% discount as zero", () => {
|
||||
expect(lineNet(3, 500, 100)).toBe(0);
|
||||
});
|
||||
|
||||
it("treats null/undefined/NaN discount as no discount", () => {
|
||||
expect(lineNet(2, 1000, null)).toBe(2000);
|
||||
expect(lineNet(2, 1000, undefined)).toBe(2000);
|
||||
expect(lineNet(2, 1000, NaN)).toBe(2000);
|
||||
});
|
||||
});
|
||||
51
src/__tests__/navdata-icons.test.ts
Normal file
51
src/__tests__/navdata-icons.test.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { isValidElement, type ReactElement } from "react";
|
||||
import { menuSections, type MenuItem } from "../admin/ui/navData";
|
||||
|
||||
/**
|
||||
* Pins the sidebar icon-refresh contract (2026-06-12 design): every menu
|
||||
* item has a glyph, and no two items share one — duplicated glyphs were the
|
||||
* whole problem the refresh fixed (3× "people", 3× "sliders", …). Odin's
|
||||
* rawIcon (OdinMark, MUI-styled + animated) is exempt from rendering here
|
||||
* but still must exist and stay the ONLY rawIcon.
|
||||
*/
|
||||
|
||||
const allItems: Array<MenuItem & { section: string }> = menuSections.flatMap(
|
||||
(s) => s.items.map((item) => ({ section: s.label, ...item })),
|
||||
);
|
||||
|
||||
describe("sidebar nav icons", () => {
|
||||
it("every item has an icon and a section hue", () => {
|
||||
for (const section of menuSections) {
|
||||
expect(section.hue, `section ${section.label}`).toBeTruthy();
|
||||
}
|
||||
for (const item of allItems) {
|
||||
expect(isValidElement(item.icon), `${item.section}/${item.label}`).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("Odin is the only rawIcon (its own tile + animation stay unique)", () => {
|
||||
const raw = allItems.filter((i) => i.rawIcon);
|
||||
expect(raw.map((i) => i.label)).toEqual(["Odin"]);
|
||||
});
|
||||
|
||||
it("no two items share a glyph", () => {
|
||||
const rendered = allItems
|
||||
.filter((i) => !i.rawIcon)
|
||||
.map((item) => ({
|
||||
key: `${item.section}/${item.label}`,
|
||||
markup: renderToStaticMarkup(item.icon as ReactElement),
|
||||
}));
|
||||
|
||||
const seen = new Map<string, string>();
|
||||
for (const { key, markup } of rendered) {
|
||||
const dupe = seen.get(markup);
|
||||
expect(dupe, `${key} shares its glyph with ${dupe}`).toBeUndefined();
|
||||
seen.set(markup, key);
|
||||
}
|
||||
expect(seen.size).toBe(rendered.length);
|
||||
});
|
||||
});
|
||||
100
src/__tests__/offer-number-release.test.ts
Normal file
100
src/__tests__/offer-number-release.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { deleteOffer } from "../services/offers.service";
|
||||
import { applyPattern } from "../services/numbering.service";
|
||||
|
||||
/**
|
||||
* Pinning test for audit finding L2: an offer created in year Y but
|
||||
* finalized (numbered) in year Y+1 must release the Y+1 sequence on delete.
|
||||
* deleteOffer used to derive the release year from created_at, so the
|
||||
* reconstructed highest number ("2025/NA/...") never matched the actual
|
||||
* "2026/NA/..." and the counter kept a permanent gap.
|
||||
*/
|
||||
|
||||
const CURRENT_YEAR = new Date().getFullYear();
|
||||
|
||||
let offerId: number;
|
||||
let originalLastNumber: number | null = null; // null = row absent before test
|
||||
let offerNumber: string;
|
||||
|
||||
async function getSeq(): Promise<number | null> {
|
||||
const rows = await prisma.$queryRaw<Array<{ last_number: number }>>`
|
||||
SELECT last_number FROM number_sequences
|
||||
WHERE \`type\` = 'offer' AND \`year\` = ${CURRENT_YEAR}
|
||||
`;
|
||||
return rows.length > 0 ? Number(rows[0].last_number) : null;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
const settings = await prisma.company_settings.findFirst();
|
||||
const pattern = settings?.offer_number_pattern || "{YYYY}/{PREFIX}/{NNN}";
|
||||
const prefix = settings?.quotation_prefix || "NA";
|
||||
|
||||
originalLastNumber = await getSeq();
|
||||
const base = originalLastNumber ?? 0;
|
||||
const seq = base + 1;
|
||||
offerNumber = applyPattern(pattern, {
|
||||
year: CURRENT_YEAR,
|
||||
prefix,
|
||||
code: "",
|
||||
seq,
|
||||
});
|
||||
|
||||
// Consume the number in the sequence (what finalize would have done).
|
||||
if (originalLastNumber === null) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO number_sequences (\`type\`, \`year\`, \`last_number\`)
|
||||
VALUES ('offer', ${CURRENT_YEAR}, ${seq})
|
||||
`;
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
UPDATE number_sequences SET \`last_number\` = ${seq}
|
||||
WHERE \`type\` = 'offer' AND \`year\` = ${CURRENT_YEAR}
|
||||
`;
|
||||
}
|
||||
|
||||
// The offer itself was CREATED last year (draft), finalized this year —
|
||||
// its number carries the finalize year, created_at the draft year.
|
||||
const offer = await prisma.quotations.create({
|
||||
data: {
|
||||
quotation_number: offerNumber,
|
||||
status: "active",
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
created_at: new Date(CURRENT_YEAR - 1, 11, 30, 12, 0, 0),
|
||||
},
|
||||
});
|
||||
offerId = offer.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prisma.quotations
|
||||
.deleteMany({ where: { id: offerId } })
|
||||
.catch(() => {});
|
||||
// Restore the sequence to its pre-test value regardless of outcome.
|
||||
if (originalLastNumber === null) {
|
||||
await prisma.$executeRaw`
|
||||
DELETE FROM number_sequences
|
||||
WHERE \`type\` = 'offer' AND \`year\` = ${CURRENT_YEAR}
|
||||
`;
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
UPDATE number_sequences SET \`last_number\` = ${originalLastNumber}
|
||||
WHERE \`type\` = 'offer' AND \`year\` = ${CURRENT_YEAR}
|
||||
`;
|
||||
}
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("offer sequence release across years (audit L2)", () => {
|
||||
it("releases the finalize-year sequence when created_at is in a previous year", async () => {
|
||||
const before = await getSeq();
|
||||
expect(before).toBe((originalLastNumber ?? 0) + 1);
|
||||
|
||||
const result = await deleteOffer(offerId);
|
||||
expect(result && "error" in result ? result.error : null).toBeNull();
|
||||
|
||||
// The highest number was just deleted → the counter must step back.
|
||||
expect(await getSeq()).toBe(originalLastNumber ?? 0);
|
||||
});
|
||||
});
|
||||
126
src/__tests__/pagination-tiebreak.test.ts
Normal file
126
src/__tests__/pagination-tiebreak.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
106
src/__tests__/plan-update-cap.test.ts
Normal file
106
src/__tests__/plan-update-cap.test.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { updateEntry } from "../services/plan.service";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M9: updateEntry must re-check the per-cell
|
||||
* cap (MAX_RECORDS_PER_CELL = 3) when the date range changes — expanding an
|
||||
* entry onto a day that already holds 3 active entries used to succeed,
|
||||
* producing a 4th that the grid (capped at 3) silently hides.
|
||||
*
|
||||
* The re-check must EXCLUDE the updated entry itself, so editing an at-cap
|
||||
* entry without moving it stays allowed.
|
||||
*/
|
||||
|
||||
const NOTE = "plan_updcap_test";
|
||||
|
||||
let userId: number;
|
||||
let cappedEntryIds: number[] = [];
|
||||
let fourthId: number;
|
||||
|
||||
const D = (day: number) => new Date(Date.UTC(2099, 6, day)); // July 2099, UTC
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.work_plan_entries.deleteMany({ where: { note: NOTE } });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const user = await prisma.users.findFirst({ select: { id: true } });
|
||||
if (!user) throw new Error("Test setup: no users — seed the database");
|
||||
userId = user.id;
|
||||
|
||||
cappedEntryIds = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const entry = await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
date_from: D(1),
|
||||
date_to: D(1),
|
||||
category: "work",
|
||||
note: NOTE,
|
||||
created_by: userId,
|
||||
},
|
||||
});
|
||||
cappedEntryIds.push(entry.id);
|
||||
}
|
||||
const fourth = await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
date_from: D(2),
|
||||
date_to: D(2),
|
||||
category: "work",
|
||||
note: NOTE,
|
||||
created_by: userId,
|
||||
},
|
||||
});
|
||||
fourthId = fourth.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("updateEntry per-cell cap (audit M9)", () => {
|
||||
it("rejects expanding an entry onto a day already at the cap", async () => {
|
||||
const result = await updateEntry(
|
||||
fourthId,
|
||||
{ date_from: "2099-07-01", date_to: "2099-07-01" },
|
||||
userId,
|
||||
false,
|
||||
);
|
||||
|
||||
expect("error" in result).toBe(true);
|
||||
if ("error" in result) expect(result.status).toBe(400);
|
||||
|
||||
// The entry must not have moved.
|
||||
const fresh = await prisma.work_plan_entries.findUnique({
|
||||
where: { id: fourthId },
|
||||
});
|
||||
expect(fresh?.date_from.toISOString().slice(0, 10)).toBe("2099-07-02");
|
||||
});
|
||||
|
||||
it("still allows editing an at-cap entry without moving it (self-exclusion)", async () => {
|
||||
const result = await updateEntry(
|
||||
cappedEntryIds[0],
|
||||
{ date_from: "2099-07-01", date_to: "2099-07-01", note: NOTE },
|
||||
userId,
|
||||
false,
|
||||
);
|
||||
expect("error" in result).toBe(false);
|
||||
});
|
||||
|
||||
it("still allows a note-only edit and a move to a free day", async () => {
|
||||
const noteOnly = await updateEntry(fourthId, { note: NOTE }, userId, false);
|
||||
expect("error" in noteOnly).toBe(false);
|
||||
|
||||
const move = await updateEntry(
|
||||
fourthId,
|
||||
{ date_from: "2099-07-03", date_to: "2099-07-03" },
|
||||
userId,
|
||||
false,
|
||||
);
|
||||
expect("error" in move).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1090,26 +1090,6 @@ async function authPost(path: string, token: string, body: unknown) {
|
||||
});
|
||||
}
|
||||
|
||||
async function authPatch(path: string, token: string, body: unknown) {
|
||||
return app.inject({
|
||||
method: "PATCH",
|
||||
url: path,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: body as object,
|
||||
});
|
||||
}
|
||||
|
||||
async function authDelete(path: string, token: string) {
|
||||
return app.inject({
|
||||
method: "DELETE",
|
||||
url: path,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
|
||||
|
||||
76
src/__tests__/projects-update-fk.test.ts
Normal file
76
src/__tests__/projects-update-fk.test.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { updateProject } from "../services/projects.service";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M6: updateProject must pre-validate FK ids
|
||||
* (customer_id, responsible_user_id, quotation_id, order_id) and return clean
|
||||
* Czech 400s like createProject does — a dangling id otherwise raises P2003
|
||||
* at Prisma and surfaces as a generic 500.
|
||||
*/
|
||||
|
||||
const N = "prj_fk_";
|
||||
|
||||
let projectId: number;
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.projects.deleteMany({ where: { name: { startsWith: N } } });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const project = await prisma.projects.create({
|
||||
data: { name: `${N}project`, status: "active" },
|
||||
});
|
||||
projectId = project.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
function isError(r: unknown): r is { error: string; status: number } {
|
||||
return typeof r === "object" && r !== null && "error" in r;
|
||||
}
|
||||
|
||||
describe("updateProject FK existence checks (audit M6)", () => {
|
||||
it.each([
|
||||
["customer_id", "Zákazník nenalezen"],
|
||||
["responsible_user_id", "Zodpovědná osoba nenalezena"],
|
||||
["quotation_id", "Nabídka nenalezena"],
|
||||
["order_id", "Zakázka nenalezena"],
|
||||
])("returns a Czech 400 for a dangling %s", async (field, message) => {
|
||||
const result = await updateProject(projectId, { [field]: 99999999 });
|
||||
|
||||
expect(isError(result)).toBe(true);
|
||||
if (isError(result)) {
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toBe(message);
|
||||
}
|
||||
|
||||
// Nothing was written.
|
||||
const fresh = await prisma.projects.findUnique({
|
||||
where: { id: projectId },
|
||||
});
|
||||
expect(fresh?.[field as "customer_id"]).toBeNull();
|
||||
});
|
||||
|
||||
it("still allows clearing an FK with null", async () => {
|
||||
const result = await updateProject(projectId, { customer_id: null });
|
||||
expect(isError(result)).toBe(false);
|
||||
});
|
||||
|
||||
it("still allows setting a valid FK", async () => {
|
||||
const user = await prisma.users.findFirst({ select: { id: true } });
|
||||
expect(user).not.toBeNull();
|
||||
const result = await updateProject(projectId, {
|
||||
responsible_user_id: user!.id,
|
||||
});
|
||||
expect(isError(result)).toBe(false);
|
||||
const fresh = await prisma.projects.findUnique({
|
||||
where: { id: projectId },
|
||||
});
|
||||
expect(fresh?.responsible_user_id).toBe(user!.id);
|
||||
});
|
||||
});
|
||||
115
src/__tests__/received-invoice-dates.test.ts
Normal file
115
src/__tests__/received-invoice-dates.test.ts
Normal 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");
|
||||
});
|
||||
});
|
||||
394
src/__tests__/schema-caps.test.ts
Normal file
394
src/__tests__/schema-caps.test.ts
Normal file
@@ -0,0 +1,394 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { z } from "zod";
|
||||
import {
|
||||
CreateOrderSchema,
|
||||
UpdateOrderSchema,
|
||||
CreateOrderFromQuotationSchema,
|
||||
} from "../schemas/orders.schema";
|
||||
import {
|
||||
CreateInvoiceSchema,
|
||||
UpdateInvoiceSchema,
|
||||
} from "../schemas/invoices.schema";
|
||||
import { CreateTripSchema, UpdateTripSchema } from "../schemas/trips.schema";
|
||||
import { TotpEnableSchema } from "../schemas/auth.schema";
|
||||
import {
|
||||
CreateReceivedInvoiceSchema,
|
||||
UpdateReceivedInvoiceSchema,
|
||||
} from "../schemas/received-invoices.schema";
|
||||
import {
|
||||
CreateSupplierSchema,
|
||||
UpdateSupplierSchema,
|
||||
} from "../schemas/warehouse.schema";
|
||||
import {
|
||||
CreateCustomerSchema,
|
||||
UpdateCustomerSchema,
|
||||
} from "../schemas/customers.schema";
|
||||
|
||||
/**
|
||||
* Pinning tests for the Zod-cap-vs-DB-column class (audit H2, M2, M4, M11,
|
||||
* L1, L8d, L8e + adjacent invoice item/bank caps): every form-facing string
|
||||
* cap must fit its DB column width, or an over-width value passes Zod and
|
||||
* dies at Prisma as a 500 (P2000) instead of a clean Czech 400.
|
||||
*
|
||||
* Each case asserts BOTH directions: width+1 chars must FAIL the schema, and
|
||||
* exactly width chars must PASS (guards against over-tightening — stored
|
||||
* values can never exceed the column width, so re-submitted edit forms stay
|
||||
* valid).
|
||||
*/
|
||||
|
||||
interface CapCase {
|
||||
name: string;
|
||||
schema: z.ZodTypeAny;
|
||||
/** DB column width from prisma/schema.prisma */
|
||||
width: number;
|
||||
build: (value: string) => unknown;
|
||||
}
|
||||
|
||||
const tripBase = {
|
||||
vehicle_id: 1,
|
||||
trip_date: "2098-03-02",
|
||||
start_km: 0,
|
||||
end_km: 1,
|
||||
route_from: "A",
|
||||
route_to: "B",
|
||||
};
|
||||
const receivedBase = { supplier_name: "X", month: 6, year: 2026 };
|
||||
|
||||
const CASES: CapCase[] = [
|
||||
// ── orders.schema.ts vs order_items / orders ──
|
||||
{
|
||||
name: "CreateOrderSchema items.description",
|
||||
schema: CreateOrderSchema,
|
||||
width: 500,
|
||||
build: (v) => ({ items: [{ description: v }] }),
|
||||
},
|
||||
{
|
||||
name: "CreateOrderSchema items.unit",
|
||||
schema: CreateOrderSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ items: [{ unit: v }] }),
|
||||
},
|
||||
{
|
||||
name: "CreateOrderSchema order_number",
|
||||
schema: CreateOrderSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ order_number: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateOrderSchema customer_order_number",
|
||||
schema: CreateOrderSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ customer_order_number: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateOrderSchema currency",
|
||||
schema: CreateOrderSchema,
|
||||
width: 10,
|
||||
build: (v) => ({ currency: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateOrderSchema language",
|
||||
schema: CreateOrderSchema,
|
||||
width: 5,
|
||||
build: (v) => ({ language: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateOrderSchema customer_order_number",
|
||||
schema: UpdateOrderSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ customer_order_number: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateOrderSchema currency",
|
||||
schema: UpdateOrderSchema,
|
||||
width: 10,
|
||||
build: (v) => ({ currency: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateOrderSchema language",
|
||||
schema: UpdateOrderSchema,
|
||||
width: 5,
|
||||
build: (v) => ({ language: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateOrderFromQuotationSchema customerOrderNumber",
|
||||
schema: CreateOrderFromQuotationSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ quotationId: 1, customerOrderNumber: v }),
|
||||
},
|
||||
// ── invoices.schema.ts vs invoice_items / invoices ──
|
||||
{
|
||||
name: "CreateInvoiceSchema items.description",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 500,
|
||||
build: (v) => ({ items: [{ description: v }] }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema items.unit",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ items: [{ unit: v }] }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema invoice_number",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ invoice_number: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema currency",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 10,
|
||||
build: (v) => ({ currency: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema language",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 5,
|
||||
build: (v) => ({ language: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema payment_method",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ payment_method: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema constant_symbol",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ constant_symbol: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema bank_swift",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ bank_swift: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema bank_iban",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ bank_iban: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema bank_account",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ bank_account: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateInvoiceSchema billing_text",
|
||||
schema: CreateInvoiceSchema,
|
||||
width: 500,
|
||||
build: (v) => ({ billing_text: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema currency",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 10,
|
||||
build: (v) => ({ currency: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema language",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 5,
|
||||
build: (v) => ({ language: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema payment_method",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ payment_method: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema constant_symbol",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ constant_symbol: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema bank_swift",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ bank_swift: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema bank_iban",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ bank_iban: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema bank_account",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ bank_account: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateInvoiceSchema billing_text",
|
||||
schema: UpdateInvoiceSchema,
|
||||
width: 500,
|
||||
build: (v) => ({ billing_text: v }),
|
||||
},
|
||||
// ── trips.schema.ts vs trips ──
|
||||
{
|
||||
name: "CreateTripSchema route_from",
|
||||
schema: CreateTripSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ ...tripBase, route_from: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateTripSchema route_to",
|
||||
schema: CreateTripSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ ...tripBase, route_to: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateTripSchema route_from",
|
||||
schema: UpdateTripSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ route_from: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateTripSchema route_to",
|
||||
schema: UpdateTripSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ route_to: v }),
|
||||
},
|
||||
// ── auth.schema.ts vs users.totp_secret ──
|
||||
// The stored value is AES-256-GCM ciphertext (base64(IV+ct+tag)) of the
|
||||
// plaintext secret in a VarChar(255) column: a plaintext over ~164 chars
|
||||
// overflows after encryption. Real TOTP secrets are 16-32 chars; cap 64.
|
||||
{
|
||||
name: "TotpEnableSchema secret",
|
||||
schema: TotpEnableSchema,
|
||||
width: 64,
|
||||
build: (v) => ({ secret: v, code: "123456" }),
|
||||
},
|
||||
// ── received-invoices.schema.ts vs received_invoices ──
|
||||
{
|
||||
name: "CreateReceivedInvoiceSchema description",
|
||||
schema: CreateReceivedInvoiceSchema,
|
||||
width: 500,
|
||||
build: (v) => ({ ...receivedBase, description: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateReceivedInvoiceSchema invoice_number",
|
||||
schema: CreateReceivedInvoiceSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ ...receivedBase, invoice_number: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateReceivedInvoiceSchema currency",
|
||||
schema: CreateReceivedInvoiceSchema,
|
||||
width: 3,
|
||||
build: (v) => ({ ...receivedBase, currency: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateReceivedInvoiceSchema description",
|
||||
schema: UpdateReceivedInvoiceSchema,
|
||||
width: 500,
|
||||
build: (v) => ({ description: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateReceivedInvoiceSchema invoice_number",
|
||||
schema: UpdateReceivedInvoiceSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ invoice_number: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateReceivedInvoiceSchema currency",
|
||||
schema: UpdateReceivedInvoiceSchema,
|
||||
width: 3,
|
||||
build: (v) => ({ currency: v }),
|
||||
},
|
||||
// ── warehouse.schema.ts (suppliers) vs sklad_suppliers ──
|
||||
{
|
||||
name: "CreateSupplierSchema ico",
|
||||
schema: CreateSupplierSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ name: "X", ico: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateSupplierSchema dic",
|
||||
schema: CreateSupplierSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ name: "X", dic: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateSupplierSchema ico",
|
||||
schema: UpdateSupplierSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ ico: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateSupplierSchema dic",
|
||||
schema: UpdateSupplierSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ dic: v }),
|
||||
},
|
||||
// ── customers.schema.ts vs customers ──
|
||||
{
|
||||
name: "CreateCustomerSchema company_id",
|
||||
schema: CreateCustomerSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ name: "X", company_id: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateCustomerSchema vat_id",
|
||||
schema: CreateCustomerSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ name: "X", vat_id: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateCustomerSchema postal_code",
|
||||
schema: CreateCustomerSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ name: "X", postal_code: v }),
|
||||
},
|
||||
{
|
||||
name: "CreateCustomerSchema country",
|
||||
schema: CreateCustomerSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ name: "X", country: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateCustomerSchema company_id",
|
||||
schema: UpdateCustomerSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ company_id: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateCustomerSchema vat_id",
|
||||
schema: UpdateCustomerSchema,
|
||||
width: 50,
|
||||
build: (v) => ({ vat_id: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateCustomerSchema postal_code",
|
||||
schema: UpdateCustomerSchema,
|
||||
width: 20,
|
||||
build: (v) => ({ postal_code: v }),
|
||||
},
|
||||
{
|
||||
name: "UpdateCustomerSchema country",
|
||||
schema: UpdateCustomerSchema,
|
||||
width: 100,
|
||||
build: (v) => ({ country: v }),
|
||||
},
|
||||
];
|
||||
|
||||
describe("Zod caps fit DB column widths (audit H2/M2/M4/M11/L1/L8d/L8e + adjacent)", () => {
|
||||
for (const c of CASES) {
|
||||
it(`${c.name} rejects ${c.width + 1} chars`, () => {
|
||||
const result = c.schema.safeParse(c.build("x".repeat(c.width + 1)));
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it(`${c.name} accepts ${c.width} chars`, () => {
|
||||
const result = c.schema.safeParse(c.build("x".repeat(c.width)));
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -85,11 +85,13 @@ describe("Zod form coercion + NaN rejection", () => {
|
||||
|
||||
describe("CreateTripSchema", () => {
|
||||
it("coerces numeric STRING vehicle_id / start_km / end_km to numbers", () => {
|
||||
// km fields are Int columns — integer strings coerce, decimals are
|
||||
// rejected (see trips-vehicles-km-int.test.ts for the rejection pins).
|
||||
const result = CreateTripSchema.safeParse({
|
||||
vehicle_id: "5",
|
||||
trip_date: "2026-01-15",
|
||||
start_km: "100",
|
||||
end_km: "150.5",
|
||||
end_km: "150",
|
||||
route_from: "Praha",
|
||||
route_to: "Brno",
|
||||
});
|
||||
@@ -97,7 +99,7 @@ describe("Zod form coercion + NaN rejection", () => {
|
||||
if (result.success) {
|
||||
expect(result.data.vehicle_id).toBe(5);
|
||||
expect(result.data.start_km).toBe(100);
|
||||
expect(result.data.end_km).toBe(150.5);
|
||||
expect(result.data.end_km).toBe(150);
|
||||
expect(typeof result.data.start_km).toBe("number");
|
||||
}
|
||||
});
|
||||
|
||||
138
src/__tests__/session-terminate-refresh.test.ts
Normal file
138
src/__tests__/session-terminate-refresh.test.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import prisma from "../config/database";
|
||||
import { refreshAccessToken, hashToken } from "../services/auth";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding H1: a session terminated via the sessions
|
||||
* routes (replaced_at set, NO replaced_by_hash) presented on a later refresh
|
||||
* is NOT token theft — it must be rejected with a plain 401 WITHOUT revoking
|
||||
* the user's other sessions. Real theft (replay of a ROTATED token, i.e.
|
||||
* replaced_by_hash set) must keep revoking the whole family.
|
||||
*/
|
||||
|
||||
const N = "sess_term_";
|
||||
const stamp = Date.now().toString(36);
|
||||
|
||||
const fakeReq = {
|
||||
log: { warn: () => {} },
|
||||
ip: "127.0.0.1",
|
||||
headers: {},
|
||||
} as unknown as FastifyRequest;
|
||||
|
||||
let userId: number;
|
||||
|
||||
const rawA = `${N}rawA_${stamp}`;
|
||||
const rawB = `${N}rawB_${stamp}`;
|
||||
const rawC = `${N}rawC_${stamp}`;
|
||||
const rawD = `${N}rawD_${stamp}`;
|
||||
|
||||
let tokenAId: number;
|
||||
let tokenDId: number;
|
||||
|
||||
async function cleanup() {
|
||||
const users = await prisma.users.findMany({
|
||||
where: { username: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const ids = users.map((u) => u.id);
|
||||
if (ids.length > 0) {
|
||||
await prisma.refresh_tokens.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.users.deleteMany({ where: { id: { in: ids } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const role = await prisma.roles.findFirst();
|
||||
if (!role) throw new Error("Test setup: no roles found — seed the database");
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user_${stamp}`,
|
||||
email: `${N}${stamp}@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
first_name: "Session",
|
||||
last_name: "Terminate",
|
||||
is_active: true,
|
||||
role_id: role.id,
|
||||
},
|
||||
});
|
||||
userId = user.id;
|
||||
|
||||
const future = new Date(Date.now() + 7 * 24 * 3600 * 1000);
|
||||
const tokenA = await prisma.refresh_tokens.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
token_hash: hashToken(rawA),
|
||||
expires_at: future,
|
||||
remember_me: false,
|
||||
},
|
||||
});
|
||||
tokenAId = tokenA.id;
|
||||
// Token B: terminated the way DELETE /sessions/:id does it — replaced_at
|
||||
// ONLY, no replaced_by_hash, row kept.
|
||||
await prisma.refresh_tokens.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
token_hash: hashToken(rawB),
|
||||
expires_at: future,
|
||||
remember_me: false,
|
||||
replaced_at: new Date(),
|
||||
},
|
||||
});
|
||||
// Token C: legitimately ROTATED (both replaced_at and replaced_by_hash set)
|
||||
// — replaying it is the theft signature.
|
||||
await prisma.refresh_tokens.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
token_hash: hashToken(rawC),
|
||||
expires_at: future,
|
||||
remember_me: false,
|
||||
replaced_at: new Date(),
|
||||
replaced_by_hash: hashToken(`${N}descendant_${stamp}`),
|
||||
},
|
||||
});
|
||||
const tokenD = await prisma.refresh_tokens.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
token_hash: hashToken(rawD),
|
||||
expires_at: future,
|
||||
remember_me: false,
|
||||
},
|
||||
});
|
||||
tokenDId = tokenD.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("refreshAccessToken vs terminated sessions (audit H1)", () => {
|
||||
it("rejects a manually terminated token with 401 WITHOUT revoking other sessions", async () => {
|
||||
const result = await refreshAccessToken(rawB, fakeReq);
|
||||
|
||||
expect(result.type).toBe("error");
|
||||
if (result.type === "error") expect(result.status).toBe(401);
|
||||
|
||||
// The user's OTHER session must survive — termination is not theft.
|
||||
const tokenA = await prisma.refresh_tokens.findUnique({
|
||||
where: { id: tokenAId },
|
||||
});
|
||||
expect(tokenA).not.toBeNull();
|
||||
});
|
||||
|
||||
it("still revokes the whole family on replay of a ROTATED token (theft)", async () => {
|
||||
const result = await refreshAccessToken(rawC, fakeReq);
|
||||
|
||||
expect(result.type).toBe("error");
|
||||
|
||||
// Breach containment must keep working: every session of the user is
|
||||
// gone, including the otherwise-valid token D.
|
||||
const tokenD = await prisma.refresh_tokens.findUnique({
|
||||
where: { id: tokenDId },
|
||||
});
|
||||
expect(tokenD).toBeNull();
|
||||
});
|
||||
});
|
||||
63
src/__tests__/trips-vehicles-km-int.test.ts
Normal file
63
src/__tests__/trips-vehicles-km-int.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { CreateTripSchema, UpdateTripSchema } from "../schemas/trips.schema";
|
||||
import {
|
||||
CreateVehicleSchema,
|
||||
UpdateVehicleSchema,
|
||||
} from "../schemas/vehicles.schema";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding L7: odometer fields are Int columns —
|
||||
* a decimal reading must 400 at Zod instead of 500ing at Prisma (or
|
||||
* silently truncating, corrupting the derived distance and
|
||||
* vehicles.actual_km).
|
||||
*/
|
||||
|
||||
const tripBase = {
|
||||
vehicle_id: 1,
|
||||
trip_date: "2098-01-15",
|
||||
start_km: 100,
|
||||
end_km: 200,
|
||||
route_from: "A",
|
||||
route_to: "B",
|
||||
};
|
||||
|
||||
describe("km fields are integers (audit L7)", () => {
|
||||
it.each([["start_km"], ["end_km"]])(
|
||||
"CreateTripSchema rejects a decimal %s",
|
||||
(field) => {
|
||||
expect(
|
||||
CreateTripSchema.safeParse({ ...tripBase, [field]: 100.5 }).success,
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("CreateTripSchema still accepts integer readings", () => {
|
||||
expect(CreateTripSchema.safeParse(tripBase).success).toBe(true);
|
||||
});
|
||||
|
||||
it("UpdateTripSchema rejects a decimal start_km", () => {
|
||||
expect(UpdateTripSchema.safeParse({ start_km: 100.5 }).success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([["initial_km"], ["actual_km"]])(
|
||||
"CreateVehicleSchema rejects a decimal %s",
|
||||
(field) => {
|
||||
expect(
|
||||
CreateVehicleSchema.safeParse({
|
||||
spz: "1AB 1234",
|
||||
name: "Test",
|
||||
[field]: 12345.5,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("UpdateVehicleSchema rejects a decimal actual_km, accepts an integer", () => {
|
||||
expect(UpdateVehicleSchema.safeParse({ actual_km: 12345.5 }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(UpdateVehicleSchema.safeParse({ actual_km: 12345 }).success).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
165
src/__tests__/users-create-role-guard.test.ts
Normal file
165
src/__tests__/users-create-role-guard.test.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import usersRoutes from "../routes/admin/users";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M10: POST /users must strip role_id for
|
||||
* non-admin callers (mirroring the PUT privilege-escalation guard) — a bare
|
||||
* users.create holder must not be able to mint an account on a privileged
|
||||
* role the caller itself lacks.
|
||||
*/
|
||||
|
||||
const N = "usr_roleguard_";
|
||||
const stamp = Date.now().toString(36);
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let creatorToken: string;
|
||||
let creatorRoleId: number;
|
||||
let privilegedRoleId: number;
|
||||
|
||||
function token(user: { id: number; username: string; roleName: string }) {
|
||||
return jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: user.roleName },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.users.deleteMany({ where: { username: { startsWith: N } } });
|
||||
const roles = await prisma.roles.findMany({
|
||||
where: { name: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const roleIds = roles.map((r) => r.id);
|
||||
if (roleIds.length > 0) {
|
||||
await prisma.role_permissions.deleteMany({
|
||||
where: { role_id: { in: roleIds } },
|
||||
});
|
||||
await prisma.roles.deleteMany({ where: { id: { in: roleIds } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(cookie);
|
||||
await app.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
app.addHook("onRequest", securityHeaders);
|
||||
await app.register(usersRoutes, { prefix: "/api/admin/users" });
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
include: { roles: true },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = token({
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
roleName: "admin",
|
||||
});
|
||||
|
||||
// Caller role: ONLY users.create.
|
||||
const creatorRole = await prisma.roles.create({
|
||||
data: { name: `${N}creator_${stamp}`, display_name: "Creator Only" },
|
||||
});
|
||||
creatorRoleId = creatorRole.id;
|
||||
const perm = await prisma.permissions.findFirst({
|
||||
where: { name: "users.create" },
|
||||
});
|
||||
if (!perm) throw new Error("Test setup: users.create permission missing");
|
||||
await prisma.role_permissions.create({
|
||||
data: { role_id: creatorRoleId, permission_id: perm.id },
|
||||
});
|
||||
const creator = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}creator_${stamp}`,
|
||||
email: `${N}creator_${stamp}@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
first_name: "Creator",
|
||||
last_name: "Only",
|
||||
is_active: true,
|
||||
role_id: creatorRoleId,
|
||||
},
|
||||
});
|
||||
creatorToken = token({
|
||||
id: creator.id,
|
||||
username: creator.username,
|
||||
roleName: creatorRole.name,
|
||||
});
|
||||
|
||||
// Target role the caller does NOT hold — its content is irrelevant, the
|
||||
// guard must strip ANY role assignment from a non-admin create.
|
||||
const privilegedRole = await prisma.roles.create({
|
||||
data: { name: `${N}privileged_${stamp}`, display_name: "Privileged" },
|
||||
});
|
||||
privilegedRoleId = privilegedRole.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("POST /users role escalation guard (audit M10)", () => {
|
||||
it("strips role_id when the caller is not admin", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/users",
|
||||
headers: {
|
||||
Authorization: `Bearer ${creatorToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
username: `${N}victim_${stamp}`,
|
||||
email: `${N}victim_${stamp}@test.local`,
|
||||
password: "Heslo12345",
|
||||
first_name: "Victim",
|
||||
last_name: "User",
|
||||
role_id: privilegedRoleId,
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
|
||||
const created = await prisma.users.findFirst({
|
||||
where: { username: `${N}victim_${stamp}` },
|
||||
});
|
||||
expect(created).not.toBeNull();
|
||||
expect(created?.role_id).not.toBe(privilegedRoleId);
|
||||
});
|
||||
|
||||
it("keeps role assignment for an admin caller", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/users",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
username: `${N}byadmin_${stamp}`,
|
||||
email: `${N}byadmin_${stamp}@test.local`,
|
||||
password: "Heslo12345",
|
||||
first_name: "ByAdmin",
|
||||
last_name: "User",
|
||||
role_id: privilegedRoleId,
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
|
||||
const created = await prisma.users.findFirst({
|
||||
where: { username: `${N}byadmin_${stamp}` },
|
||||
});
|
||||
expect(created?.role_id).toBe(privilegedRoleId);
|
||||
});
|
||||
});
|
||||
92
src/__tests__/warehouse-date-filter.test.ts
Normal file
92
src/__tests__/warehouse-date-filter.test.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import warehouseRoutes from "../routes/admin/warehouse";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M7: date_from/date_to filters on warehouse
|
||||
* lists must cover the FULL local calendar days. created_at holds local-time
|
||||
* instants; the old bounds (gte/lte `new Date("YYYY-MM-DD")` = UTC midnight)
|
||||
* excluded the whole inclusive end day and the first 1-2 morning hours of
|
||||
* the start day.
|
||||
*/
|
||||
|
||||
const N = "wh_datefilter_";
|
||||
const DAY = "2098-04-08";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let earlyId: number; // 00:30 local on DAY — start-day morning window
|
||||
let middayId: number; // 09:00 local on DAY
|
||||
let lateId: number; // 23:30 local on DAY — end-day coverage
|
||||
let nextDayId: number; // 00:30 local the day AFTER — must stay excluded
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.sklad_receipts.deleteMany({ where: { notes: { contains: N } } });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(cookie);
|
||||
await app.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
app.addHook("onRequest", securityHeaders);
|
||||
await app.register(warehouseRoutes, { prefix: "/api/admin/warehouse" });
|
||||
|
||||
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" },
|
||||
);
|
||||
|
||||
// Local-time instants on the filtered day (year 2098 keeps real data out).
|
||||
const early = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}early`, created_at: new Date(2098, 3, 8, 0, 30, 0) },
|
||||
});
|
||||
earlyId = early.id;
|
||||
const midday = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}midday`, created_at: new Date(2098, 3, 8, 9, 0, 0) },
|
||||
});
|
||||
middayId = midday.id;
|
||||
const late = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}late`, created_at: new Date(2098, 3, 8, 23, 30, 0) },
|
||||
});
|
||||
lateId = late.id;
|
||||
const nextDay = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}nextday`, created_at: new Date(2098, 3, 9, 0, 30, 0) },
|
||||
});
|
||||
nextDayId = nextDay.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("warehouse receipts date filter (audit M7)", () => {
|
||||
it("a single-day range returns every receipt of that local day and nothing else", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/warehouse/receipts?date_from=${DAY}&date_to=${DAY}&limit=100`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const ids = (res.json().data as Array<{ id: number }>).map((r) => r.id);
|
||||
|
||||
expect(ids).toContain(earlyId); // 00:30 — dropped by the old UTC from-bound
|
||||
expect(ids).toContain(middayId); // 09:00 — dropped by the old lte to-bound
|
||||
expect(ids).toContain(lateId); // 23:30 — dropped by the old lte to-bound
|
||||
expect(ids).not.toContain(nextDayId); // next day stays out
|
||||
});
|
||||
});
|
||||
206
src/__tests__/warehouse-fk-400.test.ts
Normal file
206
src/__tests__/warehouse-fk-400.test.ts
Normal file
@@ -0,0 +1,206 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import warehouseRoutes from "../routes/admin/warehouse";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M8: warehouse receipts/issues create+update
|
||||
* must pre-validate FK existence (supplier, item, location, project, explicit
|
||||
* batch) and return Czech 400s — a dangling id otherwise raises P2003 at
|
||||
* Prisma and surfaces as a generic 500. The document modules and trips.ts
|
||||
* pre-validate this way; warehouse omitted the guard.
|
||||
*/
|
||||
|
||||
const N = "wh_fk400_";
|
||||
const MISSING_ID = 99999999;
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let projectId: number;
|
||||
let itemId: number;
|
||||
let draftReceiptId: number;
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.sklad_issue_lines.deleteMany({
|
||||
where: { issue: { notes: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_issues.deleteMany({ where: { notes: { contains: N } } });
|
||||
await prisma.sklad_batches.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipt_lines.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipts.deleteMany({ where: { notes: { contains: N } } });
|
||||
await prisma.sklad_items.deleteMany({ where: { name: { contains: N } } });
|
||||
await prisma.projects.deleteMany({ where: { name: { startsWith: N } } });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(cookie);
|
||||
await app.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
app.addHook("onRequest", securityHeaders);
|
||||
await app.register(warehouseRoutes, { prefix: "/api/admin/warehouse" });
|
||||
|
||||
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" },
|
||||
);
|
||||
|
||||
const project = await prisma.projects.create({
|
||||
data: { name: `${N}project`, status: "active" },
|
||||
});
|
||||
projectId = project.id;
|
||||
|
||||
const item = await prisma.sklad_items.create({
|
||||
data: { name: `${N}item`, unit: "ks" },
|
||||
});
|
||||
itemId = item.id;
|
||||
|
||||
// In-stock batch so issue tests get past availability checks.
|
||||
const receipt = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}stock`, status: "CONFIRMED" },
|
||||
});
|
||||
const line = await prisma.sklad_receipt_lines.create({
|
||||
data: {
|
||||
receipt_id: receipt.id,
|
||||
item_id: itemId,
|
||||
quantity: 10,
|
||||
unit_price: 5,
|
||||
},
|
||||
});
|
||||
await prisma.sklad_batches.create({
|
||||
data: {
|
||||
item_id: itemId,
|
||||
receipt_line_id: line.id,
|
||||
quantity: 10,
|
||||
original_qty: 10,
|
||||
unit_price: 5,
|
||||
received_at: new Date(2026, 0, 1, 12, 0, 0),
|
||||
is_consumed: false,
|
||||
},
|
||||
});
|
||||
|
||||
// DRAFT receipt for the PUT test.
|
||||
const draft = await prisma.sklad_receipts.create({
|
||||
data: {
|
||||
notes: `${N}draft`,
|
||||
status: "DRAFT",
|
||||
items: { create: [{ item_id: itemId, quantity: 1, unit_price: 5 }] },
|
||||
},
|
||||
});
|
||||
draftReceiptId = draft.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
function post(url: string, payload: unknown) {
|
||||
return app.inject({
|
||||
method: "POST",
|
||||
url,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: payload as Record<string, unknown>,
|
||||
});
|
||||
}
|
||||
|
||||
describe("warehouse FK pre-validation (audit M8)", () => {
|
||||
it("POST /receipts with a nonexistent item_id returns 400, not 500", async () => {
|
||||
const res = await post("/api/admin/warehouse/receipts", {
|
||||
notes: `${N}r1`,
|
||||
items: [{ item_id: MISSING_ID, quantity: 1, unit_price: 10 }],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain("nenalezen");
|
||||
});
|
||||
|
||||
it("POST /receipts with a nonexistent supplier_id returns 400, not 500", async () => {
|
||||
const res = await post("/api/admin/warehouse/receipts", {
|
||||
notes: `${N}r2`,
|
||||
supplier_id: MISSING_ID,
|
||||
items: [{ item_id: itemId, quantity: 1, unit_price: 10 }],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain("nenalezen");
|
||||
});
|
||||
|
||||
it("POST /receipts with a nonexistent location_id returns 400, not 500", async () => {
|
||||
const res = await post("/api/admin/warehouse/receipts", {
|
||||
notes: `${N}r3`,
|
||||
items: [
|
||||
{
|
||||
item_id: itemId,
|
||||
quantity: 1,
|
||||
unit_price: 10,
|
||||
location_id: MISSING_ID,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain("nenalezen");
|
||||
});
|
||||
|
||||
it("PUT /receipts/:id with a nonexistent item_id returns 400, not 500", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/warehouse/receipts/${draftReceiptId}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
notes: `${N}draft`,
|
||||
items: [{ item_id: MISSING_ID, quantity: 1, unit_price: 10 }],
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain("nenalezen");
|
||||
});
|
||||
|
||||
it("POST /issues with a nonexistent project_id returns 400, not 500", async () => {
|
||||
const res = await post("/api/admin/warehouse/issues", {
|
||||
notes: `${N}i1`,
|
||||
project_id: MISSING_ID,
|
||||
items: [{ item_id: itemId, quantity: 1 }],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain("nenalezen");
|
||||
});
|
||||
|
||||
it("POST /issues with a nonexistent explicit batch_id returns 400, not 500", async () => {
|
||||
const res = await post("/api/admin/warehouse/issues", {
|
||||
notes: `${N}i2`,
|
||||
project_id: projectId,
|
||||
items: [{ item_id: itemId, quantity: 1, batch_id: MISSING_ID }],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain("nenalezen");
|
||||
});
|
||||
|
||||
it("valid receipt create still succeeds", async () => {
|
||||
const res = await post("/api/admin/warehouse/receipts", {
|
||||
notes: `${N}ok`,
|
||||
items: [{ item_id: itemId, quantity: 2, unit_price: 10 }],
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
});
|
||||
});
|
||||
124
src/__tests__/warehouse-inventory-confirm.test.ts
Normal file
124
src/__tests__/warehouse-inventory-confirm.test.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { confirmInventorySession } from "../services/warehouse.service";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding C3: confirmInventorySession must be atomic.
|
||||
* A session whose item list contains a valid surplus line BEFORE a deficit
|
||||
* line that cannot be satisfied (no batches) must fail WITHOUT committing the
|
||||
* surplus item's corrective receipt/batch — and retries must not accumulate
|
||||
* phantom stock.
|
||||
*/
|
||||
|
||||
const N = "wh_invconf_";
|
||||
|
||||
let itemAId: number; // surplus line (processed first — lower line id)
|
||||
let itemBId: number; // deficit line with no batches -> selectFifoBatches throws
|
||||
let sessionId: number;
|
||||
|
||||
/** Corrective receipts carry generated notes without our prefix — collect
|
||||
* them via their lines' items before deleting. */
|
||||
async function cleanup() {
|
||||
const lines = await prisma.sklad_receipt_lines.findMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
select: { receipt_id: true },
|
||||
});
|
||||
const receiptIds = [...new Set(lines.map((l) => l.receipt_id))];
|
||||
await prisma.sklad_batches.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipt_lines.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
if (receiptIds.length > 0) {
|
||||
await prisma.sklad_receipts.deleteMany({
|
||||
where: { id: { in: receiptIds } },
|
||||
});
|
||||
}
|
||||
await prisma.sklad_inventory_lines.deleteMany({
|
||||
where: { session: { notes: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_inventory_sessions.deleteMany({
|
||||
where: { notes: { contains: N } },
|
||||
});
|
||||
await prisma.sklad_items.deleteMany({ where: { name: { contains: N } } });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
const itemA = await prisma.sklad_items.create({
|
||||
data: { name: `${N}surplus_item`, unit: "ks" },
|
||||
});
|
||||
itemAId = itemA.id;
|
||||
const itemB = await prisma.sklad_items.create({
|
||||
data: { name: `${N}deficit_item`, unit: "ks" },
|
||||
});
|
||||
itemBId = itemB.id;
|
||||
|
||||
// Surplus line created first => lower id => processed first by the confirm
|
||||
// loop. Deficit line for an item with NO batches forces the FIFO throw.
|
||||
const session = await prisma.sklad_inventory_sessions.create({
|
||||
data: {
|
||||
notes: `${N}session`,
|
||||
items: {
|
||||
create: [
|
||||
{ item_id: itemAId, system_qty: 0, actual_qty: 5, difference: 5 },
|
||||
{ item_id: itemBId, system_qty: 3, actual_qty: 0, difference: -3 },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
sessionId = session.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("confirmInventorySession atomicity (audit C3)", () => {
|
||||
it("rolls back the surplus corrective receipt when a later deficit line fails", async () => {
|
||||
const result = await confirmInventorySession(sessionId);
|
||||
|
||||
// The confirm must fail — item B has nothing to consume.
|
||||
expect("error" in result).toBe(true);
|
||||
if ("error" in result) {
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain(`ID ${itemBId}`);
|
||||
}
|
||||
|
||||
// ...and item A's surplus writes must NOT have been committed.
|
||||
const receiptLines = await prisma.sklad_receipt_lines.findMany({
|
||||
where: { item_id: itemAId },
|
||||
});
|
||||
expect(receiptLines).toHaveLength(0);
|
||||
|
||||
const batches = await prisma.sklad_batches.findMany({
|
||||
where: { item_id: itemAId },
|
||||
});
|
||||
expect(batches).toHaveLength(0);
|
||||
|
||||
// The session itself stays DRAFT and unnumbered either way.
|
||||
const session = await prisma.sklad_inventory_sessions.findUnique({
|
||||
where: { id: sessionId },
|
||||
});
|
||||
expect(session?.status).toBe("DRAFT");
|
||||
expect(session?.session_number).toBeNull();
|
||||
});
|
||||
|
||||
it("does not accumulate phantom stock when the failed confirm is retried", async () => {
|
||||
await confirmInventorySession(sessionId);
|
||||
await confirmInventorySession(sessionId);
|
||||
|
||||
const batches = await prisma.sklad_batches.findMany({
|
||||
where: { item_id: itemAId },
|
||||
});
|
||||
expect(batches).toHaveLength(0);
|
||||
|
||||
const receipts = await prisma.sklad_receipts.findMany({
|
||||
where: { notes: { contains: `inventarizace #${sessionId}` } },
|
||||
});
|
||||
expect(receipts).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
196
src/__tests__/warehouse-issue-confirm.test.ts
Normal file
196
src/__tests__/warehouse-issue-confirm.test.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { confirmIssue } from "../services/warehouse.service";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding C2: confirmIssue must validate duplicate
|
||||
* lines pointing at the SAME batch against their combined quantity. Two lines
|
||||
* that each pass the per-line check individually must not decrement the batch
|
||||
* cumulatively below zero (silent over-issue hidden from stock totals).
|
||||
*
|
||||
* The duplicate-lines draft is exactly what POST /issues produces when two
|
||||
* same-item lines without batch_id FIFO-resolve to the same oldest batch
|
||||
* (per-line resolution persists nothing between lines), and is equally
|
||||
* reachable with explicit batch_ids.
|
||||
*/
|
||||
|
||||
const N = "wh_issueconf_";
|
||||
|
||||
let projectId: number;
|
||||
let userId: number;
|
||||
let itemId: number;
|
||||
let batch1Id: number;
|
||||
let overIssueId: number;
|
||||
let exactIssueId: number;
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.sklad_issue_lines.deleteMany({
|
||||
where: { issue: { notes: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_issues.deleteMany({ where: { notes: { contains: N } } });
|
||||
await prisma.sklad_batches.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipt_lines.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipts.deleteMany({ where: { notes: { contains: N } } });
|
||||
await prisma.sklad_items.deleteMany({ where: { name: { contains: N } } });
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
await prisma.projects
|
||||
.deleteMany({ where: { name: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
const adminRole = await prisma.roles.findFirst({ where: { name: "admin" } });
|
||||
if (!adminRole)
|
||||
throw new Error("Admin role not found — seed the database first");
|
||||
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash:
|
||||
"$2a$12$LJ3m4ys3Lg4oLBFnYP2amuPBzJnJBbGzCl5Y6X9Y8r0q5.s3L6OyO",
|
||||
first_name: "Issue",
|
||||
last_name: "Confirm",
|
||||
is_active: true,
|
||||
role_id: adminRole.id,
|
||||
},
|
||||
});
|
||||
userId = user.id;
|
||||
|
||||
const project = await prisma.projects.create({
|
||||
data: { name: `${N}project`, status: "active" },
|
||||
});
|
||||
projectId = project.id;
|
||||
|
||||
const item = await prisma.sklad_items.create({
|
||||
data: { name: `${N}item`, unit: "ks" },
|
||||
});
|
||||
itemId = item.id;
|
||||
|
||||
// Two batches of 8 — total stock 16, so the per-item aggregate check
|
||||
// passes a combined quantity of 10, but FIFO resolves both lines to the
|
||||
// OLDER batch B1 which only holds 8.
|
||||
const receipt = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}receipt`, status: "CONFIRMED" },
|
||||
});
|
||||
const line1 = await prisma.sklad_receipt_lines.create({
|
||||
data: {
|
||||
receipt_id: receipt.id,
|
||||
item_id: itemId,
|
||||
quantity: 8,
|
||||
unit_price: 10,
|
||||
},
|
||||
});
|
||||
const line2 = await prisma.sklad_receipt_lines.create({
|
||||
data: {
|
||||
receipt_id: receipt.id,
|
||||
item_id: itemId,
|
||||
quantity: 8,
|
||||
unit_price: 10,
|
||||
},
|
||||
});
|
||||
const batch1 = await prisma.sklad_batches.create({
|
||||
data: {
|
||||
item_id: itemId,
|
||||
receipt_line_id: line1.id,
|
||||
quantity: 8,
|
||||
original_qty: 8,
|
||||
unit_price: 10,
|
||||
received_at: new Date(2026, 0, 1, 12, 0, 0),
|
||||
is_consumed: false,
|
||||
},
|
||||
});
|
||||
batch1Id = batch1.id;
|
||||
await prisma.sklad_batches.create({
|
||||
data: {
|
||||
item_id: itemId,
|
||||
receipt_line_id: line2.id,
|
||||
quantity: 8,
|
||||
original_qty: 8,
|
||||
unit_price: 10,
|
||||
received_at: new Date(2026, 0, 2, 12, 0, 0),
|
||||
is_consumed: false,
|
||||
},
|
||||
});
|
||||
|
||||
// Draft mirroring the FIFO resolution: two lines, both on B1, 5 + 5 = 10 > 8.
|
||||
const overIssue = await prisma.sklad_issues.create({
|
||||
data: {
|
||||
project_id: projectId,
|
||||
notes: `${N}over_issue`,
|
||||
items: {
|
||||
create: [
|
||||
{ item_id: itemId, batch_id: batch1Id, quantity: 5 },
|
||||
{ item_id: itemId, batch_id: batch1Id, quantity: 5 },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
overIssueId = overIssue.id;
|
||||
|
||||
// Control draft: duplicate lines whose combined quantity EXACTLY fits B1.
|
||||
const exactIssue = await prisma.sklad_issues.create({
|
||||
data: {
|
||||
project_id: projectId,
|
||||
notes: `${N}exact_issue`,
|
||||
items: {
|
||||
create: [
|
||||
{ item_id: itemId, batch_id: batch1Id, quantity: 3 },
|
||||
{ item_id: itemId, batch_id: batch1Id, quantity: 5 },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
exactIssueId = exactIssue.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("confirmIssue cross-line batch totals (audit C2)", () => {
|
||||
it("rejects duplicate same-batch lines whose combined quantity exceeds the batch", async () => {
|
||||
const result = await confirmIssue(overIssueId, userId);
|
||||
|
||||
expect("error" in result).toBe(true);
|
||||
if ("error" in result) expect(result.status).toBe(400);
|
||||
|
||||
// The batch must be untouched — not driven negative and hidden.
|
||||
const b1 = await prisma.sklad_batches.findUnique({
|
||||
where: { id: batch1Id },
|
||||
});
|
||||
expect(Number(b1?.quantity)).toBe(8);
|
||||
expect(b1?.is_consumed).toBe(false);
|
||||
|
||||
const negatives = await prisma.sklad_batches.findMany({
|
||||
where: { item_id: itemId, quantity: { lt: 0 } },
|
||||
});
|
||||
expect(negatives).toHaveLength(0);
|
||||
|
||||
const issue = await prisma.sklad_issues.findUnique({
|
||||
where: { id: overIssueId },
|
||||
});
|
||||
expect(issue?.status).toBe("DRAFT");
|
||||
});
|
||||
|
||||
it("still confirms duplicate same-batch lines whose combined quantity fits", async () => {
|
||||
const result = await confirmIssue(exactIssueId, userId);
|
||||
|
||||
expect("error" in result).toBe(false);
|
||||
|
||||
const b1 = await prisma.sklad_batches.findUnique({
|
||||
where: { id: batch1Id },
|
||||
});
|
||||
expect(Number(b1?.quantity)).toBe(0);
|
||||
expect(b1?.is_consumed).toBe(true);
|
||||
});
|
||||
});
|
||||
97
src/__tests__/warehouse-items-sort.test.ts
Normal file
97
src/__tests__/warehouse-items-sort.test.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import warehouseRoutes from "../routes/admin/warehouse";
|
||||
|
||||
/**
|
||||
* Pinning tests for the verified-adjacent audit finding: GET /items ignores
|
||||
* the client `sort` param (the WarehouseItems page sends one — default
|
||||
* item_number) and hardcodes `orderBy: { name: "asc" }` with no `{ id }`
|
||||
* tiebreak.
|
||||
*/
|
||||
|
||||
const N = "wh_itemsort_";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
// Names sort A→B, item numbers sort the OPPOSITE way, so honoring the sort
|
||||
// param produces a different first row than the hardcoded name ordering.
|
||||
let itemAId: number; // name "...a_name", item_number "...Z2"
|
||||
let itemBId: number; // name "...b_name", item_number "...A1"
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.sklad_items.deleteMany({ where: { name: { contains: N } } });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(cookie);
|
||||
await app.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
app.addHook("onRequest", securityHeaders);
|
||||
await app.register(warehouseRoutes, { prefix: "/api/admin/warehouse" });
|
||||
|
||||
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" },
|
||||
);
|
||||
|
||||
const itemA = await prisma.sklad_items.create({
|
||||
data: { name: `${N}a_name`, item_number: `${N}Z2`, unit: "ks" },
|
||||
});
|
||||
itemAId = itemA.id;
|
||||
const itemB = await prisma.sklad_items.create({
|
||||
data: { name: `${N}b_name`, item_number: `${N}A1`, unit: "ks" },
|
||||
});
|
||||
itemBId = itemB.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("GET /warehouse/items sort param", () => {
|
||||
it("honors sort=item_number (asc puts the A1 item first)", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/warehouse/items?search=${N}&sort=item_number&order=asc`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const ids = (res.json().data as Array<{ id: number }>).map((r) => r.id);
|
||||
expect(ids).toEqual([itemBId, itemAId]);
|
||||
});
|
||||
|
||||
it("defaults to name ordering when no sort is given", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/warehouse/items?search=${N}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const ids = (res.json().data as Array<{ id: number }>).map((r) => r.id);
|
||||
expect(ids).toEqual([itemAId, itemBId]);
|
||||
});
|
||||
|
||||
it("ignores a non-allow-listed sort field (no 500)", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/warehouse/items?search=${N}&sort=total_quantity`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -148,7 +148,7 @@ const TrashIcon = (
|
||||
);
|
||||
|
||||
export default function PlanCellModal(props: Props) {
|
||||
const { open, mode, onClose } = props;
|
||||
const { open, mode } = props;
|
||||
if (!open || mode.kind === "closed") return null;
|
||||
if (mode.kind === "view") return <ViewModal {...props} />;
|
||||
if (mode.kind === "day-in-range")
|
||||
@@ -488,6 +488,7 @@ function DayInRangeModal(
|
||||
onClose={onClose}
|
||||
onSubmit={onClose}
|
||||
submitText="Zavřít — ponechat rozsah beze změny"
|
||||
hideCancel
|
||||
maxWidth="md"
|
||||
>
|
||||
<Typography variant="body2" sx={{ mb: 2 }}>
|
||||
|
||||
@@ -491,9 +491,11 @@ export default function PlanGrid({
|
||||
}, [projects]);
|
||||
// Memoize the day list so it isn't rebuilt on every render (only when the
|
||||
// visible range changes). Stable identity also keeps the row map cheap.
|
||||
const dateFrom = data?.date_from;
|
||||
const dateTo = data?.date_to;
|
||||
const days = useMemo(
|
||||
() => (data ? eachDay(data.date_from, data.date_to) : []),
|
||||
[data?.date_from, data?.date_to],
|
||||
() => (dateFrom && dateTo ? eachDay(dateFrom, dateTo) : []),
|
||||
[dateFrom, dateTo],
|
||||
);
|
||||
|
||||
if (!data) return <LoadingState />;
|
||||
|
||||
@@ -19,46 +19,22 @@ import {
|
||||
} from "../utils/attendanceHelpers";
|
||||
|
||||
// ---------- Shared types ----------
|
||||
|
||||
export interface ShiftFormData {
|
||||
user_id: string;
|
||||
shift_date: string;
|
||||
leave_type: string;
|
||||
leave_hours: number;
|
||||
arrival_date: string;
|
||||
arrival_time: string;
|
||||
break_start_date: string;
|
||||
break_start_time: string;
|
||||
break_end_date: string;
|
||||
break_end_time: string;
|
||||
departure_date: string;
|
||||
departure_time: string;
|
||||
notes: string;
|
||||
}
|
||||
|
||||
export interface ProjectLog {
|
||||
_key?: string;
|
||||
id?: number;
|
||||
project_id: string | number;
|
||||
hours: string | number;
|
||||
minutes: string | number;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: number | string;
|
||||
project_number: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: number | string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface EditingRecord {
|
||||
user_name: string;
|
||||
shift_date: string;
|
||||
}
|
||||
// Definitions live in the dependency-free ./shiftFormTypes module; re-exported
|
||||
// here so existing importers of ShiftFormModal keep working.
|
||||
export type {
|
||||
ShiftFormData,
|
||||
ProjectLog,
|
||||
Project,
|
||||
User,
|
||||
EditingRecord,
|
||||
} from "./shiftFormTypes";
|
||||
import type {
|
||||
ShiftFormData,
|
||||
ProjectLog,
|
||||
Project,
|
||||
User,
|
||||
EditingRecord,
|
||||
} from "./shiftFormTypes";
|
||||
|
||||
// ---------- Sub-component props ----------
|
||||
|
||||
|
||||
@@ -179,10 +179,12 @@ export default function DashQuickActions({
|
||||
});
|
||||
const result: ApiResult<unknown> = await response.json();
|
||||
if (result.success) {
|
||||
// A new trip changes the trip list and the dashboard vehicle widgets —
|
||||
// invalidate the broad domains (prefix-matching covers sub-queries).
|
||||
// A new trip changes the trip list, the dashboard vehicle widgets AND
|
||||
// the vehicles domain (actual_km moves) — invalidate all three broad
|
||||
// domains (prefix-matching covers sub-queries).
|
||||
queryClient.invalidateQueries({ queryKey: ["trips"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["vehicles"] });
|
||||
setShowTripModal(false);
|
||||
alert.success(result.message ?? "Jízda uložena");
|
||||
} else {
|
||||
|
||||
@@ -49,10 +49,31 @@ export interface DocumentItem {
|
||||
quantity: string | number;
|
||||
unit: string;
|
||||
unit_price: string | number;
|
||||
/** Per-item discount as a percentage (0–100). Offers only; 0 elsewhere. */
|
||||
discount: string | number;
|
||||
/** Offers only — undefined (issued orders) counts as included. */
|
||||
is_included_in_total?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discount input styling: centered, and with the native number spinners hidden
|
||||
* so a 3-digit value ("100") isn't clipped under the up/down arrows.
|
||||
*/
|
||||
const discountInputSx = {
|
||||
"& input": { textAlign: "center" },
|
||||
"& input[type=number]": { MozAppearance: "textfield" as const },
|
||||
"& input::-webkit-outer-spin-button, & input::-webkit-inner-spin-button": {
|
||||
WebkitAppearance: "none",
|
||||
margin: 0,
|
||||
},
|
||||
};
|
||||
|
||||
/** NET of one line after its per-item percentage discount. */
|
||||
const discountedLineNet = (item: DocumentItem): number =>
|
||||
(Number(item.quantity) || 0) *
|
||||
(Number(item.unit_price) || 0) *
|
||||
(1 - (Number(item.discount) || 0) / 100);
|
||||
|
||||
let documentItemKeyCounter = 0;
|
||||
|
||||
/** Unique client-side key for a (new or hydrated) document item row. */
|
||||
@@ -66,6 +87,7 @@ export const emptyDocumentItem = (): DocumentItem => ({
|
||||
quantity: 1,
|
||||
unit: "ks",
|
||||
unit_price: 0,
|
||||
discount: 0,
|
||||
is_included_in_total: true,
|
||||
});
|
||||
|
||||
@@ -73,9 +95,7 @@ export const emptyDocumentItem = (): DocumentItem => ({
|
||||
export const documentItemsTotal = (items: DocumentItem[]): number =>
|
||||
items.reduce(
|
||||
(sum, it) =>
|
||||
it.is_included_in_total === false
|
||||
? sum
|
||||
: sum + (Number(it.quantity) || 0) * (Number(it.unit_price) || 0),
|
||||
it.is_included_in_total === false ? sum : sum + discountedLineNet(it),
|
||||
0,
|
||||
);
|
||||
|
||||
@@ -111,6 +131,7 @@ function SortableItemRow({
|
||||
readOnly,
|
||||
canDelete,
|
||||
showIncludedInTotal,
|
||||
showDiscount,
|
||||
itemDescriptionMaxLength,
|
||||
onUpdate,
|
||||
onRemove,
|
||||
@@ -121,6 +142,7 @@ function SortableItemRow({
|
||||
readOnly: boolean;
|
||||
canDelete: boolean;
|
||||
showIncludedInTotal: boolean;
|
||||
showDiscount: boolean;
|
||||
itemDescriptionMaxLength: number;
|
||||
onUpdate: (field: keyof DocumentItem, value: string | boolean) => void;
|
||||
onRemove: () => void;
|
||||
@@ -143,8 +165,7 @@ function SortableItemRow({
|
||||
position: "relative" as const,
|
||||
zIndex: isDragging ? 10 : undefined,
|
||||
};
|
||||
const lineTotal =
|
||||
(Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
|
||||
const lineTotal = discountedLineNet(item);
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
@@ -253,6 +274,17 @@ function SortableItemRow({
|
||||
InputProps={{ readOnly }}
|
||||
sx={{ "& input": { textAlign: "right" } }}
|
||||
/>
|
||||
{showDiscount && (
|
||||
<TextField
|
||||
label="Sleva %"
|
||||
type="number"
|
||||
value={item.discount ?? ""}
|
||||
onChange={(e) => onUpdate("discount", e.target.value)}
|
||||
slotProps={{ htmlInput: { min: "0", max: "100", step: "any" } }}
|
||||
InputProps={{ readOnly }}
|
||||
sx={discountInputSx}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
@@ -396,6 +428,18 @@ function SortableItemRow({
|
||||
sx={{ "& input": { textAlign: "right" } }}
|
||||
/>
|
||||
</TableCell>
|
||||
{showDiscount && (
|
||||
<TableCell>
|
||||
<TextField
|
||||
type="number"
|
||||
value={item.discount ?? ""}
|
||||
onChange={(e) => onUpdate("discount", e.target.value)}
|
||||
slotProps={{ htmlInput: { min: "0", max: "100", step: "any" } }}
|
||||
InputProps={{ readOnly }}
|
||||
sx={discountInputSx}
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
{showIncludedInTotal && (
|
||||
<TableCell align="center">
|
||||
<Checkbox
|
||||
@@ -442,6 +486,8 @@ interface DocumentItemsEditorProps {
|
||||
error?: string;
|
||||
/** Render the offers-only "V ceně" (is_included_in_total) column. */
|
||||
showIncludedInTotal?: boolean;
|
||||
/** Render the per-item "Sleva %" discount column (offers only). */
|
||||
showDiscount?: boolean;
|
||||
/** Schema cap for the detailed description (offers 8000, issued orders 5000). */
|
||||
itemDescriptionMaxLength?: number;
|
||||
/** Optional page-specific control (e.g. item-template Select) next to the add button. */
|
||||
@@ -460,6 +506,7 @@ export default function DocumentItemsEditor({
|
||||
readOnly,
|
||||
error,
|
||||
showIncludedInTotal = false,
|
||||
showDiscount = false,
|
||||
itemDescriptionMaxLength = 5000,
|
||||
templatesSlot,
|
||||
}: DocumentItemsEditorProps) {
|
||||
@@ -563,6 +610,7 @@ export default function DocumentItemsEditor({
|
||||
readOnly={readOnly}
|
||||
canDelete={items.length > 1}
|
||||
showIncludedInTotal={showIncludedInTotal}
|
||||
showDiscount={showDiscount}
|
||||
itemDescriptionMaxLength={itemDescriptionMaxLength}
|
||||
onUpdate={(field, value) => updateItem(index, field, value)}
|
||||
onRemove={() => removeItem(index)}
|
||||
@@ -594,6 +642,11 @@ export default function DocumentItemsEditor({
|
||||
<TableCell sx={{ width: "8rem" }} align="center">
|
||||
Jedn. cena
|
||||
</TableCell>
|
||||
{showDiscount && (
|
||||
<TableCell sx={{ width: "7rem" }} align="center">
|
||||
Sleva %
|
||||
</TableCell>
|
||||
)}
|
||||
{showIncludedInTotal && (
|
||||
<TableCell sx={{ width: "4rem" }} align="center">
|
||||
V ceně
|
||||
@@ -615,6 +668,7 @@ export default function DocumentItemsEditor({
|
||||
readOnly={readOnly}
|
||||
canDelete={items.length > 1}
|
||||
showIncludedInTotal={showIncludedInTotal}
|
||||
showDiscount={showDiscount}
|
||||
itemDescriptionMaxLength={itemDescriptionMaxLength}
|
||||
onUpdate={(field, value) =>
|
||||
updateItem(index, field, value)
|
||||
|
||||
44
src/admin/components/shiftFormTypes.ts
Normal file
44
src/admin/components/shiftFormTypes.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// Shared attendance shift-form types, kept in a dependency-free module so they
|
||||
// can be imported without pulling in the ShiftFormModal component graph (which
|
||||
// reaches MUI/import.meta files that don't compile under the CommonJS test
|
||||
// project). ShiftFormModal re-exports these for backward compatibility.
|
||||
|
||||
export interface ShiftFormData {
|
||||
user_id: string;
|
||||
shift_date: string;
|
||||
leave_type: string;
|
||||
leave_hours: number;
|
||||
arrival_date: string;
|
||||
arrival_time: string;
|
||||
break_start_date: string;
|
||||
break_start_time: string;
|
||||
break_end_date: string;
|
||||
break_end_time: string;
|
||||
departure_date: string;
|
||||
departure_time: string;
|
||||
notes: string;
|
||||
}
|
||||
|
||||
export interface ProjectLog {
|
||||
_key?: string;
|
||||
id?: number;
|
||||
project_id: string | number;
|
||||
hours: string | number;
|
||||
minutes: string | number;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: number | string;
|
||||
project_number: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: number | string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface EditingRecord {
|
||||
user_name: string;
|
||||
shift_date: string;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { Select } from "../../ui";
|
||||
@@ -26,7 +26,7 @@ export default function ReservationPicker({
|
||||
}),
|
||||
);
|
||||
|
||||
const reservations = result?.data ?? [];
|
||||
const reservations = useMemo(() => result?.data ?? [], [result?.data]);
|
||||
|
||||
// When item/project change, the loaded reservation list changes. If the
|
||||
// currently-selected reservation is no longer available, clear it and notify
|
||||
|
||||
@@ -43,9 +43,10 @@ export function AlertProvider({ children }: { children: ReactNode }) {
|
||||
const timeoutsRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
const timeouts = timeoutsRef.current;
|
||||
return () => {
|
||||
timeoutsRef.current.forEach(clearTimeout);
|
||||
timeoutsRef.current.clear();
|
||||
timeouts.forEach(clearTimeout);
|
||||
timeouts.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -122,6 +122,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
},
|
||||
// silentRefresh and setAccessTokenFn reference each other; listing
|
||||
// silentRefresh here would recreate both callbacks on every render. The
|
||||
// scheduled silentRefresh is safe to call as a stable closure because all
|
||||
// of its state lives in refs.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[],
|
||||
);
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ import type {
|
||||
ProjectLog,
|
||||
Project,
|
||||
User,
|
||||
} from "../components/ShiftFormModal";
|
||||
} from "../components/shiftFormTypes";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@@ -234,7 +234,6 @@ function computeUserTotals(
|
||||
}
|
||||
|
||||
const holidayDates = holidaysInMonth(yr, mo + 1);
|
||||
const holidayCount = holidayDates.length;
|
||||
|
||||
for (const uid of Object.keys(totals)) {
|
||||
const t = totals[uid];
|
||||
@@ -345,14 +344,25 @@ function escapeHtml(str: string): string {
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function buildProjectLogsHtml(record: Record<string, any>): string {
|
||||
/** Shape of the print endpoint payload consumed by the HTML builders. */
|
||||
interface PrintData {
|
||||
month: string;
|
||||
month_name: string;
|
||||
selected_user_name?: string | null;
|
||||
user_totals: Record<string, UserTotal>;
|
||||
}
|
||||
|
||||
export function buildProjectLogsHtml(record: AttendanceRecord): string {
|
||||
if (record.project_logs && record.project_logs.length > 0) {
|
||||
return record.project_logs
|
||||
.map((log: any) => {
|
||||
.map((log) => {
|
||||
let h: number, m: number;
|
||||
if (log.hours !== null && log.hours !== undefined) {
|
||||
h = parseInt(log.hours) || 0;
|
||||
m = parseInt(log.minutes) || 0;
|
||||
// hours/minutes arrive as string or number — String() before parseInt
|
||||
// (parseInt already coerces to string internally, so this is a no-op
|
||||
// at runtime, it just satisfies parseInt's string parameter type).
|
||||
h = parseInt(String(log.hours)) || 0;
|
||||
m = parseInt(String(log.minutes)) || 0;
|
||||
} else if (log.started_at && log.ended_at) {
|
||||
const mins = Math.max(
|
||||
0,
|
||||
@@ -375,13 +385,13 @@ function buildProjectLogsHtml(record: Record<string, any>): string {
|
||||
return escapeHtml(record.project_name || "—");
|
||||
}
|
||||
|
||||
function buildUserSectionHtml(
|
||||
export function buildUserSectionHtml(
|
||||
userId: string,
|
||||
userData: Record<string, any>,
|
||||
printData: Record<string, any>,
|
||||
userData: UserTotal,
|
||||
printData: PrintData,
|
||||
): string {
|
||||
// Build a date-keyed lookup of the user's records.
|
||||
const recordsByDate = new Map<string, Record<string, any>>();
|
||||
const recordsByDate = new Map<string, AttendanceRecord>();
|
||||
for (const r of userData.records || []) {
|
||||
recordsByDate.set(normalizeDateStr(r.shift_date), r);
|
||||
}
|
||||
@@ -392,7 +402,7 @@ function buildUserSectionHtml(
|
||||
const mo = parseInt(monthStr, 10);
|
||||
const daysInMonth = getDaysInMonth(yr, mo);
|
||||
|
||||
const userRecords = (userData.records || []) as Record<string, any>[];
|
||||
const userRecords = userData.records ?? [];
|
||||
|
||||
const rows: string[] = [];
|
||||
for (let d = 1; d <= daysInMonth; d++) {
|
||||
@@ -476,14 +486,12 @@ function buildUserSectionHtml(
|
||||
// Sum of vacation/sick/unpaid hours (in hours, not minutes). The
|
||||
// "holiday" leave_type is auto-computed from Czech holidays further down
|
||||
// and no longer selectable in the UI, so it's deliberately omitted here.
|
||||
let vacationHours = 0,
|
||||
sickHours = 0;
|
||||
let vacationHours = 0;
|
||||
for (const r of userRecords) {
|
||||
const lt = r.leave_type || "work";
|
||||
if (lt === "work") continue;
|
||||
const h = Number(r.leave_hours) || 8;
|
||||
if (lt === "vacation") vacationHours += h;
|
||||
else if (lt === "sick") sickHours += h;
|
||||
}
|
||||
|
||||
// Odpracováno: floor(worked / 8) × 8.
|
||||
@@ -492,7 +500,6 @@ function buildUserSectionHtml(
|
||||
|
||||
// Free Svátek: 8h per holiday date the user did not work.
|
||||
const holidayDates = holidaysInMonth(yr, mo);
|
||||
const holidayCount = holidayDates.length;
|
||||
const workedDates = new Set(
|
||||
userRecords
|
||||
.filter((r) => (r.leave_type || "work") === "work")
|
||||
@@ -592,8 +599,8 @@ function buildUserSectionHtml(
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function buildPrintHtml(
|
||||
pData: Record<string, any>,
|
||||
export function buildPrintHtml(
|
||||
pData: PrintData,
|
||||
userSections: string,
|
||||
emptyMsg: string,
|
||||
filterNote: string,
|
||||
@@ -1334,7 +1341,7 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
||||
const pData = result.data;
|
||||
const userSections = Object.entries(pData.user_totals)
|
||||
.map(([uid, uData]) =>
|
||||
buildUserSectionHtml(uid, uData as Record<string, any>, pData),
|
||||
buildUserSectionHtml(uid, uData as UserTotal, pData),
|
||||
)
|
||||
.join("");
|
||||
const emptyMsg =
|
||||
|
||||
@@ -200,7 +200,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// Snapshot the currently-cached grid for a given key. Returns
|
||||
// `undefined` if there's nothing cached (we don't patch empty data).
|
||||
function snapshotGrid(key: readonly unknown[]): GridData | undefined {
|
||||
return qc.getQueryData<GridData>(key as any);
|
||||
return qc.getQueryData<GridData>(key);
|
||||
}
|
||||
|
||||
// Apply a per-date cell patch to the cached grid at `key`. Returns the
|
||||
@@ -312,7 +312,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// `ctx` may be `undefined` (e.g. if onMutate itself threw) — guarded below.
|
||||
function rollbackCells(ctx: CellRollback | undefined) {
|
||||
if (!ctx || !ctx.rolled) return;
|
||||
const prev = qc.getQueryData<GridData>(ctx.key as any);
|
||||
const prev = qc.getQueryData<GridData>(ctx.key);
|
||||
if (!prev) return;
|
||||
const userPrev = prev.cells[ctx.userId] ?? {};
|
||||
const userNext = { ...userPrev };
|
||||
@@ -379,7 +379,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// Find the user that owns this entry in the current grid by
|
||||
// looking for any cell with entryId === id (we already know
|
||||
// the id from vars; it doesn't change across the update).
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey);
|
||||
let ownerUserId: number | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
@@ -430,7 +430,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// For delete we need to know the entry's user_id and full range.
|
||||
// Look it up from the current grid: find the user that has a cell
|
||||
// with entryId === id, and read rangeFrom/rangeTo from that cell.
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey);
|
||||
if (!grid) return null;
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
let entryRange: { from: string; to: string } | null = null;
|
||||
@@ -511,7 +511,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
onMutate: (vars): CellRollback => {
|
||||
// Find the user/date for this overrideId in the current grid, then
|
||||
// patch that single cell with the new values.
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey);
|
||||
if (!grid) return null;
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
@@ -559,7 +559,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
method: "DELETE",
|
||||
}),
|
||||
onMutate: (vars): CellRollback => {
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey);
|
||||
if (!grid) return null;
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
|
||||
@@ -38,6 +38,7 @@ export interface InvoiceItem {
|
||||
quantity: number;
|
||||
unit: string;
|
||||
unit_price: number;
|
||||
discount?: number;
|
||||
vat_rate?: number;
|
||||
is_included_in_total: boolean;
|
||||
position?: number;
|
||||
|
||||
@@ -92,7 +92,7 @@ async function performMutation<TIn, TOut>(opts: {
|
||||
return result.data as TOut;
|
||||
}
|
||||
|
||||
export interface ApiMutationOptions<TIn, TOut> {
|
||||
export interface ApiMutationOptions<TIn> {
|
||||
url: string | ((input: TIn) => string);
|
||||
method: HttpMethod | ((input: TIn) => HttpMethod);
|
||||
/** Query-key prefixes to invalidate on success. Broad per CLAUDE.md. */
|
||||
@@ -122,7 +122,7 @@ export interface ApiMutationOptions<TIn, TOut> {
|
||||
* as `ApiError` (with `.status` attached) so callers can branch on HTTP code.
|
||||
*/
|
||||
export function useApiMutation<TIn, TOut>(
|
||||
opts: ApiMutationOptions<TIn, TOut> &
|
||||
opts: ApiMutationOptions<TIn> &
|
||||
Omit<UseMutationOptions<TOut, ApiError, TIn>, "mutationFn">,
|
||||
) {
|
||||
const { url, method, invalidate, envelope, onSuccess, ...rest } = opts;
|
||||
|
||||
@@ -143,6 +143,7 @@ export interface OfferItemData {
|
||||
quantity: number;
|
||||
unit: string;
|
||||
unit_price: number;
|
||||
discount?: number;
|
||||
is_included_in_total: boolean;
|
||||
position?: number;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
import apiFetch from "../../utils/api";
|
||||
import { jsonQuery } from "../apiAdapter";
|
||||
|
||||
export interface PlanUser {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useMemo, useRef } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
@@ -9,7 +9,6 @@ import { iconBadgeSx } from "../theme";
|
||||
import {
|
||||
attendanceHistoryOptions,
|
||||
type AttendanceRecord,
|
||||
type ProjectLogEntry,
|
||||
} from "../lib/queries/attendance";
|
||||
import {
|
||||
formatDate,
|
||||
@@ -201,7 +200,6 @@ const renderProjectCell = (record: AttendanceRecord) => {
|
||||
|
||||
export default function AttendanceHistory() {
|
||||
const { user, hasPermission } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const { data: companySettings } = useQuery(companySettingsOptions());
|
||||
const companyName = companySettings?.company_name || "";
|
||||
const printRef = useRef<HTMLDivElement>(null);
|
||||
@@ -212,7 +210,7 @@ export default function AttendanceHistory() {
|
||||
const { data, isPending } = useQuery(
|
||||
attendanceHistoryOptions({ month, userId: user?.id }),
|
||||
);
|
||||
const records = data ?? [];
|
||||
const records = useMemo(() => data ?? [], [data]);
|
||||
|
||||
const computed = useMemo(() => {
|
||||
const [yearStr, monthStr] = month.split("-");
|
||||
|
||||
@@ -26,10 +26,7 @@ const LocationMap = styled("div")(({ theme }) => ({
|
||||
}));
|
||||
|
||||
import { formatDate, formatTime } from "../utils/attendanceHelpers";
|
||||
import {
|
||||
attendanceLocationOptions,
|
||||
type LocationRecord,
|
||||
} from "../lib/queries/attendance";
|
||||
import { attendanceLocationOptions } from "../lib/queries/attendance";
|
||||
import { Button, Card, LoadingState, PageEnter, PageHeader } from "../ui";
|
||||
|
||||
const BackIcon = (
|
||||
|
||||
@@ -3,10 +3,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import {
|
||||
companySettingsOptions,
|
||||
type CompanySettingsData,
|
||||
} from "../lib/queries/settings";
|
||||
import { companySettingsOptions } from "../lib/queries/settings";
|
||||
import { bankAccountsOptions, type BankAccount } from "../lib/queries/common";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
@@ -23,7 +20,6 @@ import {
|
||||
TextField,
|
||||
Select,
|
||||
CheckboxField,
|
||||
StatusChip,
|
||||
FileUpload,
|
||||
LoadingState,
|
||||
type DataColumn,
|
||||
|
||||
@@ -185,9 +185,34 @@ interface InvoiceItem {
|
||||
quantity: string | number;
|
||||
unit: string;
|
||||
unit_price: string | number;
|
||||
/** Per-item discount as a percentage (0–100). */
|
||||
discount: string | number;
|
||||
vat_rate: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discount input styling: centered, native number spinners hidden so a 3-digit
|
||||
* value ("100") isn't clipped under the up/down arrows.
|
||||
*/
|
||||
const discountInputSx = {
|
||||
"& input": { textAlign: "center" },
|
||||
"& input[type=number]": { MozAppearance: "textfield" as const },
|
||||
"& input::-webkit-outer-spin-button, & input::-webkit-inner-spin-button": {
|
||||
WebkitAppearance: "none",
|
||||
margin: 0,
|
||||
},
|
||||
};
|
||||
|
||||
/** NET of one invoice line after its per-item percentage discount. */
|
||||
const invoiceLineNet = (item: {
|
||||
quantity: string | number;
|
||||
unit_price: string | number;
|
||||
discount?: string | number | null;
|
||||
}): number =>
|
||||
(Number(item.quantity) || 0) *
|
||||
(Number(item.unit_price) || 0) *
|
||||
(1 - (Number(item.discount) || 0) / 100);
|
||||
|
||||
interface InvoiceForm {
|
||||
customer_id: number | null;
|
||||
customer_name: string;
|
||||
@@ -253,8 +278,7 @@ function SortableInvoiceRow({
|
||||
position: "relative" as const,
|
||||
zIndex: isDragging ? 10 : undefined,
|
||||
};
|
||||
const lineTotal =
|
||||
(Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
|
||||
const lineTotal = invoiceLineNet(item);
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
@@ -349,6 +373,14 @@ function SortableInvoiceRow({
|
||||
onChange={(e) => onUpdate(index, "unit_price", e.target.value)}
|
||||
slotProps={{ htmlInput: { step: "any" } }}
|
||||
/>
|
||||
<TextField
|
||||
label="Sleva %"
|
||||
type="number"
|
||||
value={item.discount ?? ""}
|
||||
onChange={(e) => onUpdate(index, "discount", e.target.value)}
|
||||
slotProps={{ htmlInput: { min: "0", max: "100", step: "any" } }}
|
||||
sx={discountInputSx}
|
||||
/>
|
||||
{apply_vat && (
|
||||
<Select
|
||||
label="DPH"
|
||||
@@ -458,6 +490,15 @@ function SortableInvoiceRow({
|
||||
sx={{ "& input": { textAlign: "right" } }}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TextField
|
||||
type="number"
|
||||
value={item.discount ?? ""}
|
||||
onChange={(e) => onUpdate(index, "discount", e.target.value)}
|
||||
slotProps={{ htmlInput: { min: "0", max: "100", step: "any" } }}
|
||||
sx={discountInputSx}
|
||||
/>
|
||||
</TableCell>
|
||||
{apply_vat ? (
|
||||
<TableCell>
|
||||
<Select
|
||||
@@ -513,6 +554,7 @@ export default function InvoiceDetail() {
|
||||
quantity: 1,
|
||||
unit: "ks",
|
||||
unit_price: 0,
|
||||
discount: 0,
|
||||
vat_rate: 21,
|
||||
}),
|
||||
[],
|
||||
@@ -577,6 +619,7 @@ export default function InvoiceDetail() {
|
||||
quantity: 1,
|
||||
unit: "ks",
|
||||
unit_price: 0,
|
||||
discount: 0,
|
||||
vat_rate: 21,
|
||||
},
|
||||
]);
|
||||
@@ -621,10 +664,17 @@ export default function InvoiceDetail() {
|
||||
const customers = customersQuery.data ?? [];
|
||||
|
||||
const bankAccountsQuery = useQuery(bankAccountsOptions());
|
||||
const bankAccounts = bankAccountsQuery.data ?? [];
|
||||
const bankAccounts = useMemo(
|
||||
() => bankAccountsQuery.data ?? [],
|
||||
[bankAccountsQuery.data],
|
||||
);
|
||||
|
||||
const invoiceQuery = useQuery(invoiceDetailOptions(id));
|
||||
const invoice = invoiceQuery.data ?? null;
|
||||
// Read-only view: show the Sleva column only when some line carries a discount.
|
||||
const hasItemDiscount = (invoice?.items ?? []).some(
|
||||
(it) => Number(it.discount) > 0,
|
||||
);
|
||||
|
||||
const nextNumberQuery = useQuery({
|
||||
queryKey: ["invoices", "next-number"],
|
||||
@@ -656,8 +706,9 @@ export default function InvoiceDetail() {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const blobTimeouts = blobTimeoutsRef.current;
|
||||
return () => {
|
||||
blobTimeoutsRef.current.forEach(clearTimeout);
|
||||
blobTimeouts.forEach(clearTimeout);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -747,6 +798,7 @@ export default function InvoiceDetail() {
|
||||
quantity: Number(item.quantity) || 1,
|
||||
unit: item.unit || "",
|
||||
unit_price: Number(item.unit_price) || 0,
|
||||
discount: Number(item.discount) || 0,
|
||||
// Per-line VAT: hydrate from the ITEM's own stored rate (a real DB
|
||||
// column returned by the detail endpoint) — falling back to the
|
||||
// invoice-level rate only when the line carries none. Hydrating
|
||||
@@ -844,6 +896,7 @@ export default function InvoiceDetail() {
|
||||
quantity: Number(item.quantity) || 1,
|
||||
unit: (item.unit as string) || "",
|
||||
unit_price: Number(item.unit_price) || 0,
|
||||
discount: Number(item.discount) || 0,
|
||||
vat_rate: vatRate,
|
||||
})),
|
||||
);
|
||||
@@ -963,8 +1016,7 @@ export default function InvoiceDetail() {
|
||||
const vatByRate: Record<number, number> = {};
|
||||
|
||||
items.forEach((item) => {
|
||||
const lineTotal =
|
||||
(Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
|
||||
const lineTotal = invoiceLineNet(item);
|
||||
subtotal += lineTotal;
|
||||
|
||||
if (form.apply_vat) {
|
||||
@@ -1034,6 +1086,7 @@ export default function InvoiceDetail() {
|
||||
// field never reaches the server as NaN (mirrors createTotals).
|
||||
quantity: Number(item.quantity) || 0,
|
||||
unit_price: Number(item.unit_price) || 0,
|
||||
discount: Number(item.discount) || 0,
|
||||
position: i,
|
||||
})),
|
||||
sections: sections.map((s, i) => ({
|
||||
@@ -1357,9 +1410,7 @@ export default function InvoiceDetail() {
|
||||
isMobile ? (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||
{invoice.items.map((item, index) => {
|
||||
const lineSubtotal =
|
||||
(Number(item.quantity) || 0) *
|
||||
(Number(item.unit_price) || 0);
|
||||
const lineSubtotal = invoiceLineNet(item);
|
||||
const lineVat = Number(invoice.apply_vat)
|
||||
? (lineSubtotal * (Number(item.vat_rate) || 0)) / 100
|
||||
: 0;
|
||||
@@ -1490,6 +1541,11 @@ export default function InvoiceDetail() {
|
||||
<TableCell sx={{ width: "8rem" }} align="center">
|
||||
Jedn. cena
|
||||
</TableCell>
|
||||
{hasItemDiscount && (
|
||||
<TableCell sx={{ width: "4rem" }} align="center">
|
||||
Sleva %
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell sx={{ width: "4rem" }} align="center">
|
||||
DPH
|
||||
</TableCell>
|
||||
@@ -1500,9 +1556,7 @@ export default function InvoiceDetail() {
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{invoice.items.map((item, index) => {
|
||||
const lineSubtotal =
|
||||
(Number(item.quantity) || 0) *
|
||||
(Number(item.unit_price) || 0);
|
||||
const lineSubtotal = invoiceLineNet(item);
|
||||
const lineVat = Number(invoice.apply_vat)
|
||||
? (lineSubtotal * (Number(item.vat_rate) || 0)) / 100
|
||||
: 0;
|
||||
@@ -1551,6 +1605,13 @@ export default function InvoiceDetail() {
|
||||
>
|
||||
{formatCurrency(item.unit_price, invoice.currency)}
|
||||
</TableCell>
|
||||
{hasItemDiscount && (
|
||||
<TableCell align="center">
|
||||
{Number(item.discount) > 0
|
||||
? `${Number(item.discount)} %`
|
||||
: "—"}
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell align="center">
|
||||
{Number(invoice.apply_vat)
|
||||
? Number(item.vat_rate)
|
||||
@@ -1802,23 +1863,28 @@ export default function InvoiceDetail() {
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={headerActionsSx}>
|
||||
{isEdit && invoice && hasPermission("invoices.view") && (
|
||||
<Button
|
||||
onClick={() => handleViewPdf(invoice.language || "cs")}
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
disabled={pdfLoading}
|
||||
startIcon={
|
||||
pdfLoading ? (
|
||||
<CircularProgress size={16} color="inherit" />
|
||||
) : (
|
||||
FileIcon
|
||||
)
|
||||
}
|
||||
>
|
||||
Zobrazit fakturu
|
||||
</Button>
|
||||
)}
|
||||
{/* Drafts have no number → /file 404s; hide the button like
|
||||
OfferDetail/IssuedOrderDetail do. */}
|
||||
{isEdit &&
|
||||
invoice &&
|
||||
invoice.invoice_number &&
|
||||
hasPermission("invoices.view") && (
|
||||
<Button
|
||||
onClick={() => handleViewPdf(invoice.language || "cs")}
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
disabled={pdfLoading}
|
||||
startIcon={
|
||||
pdfLoading ? (
|
||||
<CircularProgress size={16} color="inherit" />
|
||||
) : (
|
||||
FileIcon
|
||||
)
|
||||
}
|
||||
>
|
||||
Zobrazit fakturu
|
||||
</Button>
|
||||
)}
|
||||
{/* ── Create mode: two-button save ── */}
|
||||
{!isEdit && (
|
||||
<>
|
||||
@@ -2229,6 +2295,9 @@ export default function InvoiceDetail() {
|
||||
<TableCell sx={{ width: "8rem" }} align="center">
|
||||
Jedn. cena
|
||||
</TableCell>
|
||||
<TableCell sx={{ width: "7rem" }} align="center">
|
||||
Sleva %
|
||||
</TableCell>
|
||||
{form.apply_vat ? (
|
||||
<TableCell sx={{ width: "5rem" }} align="center">
|
||||
DPH
|
||||
|
||||
@@ -248,6 +248,9 @@ export default function Invoices() {
|
||||
} else {
|
||||
setStatsMonth((m) => m - 1);
|
||||
}
|
||||
// Back to page 1 — the server never clamps, so keeping e.g. page 3 in a
|
||||
// sparser month shows an empty table (same reset as the filter handlers).
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const nextMonth = () => {
|
||||
@@ -258,6 +261,7 @@ export default function Invoices() {
|
||||
} else {
|
||||
setStatsMonth((m) => m + 1);
|
||||
}
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{
|
||||
|
||||
@@ -254,7 +254,7 @@ export default function IssuedOrderDetail() {
|
||||
const editable = !readOnly;
|
||||
const canExport = hasPermission("orders.view");
|
||||
|
||||
const { markClean } = useUnsavedChangesGuard(
|
||||
const { isDirty, markClean } = useUnsavedChangesGuard(
|
||||
{ form, items, sections },
|
||||
!isEdit || dataReady,
|
||||
);
|
||||
@@ -293,6 +293,8 @@ export default function IssuedOrderDetail() {
|
||||
quantity: numberOr(it.quantity, 1),
|
||||
unit: it.unit || "",
|
||||
unit_price: Number(it.unit_price) || 0,
|
||||
// Issued orders have no Sleva column; keep the shared item shape happy.
|
||||
discount: 0,
|
||||
}))
|
||||
: [emptyDocumentItem()];
|
||||
setItems(mappedItems);
|
||||
@@ -506,11 +508,23 @@ export default function IssuedOrderDetail() {
|
||||
else void handleSubmit();
|
||||
};
|
||||
|
||||
// ─── Status transition (status-ONLY payload — a full-form resubmit on a
|
||||
// non-editable order now 400s server-side) ───
|
||||
// ─── Status transition. With unsaved edits on an editable (sent) order
|
||||
// the transition routes through handleSubmit so the edits are PERSISTED
|
||||
// with the status — a status-only payload would silently drop them, and
|
||||
// the markClean below would re-baseline the guard so even the beforeunload
|
||||
// warning disappears (the order is then read-only: edits unrecoverable).
|
||||
// Clean (or non-editable) orders keep the status-only payload — a
|
||||
// full-form resubmit on a non-editable order 400s server-side. ───
|
||||
const handleStatusChange = async () => {
|
||||
if (!statusConfirm.status || statusChanging) return;
|
||||
const newStatus = statusConfirm.status;
|
||||
if (editable && isDirty) {
|
||||
setStatusConfirm({ show: false, status: null });
|
||||
// handleSubmit validates, sends the full payload + status, archives
|
||||
// the PDF and re-baselines the guard with what was actually persisted.
|
||||
await handleSubmit(newStatus);
|
||||
return;
|
||||
}
|
||||
setStatusChanging(newStatus);
|
||||
try {
|
||||
const result = await statusMutation.mutateAsync({ status: newStatus });
|
||||
|
||||
@@ -133,6 +133,15 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
const [status, setStatus] = useState("");
|
||||
const [supplierFilter, setSupplierFilter] = useState<number | "">("");
|
||||
const [page, setPage] = useState(1);
|
||||
// Reset to page 1 when the parent moves to another month — the kept page
|
||||
// index would otherwise request e.g. page 2 of a sparser month and render
|
||||
// an empty list. Adjusted during render (adjust-state-on-prop-change
|
||||
// pattern); a remount via `key` would also clear search/filters.
|
||||
const [prevMonthYear, setPrevMonthYear] = useState(`${month}-${year}`);
|
||||
if (`${month}-${year}` !== prevMonthYear) {
|
||||
setPrevMonthYear(`${month}-${year}`);
|
||||
setPage(1);
|
||||
}
|
||||
// Track first successful load so later refetches (filter/status/page change)
|
||||
// keep the table visible instead of flashing the full-page skeleton.
|
||||
const hasLoadedOnce = useRef(false);
|
||||
|
||||
@@ -93,6 +93,7 @@ interface OfferItemPayload {
|
||||
quantity: number;
|
||||
unit: string;
|
||||
unit_price: number;
|
||||
discount: number;
|
||||
is_included_in_total: boolean;
|
||||
position: number;
|
||||
}
|
||||
@@ -303,6 +304,7 @@ export default function OfferDetail() {
|
||||
quantity: numberOr(it.quantity, 1),
|
||||
unit: it.unit || "",
|
||||
unit_price: Number(it.unit_price) || 0,
|
||||
discount: Number(it.discount) || 0,
|
||||
is_included_in_total: it.is_included_in_total !== false,
|
||||
}))
|
||||
: [emptyDocumentItem()];
|
||||
@@ -433,6 +435,7 @@ export default function OfferDetail() {
|
||||
quantity: Number(item.quantity) || 0,
|
||||
unit: item.unit,
|
||||
unit_price: Number(item.unit_price) || 0,
|
||||
discount: Number(item.discount) || 0,
|
||||
is_included_in_total: item.is_included_in_total !== false,
|
||||
position: i,
|
||||
})),
|
||||
@@ -936,6 +939,7 @@ export default function OfferDetail() {
|
||||
readOnly={readOnly}
|
||||
error={errors.items}
|
||||
showIncludedInTotal
|
||||
showDiscount
|
||||
itemDescriptionMaxLength={8000}
|
||||
templatesSlot={
|
||||
itemTemplates && itemTemplates.length > 0 ? (
|
||||
@@ -957,6 +961,7 @@ export default function OfferDetail() {
|
||||
quantity: 1,
|
||||
unit: "ks",
|
||||
unit_price: template.default_price || 0,
|
||||
discount: 0,
|
||||
is_included_in_total: true,
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import { useState, useEffect, useMemo, useRef } from "react";
|
||||
import DOMPurify from "dompurify";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
orderDetailOptions,
|
||||
type OrderData,
|
||||
type OrderItem,
|
||||
type OrderSection,
|
||||
type OrderInvoice,
|
||||
type OrderProject,
|
||||
} from "../lib/queries/orders";
|
||||
import { orderDetailOptions, type OrderItem } from "../lib/queries/orders";
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
@@ -128,8 +121,9 @@ export default function OrderDetail() {
|
||||
}, [orderQuery.error]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
const blobTimeouts = blobTimeoutsRef.current;
|
||||
return () => {
|
||||
blobTimeoutsRef.current.forEach(clearTimeout);
|
||||
blobTimeouts.forEach(clearTimeout);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -389,7 +383,17 @@ export default function OrderDetail() {
|
||||
mb: 3,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
||||
{/* flexWrap: the title must drop below the Zpět button on phones
|
||||
instead of overflowing the viewport (same as Offer/Invoice
|
||||
detail headers). */}
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to="/orders"
|
||||
@@ -399,9 +403,22 @@ export default function OrderDetail() {
|
||||
>
|
||||
Zpět
|
||||
</Button>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1.5,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4">
|
||||
Objednávka {order.order_number}
|
||||
Objednávka
|
||||
<Box
|
||||
component="span"
|
||||
sx={{ color: "text.secondary", ml: 1, fontWeight: 400 }}
|
||||
>
|
||||
{order.order_number}
|
||||
</Box>
|
||||
</Typography>
|
||||
<StatusChip
|
||||
label={statusLabel(ORDER_STATUS, order.status)}
|
||||
|
||||
@@ -10,6 +10,10 @@ import {
|
||||
getCell,
|
||||
getCells,
|
||||
type ModalMode as HookModalMode,
|
||||
type PlanEntryBody,
|
||||
type PlanEntryPatchBody,
|
||||
type PlanOverrideBody,
|
||||
type PlanOverridePatchBody,
|
||||
} from "../hooks/usePlanWork";
|
||||
import type { PlanCellModalMode } from "../components/PlanCellModal";
|
||||
import PlanGrid from "../components/PlanGrid";
|
||||
@@ -182,7 +186,13 @@ export default function PlanWork() {
|
||||
if (bulkForm.user_ids.length === 0) return;
|
||||
setBulkSubmitting(true);
|
||||
try {
|
||||
const data: any = await bulkCreate.mutateAsync({
|
||||
// Counts can arrive either at the envelope root or nested under .data.
|
||||
type BulkSummary = {
|
||||
created_days?: number;
|
||||
skipped_days?: number;
|
||||
users?: number;
|
||||
};
|
||||
const data = (await bulkCreate.mutateAsync({
|
||||
user_ids: bulkForm.user_ids.map(Number),
|
||||
date_from: bulkForm.date_from,
|
||||
date_to: bulkForm.is_range ? bulkForm.date_to : bulkForm.date_from,
|
||||
@@ -190,12 +200,12 @@ export default function PlanWork() {
|
||||
project_id: bulkForm.project_id ? Number(bulkForm.project_id) : null,
|
||||
category: bulkForm.category,
|
||||
note: bulkForm.note,
|
||||
});
|
||||
})) as BulkSummary & { data?: BulkSummary };
|
||||
// apiCall returns the full envelope { success, data, message };
|
||||
// the summary counts are under .data
|
||||
const summary = data?.data ?? data;
|
||||
const summary: BulkSummary = data?.data ?? data;
|
||||
const skipped =
|
||||
summary?.skipped_days > 0
|
||||
(summary?.skipped_days ?? 0) > 0
|
||||
? ` ${summary.skipped_days} dní přeskočeno (limit 3 na den).`
|
||||
: "";
|
||||
alert.success(
|
||||
@@ -392,7 +402,7 @@ export default function PlanWork() {
|
||||
// optimistic cache patch the hook already applied.
|
||||
|
||||
const saveEntry = useCallback(
|
||||
async (body: any) => {
|
||||
async (body: PlanEntryBody) => {
|
||||
try {
|
||||
await createEntry.mutateAsync(body);
|
||||
// Pulse the first day of the new entry — for multi-day entries
|
||||
@@ -409,7 +419,7 @@ export default function PlanWork() {
|
||||
);
|
||||
|
||||
const updateEntryFn = useCallback(
|
||||
async (id: number, body: any) => {
|
||||
async (id: number, body: PlanEntryPatchBody) => {
|
||||
// Find the user for this entry so we know which cell to pulse /
|
||||
// which cache to roll back. The hook's optimistic patch already
|
||||
// discovered this; we read it from the current grid.
|
||||
@@ -473,7 +483,7 @@ export default function PlanWork() {
|
||||
);
|
||||
|
||||
const saveOverride = useCallback(
|
||||
async (body: any) => {
|
||||
async (body: PlanOverrideBody) => {
|
||||
try {
|
||||
await createOverride.mutateAsync(body);
|
||||
firePulse(body.user_id, body.shift_date);
|
||||
@@ -488,7 +498,7 @@ export default function PlanWork() {
|
||||
);
|
||||
|
||||
const updateOverrideFn = useCallback(
|
||||
async (id: number, body: any) => {
|
||||
async (id: number, body: PlanOverridePatchBody) => {
|
||||
// Find the user/date for the pulse + rollback.
|
||||
let userId: number | null = null;
|
||||
let date: string | null = null;
|
||||
|
||||
@@ -11,7 +11,6 @@ import MenuItem from "@mui/material/MenuItem";
|
||||
|
||||
import {
|
||||
projectDetailOptions,
|
||||
type ProjectData,
|
||||
type ProjectNote,
|
||||
} from "../lib/queries/projects";
|
||||
import { userListOptions, type User as ApiUser } from "../lib/queries/users";
|
||||
@@ -298,7 +297,17 @@ export default function ProjectDetail() {
|
||||
mb: 3,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
||||
{/* flexWrap: the title must drop below the Zpět button on phones
|
||||
instead of being squeezed beside it (mirrors Offer/Invoice
|
||||
detail headers). */}
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to="/projects"
|
||||
@@ -308,9 +317,22 @@ export default function ProjectDetail() {
|
||||
>
|
||||
Zpět
|
||||
</Button>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1.5,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4">
|
||||
Projekt {project.project_number}
|
||||
Projekt
|
||||
<Box
|
||||
component="span"
|
||||
sx={{ color: "text.secondary", ml: 1, fontWeight: 400 }}
|
||||
>
|
||||
{project.project_number}
|
||||
</Box>
|
||||
</Typography>
|
||||
<StatusChip
|
||||
label={STATUS_LABELS[project.status] || project.status}
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "../utils/formatters";
|
||||
import { normalizeDateStr } from "../utils/attendanceHelpers";
|
||||
import useTableSort from "../hooks/useTableSort";
|
||||
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
|
||||
import {
|
||||
companySettingsOptions,
|
||||
type CompanySettingsData,
|
||||
@@ -44,6 +45,7 @@ import {
|
||||
StatCard,
|
||||
EmptyState,
|
||||
LoadingState,
|
||||
Pagination,
|
||||
type DataColumn,
|
||||
type StatCardColor,
|
||||
} from "../ui";
|
||||
@@ -261,14 +263,33 @@ export default function ReceivedInvoices({
|
||||
const { data: supplierNames = [] } = useQuery(supplierListOptions());
|
||||
const companySettings = useQuery(companySettingsOptions()).data;
|
||||
|
||||
// List query — auto-refetches when filters change
|
||||
const listQuery = useQuery(
|
||||
const [page, setPage] = useState(1);
|
||||
// Reset to page 1 when the parent moves to another month — the kept page
|
||||
// index would otherwise request e.g. page 2 of a sparser month and render
|
||||
// an empty list. Adjusted during render (adjust-state-on-prop-change
|
||||
// pattern); a remount via `key` would also clear the search field.
|
||||
const [prevMonthYear, setPrevMonthYear] = useState(
|
||||
`${statsMonth}-${statsYear}`,
|
||||
);
|
||||
if (`${statsMonth}-${statsYear}` !== prevMonthYear) {
|
||||
setPrevMonthYear(`${statsMonth}-${statsYear}`);
|
||||
setPage(1);
|
||||
}
|
||||
|
||||
// List query — auto-refetches when filters change. Paginated: the server
|
||||
// caps at 25/page, so without the page param rows 26+ were unreachable.
|
||||
const {
|
||||
items: invoices,
|
||||
pagination,
|
||||
isPending: listPending,
|
||||
} = usePaginatedQuery<ReceivedInvoice>(
|
||||
receivedInvoiceListOptions({
|
||||
month: statsMonth,
|
||||
year: statsYear,
|
||||
search,
|
||||
sort,
|
||||
order,
|
||||
page,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -289,13 +310,10 @@ export default function ReceivedInvoices({
|
||||
}),
|
||||
);
|
||||
|
||||
// Derive list data from query (paginatedJsonQuery returns { data, pagination })
|
||||
const invoices = listQuery.data?.data ?? [];
|
||||
|
||||
// Track first successful load (used to suppress the skeleton on later
|
||||
// refetches). Set in an effect rather than during render to avoid a
|
||||
// render-phase ref mutation.
|
||||
const hasData = !!(listQuery.data || statsQuery.data);
|
||||
const hasData = !!(pagination || statsQuery.data);
|
||||
useEffect(() => {
|
||||
if (hasData) hasLoadedOnce.current = true;
|
||||
}, [hasData]);
|
||||
@@ -336,7 +354,7 @@ export default function ReceivedInvoices({
|
||||
},
|
||||
});
|
||||
|
||||
const showListSkeleton = listQuery.isPending && !hasLoadedOnce.current;
|
||||
const showListSkeleton = listPending && !hasLoadedOnce.current;
|
||||
|
||||
const [uploadFiles, setUploadFiles] = useState<File[]>([]);
|
||||
const [uploadMeta, setUploadMeta] = useState<UploadMeta[]>([]);
|
||||
@@ -344,8 +362,9 @@ export default function ReceivedInvoices({
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const blobTimeouts = blobTimeoutsRef.current;
|
||||
return () => {
|
||||
blobTimeoutsRef.current.forEach(clearTimeout);
|
||||
blobTimeouts.forEach(clearTimeout);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -814,7 +833,10 @@ export default function ReceivedInvoices({
|
||||
<Box sx={{ flex: "1 1 320px" }}>
|
||||
<TextField
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Hledat podle dodavatele nebo čísla faktury..."
|
||||
fullWidth
|
||||
/>
|
||||
@@ -869,6 +891,11 @@ export default function ReceivedInvoices({
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
<Pagination
|
||||
page={page}
|
||||
pageCount={pagination?.total_pages ?? 1}
|
||||
onChange={setPage}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Upload Modal */}
|
||||
@@ -1123,11 +1150,9 @@ export default function ReceivedInvoices({
|
||||
? "Zavřít"
|
||||
: "Uložit"
|
||||
}
|
||||
cancelText={
|
||||
editInvoice && editInvoice._originalStatus === "paid"
|
||||
? "Zavřít"
|
||||
: "Zrušit"
|
||||
}
|
||||
// Read-only (paid) detail has only a close action — a single "Zavřít"
|
||||
// button, not a redundant cancel button beside it.
|
||||
hideCancel={editInvoice?._originalStatus === "paid"}
|
||||
loading={saving}
|
||||
>
|
||||
{editInvoice &&
|
||||
|
||||
@@ -334,7 +334,7 @@ export default function Settings() {
|
||||
}, [sysSettingsData, sysFormInitialized]);
|
||||
|
||||
const saveSystemSettingsMutation = useApiMutation<
|
||||
typeof sysForm,
|
||||
Partial<typeof sysForm>,
|
||||
{ message?: string; error?: string }
|
||||
>({
|
||||
url: () => `${API_BASE}/company-settings`,
|
||||
@@ -424,7 +424,24 @@ export default function Settings() {
|
||||
|
||||
const handleSaveSystemSettings = async () => {
|
||||
try {
|
||||
await saveSystemSettingsMutation.mutateAsync(sysForm);
|
||||
// Send ONLY the fields this tab edits. sysForm also carries
|
||||
// numbering/currency fields captured once at init (sysFormInitialized
|
||||
// never resets), and the backend applies every defined field — sending
|
||||
// the whole form would silently revert a Firma-tab numbering edit made
|
||||
// in the meantime with stale values.
|
||||
await saveSystemSettingsMutation.mutateAsync({
|
||||
break_threshold_hours: sysForm.break_threshold_hours,
|
||||
break_duration_short: sysForm.break_duration_short,
|
||||
break_duration_long: sysForm.break_duration_long,
|
||||
clock_rounding_minutes: sysForm.clock_rounding_minutes,
|
||||
invoice_alert_email: sysForm.invoice_alert_email,
|
||||
leave_notify_email: sysForm.leave_notify_email,
|
||||
smtp_from: sysForm.smtp_from,
|
||||
smtp_from_name: sysForm.smtp_from_name,
|
||||
max_login_attempts: sysForm.max_login_attempts,
|
||||
lockout_minutes: sysForm.lockout_minutes,
|
||||
max_requests_per_minute: sysForm.max_requests_per_minute,
|
||||
});
|
||||
} catch (e) {
|
||||
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||
}
|
||||
@@ -698,7 +715,25 @@ export default function Settings() {
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const si = systemInfo as Record<string, any>;
|
||||
type NasInfo = { configured?: boolean; path?: string | null };
|
||||
type SystemInfo = {
|
||||
app_version?: string;
|
||||
node_version?: string;
|
||||
platform?: string;
|
||||
uptime?: string;
|
||||
environment?: string;
|
||||
timezone?: string;
|
||||
memory?: {
|
||||
rss?: string;
|
||||
heap_used?: string;
|
||||
heap_total?: string;
|
||||
system_free?: string;
|
||||
system_total?: string;
|
||||
};
|
||||
database?: { status?: string; migrations_applied?: number | string };
|
||||
nas?: Record<string, NasInfo | undefined>;
|
||||
};
|
||||
const si = systemInfo as SystemInfo;
|
||||
const Row = ({
|
||||
label,
|
||||
children,
|
||||
@@ -783,7 +818,7 @@ export default function Settings() {
|
||||
["Faktury", si.nas?.invoices],
|
||||
["Objednávky", si.nas?.orders],
|
||||
["Nabídky", si.nas?.offers],
|
||||
] as [string, Record<string, any>][]
|
||||
] as [string, NasInfo | undefined][]
|
||||
).map(([label, info]) => (
|
||||
<Row key={label} label={label}>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
|
||||
@@ -199,7 +199,7 @@ export default function Trips() {
|
||||
TripForm,
|
||||
{ message?: string; error?: string }
|
||||
>({
|
||||
url: (formData) =>
|
||||
url: () =>
|
||||
editingTrip ? `${API_BASE}/trips/${editingTrip.id}` : `${API_BASE}/trips`,
|
||||
method: () => (editingTrip ? "PUT" : "POST"),
|
||||
invalidate: ["trips", "vehicles"],
|
||||
|
||||
@@ -23,7 +23,7 @@ interface InventoryItem {
|
||||
}
|
||||
|
||||
function parseDecimal(raw: string): number {
|
||||
const cleaned = raw.replace(/[eE+\-]/g, "");
|
||||
const cleaned = raw.replace(/[eE+-]/g, "");
|
||||
const n = Number(cleaned);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useRef, useId } from "react";
|
||||
import { useState, useEffect, useRef, useId, useCallback } from "react";
|
||||
import {
|
||||
useParams,
|
||||
useNavigate,
|
||||
@@ -65,7 +65,7 @@ interface BatchesResponse {
|
||||
}
|
||||
|
||||
function parseDecimal(raw: string): number {
|
||||
const cleaned = raw.replace(/[eE+\-]/g, "");
|
||||
const cleaned = raw.replace(/[eE+-]/g, "");
|
||||
const n = Number(cleaned);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
@@ -174,7 +174,10 @@ export default function WarehouseIssueForm() {
|
||||
|
||||
const baseId = useId();
|
||||
const counterRef = useRef(0);
|
||||
const nextKey = () => `${baseId}-item-${counterRef.current++}`;
|
||||
const nextKey = useCallback(
|
||||
() => `${baseId}-item-${counterRef.current++}`,
|
||||
[baseId],
|
||||
);
|
||||
|
||||
// Pre-fill data from reservation ("Create výdej" button)
|
||||
const prefill = location.state as {
|
||||
@@ -262,7 +265,7 @@ export default function WarehouseIssueForm() {
|
||||
}
|
||||
formInitialized.current = true;
|
||||
}
|
||||
}, [isEdit, issue]);
|
||||
}, [isEdit, issue, nextKey]);
|
||||
|
||||
const saveMutation = useApiMutation<
|
||||
ReturnType<typeof buildPayload>,
|
||||
|
||||
@@ -50,7 +50,7 @@ interface MovementItem {
|
||||
}
|
||||
|
||||
function parseDecimal(raw: string): number {
|
||||
const cleaned = raw.replace(/[eE+\-]/g, "");
|
||||
const cleaned = raw.replace(/[eE+-]/g, "");
|
||||
const n = Number(cleaned);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
@@ -126,7 +126,10 @@ export default function WarehouseReceiptForm() {
|
||||
|
||||
const baseId = useId();
|
||||
const counterRef = useRef(0);
|
||||
const nextKey = () => `${baseId}-item-${counterRef.current++}`;
|
||||
const nextKey = useCallback(
|
||||
() => `${baseId}-item-${counterRef.current++}`,
|
||||
[baseId],
|
||||
);
|
||||
|
||||
const [form, setForm] = useState<ReceiptForm>({
|
||||
supplier_id: null,
|
||||
@@ -198,7 +201,7 @@ export default function WarehouseReceiptForm() {
|
||||
}
|
||||
formInitialized.current = true;
|
||||
}
|
||||
}, [isEdit, receipt]);
|
||||
}, [isEdit, receipt, nextKey]);
|
||||
|
||||
const saveMutation = useApiMutation<
|
||||
ReturnType<typeof buildPayload>,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { theme } from "./theme";
|
||||
|
||||
/** Loose shape for poking into MUI styleOverrides objects in assertions. */
|
||||
type StyleObj = Record<string, unknown>;
|
||||
|
||||
/** Minimal palette shape used by the colorSchemes assertions below. */
|
||||
interface SchemesPalette {
|
||||
primary: { main: string };
|
||||
@@ -44,18 +47,20 @@ describe("MUI theme", () => {
|
||||
});
|
||||
|
||||
it("makes buttons pill-shaped and cards 16px by default", () => {
|
||||
const btn = theme.components?.MuiButton?.styleOverrides?.root as any;
|
||||
expect(btn?.borderRadius).toBe(999);
|
||||
const card = theme.components?.MuiCard?.styleOverrides?.root as any;
|
||||
expect(card?.borderRadius).toBe(16);
|
||||
const btn = theme.components?.MuiButton?.styleOverrides?.root as StyleObj;
|
||||
expect(btn.borderRadius).toBe(999);
|
||||
const card = theme.components?.MuiCard?.styleOverrides?.root as StyleObj;
|
||||
expect(card.borderRadius).toBe(16);
|
||||
});
|
||||
|
||||
it("adds 200-300ms interaction motion (press + focus ring)", () => {
|
||||
const btn = theme.components?.MuiButton?.styleOverrides?.root as any;
|
||||
expect(btn?.transition).toContain("transform");
|
||||
expect(btn?.["&:active"]?.transform).toBe("scale(0.97)");
|
||||
const btn = theme.components?.MuiButton?.styleOverrides?.root as StyleObj;
|
||||
expect(btn.transition).toContain("transform");
|
||||
const active = btn["&:active"] as StyleObj;
|
||||
expect(active.transform).toBe("scale(0.97)");
|
||||
const input = theme.components?.MuiOutlinedInput?.styleOverrides
|
||||
?.root as any;
|
||||
expect(input?.["&.Mui-focused"]?.boxShadow).toContain("rgba");
|
||||
?.root as StyleObj;
|
||||
const focused = input["&.Mui-focused"] as StyleObj;
|
||||
expect(focused.boxShadow).toContain("rgba");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { createTheme, type Theme } from "@mui/material/styles";
|
||||
import {
|
||||
createTheme,
|
||||
type Theme,
|
||||
type PaletteColor,
|
||||
type PaletteColorChannel,
|
||||
} from "@mui/material/styles";
|
||||
|
||||
const FONT_BODY = "'Plus Jakarta Sans', system-ui, sans-serif";
|
||||
const FONT_HEADING = "'Urbanist', sans-serif";
|
||||
@@ -33,6 +38,26 @@ export const theme = createTheme({
|
||||
warning: { main: "#b45309", contrastText: "#fff" },
|
||||
error: { main: "#b91c1c", contrastText: "#fff" },
|
||||
info: { main: "#1d4ed8", contrastText: "#fff" },
|
||||
// Sidebar section hues (full objects so cssVariables emits *Channel
|
||||
// tokens — the nav tiles use channel-alpha washes).
|
||||
teal: {
|
||||
main: "#0e8a7c",
|
||||
light: "#3aa99c",
|
||||
dark: "#0a675d",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
violet: {
|
||||
main: "#6a4cb4",
|
||||
light: "#8a6fd0",
|
||||
dark: "#54399a",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
slate: {
|
||||
main: "#5c6470",
|
||||
light: "#7d8694",
|
||||
dark: "#454c56",
|
||||
contrastText: "#fff",
|
||||
},
|
||||
background: { default: "#f4f3f1", paper: "#ffffff" },
|
||||
text: { primary: "#1a1a1a", secondary: "#555555" },
|
||||
divider: "rgba(0,0,0,0.1)",
|
||||
@@ -46,6 +71,25 @@ export const theme = createTheme({
|
||||
warning: { main: "#f59e0b", contrastText: "#1a1a1a" },
|
||||
error: { main: "#ef4444", contrastText: "#1a1a1a" },
|
||||
info: { main: "#3b82f6", contrastText: "#1a1a1a" },
|
||||
// Sidebar section hues — brighter mains so the glyphs read on dark.
|
||||
teal: {
|
||||
main: "#2dd4bf",
|
||||
light: "#5eead4",
|
||||
dark: "#14b8a6",
|
||||
contrastText: "#1a1a1a",
|
||||
},
|
||||
violet: {
|
||||
main: "#a78bfa",
|
||||
light: "#c4b5fd",
|
||||
dark: "#8b5cf6",
|
||||
contrastText: "#1a1a1a",
|
||||
},
|
||||
slate: {
|
||||
main: "#94a3b8",
|
||||
light: "#cbd5e1",
|
||||
dark: "#64748b",
|
||||
contrastText: "#1a1a1a",
|
||||
},
|
||||
background: { default: "#0f0f0f", paper: "#1a1a1a" },
|
||||
text: { primary: "#ffffff", secondary: "#a0a0a0" },
|
||||
divider: "rgba(255,255,255,0.08)",
|
||||
@@ -239,6 +283,24 @@ export const fonts = {
|
||||
mono: FONT_MONO,
|
||||
};
|
||||
|
||||
// Custom sidebar-section palette entries (teal/violet/slate above). The
|
||||
// channel intersection matters: theme.vars.palette.<hue>.mainChannel is how
|
||||
// the nav tiles build their alpha washes.
|
||||
type NavPaletteColor = PaletteColor & PaletteColorChannel;
|
||||
|
||||
declare module "@mui/material/styles" {
|
||||
interface Palette {
|
||||
teal: NavPaletteColor;
|
||||
violet: NavPaletteColor;
|
||||
slate: NavPaletteColor;
|
||||
}
|
||||
interface PaletteOptions {
|
||||
teal?: PaletteOptions["primary"];
|
||||
violet?: PaletteOptions["primary"];
|
||||
slate?: PaletteOptions["primary"];
|
||||
}
|
||||
}
|
||||
|
||||
export type IconBadgeColor =
|
||||
| "default"
|
||||
| "primary"
|
||||
|
||||
@@ -88,9 +88,8 @@ export default function SidebarNav({ onNavigate, onLogout }: SidebarNavProps) {
|
||||
sx={{
|
||||
borderRadius: 2,
|
||||
mb: 0.25,
|
||||
py: 0.6,
|
||||
py: 0.45,
|
||||
color: "text.secondary",
|
||||
"& svg": { width: 18, height: 18 },
|
||||
"&.Mui-selected, &.Mui-selected:hover": {
|
||||
bgcolor: "background.paper",
|
||||
color: "primary.main",
|
||||
@@ -99,8 +98,29 @@ export default function SidebarNav({ onNavigate, onLogout }: SidebarNavProps) {
|
||||
},
|
||||
}}
|
||||
>
|
||||
<ListItemIcon sx={{ minWidth: 32, color: "inherit" }}>
|
||||
{item.icon}
|
||||
<ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
|
||||
{item.rawIcon ? (
|
||||
item.icon
|
||||
) : (
|
||||
<Box
|
||||
sx={(t) => ({
|
||||
width: 26,
|
||||
height: 26,
|
||||
// Echoes OdinMark's rounded-square tile; only Odin
|
||||
// is solid + animated, these are quiet washes.
|
||||
borderRadius: "32%",
|
||||
flexShrink: 0,
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
bgcolor: `rgba(${t.vars!.palette[section.hue].mainChannel} / 0.12)`,
|
||||
color: t.vars!.palette[section.hue].main,
|
||||
"& svg": { width: 16, height: 16 },
|
||||
})}
|
||||
>
|
||||
{item.icon}
|
||||
</Box>
|
||||
)}
|
||||
</ListItemIcon>
|
||||
<ListItemText
|
||||
primary={item.label}
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import { type ReactNode } from "react";
|
||||
import OdinMark from "../components/odin/OdinMark";
|
||||
|
||||
/** Palette key driving a section's tile wash + glyph color (see theme.ts). */
|
||||
export type NavHue =
|
||||
| "primary"
|
||||
| "info"
|
||||
| "teal"
|
||||
| "warning"
|
||||
| "violet"
|
||||
| "slate";
|
||||
|
||||
export interface MenuItem {
|
||||
path: string;
|
||||
label: string;
|
||||
@@ -10,33 +19,51 @@ export interface MenuItem {
|
||||
matchAlso?: string[];
|
||||
matchExclude?: string[];
|
||||
icon: ReactNode;
|
||||
/** Icon ships its own container (OdinMark) — SidebarNav skips the tile. */
|
||||
rawIcon?: boolean;
|
||||
}
|
||||
|
||||
export interface MenuSection {
|
||||
label: string;
|
||||
hue: NavHue;
|
||||
items: MenuItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
* One stroke glyph per item, every glyph unique within the set (pinned by
|
||||
* navdata-icons.test.ts). 24-viewBox, stroke 2, round caps — rendered at
|
||||
* 16px inside SidebarNav's 26px section-hue tile.
|
||||
*/
|
||||
function glyph(children: ReactNode) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const menuSections: MenuSection[] = [
|
||||
{
|
||||
label: "Přehled",
|
||||
hue: "primary",
|
||||
items: [
|
||||
{
|
||||
path: "/",
|
||||
label: "Přehled",
|
||||
end: true,
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect x="3" y="3" width="7" height="7" rx="1" />
|
||||
<rect x="14" y="3" width="7" height="7" rx="1" />
|
||||
<rect x="14" y="14" width="7" height="7" rx="1" />
|
||||
<rect x="3" y="14" width="7" height="7" rx="1" />
|
||||
</svg>
|
||||
// tachometr — dashboard
|
||||
icon: glyph(
|
||||
<>
|
||||
<circle cx="12" cy="13" r="8.5" />
|
||||
<path d="M12 13l4-4.5" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -44,78 +71,66 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Odin",
|
||||
permission: "ai.use",
|
||||
end: true,
|
||||
icon: <OdinMark size={22} />,
|
||||
icon: <OdinMark size={26} />,
|
||||
rawIcon: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Docházka",
|
||||
hue: "info",
|
||||
items: [
|
||||
{
|
||||
path: "/attendance",
|
||||
label: "Záznam",
|
||||
permission: "attendance.record",
|
||||
end: true,
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
// píchačky — hodiny
|
||||
icon: glyph(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<polyline points="12 7 12 12 15 15" />
|
||||
</svg>
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/attendance/history",
|
||||
label: "Moje historie",
|
||||
permission: "attendance.history",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<polyline points="12 8 12 12 14 14" />
|
||||
<path d="M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5" />
|
||||
</svg>
|
||||
// výkaz s hodinami — timesheet
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M14 3H5a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h6" />
|
||||
<line x1="7" y1="8" x2="13" y2="8" />
|
||||
<line x1="7" y1="12" x2="11" y2="12" />
|
||||
<circle cx="16.5" cy="16" r="4.5" />
|
||||
<polyline points="16.5 14 16.5 16 18 17" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/attendance/requests",
|
||||
label: "Žádosti",
|
||||
permission: "attendance.record",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<polyline points="14 2 14 8 20 8" />
|
||||
<line x1="12" y1="18" x2="12" y2="12" />
|
||||
<line x1="9" y1="15" x2="15" y2="15" />
|
||||
</svg>
|
||||
// odeslaná žádost — vlaštovka
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M22 2L11 13" />
|
||||
<path d="M22 2l-7 20-4-9-9-4z" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/attendance/approval",
|
||||
label: "Schvalování",
|
||||
permission: "attendance.approve",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M9 12l2 2 4-4" />
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
</svg>
|
||||
// razítko
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M9.5 12V9.8C9.5 8.4 8 7.8 8 6a4 4 0 0 1 8 0c0 1.8-1.5 2.4-1.5 3.8V12" />
|
||||
<path d="M5 16a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v2H5z" />
|
||||
<line x1="5" y1="21" x2="19" y2="21" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -124,147 +139,108 @@ export const menuSections: MenuSection[] = [
|
||||
permission: "attendance.manage",
|
||||
matchPrefix: "/attendance/admin",
|
||||
matchAlso: ["/attendance/create", "/attendance/location"],
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="4" y1="21" x2="4" y2="14" />
|
||||
<line x1="4" y1="10" x2="4" y2="3" />
|
||||
<line x1="12" y1="21" x2="12" y2="12" />
|
||||
<line x1="12" y1="8" x2="12" y2="3" />
|
||||
<line x1="20" y1="21" x2="20" y2="16" />
|
||||
<line x1="20" y1="12" x2="20" y2="3" />
|
||||
<line x1="1" y1="14" x2="7" y2="14" />
|
||||
<line x1="9" y1="8" x2="15" y2="8" />
|
||||
<line x1="17" y1="16" x2="23" y2="16" />
|
||||
</svg>
|
||||
// osoba + fajfka
|
||||
icon: glyph(
|
||||
<>
|
||||
<circle cx="9" cy="8" r="3.5" />
|
||||
<path d="M3 20a6 6 0 0 1 12 0" />
|
||||
<path d="M15.5 11.5l2 2 4-4" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/attendance/balances",
|
||||
label: "Správa bilancí",
|
||||
permission: "attendance.balances",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="18" y1="20" x2="18" y2="10" />
|
||||
<line x1="12" y1="20" x2="12" y2="4" />
|
||||
<line x1="6" y1="20" x2="6" y2="14" />
|
||||
</svg>
|
||||
// kniha plus/mínus — ruční korekce bilancí
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="4" y="3" width="16" height="18" rx="2" />
|
||||
<line x1="9" y1="8.5" x2="15" y2="8.5" />
|
||||
<line x1="12" y1="5.5" x2="12" y2="11.5" />
|
||||
<line x1="9" y1="16" x2="15" y2="16" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/plan-work",
|
||||
label: "Plán prací",
|
||||
permission: ["attendance.manage", "attendance.record"],
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<rect x="3" y="4" width="18" height="18" rx="2" />
|
||||
// kalendář s plánovacím blokem
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="17" rx="2" />
|
||||
<line x1="16" y1="2" x2="16" y2="6" />
|
||||
<line x1="8" y1="2" x2="8" y2="6" />
|
||||
<line x1="3" y1="10" x2="21" y2="10" />
|
||||
</svg>
|
||||
<line x1="3" y1="9.5" x2="21" y2="9.5" />
|
||||
<path d="M8 14h3v3H8z" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Kniha jízd",
|
||||
hue: "teal",
|
||||
items: [
|
||||
{
|
||||
path: "/trips",
|
||||
label: "Záznam",
|
||||
permission: "trips.record",
|
||||
end: true,
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<circle cx="5" cy="18" r="3" />
|
||||
<circle cx="19" cy="18" r="3" />
|
||||
<path d="M5 18V12L8 5h8l3 7v6" />
|
||||
<path d="M10 18h4" />
|
||||
</svg>
|
||||
// trasa A→B
|
||||
icon: glyph(
|
||||
<>
|
||||
<circle cx="5" cy="19" r="2" />
|
||||
<circle cx="19" cy="5" r="2" />
|
||||
<path d="M5 17C5 11 19 13 19 7" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/trips/history",
|
||||
label: "Moje historie",
|
||||
permission: "trips.history",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<polyline points="12 8 12 12 14 14" />
|
||||
<path d="M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5" />
|
||||
</svg>
|
||||
// navštívená místa — pin
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M12 21s-6-5.2-6-10a6 6 0 0 1 12 0c0 4.8-6 10-6 10z" />
|
||||
<circle cx="12" cy="11" r="2.5" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/trips/admin",
|
||||
label: "Správa",
|
||||
permission: "trips.manage",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="4" y1="21" x2="4" y2="14" />
|
||||
<line x1="4" y1="10" x2="4" y2="3" />
|
||||
<line x1="12" y1="21" x2="12" y2="12" />
|
||||
<line x1="12" y1="8" x2="12" y2="3" />
|
||||
<line x1="20" y1="21" x2="20" y2="16" />
|
||||
<line x1="20" y1="12" x2="20" y2="3" />
|
||||
<line x1="1" y1="14" x2="7" y2="14" />
|
||||
<line x1="9" y1="8" x2="15" y2="8" />
|
||||
<line x1="17" y1="16" x2="23" y2="16" />
|
||||
</svg>
|
||||
// schránka s fajfkou — kniha jízd
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="5" y="4" width="14" height="17" rx="2" />
|
||||
<path d="M9 2h6v4H9z" />
|
||||
<path d="M9 13l2 2 4-4" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/vehicles",
|
||||
label: "Vozidla",
|
||||
permission: "vehicles.manage",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect x="1" y="3" width="15" height="13" rx="2" />
|
||||
<path d="M16 8h4l3 3v5h-7V8z" />
|
||||
<circle cx="5.5" cy="18.5" r="2.5" />
|
||||
<circle cx="18.5" cy="18.5" r="2.5" />
|
||||
</svg>
|
||||
// auto
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M5 17H3v-4l2-5h11l3 5h2v4h-2" />
|
||||
<circle cx="7.5" cy="17" r="2" />
|
||||
<circle cx="16.5" cy="17" r="2" />
|
||||
<line x1="9.5" y1="17" x2="14.5" y2="17" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Administrativa",
|
||||
hue: "warning",
|
||||
items: [
|
||||
{
|
||||
path: "/offers",
|
||||
@@ -272,16 +248,12 @@ export const menuSections: MenuSection[] = [
|
||||
permission: "offers.view",
|
||||
matchPrefix: "/offers",
|
||||
matchExclude: ["/offers/customers", "/offers/templates"],
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<polyline points="14 2 14 8 20 8" />
|
||||
</svg>
|
||||
// cenovka
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M20.6 13.4L11 3H4v7l9.6 10.4a2 2 0 0 0 2.8 0l4.2-4.2a2 2 0 0 0 0-2.8z" />
|
||||
<circle cx="8" cy="8" r="1.5" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -289,17 +261,13 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Objednávky",
|
||||
permission: "orders.view",
|
||||
matchPrefix: "/orders",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z" />
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<path d="M16 10a4 4 0 0 1-8 0" />
|
||||
</svg>
|
||||
// košík
|
||||
icon: glyph(
|
||||
<>
|
||||
<circle cx="9" cy="20" r="1.6" />
|
||||
<circle cx="17" cy="20" r="1.6" />
|
||||
<path d="M2 3h3l2.7 12h10.6l2.7-9H6" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -307,16 +275,13 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Faktury",
|
||||
permission: "invoices.view",
|
||||
matchPrefix: "/invoices",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="12" y1="1" x2="12" y2="23" />
|
||||
<path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
|
||||
</svg>
|
||||
// účtenka
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M6 2h12v20l-3-2-3 2-3-2-3 2z" />
|
||||
<line x1="9" y1="7" x2="15" y2="7" />
|
||||
<line x1="9" y1="11" x2="15" y2="11" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -324,60 +289,44 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Projekty",
|
||||
permission: "projects.view",
|
||||
matchPrefix: "/projects",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect x="2" y="3" width="20" height="14" rx="2" />
|
||||
<line x1="8" y1="21" x2="16" y2="21" />
|
||||
<line x1="12" y1="17" x2="12" y2="21" />
|
||||
</svg>
|
||||
// složka (NAS projektové složky)
|
||||
icon: glyph(
|
||||
<path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/offers/customers",
|
||||
label: "Zákazníci",
|
||||
permission: "customers.view",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
|
||||
</svg>
|
||||
// vizitka
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="2" y="4" width="20" height="16" rx="2" />
|
||||
<circle cx="8.5" cy="10.5" r="2.2" />
|
||||
<path d="M5 16.5a3.5 3.5 0 0 1 7 0" />
|
||||
<line x1="14.5" y1="9.5" x2="19" y2="9.5" />
|
||||
<line x1="14.5" y1="13.5" x2="19" y2="13.5" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Sklad",
|
||||
hue: "violet",
|
||||
items: [
|
||||
{
|
||||
path: "/warehouse",
|
||||
label: "Přehled",
|
||||
permission: "warehouse.view",
|
||||
end: true,
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
|
||||
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
|
||||
<line x1="12" y1="22.08" x2="12" y2="12" />
|
||||
</svg>
|
||||
// skladová hala
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M3 21V9l9-5 9 5v12" />
|
||||
<path d="M7 21v-7h10v7" />
|
||||
<line x1="7" y1="17.5" x2="17" y2="17.5" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -385,17 +334,13 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Položky",
|
||||
permission: "warehouse.view",
|
||||
matchPrefix: "/warehouse/items",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
// krabice
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
|
||||
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
|
||||
<line x1="12" y1="22.08" x2="12" y2="12" />
|
||||
</svg>
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -403,17 +348,13 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Příjmy",
|
||||
permission: "warehouse.operate",
|
||||
matchPrefix: "/warehouse/receipts",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<polyline points="17 11 12 6 7 11" />
|
||||
<line x1="12" y1="6" x2="12" y2="18" />
|
||||
<path d="M5 19h14" />
|
||||
</svg>
|
||||
// šipka do krabice
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="4" y="12" width="16" height="9" rx="1" />
|
||||
<polyline points="8 6 12 10 16 6" />
|
||||
<line x1="12" y1="2" x2="12" y2="10" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -421,17 +362,13 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Výdeje",
|
||||
permission: "warehouse.operate",
|
||||
matchPrefix: "/warehouse/issues",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<polyline points="7 13 12 18 17 13" />
|
||||
<line x1="12" y1="18" x2="12" y2="6" />
|
||||
<path d="M5 5h14" />
|
||||
</svg>
|
||||
// šipka z krabice ven
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="4" y="13" width="16" height="8" rx="1" />
|
||||
<polyline points="8 6 12 2 16 6" />
|
||||
<line x1="12" y1="2" x2="12" y2="11" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -439,18 +376,12 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Rezervace",
|
||||
permission: "warehouse.operate",
|
||||
matchPrefix: "/warehouse/reservations",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<line x1="19" y1="8" x2="19" y2="14" />
|
||||
<line x1="22" y1="11" x2="16" y2="11" />
|
||||
</svg>
|
||||
// krabice se záložkou
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="3" y="8" width="13" height="12" rx="1" />
|
||||
<path d="M16 3h5v9l-2.5-2L16 12z" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -458,16 +389,15 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Inventura",
|
||||
permission: "warehouse.inventory",
|
||||
matchPrefix: "/warehouse/inventory",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M9 11l3 3L22 4" />
|
||||
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
|
||||
</svg>
|
||||
// čárový kód — fyzický sken zásob
|
||||
icon: glyph(
|
||||
<>
|
||||
<line x1="4" y1="6" x2="4" y2="18" />
|
||||
<line x1="8" y1="6" x2="8" y2="18" />
|
||||
<line x1="12" y1="6" x2="12" y2="18" />
|
||||
<line x1="17" y1="6" x2="17" y2="18" />
|
||||
<line x1="20" y1="6" x2="20" y2="18" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -475,17 +405,12 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Reporty",
|
||||
permission: "warehouse.view",
|
||||
end: true,
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="18" y1="20" x2="18" y2="10" />
|
||||
<line x1="12" y1="20" x2="12" y2="4" />
|
||||
<line x1="6" y1="20" x2="6" y2="14" />
|
||||
</svg>
|
||||
// graf v rámu
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" />
|
||||
<polyline points="7 14 11 10 14 13 17 8" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -493,23 +418,14 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Kategorie",
|
||||
permission: "warehouse.manage",
|
||||
matchPrefix: "/warehouse/categories",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="4" y1="21" x2="4" y2="14" />
|
||||
<line x1="4" y1="10" x2="4" y2="3" />
|
||||
<line x1="12" y1="21" x2="12" y2="12" />
|
||||
<line x1="12" y1="8" x2="12" y2="3" />
|
||||
<line x1="20" y1="21" x2="20" y2="16" />
|
||||
<line x1="20" y1="12" x2="20" y2="3" />
|
||||
<line x1="1" y1="14" x2="7" y2="14" />
|
||||
<line x1="9" y1="8" x2="15" y2="8" />
|
||||
<line x1="17" y1="16" x2="23" y2="16" />
|
||||
</svg>
|
||||
// tvary — třídění do kategorií
|
||||
icon: glyph(
|
||||
<>
|
||||
<circle cx="7.5" cy="7.5" r="3.5" />
|
||||
<rect x="13.5" y="4" width="7" height="7" rx="1" />
|
||||
<path d="M7.5 13.5l3.5 7h-7z" />
|
||||
<rect x="13.5" y="13.5" width="7" height="7" rx="3.5" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -517,18 +433,16 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Lokace",
|
||||
permission: "warehouse.manage",
|
||||
matchPrefix: "/warehouse/locations",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect x="3" y="3" width="7" height="7" rx="1" />
|
||||
<rect x="14" y="3" width="7" height="7" rx="1" />
|
||||
<rect x="3" y="14" width="7" height="7" rx="1" />
|
||||
<rect x="14" y="14" width="7" height="7" rx="1" />
|
||||
</svg>
|
||||
// regál s krabicemi
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M3 21V4" />
|
||||
<path d="M21 21V4" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="21" x2="21" y2="21" />
|
||||
<rect x="7" y="8" width="4" height="4" />
|
||||
<rect x="13" y="17" width="4" height="4" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -536,41 +450,34 @@ export const menuSections: MenuSection[] = [
|
||||
label: "Dodavatelé",
|
||||
permission: "warehouse.manage",
|
||||
matchPrefix: "/warehouse/suppliers",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
|
||||
</svg>
|
||||
// kamion
|
||||
icon: glyph(
|
||||
<>
|
||||
<rect x="1" y="6" width="13" height="10" rx="1" />
|
||||
<path d="M14 9h4l3 4v3h-7" />
|
||||
<circle cx="6" cy="18.5" r="2" />
|
||||
<circle cx="17.5" cy="18.5" r="2" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Systém",
|
||||
hue: "slate",
|
||||
items: [
|
||||
{
|
||||
path: "/users",
|
||||
label: "Uživatelé",
|
||||
permission: "users.view",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
// lidé — uživatelské účty
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
|
||||
</svg>
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -583,35 +490,27 @@ export const menuSections: MenuSection[] = [
|
||||
"settings.system",
|
||||
"settings.templates",
|
||||
],
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
// ozubené kolo
|
||||
icon: glyph(
|
||||
<>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
|
||||
</svg>
|
||||
</>,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/audit-log",
|
||||
label: "Audit log",
|
||||
permission: "settings.audit",
|
||||
icon: (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<polyline points="14 2 14 8 20 8" />
|
||||
<line x1="16" y1="13" x2="8" y2="13" />
|
||||
<line x1="16" y1="17" x2="8" y2="17" />
|
||||
<polyline points="10 9 9 9 8 9" />
|
||||
</svg>
|
||||
// lupa nad záznamy
|
||||
icon: glyph(
|
||||
<>
|
||||
<path d="M4 5h12" />
|
||||
<path d="M4 10h6" />
|
||||
<path d="M4 15h5" />
|
||||
<circle cx="15" cy="14" r="4.5" />
|
||||
<line x1="18.2" y1="17.2" x2="21.5" y2="20.5" />
|
||||
</>,
|
||||
),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { FastifyRequest, FastifyReply } from "fastify";
|
||||
import { verifyAccessToken } from "../services/auth";
|
||||
import { error } from "../utils/response";
|
||||
import { AuthData } from "../types";
|
||||
|
||||
export async function requireAuth(
|
||||
request: FastifyRequest,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
|
||||
import multipart from "@fastify/multipart";
|
||||
import { requirePermission } from "../../middleware/auth";
|
||||
import { requirePermission, requireAnyPermission } from "../../middleware/auth";
|
||||
import { success, error, parseId } from "../../utils/response";
|
||||
import { parseBody } from "../../schemas/common";
|
||||
import {
|
||||
@@ -54,10 +54,14 @@ export default async function aiRoutes(app: FastifyInstance): Promise<void> {
|
||||
},
|
||||
);
|
||||
|
||||
// PUT /api/admin/ai/budget — set the monthly budget (admins have ai.use)
|
||||
// PUT /api/admin/ai/budget — set the monthly budget. A COMPANY setting
|
||||
// (budget_usd=0 is a company-wide AI DoS; a huge value removes the cost
|
||||
// cap), so it is gated like company_settings writes, NOT by ai.use.
|
||||
app.put(
|
||||
"/budget",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
{
|
||||
preHandler: requireAnyPermission("settings.company", "settings.system"),
|
||||
},
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(AiBudgetSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
|
||||
@@ -42,7 +42,10 @@ export default async function auditLogRoutes(
|
||||
if (query.date_from || query.date_to) {
|
||||
const dateFilter: Record<string, Date> = {};
|
||||
if (query.date_from) {
|
||||
const from = new Date(String(query.date_from));
|
||||
// LOCAL midnight, symmetric with the date_to side below — a bare
|
||||
// new Date("YYYY-MM-DD") is UTC midnight (01:00/02:00 Prague) and
|
||||
// silently excluded events from the first morning hours.
|
||||
const from = new Date(String(query.date_from) + "T00:00:00");
|
||||
if (isNaN(from.getTime())) {
|
||||
return error(reply, "Neplatné datum od", 400);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ import { parseBody } from "../../schemas/common";
|
||||
import { UpdateCompanySettingsSchema } from "../../schemas/settings.schema";
|
||||
import { invalidateSettingsCache } from "../../services/system-settings";
|
||||
import os from "os";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { config } from "../../config/env";
|
||||
import { NasFileManager } from "../../services/nas-file-manager";
|
||||
import {
|
||||
@@ -21,6 +23,15 @@ import {
|
||||
} from "../../services/nas-financials-manager";
|
||||
import { nasOffersManager } from "../../services/nas-offers-manager";
|
||||
|
||||
// Read once at load. A static `import` of the root package.json would pull a
|
||||
// file outside `src` into the program, expanding tsc's rootDir and shifting the
|
||||
// whole dist/ layout — so resolve it at runtime relative to the compiled file.
|
||||
const APP_VERSION = (
|
||||
JSON.parse(
|
||||
readFileSync(join(__dirname, "../../../package.json"), "utf8"),
|
||||
) as { version: string }
|
||||
).version;
|
||||
|
||||
/** Encode custom_fields + supplier_field_order into a single JSON blob (matching PHP format) */
|
||||
function encodeCustomFields(
|
||||
fields: unknown,
|
||||
@@ -325,8 +336,6 @@ export default async function companySettingsRoutes(
|
||||
settings.custom_fields as string | null,
|
||||
);
|
||||
|
||||
const pkg = require("../../../package.json") as { version: string };
|
||||
|
||||
let available_vat_rates: number[] = [0, 10, 12, 15, 21];
|
||||
try {
|
||||
const raw = settings.available_vat_rates as string | null;
|
||||
@@ -359,7 +368,7 @@ export default async function companySettingsRoutes(
|
||||
available_currencies,
|
||||
has_logo,
|
||||
has_logo_dark,
|
||||
app_version: pkg.version,
|
||||
app_version: APP_VERSION,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -368,7 +377,6 @@ export default async function companySettingsRoutes(
|
||||
"/system-info",
|
||||
{ preHandler: requirePermission("settings.system") },
|
||||
async (request, reply) => {
|
||||
const pkg = require("../../../package.json") as { version: string };
|
||||
const uptimeSec = process.uptime();
|
||||
const days = Math.floor(uptimeSec / 86400);
|
||||
const hours = Math.floor((uptimeSec % 86400) / 3600);
|
||||
@@ -401,7 +409,7 @@ export default async function companySettingsRoutes(
|
||||
const projectNas = new NasFileManager();
|
||||
|
||||
return success(reply, {
|
||||
app_version: pkg.version,
|
||||
app_version: APP_VERSION,
|
||||
node_version: process.version,
|
||||
platform: `${os.type()} ${os.release()}`,
|
||||
uptime: uptimeStr,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FastifyInstance } from "fastify";
|
||||
import prisma from "../../config/database";
|
||||
import { requireAuth, requirePermission } from "../../middleware/auth";
|
||||
import { requirePermission } from "../../middleware/auth";
|
||||
import { logAudit } from "../../services/audit";
|
||||
import { success, error, parseId, paginated } from "../../utils/response";
|
||||
import { parsePagination, buildPaginationMeta } from "../../utils/pagination";
|
||||
@@ -51,7 +51,10 @@ export default async function customersRoutes(
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: order },
|
||||
// {id} tiebreak: the allow-listed sort columns are non-unique, and
|
||||
// offset pagination over a tied run reorders between page queries
|
||||
// (rows duplicate/vanish across pages) without a total order.
|
||||
orderBy: [{ [sortField]: order }, { id: order }],
|
||||
include: { _count: { select: { quotations: true } } },
|
||||
}),
|
||||
prisma.customers.count({ where }),
|
||||
|
||||
@@ -7,6 +7,7 @@ import { htmlToPdf } from "../../utils/html-to-pdf";
|
||||
import { getRate } from "../../services/exchange-rates";
|
||||
import { localDateStr } from "../../utils/date";
|
||||
import { parseId, success } from "../../utils/response";
|
||||
import { lineNet } from "../../utils/money";
|
||||
import {
|
||||
formatDate,
|
||||
formatNum,
|
||||
@@ -161,6 +162,7 @@ const translations: Record<string, Record<string, string>> = {
|
||||
col_desc: "Popis",
|
||||
col_qty: "Množství",
|
||||
col_unit_price: "Jedn. cena",
|
||||
col_discount: "Sleva",
|
||||
col_price: "Cena",
|
||||
col_vat_pct: "%DPH",
|
||||
col_vat: "DPH",
|
||||
@@ -208,6 +210,7 @@ const translations: Record<string, Record<string, string>> = {
|
||||
col_desc: "Description",
|
||||
col_qty: "Quantity",
|
||||
col_unit_price: "Unit price",
|
||||
col_discount: "Discount",
|
||||
col_price: "Price",
|
||||
col_vat_pct: "VAT%",
|
||||
col_vat: "VAT",
|
||||
@@ -312,6 +315,8 @@ export default async function invoicesPdfRoutes(
|
||||
where: { invoice_id: id },
|
||||
orderBy: [{ position: "asc" }, { id: "asc" }],
|
||||
});
|
||||
// Sleva column is rendered only when at least one item has a discount.
|
||||
const hasDiscount = items.some((it) => Number(it.discount) > 0);
|
||||
|
||||
let customer: Record<string, unknown> | null = null;
|
||||
if (invoice.customer_id) {
|
||||
@@ -362,7 +367,11 @@ export default async function invoicesPdfRoutes(
|
||||
let subtotal = 0;
|
||||
|
||||
for (const item of items) {
|
||||
const lineSubtotal = Number(item.quantity) * Number(item.unit_price);
|
||||
const lineSubtotal = lineNet(
|
||||
Number(item.quantity),
|
||||
Number(item.unit_price),
|
||||
Number(item.discount),
|
||||
);
|
||||
subtotal += lineSubtotal;
|
||||
const rate = Number(item.vat_rate);
|
||||
const key = String(rate);
|
||||
@@ -408,7 +417,22 @@ export default async function invoicesPdfRoutes(
|
||||
const issueDateStr = invoice.issue_date
|
||||
? localDateStr(new Date(invoice.issue_date))
|
||||
: undefined;
|
||||
const cnbRate = isForeign ? await getRate(currency, issueDateStr) : 1.0;
|
||||
// CNB may be unreachable (or the issue date never cached). The rate
|
||||
// only feeds the CZK recap + conversion footnote — degrade by
|
||||
// omitting them (cnbRate = null) rather than failing the whole
|
||||
// render AND the NAS archival (expected condition, logged).
|
||||
let cnbRate: number | null = 1.0;
|
||||
if (isForeign) {
|
||||
try {
|
||||
cnbRate = await getRate(currency, issueDateStr);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`[invoices-pdf] Kurz ČNB nedostupný pro ${currency} — rekapitulace v Kč vynechána`,
|
||||
err,
|
||||
);
|
||||
cnbRate = null;
|
||||
}
|
||||
}
|
||||
const vatRates = [21, 12, 0];
|
||||
const vatRecap: Array<{
|
||||
rate: number;
|
||||
@@ -416,16 +440,18 @@ export default async function invoicesPdfRoutes(
|
||||
vat: number;
|
||||
total: number;
|
||||
}> = [];
|
||||
for (const rate of vatRates) {
|
||||
const key = String(rate);
|
||||
const base = vatSummary[key]?.base ?? 0;
|
||||
const vat = vatSummary[key]?.vat ?? 0;
|
||||
vatRecap.push({
|
||||
rate,
|
||||
base: Math.round(base * cnbRate * 100) / 100,
|
||||
vat: Math.round(vat * cnbRate * 100) / 100,
|
||||
total: Math.round((base + vat) * cnbRate * 100) / 100,
|
||||
});
|
||||
if (cnbRate !== null) {
|
||||
for (const rate of vatRates) {
|
||||
const key = String(rate);
|
||||
const base = vatSummary[key]?.base ?? 0;
|
||||
const vat = vatSummary[key]?.vat ?? 0;
|
||||
vatRecap.push({
|
||||
rate,
|
||||
base: Math.round(base * cnbRate * 100) / 100,
|
||||
vat: Math.round(vat * cnbRate * 100) / 100,
|
||||
total: Math.round((base + vat) * cnbRate * 100) / 100,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const supp = buildAddressLines(settings, true, t);
|
||||
@@ -472,11 +498,16 @@ export default async function invoicesPdfRoutes(
|
||||
.map((item, i) => {
|
||||
const qty = Number(item.quantity);
|
||||
const unitPrice = Number(item.unit_price);
|
||||
const lineSubtotal = qty * unitPrice;
|
||||
const disc = Number(item.discount) || 0;
|
||||
const lineSubtotal = lineNet(qty, unitPrice, disc);
|
||||
const vatRate = Number(item.vat_rate);
|
||||
const lineVat = applyVat ? (lineSubtotal * vatRate) / 100 : 0;
|
||||
const lineTotal = lineSubtotal + lineVat;
|
||||
const qtyDecimals = Math.floor(qty) === qty ? 0 : 2;
|
||||
const discDecimals = Math.floor(disc) === disc ? 0 : 2;
|
||||
const discCell = hasDiscount
|
||||
? `<td class="center">${disc > 0 ? `${formatNum(disc, discDecimals)} %` : "—"}</td>`
|
||||
: "";
|
||||
const subDesc = item.item_description || "";
|
||||
|
||||
return `<tr>
|
||||
@@ -484,6 +515,7 @@ export default async function invoicesPdfRoutes(
|
||||
<td class="desc">${escapeHtml(item.description)}${subDesc ? `<div class="item-subdesc">${escapeHtml(subDesc)}</div>` : ""}</td>
|
||||
<td class="center">${formatNum(qty, qtyDecimals)}${item.unit ? ` / ${escapeHtml(item.unit)}` : ""}</td>
|
||||
<td class="right">${formatNum(unitPrice)}</td>
|
||||
${discCell}
|
||||
<td class="right">${formatNum(lineSubtotal)}</td>
|
||||
<td class="center">${applyVat ? Math.floor(vatRate) : 0}%</td>
|
||||
<td class="right">${formatNum(lineVat)}</td>
|
||||
@@ -503,6 +535,39 @@ export default async function invoicesPdfRoutes(
|
||||
)
|
||||
.join("");
|
||||
|
||||
// CNB rate unavailable → the CZK figures cannot be computed; omit
|
||||
// the whole recap table (the payment QR next to it stays).
|
||||
const recapTableHtml =
|
||||
cnbRate === null
|
||||
? ""
|
||||
: `<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th colspan="4">${escapeHtml(t.vat_recap)}</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>${escapeHtml(t.vat_base)}</th>
|
||||
<th>${escapeHtml(t.vat_rate)}</th>
|
||||
<th>${escapeHtml(t.vat_amount)}</th>
|
||||
<th>${escapeHtml(t.vat_with_total)}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${vatRecapHtml}
|
||||
</tbody>
|
||||
${
|
||||
isForeign
|
||||
? `<tfoot>
|
||||
<tr>
|
||||
<td colspan="4" style="font-size:0.7em; color:#666; padding-top:6px; text-align:left;">
|
||||
${escapeHtml(t.cnb_rate)} ${formatDate(invoice.issue_date)}: 1 ${escapeHtml(currency)} = ${cnbRate.toFixed(3).replace(".", ",")} CZK
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>`
|
||||
: ""
|
||||
}
|
||||
</table>`;
|
||||
|
||||
let vatDetailHtml = "";
|
||||
if (applyVat) {
|
||||
for (const [rate, data] of Object.entries(vatSummary)) {
|
||||
@@ -1002,9 +1067,10 @@ ${indentCSS}
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="center" style="width:3%">${escapeHtml(t.col_no)}</th>
|
||||
<th style="width:36%">${escapeHtml(t.col_desc)}</th>
|
||||
<th style="width:${hasDiscount ? 29 : 36}%">${escapeHtml(t.col_desc)}</th>
|
||||
<th class="center" style="width:10%">${escapeHtml(t.col_qty)}</th>
|
||||
<th class="right" style="width:10%">${escapeHtml(t.col_unit_price)}</th>
|
||||
${hasDiscount ? `<th class="center" style="width:7%">${escapeHtml(t.col_discount)}</th>` : ""}
|
||||
<th class="right" style="width:10%">${escapeHtml(t.col_price)}</th>
|
||||
<th class="center" style="width:5%">${escapeHtml(t.col_vat_pct)}</th>
|
||||
<th class="right" style="width:10%">${escapeHtml(t.col_vat)}</th>
|
||||
@@ -1050,33 +1116,7 @@ ${indentCSS}
|
||||
<div class="qr">
|
||||
${qrSvg}
|
||||
</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th colspan="4">${escapeHtml(t.vat_recap)}</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>${escapeHtml(t.vat_base)}</th>
|
||||
<th>${escapeHtml(t.vat_rate)}</th>
|
||||
<th>${escapeHtml(t.vat_amount)}</th>
|
||||
<th>${escapeHtml(t.vat_with_total)}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${vatRecapHtml}
|
||||
</tbody>
|
||||
${
|
||||
isForeign
|
||||
? `<tfoot>
|
||||
<tr>
|
||||
<td colspan="4" style="font-size:0.7em; color:#666; padding-top:6px; text-align:left;">
|
||||
${escapeHtml(t.cnb_rate)} ${formatDate(invoice.issue_date)}: 1 ${escapeHtml(currency)} = ${cnbRate.toFixed(3).replace(".", ",")} CZK
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>`
|
||||
: ""
|
||||
}
|
||||
</table>
|
||||
${recapTableHtml}
|
||||
</div>
|
||||
|
||||
<!-- Prevzal / razitko -->
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
markOverdueInvoices,
|
||||
listInvoices,
|
||||
getInvoiceListTotals,
|
||||
getNextInvoiceNumberFormatted,
|
||||
getNextInvoiceNumberPreview,
|
||||
getInvoiceStats,
|
||||
getOrderDataForInvoice,
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
ReviewLeaveRequestSchema,
|
||||
} from "../../schemas/leave-requests.schema";
|
||||
import { notifyNewLeaveRequest } from "../../services/leave-notification";
|
||||
import { isHoliday } from "../../utils/czech-holidays";
|
||||
import { localDateStr } from "../../utils/date";
|
||||
|
||||
const VALID_LEAVE_TYPES = ["vacation", "sick", "unpaid"] as const;
|
||||
const VALID_REVIEW_STATUSES = ["approved", "rejected"] as const;
|
||||
@@ -87,12 +89,16 @@ export default async function leaveRequestsRoutes(
|
||||
return error(reply, "Datum do musí být po datu od", 400);
|
||||
}
|
||||
|
||||
// Compute business days server-side (matching PHP logic)
|
||||
// Compute business days server-side — weekends AND Czech public
|
||||
// holidays excluded (mirrors attendance.service createLeave: a weekday
|
||||
// holiday is already paid/free, charging it would double-deduct).
|
||||
let businessDays = 0;
|
||||
const current = new Date(dateFrom);
|
||||
while (current <= dateTo) {
|
||||
const day = current.getDay();
|
||||
if (day !== 0 && day !== 6) businessDays++;
|
||||
if (day !== 0 && day !== 6 && !isHoliday(localDateStr(current))) {
|
||||
businessDays++;
|
||||
}
|
||||
current.setDate(current.getDate() + 1);
|
||||
}
|
||||
|
||||
@@ -185,31 +191,19 @@ export default async function leaveRequestsRoutes(
|
||||
}
|
||||
|
||||
if (status === "approved") {
|
||||
// --- APPROVAL: create attendance records + update leave balance (matching PHP) ---
|
||||
// --- APPROVAL: create attendance records + update leave balance ---
|
||||
const leaveType = existing.leave_type as string;
|
||||
const dateFrom = new Date(existing.date_from);
|
||||
const dateTo = new Date(existing.date_to);
|
||||
|
||||
// For vacation: re-check balance at approval time
|
||||
if (leaveType === "vacation") {
|
||||
const year = dateFrom.getFullYear();
|
||||
const balance = await prisma.leave_balances.findFirst({
|
||||
where: { user_id: existing.user_id, year },
|
||||
});
|
||||
const vacTotal = balance ? Number(balance.vacation_total) : 160;
|
||||
const vacUsed = balance ? Number(balance.vacation_used) : 0;
|
||||
const vacRemaining = vacTotal - vacUsed;
|
||||
const totalHours = Number(existing.total_hours) || 0;
|
||||
if (totalHours > vacRemaining) {
|
||||
return error(
|
||||
reply,
|
||||
`Nedostatek dovolené. Zbývá ${vacRemaining}h, požadováno ${totalHours}h.`,
|
||||
400,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Walk the range once (mirrors attendance.service createLeave):
|
||||
// weekends AND Czech public holidays are skipped — a weekday holiday
|
||||
// is already paid/free, charging it would double-deduct — and hours
|
||||
// accumulate per CALENDAR YEAR so a Dec→Jan request books each day
|
||||
// against its own year's balance. The stored total_hours is NOT
|
||||
// trusted (pre-fix requests carry holiday-inflated totals).
|
||||
let totalBusinessDays = 0;
|
||||
const hoursByYear = new Map<number, number>();
|
||||
const current = new Date(dateFrom);
|
||||
const attendanceCreates: Array<{
|
||||
user_id: number;
|
||||
@@ -221,8 +215,10 @@ export default async function leaveRequestsRoutes(
|
||||
|
||||
while (current <= dateTo) {
|
||||
const dow = current.getDay();
|
||||
if (dow !== 0 && dow !== 6) {
|
||||
if (dow !== 0 && dow !== 6 && !isHoliday(localDateStr(current))) {
|
||||
totalBusinessDays++;
|
||||
const dayYear = current.getFullYear();
|
||||
hoursByYear.set(dayYear, (hoursByYear.get(dayYear) ?? 0) + 8);
|
||||
attendanceCreates.push({
|
||||
user_id: existing.user_id,
|
||||
shift_date: new Date(
|
||||
@@ -245,6 +241,26 @@ export default async function leaveRequestsRoutes(
|
||||
|
||||
const totalHours = totalBusinessDays * 8;
|
||||
|
||||
// For vacation: re-check the balance at approval time — per year,
|
||||
// each against ITS OWN remaining entitlement.
|
||||
if (leaveType === "vacation") {
|
||||
for (const [year, yearHours] of hoursByYear) {
|
||||
const balance = await prisma.leave_balances.findFirst({
|
||||
where: { user_id: existing.user_id, year },
|
||||
});
|
||||
const vacTotal = balance ? Number(balance.vacation_total) : 160;
|
||||
const vacUsed = balance ? Number(balance.vacation_used) : 0;
|
||||
const vacRemaining = vacTotal - vacUsed;
|
||||
if (yearHours > vacRemaining) {
|
||||
return error(
|
||||
reply,
|
||||
`Nedostatek dovolené pro rok ${year}. Zbývá ${vacRemaining}h, požadováno ${yearHours}h.`,
|
||||
400,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Check for duplicate attendance records inside the transaction
|
||||
@@ -264,38 +280,40 @@ export default async function leaveRequestsRoutes(
|
||||
await tx.attendance.createMany({ data: attendanceCreates });
|
||||
}
|
||||
|
||||
// 2. Update leave balance (vacation/sick only — not unpaid)
|
||||
// 2. Update leave balances (vacation/sick only — not unpaid),
|
||||
// each calendar year charged separately.
|
||||
if (leaveType === "vacation" || leaveType === "sick") {
|
||||
const year = dateFrom.getFullYear();
|
||||
const existingBalance = await tx.leave_balances.findFirst({
|
||||
where: { user_id: existing.user_id, year },
|
||||
});
|
||||
for (const [year, yearHours] of hoursByYear) {
|
||||
const existingBalance = await tx.leave_balances.findFirst({
|
||||
where: { user_id: existing.user_id, year },
|
||||
});
|
||||
|
||||
if (existingBalance) {
|
||||
const updateData: Record<string, unknown> = {
|
||||
updated_at: new Date(),
|
||||
};
|
||||
if (leaveType === "vacation") {
|
||||
updateData.vacation_used =
|
||||
Number(existingBalance.vacation_used) + totalHours;
|
||||
if (existingBalance) {
|
||||
const updateData: Record<string, unknown> = {
|
||||
updated_at: new Date(),
|
||||
};
|
||||
if (leaveType === "vacation") {
|
||||
updateData.vacation_used =
|
||||
Number(existingBalance.vacation_used) + yearHours;
|
||||
} else {
|
||||
updateData.sick_used =
|
||||
Number(existingBalance.sick_used) + yearHours;
|
||||
}
|
||||
await tx.leave_balances.update({
|
||||
where: { id: existingBalance.id },
|
||||
data: updateData,
|
||||
});
|
||||
} else {
|
||||
updateData.sick_used =
|
||||
Number(existingBalance.sick_used) + totalHours;
|
||||
await tx.leave_balances.create({
|
||||
data: {
|
||||
user_id: existing.user_id,
|
||||
year,
|
||||
vacation_total: 160,
|
||||
vacation_used: leaveType === "vacation" ? yearHours : 0,
|
||||
sick_used: leaveType === "sick" ? yearHours : 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
await tx.leave_balances.update({
|
||||
where: { id: existingBalance.id },
|
||||
data: updateData,
|
||||
});
|
||||
} else {
|
||||
await tx.leave_balances.create({
|
||||
data: {
|
||||
user_id: existing.user_id,
|
||||
year,
|
||||
vacation_total: 160,
|
||||
vacation_used: leaveType === "vacation" ? totalHours : 0,
|
||||
sick_used: leaveType === "sick" ? totalHours : 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { requirePermission } from "../../middleware/auth";
|
||||
import { nasOffersManager } from "../../services/nas-offers-manager";
|
||||
import { htmlToPdf } from "../../utils/html-to-pdf";
|
||||
import { parseId, success } from "../../utils/response";
|
||||
import { lineNet } from "../../utils/money";
|
||||
import {
|
||||
formatDate,
|
||||
formatNum,
|
||||
@@ -123,6 +124,7 @@ const TRANSLATIONS: Record<string, Record<string, string>> = {
|
||||
description: { EN: "Description", CZ: "Popis" },
|
||||
qty: { EN: "Qty", CZ: "Mn." },
|
||||
unit_price: { EN: "Unit Price", CZ: "Jedn. cena" },
|
||||
discount: { EN: "Discount", CZ: "Sleva" },
|
||||
included: { EN: "Included", CZ: "Zahrnuto" },
|
||||
total: { EN: "Total", CZ: "Celkem" },
|
||||
total_no_vat: { EN: "Total excl. VAT", CZ: "Celkem bez DPH" },
|
||||
@@ -170,9 +172,15 @@ export function renderOfferHtml(
|
||||
let total = 0;
|
||||
for (const item of items) {
|
||||
if (item.is_included_in_total !== false) {
|
||||
total += (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
|
||||
total += lineNet(
|
||||
Number(item.quantity) || 0,
|
||||
Number(item.unit_price) || 0,
|
||||
Number(item.discount),
|
||||
);
|
||||
}
|
||||
}
|
||||
// Sleva column is rendered only when at least one item carries a discount.
|
||||
const hasDiscount = items.some((it) => Number(it.discount) > 0);
|
||||
// Visibility uses the SAME per-language title rule as the render loop plus
|
||||
// a tag-stripped content check (an empty-Quill "<p><br></p>" doesn't count)
|
||||
// — otherwise a section with only the other language's title would count as
|
||||
@@ -217,10 +225,15 @@ export function renderOfferHtml(
|
||||
let itemsHtml = "";
|
||||
items.forEach((item, i) => {
|
||||
const qty = Number(item.quantity) || 0;
|
||||
const lineTotal = qty * (Number(item.unit_price) || 0);
|
||||
const disc = Number(item.discount) || 0;
|
||||
const lineTotal = lineNet(qty, Number(item.unit_price) || 0, disc);
|
||||
// Integers render without decimals; fractional quantities keep 2 decimals
|
||||
// (the old toFixed(0) ROUNDED 1.5 → 2 on the printed document).
|
||||
const qtyDecimals = Math.floor(qty) === qty ? 0 : 2;
|
||||
const discDecimals = Math.floor(disc) === disc ? 0 : 2;
|
||||
const discCell = hasDiscount
|
||||
? `<td class="center">${disc > 0 ? `${formatNum(disc, discDecimals)} %` : "—"}</td>`
|
||||
: "";
|
||||
const subDesc = item.item_description || "";
|
||||
const evenClass = i % 2 === 1 ? ' class="even"' : "";
|
||||
itemsHtml += `<tr${evenClass}>
|
||||
@@ -228,6 +241,7 @@ export function renderOfferHtml(
|
||||
<td class="desc">${escapeHtml(item.description)}${subDesc ? `<div class="item-subdesc">${escapeHtml(subDesc)}</div>` : ""}</td>
|
||||
<td class="center">${formatNum(qty, qtyDecimals)}${(item.unit || "").trim() ? ` / ${escapeHtml((item.unit || "").trim())}` : ""}</td>
|
||||
<td class="right">${formatCurrency(Number(item.unit_price) || 0, currency)}</td>
|
||||
${discCell}
|
||||
<td class="right total-cell">${formatCurrency(lineTotal, currency)}</td>
|
||||
</tr>`;
|
||||
});
|
||||
@@ -621,10 +635,11 @@ ${indentCSS}
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="center" style="width:5%">${escapeHtml(t("no"))}</th>
|
||||
<th style="width:44%">${escapeHtml(t("description"))}</th>
|
||||
<th class="center" style="width:13%">${escapeHtml(t("qty"))}</th>
|
||||
<th class="right" style="width:18%">${escapeHtml(t("unit_price"))}</th>
|
||||
<th class="right" style="width:20%">${escapeHtml(t("total"))}</th>
|
||||
<th style="width:${hasDiscount ? 36 : 44}%">${escapeHtml(t("description"))}</th>
|
||||
<th class="center" style="width:12%">${escapeHtml(t("qty"))}</th>
|
||||
<th class="right" style="width:16%">${escapeHtml(t("unit_price"))}</th>
|
||||
${hasDiscount ? `<th class="center" style="width:9%">${escapeHtml(t("discount"))}</th>` : ""}
|
||||
<th class="right" style="width:18%">${escapeHtml(t("total"))}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
@@ -194,7 +194,7 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
"/categories/:id",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const body = parseBody(UpdatePlanCategorySchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
@@ -218,7 +218,7 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
"/categories/:id",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const result = await deletePlanCategory(id);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
@@ -289,7 +289,7 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
"/entries/:id",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const body = parseBody(UpdatePlanEntrySchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
@@ -321,7 +321,7 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
"/entries/:id",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const force = forceFromQuery(request.query);
|
||||
const result = await deleteEntry(id, request.authData!.userId, force);
|
||||
@@ -373,7 +373,7 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
"/overrides/:id",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const body = parseBody(UpdatePlanOverrideSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
@@ -405,7 +405,7 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
"/overrides/:id",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const force = forceFromQuery(request.query);
|
||||
const result = await deleteOverride(id, request.authData!.userId, force);
|
||||
|
||||
@@ -199,7 +199,7 @@ export default async function projectFilesRoutes(
|
||||
|
||||
const subPath = parsedQuery.data.path || "";
|
||||
const rawFileName = file.filename;
|
||||
const fileName = rawFileName.replace(/[\/\\:*?"<>|]/g, "_");
|
||||
const fileName = rawFileName.replace(/[/\\:*?"<>|]/g, "_");
|
||||
|
||||
const buffer = await file.toBuffer();
|
||||
const err = await fm.uploadFile(
|
||||
|
||||
@@ -89,7 +89,11 @@ export default async function projectsRoutes(
|
||||
|
||||
const result = await createProject(parsed.data);
|
||||
if ("error" in result)
|
||||
return error(reply, result.error, (result as any).status ?? 400);
|
||||
return error(
|
||||
reply,
|
||||
result.error,
|
||||
(result as { status?: number }).status ?? 400,
|
||||
);
|
||||
|
||||
await logAudit({
|
||||
request,
|
||||
@@ -127,7 +131,11 @@ export default async function projectsRoutes(
|
||||
const result = await updateProject(id, parsed.data);
|
||||
if (!result) return error(reply, "Projekt nenalezen", 404);
|
||||
if ("error" in result) {
|
||||
return error(reply, result.error, (result as any).status ?? 400);
|
||||
return error(
|
||||
reply,
|
||||
result.error,
|
||||
(result as { status?: number }).status ?? 400,
|
||||
);
|
||||
}
|
||||
|
||||
await logAudit({
|
||||
@@ -160,7 +168,11 @@ export default async function projectsRoutes(
|
||||
content: parsed.data.content ?? undefined,
|
||||
});
|
||||
if (note && "error" in note) {
|
||||
return error(reply, note.error, (note as any).status ?? 400);
|
||||
return error(
|
||||
reply,
|
||||
note.error,
|
||||
(note as { status?: number }).status ?? 400,
|
||||
);
|
||||
}
|
||||
|
||||
await logAudit({
|
||||
|
||||
@@ -141,7 +141,9 @@ export default async function receivedInvoicesRoutes(
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: order },
|
||||
// {id} tiebreak — non-unique sort keys reorder between page
|
||||
// queries without it (rows duplicate/vanish across pages).
|
||||
orderBy: [{ [sortField]: order }, { id: order }],
|
||||
}),
|
||||
prisma.received_invoices.count({ where }),
|
||||
]);
|
||||
@@ -396,6 +398,19 @@ export default async function receivedInvoicesRoutes(
|
||||
const issueDate = meta.issue_date
|
||||
? new Date(String(meta.issue_date))
|
||||
: null;
|
||||
const dueDate = meta.due_date
|
||||
? new Date(String(meta.due_date))
|
||||
: null;
|
||||
// The schema regex can't catch impossible dates ("2098-99-99") —
|
||||
// an Invalid Date here would derive NaN month/year and fail at
|
||||
// Prisma only AFTER the NAS save (orphaned file). Reject before
|
||||
// any side effect.
|
||||
if (issueDate && isNaN(issueDate.getTime())) {
|
||||
return error(reply, "Neplatné datum vystavení", 400);
|
||||
}
|
||||
if (dueDate && isNaN(dueDate.getTime())) {
|
||||
return error(reply, "Neplatné datum splatnosti", 400);
|
||||
}
|
||||
const invoiceMonth = issueDate
|
||||
? issueDate.getMonth() + 1
|
||||
: Number(meta.month) || now.getMonth() + 1;
|
||||
@@ -432,10 +447,8 @@ export default async function receivedInvoicesRoutes(
|
||||
currency: meta.currency ? String(meta.currency) : "CZK",
|
||||
vat_rate: vatRate,
|
||||
vat_amount: vatAmount,
|
||||
issue_date: meta.issue_date
|
||||
? new Date(String(meta.issue_date))
|
||||
: null,
|
||||
due_date: meta.due_date ? new Date(String(meta.due_date)) : null,
|
||||
issue_date: issueDate,
|
||||
due_date: dueDate,
|
||||
status: "unpaid",
|
||||
notes: meta.notes ? String(meta.notes) : null,
|
||||
uploaded_by: request.authData?.userId,
|
||||
|
||||
@@ -82,7 +82,7 @@ export default async function sessionsRoutes(
|
||||
"/:id",
|
||||
{ preHandler: requireAuth },
|
||||
async (request, reply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
const authData = request.authData!;
|
||||
|
||||
|
||||
@@ -293,7 +293,7 @@ export default async function tripsRoutes(
|
||||
"/last-km/:vehicleId",
|
||||
{ preHandler: requirePermission("trips.manage") },
|
||||
async (request, reply) => {
|
||||
const vehicleId = parseId((request.params as any).vehicleId, reply);
|
||||
const vehicleId = parseId(request.params.vehicleId, reply);
|
||||
if (vehicleId === null) return;
|
||||
|
||||
const [lastTrip, vehicle] = await Promise.all([
|
||||
@@ -373,7 +373,7 @@ export default async function tripsRoutes(
|
||||
"/:id",
|
||||
{ preHandler: requireAnyPermission("trips.manage", "trips.record") },
|
||||
async (request, reply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
const parsed = parseBody(UpdateTripSchema, request.body);
|
||||
if ("error" in parsed) return error(reply, parsed.error, 400);
|
||||
@@ -461,7 +461,7 @@ export default async function tripsRoutes(
|
||||
"/:id",
|
||||
{ preHandler: requireAnyPermission("trips.manage", "trips.record") },
|
||||
async (request, reply) => {
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
const authData = request.authData!;
|
||||
const existing = await prisma.trips.findUnique({ where: { id } });
|
||||
|
||||
@@ -60,6 +60,11 @@ export default async function usersRoutes(
|
||||
if ("error" in parsed) return error(reply, parsed.error, 400);
|
||||
const body = parsed.data;
|
||||
|
||||
// Privilege-escalation guard (mirrors PUT): role assignment is
|
||||
// admin-only. A bare users.create holder could otherwise mint an
|
||||
// account on a high-privilege role the caller itself lacks.
|
||||
const callerIsAdmin = request.authData?.roleName === "admin";
|
||||
|
||||
const result = await createUser(
|
||||
{
|
||||
username: body.username,
|
||||
@@ -67,7 +72,7 @@ export default async function usersRoutes(
|
||||
password: body.password,
|
||||
first_name: body.first_name,
|
||||
last_name: body.last_name,
|
||||
role_id: body.role_id,
|
||||
role_id: callerIsAdmin ? body.role_id : undefined,
|
||||
is_active: body.is_active,
|
||||
},
|
||||
request.authData?.roleName ?? undefined,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { FastifyInstance } from "fastify";
|
||||
import multipart from "@fastify/multipart";
|
||||
import prisma from "../../config/database";
|
||||
import { config } from "../../config/env";
|
||||
import { requireAuth, requirePermission } from "../../middleware/auth";
|
||||
import { requirePermission } from "../../middleware/auth";
|
||||
import { logAudit } from "../../services/audit";
|
||||
import { success, error, parseId, paginated } from "../../utils/response";
|
||||
import { contentDisposition } from "../../utils/content-disposition";
|
||||
@@ -73,6 +73,90 @@ function numFilter(raw: unknown): number | undefined {
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Local-day boundaries for created_at range filters. created_at holds
|
||||
* LOCAL-time instants, so the from-bound is the day's local midnight — a
|
||||
* bare new Date("YYYY-MM-DD") is UTC midnight (01:00/02:00 Prague), which
|
||||
* silently dropped the first morning hours. The to-bound is the NEXT day's
|
||||
* local midnight, exclusive — `lte` against UTC midnight dropped the entire
|
||||
* inclusive end day.
|
||||
*/
|
||||
function localDayStart(dateStr: string): Date {
|
||||
return new Date(`${dateStr}T00:00:00`);
|
||||
}
|
||||
function localDayEndExclusive(dateStr: string): Date {
|
||||
const d = new Date(`${dateStr}T00:00:00`);
|
||||
d.setDate(d.getDate() + 1);
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* FK pre-validation for receipt/issue payloads (mirrors the document
|
||||
* modules): a dangling id would otherwise raise P2003 at Prisma and surface
|
||||
* as a generic 500. Returns a Czech message for a clean 400, or null when
|
||||
* all referenced rows exist.
|
||||
*/
|
||||
async function findMissingLineRef(
|
||||
items: Array<{ item_id: number; location_id?: number | null }>,
|
||||
): Promise<string | null> {
|
||||
for (const line of items) {
|
||||
const item = await prisma.sklad_items.findUnique({
|
||||
where: { id: line.item_id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!item) return `Položka ID ${line.item_id} nenalezena`;
|
||||
if (line.location_id != null) {
|
||||
const location = await prisma.sklad_locations.findUnique({
|
||||
where: { id: line.location_id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!location) return `Lokace ID ${line.location_id} nenalezena`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function findMissingReceiptRef(body: {
|
||||
supplier_id?: number | null;
|
||||
items?: Array<{ item_id: number; location_id?: number | null }>;
|
||||
}): Promise<string | null> {
|
||||
if (body.supplier_id != null) {
|
||||
const supplier = await prisma.sklad_suppliers.findUnique({
|
||||
where: { id: body.supplier_id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!supplier) return "Dodavatel nenalezen";
|
||||
}
|
||||
return findMissingLineRef(body.items ?? []);
|
||||
}
|
||||
|
||||
async function findMissingIssueRef(body: {
|
||||
project_id?: number;
|
||||
items?: Array<{
|
||||
item_id: number;
|
||||
batch_id?: number | null;
|
||||
location_id?: number | null;
|
||||
}>;
|
||||
}): Promise<string | null> {
|
||||
if (body.project_id != null) {
|
||||
const project = await prisma.projects.findUnique({
|
||||
where: { id: body.project_id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!project) return "Projekt nenalezen";
|
||||
}
|
||||
for (const line of body.items ?? []) {
|
||||
if (line.batch_id != null) {
|
||||
const batch = await prisma.sklad_batches.findUnique({
|
||||
where: { id: line.batch_id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!batch) return `Šarže ID ${line.batch_id} nenalezena`;
|
||||
}
|
||||
}
|
||||
return findMissingLineRef(body.items ?? []);
|
||||
}
|
||||
|
||||
// NOTE: this file bundles 8 warehouse sub-entities (~2400 lines). Splitting it
|
||||
// per sub-entity (items/receipts/issues/reservations/inventory/reports) is a
|
||||
// tracked refactor, deferred — see REVIEW_FINDINGS.md.
|
||||
@@ -625,13 +709,22 @@ export default async function warehouseRoutes(
|
||||
"/items",
|
||||
{ preHandler: requirePermission("warehouse.view") },
|
||||
async (request, reply) => {
|
||||
const { page, limit, skip, search } = parsePagination(
|
||||
const { page, limit, skip, order, search } = parsePagination(
|
||||
request.query as Record<string, unknown>,
|
||||
);
|
||||
const query = request.query as Record<string, unknown>;
|
||||
const categoryFilter = query.category_id
|
||||
? Number(query.category_id)
|
||||
: undefined;
|
||||
// Allow-listed DB sort columns (computed columns like total_quantity
|
||||
// can't be ordered server-side); anything else falls back to name.
|
||||
const ITEM_SORT_FIELDS = ["name", "item_number", "created_at"];
|
||||
const sortField = ITEM_SORT_FIELDS.includes(String(query.sort))
|
||||
? String(query.sort)
|
||||
: "name";
|
||||
// Default stays ASC (the route always sorted name asc); parsePagination
|
||||
// defaults to desc, so only honor it when the client sent one.
|
||||
const sortOrder = query.order ? order : "asc";
|
||||
|
||||
const where: Record<string, unknown> = {};
|
||||
if (search || categoryFilter !== undefined) {
|
||||
@@ -659,7 +752,9 @@ export default async function warehouseRoutes(
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { name: "asc" },
|
||||
// {id} tiebreak — name/item_number are non-unique; offset
|
||||
// pagination needs a total order or rows duplicate/vanish.
|
||||
orderBy: [{ [sortField]: sortOrder }, { id: sortOrder }],
|
||||
include: {
|
||||
category: { select: { id: true, name: true } },
|
||||
item_locations: {
|
||||
@@ -1032,10 +1127,14 @@ export default async function warehouseRoutes(
|
||||
where.push({ supplier_id: supplierId });
|
||||
}
|
||||
if (query.date_from) {
|
||||
where.push({ created_at: { gte: new Date(String(query.date_from)) } });
|
||||
where.push({
|
||||
created_at: { gte: localDayStart(String(query.date_from)) },
|
||||
});
|
||||
}
|
||||
if (query.date_to) {
|
||||
where.push({ created_at: { lte: new Date(String(query.date_to)) } });
|
||||
where.push({
|
||||
created_at: { lt: localDayEndExclusive(String(query.date_to)) },
|
||||
});
|
||||
}
|
||||
if (search) {
|
||||
where.push({
|
||||
@@ -1114,6 +1213,9 @@ export default async function warehouseRoutes(
|
||||
const body = parsed.data;
|
||||
const authUserId = request.authData!.userId;
|
||||
|
||||
const missingRef = await findMissingReceiptRef(body);
|
||||
if (missingRef) return error(reply, missingRef, 400);
|
||||
|
||||
const receipt = await prisma.sklad_receipts.create({
|
||||
data: {
|
||||
supplier_id: body.supplier_id ?? null,
|
||||
@@ -1183,6 +1285,9 @@ export default async function warehouseRoutes(
|
||||
return error(reply, "Příjem lze upravit pouze ve stavu DRAFT", 400);
|
||||
}
|
||||
|
||||
const missingRef = await findMissingReceiptRef(body);
|
||||
if (missingRef) return error(reply, missingRef, 400);
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (body.supplier_id !== undefined)
|
||||
updateData.supplier_id = body.supplier_id;
|
||||
@@ -1498,10 +1603,14 @@ export default async function warehouseRoutes(
|
||||
where.push({ project_id: projectId });
|
||||
}
|
||||
if (query.date_from) {
|
||||
where.push({ created_at: { gte: new Date(String(query.date_from)) } });
|
||||
where.push({
|
||||
created_at: { gte: localDayStart(String(query.date_from)) },
|
||||
});
|
||||
}
|
||||
if (query.date_to) {
|
||||
where.push({ created_at: { lte: new Date(String(query.date_to)) } });
|
||||
where.push({
|
||||
created_at: { lt: localDayEndExclusive(String(query.date_to)) },
|
||||
});
|
||||
}
|
||||
if (search) {
|
||||
where.push({
|
||||
@@ -1585,6 +1694,11 @@ export default async function warehouseRoutes(
|
||||
const body = parsed.data;
|
||||
const authUserId = request.authData!.userId;
|
||||
|
||||
// Before FIFO resolution, so a nonexistent item gets "Položka
|
||||
// nenalezena" instead of a misleading insufficient-stock message.
|
||||
const missingRef = await findMissingIssueRef(body);
|
||||
if (missingRef) return error(reply, missingRef, 400);
|
||||
|
||||
// Resolve FIFO batches for items without batch_id
|
||||
const resolvedItems: Array<{
|
||||
item_id: number;
|
||||
@@ -1704,6 +1818,9 @@ export default async function warehouseRoutes(
|
||||
return error(reply, "Výdej lze upravit pouze ve stavu DRAFT", 400);
|
||||
}
|
||||
|
||||
const missingRef = await findMissingIssueRef(body);
|
||||
if (missingRef) return error(reply, missingRef, 400);
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (body.project_id !== undefined)
|
||||
updateData.project_id = body.project_id;
|
||||
@@ -2092,7 +2209,7 @@ export default async function warehouseRoutes(
|
||||
// Build items with auto-filled system_qty and calculated difference
|
||||
const itemsData = await Promise.all(
|
||||
body.items.map(async (item) => {
|
||||
let systemQty = 0;
|
||||
let systemQty: number;
|
||||
|
||||
if (item.location_id != null) {
|
||||
// Get stock at specific location
|
||||
@@ -2201,7 +2318,7 @@ export default async function warehouseRoutes(
|
||||
if (body.items) {
|
||||
itemsData = await Promise.all(
|
||||
body.items.map(async (item) => {
|
||||
let systemQty = 0;
|
||||
let systemQty: number;
|
||||
|
||||
if (item.location_id != null) {
|
||||
const loc = await prisma.sklad_item_locations.findUnique({
|
||||
@@ -2400,12 +2517,12 @@ export default async function warehouseRoutes(
|
||||
}
|
||||
if (query.date_from) {
|
||||
issueWhere.push({
|
||||
created_at: { gte: new Date(String(query.date_from)) },
|
||||
created_at: { gte: localDayStart(String(query.date_from)) },
|
||||
});
|
||||
}
|
||||
if (query.date_to) {
|
||||
issueWhere.push({
|
||||
created_at: { lte: new Date(String(query.date_to)) },
|
||||
created_at: { lt: localDayEndExclusive(String(query.date_to)) },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2491,14 +2608,14 @@ export default async function warehouseRoutes(
|
||||
const issueWhere: Record<string, unknown>[] = [{ status: "CONFIRMED" }];
|
||||
|
||||
if (query.date_from) {
|
||||
const dateFrom = new Date(String(query.date_from));
|
||||
const dateFrom = localDayStart(String(query.date_from));
|
||||
receiptWhere.push({ created_at: { gte: dateFrom } });
|
||||
issueWhere.push({ created_at: { gte: dateFrom } });
|
||||
}
|
||||
if (query.date_to) {
|
||||
const dateTo = new Date(String(query.date_to));
|
||||
receiptWhere.push({ created_at: { lte: dateTo } });
|
||||
issueWhere.push({ created_at: { lte: dateTo } });
|
||||
const dateTo = localDayEndExclusive(String(query.date_to));
|
||||
receiptWhere.push({ created_at: { lt: dateTo } });
|
||||
issueWhere.push({ created_at: { lt: dateTo } });
|
||||
}
|
||||
|
||||
const [receipts, issues] = await Promise.all([
|
||||
|
||||
@@ -27,7 +27,10 @@ export const TotpBackupSchema = z.object({
|
||||
});
|
||||
|
||||
export const TotpEnableSchema = z.object({
|
||||
secret: z.string().min(1).max(255),
|
||||
// The secret is stored AES-256-GCM encrypted (base64 of IV+ciphertext+tag)
|
||||
// in a VarChar(255) column — plaintext over ~164 chars overflows AFTER
|
||||
// encryption. Real TOTP secrets are 16-32 chars; 64 is generous.
|
||||
secret: z.string().min(1).max(64),
|
||||
code: z.string().min(1).max(64),
|
||||
password: z.string().max(200).optional(),
|
||||
current_code: z.string().max(64).optional(),
|
||||
|
||||
@@ -110,6 +110,26 @@ export const isoDateString = z.preprocess(
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/, "Datum musí být ve formátu YYYY-MM-DD"),
|
||||
);
|
||||
|
||||
/**
|
||||
* Nullable/optional variant of isoDateString for edit-form date fields:
|
||||
* "" and null normalize to null (the forms clear date inputs with empty
|
||||
* strings), undefined stays undefined (update semantics: field untouched).
|
||||
* Same lenient trailing-time stripping — a local-midnight datetime written
|
||||
* to a @db.Date column would land a day early (Prisma truncates to the UTC
|
||||
* date part).
|
||||
*/
|
||||
export const nullableIsoDateString = z.preprocess(
|
||||
(v) => {
|
||||
if (v === undefined) return undefined;
|
||||
if (v === null || v === "") return null;
|
||||
return typeof v === "string" ? v.slice(0, 10) : v;
|
||||
},
|
||||
z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/, "Datum musí být ve formátu YYYY-MM-DD")
|
||||
.nullish(),
|
||||
);
|
||||
|
||||
/** HH:MM (24h) time string. Tolerant of a trailing ":ss" seconds component. */
|
||||
export const timeString = z.preprocess(
|
||||
(v) =>
|
||||
|
||||
@@ -4,10 +4,10 @@ export const CreateCustomerSchema = z.object({
|
||||
name: z.string().min(1, "Název zákazníka je povinný").max(255),
|
||||
street: z.string().max(255).nullish(),
|
||||
city: z.string().max(255).nullish(),
|
||||
postal_code: z.string().max(255).nullish(),
|
||||
country: z.string().max(255).nullish(),
|
||||
company_id: z.string().max(255).nullish(),
|
||||
vat_id: z.string().max(255).nullish(),
|
||||
postal_code: z.string().max(20).nullish(),
|
||||
country: z.string().max(100).nullish(),
|
||||
company_id: z.string().max(50).nullish(),
|
||||
vat_id: z.string().max(50).nullish(),
|
||||
custom_fields: z.array(z.unknown()).max(100).optional(),
|
||||
customer_field_order: z.array(z.string()).optional(),
|
||||
});
|
||||
@@ -16,10 +16,10 @@ export const UpdateCustomerSchema = z.object({
|
||||
name: z.string().min(1, "Název zákazníka je povinný").max(255).optional(),
|
||||
street: z.string().max(255).nullish(),
|
||||
city: z.string().max(255).nullish(),
|
||||
postal_code: z.string().max(255).nullish(),
|
||||
country: z.string().max(255).nullish(),
|
||||
company_id: z.string().max(255).nullish(),
|
||||
vat_id: z.string().max(255).nullish(),
|
||||
postal_code: z.string().max(20).nullish(),
|
||||
country: z.string().max(100).nullish(),
|
||||
company_id: z.string().max(50).nullish(),
|
||||
vat_id: z.string().max(50).nullish(),
|
||||
custom_fields: z.array(z.unknown()).max(100).optional(),
|
||||
customer_field_order: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user