Compare commits

...

36 Commits

Author SHA1 Message Date
BOHA
200aa0e1a8 chore(release): v2.4.44 — payroll recap per accountant spec
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 18:00:37 +02:00
BOHA
e3b414d22c fix(attendance): payroll recap per accountant spec; multi-shift day rows; shared computation
Rekapitulace (accountant notes, confirmed by owner 2026-07):
- Odpracováno = all worked hours EXCEPT hours worked on holidays
  (was floor(worked/8)×8 — a 3h day printed as 0h)
- Vč. svátků a přesčasů = ALL worked hours; line2 − line1 = Svátek
  (was worked + vacation − 8h×worked-holidays — could print less than
  actually worked, and vacation inflated it)
- Přesčas = max(0, worked − fond), month-level, never negative
  (was the sub-8h remainder + vacation — printed 3h overtime for a
  3h month, 8h overtime for pure vacation, and −6h when a holiday
  was worked)
- Svátek = hours actually WORKED on holiday dates
  (was 8h per UNworked holiday — opposite meaning)
- So/Ne, Práce v noci, Dovolená, Fond unchanged (verified correct)

Single shared computeMzdaSummary now feeds BOTH the print and the
admin screen (they had drifted: capped vs uncapped holiday adjustment).

Print day table: one row PER RECORD — days with two shifts (real in
prod data) silently dropped all but the last record from the table
while the totals counted them all.

+7 spec tests (accountant's own examples); print snapshot updated to
the new spec values.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 18:00:17 +02:00
BOHA
89656ac2c6 chore(release): v2.4.43 — timezone-proof attendance print
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 16:26:44 +02:00
BOHA
94030230e7 fix(attendance): timezone-proof print dates; overnight-only time prefixes
Two bugs in the attendance admin print (Tisk on Správa docházky):

1. Viewer-timezone date shift: day rows are built from date-only strings
   ('2026-06-01'), which new Date() parses as UTC midnight per spec; local
   formatting then rendered the PREVIOUS day for any viewer west of UTC —
   a June print opened with '31. 5. Neděle' (a May row holding June 1's
   punches) and every weekday name + weekend tint shifted by one. Czech
   viewers were unaffected (UTC+1/+2), US viewers always hit it.
   formatDate / getCzechWeekday / isWeekendDate now parse the calendar day
   from the string parts — identical output in every timezone.

2. Every time cell carried a bogus date prefix ('1.6. 08:00'): the
   overnight-only guard compared the extracted date part against the raw
   wire shift_date ('2026-06-01T02:00:00') — never equal. Now compares
   normalized date parts; the prefix fires only for true overnight punches.

Verified end-to-end against the production June payload; +8 regression
tests (timezone-proof by construction — parts-based, no UTC parse).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 16:26:23 +02:00
BOHA
d859b5bbf7 chore(release): v2.4.42 — status quick actions + bidirectional project-order sync
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 04:34:57 +02:00
BOHA
5683912b76 feat(ui): quick status-action chip menus on offers/orders/projects; ProjectDetail transition buttons
- NEW shared StatusChipMenu: clickable status chip opens a dense menu of valid
  next states; picks confirm via the shared ConfirmDialog (danger variant,
  loading, stays open on failure); plain chip without edit permission;
  row-click-safe (stopPropagation both directions).
- Offers list: draft -> Aktivovat (number assignment noted, PDF archived after
  finalize like the detail); active -> 'Vytvořit objednávku…' (opens the
  existing create-order modal — 'ordered' stays owned by that flow) +
  Zneplatnit; ordered -> Zneplatnit.
- ReceivedOrders list: Zahájit realizaci / Dokončit / Stornovat / Obnovit with
  cascade notes; Czech quote pairs fixed („…“); OrderDetail transition button
  says 'Obnovit' when reopening.
- Projects list + ProjectDetail: status combobox replaced by transition
  buttons (Dokončit/Zrušit/Obnovit projekt) rendered from valid_transitions;
  cascade notes only when a linked order will actually change; save no longer
  carries status; busy states symmetric.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 04:33:58 +02:00
BOHA
3ec512faf1 feat(projects/orders): project status machine + bidirectional project-order sync; order reopen
- projects.service: VALID_TRANSITIONS (aktivni->dokonceny/zruseny,
  terminal->aktivni reopen), tolerant of legacy statuses; getProject returns
  valid_transitions; updateProject validates transitions (invalid_transition
  token -> Czech 400 in the route).
- NEW project->order cascade, transactional with the project update: finishing/
  cancelling a project completes/cancels its linked received order — only while
  the order is still open (never resurrects storno, never cancels completed);
  reopen never cascades. Direct tx write, no service recursion; cascaded order
  change gets its own audit row.
- orders.service: reopen edges (dokoncena/stornovana -> v_realizaci);
  syncProjectStatus is reopen-aware (reopen skips project sync) and returns
  the cascaded projects for per-project audit rows in the route.
- orders.schema: fix phantom 'zrusena' enum token -> canonical 'stornovana'
  (every storno PUT through the route 400ed with a raw English Zod message;
  latent until now because no UI sent it) + route-level regression test.
- NEW project-order-status-sync.test.ts: 15 tests — both cascade directions,
  guards, reopen-no-cascade, legacy tolerance, forward-sync regression.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 04:33:58 +02:00
BOHA
9f9f359acb docs(spec): status quick actions + bidirectional project-order sync
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:49:46 +02:00
BOHA
593dfc356d chore(release): v2.4.41 — UX quick wins (freshness, confirmations, mobile tabs, Odin DnD)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:25:24 +02:00
BOHA
0172c9a442 feat(odin): multi-invoice review scrolls; drag & drop attachments
- Review panel: flex children no longer shrink (flexShrink 0) — with 2+
  extracted invoices the cards kept compressing to fit 35vh, squashing the
  field grids with nothing to scroll; panel now scrolls, maxHeight 40vh.
- Drag & drop onto the chat column: depth-counted dragenter/leave (no
  flicker), Files-only, refused while busy, PDF/image filter with a Czech
  hint toast when nothing usable was dropped, channel-alpha overlay with
  dashed primary border ('Přetáhněte soubory sem'), staged through the same
  path as the paperclip.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:22:26 +02:00
BOHA
81b4cb51e7 fix(trips): reject on-behalf trip creation without trips.manage
POST /trips honored body.user_id for any trips.record holder — impersonation
on create (reads were already scoped). Now an explicit Czech 403 unless the
caller has the manager capability; manager on-behalf flow unchanged. +4 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:22:26 +02:00
BOHA
a274a49e90 fix(ui): project status convention, linked-order chip, diacritics, lazy dashboard
- PROJECT_STATUS added to documentStatus.ts (aktivni=info, dokonceny=success,
  zruseny=error — app convention); Projects/ProjectDetail local maps deleted;
  status Select derives its MenuItems from the shared map.
- ProjectDetail linked-order status now rendered via the received-order map
  (was the project map with zero key overlap → raw DB token).
- Cancelled label unified across received/issued orders in documentStatus.ts.
- 'Chyba pripojeni' → 'Chyba připojení' (Dashboard, AuthContext).
- Dashboard lazy-loaded like every other route — its 7 subcomponents leave
  the Login critical path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:22:26 +02:00
BOHA
9c192e79e7 feat(invoices/orders): confirm before paid, draft PDF gate, debounced search, distinct create labels
- Marking an invoice paid (issued + received lists) now confirms via
  ConfirmDialog with loading guard — was a single unguarded chip click on a
  terminal transition; chips got affordance tooltips.
- Invoices list PDF icon hidden for drafts (no number → /file 404s),
  matching Offers/IssuedOrders.
- Search debounced (300ms) on Invoices/ReceivedInvoices (list + totals).
- Orders tabs create buttons renamed 'Nová vydaná/přijatá objednávka'
  (were identical for two document types); issued empty-state CTA aligned;
  draft delete dialog uses documentNumberLabel.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:22:06 +02:00
BOHA
4d0ec53514 feat(shell): scrollable status tabs, per-page tab titles, skip-to-content, Czech MUI locale
- Shared Tabs: variant=scrollable + auto scroll buttons — the 5 status-filter
  tabs no longer clip unreachable at ~360px (desktop rendering unchanged).
- TitleSync: browser tab shows the active page ('Faktury · BOHA'; ambiguous
  labels qualified with their section, e.g. 'Záznam – Docházka · BOHA');
  index.html fallback now 'BOHA Admin'.
- Skip-to-content link (visually hidden, visible on focus) + id/tabIndex on
  <main> — keyboard users skip the 248px sidebar.
- MUI csCZ locale merged into the theme (kills built-in English strings like
  'No options'); Czech noOptionsText on Customer/Supplier pickers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:22:06 +02:00
BOHA
87e644eef8 fix(freshness): converge invalidation sets; global query-error toast; silent-toggle feedback
- OrderDetail/InvoiceDetail/LeaveRequests mutations now invalidate the same
  domain sets as their list-page twins (orders+offers+projects+invoices /
  +projects / +users+dashboard) — no more stale project/order labels after
  a detail-page action.
- USER_INVALIDATE hoisted to lib/queries/users.ts; DashProfile self-edit now
  refreshes trips/attendance/leave/projects like an admin edit.
- Global QueryCache.onError toast: failed first-loads no longer masquerade as
  empty lists (data-present refetches stay silent; Unauthorized skipped; 4s
  rate limit; meta.suppressGlobalErrorToast opt-out used by offer/issued-order
  detail + the local TOTP QR query).
- Users/Vehicles active-toggle mutations toast on error (was silent revert);
  clickable status chips got affordance tooltips (incl. warehouse parity).
- AuditLog: refetchOnMount always + staleTime 0 (mutations write audit rows
  but nothing invalidates the key); search debounced; dead auditLogOptions
  module removed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:21:50 +02:00
BOHA
6428044624 docs: UX & consistency review (104 verified findings, independently re-verified)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 03:00:51 +02:00
BOHA
67ddfb2d5d chore: gitignore local Claude tooling and personal scratch files
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:23:08 +02:00
BOHA
81293ae543 chore(release): v2.4.40 — optional line items on issued orders
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 22:03:54 +02:00
BOHA
237ebf3ef8 feat(issued-orders): make line items optional (issue by sections alone)
Items are no longer required on issued orders — an order can be issued
purely from its rich-text sections (Obsah).

- DocumentItemsEditor: opt-in allowEmpty prop lets the list go to zero
  rows (default false keeps the offers/invoices at-least-one-item rule).
- IssuedOrderDetail: allowEmpty on the editor; a saved order with no
  items reopens empty (not a blank starter row); submit guard now
  requires at least one item OR a non-empty section, not an item.
- PDF: with no items the billing heading, items table and total row are
  omitted entirely — a sections-only order shows only its Obsah.
- Service: finalize (draft->sent) and create-as-non-draft reject a
  completely blank order (no items AND no sections) with a Czech 400
  (empty_document); drafts may still be saved empty as WIP.
- Tests: sections-only finalize + blank-order rejection + sections-only
  PDF render; existing finalize fixtures given minimal content.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:36:35 +02:00
BOHA
983a1408f1 docs(release): clarify nginx reload is only for nginx config changes, not every deploy
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:44:47 +02:00
BOHA
ae4a51bf7d chore(release): v2.4.39 — per-document custom-field print selection
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:40:16 +02:00
BOHA
fb480d886d fix(documents): gate selected_custom_fields behind editable guard; bound index cap to column width
Addresses review: add selected_custom_fields to offers/issued-orders
NON_STATUS_UPDATE_FIELDS so a non-editable document rejects selection
edits (status-only transitions still pass); tighten Zod cap 200->50 to
stay within VARCHAR(255).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:31:58 +02:00
BOHA
59f555059b fix(documents): include custom-field selection in offer/issued-order unsaved-changes guard
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:22:36 +02:00
BOHA
3d784adf5d feat(documents): per-document custom-field print picker on offer/issued-order/invoice detail
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:20:51 +02:00
BOHA
44cfea22ca feat(documents): shared CustomFieldsPrintPicker + detail query types
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:17:23 +02:00
BOHA
bce0280846 feat(documents): PDF prints only the document's selected company custom fields
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:15:26 +02:00
BOHA
0d9b5e9570 feat(documents): persist & expose selected_custom_fields in services
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:11:10 +02:00
BOHA
2b3266a1cc feat(documents): accept selected_custom_fields in document schemas
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:08:44 +02:00
BOHA
2f084174df feat(documents): selected-custom-fields encode/decode helpers
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:07:35 +02:00
BOHA
5551786da2 feat(documents): add selected_custom_fields column to quotations/issued_orders/invoices
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 20:06:10 +02:00
BOHA
09f8dc63bf docs(plan): per-document custom-field print selection implementation plan
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 19:52:03 +02:00
BOHA
8dec785d13 docs(spec): per-document custom-field print selection (offers/issued orders/invoices)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 19:44:32 +02:00
BOHA
4674ff3389 fix(dashboard): equal-height cards — stretch + fill instead of ragged
The dashboard content grids used alignItems:"start", so cards in a row sized to
their own content (ragged bottoms). Switch to alignItems:"stretch" so each row
shares one height, and make the wrapped cards actually fill the cell:

- DashProfile / DashSessions: motion-div + Card height:100% (the inner card was
  shorter than its stretched cell).
- Right column (Aktivní projekty + Nabídky): cards flex:1 so the stacked pair
  fills the column to match the neighbouring single cards.

CSS-only; no logic change. tsc clean, lint 0, 669 tests pass. Verified live via
Playwright (3-col row cells equal at 607; bottom 2-col cards equal at 257).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 21:34:17 +02:00
BOHA
4bb7de7247 feat(app): detect new deploy and prompt refresh (+ lazy-chunk recovery)
When a new version is deployed, open tabs no longer silently run stale code
until a manual F5.

- Server stamps every response with X-App-Version (src/middleware/version.ts,
  onSend hook in server.ts).
- Client bakes its build version via Vite define (__APP_VERSION__); apiFetch
  compares the header to it (no polling — piggybacks existing traffic) and
  latches a mismatch in a small store (appVersion.ts).
- UpdateBanner: a persistent bottom Snackbar "Je k dispozici nová verze
  aplikace. — Obnovit" → location.reload(). User-initiated, so an in-progress
  form is never interrupted.
- lazyWithReload: every React.lazy page reloads once if its hashed chunk 404s
  after a deploy (sessionStorage-guarded against loops), fixing the "old chunk
  gone" error screen.

Approach chosen after researching current SPA practice (version header + banner
beats polling / a service worker for a non-PWA admin app).

Tests: +4 (server header, client store latch/notify). Full suite 669 pass,
tsc -b clean, lint 0. Verified live via Playwright (header emitted; banner
appears on a simulated mismatch). Detection applies to deploys from the NEXT
release onward (current clients lack the detection code).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 21:19:46 +02:00
BOHA
719d1f2659 feat(documents): per-item Sleva (% discount) on offers + invoices
Adds an optional per-line-item percentage discount ("Sleva") to offers and
issued invoices, on both the detail-page editor and the PDF.

- DB: discount Decimal(5,2) DEFAULT 0 on quotation_items + invoice_items
  (migration 20260613195833_add_item_discount).
- Totals/VAT: new shared lineNet() (qty × price × (1 − discount/100)); offers'
  NET total and invoices' subtotal AND VAT now compute on the discounted net
  (every getBase/enrichQuotation/stats path). Backward compatible: discount 0
  is identical to before.
- Schemas: discount = numberInRange(0,100), default 0; persisted on
  create/update (+ offer duplicate).
- Detail editors: editable "Sleva %" column — offers via DocumentItemsEditor's
  new opt-in showDiscount prop (issued orders unaffected); invoices in their own
  editor. Spinners hidden + 7rem column so "100" is fully visible. Read-only
  invoice view shows the column when any line has a discount.
- PDFs (offers + invoices): conditional "Sleva"/"Discount" column rendered only
  when an item has a discount; line/total/VAT always use the discounted net.

Tests: +16 (money, totals incl. VAT-on-discounted-net, schema range, PDF
column present/absent). Full suite 665 pass, tsc -b clean, lint 0. Editor
verified live via Playwright. Design spec in docs/superpowers/specs/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 20:46:44 +02:00
BOHA
3787cc4dd0 docs(spec): per-item Sleva (% discount) on offers + invoices
Approved design: percentage per line item, reduces net (VAT on discounted
net), conditional PDF column, offers + issued invoices only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 19:56:43 +02:00
98 changed files with 5454 additions and 743 deletions

9
.gitignore vendored
View File

@@ -21,5 +21,14 @@ dist-client/
.claude/worktrees/
.claude/settings.local.json
# Local Claude tooling (personal, not shared)
.claude/commands/
.claude/skills/
.claude/workflows/
CLAUDE-FABLE-5.md
# Personal scratch (planning docs, etc.)
simon/
# Superpowers brainstorm mockups
.superpowers/

407
POSSIBLE_IMPROVEMENTS.md Normal file
View File

@@ -0,0 +1,407 @@
# Possible Improvements — UX & Consistency Review
_A prioritized UX review of boha-app, grounded in 104 verified, code-referenced findings._
> **How this was produced (2026-06-24):** a multi-agent audit fanned out 16 independent
> reviewers across 5 feature domains and 11 cross-cutting UX dimensions (155 raw findings),
> deduplicated them into 118 unique items, then **adversarially re-checked every finding
> against the actual code** — dropping 14 that didn't hold up or contradicted a deliberate
> documented decision (CLAUDE.md). What remains are 104 findings each confirmed in the
> source, with file references kept intact so they can be acted on directly. Read §1§3 for
> the opinion and the plan; §4 is the full catalogue by theme; §5 is suggested sequencing.
>
> **Independently re-verified (2026-06-24):** a second adversarial pass (9 parallel
> verifiers, different model) re-checked all 104 findings against the source:
> **100 confirmed, 4 partial, 0 refuted.** The partials were factual nits (a couple of
> miscounts, one wrong fix target, one mis-cited import), corrected inline in this
> document. The pass also surfaced one new backend finding (trips create authz — see §4.9)
> and upgraded confidence on the AttendanceAdmin and warehouse-models findings.
---
## 1. Executive Summary
boha-app is a **mature, broad, and genuinely well-built** back-office system. The bones are excellent: there is a real component kit (`src/admin/ui/`), shared document modules, a single-source-of-truth status module (`documentStatus.ts`), a global React Query cache with disciplined invalidation conventions, timezone-safe date handling, edit-locking on documents, and an accessibility-aware theme. Most of the "hard" platform work is done and done well. This is not a rescue job — it is a **polish-and-converge job**.
That said, the owner asked the right question. The single dominant theme across these findings is **consistency debt: the app does the same thing several different ways, and the variants disagree in ways the daily user feels.** Almost every cluster below is a story of "module A got it right, module B is an older or forked copy that drifted." The codebase even documents this pattern against itself — `documentStatus.ts` exists _because_ per-page status maps drifted; `useUnsavedChangesGuard` exists _because_ the dirty-check was copy-pasted; CLAUDE.md explicitly says "extend, never fork." The findings show those rules are followed in the newest modules (offers, issued orders) and quietly violated in the older twins (invoices, orders, attendance-admin, projects, warehouse).
Why this matters: the user's mental model breaks at the seams. Marking an invoice paid from the **detail** page leaves a project's order-status label stale, but doing it from the **list** page refreshes it. The "create" button **navigates to a page** on one Orders tab and **opens a modal** on the other. A failed list fetch shows "no records yet" — which can convince a user a customer has zero invoices when the server actually errored. Validation errors appear **inline under the field** on the supplier modal but **as a 4-second toast** on its mirror-image customer modal. None of these is catastrophic alone; collectively they make a strong app feel "not quite finished" and erode trust in what's on screen.
**The five highest-leverage moves, in order:**
1. **Stop showing stale data after writes.** Define one canonical React Query invalidation set per document family and apply it to _both_ list and detail mutations. Today detail-page edits invalidate fewer domains than their list twins (`OrderDetail`, `InvoiceDetail`, `DashProfile`, leave-cancel). Small effort, removes a whole class of "why is this number wrong" confusion. _(Cluster: data-freshness)_
2. **Guard the irreversible actions that currently aren't.** Marking an invoice **"Zaplaceno"** is a single unconfirmed chip click and is _terminal_ — the one truly irreversible document transition with **no** confirm, while every reversible status change has one. Same inversion in the warehouse: **"Potvrdit"** (posts stock) has no confirm but its **undo** does. And the **Aktivní/Neaktivní** chips are secret one-click toggles that fail silently on error. _(Cluster: destructive actions)_
3. **Fix list-page failure and loading states.** No list page reads `isError`, and there is no global `QueryCache.onError`, so failed fetches fall through to the **empty state** — actively misleading. Add a global error toast plus a distinct inline error. _(Cluster: loading/empty/error)_
4. **Make the app usable on a phone.** The shared `Tabs` uses MUI's non-scrolling `variant="standard"`, so the 5 status-filter tabs on Offers/Invoices simply **clip off-screen and become unreachable** at ~360px — a one-prop fix that touches every status filter. Modals never go full-screen on phones. _(Cluster: mobile)_
5. **Converge the shared primitives the app already owns.** Route the forked dirty-guards, status maps, empty states, page headers, save buttons, and PDF openers back through their canonical implementations. This is the structural fix that prevents the other four from re-drifting. _(Cluster: forked modules)_
The rest of this report groups all findings by theme, gives a prioritized action table, and then lists every finding with its file references intact so they can be acted on directly.
---
## 2. Top Themes
### Theme A — Data-freshness drift (the trust killer)
React Query invalidation is the app's nervous system, and CLAUDE.md lays out clear rules ("invalidate every domain that embeds the data"). The newest modules obey; older and raw-`apiFetch` paths don't. **List pages and their own detail pages invalidate different domain sets** because list pages use manual `invalidate` arrays while detail pages use `useApiMutation` arrays, and the two drifted independently. The result is subtle: a value that is correct after editing it one way is stale after editing it the identical other way. Converge on **one named invalidation constant per family** and reuse it on both surfaces. The dashboard already solved the "many domains feed me" case with `refetchOnMount: "always"` — apply the same backstop to the audit log.
### Theme B — Destructive & risky actions are gated by consequence-inverted logic
The pattern across the app is sound — `ConfirmDialog` everywhere — but the gating is **inversely correlated with actual consequence** in the few places it matters most. The _irreversible_ transitions (invoice→paid, warehouse "Potvrdit" posts stock) have **no** guard, while their _reversible_ counterparts (cancel document) get a full danger confirm. Several state changes hide as **chip toggles with no affordance** and **no `onError`**, so a rejected toggle silently reverts with zero feedback. And the "wipe the entire audit log" case uses the same low-key modal as "trim 30-day rows." Converge on: irreversibility → stronger friction, never weaker; every mutating control announces itself and reports its errors.
### Theme C — Forms & save UX speak three dialects
Validation is **inline-under-field** in some forms and **transient toast** in others — and _mirrored screens disagree_ (supplier modal inline vs customer modal toast; trip editor inline vs admin-trip editor toast; received-invoice bulk-review inline vs its single-edit toast). Enter submits page forms but **never** submits a shared-`Modal` form. Save buttons **spin** in document pages but only **swap text** elsewhere, and dual-save warehouse forms can't tell you which action is running. Failed validation never **moves focus** to the bad field. Converge on: inline `<Field error>` for validation, toasts only for transport/server failures, `<form onSubmit>` in the shared Modal, one save affordance, and focus-the-first-error.
### Theme D — Unsaved-work protection is partial and fork-ridden
The shared `useUnsavedChangesGuard` is used by exactly two pages; `OrderDetail` and `InvoiceDetail` **re-implement it inline**, and `ProjectDetail`, `CompanySettings`, all three warehouse forms, and `AttendanceCreate` have **no guard at all** — a refresh discards a 15-line receipt silently. Worse, _every_ guard only catches `beforeunload`, so clicking the in-app **"Zpět"** or a sidebar link — the most common way to leave — discards edits with no prompt (this one needs a router upgrade). And `InvoiceDetail` has **no edit-lock** while its siblings do, so two users can clobber each other's invoice line items.
### Theme E — Loading, empty & error states have no single grammar
Three different loading behaviors for the _same_ "change the month" action (dim / nothing / flash). Empty states built two ways (`<EmptyState>` vs hand-rolled `Box+Typography`). 40 pages **blank the whole page to a centered spinner** (layout shift) instead of keeping chrome; there are **zero** real MUI `<Skeleton>`s despite identifiers literally named `showListSkeleton`. The dashboard hand-rolls its own spinner. And the big one: **failed fetches render as empty**, not as errors.
### Theme F — Navigation & information architecture has thin orientation
Every browser tab reads **"Admin"** (no per-page title), there are no breadcrumbs, the back control is built **four different ways**, and `Received-order` detail sends you back to the **wrong Orders tab**. Master data is scattered across four nav sections; "Zákazníci" lives at the misleading URL `/offers/customers`; `settings.templates` opens the gear then **bounces you to the dashboard**; and there are three different "access denied" experiences. None blocks work, but together they make deep pages feel un-anchored.
### Theme G — Mobile is a second-class citizen in specific, fixable spots
Status-filter tabs **clip and become unreachable** on phones. Modals never go full-screen. Long full-page editors keep **Save only at the top**, so phone users scroll all the way back up to save. Warehouse line-items lose the labeled card-per-row layout the document editor has — worst exactly where shop-floor mobile use is likely. `FilterBar` children mix fixed and growing flex bases, leaving dead space.
### Theme H — Microcopy & localization inconsistency
The goods-receipt module is named **four ways** (Příjmy / Nový příjem / Příjmové doklady / Příjemka) and "Příjmy" also means _financial income_. "Cancelled" is spelled two ways in the same status file. Create verbs split three ways. The busy label has five competing forms plus a `"Chyba pripojeni"` diacritics typo. Autocompletes leak English **"No options"** in an otherwise fully-Czech app. Several prices bypass cs-CZ formatting (period decimals, no currency).
### Theme I — Accessibility gaps in the hot paths
Clickable table rows aren't keyboard-operable (warehouse records literally can't be opened by keyboard). Search boxes are placeholder-only with no accessible name across ~13 pages. The desktop line-item grid is unlabeled while the mobile card is fully labeled. No skip-to-content link, so keyboard users tab the whole sidebar on every navigation.
### Theme J — Bundle & performance
MUI + Emotion sit in the **781 kB entry chunk**, so every patch release busts the cached UI vendor code and daily users re-download ~232 kB gzip of unchanged MUI. The Dashboard and its 7 subcomponents are bundled into the entry chunk and downloaded **on the Login screen**. No route-transition progress bar, no link prefetch.
---
## 3. Prioritized Recommendations
Effort: **S** = hours · **M** = a focused day or two · **L** = multi-day / structural.
### Quick wins — high impact, low effort
| # | Change | Where | Impact | Effort |
| --- | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------ | ------ |
| 1 | Make status-filter `Tabs` scrollable so they stop clipping off-screen on phones | `src/admin/ui/Tabs.tsx:28-49` (one prop fixes all) | High | S |
| 2 | Add a confirm (or undo toast) + hover affordance to the **"mark invoice paid"** chip — the only unguarded irreversible transition | `Invoices.tsx:339-359,550-562`, `ReceivedInvoices.tsx:668-680` | High | S |
| 3 | Converge detail-page invalidation sets onto the list-page (full) sets | `OrderDetail.tsx:162,168,177`; `InvoiceDetail.tsx:1054,1067,1073`; `DashProfile.tsx:225-226`; `LeaveRequests.tsx:90` | Medium | S |
| 4 | Gate the Invoices **list** PDF icon on `invoice_number` so drafts stop dead-ending in a 404 | `Invoices.tsx:616-626` | Medium | S |
| 5 | Point `Received-order` detail Zpět / redirects at `/orders?tab=prijate` | `OrderDetail.tsx:116-121,275-287,397-405` | Medium | S |
| 6 | Add a global `QueryCache.onError` toast so failed fetches stop masquerading as empty | `src/admin/lib/queryClient.ts` | High | S |
| 7 | Debounce search on Invoices / ReceivedInvoices / AuditLog (reuse `useDebounce`) | `Invoices.tsx:282`, `ReceivedInvoices.tsx:250`, `AuditLog.tsx:202` | Medium | S |
| 8 | Add global MUI `csCZ` `localeText` (kills English "No options" everywhere) | `src/admin/ui/MuiProvider.tsx:15`; pickers `CustomerPicker.tsx:49`, `SupplierPicker.tsx:49` | Medium | S |
| 9 | Add `onError` toast to Vehicles/Users active-toggle mutations (silent failure today) | `Vehicles.tsx:146-160`, `Users.tsx:162-171` | Medium | S |
| 10 | Add a per-page `document.title` (`<TitleSync>`) so tabs/bookmarks aren't all "Admin" | `index.html:22`, `AppShell`, `navData.tsx` | Medium | S |
| 11 | Use `PROJECT_STATUS`/`ORDER_STATUS` maps for project + linked-order chips (currently wrong colors / raw DB tokens) | `Projects.tsx:50`, `ProjectDetail.tsx:43,577`, `documentStatus.ts` | Medium | S |
| 12 | Fix `"Chyba pripojeni"` diacritics typo; unify cancelled-label spelling | `Dashboard.tsx:127`, `AuthContext.tsx:256,314`; `documentStatus.ts:49,58` | Low | S |
| 13 | Add a skip-to-content link + `id="main-content"` on `<main>` | `AppShell.tsx:130-145,210-223` | Medium | S |
| 14 | Lazy-load Dashboard so its 7 subcomponents leave the Login critical path | `AdminApp.tsx:14-15`, `Dashboard.tsx:16` | Medium | S |
| 15 | Relabel the two Orders-tab "Vytvořit objednávku" buttons (identical for two doc types) | `Orders.tsx:125,129` | Medium | S |
### High-impact — worth a focused effort
| # | Change | Where | Impact | Effort |
| --- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------ | ------ |
| 16 | Add unsaved-changes guards to the heavy editors that have none; de-fork `OrderDetail`/`InvoiceDetail` onto the shared hook | `ProjectDetail`, `CompanySettings`, `Warehouse*Form`, `AttendanceCreate`; `useUnsavedChangesGuard.ts` | High | M |
| 17 | Render an inline error (distinct from empty) when `isError`, with retry | `usePaginatedQuery.ts:47`, all list pages | High | M |
| 18 | Standardize validation on inline `<Field error>`; fix the mirrored screens that disagree | `WarehouseSuppliers` vs `OffersCustomers`; `Trips` vs `TripsAdmin`; `ReceivedInvoices` bulk vs single | Medium | M |
| 19 | Wrap shared `Modal` in `<form onSubmit>` so Enter submits every dialog | `src/admin/ui/Modal.tsx:84,92` | Medium | M |
| 20 | Route the three forked invoice PDF openers through `useDocumentPdf`/`useDocumentListPdf` | `Invoices.tsx:361`, `InvoiceDetail.tsx:1175`, `ReceivedInvoices.tsx:561` | Medium | M |
| 21 | Replace inline English/technical error strings with `apiErrorMessage(...)` across ~32 pages | `mutations.ts:30-36`; per-page catch blocks | Medium | M |
| 22 | Make `Modal` full-screen on phones; fix leave-modal hardcoded 2-col date grid | `Modal.tsx:67-75`, `Attendance.tsx:1195-1199` | Medium | S |
| 23 | Give warehouse line-items the labeled card-per-row mobile layout the document editor has | `WarehouseIssueForm.tsx:513-567` vs `DocumentItemsEditor.tsx:170-342` | Medium | M |
| 24 | Add keyboard semantics to `DataTable` clickable rows (role/tabindex/Enter-Space) | `DataTable.tsx:285-303,137-161` | Medium | M |
| 25 | Add a "Nová žádost" create action to "Moje žádosti" (lift the leave modal out of Attendance) | `LeaveRequests.tsx:241`, `Attendance.tsx:936,978` | Medium | M |
| 26 | Route hand-rolled headers through `PageHeader`/`headerActionsSx` (~20 pages) so mobile buttons stack | `PageHeader.tsx:19`; `Projects`, `Users`, `Vehicles`, `TripsAdmin`, `AttendanceAdmin`, `Settings`, `CompanySettings` | Medium | M |
| 27 | Confirm before warehouse **"Potvrdit"** / **"Uložit a potvrdit"** (posts stock irreversibly) | `WarehouseReceiptDetail.tsx:354-356`, `WarehouseReceiptForm.tsx:445` | Medium | S |
| 28 | Split `@mui/*`+`@emotion/*`(+quill) into a long-lived `vendor-mui` chunk | `vite.config.ts` | Medium | M |
| 29 | Give list-page search inputs an accessible name + `type="search"` (shared `SearchField`) | `Offers.tsx:787`, `Invoices.tsx:741`, +11 pages | Medium | S |
### Strategic — larger bets
| # | Change | Where | Impact | Effort |
| --- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- | ------ | ------ |
| 30 | Add edit-locking (migration + route trio) to `InvoiceDetail` (and order notes) to stop multi-user clobbering | `invoices.ts`, `orders.ts`, schema; wire `useDocumentLock`/`LockBanner` | High | L |
| 31 | Migrate `InvoiceDetail` off its fork onto shared `DocumentItemsEditor`/`useDocumentPdf`/dirty-guard (add `showVat` flag) | `InvoiceDetail.tsx:241-541`, `DocumentItemsEditor.tsx` | Medium | L |
| 32 | Block dirty in-app navigation (requires `createBrowserRouter`/`RouterProvider` migration, then centralize in the guard) | `main.tsx`, `useUnsavedChangesGuard.ts` | Medium | L |
| 33 | Move `AttendanceAdmin` reads off raw `apiFetch` onto React Query (kills the `setTimeout(300)` refetch dance) | `useAttendanceAdmin.ts:823,871,1057` | Medium | L |
| 34 | Real skeleton/page-shell first paint instead of full-page spinner on 40 pages | `LoadingState.tsx`, list pages; `skeleton-boha` skill exists | Medium | L |
| 35 | Route-transition top progress bar + sidebar link prefetch | `AppShell.tsx:222`, `AdminApp.tsx` | Medium | M |
| 36 | Consolidate duplicated status/label maps into `documentStatus.ts` (warehouse/projects/leave) | `documentStatus.ts`; 6 warehouse files, `Projects`, `Leave*` | Medium | M |
---
## 4. Detailed Findings by Area
### 4.1 Data-freshness — stale data after mutations
- **Detail-page mutations invalidate fewer domains than their list twins.** `OrderDetail` status/notes/delete (`OrderDetail.tsx:162,168,177`) invalidate only `[orders,invoices]` while the `ReceivedOrders` list delete (`ReceivedOrders.tsx:175`) uses `[orders,offers,projects,invoices]`. `InvoiceDetail` save/status/delete (`InvoiceDetail.tsx:1054,1067,1073`) use `[invoices,orders]` while the `Invoices` list adds `projects` (`Invoices.tsx:328,352`). **Why it matters:** marking an invoice paid or changing an order status from the _detail_ page leaves `ProjectDetail`'s `order_status` label (`ProjectDetail.tsx:571`) and the source offer stale until staleTime/refocus. **Fix:** define one canonical set per family (e.g. `[offers,orders,issued-orders,projects,invoices]`) and apply to both surfaces; `OfferDetail`/`Offers` are the consistent reference to copy.
- **Self-profile edit refreshes fewer domains than an admin editing the same user.** `DashProfile` (`DashProfile.tsx:225-226`) invalidates only `[dashboard,users]`, but admin Users edit uses `USER_INVALIDATE=[users,trips,attendance,leave-requests,leave,projects]` (`Users.tsx:117-124`). **Why:** your display name is embedded in trips/attendance/leave/projects (none keyed under `[users]`), so renaming yourself leaves it stale there. **Fix:** export `USER_INVALIDATE` from a shared module and reuse it in `DashProfile`.
- **Cancelling a leave request omits the `[users]` balance invalidation that create/approve include.** Cancel (`LeaveRequests.tsx:90`) invalidates `[leave-requests,leave,attendance]`; create (`Attendance.tsx:305`) and approve/reject (`LeaveApproval.tsx:164,177`) add `users,dashboard`. **Why:** the genuinely-stale gap is `[users]` balance/history when an approved future request is cancelled (the `[dashboard]` part self-heals via `refetchOnMount`). **Fix:** hoist a shared `LEAVE_INVALIDATE` set across all three flows.
- **Audit Log is never invalidated by the mutations that write audit rows.** `logAudit()` runs on every mutation, but `[audit-log]` is invalidated only by plan flows (`usePlanWork.ts:167`) and the page's own cleanup (`AuditLog.tsx:191`). **Why:** recent actions don't appear within the 30s default staleTime. **Fix:** add `refetchOnMount:'always'` (and `staleTime:0`) to the AuditLog page's inline `useQuery` (`AuditLog.tsx:135`), mirroring `dashboardOptions` — don't sprinkle `[audit-log]` into dozens of arrays. _(Verification note: `auditLogOptions` in `auditLog.ts` is dead code — nothing imports it; either delete it or wire the page onto it and put the option there.)_
- **Odin invoice import invalidates only `[invoices]`, not `[suppliers]`/`[company-settings]`.** `OdinChat.tsx:362` vs manual `[invoices,suppliers,company-settings]` (`ReceivedInvoices.tsx:331,341`). **Why:** an Odin import that introduces a new vendor name won't appear in the `[suppliers]`-keyed autocomplete until staleTime expires. **Fix:** use the same set on both paths (they POST to the same endpoint).
- **Received-invoice supplier picker is disjoint from the warehouse/issued-order supplier registry.** Received invoices use a free-text `string[]` under `[suppliers]``/received-invoices/suppliers` (`common.ts:22-28`); issued orders/warehouse use the structured `sklad_suppliers` table (`issued-orders.ts:76`, `warehouse.ts:241`). **Why:** a vendor added in Warehouse→Suppliers never shows when entering a received invoice, and vice-versa — same conceptual entity, two disjoint stores. **Fix:** don't force an FK (keep one-off vendors as quick free-text), but **union** `sklad_suppliers` names into the received-invoice autocomplete source.
### 4.2 Destructive & risky actions — confirmation and undo
- **Marking an invoice "Zaplaceno" is a single unconfirmed chip click — the only irreversible transition with no guard.** In both invoice lists the chip instantly PUTs `status=paid` with no confirm and no undo (`Invoices.tsx:339-359,550-562`, `ReceivedInvoices.tsx:668-680`); for issued invoices "paid" is terminal (detail goes read-only, row undeletable, `InvoiceDetail.tsx:1220-1314`). Every _detail_ page gates status changes behind a `ConfirmDialog`, but this one doesn't, and the chip only differs from a static one by a pointer cursor. **Fix:** route the chip click through a `ConfirmDialog` ("Označit fakturu … jako zaplacenou?") or an undo toast, and add a hover/tooltip affordance.
- **Aktivní/Neaktivní chips are hidden one-click toggles with no affordance, and fail silently.** On Vehicles, Users, Warehouse Locations and Suppliers the `StatusChip` is secretly an `onClick` toggle with no tooltip/label (`Vehicles.tsx:263`, `Users.tsx:288`). Deactivation fires on one click while the less-destructive delete gets a full `ConfirmDialog`. The Vehicles/Users toggle mutations declare only `onSuccess`, **no `onError`** and no try/catch (`Vehicles.tsx:146-160`, `Users.tsx:162-171`), so a rejected toggle gives zero feedback and the chip silently reverts. **Fix:** make activation an explicit labelled control (switch/menu action) with a tooltip; add a deactivation confirm for user/vehicle; add `onError` toasts. (`WarehouseLocations`/`WarehouseSuppliers` already toast via try/catch — copy them.)
- **`ConfirmDialog` in-flight `loading` is applied inconsistently — some dialogs allow duplicate submits.** `IssuedOrderDetail` passes `loading` to both status and delete dialogs (`:958`); `OrderDetail`/`InvoiceDetail` pass it to delete but not status (`OrderDetail.tsx:780-790`, `InvoiceDetail.tsx:2453-2463`); Vehicles delete (`:417-429`), `AttendanceAdmin` delete (raw `apiFetch`, no `isPending`, `useAttendanceAdmin.ts:1293-1320`) and CompanySettings bank delete omit it entirely → a second click fires a duplicate request. **Fix:** pass `loading={mutation.isPending}` to every `ConfirmDialog`; convert `AttendanceAdmin`'s raw delete to `useApiMutation`; standardize on `IssuedOrderDetail`'s keep-open "Zpracovávám…" convention.
- **Irreversible "Potvrdit" (posts stock) has no confirm, while its reversible "Zrušit doklad" undo does.** `WarehouseReceiptDetail.tsx:354-356` commits stock movements on one click; `:508-517` requires a danger confirm to reverse it. Same single-click commit in the form's "Uložit a potvrdit" (`WarehouseReceiptForm.tsx:445`). **Why:** the gating is inverted relative to consequence; a misclick commits stock. **Fix:** add a `ConfirmDialog` before "Potvrdit" (and ideally the form's commit).
- **Cancellation confirms show two near-identical "Zrušit" buttons.** When the confirmed action is itself a cancellation, both the dismiss and the confirm start with "Zrušit" (`WarehouseReceiptDetail.tsx:508-516`, `LeaveRequests.tsx:260-268`) — same leading word, opposite meanings (the buttons do differ visually: contained vs text). **Fix:** relabel the dismiss to "Zpět"/"Ne" via `cancelText` (`ConfirmDialog.tsx:31-33`).
- **Wiping the ENTIRE audit log uses the same low-key modal as trimming old rows.** "Vše" sits in the same dropdown as "30 dní"/"90 dní" and the only warning is a 0.6-opacity caption (`AuditLog.tsx:297-319,207-218`). The backend deliberately requires a special literal to wipe everything (`routes/admin/audit-log.ts:92-109`), but the UI auto-supplies it with no extra friction. **Fix:** when "Vše" is selected, switch to danger styling, show a prominent warning, ideally require typing a confirmation word.
- **Error toasts auto-dismiss after 4s identically to successes, with no history.** `AlertContext.tsx:53-70` defaults every severity to 4000ms; a long Czech validation message vanishes as fast as "Uloženo," with no toast history (`AlertContainer.tsx:20-27`). **Fix:** key the default off severity — error/warning longer or sticky-until-dismissed, success ~4s.
### 4.3 Error & message feedback fidelity
- **Raw English/technical error strings leak into Czech toasts on ~30 pages.** A helper `apiErrorMessage(err, fallback)` converts client-generated English ("Unauthorized", "Failed to fetch", "Invalid JSON response", "Request failed (NNN)") into a Czech fallback (`mutations.ts:30-36,69-84`), but only `OfferDetail`/`IssuedOrderDetail` use it. ~30 pages do `alert.error(e instanceof Error ? e.message : "Chyba připojení")` (`Vehicles.tsx:203`, `OrderDetail.tsx:191`), passing the raw English through on dropped connections / non-JSON 500s / 401s. **Fix:** replace the inline pattern with `apiErrorMessage(e, "<Czech fallback>")` across the ~32 files. **Do not** add a blanket `useApiMutation` default `onError` — pages call `mutateAsync` inside try/catch and also reset local state there, so a default handler would double-toast.
### 4.4 Unsaved-changes & data-loss protection
- **The dirty guard is absent on heavy editors and forked twice.** Shared `useUnsavedChangesGuard` is used only by `OfferDetail`/`IssuedOrderDetail`; `OrderDetail` (`:130-143`) and `InvoiceDetail` (`:942-958`) re-implement `isDirty`+`beforeunload` inline; `ProjectDetail`, `CompanySettings`, `WarehouseIssueForm/ReceiptForm/InventoryForm` and `AttendanceCreate` register **no guard at all** — a refresh discards everything typed. **Fix:** route the two forks through the shared hook and add it to the six unguarded editors.
- **Dirty guards block only tab-close, not in-app navigation.** Every guard registers only `beforeunload` (`useUnsavedChangesGuard.ts:25-33`), which doesn't fire on React-Router navigation — so the in-app "Zpět" or a sidebar link discards edits silently. **Fix (structural):** the app uses classic `<BrowserRouter>` (react-router 6.30.3) where `useBlocker`/`usePrompt` aren't available — this needs a migration to `createBrowserRouter`/`RouterProvider` (or a custom nav-intercept context), then centralize the blocker inside the shared hook.
- **Always-editable page forms offer no explicit Discard.** Modals have "Zrušit" and `WarehouseItemDetail` has an edit/cancel toggle that restores the snapshot (`:247-269`), but `ProjectDetail` (only Uložit+Smazat, `:343`) and `CompanySettings` (only Uložit, `:647`) give no way to abandon edits — you must reload (and they don't even warn). **Fix:** add a "Zrušit změny" button that restores the loaded snapshot from query cache.
- **Invoices have no edit-lock while offers and issued orders do (multi-user clobbering).** `OfferDetail`/`IssuedOrderDetail` acquire a server lock, heartbeat, render `LockBanner` and force read-only when another user holds it; `InvoiceDetail` imports none of it (`:22-88`), so two users can clobber each other's line items (last-save-wins). Same gap for received-order notes on `OrderDetail`. **Fix (structural):** the _client_ pieces exist (`useDocumentLock`+`LockBanner`) but the _server_ trio does **not** — needs a migration adding `locked_by`/`locked_at` to invoices (and orders), a lock/heartbeat/unlock route trio + `locked_by` enrichment in the detail endpoint (mirror `issued-orders.ts:138-245`), then wire the existing hook + banner.
### 4.5 Form validation & submission
- **Validation is inline in some forms, transient toasts in others — and mirrored screens disagree.** Inline `<Field error>` camp: Trips, Users, Vehicles, WarehouseSuppliers, OfferDetail. Toast camp: ProjectDetail, AttendanceCreate, CompanySettings, OffersCustomers, TripsAdmin, ReceivedInvoices-edit. The disagreements: supplier modal inline (`WarehouseSuppliers.tsx:266-270`) vs its mirror customer modal toast (`OffersCustomers.tsx:338-341`); regular trip editor inline `end_km>start_km` (`Trips.tsx:294-300`) vs admin trip editor toast (`TripsAdmin.tsx:485-490`); received-invoice bulk-review inline per-row (`:431-446`) vs single-edit toast (`:508-519`). **Fix:** standardize on inline `<Field error>`; reserve toasts for server/transport failures.
- **Enter submits page forms but never any shared-Modal form.** `Modal` renders children in `DialogContent` with an `onClick` button (default `type=button`) and no surrounding `<form>` (`Modal.tsx:84,92`), so Enter never submits a modal. `OfferDetail` even hand-rolled an `onKeyDown` Enter workaround (`:1059-1061`). **Fix:** wrap `DialogContent`+`DialogActions` in `<form onSubmit>`, make the primary action `type=submit`, mark secondary/in-content buttons `type=button`, and remove the workaround.
- **Failed validation doesn't move focus to the first invalid field nor announce to AT.** Handlers just `setErrors` and return (`Vehicles.tsx:192-197`); the `Field` error is a plain caption wired via `aria-describedby`/`aria-invalid`, not `aria-live`/`role=alert` (`Field.tsx:81-89`). In a long modal the error can be off-screen. **Fix:** after `setErrors`, focus+`scrollIntoView` the first errored field and render the inline error with `role=alert`; centralize in `Field.tsx`/`Modal.tsx`.
- **Required-asterisk marking is inconsistent with what's validated; DateField/TimeField can't show an error border.** `Field` paints the asterisk only when `required` is passed (`Field.tsx:74`), but it's applied unevenly: `WarehouseIssueForm` validates Projekt-required with no asterisk (`:474` vs `:328-329`); `ProjectDetail` validates Název-required with no asterisk (`:377` vs `:192`); `DateField`/`TimeField` take no `error` prop so a failed required date only reddens helper text, not the border. **Fix:** make `required` the single source of truth (drives asterisk + ideally validation); thread an `error` prop through `DateField`/`TimeField`.
- **Save-button feedback differs (spinner vs text swap); dual-save warehouse forms don't show which action is running.** Document pages render a `CircularProgress` and track `savingAction` so only the clicked button spins (`OfferDetail.tsx:764`); most other forms just swap to text (`ProjectDetail.tsx:346`). On `WarehouseIssueForm` both save buttons swap to identical "Ukládání..." and disable (`:455-465`) — you can't tell which is in flight. **Fix:** adopt one affordance app-wide (spinner+disabled with per-action targeting); spin only the clicked warehouse action.
- **Note typed in the create-project modal is saved to the legacy column and shown as non-editable.** The "Přidat projekt" modal's Poznámka writes `projects.notes` (`Projects.tsx:164`, `projects.service.ts:222`), but `ProjectDetail` renders that column read-only under "Starší poznámka (před zavedením systému)" (`:477,491`). So a note typed at creation is instantly mislabeled as legacy and uneditable, while the real editable `project_notes` system lives only on the detail page. **Fix:** drop the Poznámka field from the create modal, or route the create-time note through `createProjectNote`.
### 4.6 Loading, empty & error states
- **Failed list fetches silently render the empty state.** `usePaginatedQuery` exposes `isError`/`error` (`:47-48`) but no list page reads them, and `queryClient.ts` has no `QueryCache.onError`. So a 500/network drop falls through to the `DataTable` empty slot — Projects shows "Zatím nejsou žádné projekty" (`:480`). Detail pages handle errors loudly; `WarehouseReports.tsx:350` shows an inline `<Alert severity=error>`. **Fix:** add a `QueryCache.onError` toast and/or render an inline error distinct from empty when `isError`, with retry wired to `refetch`.
- **Empty states built two ways, and clickable-CTA vs text-only split.** Shared `<EmptyState>` is used by document/warehouse lists, but Projects/Vehicles/Users hand-roll `Box(textAlign,py:6)+Typography+Button` (`Projects.tsx:471/480`, `Vehicles.tsx:323`, `Users.tsx:350`), reinventing the `action` prop. Offers renders a clickable "Vytvořit první nabídku" (`:835`) while Invoices/ReceivedInvoices only name the button in description text (`Invoices.tsx:770`). **Fix:** migrate hand-rolled empties to `<EmptyState title description action>` and standardize the clickable-create-CTA convention.
- **Empty-state microcopy is inconsistent** (fragments vs sentences, trailing-period split, three filtered-empty phrasings, 2nd person). Fragments with no period (`AuditLog.tsx:368`, `WarehouseReports.tsx:223,364`) vs full sentences (`AttendanceHistory.tsx:653`). Filtered-empty worded three ways: "neodpovídají filtru" (`Offers.tsx:827`) / "neodpovídají filtru." (`Projects.tsx:473`) / "neodpovídají hledání." (`ReceivedInvoices.tsx:859`). Nothing-yet mixes "Zatím nejsou žádné X." with 2nd-person "Zatím nemáte žádné žádosti" (`LeaveRequests.tsx:253`). **Fix:** adopt one canonical filtered-empty string, one unfiltered-empty string, one trailing-period rule.
- **Changing a month/filter gives three different loading behaviors.** Document/warehouse lists dim the card via `isFetching` opacity (`Offers.tsx:815`). `TripsHistory`/`TripsAdmin` keep stale data with NO feedback (`:304-306`/`:810-812`). `AttendanceHistory` uses plain `useQuery` with no `placeholderData`, so a month change flips `isPending` and swaps the whole table for a centered spinner (`:523,646`). **Fix:** standardize on the `isFetching` card-dim; give Trips screens the dim and `AttendanceHistory` `keepPreviousData`.
- **No real skeletons; 40 list pages blank the whole page to a centered spinner (layout shift); "skeleton" identifiers are misnamed.** The only first-paint affordance is `LoadingState` (centered spinner, `LoadingState.tsx:10-22`); 40 pages early-return it before rendering chrome (`Projects.tsx:267`, `Offers.tsx:492`), so title/tabs/filter bar vanish then snap in. There are zero MUI `<Skeleton>`s despite identifiers like `showListSkeleton` (`ReceivedInvoices.tsx:357`). **Fix:** render `PageHeader`+`FilterBar` immediately and confine the spinner (or a real DataTable skeleton — the `skeleton-boha` skill exists) to the table area; at minimum rename the misleading identifiers.
- **Redundant sequential/stacked spinners.** First visit to a lazy section shows the Suspense fallback spinner (chunk download, `AdminApp.tsx:112`), then the page's own `isPending` shows a SECOND centered spinner. Separately `ReceivedInvoices` never early-returns: `renderKpi` shows `<LoadingState/>` (`:752`) AND the list shows one (`:846`) — two stacked spinners on cold load, where sibling `Invoices` shows one. **Fix:** render a single unified loading state per page (have lazy pages supply their own shell as the Suspense fallback).
- **Dashboard hand-rolls its loading spinner and mixes empty-state styles.** `Dashboard.tsx:313-316` and `DashSessions.tsx:161-164` inline `Box+CircularProgress` (different padding/size, no aria-label) vs the shared `<LoadingState/>`. `DashTodayPlan`/`DashSessions` hand-roll Typography empties while `DashActivityFeed`/`DashAttendanceToday` use `<EmptyState>`. On the most-visited page. **Fix:** use `<LoadingState/>` and standardize card empties on `<EmptyState>`.
- **Profile, 2FA and active sessions are gated behind the heavy dashboard aggregate query.** `DashProfile` and `DashSessions` render only inside `{!dashLoading && (...)}` (`Dashboard.tsx:505`), where `dashLoading` is the multi-domain aggregate (attendance+offers+invoices+orders+projects+leave). Neither block depends on that data — `DashProfile`'s 2FA comes from `totpStatusOptions`, `DashSessions` has its own query (`:74`). **Fix:** render `DashProfile`/`DashSessions` independently; gate only the data-dependent cards.
- **Autocomplete pickers show English "No options."** `MuiProvider` sets only the date-picker locale, no global `csCZ` `localeText` (`:15-22`); `CustomerPicker.tsx:49`/`SupplierPicker.tsx:49` omit `noOptionsText`, so empty search shows MUI's built-in English. `ItemPicker.tsx:61` correctly sets "Žádné položky." **Fix:** add MUI `csCZ` component `localeText` (fixes every Autocomplete/pagination at once) or at minimum `noOptionsText` on the two pickers.
### 4.7 List-page consistency
- **Invoices/ReceivedInvoices/AuditLog search fires a query per keystroke (no debounce).** Offers/IssuedOrders/ReceivedOrders/Projects/Warehouse use `useDebounce(value,300)`, but `Invoices.tsx:282`, `ReceivedInvoices.tsx:250` and `AuditLog.tsx:202` feed the raw value into the query key — laggier and hammering the API on the busiest financial screens. **Fix:** wrap in `useDebounce` (or a shared `SearchField`).
- **DataTable `onRowClick` rows aren't keyboard-operable; row-click only exists on warehouse lists.** Warehouse Items/Issues/Inventory/Receipts open via clicking the row (their _only_ entry), but Offers/Invoices/Orders/Projects/Users/Vehicles don't set `onRowClick`. Worse, the clickable `TableRow` has no `tabIndex`/`role`/`onKeyDown` (`DataTable.tsx:285-303,137-161`), so a keyboard user **cannot** open a warehouse record. `OdinSidebar` already has the correct pattern (`:126-140`). **Fix:** add `role="button"`, `tabIndex=0`, Enter/Space handling when `onRowClick` is set; then pick one row convention.
- **Column sorting absent on warehouse-document, audit-log and trips tables that look sortable.** `DataTable` renders sort headers only when columns carry `sortKey` and the page wires `onSort`. Offers/Invoices/Orders/Projects/WarehouseItems do; `WarehouseIssues.tsx:258`, `AuditLog.tsx:364`, `TripsAdmin.tsx:815` and WarehouseReceipts don't — you can't reorder warehouse docs by date/status nor the audit log by user, with no cue distinguishing a sortable header from a dead one. **Fix:** wire `useTableSort`+`sortKey`+`onSort` into the large paginated tables.
- **Sibling Order tabs disagree on the "all" status label.** `IssuedOrders` uses "Všechny" (`:60`), `ReceivedOrders` "Všechny stavy" (`:54`) under the same parent Orders tabs. **Fix:** unify the label (don't force the Tabs-vs-Select control change — IssuedOrders deliberately keeps a Select).
- **Filter baseline diverges: search/date/reset missing where needed.** WarehouseIssues/Receipts have search+status+date-range+reset; `WarehouseInventory.tsx:149` has only a status dropdown (no search despite `session_number`); `WarehouseReservations.tsx:354` has no text search or date filter; `AuditLog.tsx:321` (5 filters) and `TripsAdmin.tsx:734` (3 filters) have **no reset**. **Fix:** standardize a list-filter baseline; add the missing search/date/reset.
- **Offers/IssuedOrders filter by customer/supplier but the Invoices list cannot.** Offers has a customer Select (`:797-812`), IssuedOrders a supplier Select (`:400-415`), but the equally customer-centric Invoices list offers only free-text search (`:739-751`). **Fix:** add a customer Select (load via `offerCustomersOptions`, wire `customer_id` into list+totals; may need a small backend add).
- **Count subtitle missing on Projects/Users/Vehicles/Customers and the Přijaté tab; count copy splits `czechPlural` vs hand-rolled ternary.** Projects/Users/Vehicles show a bare title (`Projects.tsx:427`, `Users.tsx:338`, `Vehicles.tsx:311`), Customers a static description (`:492`), and Vydané shows a count line but Přijaté doesn't. The plural is hand-rolled five times (`WarehouseIssues.tsx:112-114`) where `czechPlural()` exists (`formatters.ts:69`). **Fix:** add a result-count subtitle via `PageHeader`; replace the hand-rolled ternaries with `czechPlural()`.
- **Many pages hand-roll the title bar instead of `PageHeader`, so multi-button headers wrap raggedly on mobile.** `PageHeader`'s `headerActionsSx` makes header buttons stack full-width on phones (`PageHeader.tsx:19-30`), but ~20 pages hand-roll `Box+Typography h4 + raw action Box` (Projects, Users, Vehicles, TripsAdmin, Attendance, AttendanceAdmin, Settings, CompanySettings). The multi-button ones (AttendanceAdmin Tisk/Vyplnit/Přidat `:179-198`; TripsAdmin Tisk/Vozidla `:699-731`) wrap into a ragged half-width grid on phones. **Fix:** route through `<PageHeader>` or wrap the action Box in `headerActionsSx`.
- **Three forked invoice PDF openers → inconsistent feedback and different error copy.** Shared `useDocumentListPdf`/`useDocumentPdf` pre-opens the tab, shows a per-row spinner, guards double-clicks, handles 401 and revokes the blob URL (`useDocumentPdf.ts:37-86`); Offers/IssuedOrders use it. But Invoices reimplements it inline (`:361`), ReceivedInvoices reimplements with **no** loading state (`:561`), and InvoiceDetail forks its own (`:1175`). Same failure yields three different sentences. **Fix:** route all three through the shared hook (make the error string a parameter — received-invoice `openFile` streams a stored upload, not a generated PDF).
- **Invoices LIST shows a PDF button on draft invoices, dead-ending in a 404.** Offers/IssuedOrders hide the PDF icon for drafts and InvoiceDetail's own header hides it on drafts (`:1890`), but the Invoices list renders it for every invoice gated only on permission (`:616-626`). **Fix:** gate on `inv.invoice_number` too, matching `Offers.tsx:660`/`IssuedOrders.tsx:303`.
- **Customers and Suppliers directories use opposite data/search/pagination models.** Built as mirrors, but `OffersCustomers` fetches the entire list once and filters client-side with no debounce/pagination (`:159,380`), while `WarehouseSuppliers` is server-paginated, debounced, page-sized with real Pagination (`:139,449`). **Fix:** align Customers on the Suppliers model (server pagination/search), preserving instant responsiveness via `keepPreviousData`/quick debounce.
### 4.8 Navigation & information architecture
- **Received-order detail returns you to the wrong Orders tab.** Received orders live under Orders→"Přijaté", but `OrderDetail`'s Zpět/post-delete/fetch-error redirects all go to `/orders` with no tab, and Orders defaults to "vydane" (`Orders.tsx:78-79`) — so you land on the issued-orders list (a different doc type). IssuedOrderDetail does it right with `/orders?tab=vydane`. **Fix:** point `OrderDetail`'s links (`:116,280,399`) at `/orders?tab=prijate`.
- **The "Zpět" back control is built four different ways.** No shared back primitive: document detail puts a labeled outlined Zpět on the LEFT (`OfferDetail.tsx:643`); warehouse detail puts it on the RIGHT inside PageHeader (`WarehouseItemDetail.tsx:372`); warehouse forms use an icon-only IconButton on the left (`WarehouseReceiptForm.tsx:423`); `AttendanceCreate` uses a text "← Zpět na správu" on the right (`:173`). All hardcode the list route. **Fix:** add an optional `back={{to,label}}`/`onBack` prop to `PageHeader` rendering one canonical left-aligned icon+label control.
- **No per-page browser title — every tab/bookmark/history entry reads "Admin."** `index.html:22` hardcodes `<title>Admin</title>` and nothing updates it (zero `document.title` refs). With multiple tabs open (common here), the tab strip/history/bookmarks all read "Admin." **Fix:** add a `<TitleSync>` setting `document.title` per route from `navData.tsx` labels (`+ " · BOHA"`).
- **No route breadcrumbs on deep detail/form pages.** Deep destinations (`/warehouse/items/:id`, `/warehouse/receipts/:id/edit`, `/orders/issued/:id`) give only one back link to a single hardcoded list, with no "Sklad Položky <item>" trail. Combined with the missing title, deep-page orientation is thin. **Fix:** add a lightweight section list record breadcrumb derived from route + `navData` metadata.
- **`settings.templates` gates the Nastavení nav item but Settings bounces such users to the dashboard.** The gear shows if the user holds any of five permissions including `settings.templates`, but `canAccessSettings` checks only roles/company/system/banking and `Navigate`-to-`/` otherwise (`Settings.tsx:199-200,421-423`). So a templates-only user sees the gear, clicks, and is teleported away. Meanwhile the offer-templates editor (`/offers/templates`, `OffersTemplates.tsx:137`) has **no** nav entry — only a "Šablony" button buried in the Offers header (`Offers.tsx:750`). **Fix:** drop `settings.templates` from the Nastavení gate (`navData.tsx:486-492`) and give the templates editor a discoverable home.
- **Three different "access denied" experiences.** ~40 pages render the polished `<Forbidden/>` (403 + explanation + "Zpět na Dashboard"); Settings silently `Navigate`-to-`/` (`:421-423`); Odin shows a bare unstyled line of text (`Odin.tsx:9-17`). **Fix:** standardize on `<Forbidden/>` everywhere.
- **"Zákazníci" master data sits under the misleading URL `/offers/customers`.** Customers are a top-level entity referenced by offers, orders and invoices, yet the route implies a sub-resource of offers — visible in code as the `matchExclude:['/offers/customers','/offers/templates']` hack the Nabídky nav item needs (`navData.tsx:250`). **Fix:** move customers to a top-level `/customers` (redirect from the old URL), removing the hack.
- **Master-data lists are scattered across four nav sections with no cross-links.** Zákazníci under Administrativa, Dodavatelé under Sklad, Vozidla under Kniha jízd, Uživatelé under Systém (`navData.tsx:226,297,448,470`). Salient consequence: issued orders (Administrativa) pull suppliers from `sklad_suppliers` (Sklad), so fixing a supplier means jumping to Sklad. **Fix:** at minimum add cross-links (e.g. "spravovat dodavatele" from the issued-order supplier picker → `/warehouse/suppliers`).
- **Sklad nav is a flat 10-item list mixing daily ops with one-time config.** Ten ungrouped items (`navData.tsx:314-463`) intermix `warehouse.operate` daily drivers with rarely-touched `warehouse.manage` config (Kategorie/Lokace/Dodavatelé). **Fix:** split into operations vs "nastavení skladu" subgroups (or move the three config screens behind one entry).
- **One "Vytvořit objednávku" button navigates to a page on one tab and opens a modal on the other.** On Objednávky: Vydané routes to `/orders/issued/new`, Přijaté opens a modal (`Orders.tsx:119-132`, `ReceivedOrders.tsx:606`). Across modules, offers/invoices/issued orders use routed full-page forms while received orders create in a modal. **Fix:** pick one pattern per tier or split into two distinct labelled actions.
- **No skip-to-content link — keyboard users tab the whole sidebar on every page.** A permanent 248px sidebar with many links renders before `<main>` (`AppShell.tsx:130-145,210-223`), with no skip link and no id on `<main>`. **Fix:** add a visually-hidden "Přeskočit na obsah" link (visible on focus) targeting `id="main-content"`.
### 4.9 Discoverability & workflow friction
- **"Moje žádosti" has no create action.** Its header has no actions and its empty state literally instructs filing on the Docházka page (`LeaveRequests.tsx:241,254`); the only way to open the leave form is a button buried on the punch screen (`Attendance.tsx:936,978`). **Fix:** add a "Nová žádost" button to `LeaveRequests` opening the same modal; lift the modal into a shared component.
- **Dashboard "Vaše dnešní zařazení" card shows the project as plain text — every other dash card links onward.** `DashTodayPlan` renders `projectLabel` as plain text (`:69`) while other cards link "Vše →"/"Detail →." **Fix:** wrap `projectLabel` in a `RouterLink` to `/projects/:id` (id is already in `TodayPlan`); optionally add a "Plán prací →" header button.
- **Issue detail shows the consumed reservation as a raw "ID: n" database identifier** (`WarehouseIssueDetail.tsx:204`), unlike the project reference beside it (a real link). **Fix:** at minimum render "R{id}" to match `ReservationPicker`'s own label (`:65`).
- **`ReservationPicker` is dead code — a manual Výdejka can't draw down an existing reservation.** A ready-made picker exists (`ReservationPicker.tsx:14`) but is imported nowhere; the issue form only sets `reservation_id` from router prefill (`WarehouseIssueForm.tsx:183`). **Fix:** render it in the issue-form line (gated on item_id+project_id, mirroring `BatchSelect`) — or delete the unused component.
- **Audit log surfaces only the one-line description — the stored old/new values are on the wire but never shown.** `audit_logs` stores `old_values`/`new_values` and the route returns full rows (`routes/admin/audit-log.ts:64-74`), but the page's row type omits them and rows aren't expandable (`AuditLog.tsx:97-105,229-275`). The most valuable part of an audit trail is invisible. **Fix:** add the fields to the type and open a detail modal rendering old→new.
- **Odin's empty state never hints it can query real system data.** The landing hero only says "Zeptejte se na cokoli, nebo přiložte fakturu…" (`OdinThread.tsx:82-149`), giving no hint Odin can query invoices/offers/orders/projects/warehouse via its read-only tools. **Fix:** add 3-4 clickable example-prompt chips that prefill the composer (`OdinChat.tsx:218-219`).
- **Keyboard shortcuts ship undiscoverable; `ShortcutsHelp` is a permanent no-op.** `ShortcutsHelp` is mounted but returns null (`:1-7`, `AppShell.tsx:226`), while Ctrl+Enter (note save), Enter (Odin send), Enter (plan category) ship with no help. **Fix:** build the "?"-opens-cheat-sheet overlay, or as a cheap first step add `title` hints (copy `OdinComposer`'s `title="Odeslat (Enter)"` onto `NoteCard`'s Ctrl+Enter).
- **Plan grid resets to the current week on every remount.** `usePlanWork` inits view/anchor to `new Date()` with no persistence (`:112-113`), so leaving and returning to `/plan` loses your scroll position. **Fix:** persist view+anchor (URL query or localStorage).
- **"Zpět na správu" / post-save links pass `?month=YYYY-MM` but AttendanceAdmin ignores it.** `AttendanceCreate` (`:141`) and `AttendanceLocation` (`:211`) link to `/attendance/admin?month=…`, but `useAttendanceAdmin` never reads the URL (hard-inits month to current). **Fix:** seed the initial month from `useSearchParams()` and keep it synced.
- **Receipt/Issue details never show a document-level total.** They compute per-line "Celkem" but the `DataTable` has no footer/sum (`WarehouseReceiptDetail.tsx:250`, `WarehouseIssueDetail.tsx:182`); forms show no running total. Every other money-bearing document leads with a prominent total. **Fix:** add a summary line (sum of qty×unit_price via `formatCurrency`) under the Položky table and a live running total in the forms.
- **Inventory form only creates a draft; Receipt/Issue forms offer "Uložit a potvrdit" in one action.** `WarehouseInventoryForm` offers only "Vytvořit inventuru" (`:204`); to post you must go to the detail and click "Potvrdit inventuru" (`:209`). **Fix:** add a "Vytvořit a potvrdit" button (the form already collects `actual_qty`), OR surface a hint explaining the deliberate two-step variance-review flow.
- **Trips admin can't enter a trip on behalf of a driver, though attendance admin can create for any employee.** `TripsAdmin` offers only Tisk + a Vozidla link (`:710`), no "add trip," and its edit modal has no driver picker. The `/trips` POST already accepts `body.user_id` (`trips.ts:341`). **Fix:** add an "Přidat jízdu" action with a driver selector, mirroring `AttendanceAdmin`.
- **⚠ Found during verification (backend, not UX): `POST /trips` accepts `body.user_id` without a `trips.manage` check.** Any user holding only `trips.record` can create a trip attributed to another user's id (`src/routes/admin/trips.ts:341`, `trips.schema.ts:13`) — reads are correctly scoped (`buildTripsWhere` limits non-managers to their own trips) but the create path is not. Minor impersonation-on-create authz gap. **Fix:** ignore `body.user_id` (force `authData.userId`) unless the caller holds `trips.manage`.
- **Personal Trips "Záznam" shows company-wide trips/stats for managers.** Unlike "Moje historie" (filters by `userId`), the personal Trips page calls `tripListOptions`/`tripStatsOptions` with no `userId` and renders a "Řidič" column (`Trips.tsx:166,359`) — surfacing all drivers' trips and company-wide totals, unlike the strictly-personal attendance punch screen. **Fix:** pass `userId` (matching `TripsHistory`), or relabel/drop the Řidič column. Keep list and stats on one scope.
### 4.10 Forked/duplicated shared modules & code drift
- **`InvoiceDetail` forks the shared document editor (and drops the item-description maxLength cap).** Offers/issued orders compose shared `DocumentItemsEditor`/`useDocumentPdf`/`useUnsavedChangesGuard`; `InvoiceDetail` reimplements all three (`:241-541,1175-1196,942-958`). Divergence: the invoice item description textarea has **no maxLength** while the shared editor caps it (`DocumentItemsEditor.tsx:390`) — an over-long description 500s at Prisma instead of capping client-side. **Fix:** add a `showVat`/`vatOptions` flag to `DocumentItemsEditor` (respecting "VAT only on invoices") and migrate `InvoiceDetail` onto it plus the shared hooks.
- **Status label/color maps duplicated across warehouse, projects and leave.** `documentStatus.ts` exists specifically to kill per-page maps, yet DRAFT/CONFIRMED/CANCELLED recur across 6 warehouse files (`WarehouseIssues.tsx:35-48`), `Projects.tsx:44-57`/`ProjectDetail.tsx:37-50` are byte-identical, and `LeaveRequests.tsx:25-55`/`LeaveApproval.tsx:36-66` are byte-identical. **Fix:** add `WAREHOUSE_DOC_STATUS`, `MOVEMENT_TYPE`, `RESERVATION_STATUS`, `PROJECT_STATUS`, `LEAVE_STATUS`/`LEAVE_TYPE` to `documentStatus.ts` and import them.
- **`AttendanceAdmin` fetches outside React Query (raw `apiFetch` in `useEffect` + manual refetch dance).** `useAttendanceAdmin` loads projects/users/records via raw `apiFetch` with its own `setData`/`setLoading` (`:823,871`), so it doesn't participate in `['attendance']` invalidations — each mutation must invalidate AND manually re-run `fetchData` with a `setTimeout(300)` (`:1057-1063`). The single biggest structural inconsistency and a latent stale-data risk. **Fix:** migrate reads to React Query options.
- **Orphaned standalone attendance-create page diverges from the admin modal (no project logs).** Adding a record exists twice: a standalone full-page form at `/attendance/create` AND `ShiftFormModal` (`AttendanceAdmin.tsx:194`). The modal supports per-shift project-time logs; the standalone page can't (`AttendanceCreate.tsx:63-147`), and nothing navigates to it. **Fix:** delete `AttendanceCreate.tsx` and its route — the modal is the live superset.
- **"Vytvořit objednávku" modal uses two different file pickers.** The Offers-list version uses the shared `FileUpload`; the Offer-detail version reimplements it with a raw `<input type=file>` + manual readout + custom remove button (`OfferDetail.tsx:1066-1112` vs `Offers.tsx:894-929`). Same dialog, two attachment UIs. **Fix:** replace the raw input with `FileUpload` (gains drag-drop/validation).
- **Warehouse entities use three different create/edit interaction models.** Items edit inline on the detail page via a toggle (`WarehouseItemDetail.tsx:112`); Receipts/Issues use a full-page Form + read-only Detail; Inventory has a Form for creation only; Reservations/Categories/Locations/Suppliers use a list-page Modal. Items (a flat record like Suppliers) using inline edit is the main outlier. **Fix:** document one convention (line-item records = Form+Detail; flat lookups = list modal) and reconcile the Items outlier — treat as a documented rule, not a forced risky migration.
- **Inconsistent "record not found": Item detail redirects away, siblings keep a stable URL.** `WarehouseItemDetail` toasts + `navigate('/warehouse/items')` (`:153-158`); `WarehouseIssueDetail`/`ReceiptDetail`/`InventoryDetail` render an in-place "nebyla nalezena" EmptyState with a Back button and keep the URL (`:122`/`:200`/`:99`). **Fix:** align Item detail to the in-place EmptyState pattern.
- **Settings save model is inconsistent.** The System tab has **two** "Uložit" buttons doing the same thing (`Settings.tsx:997-1007,1193-1199`); other cards have no save; 2FA saves instantly; on Firma, bank accounts/logo apply instantly while company info/numbering/currency need the bottom save (`CompanySettings.tsx:990-1013,1457-1461`). The user can't predict whether a change is live or pending. **Fix:** drop one duplicate System Save; visually distinguish auto-apply vs pending controls.
- **Attendance location page formats datetime with `new Date()` instead of the timezone-safe shared helper.** `AttendanceLocation` defines a local `formatDatetimeLocal` parsing with `new Date()` (`:176`); the rest of attendance uses the timezone-safe `formatDatetime` (`attendanceHelpers.ts:42`), so the same timestamp renders differently. **Fix:** build a regex-based timezone-safe formatter that keeps the year (the location detail legitimately wants the year, which `formatDatetime` omits).
- **Document editor uses two reorder gestures side by side.** Line items reorder via a drag handle (`DocumentItemsEditor.tsx:350-364`), but sections (`SectionsEditor.tsx:200-219`) and company custom fields (`CompanySettings.tsx:1049-1067`) use up/down arrows — on the same page. The drag-only items are also less keyboard-discoverable. **Fix:** add up/down arrow buttons alongside the line-item drag handle (matching SectionsEditor) — also fixes the keyboard-affordance gap.
- **Login re-implements the theme toggle.** The shell uses shared `<ThemeToggle/>` (animated crossfade, title + aria-label); Login builds its own IconButton with hand-duplicated SVGs, only a title, no aria-label, no animation (`Login.tsx:264-313` vs `ThemeToggle.tsx:36-57`). The first screen every user sees is less accessible. **Fix:** reuse the shared `<ThemeToggle/>`.
### 4.11 Visual & theming consistency
- **Projects status-chip colors diverge from the app-wide convention (and duplicate the label map).** `documentStatus.ts` establishes success=done/paid, error=cancelled, info=open. Projects breaks all three — ACTIVE=green, COMPLETED=**blue**, CANCELLED=**grey** (`Projects.tsx:50`, `ProjectDetail.tsx:43`). So a finished project shows blue while a finished order shows green. **Fix:** add a `PROJECT_STATUS` map (aktivni→info, dokonceny→success, zruseny→error) and consume via `statusLabel`/`statusColor`.
- **Linked order status on Project detail renders as a raw untranslated token.** `ProjectDetail` shows `STATUS_LABELS[project.order_status]` but `STATUS_LABELS` is the _project_ map while `order_status` is `prijata`/`v_realizaci`/… — zero key overlap (`:577`), so a completed order shows "(dokoncena)" lowercase plain text. **Fix:** render via `statusLabel(ORDER_STATUS, project.order_status)` (ideally a `StatusChip`).
- **Settings admin-role callout uses a solid `info.light`/`info.dark` fill (the forbidden .light-fill anti-pattern).** The "Administrátor má vždy plný přístup" box is hand-styled with `bgcolor:'info.light'`/`color:'info.dark'` (`Settings.tsx:1228-1229`) — the single solid palette-.light fill in the admin, violating the documented channel-alpha rule; in dark mode it's garish low-contrast blue-on-blue. **Fix:** use the kit `<Alert severity='info'>` (`Alert.tsx:8`), or a channel-alpha wash.
- **Dashboard "Vystavit fakturu" quick action reuses the destructive error/red palette.** `DashQuickActions` sets color `'danger'` → MUI error (`:296`,`:59`), the same red as every Delete button, so "Issue invoice" reads as destructive beside green/blue/orange create actions. _(Caveat: red is also the invoice PDF brand family (#de3a3a), and "Odchod" uses `danger` too — this may be deliberate branding; treat as optional.)_ **Fix:** if not intentional, change to a non-destructive color (info/primary); reserve error/red for deletes.
- **Plan `DayInRangeModal` shows raw ISO dates while the rest of the plan dialogs format cs-CZ.** It prints "2026-06-28 2026-07-02" (`PlanCellModal.tsx:466,474,495`) while ViewModal/DayPanel format "28. 6. 2026." **Fix:** wrap the dates in `formatDate()`.
- **Project delete confirm differs between list and detail.** The list ConfirmDialog always renders the "Smazat i soubory na disku" checkbox even for projects with no NAS folder, with terse copy, no name, no irreversibility warning (`Projects.tsx:508,516`); the detail gates the checkbox on `has_nas_folder` and uses richer copy + "Tato akce je nevratná." (`ProjectDetail.tsx:621,626`). **Fix:** gate the list checkbox on `has_nas_folder` and use the same copy (name + warning).
### 4.12 Microcopy & localization
- **Goods-receipt module named four ways; "Příjmy" also reads as financial income.** Nav "Příjmy" (`navData.tsx:348`), overview button "Nový příjem" (`Warehouse.tsx:203`), list title "Příjmové doklady" + "Nový doklad" (`WarehouseReceipts.tsx:170,178`), detail/audit "Příjemka" (`WarehouseReceiptDetail.tsx:204`, `entityTypeLabels.ts:29`). Issues mirror this (Výdeje/Výdejky/Výdejka). "Příjmy" is the standard Czech word for _income_, so the nav label is actively misleading. **Fix:** settle on "Příjemka"/"Výdejka" everywhere.
- **Saving/busy labels inconsistent; one "Chyba pripojeni" diacritics typo; Modal overrides caller `submitText` mid-save.** Competing forms: "Ukládám…" (Modal, AttendanceCreate, NoteCard, DashProfile), "Ukládání..." (most pages), "Zpracovávám…" vs "Zpracovávám...", plus "Vytváření..."/"Odesílám..."; ellipsis sometimes "…" sometimes three dots. The connection-error fallback is "Chyba pripojeni" (no diacritics) on the dashboard (`Dashboard.tsx:127`, `AuthContext.tsx:256,314`) vs "Chyba připojení" elsewhere. Modal hardcodes `loading?'Ukládám…':submitText` (`:96`), overriding "Vytvořit uživatele" mid-save. **Fix:** fix the typo (outlier vs ~90 sites); standardize the busy label + Unicode ellipsis; the Modal hardcoding is acceptable for save forms (lower priority).
- **"Cancelled" order status spelled two ways in `documentStatus.ts`.** Received orders use `stornovana`→"Stornována" (`:49`); issued orders use `cancelled`→"Stornovaná" (`:58`) — side-by-side under the same `/orders` page. These are display labels (safe to change). **Fix:** pick one Czech form for both.
- **Add-line button uses literal "+ Přidat položku" in document editors vs icon + "Přidat položku" in warehouse forms.** `DocumentItemsEditor.tsx:596` (literal plus, no startIcon) vs warehouse forms with `startIcon={PlusIcon}` (`WarehouseIssueForm.tsx:601` etc.). **Fix:** standardize the affordance and label.
- **Create/edit modal submit labels mix entity-specific, bare, and default wording.** "Vytvořit zákazníka"/"Uložit změny" (`OffersCustomers.tsx:543`), "Vytvořit uživatele" (`Users.tsx:369`), bare "Vytvořit"/"Uložit" (`OffersTemplates.tsx:361`), and Vehicles falls back to the Modal default "Uložit" (`Modal.tsx:36`). **Fix:** adopt one rule (create="Vytvořit", edit="Uložit změny") and set it as the Modal default.
- **Create-action verb differs across analogous list pages; both Orders tabs share the identical "Vytvořit objednávku" label.** Imperative "Přidat X" (master data) vs "Nový/Nová X" (documents) vs "Vytvořit objednávku" (Orders, identical on both tabs for two different doc types, `Orders.tsx:125,129`); the empty-state CTA verb mirrors and compounds this. **Fix:** disambiguate the two Orders tabs first ("Nová vydaná/přijatá objednávka"), then pick one verb convention and align the empty-state CTA.
- **Several numbers/prices bypass cs-CZ formatting; file-size unit casing disagrees (kB vs KB).** Offers item-template price uses `Number().toFixed(2)`→"1234.50" (period, no separator/currency, `OffersTemplates.tsx:287`); warehouse batch picker builds "…toFixed(2) Kč" (`WarehouseIssueForm.tsx:160`); vacation/sick hour balances use `.toFixed(1)`→"12.5" (`AttendanceBalances.tsx:307`); zeros render "0 Kč" vs "0,00 Kč." File-size helper duplicated with "kB" (`FileUpload.tsx:9`) vs "KB" (`OfferDetail.tsx:1072`). **Fix:** route money through `formatCurrency` and decimals through cs-CZ/Intl; extract one `formatFileSize()` with one unit casing.
- **Leave-request modal day/hour estimate ignores public holidays.** The modal previews "X pracovních dnů" using `calculateBusinessDays` (MonFri only, `Attendance.tsx:498,1242`), but the rest of the system is holiday-aware (server `leave-requests.ts:99` excludes weekends AND holidays). A vacation spanning e.g. 1 May over-counts vs the stored `total_days`/`total_hours`. **Fix:** make the modal estimate holiday-aware (reuse the holiday helper).
### 4.13 Mobile / responsive
- **Status-filter tab bars clip on phones — shared `Tabs` has no scrollable variant.** `Tabs.tsx:28-49` uses MUI's default `variant="standard"` (overflow hidden, no scroll). At ~360px the 5 offer/invoice tabs and 4 project tabs overflow the centered Box and get clipped with no scroll affordance — effectively unreachable. **Fix:** set `variant="scrollable"`, `scrollButtons="auto"`, `allowScrollButtonsMobile` — one change fixes every status filter and the issued/received toggle.
- **Shared Modal never goes full-screen on phones; leave date grid is hardcoded two-column.** `Modal` renders a plain `fullWidth+maxWidth` Dialog with no responsive `fullScreen` (`:67-75`), so the ~9-field Trip form, the admin shift form and the leave form become a narrow scrolling box at 360px. The leave modal's Od/Do grid is hardcoded `minmax(0,1fr) minmax(0,1fr)` (`Attendance.tsx:1195-1199`) while every other date-pair grid is responsive `{xs:'1fr',sm:'1fr 1fr'}` (`ShiftFormModal.tsx:254`, `Trips.tsx:528-535`). **Fix:** add `fullScreen={useMediaQuery(down('sm'))}` to Modal; fix the leave grid.
- **Long full-page editors keep Save only in the top header (no sticky save); placement differs page-to-page.** Document detail editors place all Save/Create/Activate in the top `headerActionsSx` slot (`OfferDetail.tsx:688-828`), so after scrolling through header fields/picker/line-items/rich-text/notes a phone user must scroll back to the top to save. `AttendanceCreate` pins Zrušit/Uložit at the **bottom** (`:362-374`); modals pin submit in DialogActions — three placements. **Fix:** add a sticky action bar to long editors and standardize placement.
- **Warehouse issue/receipt line items lack the labeled card-per-row mobile layout the document editor has.** `DocumentItemsEditor` has a dedicated `isMobile` branch — a bordered card per row with "Položka N" index, labeled fields, per-row total, drag/remove (`:170-342`). `WarehouseIssueForm.tsx:513-567` just collapses a grid to `xs:'1fr'` with placeholder-only fields, no border/labels/separator — once a value is typed the placeholder vanishes and rows blur together. Worst exactly where shop-floor mobile use is likely. **Fix:** reuse the card-per-row pattern (ideally a shared mobile line-item card).
- **FilterBar children mix fixed-vs-grow flex bases, leaving dead space on mobile.** `AttendanceAdmin.tsx:202,205` use `flex:'0 0 180px'`/`'0 0 220px'` and `AttendanceHistory.tsx:516` uses `flex:'0 0 180px'` (fixed, never grow), so on a phone they sit narrow with dead space beside them, while `Offers.tsx:786` uses `flex:'1 1 320px'` which fills the row. **Fix:** adopt one convention (e.g. `flex:'1 1 <min>px'`) or have `FilterBar` stretch children full-width below `sm`.
### 4.14 Accessibility
- **Desktop document line-item grid inputs are unlabeled while the mobile card layout labels every field.** The mobile branch passes explicit labels (Popis, Množství, Jednotka, Jedn. cena, Sleva %); the desktop table renders the same TextFields with **no** label/aria-label, relying on visual `<th>` headers not programmatically associated with the inputs; the desktop "V ceně" Checkbox is unnamed (`DocumentItemsEditor.tsx:374-440,445-450`). A screen-reader user editing an offer on desktop hears a column of unlabeled "edit text" boxes. **Fix:** add an `aria-label` to each desktop cell control (e.g. `Množství, položka ${index+1}`).
- **List-page search boxes are placeholder-only inputs with no accessible name.** Raw TextFields with only a placeholder (not an accessible name) across ~13 pages (`Offers.tsx:787`, `Invoices.tsx:741`, `WarehouseItems.tsx:180`, `Projects.tsx:454`, `IssuedOrders.tsx:386`). **Fix:** add `aria-label="Hledat"` + `type="search"` — best via a shared `SearchField` (also adds the native clear button and mobile search keyboard).
- **(Cross-listed) DataTable clickable rows aren't keyboard-operable; no skip-to-content link.** See §4.7 (row semantics) and §4.8 (skip link).
### 4.15 Performance & bundle
- **MUI + Emotion live in the 781 kB entry chunk, so every deploy busts the cached UI vendor code.** `vite.config.ts` `manualChunks` only carves out react/react-dom/react-router (436 kB) and framer-motion (147 kB); the entire MUI library + Emotion fall into the entry chunk (781 kB raw / 232 kB gzip). With frequent same-day patch releases, daily users re-download ~232 kB gzip of unchanged MUI every deploy. **Fix:** split `@mui/*`+`@emotion/*`(+quill) into a long-lived `vendor-mui` chunk.
- **framer-motion (147 kB) is a static dependency of the eager AppShell, loading on first paint incl. Login.** `AppShell`/`PageEnter`/`ThemeToggle` statically import framer-motion (`PageHeader` deliberately does not); `AppShell` is eagerly imported by `AdminApp` (`:8`, `AppShell.tsx:101`). Login pays for it too. **Fix:** migrate to `LazyMotion` + the lightweight `m` component (`domAnimation`) — note Login and the Dash\* components import framer-motion directly, so lazy-gating only `PageEnter` won't remove it from the login critical path.
- **Dashboard + its 7 Dash\* subcomponents are bundled into the entry chunk, downloaded on the Login screen.** Dashboard and Login are statically imported in `AdminApp` (`:14-15`), so an unauthenticated user hitting `/login` downloads the entire authenticated dashboard's code before typing a password. **Fix:** lazy-load Dashboard via `lazyWithReload` like every other route; keep Login eager.
- **No route-transition progress indicator and no link prefetch — heavy pages blank to a spinner on click.** Clicking a sidebar item blanks main content to a centered spinner while the chunk downloads (PlanWork 44 kB, InvoiceDetail 35 kB, AttendanceLocation 155 kB with Leaflet), with no top progress bar and no prefetch (zero `prefetchQuery`/`onMouseEnter`/`preload` hits). A `ProgressBar` exists but is reused only as an attendance-fund meter. **Fix:** add an unobtrusive top `LinearProgress` during route transitions and prefetch the lazy chunk (+ primary query) on sidebar link hover/focus.
---
## 5. Suggested Sequencing
**Sprint 1 — "Stop lying to the user" (mostly Quick Wins, ~2-3 days).**
Ship the data-freshness convergence (one invalidation set per family), the global `QueryCache.onError` so failed fetches stop showing as empty, the scrollable mobile tabs, the invoice-paid confirm, the silent-toggle `onError` toasts, the draft-PDF 404 gate, the wrong-Orders-tab redirect, the search debounces, the `csCZ` localeText, the `document.title`, the project/order status-color fixes, and the diacritics/label typos. These are individually small, collectively high-trust, and low-risk. Pair each with a quick Playwright check on the dev server (the user runs it).
**Sprint 2 — "Converge the primitives" (the structural anti-drift work, ~1 week).**
De-fork the dirty-guards and add them to the six unguarded editors; route the invoice PDF openers through `useDocumentPdf`; consolidate the status maps into `documentStatus.ts`; standardize validation on inline `<Field error>` (starting with the mirrored screens); add `<form onSubmit>` to Modal; migrate hand-rolled headers to `PageHeader`; replace inline English errors with `apiErrorMessage`. This is where you stop the Sprint-1 fixes from re-drifting, and it's the cleanest fit for the codebase's "extend, never fork" rule.
**Sprint 3 — "Mobile + a11y + warehouse parity" (~1 week).**
Full-screen modals, sticky save bars, warehouse card-per-row line items, keyboard-operable rows, skip link, search-field accessible names, warehouse document totals, the leave "Nová žádost" action, and the warehouse "Potvrdit" confirm.
**Strategic backlog (schedule deliberately, each is multi-day and one needs a migration).**
Invoice edit-locking (DB migration + route trio — coordinate the migration per CLAUDE.md: ask the user to stop the dev server, apply to `app_test` too). The router upgrade for in-app dirty-nav blocking. `AttendanceAdmin` onto React Query. `InvoiceDetail` onto the shared editor. Real skeletons. Bundle splitting + route prefetch. Treat the navigation/IA items (breadcrumbs, master-data nav grouping, `/customers` move) as a focused IA pass once the above settle.
A note on scope discipline: nearly every item here is "make B match the already-correct A," so the safest pattern is to **read the reference implementation first** (offers/issued orders for documents, `WarehouseSuppliers` for lists, `documentStatus.ts` for status) and converge onto it — rather than inventing new patterns. That keeps the diff small and the regression surface low, which matches the user's same-day-patch-release rhythm.

View File

@@ -46,6 +46,17 @@ without explicit user confirmation.**
errors from prior pids).
9. Clean up tarballs locally and in `/tmp/` on the server.
**nginx is NOT part of a normal release.** nginx is only a reverse proxy in
front of the pm2 app (`proxy_pass` → `127.0.0.1:3001`); a code release changes
app code, which `pm2 restart app-ts` picks up — nginx has nothing new to read.
Do **not** run `sudo nginx -t && sudo systemctl reload nginx` every deploy. Run
it ONLY when you actually edit nginx config (`/etc/nginx/…` — `server_name`,
ports, `proxy_pass` upstream, TLS cert paths, locations/redirects/headers,
`client_max_body_size`, rate limits, etc.). When you do change it, always
`nginx -t` first (validates syntax, changes nothing) THEN `systemctl reload
nginx` (graceful re-read, keeps active connections; a bad config on reload is
rejected and the old one keeps running).
Risky releases (framework jumps, FK/constraint-altering migrations) get a
read-only pre-flight first: `prisma migrate status` on prod, verify FK
constraint names the migration DROPs, check no data violates new

View File

@@ -0,0 +1,789 @@
# Per-document custom-field print selection — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Let each offer, issued order, and invoice choose — on its detail page — which company custom fields print in its PDF sender block; default none selected.
**Architecture:** A new nullable `selected_custom_fields` column (JSON-array-in-VARCHAR) on `quotations`, `issued_orders`, `invoices`. A shared backend util encodes/decodes the index array. Create/update services persist it; detail services decode it to `number[]`. The PDF `buildAddressLines()` company-block builder gains an optional selected-indices filter. A shared React picker reused by the three detail pages drives the selection.
**Tech Stack:** Prisma 7 / MySQL, Fastify 5, Zod 4, Vitest (real `app_test` DB), React 19 + MUI v7 + React Query.
**Spec:** `docs/superpowers/specs/2026-06-16-per-document-custom-field-selection-design.md`
---
## Conventions for this plan
- This shell is non-interactive — `prisma migrate dev` is forbidden. Use the `migrate diff` recipe (Task 1).
- **Before the migration, ask the user to stop their dev server and wait for confirmation** (it holds DB connections). Do not run the migration until they confirm.
- Server tests run against `app_test` via `.env.test` (`npm test`). Apply the migration to `app_test` too or the suite breaks.
- `npm run typecheck` = `tsc -b --noEmit`. `npm run lint` must stay at 0 errors.
- Selection semantics in `buildAddressLines`: param **omitted/`undefined`** ⇒ show ALL custom fields (unchanged behavior — used for customer/supplier blocks). Param is an **array** (possibly empty) ⇒ show ONLY those indices (used for the company/sender block; empty ⇒ none).
---
## File Structure
- **Modify** `prisma/schema.prisma` — add `selected_custom_fields String?` to `quotations`, `issued_orders`, `invoices`.
- **Create** `prisma/migrations/<ts>_add_selected_custom_fields/migration.sql`.
- **Modify** `src/utils/custom-fields.ts` — add `encodeSelectedCustomFields` / `parseSelectedCustomFields`.
- **Create** `src/__tests__/selected-custom-fields.test.ts` — util + integration coverage.
- **Modify** `src/schemas/offers.schema.ts`, `issued-orders.schema.ts`, `invoices.schema.ts` — new optional array field.
- **Modify** `src/services/offers.service.ts`, `issued-orders.service.ts`, `invoices.service.ts` — persist on create/update, decode in detail.
- **Modify** `src/routes/admin/offers-pdf.ts`, `issued-orders-pdf.ts`, `invoices-pdf.ts` — filter company custom lines.
- **Modify** `src/admin/lib/queries/offers.ts`, `issued-orders.ts`, `invoices.ts` — add `selected_custom_fields: number[]` to detail interfaces.
- **Create** `src/admin/components/document/CustomFieldsPrintPicker.tsx` — shared picker.
- **Modify** `src/admin/pages/OfferDetail.tsx`, `IssuedOrderDetail.tsx`, `InvoiceDetail.tsx` — render picker, wire into save payload.
---
## Task 1: Schema column + migration
**Files:**
- Modify: `prisma/schema.prisma` (models `quotations`, `issued_orders`, `invoices`)
- Create: `prisma/migrations/<yyyyMMddHHmmss>_add_selected_custom_fields/migration.sql`
- [ ] **Step 1: Ask the user to stop their dev server**
Post: "Please stop your dev server so I can apply a migration, and tell me when it's stopped." Wait for confirmation before any later `migrate deploy` step.
- [ ] **Step 2: Add the column to each model in `prisma/schema.prisma`**
Add this line to the `quotations` model (near other scalar columns, e.g. after `language`):
```prisma
selected_custom_fields String? @db.VarChar(255)
```
Add the identical line to the `issued_orders` model and to the `invoices` model.
- [ ] **Step 3: Generate the migration SQL**
Run (Git Bash):
```bash
cd /d/cortex/boha-app-ts
TS=$(date +%Y%m%d%H%M%S)
mkdir -p "prisma/migrations/${TS}_add_selected_custom_fields"
npx prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script \
> "prisma/migrations/${TS}_add_selected_custom_fields/migration.sql"
```
Expected: a `migration.sql` containing three `ALTER TABLE … ADD COLUMN selected_custom_fields VARCHAR(255) NULL` statements (one per table). Open it and confirm it touches ONLY `quotations`, `issued_orders`, `invoices` and adds nothing else (no BOM — if it was written via PowerShell, strip the BOM).
- [ ] **Step 4: Apply to dev DB + regenerate client (after user confirmed server stopped)**
```bash
npx prisma migrate deploy
npx prisma generate
```
Expected: "All migrations have been applied" and a regenerated client.
- [ ] **Step 5: Apply to the test DB**
```bash
DATABASE_URL="$(grep -m1 '^DATABASE_URL' .env.test | cut -d= -f2- | tr -d '"')" npx prisma migrate deploy
```
Expected: the same migration applied to `app_test`. (If the env parsing is awkward on this shell, temporarily set `DATABASE_URL` to the app_test URL from `.env.test` and run `npx prisma migrate deploy`.)
- [ ] **Step 6: Typecheck**
Run: `npm run typecheck`
Expected: PASS (the new Prisma field is now known to the client).
- [ ] **Step 7: Commit**
```bash
git add prisma/schema.prisma prisma/migrations
git commit -m "feat(documents): add selected_custom_fields column to quotations/issued_orders/invoices"
```
---
## Task 2: Backend encode/decode util (TDD)
**Files:**
- Modify: `src/utils/custom-fields.ts`
- Test: `src/__tests__/selected-custom-fields.test.ts`
- [ ] **Step 1: Write the failing test**
Create `src/__tests__/selected-custom-fields.test.ts`:
```ts
import { describe, it, expect } from "vitest";
import {
encodeSelectedCustomFields,
parseSelectedCustomFields,
} from "../utils/custom-fields";
describe("selected custom fields encode/decode", () => {
it("encodes a non-empty index array to a JSON string", () => {
expect(encodeSelectedCustomFields([0, 2])).toBe("[0,2]");
});
it("encodes empty / non-array to null", () => {
expect(encodeSelectedCustomFields([])).toBeNull();
expect(encodeSelectedCustomFields(undefined)).toBeNull();
expect(encodeSelectedCustomFields("nope")).toBeNull();
});
it("dedupes, sorts, and drops invalid entries before encoding", () => {
expect(encodeSelectedCustomFields([2, 0, 2, -1, 1.5, 3])).toBe("[0,2,3]");
});
it("parses a stored string back to a number array", () => {
expect(parseSelectedCustomFields("[0,2]")).toEqual([0, 2]);
});
it("parses null / malformed to an empty array", () => {
expect(parseSelectedCustomFields(null)).toEqual([]);
expect(parseSelectedCustomFields("")).toEqual([]);
expect(parseSelectedCustomFields("{garbage")).toEqual([]);
expect(parseSelectedCustomFields('"x"')).toEqual([]);
});
it("parses already-array input (defensive) and filters invalid", () => {
expect(parseSelectedCustomFields([0, "1", 2, -3] as unknown)).toEqual([
0, 2,
]);
});
});
```
- [ ] **Step 2: Run it to confirm failure**
Run: `npm test -- selected-custom-fields`
Expected: FAIL — `encodeSelectedCustomFields is not a function`.
- [ ] **Step 3: Implement the helpers**
Append to `src/utils/custom-fields.ts`:
```ts
/**
* Per-document selection of which COMPANY custom fields print on a PDF.
* Stored positionally (matching the `custom_<i>` keys the PDF builder emits)
* as a JSON array string, e.g. "[0,2]". Null/empty means "none selected".
*/
export function encodeSelectedCustomFields(indices: unknown): string | null {
const clean = normalizeIndices(indices);
return clean.length > 0 ? JSON.stringify(clean) : null;
}
/** Decode the stored selection (string OR defensive array) into a clean number[]. */
export function parseSelectedCustomFields(raw: unknown): number[] {
if (raw == null) return [];
if (Array.isArray(raw)) return normalizeIndices(raw);
if (typeof raw !== "string" || raw.trim() === "") return [];
try {
return normalizeIndices(JSON.parse(raw));
} catch {
// Malformed JSON in a selection column degrades to "none" (expected
// condition — a hand-edited/legacy row should never 500 a PDF render).
return [];
}
}
function normalizeIndices(input: unknown): number[] {
if (!Array.isArray(input)) return [];
const set = new Set<number>();
for (const v of input) {
if (typeof v === "number" && Number.isInteger(v) && v >= 0) set.add(v);
}
return [...set].sort((a, b) => a - b);
}
```
- [ ] **Step 4: Run the test to confirm it passes**
Run: `npm test -- selected-custom-fields`
Expected: PASS (all util cases).
- [ ] **Step 5: Commit**
```bash
git add src/utils/custom-fields.ts src/__tests__/selected-custom-fields.test.ts
git commit -m "feat(documents): selected-custom-fields encode/decode helpers"
```
---
## Task 3: Zod schemas
**Files:**
- Modify: `src/schemas/offers.schema.ts`
- Modify: `src/schemas/issued-orders.schema.ts`
- Modify: `src/schemas/invoices.schema.ts`
- [ ] **Step 1: Offers schema**
In `src/schemas/offers.schema.ts`, inside `CreateQuotationSchema`, add after the `sections` line (line 50):
```ts
// Positional indices of company custom fields to print on this document's
// PDF. Omitted/empty ⇒ none. Update schema derives via .partial().
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
```
(`UpdateQuotationSchema` already derives from this via `.partial().omit({ quotation_number: true })` — no change needed there.)
- [ ] **Step 2: Issued-orders schema**
In `src/schemas/issued-orders.schema.ts`, inside `CreateIssuedOrderSchema`, add after the `sections` field:
```ts
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
```
(`UpdateIssuedOrderSchema` derives via `.partial()` — no change.)
- [ ] **Step 3: Invoices schema**
In `src/schemas/invoices.schema.ts`, add the same line to BOTH `CreateInvoiceSchema` (after its `sections` field) and `UpdateInvoiceSchema` (after its `sections` field — invoices define the two schemas separately, so it must be added in both):
```ts
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
```
- [ ] **Step 4: Typecheck**
Run: `npm run typecheck`
Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add src/schemas/offers.schema.ts src/schemas/issued-orders.schema.ts src/schemas/invoices.schema.ts
git commit -m "feat(documents): accept selected_custom_fields in document schemas"
```
---
## Task 4: Services — persist on write, decode in detail (TDD)
**Files:**
- Modify: `src/services/offers.service.ts`
- Modify: `src/services/issued-orders.service.ts`
- Modify: `src/services/invoices.service.ts`
- Test: `src/__tests__/selected-custom-fields.test.ts` (extend)
- [ ] **Step 1: Add the import to all three services**
At the top of each of the three service files, add (or extend the existing import from `../utils/custom-fields`):
```ts
import {
encodeSelectedCustomFields,
parseSelectedCustomFields,
} from "../utils/custom-fields";
```
- [ ] **Step 2: Offers — persist on create**
In `createOffer` (`src/services/offers.service.ts`), inside `tx.quotations.create({ data: { … } })`, add after `scope_description`:
```ts
selected_custom_fields: encodeSelectedCustomFields(
body.selected_custom_fields,
),
```
- [ ] **Step 3: Offers — persist on update**
In `updateOffer`, inside the `const data = { … }` object (after `scope_description`, before `modified_at`), add:
```ts
selected_custom_fields:
body.selected_custom_fields !== undefined
? encodeSelectedCustomFields(body.selected_custom_fields)
: undefined,
```
(`undefined` = "key absent in payload, leave column untouched" — matches the sibling header fields.)
- [ ] **Step 4: Offers — decode in detail**
In `getOffer`, in the returned object (after `valid_transitions`), add:
```ts
selected_custom_fields: parseSelectedCustomFields(rest.selected_custom_fields),
```
- [ ] **Step 5: Issued orders — persist + decode**
In `src/services/issued-orders.service.ts`:
- In `createIssuedOrder`, inside `tx.issued_orders.create({ data: { … } })`, add:
```ts
selected_custom_fields: encodeSelectedCustomFields(
body.selected_custom_fields,
),
```
- In `updateIssuedOrder`, inside the header `data` object passed to `issued_orders.update`, add:
```ts
selected_custom_fields:
body.selected_custom_fields !== undefined
? encodeSelectedCustomFields(body.selected_custom_fields)
: undefined,
```
- In `getIssuedOrder`, in the returned object (after `valid_transitions`), add:
```ts
selected_custom_fields: parseSelectedCustomFields(rest.selected_custom_fields),
```
- [ ] **Step 6: Invoices — persist + decode**
In `src/services/invoices.service.ts`:
- In `createInvoice`, inside `tx.invoices.create({ data: { … } })`, add after `internal_notes`:
```ts
selected_custom_fields: encodeSelectedCustomFields(
body.selected_custom_fields,
),
```
- In `updateInvoice`, inside the first `if (editable) { … }` block (after the `tax_date` handling, still inside the block), add:
```ts
if (body.selected_custom_fields !== undefined)
data.selected_custom_fields = encodeSelectedCustomFields(
body.selected_custom_fields,
);
```
- In `getInvoice`, in the returned object (after `valid_transitions`), add:
```ts
selected_custom_fields: parseSelectedCustomFields(rest.selected_custom_fields),
```
- [ ] **Step 7: Extend the test with an offers round-trip (real DB)**
Append to `src/__tests__/selected-custom-fields.test.ts`. Match the existing suite's fixture style — import the offers service directly and clean up. Use a far-future placeholder where the suite does; if an existing offers test helper exists, prefer it. Minimal version:
```ts
import { createOffer, getOffer } from "../services/offers.service";
import { prisma } from "../config/prisma"; // adjust to the project's prisma export path
describe("offers selected_custom_fields round-trip", () => {
const created: number[] = [];
afterAll(async () => {
if (created.length)
await prisma.quotations.deleteMany({ where: { id: { in: created } } });
});
it("persists selection on create and decodes it on detail", async () => {
const res = (await createOffer({
status: "draft",
selected_custom_fields: [2, 0, 0],
})) as { id: number };
created.push(res.id);
const row = await prisma.quotations.findUnique({ where: { id: res.id } });
expect(row?.selected_custom_fields).toBe("[0,2]");
const detail = await getOffer(res.id);
expect(detail?.selected_custom_fields).toEqual([0, 2]);
});
it("stores null when selection is empty", async () => {
const res = (await createOffer({
status: "draft",
selected_custom_fields: [],
})) as { id: number };
created.push(res.id);
const row = await prisma.quotations.findUnique({ where: { id: res.id } });
expect(row?.selected_custom_fields).toBeNull();
});
});
```
> Before running: confirm the prisma import path (`../config/prisma` vs `../config/db` — grep an existing test). Adjust the import to match.
- [ ] **Step 8: Run tests**
Run: `npm test -- selected-custom-fields`
Expected: PASS (util + offers round-trip). If FK constraints require a customer, the `customer_id`-less draft path above avoids them.
- [ ] **Step 9: Typecheck + commit**
```bash
npm run typecheck
git add src/services/offers.service.ts src/services/issued-orders.service.ts src/services/invoices.service.ts src/__tests__/selected-custom-fields.test.ts
git commit -m "feat(documents): persist & expose selected_custom_fields in services"
```
---
## Task 5: PDF rendering — filter company custom lines (TDD)
**Files:**
- Modify: `src/routes/admin/offers-pdf.ts`
- Modify: `src/routes/admin/issued-orders-pdf.ts`
- Modify: `src/routes/admin/invoices-pdf.ts`
- Test: `src/__tests__/selected-custom-fields.test.ts` (extend, if a PDF render is unit-testable; otherwise assert via the helper — see Step 6)
- [ ] **Step 1: Offers PDF — add the filter param to `buildAddressLines`**
In `src/routes/admin/offers-pdf.ts`, change the signature (line 28-32):
```ts
function buildAddressLines(
entity: Record<string, unknown> | null,
isSupplier: boolean,
t: (key: string) => string,
selectedCustomFields?: number[],
): AddressResult {
```
Then change the custom-field loop (lines 88-96) to skip non-selected indices when a selection array is provided:
```ts
const filterCustom = Array.isArray(selectedCustomFields);
cfData.forEach((cf, i) => {
if (filterCustom && !selectedCustomFields!.includes(i)) return;
const cfName = (cf.name || "").trim();
const cfValue = (cf.value || "").trim();
const showLabel = cf.showLabel !== false;
if (cfValue) {
fieldMap[`custom_${i}`] =
showLabel && cfName ? `${cfName}: ${cfValue}` : cfValue;
}
});
```
- [ ] **Step 2: Offers PDF — pass the document's selection into the COMPANY call**
The offer's sender/company block is `supp` (`isSupplier: true` on `settings`). Update that call (lines 209-213) to pass the parsed selection; leave the customer call (`cust`) unchanged so customer custom fields still show in full:
```ts
const supp = buildAddressLines(
settings as unknown as Record<string, unknown>,
true,
t,
parseSelectedCustomFields(
(quotation as { selected_custom_fields?: unknown }).selected_custom_fields,
),
);
```
Add the import at the top of the file:
```ts
import { parseSelectedCustomFields } from "../../utils/custom-fields";
```
> Confirm `quotation` (the `OfferForPdf` payload the render function receives) is selected with the default field set so `selected_custom_fields` is present. It's a scalar column on `quotations`, so the default `findUnique`/`include` returns it — no `select` narrowing to adjust here.
- [ ] **Step 3: Issued-orders PDF — same change on the COMPANY (buyer) block**
In `src/routes/admin/issued-orders-pdf.ts`:
- Add `selectedCustomFields?: number[]` as the last param of `buildAddressLines` and apply the identical `filterCustom` guard in its custom-field loop.
- The company block is `buyer = buildAddressLines(settings, true, t)` (line 316). Change to:
```ts
const buyer = buildAddressLines(
settings,
true,
t,
parseSelectedCustomFields(
(order as { selected_custom_fields?: unknown }).selected_custom_fields,
),
);
```
- Leave `buildSupplierLines(...)` untouched (supplier fields keep showing in full).
- Add `import { parseSelectedCustomFields } from "../../utils/custom-fields";`.
> Confirm the render function's `order` param carries `selected_custom_fields`. If the route fetches the order via a narrow `select`, add `selected_custom_fields: true` to it; if it uses `include`/default scalars, it's already present. Grep the route's `issued_orders.findUnique`/`findFirst` before assuming.
- [ ] **Step 4: Invoices PDF — same change on the COMPANY (supplier-of-invoice) block**
In `src/routes/admin/invoices-pdf.ts`:
- Add `selectedCustomFields?: number[]` as the last param of `buildAddressLines` and apply the identical `filterCustom` guard.
- The company block is `supp = buildAddressLines(settings, true, t)` (line 457). Change to:
```ts
const supp = buildAddressLines(
settings,
true,
t,
parseSelectedCustomFields(
(invoice as { selected_custom_fields?: unknown }).selected_custom_fields,
),
);
```
- Leave `cust = buildAddressLines(customer, false, t)` untouched.
- Note the separate `settings.custom_fields` read lower down (the "supplier email/web" extraction near line 469) is a DIFFERENT concern (pulls an email for a header line) — **do not** filter that; leave it as-is.
- Add `import { parseSelectedCustomFields } from "../../utils/custom-fields";`.
> Confirm `invoice` is fetched with default scalars (it is — `prisma.invoices.findUnique` without a narrowing `select` in this route), so `selected_custom_fields` is present.
- [ ] **Step 5: Typecheck + lint**
Run: `npm run typecheck && npm run lint`
Expected: PASS, 0 lint errors.
- [ ] **Step 6: Add a focused render assertion (extend the test file)**
If the three PDF modules export their HTML render function (e.g. offers exports `renderOfferHtml`), add a test that renders with a stubbed settings object carrying two company custom fields and asserts only the selected one appears. Mock `html-to-pdf` per the suite convention; you're asserting on the returned HTML string, not a real PDF. Example for offers (adapt names to the actual export):
```ts
import { renderOfferHtml } from "../routes/admin/offers-pdf"; // confirm export name
it("offer PDF prints only selected company custom fields", () => {
const settings = {
name: "Naše Firma s.r.o.",
custom_fields: JSON.stringify({
fields: [
{ name: "Tel.", value: "123", showLabel: true },
{ name: "Web", value: "example.cz", showLabel: true },
],
field_order: [],
}),
};
const quotation = {
customers: null,
quotation_items: [],
scope_sections: [],
status: "draft",
currency: "CZK",
language: "cs",
selected_custom_fields: "[0]",
};
const html = renderOfferHtml(quotation as never, settings as never);
expect(html).toContain("Tel.: 123");
expect(html).not.toContain("example.cz");
});
```
If the render function is NOT exported / not unit-testable without a DB, SKIP this step rather than forcing it — the util test (Task 2) plus the service round-trip (Task 4) already cover the data path; note in the commit that PDF filtering was verified manually. Do not export internals solely to test them if that breaks the module's encapsulation; prefer a manual verification note.
- [ ] **Step 7: Commit**
```bash
git add src/routes/admin/offers-pdf.ts src/routes/admin/issued-orders-pdf.ts src/routes/admin/invoices-pdf.ts src/__tests__/selected-custom-fields.test.ts
git commit -m "feat(documents): PDF prints only the document's selected company custom fields"
```
---
## Task 6: Frontend — detail query types + shared picker
**Files:**
- Modify: `src/admin/lib/queries/offers.ts`, `issued-orders.ts`, `invoices.ts`
- Create: `src/admin/components/document/CustomFieldsPrintPicker.tsx`
- [ ] **Step 1: Add the field to the three detail interfaces**
- `src/admin/lib/queries/offers.ts` — add to `OfferDetailData`:
```ts
selected_custom_fields: number[];
```
- `src/admin/lib/queries/issued-orders.ts` — add to `IssuedOrderDetail`:
```ts
selected_custom_fields: number[];
```
- `src/admin/lib/queries/invoices.ts` — add to `InvoiceDetail`:
```ts
selected_custom_fields?: number[];
```
- [ ] **Step 2: Create the shared picker component**
Create `src/admin/components/document/CustomFieldsPrintPicker.tsx`:
```tsx
import { FormControlLabel, Checkbox, Box, Typography } from "@mui/material";
import type { CompanySettingsCustomField } from "../../lib/queries/settings";
interface Props {
/** Company custom field definitions, in positional order (index = print key). */
fields: CompanySettingsCustomField[];
/** Currently selected positional indices. */
selected: number[];
/** Read-only (document not editable / locked by another user). */
disabled?: boolean;
onChange: (next: number[]) => void;
}
/**
* Per-document picker: choose which COMPANY custom fields print on this
* document's PDF. Selection is positional (matches the PDF `custom_<i>` keys).
* Renders nothing when the company has defined no custom fields.
*/
export default function CustomFieldsPrintPicker({
fields,
selected,
disabled = false,
onChange,
}: Props) {
const printable = fields.filter((f) => (f.value || "").trim());
if (printable.length === 0) return null;
const toggle = (idx: number, checked: boolean) => {
const set = new Set(selected);
if (checked) set.add(idx);
else set.delete(idx);
onChange([...set].sort((a, b) => a - b));
};
return (
<Box>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
Vlastní pole na PDF
</Typography>
{fields.map((f, idx) => {
if (!(f.value || "").trim()) return null;
const label = (f.name || "").trim() ? `${f.name}: ${f.value}` : f.value;
return (
<FormControlLabel
key={idx}
control={
<Checkbox
size="small"
checked={selected.includes(idx)}
disabled={disabled}
onChange={(e) => toggle(idx, e.target.checked)}
/>
}
label={<Typography variant="body2">{label}</Typography>}
/>
);
})}
</Box>
);
}
```
> Note: indices are keyed off the FULL `fields` array (not the filtered `printable`) so they stay aligned with the PDF's `custom_<i>`, which also enumerates the full array. Empty-value fields are skipped visually but still consume their index.
- [ ] **Step 3: Typecheck**
Run: `npm run typecheck`
Expected: PASS.
- [ ] **Step 4: Commit**
```bash
git add src/admin/lib/queries/offers.ts src/admin/lib/queries/issued-orders.ts src/admin/lib/queries/invoices.ts src/admin/components/document/CustomFieldsPrintPicker.tsx
git commit -m "feat(documents): shared CustomFieldsPrintPicker + detail query types"
```
---
## Task 7: Frontend — wire the picker into the three detail pages
**Files:**
- Modify: `src/admin/pages/OfferDetail.tsx`
- Modify: `src/admin/pages/IssuedOrderDetail.tsx`
- Modify: `src/admin/pages/InvoiceDetail.tsx`
For EACH page, the same four edits. Detail below uses OfferDetail; repeat the pattern for the other two (their company-settings query and edit-lock/editable flags already exist on the page — reuse them; do not add new queries).
- [ ] **Step 1: Import the picker (all three pages)**
```ts
import CustomFieldsPrintPicker from "../components/document/CustomFieldsPrintPicker";
```
- [ ] **Step 2: Seed local state from the loaded document**
Add state near the page's other editable-field state, and seed it when the document loads (follow the page's existing seeding pattern — if it copies server data into state in an effect or on query success, add this alongside; if it derives form state via `useState` initializers keyed on the query, match that):
```ts
const [selectedCustomFields, setSelectedCustomFields] = useState<number[]>([]);
// when the detail query resolves (same place other fields are seeded):
// setSelectedCustomFields(data.selected_custom_fields ?? []);
```
Respect Rules of Hooks: declare this `useState` with the other hooks, before any early `return`.
- [ ] **Step 3: Render the picker in the editable header/meta area**
Place near the other document-level settings (currency/language). `companySettings` is already loaded on the page via `companySettingsOptions()`. Use the page's existing "is this document editable / not locked by another user" boolean for `disabled` (e.g. `!canEdit` or the locked flag the page already computes):
```tsx
<CustomFieldsPrintPicker
fields={companySettings?.custom_fields ?? []}
selected={selectedCustomFields}
disabled={!canEdit}
onChange={setSelectedCustomFields}
/>
```
> Use whatever the page already calls its edit-gate (e.g. `canEdit`, `editable`, `isLockedByOther`). Do NOT invent a new permission — reuse the page's existing flag so the picker locks exactly when the rest of the form does.
- [ ] **Step 4: Include the selection in the save payload**
Find where the page builds its update/create payload (the object passed to the save mutation) and add:
```ts
selected_custom_fields: selectedCustomFields,
```
- [ ] **Step 5: Repeat Steps 1-4 for `IssuedOrderDetail.tsx` and `InvoiceDetail.tsx`**
Same edits; the company-settings query, edit-gate flag, and save payload all already exist on each page.
- [ ] **Step 6: Typecheck + lint**
Run: `npm run typecheck && npm run lint`
Expected: PASS, 0 lint errors (watch `react-hooks/rules-of-hooks` — the new `useState` must precede any early return).
- [ ] **Step 7: Commit**
```bash
git add src/admin/pages/OfferDetail.tsx src/admin/pages/IssuedOrderDetail.tsx src/admin/pages/InvoiceDetail.tsx
git commit -m "feat(documents): per-document custom-field print picker on offer/issued-order/invoice detail"
```
---
## Task 8: Full verification
- [ ] **Step 1: Run the whole server suite**
Run: `npm test`
Expected: PASS (no regressions; new selected-custom-fields cases green).
- [ ] **Step 2: Typecheck + lint + build**
```bash
npm run typecheck
npm run lint
npm run build
```
Expected: all PASS; client builds.
- [ ] **Step 3: Manual smoke (user-driven, dev server is theirs)**
Ask the user to: open an offer detail with company custom fields defined → tick one field → save → open its PDF and confirm only that field prints in the company block; confirm an untouched/older document prints no custom fields. Repeat for an issued order and an invoice.
- [ ] **Step 4: Final state check**
```bash
git status
git log --oneline -8
```
Expected: clean tree, the feature commits present.
---
## Self-review notes (addressed)
- **Spec coverage:** storage column (T1), encode/decode (T2), schemas (T3), service persist+decode (T4), PDF filter (T5), frontend types+picker (T6), detail-page wiring (T7), tests throughout + full verify (T8). Order confirmations deliberately untouched. ✅
- **Default = none:** `buildAddressLines` filters only when passed an array; the company call always passes the parsed selection (default `[]`), so nothing prints until ticked. Customer/supplier calls omit the param ⇒ unchanged. ✅
- **Positional identity:** indices key off the full `fields` array on both render and picker sides (T5 note, T6 Step 2 note). ✅
- **Type consistency:** `encodeSelectedCustomFields` / `parseSelectedCustomFields` used with identical signatures across services and PDF routes; detail interfaces expose `number[]`. ✅
- **Open confirmations flagged inline** (prisma import path in tests; whether each PDF route narrows its document `select`) — each has a grep-first instruction rather than an assumption.

View File

@@ -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 (0100), 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, 0100
```
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 (0100);
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.

View File

@@ -0,0 +1,211 @@
# Per-document custom-field print selection
**Date:** 2026-06-16
**Status:** Approved design — ready for implementation plan
**Scope:** offers (quotations), issued orders, invoices
---
## Problem
Company custom fields are defined in company settings (`company_settings.custom_fields`,
a JSON blob of `{name, value, showLabel}[]` plus a `field_order`). They render in the
**sender/company block** of document PDFs via `buildAddressLines(settings, …)`.
Today **every** custom field with a value prints on **every** document PDF (offer, issued
order, invoice). The only existing per-field control is the company-settings checkbox
**"Zobrazit název v PDF"** (`showLabel`), which decides whether a printed field shows as
`Name: Value` or just `Value` — it does **not** control whether the field appears at all.
The user wants per-document control: on each offer / issued order / invoice **detail page**,
tick which company custom fields actually print on that specific document's PDF.
## Goals
- Each offer, issued order, and invoice independently selects which company custom fields
print in its PDF sender block.
- Selection lives on the document and is editable on its detail page.
- Default is **none selected** — existing documents and new drafts print no custom fields
until fields are deliberately ticked.
- The company-settings `showLabel` ("Zobrazit název v PDF") checkbox is **unchanged**.
## Non-goals
- Order confirmations ("orders" / `orders-pdf.ts`) are **out of scope** — they keep current
behavior (print all custom fields).
- No change to how custom fields are _defined_ in company settings.
- No stable per-field IDs — selection is **positional** (see Decisions).
## Decisions (locked)
1. **Default = none selected.** Existing rows get `NULL`; new documents start empty. A
document prints custom fields only for the indices it explicitly stores.
2. **Positional identity.** Selection stores field **positions** (`0,1,2…`) matching the
existing `custom_<i>` keys in the PDF code. No settings-structure change, no backfill.
Accepted caveat: reordering/deleting a custom field in company settings can shift what a
saved document's stored indices point at. Low risk — company fields rarely change, and
finalized PDFs are archived on NAS (served as-is, not re-rendered). The user accepted this
over the more robust stable-ID approach.
3. **Scope = 3 document types** (offers, issued orders, invoices). Order confirmations excluded.
4. **`showLabel` retained** in company settings, untouched.
---
## Design
### 1. Data storage
Add one nullable column to each of `quotations`, `issued_orders`, `invoices`:
| Column | Type | Meaning |
| ------------------------ | --------- | ------------------------------------------------------------- |
| `selected_custom_fields` | `VARCHAR` | JSON array of selected indices, e.g. `"[0,2]"`; `NULL` = none |
Stored as JSON-in-text, consistent with the existing `company_settings.custom_fields` /
`customers.custom_fields` pattern. `NULL`/empty ⇒ no custom fields print.
One tracked migration per the project's non-interactive `prisma migrate diff` recipe
(CLAUDE.md). **Apply to `app_test` as well** (`DATABASE_URL=<app_test> npx prisma migrate
deploy`) or the suite breaks. Commit `schema.prisma` + migration folder together.
### 2. Backend — schemas
Add to each document's **Create and Update** Zod schema:
```ts
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
```
Files:
- `src/schemas/offers.schema.ts``CreateQuotationSchema` (Update derives via `.partial().omit()`).
- `src/schemas/issued-orders.schema.ts``CreateIssuedOrderSchema` (Update derives via `.partial().omit()`).
- `src/schemas/invoices.schema.ts` — both `CreateInvoiceSchema` and `UpdateInvoiceSchema`
(invoices define the two schemas separately).
### 3. Backend — services
In each create/update service, persist the field inside the **existing transaction**:
- On write: `selected_custom_fields: Array.isArray(body.selected_custom_fields) &&
body.selected_custom_fields.length > 0 ? JSON.stringify(body.selected_custom_fields) : null`
- No other logic changes; sits alongside the existing header column assignments.
Files: `src/services/offers.service.ts`, `src/services/issued-orders.service.ts`,
`src/services/invoices.service.ts`.
### 4. Backend — detail responses
The detail endpoints spread the document row. Decode the stored string back into a
`number[]` so the frontend receives a clean array (default `[]` when `NULL`/malformed —
malformed JSON degrades gracefully with a logged warning, per the error convention). Add
`selected_custom_fields: number[]` to the corresponding detail interfaces in
`src/admin/lib/queries/{offers,issued-orders,invoices}.ts`.
### 5. PDF rendering
In each of `offers-pdf.ts`, `issued-orders-pdf.ts`, `invoices-pdf.ts`, extend the
company-block `buildAddressLines()` with an optional parameter:
```ts
buildAddressLines(entity, isSupplier, t, selectedCustomFields?: number[] | null)
```
When building `fieldMap`, only emit a `custom_<i>` entry when `selectedCustomFields`
includes `i`. Behavior:
- `null` / `undefined` / empty array ⇒ **no** custom lines (the new default).
- Standard address lines (name, street, city/postal, country, IČO/`company_id`,
DIČ/`vat_id`) are **unaffected** — always built as today.
- For the custom fields that _are_ selected, the existing `showLabel` (`Name: Value` vs
`Value`) and `field_order` ordering logic is preserved unchanged.
Only the **company/sender** block is filtered (that's where company custom fields render).
The customer block (offers/invoices) and supplier block (issued orders) keep their own
custom-field behavior unchanged — those come from `customers`/`sklad_suppliers`, not company
settings, and are not in scope.
The PDF route reads the document's `selected_custom_fields` column, parses it to `number[]`,
and passes it into `buildAddressLines(settings, …, selected)`.
> Archived-PDF note: finalized/numbered documents serve their archived NAS copy and won't
> change retroactively. Drafts (and any forced re-render) reflect the current selection.
### 6. Frontend — shared picker component
New shared component under `src/admin/components/document/` (e.g.
`CustomFieldsPrintPicker.tsx`), reused by all three detail pages (extend the shared module,
don't fork three copies — per CLAUDE.md document-module conventions).
Props (shape): the parsed company custom fields (`{name, value}[]` from
`companySettings.custom_fields`), the current selected indices, an `onChange`, and a
`disabled` flag.
Behavior:
- Renders a checkbox per company custom field; label shows the field's name (and/or value)
so the user knows what each is.
- Bound to local state on the detail page, seeded from the document's
`selected_custom_fields`.
- Hidden/empty when the company has no custom fields defined.
- Respects edit-lock and editable-status rules: read-only (`disabled`) when the document
isn't editable or is locked by another user, matching how the rest of the header fields
behave on that page.
- Included in the page's save payload as `selected_custom_fields: number[]`.
Pages: `src/admin/pages/OfferDetail.tsx`, `IssuedOrderDetail.tsx`, `InvoiceDetail.tsx` —
each already loads `companySettingsOptions()`, so the field definitions are available with
no new query.
Placement: in the editable header/meta area of each detail page, near the other
document-level settings (currency/language/etc.).
---
## Data flow
```
Company settings: custom_fields = [{name:"Tel.",…}, {name:"Web",…}, {name:"Datová schránka",…}]
idx 0 idx 1 idx 2
Offer detail page → user ticks "Tel." and "Datová schránka"
→ save payload selected_custom_fields: [0, 2]
→ service stores quotations.selected_custom_fields = "[0,2]"
Offer PDF render
→ read column "[0,2]" → [0,2]
→ buildAddressLines(settings, …, [0,2])
→ fieldMap emits custom_0 ("Tel.: …") and custom_2 ("Datová schránka: …"), skips custom_1
→ sender block prints Tel. and Datová schránka only
```
## Testing
Server-side Vitest against `app_test` (no Prisma mocking; mock Puppeteer/NAS only):
- Create/update each document with `selected_custom_fields` → column persists the JSON
string; empty/omitted → `NULL`.
- Detail response decodes to `number[]` (and `[]` for `NULL`).
- Schema: non-integer / negative entries rejected; omitted is valid.
- PDF: with a stubbed `html-to-pdf`, assert the rendered company block includes only the
selected custom field lines and still includes standard address lines; empty selection ⇒
no custom lines; standard lines unaffected.
- Regression: customer/supplier custom fields still render regardless of company selection.
## Migration & rollout
- One migration adding the three columns (all default `NULL`), applied to dev `app` and
`app_test`.
- No data backfill (none-selected default is the intended post-ship state).
- No production PDF changes for already-archived documents.
## Affected files (reference)
- `prisma/schema.prisma` (+ new migration folder)
- `src/schemas/offers.schema.ts`, `issued-orders.schema.ts`, `invoices.schema.ts`
- `src/services/offers.service.ts`, `issued-orders.service.ts`, `invoices.service.ts`
- `src/routes/admin/offers-pdf.ts`, `issued-orders-pdf.ts`, `invoices-pdf.ts`
- (detail route handlers, if decoding is done there rather than in the service)
- `src/admin/lib/queries/offers.ts`, `issued-orders.ts`, `invoices.ts`
- `src/admin/components/document/CustomFieldsPrintPicker.tsx` (new)
- `src/admin/pages/OfferDetail.tsx`, `IssuedOrderDetail.tsx`, `InvoiceDetail.tsx`

View File

@@ -0,0 +1,96 @@
# Status quick actions + project⇄order sync
**Date:** 2026-07-04 · **Status:** Approved (interactive design w/ owner) · **Scope:** offers, received orders, projects
## Problem
Status changes are inconsistent: the Invoices list has a quick chip action (click → confirm → paid),
but Offers/ReceivedOrders/Projects tables have inert chips — every change needs the detail page.
ProjectDetail edits status via a free combobox in the form (no transitions, no confirm), unlike
OfferDetail/OrderDetail's transition buttons. Projects have **no status machine at all** (free-text
column). Order→project completion sync exists one-way (`syncProjectStatus`), but finishing a
**project** leaves its linked order untouched.
## Decisions (owner)
1. **Chip opens a menu** of valid next states (not single-click-advance) → ConfirmDialog per pick,
danger styling + cascade notes on destructive/irreversible ones.
2. **Reopen allowed**: `dokonceny/zruseny → aktivni` (projects), `dokoncena/stornovana → v_realizaci`
(received orders). **Reopening never cascades** to the linked record.
3. **Sync scope: finish + cancel, both directions.** Project `dokonceny` ⇄ order `dokoncena`;
project `zruseny` ⇄ order `stornovana`.
4. Offers quick menu: `Aktivovat` (draft — same number-assignment + PDF-archive semantics as the
detail), `Zneplatnit` (danger), and **"Vytvořit objednávku…" which opens the existing
create-order modal** (never a raw label flip to `ordered` — that state is owned by the
create-order flow).
## Design
### Backend
**Projects gain a status machine** (`src/services/projects.service.ts`):
`VALID_TRANSITIONS = { aktivni: [dokonceny, zruseny], dokonceny: [aktivni], zruseny: [aktivni] }`.
`updateProject` validates status changes (token `invalid_transition` → Czech 400 in the route);
a legacy/unknown current status may transition to any canonical value (tolerant). `getProject`
returns `valid_transitions` (same contract as offers/orders).
**Project → order cascade** (new), inside one transaction with the project update:
- project → `dokonceny` ⇒ linked order → `dokoncena` **iff** order status ∈ {prijata, v_realizaci}
- project → `zruseny` ⇒ linked order → `stornovana` **iff** order status ∈ {prijata, v_realizaci}
- reopen ⇒ no order change; completed/cancelled orders are never resurrected by a cascade
- direct `tx` write (no service recursion); sibling projects of the same order are NOT touched
(multi-project orders are a rare schema possibility, not a flow; avoid surprise mass updates)
- the service returns what cascaded so the route writes an audit row for the order change too
**Received orders** (`src/services/orders.service.ts`):
- `VALID_TRANSITIONS` gains reopen: `dokoncena: [v_realizaci]`, `stornovana: [v_realizaci]`
- `syncProjectStatus` becomes reopen-aware: given the previous status, a transition OUT of a
terminal state (reopen) skips project sync entirely (decision 2). Forward transitions keep the
existing mapping (v_realizaci→aktivni no-op in practice, dokoncena→dokonceny,
stornovana→zruseny), and the cascaded project change now gets an audit row.
- item/section edit guards stay status-based, so a reopened order is editable again (intended).
No DB migration (status columns are strings already).
### Frontend
**Shared `StatusChipMenu`** (`src/admin/components/StatusChipMenu.tsx`): renders a `StatusChip`;
click opens a small MUI `Menu` of actions; each action either opens a `ConfirmDialog`
(danger variant + `loading` during the request; cascade note in the message) or runs a plain
`onClick` (the modal-opening offer item). Hidden affordance fixed via `title` tooltip. Chip is
plain (non-clickable) when the user lacks the edit permission or no actions exist.
**Offers list**: draft → `Aktivovat` (confirm notes the number assignment; after success the same
fire-and-forget PDF-archive call the detail does); active → `Vytvořit objednávku…` (opens the
existing modal) + `Zneplatnit` (danger); ordered → `Zneplatnit` (danger).
**ReceivedOrders list**: prijata → `Zahájit realizaci`, `Stornovat` (danger, note: linked project
will be cancelled); v_realizaci → `Dokončit` (note: linked project will be completed),
`Stornovat` (danger); dokoncena/stornovana → `Obnovit` (reopen, no cascade note).
**Projects list**: aktivni → `Dokončit` (note when `order_id` present: linked order will be
completed), `Zrušit` (danger, order-storno note); dokonceny/zruseny → `Obnovit`.
**ProjectDetail**: status `Select` removed from the form (and status removed from the save
payload); header gains transition buttons rendered from `valid_transitions`
(`Dokončit projekt` / `Zrušit projekt` danger / `Obnovit projekt`), each via ConfirmDialog with
cascade notes, as a status-only PUT with its own mutation
(invalidate: projects, orders, offers, invoices, warehouse). OrderDetail keeps its pattern;
its transition label shows `Obnovit` when reopening from a terminal state.
Invalidation for all new status mutations: `["orders","offers","projects","invoices"]`
(+`["warehouse"]` on project mutations, matching the page's existing set).
### Tests
Service-level (real `app_test` DB): project transition validation (all legal/illegal edges incl.
legacy-status tolerance), project→order cascade both mappings + the guard (no cascade onto
dokoncena/stornovana orders), reopen-no-cascade both directions, order reopen transitions, and
regression: order→project sync still fires on forward transitions.
## Out of scope
Offer machine changes (unchanged: draft→active→ordered/invalidated), issued orders, sibling-project
propagation, ReceivedOrders detail-page button changes beyond the automatic reopen button.

View File

@@ -19,7 +19,7 @@
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="shortcut icon" href="/favicon.ico" />
<title>Admin</title>
<title>BOHA Admin</title>
</head>
<body>
<div id="root"></div>

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "app-ts",
"version": "2.4.35",
"version": "2.4.44",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "app-ts",
"version": "2.4.35",
"version": "2.4.44",
"license": "ISC",
"dependencies": {
"@anthropic-ai/sdk": "^0.102.0",

View File

@@ -1,6 +1,6 @@
{
"name": "app-ts",
"version": "2.4.35",
"version": "2.4.44",
"description": "",
"main": "dist/server.js",
"scripts": {

View File

@@ -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;

View File

@@ -0,0 +1,9 @@
-- AlterTable
ALTER TABLE `invoices` ADD COLUMN `selected_custom_fields` VARCHAR(255) NULL;
-- AlterTable
ALTER TABLE `issued_orders` ADD COLUMN `selected_custom_fields` VARCHAR(255) NULL;
-- AlterTable
ALTER TABLE `quotations` ADD COLUMN `selected_custom_fields` VARCHAR(255) NULL;

View File

@@ -208,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")
@@ -238,6 +239,7 @@ model invoices {
billing_text String? @db.VarChar(500)
language String? @default("cs") @db.VarChar(5)
internal_notes String? @db.Text
selected_custom_fields String? @db.VarChar(255)
created_at DateTime? @default(now()) @db.DateTime(0)
modified_at DateTime? @db.DateTime(0)
invoice_items invoice_items[]
@@ -392,6 +394,7 @@ model issued_orders {
language String? @default("cs") @db.VarChar(5)
order_text String? @db.VarChar(500)
internal_notes String? @db.Text
selected_custom_fields String? @db.VarChar(255)
locked_by Int?
locked_at DateTime? @db.DateTime(0)
created_at DateTime? @default(now()) @db.DateTime(0)
@@ -505,6 +508,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")
@@ -525,6 +529,7 @@ model quotations {
status String @default("active") @db.VarChar(20)
scope_title String? @db.VarChar(500)
scope_description String? @db.Text
selected_custom_fields String? @db.VarChar(255)
locked_by Int?
locked_at DateTime? @db.DateTime(0)
modified_at DateTime? @db.DateTime(0)

View File

@@ -337,7 +337,7 @@ exports[`buildUserSectionHtml > produces a stable per-user section (full output
</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>
<span class="summary-value">8,00h</span>
</div>
<div class="summary-row">
<span class="summary-label">Dovolená:</span>
@@ -345,7 +345,7 @@ exports[`buildUserSectionHtml > produces a stable per-user section (full output
</div>
<div class="summary-row">
<span class="summary-label">Přesčas:</span>
<span class="summary-value">8,00h</span>
<span class="summary-value">0,00h</span>
</div>
<div class="summary-row">
<span class="summary-label">Svátek:</span>

View File

@@ -0,0 +1,46 @@
import { describe, it, expect, beforeEach } from "vitest";
import {
reportServerVersion,
subscribeNewVersion,
getNewVersion,
BUILD_VERSION,
__resetVersionStateForTest,
} from "../admin/utils/appVersion";
/**
* Client store backing the "new version available" banner. The server stamps
* X-App-Version on every response; apiFetch feeds it here. A version that
* differs from the one baked into THIS bundle (BUILD_VERSION) means a deploy
* happened → latch it and notify subscribers (the banner).
*/
describe("appVersion store", () => {
beforeEach(() => __resetVersionStateForTest());
it("ignores the same version, empty, or null", () => {
reportServerVersion(BUILD_VERSION);
reportServerVersion("");
reportServerVersion(null);
reportServerVersion(undefined);
expect(getNewVersion()).toBeNull();
});
it("latches + notifies once when the server reports a different version", () => {
let notified = 0;
const unsub = subscribeNewVersion(() => {
notified++;
});
reportServerVersion(`${BUILD_VERSION}-next`);
expect(getNewVersion()).toBe(`${BUILD_VERSION}-next`);
expect(notified).toBe(1);
// Idempotent: once a new version is known, further reports don't re-notify
// or overwrite (the banner is already showing).
reportServerVersion("99.0.0");
expect(getNewVersion()).toBe(`${BUILD_VERSION}-next`);
expect(notified).toBe(1);
unsub();
});
});

View File

@@ -0,0 +1,176 @@
import { describe, it, expect } from "vitest";
import { computeMzdaSummary } from "../admin/utils/attendanceHelpers";
import { buildUserSectionHtml } from "../admin/hooks/useAttendanceAdmin";
/**
* Payroll recap spec (accountant notes, confirmed by the owner 2026-07):
* - Odpracováno = all worked hours EXCEPT hours worked on holidays
* - Vč. svátků a přesčasů = ALL worked hours (so line2 line1 = Svátek)
* - Dovolená = Σ vacation leave_hours (hour-based)
* - Přesčas = max(0, worked fond) — month-level, never negative
* - Svátek = hours actually WORKED on public-holiday dates
* - So/Ne = worked hours on Sat/Sun
* - Fond = MonFri (holidays included) × 8 h
* June 2026: 22 workdays, no holidays → fond 176.
* July 2026: 23 MonFri days (6.7. Monday holiday counted; 5.7. is Sunday) → fond 184.
*/
const work = (
day: string,
from: string,
to: string,
brk?: [string, string],
) => ({
shift_date: `${day}T02:00:00`,
arrival_time: `${day}T${from}:00`,
departure_time: `${day}T${to}:00`,
break_start: brk ? `${day}T${brk[0]}:00` : null,
break_end: brk ? `${day}T${brk[1]}:00` : null,
leave_type: "work",
});
const vacation = (day: string, hours: number) => ({
shift_date: `${day}T02:00:00`,
leave_type: "vacation",
leave_hours: hours,
arrival_time: null,
departure_time: null,
break_start: null,
break_end: null,
});
const JUNE_WORKDAYS = [
"01",
"02",
"03",
"04",
"05",
"08",
"09",
"10",
"11",
"12",
"15",
"16",
"17",
"18",
"19",
"22",
"23",
"24",
"25",
"26",
"29",
"30",
].map((d) => `2026-06-${d}`);
describe("computeMzdaSummary — accountant spec", () => {
it("single 3h day: worked 3, no overtime (173h below fond)", () => {
const s = computeMzdaSummary(
[work("2026-06-02", "09:00", "12:00")],
"2026-06",
);
expect(s.odpracovano).toBe(3);
expect(s.vcetneSvatku).toBe(3);
expect(s.prescas).toBe(0);
expect(s.fund).toBe(176);
});
it("accountant's Přesčas example: +3h one day, 2h elsewhere → 1h overtime", () => {
const recs = JUNE_WORKDAYS.slice(0, 20).map((d) =>
work(d, "08:00", "16:30", ["12:00", "12:30"]),
); // 20 × 8h
recs.push(work("2026-06-29", "08:00", "14:00")); // 6h (2h short)
recs.push(work("2026-06-30", "08:00", "19:30", ["12:00", "12:30"])); // 11h (+3h)
const s = computeMzdaSummary(recs, "2026-06");
expect(s.vcetneSvatku).toBe(177);
expect(s.prescas).toBe(1);
});
it("accountant's Svátek example: 10h worked on 6.7. → Svátek 10; excluded from Odpracováno", () => {
const julyWorkdays = [
"01",
"02",
"03",
"07",
"08",
"09",
"10",
"13",
"14",
"15",
"16",
"17",
"20",
"21",
"22",
"23",
"24",
"27",
"28",
"29",
"30",
"31",
].map((d) => `2026-07-${d}`);
const recs = julyWorkdays.map((d) =>
work(d, "08:00", "16:30", ["12:00", "12:30"]),
); // 22 × 8h
recs.push(work("2026-07-06", "08:00", "18:30", ["12:00", "12:30"])); // holiday, 10h
const s = computeMzdaSummary(recs, "2026-07");
expect(s.fund).toBe(184); // 23 MonFri days incl. the Monday holiday
expect(s.svatekHours).toBe(10);
expect(s.vcetneSvatku).toBe(186); // all worked hours
expect(s.odpracovano).toBe(176); // minus the holiday-worked 10h
expect(s.prescas).toBe(2); // max(0, 186 184) — never negative
});
it("vacation does NOT flow into Přesčas (worked-hours-only rule)", () => {
const recs: ReturnType<typeof work | typeof vacation>[] =
JUNE_WORKDAYS.slice(0, 21).map((d) =>
work(d, "08:00", "16:30", ["12:00", "12:30"]),
); // 21 × 8 = 168
recs.push(vacation("2026-06-30", 8));
const s = computeMzdaSummary(recs, "2026-06");
expect(s.vacationHours).toBe(8);
expect(s.prescas).toBe(0); // 168 worked < 176 fond — vacation doesn't count
});
it("partial-day vacation next to a work shift on the same day (5h work + 3h vacation)", () => {
const recs = [
work("2026-06-02", "08:00", "13:00"), // 5h
vacation("2026-06-02", 3),
];
const s = computeMzdaSummary(recs, "2026-06");
expect(s.odpracovano).toBe(5);
expect(s.vacationHours).toBe(3);
});
it("weekend hours count into So/Ne and into worked totals", () => {
const s = computeMzdaSummary(
[work("2026-06-06", "08:00", "12:00")], // Saturday 4h
"2026-06",
);
expect(s.weekendHours).toBe(4);
expect(s.odpracovano).toBe(4);
});
});
describe("print day table — multiple records on one day", () => {
it("renders one row per record (two shifts are both visible)", () => {
const records = [
work("2026-06-02", "06:00", "10:00"),
work("2026-06-02", "14:00", "18:00"),
];
const totalMins = 8 * 60;
const html = buildUserSectionHtml(
"1",
{ name: "Test", minutes: totalMins, vacation_hours: 0, records } as never,
{ month: "2026-06", month_name: "Červen 2026", user_totals: {} } as never,
);
// Both shifts appear, each with its own arrival time.
expect(html).toContain("06:00");
expect(html).toContain("14:00");
// Two rows dated 2. 6.
const rows = html.match(/<td>2\. 6\. 2026<\/td>/g) || [];
expect(rows.length).toBe(2);
});
});

View File

@@ -0,0 +1,77 @@
import { describe, it, expect } from "vitest";
import {
getCzechWeekday,
isWeekendDate,
formatTimeOrDatetimePrint,
} from "../admin/utils/attendanceHelpers";
import { formatDate } from "../admin/utils/formatters";
/**
* Regression: the attendance admin print builds its day rows from date-ONLY
* strings ("2026-06-01"). `new Date("YYYY-MM-DD")` is UTC midnight per the
* ECMAScript spec, so formatting it with local getters rendered the PREVIOUS
* day for viewers west of UTC — a June print opened with "31. 5. 2026 Neděle"
* (a May row) and every weekday name was shifted by one. The helpers now
* parse the calendar day from the string parts, which is timezone-proof by
* construction: these assertions hold in EVERY zone (on a machine west of
* UTC the old implementation fails them).
*/
describe("attendance print — timezone-proof date rendering", () => {
it("formatDate renders a date-only string as that exact calendar day", () => {
expect(formatDate("2026-06-01")).toBe("1. 6. 2026");
expect(formatDate("2026-06-30")).toBe("30. 6. 2026");
});
it("formatDate keeps naive-datetime (wire format) behavior", () => {
expect(formatDate("2026-06-01T02:00:00")).toBe("1. 6. 2026");
});
it("getCzechWeekday names the string's own calendar day", () => {
expect(getCzechWeekday("2026-06-01")).toBe("Pondělí");
expect(getCzechWeekday("2026-06-06")).toBe("Sobota");
expect(getCzechWeekday("2026-06-07")).toBe("Neděle");
// naive-datetime wire format resolves to the same day
expect(getCzechWeekday("2026-06-01T02:00:00")).toBe("Pondělí");
});
it("isWeekendDate flags the string's own calendar day", () => {
expect(isWeekendDate("2026-06-06")).toBe(true); // Saturday
expect(isWeekendDate("2026-06-07")).toBe(true); // Sunday
expect(isWeekendDate("2026-06-01")).toBe(false); // Monday
expect(isWeekendDate("2026-06-06T02:00:00")).toBe(true);
});
it("agrees with a locally-constructed date in the current zone (guards a regression to UTC parsing)", () => {
// Local construction is the ground truth for "calendar day" in any zone.
const local = new Date(2026, 5, 1, 12).toLocaleDateString("cs-CZ", {
weekday: "long",
});
const expected = local.charAt(0).toUpperCase() + local.slice(1);
expect(getCzechWeekday("2026-06-01")).toBe(expected);
});
});
describe("attendance print — overnight date prefix on time cells", () => {
// shift_date arrives as a naive datetime on the wire ("2026-06-01T02:00:00");
// the guard used to compare it raw against the extracted date part, so the
// overnight-only "d.m." prefix fired on EVERY cell ("1.6. 08:00").
const wireShiftDate = "2026-06-01T02:00:00";
it("same-day punch renders time only", () => {
expect(
formatTimeOrDatetimePrint("2026-06-01T08:00:00", wireShiftDate),
).toBe("08:00");
});
it("overnight punch keeps the date prefix", () => {
expect(
formatTimeOrDatetimePrint("2026-06-02T01:30:00", wireShiftDate),
).toBe("2.6. 01:30");
});
it("date-only shiftDate also matches", () => {
expect(formatTimeOrDatetimePrint("2026-06-01T08:00:00", "2026-06-01")).toBe(
"08:00",
);
});
});

View File

@@ -87,7 +87,9 @@ describe("issued-order drafts — deferred numbering", () => {
it("finalizing a draft (draft -> sent) assigns the next sequence number", async () => {
const expected = (await previewIssuedOrderNumber()).number;
const draft = await createIssuedOrder({});
const draft = await createIssuedOrder({
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
if ("error" in draft)
throw new Error(`createIssuedOrder failed: ${draft.error}`);
issuedOrderIds.push(draft.id);
@@ -104,7 +106,9 @@ describe("issued-order drafts — deferred numbering", () => {
});
it("finalizing is idempotent — re-finalizing does not re-number", async () => {
const draft = await createIssuedOrder({});
const draft = await createIssuedOrder({
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
if ("error" in draft)
throw new Error(`createIssuedOrder failed: ${draft.error}`);
issuedOrderIds.push(draft.id);

View File

@@ -169,7 +169,10 @@ describe("createIssuedOrder", () => {
it("numbers immediately when created already-finalized (status sent)", async () => {
const before = (await previewIssuedOrderNumber()).number;
const order = await mkIssued({ status: "sent" });
const order = await mkIssued({
status: "sent",
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
expect(order.po_number).toBe(before);
expect(order.status).toBe("sent");
});
@@ -199,7 +202,9 @@ describe("createIssuedOrder", () => {
describe("updateIssuedOrder status transitions", () => {
it("allows draft -> sent and rejects draft -> completed", async () => {
const order = await mkIssued({});
const order = await mkIssued({
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
const ok = await updateIssuedOrder(order.id, { status: "sent" });
expect("error" in ok).toBe(false);
const bad = await updateIssuedOrder(order.id, { status: "completed" });
@@ -226,7 +231,9 @@ describe("updateIssuedOrder status transitions", () => {
});
it("status-only transition payloads still work when not editable", async () => {
const order = await mkIssued({});
const order = await mkIssued({
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
await updateIssuedOrder(order.id, { status: "sent" });
await updateIssuedOrder(order.id, { status: "confirmed" });
const res = await updateIssuedOrder(order.id, { status: "completed" });
@@ -242,6 +249,44 @@ describe("updateIssuedOrder status transitions", () => {
const res = await updateIssuedOrder(order.id, { supplier_id: 99999999 });
expect("error" in res && res.error).toBe("supplier_not_found");
});
it("finalizes a sections-only order (no items) successfully", async () => {
const order = await mkIssued({});
const res = await updateIssuedOrder(order.id, {
status: "sent",
items: [],
sections: [
{ title: "Scope", title_cz: "Rozsah prací", content: "<p>Detail</p>" },
],
});
expect("error" in res).toBe(false);
const row = await prisma.issued_orders.findUnique({
where: { id: order.id },
});
expect(row!.status).toBe("sent");
expect(row!.po_number).toBeTruthy();
});
it("rejects finalizing a completely blank order (no items, no sections)", async () => {
const order = await mkIssued({});
const res = await updateIssuedOrder(order.id, {
status: "sent",
items: [],
sections: [],
});
expect("error" in res && res.error).toBe("empty_document");
// Stays a draft — the finalize was rejected before any write.
const row = await prisma.issued_orders.findUnique({
where: { id: order.id },
});
expect(row!.status).toBe("draft");
expect(row!.po_number).toBeNull();
});
it("rejects creating a non-draft order with no content", async () => {
const res = await createIssuedOrder({ status: "sent" });
expect("error" in res && res.error).toBe("empty_document");
});
});
describe("getIssuedOrder", () => {
@@ -525,7 +570,9 @@ describe("POST /api/admin/issued-orders legacy dropped fields", () => {
describe("PUT /api/admin/issued-orders/:id editable-state guard (HTTP)", () => {
it("400s a field edit on a confirmed order with the explicit Czech message", async () => {
const order = await mkIssued({});
const order = await mkIssued({
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
await updateIssuedOrder(order.id, { status: "sent" });
await updateIssuedOrder(order.id, { status: "confirmed" });
@@ -543,7 +590,9 @@ describe("PUT /api/admin/issued-orders/:id editable-state guard (HTTP)", () => {
// 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({});
const order = await mkIssued({
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
await updateIssuedOrder(order.id, { status: "sent" });
const res = await app!.inject({
@@ -574,7 +623,9 @@ describe("PUT /api/admin/issued-orders/:id editable-state guard (HTTP)", () => {
});
it("a status-only transition payload keeps working (confirmed -> completed)", async () => {
const order = await mkIssued({});
const order = await mkIssued({
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
});
await updateIssuedOrder(order.id, { status: "sent" });
await updateIssuedOrder(order.id, { status: "confirmed" });
@@ -733,6 +784,23 @@ describe("renderIssuedOrderHtml", () => {
expect(html).toContain("Odběratel");
});
it("omits the items table and total when there are no items (sections-only order)", () => {
const html = renderIssuedOrderHtml(
order,
[],
supplier,
{ company_name: "Naše firma" },
"cs",
issuer,
[{ title: "Scope", title_cz: "Rozsah prací", content: "<p>Detail</p>" }],
);
// The section renders…
expect(html).toContain("Rozsah prací");
// …but the items table, the billing heading and the total row do not.
expect(html).not.toContain('class="items"');
expect(html).not.toContain("Celkem bez DPH");
});
it("renders the structured supplier address plus IČO and DIČ", () => {
const html = renderIssuedOrderHtml(
order,

View 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");
});
});

View 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 0100, default to 0 when absent, and reject out-of-range values.
*/
describe("offer item discount schema", () => {
it("accepts a 0100 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 0100 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);
});
});

View 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
});
});

View 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);
});
});

View File

@@ -196,6 +196,31 @@ describe("order attachment payload hygiene", () => {
expect(withoutDetail!.attachment_name).toBeNull();
});
it("PUT /:id accepts the canonical storno token through the Zod layer", async () => {
// Regression: UpdateOrderSchema carried a phantom "zrusena" enum member
// until 2026-07, so { status: "stornovana" } 400ed at parseBody with a
// raw English Zod message. Service-level tests bypass the schema — this
// must stay a route-level test.
const customer = await makeCustomer();
const res = await createOrder({
...baseOrder,
customer_id: customer.id,
create_project: false,
});
if (!("id" in res)) failResult(res);
createdOrderIds.push(res.id!);
const put = await app.inject({
method: "PUT",
url: `/api/admin/orders/${res.id}`,
headers: { authorization: `Bearer ${adminToken}` },
payload: { status: "stornovana" },
});
expect(put.statusCode).toBe(200);
const row = await prisma.orders.findUnique({ where: { id: res.id! } });
expect(row!.status).toBe("stornovana");
});
it("HTTP list/detail JSON carries no attachment_data; /attachment still serves the binary", async () => {
const { withId, withoutId } = await makeOrderPair();
const headers = { authorization: `Bearer ${adminToken}` };

View File

@@ -0,0 +1,301 @@
import { describe, it, expect, afterEach, afterAll } from "vitest";
import prisma from "../config/database";
import {
updateProject,
getProject,
VALID_TRANSITIONS as PROJECT_VALID_TRANSITIONS,
} from "../services/projects.service";
import { updateOrder } from "../services/orders.service";
/**
* Bidirectional project⇄order status sync (spec 2026-07-04):
* - projects gain a status machine (aktivni ⇄ dokonceny/zruseny) with
* legacy-status tolerance,
* - finishing/cancelling a project cascades onto its linked OPEN order
* (prijata/v_realizaci) — terminal orders are never touched,
* - reopen (project → aktivni, order → v_realizaci) is now a legal
* transition and NEVER cascades,
* - regression: the existing order→project forward sync stays intact.
*
* Real app_test DB via the service layer (suite convention). Fixtures use a
* unique prefix; projects are created without project_number so getProject's
* NAS folder probe is skipped.
*/
const N = "posync_";
const createdProjectIds: number[] = [];
const createdOrderIds: number[] = [];
let seq = 0;
async function mkOrder(status: string) {
const order = await prisma.orders.create({
data: { order_number: `${N}${Date.now()}_${seq++}`, status },
});
createdOrderIds.push(order.id);
return order;
}
async function mkProject(status: string, orderId?: number) {
const project = await prisma.projects.create({
data: { name: `${N}project_${seq++}`, status, order_id: orderId ?? null },
});
createdProjectIds.push(project.id);
return project;
}
// FK-safe order: projects reference orders (Restrict), so projects go first.
afterEach(async () => {
await prisma.projects.deleteMany({
where: { id: { in: createdProjectIds } },
});
await prisma.orders.deleteMany({ where: { id: { in: createdOrderIds } } });
createdProjectIds.length = 0;
createdOrderIds.length = 0;
});
afterAll(async () => {
await prisma.$disconnect();
});
function assertOk<T>(
res: T,
): asserts res is Exclude<T, null | { error: unknown }> {
if (!res || (typeof res === "object" && "error" in res)) {
throw new Error(`expected success, got ${JSON.stringify(res)}`);
}
}
describe("project → order cascade (updateProject)", () => {
it("aktivni→dokonceny completes a linked v_realizaci order and returns synced_order", async () => {
const order = await mkOrder("v_realizaci");
const project = await mkProject("aktivni", order.id);
const res = await updateProject(project.id, { status: "dokonceny" });
assertOk(res);
expect(res.synced_order).toEqual({
id: order.id,
order_number: order.order_number,
from: "v_realizaci",
to: "dokoncena",
});
expect(res.old_status).toBe("aktivni");
const freshOrder = await prisma.orders.findUnique({
where: { id: order.id },
});
expect(freshOrder?.status).toBe("dokoncena");
const freshProject = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(freshProject?.status).toBe("dokonceny");
});
it("aktivni→zruseny cancels a linked prijata order", async () => {
const order = await mkOrder("prijata");
const project = await mkProject("aktivni", order.id);
const res = await updateProject(project.id, { status: "zruseny" });
assertOk(res);
expect(res.synced_order).toEqual({
id: order.id,
order_number: order.order_number,
from: "prijata",
to: "stornovana",
});
const freshOrder = await prisma.orders.findUnique({
where: { id: order.id },
});
expect(freshOrder?.status).toBe("stornovana");
});
it("guard: never resurrects a terminal order (stornovana stays stornovana)", async () => {
const order = await mkOrder("stornovana");
const project = await mkProject("aktivni", order.id);
const res = await updateProject(project.id, { status: "dokonceny" });
assertOk(res);
expect(res.synced_order).toBeNull();
const freshOrder = await prisma.orders.findUnique({
where: { id: order.id },
});
expect(freshOrder?.status).toBe("stornovana");
const freshProject = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(freshProject?.status).toBe("dokonceny");
});
it("reopen (dokonceny→aktivni) never touches the linked order", async () => {
const order = await mkOrder("dokoncena");
const project = await mkProject("dokonceny", order.id);
const res = await updateProject(project.id, { status: "aktivni" });
assertOk(res);
expect(res.synced_order).toBeNull();
const freshOrder = await prisma.orders.findUnique({
where: { id: order.id },
});
expect(freshOrder?.status).toBe("dokoncena");
const freshProject = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(freshProject?.status).toBe("aktivni");
});
it("no linked order → no cascade, synced_order null", async () => {
const project = await mkProject("aktivni");
const res = await updateProject(project.id, { status: "dokonceny" });
assertOk(res);
expect(res.synced_order).toBeNull();
});
});
describe("project status machine (updateProject validation)", () => {
it("rejects dokonceny→zruseny with the invalid_transition token", async () => {
const project = await mkProject("dokonceny");
const res = await updateProject(project.id, { status: "zruseny" });
expect(res && "error" in res && res.error).toBe("invalid_transition");
expect(res).toMatchObject({
currentStatus: "dokonceny",
newStatus: "zruseny",
});
// Nothing was written.
const fresh = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(fresh?.status).toBe("dokonceny");
});
it("legacy tolerance: an unknown current status may move to any canonical target", async () => {
const project = await mkProject("stary");
const res = await updateProject(project.id, { status: "dokonceny" });
assertOk(res);
const fresh = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(fresh?.status).toBe("dokonceny");
});
it("legacy tolerance still rejects a non-canonical target", async () => {
const project = await mkProject("stary");
const res = await updateProject(project.id, { status: "nesmysl" });
expect(res && "error" in res && res.error).toBe("invalid_transition");
});
it("status-unchanged payloads pass without transition validation", async () => {
const project = await mkProject("dokonceny");
const res = await updateProject(project.id, {
status: "dokonceny",
notes: `${N}note`,
});
assertOk(res);
});
});
describe("order reopen + order → project sync (updateOrder)", () => {
it("dokoncena→v_realizaci is now valid and skips project sync (reopen)", async () => {
const order = await mkOrder("dokoncena");
const project = await mkProject("dokonceny", order.id);
const res = await updateOrder(order.id, { status: "v_realizaci" });
expect("error" in res).toBe(false);
if ("error" in res) throw new Error(res.error);
expect(res.synced_projects).toEqual([]);
const freshOrder = await prisma.orders.findUnique({
where: { id: order.id },
});
expect(freshOrder?.status).toBe("v_realizaci");
// Reopen never cascades — the project keeps its terminal status.
const freshProject = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(freshProject?.status).toBe("dokonceny");
});
it("stornovana→v_realizaci is valid too; other exits from terminal stay rejected", async () => {
const order = await mkOrder("stornovana");
const res = await updateOrder(order.id, { status: "v_realizaci" });
expect("error" in res).toBe(false);
const back = await mkOrder("dokoncena");
const rejected = await updateOrder(back.id, { status: "prijata" });
expect("error" in rejected).toBe(true);
if ("error" in rejected) {
expect(rejected.status).toBe(400);
expect(rejected.error).toContain("Neplatný přechod stavu");
}
});
it("regression: v_realizaci→dokoncena still completes the linked project and reports it", async () => {
const order = await mkOrder("v_realizaci");
const project = await mkProject("aktivni", order.id);
const res = await updateOrder(order.id, { status: "dokoncena" });
expect("error" in res).toBe(false);
if ("error" in res) throw new Error(res.error);
expect(res.synced_projects).toEqual([
{
id: project.id,
project_number: null,
from: "aktivni",
to: "dokonceny",
},
]);
const freshProject = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(freshProject?.status).toBe("dokonceny");
});
it("regression: prijata→stornovana still cancels the linked project", async () => {
const order = await mkOrder("prijata");
const project = await mkProject("aktivni", order.id);
const res = await updateOrder(order.id, { status: "stornovana" });
expect("error" in res).toBe(false);
if ("error" in res) throw new Error(res.error);
expect(res.synced_projects).toHaveLength(1);
const freshProject = await prisma.projects.findUnique({
where: { id: project.id },
});
expect(freshProject?.status).toBe("zruseny");
});
});
describe("getProject valid_transitions", () => {
it("matches the machine for canonical statuses", async () => {
const active = await mkProject("aktivni");
expect((await getProject(active.id))?.valid_transitions).toEqual(
PROJECT_VALID_TRANSITIONS["aktivni"],
);
expect((await getProject(active.id))?.valid_transitions).toEqual([
"dokonceny",
"zruseny",
]);
const done = await mkProject("dokonceny");
expect((await getProject(done.id))?.valid_transitions).toEqual(["aktivni"]);
const cancelled = await mkProject("zruseny");
expect((await getProject(cancelled.id))?.valid_transitions).toEqual([
"aktivni",
]);
});
it("offers all canonical targets for a legacy/unknown status", async () => {
const legacy = await mkProject("stary");
expect((await getProject(legacy.id))?.valid_transitions).toEqual([
"aktivni",
"dokonceny",
"zruseny",
]);
});
});

View File

@@ -0,0 +1,129 @@
import { describe, it, expect } from "vitest";
import {
encodeSelectedCustomFields,
parseSelectedCustomFields,
} from "../utils/custom-fields";
import { afterAll } from "vitest";
import { createOffer, getOffer } from "../services/offers.service";
import { renderOfferHtml } from "../routes/admin/offers-pdf";
import type { OfferForPdf } from "../routes/admin/offers-pdf";
import type { company_settings } from "@prisma/client";
import prisma from "../config/database";
describe("selected custom fields encode/decode", () => {
it("encodes a non-empty index array to a JSON string", () => {
expect(encodeSelectedCustomFields([0, 2])).toBe("[0,2]");
});
it("encodes empty / non-array to null", () => {
expect(encodeSelectedCustomFields([])).toBeNull();
expect(encodeSelectedCustomFields(undefined)).toBeNull();
expect(encodeSelectedCustomFields("nope")).toBeNull();
});
it("dedupes, sorts, and drops invalid entries before encoding", () => {
expect(encodeSelectedCustomFields([2, 0, 2, -1, 1.5, 3])).toBe("[0,2,3]");
});
it("parses a stored string back to a number array", () => {
expect(parseSelectedCustomFields("[0,2]")).toEqual([0, 2]);
});
it("parses null / malformed to an empty array", () => {
expect(parseSelectedCustomFields(null)).toEqual([]);
expect(parseSelectedCustomFields("")).toEqual([]);
expect(parseSelectedCustomFields("{garbage")).toEqual([]);
expect(parseSelectedCustomFields('"x"')).toEqual([]);
});
it("parses already-array input (defensive) and filters invalid", () => {
expect(parseSelectedCustomFields([0, "1", 2, -3] as unknown)).toEqual([
0, 2,
]);
});
});
describe("offers selected_custom_fields round-trip", () => {
const created: number[] = [];
afterAll(async () => {
if (created.length)
await prisma.quotations.deleteMany({ where: { id: { in: created } } });
});
it("persists selection on create and decodes it on detail", async () => {
const res = (await createOffer({
status: "draft",
selected_custom_fields: [2, 0, 0],
})) as { id: number };
created.push(res.id);
const row = await prisma.quotations.findUnique({ where: { id: res.id } });
expect(row?.selected_custom_fields).toBe("[0,2]");
const detail = await getOffer(res.id);
expect(detail?.selected_custom_fields).toEqual([0, 2]);
});
it("stores null when selection is empty", async () => {
const res = (await createOffer({
status: "draft",
selected_custom_fields: [],
})) as { id: number };
created.push(res.id);
const row = await prisma.quotations.findUnique({ where: { id: res.id } });
expect(row?.selected_custom_fields).toBeNull();
});
});
describe("offer PDF prints only selected company custom fields", () => {
// Two company custom fields; the document selects only index 0.
const settings = {
company_name: "Test s.r.o.",
custom_fields: JSON.stringify({
fields: [
{ name: "Email", value: "selected@example.com", showLabel: false },
{ name: "Web", value: "notselected.example.com", showLabel: false },
],
field_order: [],
}),
logo_data: null,
} as unknown as company_settings;
const baseQuotation = {
quotation_number: "TEST-2098-001",
language: "EN",
currency: "EUR",
valid_until: new Date("2098-01-01"),
project_code: null,
created_at: new Date("2098-01-01"),
customers: { name: "Cust" },
quotation_items: [],
scope_sections: [],
};
it("renders the selected custom field and omits the non-selected one", () => {
const html = renderOfferHtml(
{
...baseQuotation,
selected_custom_fields: "[0]",
} as unknown as OfferForPdf,
settings,
);
expect(html).toContain("selected@example.com");
expect(html).not.toContain("notselected.example.com");
});
it("prints NO company custom fields when the document selects none", () => {
// The company call site always passes a parsed array; a null column
// decodes to [] → empty selection → no custom fields on the document.
const html = renderOfferHtml(
{
...baseQuotation,
selected_custom_fields: null,
} as unknown as OfferForPdf,
settings,
);
expect(html).not.toContain("selected@example.com");
expect(html).not.toContain("notselected.example.com");
});
});

View File

@@ -19,6 +19,9 @@ import tripsRoutes from "../routes/admin/trips";
// WHOLE filtered set (not one 25-row page), honors the month filter in
// both wire formats ("month=5&year=2098" and "month=2098-05"), and scopes
// non-managers to their own trips exactly like the list does.
// 3. POST /trips rejects a non-manager filing a trip under someone else's
// user_id with an explicit Czech 403 (impersonation gap), while
// self-creates and manager on-behalf creates keep working.
// ---------------------------------------------------------------------------
/** Note-prefix for test-created rows so cleanup never touches real data. */
@@ -66,6 +69,18 @@ async function authGet(path: string, token: string) {
});
}
async function authPost(path: string, token: string, body: unknown) {
return app.inject({
method: "POST",
url: path,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
payload: body as object,
});
}
async function authPut(path: string, token: string, body: unknown) {
return app.inject({
method: "PUT",
@@ -539,3 +554,88 @@ describe("GET /api/admin/trips/stats", () => {
expect(filtered.json().data.count).toBe(2);
});
});
describe("POST /api/admin/trips — on-behalf authorization", () => {
function postBody(params: { userId?: number; note: string }) {
return {
vehicle_id: vehicleAId,
...(params.userId !== undefined ? { user_id: params.userId } : {}),
trip_date: "2098-11-10",
start_km: 100,
end_km: 150,
route_from: "Praha",
route_to: "Brno",
is_business: true,
notes: `${N}${params.note}`,
};
}
it("rejects a non-manager filing a trip under another user's id with 403", async () => {
const res = await authPost(
"/api/admin/trips",
scopeToken,
postBody({ userId: adminUserId, note: "authz_spoof" }),
);
expect(res.statusCode).toBe(403);
expect(res.json()).toEqual({
success: false,
error: "Nemáte oprávnění zadat jízdu za jiného uživatele",
});
// …and the trip must NOT have been created.
const created = await prisma.trips.findFirst({
where: { notes: `${N}authz_spoof` },
});
expect(created).toBeNull();
});
it("lets a non-manager create a trip without user_id (defaults to self)", async () => {
const res = await authPost(
"/api/admin/trips",
scopeToken,
postBody({ note: "authz_self_implicit" }),
);
expect(res.statusCode).toBe(201);
expect(res.json().success).toBe(true);
const created = await prisma.trips.findFirst({
where: { notes: `${N}authz_self_implicit` },
});
expect(created).not.toBeNull();
expect(created!.user_id).toBe(scopeUserId);
});
it("lets a non-manager create a trip with their OWN user_id", async () => {
const res = await authPost(
"/api/admin/trips",
scopeToken,
postBody({ userId: scopeUserId, note: "authz_self_explicit" }),
);
expect(res.statusCode).toBe(201);
const created = await prisma.trips.findFirst({
where: { notes: `${N}authz_self_explicit` },
});
expect(created).not.toBeNull();
expect(created!.user_id).toBe(scopeUserId);
});
it("lets a manager/admin create a trip on behalf of another user", async () => {
const res = await authPost(
"/api/admin/trips",
adminToken,
postBody({ userId: scopeUserId, note: "authz_on_behalf" }),
);
expect(res.statusCode).toBe(201);
const created = await prisma.trips.findFirst({
where: { notes: `${N}authz_on_behalf` },
});
expect(created).not.toBeNull();
expect(created!.user_id).toBe(scopeUserId);
});
});

View File

@@ -0,0 +1,24 @@
import { describe, it, expect } from "vitest";
import Fastify from "fastify";
import { registerVersionHeader, readAppVersion } from "../middleware/version";
/**
* The server stamps every response with X-App-Version so the SPA can detect a
* deploy (the client compares it to the version baked into its bundle).
*/
describe("registerVersionHeader", () => {
it("adds X-App-Version to responses", async () => {
const app = Fastify({ logger: false });
registerVersionHeader(app, "9.9.9");
app.get("/ping", async () => ({ ok: true }));
const res = await app.inject({ method: "GET", url: "/ping" });
expect(res.headers["x-app-version"]).toBe("9.9.9");
await app.close();
});
it("defaults to the package.json version (semver string)", () => {
expect(readAppVersion()).toMatch(/^\d+\.\d+\.\d+/);
});
});

View File

@@ -7,65 +7,97 @@ import { queryClient } from "./lib/queryClient";
import ErrorBoundary from "./components/ErrorBoundary";
import AppShell from "./ui/AppShell";
import AlertContainer from "./components/AlertContainer";
import UpdateBanner from "./components/UpdateBanner";
import { lazyWithReload } from "./utils/lazyWithReload";
import MuiProvider from "./ui/MuiProvider";
import { LoadingState } from "./ui";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
const Odin = lazy(() => import("./pages/Odin"));
const Users = lazy(() => import("./pages/Users"));
const Attendance = lazy(() => import("./pages/Attendance"));
const AttendanceHistory = lazy(() => import("./pages/AttendanceHistory"));
const AttendanceAdmin = lazy(() => import("./pages/AttendanceAdmin"));
const AttendanceBalances = lazy(() => import("./pages/AttendanceBalances"));
const AttendanceCreate = lazy(() => import("./pages/AttendanceCreate"));
const LeaveRequests = lazy(() => import("./pages/LeaveRequests"));
const LeaveApproval = lazy(() => import("./pages/LeaveApproval"));
const AttendanceLocation = lazy(() => import("./pages/AttendanceLocation"));
const PlanWork = lazy(() => import("./pages/PlanWork"));
const Trips = lazy(() => import("./pages/Trips"));
const TripsHistory = lazy(() => import("./pages/TripsHistory"));
const TripsAdmin = lazy(() => import("./pages/TripsAdmin"));
const Vehicles = lazy(() => import("./pages/Vehicles"));
const Offers = lazy(() => import("./pages/Offers"));
const OfferDetail = lazy(() => import("./pages/OfferDetail"));
const OffersCustomers = lazy(() => import("./pages/OffersCustomers"));
const OffersTemplates = lazy(() => import("./pages/OffersTemplates"));
const Orders = lazy(() => import("./pages/Orders"));
const OrderDetail = lazy(() => import("./pages/OrderDetail"));
const IssuedOrderDetail = lazy(() => import("./pages/IssuedOrderDetail"));
const Projects = lazy(() => import("./pages/Projects"));
const ProjectDetail = lazy(() => import("./pages/ProjectDetail"));
const Invoices = lazy(() => import("./pages/Invoices"));
const InvoiceDetail = lazy(() => import("./pages/InvoiceDetail"));
const Settings = lazy(() => import("./pages/Settings"));
const AuditLog = lazy(() => import("./pages/AuditLog"));
const NotFound = lazy(() => import("./pages/NotFound"));
const Warehouse = lazy(() => import("./pages/Warehouse"));
const WarehouseItems = lazy(() => import("./pages/WarehouseItems"));
const WarehouseItemDetail = lazy(() => import("./pages/WarehouseItemDetail"));
const WarehouseReceipts = lazy(() => import("./pages/WarehouseReceipts"));
const WarehouseReceiptDetail = lazy(
const Dashboard = lazyWithReload(() => import("./pages/Dashboard"));
const Odin = lazyWithReload(() => import("./pages/Odin"));
const Users = lazyWithReload(() => import("./pages/Users"));
const Attendance = lazyWithReload(() => import("./pages/Attendance"));
const AttendanceHistory = lazyWithReload(
() => import("./pages/AttendanceHistory"),
);
const AttendanceAdmin = lazyWithReload(() => import("./pages/AttendanceAdmin"));
const AttendanceBalances = lazyWithReload(
() => import("./pages/AttendanceBalances"),
);
const AttendanceCreate = lazyWithReload(
() => import("./pages/AttendanceCreate"),
);
const LeaveRequests = lazyWithReload(() => import("./pages/LeaveRequests"));
const LeaveApproval = lazyWithReload(() => import("./pages/LeaveApproval"));
const AttendanceLocation = lazyWithReload(
() => import("./pages/AttendanceLocation"),
);
const PlanWork = lazyWithReload(() => import("./pages/PlanWork"));
const Trips = lazyWithReload(() => import("./pages/Trips"));
const TripsHistory = lazyWithReload(() => import("./pages/TripsHistory"));
const TripsAdmin = lazyWithReload(() => import("./pages/TripsAdmin"));
const Vehicles = lazyWithReload(() => import("./pages/Vehicles"));
const Offers = lazyWithReload(() => import("./pages/Offers"));
const OfferDetail = lazyWithReload(() => import("./pages/OfferDetail"));
const OffersCustomers = lazyWithReload(() => import("./pages/OffersCustomers"));
const OffersTemplates = lazyWithReload(() => import("./pages/OffersTemplates"));
const Orders = lazyWithReload(() => import("./pages/Orders"));
const OrderDetail = lazyWithReload(() => import("./pages/OrderDetail"));
const IssuedOrderDetail = lazyWithReload(
() => import("./pages/IssuedOrderDetail"),
);
const Projects = lazyWithReload(() => import("./pages/Projects"));
const ProjectDetail = lazyWithReload(() => import("./pages/ProjectDetail"));
const Invoices = lazyWithReload(() => import("./pages/Invoices"));
const InvoiceDetail = lazyWithReload(() => import("./pages/InvoiceDetail"));
const Settings = lazyWithReload(() => import("./pages/Settings"));
const AuditLog = lazyWithReload(() => import("./pages/AuditLog"));
const NotFound = lazyWithReload(() => import("./pages/NotFound"));
const Warehouse = lazyWithReload(() => import("./pages/Warehouse"));
const WarehouseItems = lazyWithReload(() => import("./pages/WarehouseItems"));
const WarehouseItemDetail = lazyWithReload(
() => import("./pages/WarehouseItemDetail"),
);
const WarehouseReceipts = lazyWithReload(
() => import("./pages/WarehouseReceipts"),
);
const WarehouseReceiptDetail = lazyWithReload(
() => import("./pages/WarehouseReceiptDetail"),
);
const WarehouseReceiptForm = lazy(() => import("./pages/WarehouseReceiptForm"));
const WarehouseIssues = lazy(() => import("./pages/WarehouseIssues"));
const WarehouseIssueDetail = lazy(() => import("./pages/WarehouseIssueDetail"));
const WarehouseIssueForm = lazy(() => import("./pages/WarehouseIssueForm"));
const WarehouseReservations = lazy(
const WarehouseReceiptForm = lazyWithReload(
() => import("./pages/WarehouseReceiptForm"),
);
const WarehouseIssues = lazyWithReload(() => import("./pages/WarehouseIssues"));
const WarehouseIssueDetail = lazyWithReload(
() => import("./pages/WarehouseIssueDetail"),
);
const WarehouseIssueForm = lazyWithReload(
() => import("./pages/WarehouseIssueForm"),
);
const WarehouseReservations = lazyWithReload(
() => import("./pages/WarehouseReservations"),
);
const WarehouseInventory = lazy(() => import("./pages/WarehouseInventory"));
const WarehouseInventoryDetail = lazy(
const WarehouseInventory = lazyWithReload(
() => import("./pages/WarehouseInventory"),
);
const WarehouseInventoryDetail = lazyWithReload(
() => import("./pages/WarehouseInventoryDetail"),
);
const WarehouseInventoryForm = lazy(
const WarehouseInventoryForm = lazyWithReload(
() => import("./pages/WarehouseInventoryForm"),
);
const WarehouseReports = lazy(() => import("./pages/WarehouseReports"));
const WarehouseSuppliers = lazy(() => import("./pages/WarehouseSuppliers"));
const WarehouseLocations = lazy(() => import("./pages/WarehouseLocations"));
const WarehouseCategories = lazy(() => import("./pages/WarehouseCategories"));
const WarehouseReports = lazyWithReload(
() => import("./pages/WarehouseReports"),
);
const WarehouseSuppliers = lazyWithReload(
() => import("./pages/WarehouseSuppliers"),
);
const WarehouseLocations = lazyWithReload(
() => import("./pages/WarehouseLocations"),
);
const WarehouseCategories = lazyWithReload(
() => import("./pages/WarehouseCategories"),
);
const UiKit = import.meta.env.DEV ? lazy(() => import("./pages/UiKit")) : null;
export default function AdminApp() {
@@ -75,6 +107,7 @@ export default function AdminApp() {
<AlertProvider>
<QueryClientProvider client={queryClient}>
<AlertContainer />
<UpdateBanner />
<ErrorBoundary>
<Suspense fallback={<LoadingState />}>
<Routes>

View File

@@ -0,0 +1,148 @@
import { useState, type ComponentProps } from "react";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import { StatusChip, ConfirmDialog } from "../ui";
/** One entry in a {@link StatusChipMenu}. */
export interface StatusChipAction {
/** Stable identifier, e.g. the target status. */
key: string;
/** Menu item text, e.g. "Dokončit". */
label: string;
/** Red menu-item text + danger ConfirmDialog variant. */
danger?: boolean;
/**
* Confirmation dialog content. When omitted the action fires directly from
* the menu without confirmation (used by "Vytvořit objednávku…", which
* opens its own modal).
*/
confirm?: { title: string; message: string; confirmText: string };
/**
* Executed on pick (after confirmation when `confirm` is set). Awaited:
* while pending the ConfirmDialog shows its loading state and cannot be
* closed; on resolve the dialog closes; on rejection it stays open (the
* caller is responsible for toasting the error).
*/
onAction: () => void | Promise<void>;
}
interface StatusChipMenuProps {
/** Chip text (current status label). */
label: string;
/** Chip color, same palette as {@link StatusChip}. */
color: ComponentProps<typeof StatusChip>["color"];
/** Quick actions. Empty/undefined renders a plain non-clickable chip. */
actions?: StatusChipAction[];
/** Force a plain chip (e.g. the user lacks the edit permission). */
disabled?: boolean;
/** Tooltip on the clickable chip. */
title?: string;
}
/**
* Status chip with a quick-action menu, shared by the list pages
* (offers / received orders / projects).
*
* Clicking the chip (stopPropagation, so row navigation never fires) opens a
* dense MUI Menu of the valid next actions. Picking one closes the menu and
* either fires `onAction` directly (no `confirm` given) or opens the single
* shared ConfirmDialog instance — danger variant for destructive actions,
* `loading` while the awaited `onAction` is pending, staying open when it
* rejects per app convention (the caller toasts errors).
*
* With no actions — or with `disabled` — it renders a plain non-clickable
* StatusChip without a tooltip.
*/
export default function StatusChipMenu({
label,
color,
actions,
disabled = false,
title = "Změnit stav",
}: StatusChipMenuProps) {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const [pending, setPending] = useState<StatusChipAction | null>(null);
const [loading, setLoading] = useState(false);
if (disabled || !actions || actions.length === 0) {
return <StatusChip label={label} color={color} />;
}
const handlePick = (action: StatusChipAction) => {
setAnchorEl(null);
if (action.confirm) {
setPending(action);
} else {
void (async () => {
try {
await action.onAction();
} catch {
// Expected: the caller toasts its own errors; nothing to close here.
}
})();
}
};
const handleConfirm = async () => {
if (!pending) return;
setLoading(true);
try {
await pending.onAction();
// Success → close; ConfirmDialog freezes its content through the fade.
setPending(null);
} catch {
// Expected: rejection keeps the dialog open; the caller toasts the error.
} finally {
setLoading(false);
}
};
return (
<>
<StatusChip
label={label}
color={color}
title={title}
aria-haspopup="menu"
aria-expanded={Boolean(anchorEl)}
onClick={(e) => {
e.stopPropagation();
setAnchorEl(e.currentTarget);
}}
/>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
transformOrigin={{ vertical: "top", horizontal: "left" }}
slotProps={{ list: { dense: true } }}
>
{actions.map((action) => (
<MenuItem
key={action.key}
// stopPropagation: MUI portals re-bubble synthetic events to
// React-tree ancestors — a future onRowClick row must not fire.
onClick={(e) => {
e.stopPropagation();
handlePick(action);
}}
sx={action.danger ? { color: "error.main" } : undefined}
>
{action.label}
</MenuItem>
))}
</Menu>
<ConfirmDialog
isOpen={pending !== null}
onClose={() => setPending(null)}
onConfirm={() => void handleConfirm()}
title={pending?.confirm?.title ?? ""}
message={pending?.confirm?.message ?? ""}
confirmText={pending?.confirm?.confirmText}
confirmVariant={pending?.danger ? "danger" : "primary"}
loading={loading}
/>
</>
);
}

View File

@@ -0,0 +1,42 @@
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { menuSections, isItemActive } from "../ui/navData";
/**
* Null-rendering helper that keeps the browser tab title in sync with the
* active navigation item. Scans menuSections in order (first match wins) via
* the same isItemActive logic the sidebar uses, so detail routes covered by
* matchPrefix (e.g. /offers/123) inherit their section item's label.
* No cleanup on unmount — the last title simply persists.
*/
// Labels reused across sections ("Záznam", "Moje historie", "Správa",
// "Přehled") would produce identical tab titles — qualify those with their
// section label so /attendance and /trips tabs stay distinguishable.
const labelCounts = new Map<string, number>();
for (const section of menuSections) {
for (const item of section.items) {
labelCounts.set(item.label, (labelCounts.get(item.label) ?? 0) + 1);
}
}
export default function TitleSync() {
const { pathname } = useLocation();
useEffect(() => {
for (const section of menuSections) {
const item = section.items.find((candidate) =>
isItemActive(candidate, pathname),
);
if (item) {
const ambiguous = (labelCounts.get(item.label) ?? 0) > 1;
document.title = ambiguous
? `${item.label} ${section.label} · BOHA`
: `${item.label} · BOHA`;
return;
}
}
document.title = "BOHA Admin";
}, [pathname]);
return null;
}

View File

@@ -0,0 +1,35 @@
import { useSyncExternalStore } from "react";
import Snackbar from "@mui/material/Snackbar";
import Button from "@mui/material/Button";
import { subscribeNewVersion, getNewVersion } from "../utils/appVersion";
/**
* Shows a persistent banner when the server reports a newer build than the one
* this tab is running (detected via the X-App-Version header in apiFetch). The
* reload is user-initiated — we never force it, so an in-progress form is safe.
*/
export default function UpdateBanner() {
const newVersion = useSyncExternalStore(
subscribeNewVersion,
getNewVersion,
() => null,
);
return (
<Snackbar
open={Boolean(newVersion)}
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
message="Je k dispozici nová verze aplikace."
action={
<Button
color="primary"
size="small"
variant="contained"
onClick={() => window.location.reload()}
>
Obnovit
</Button>
}
/>
);
}

View File

@@ -12,6 +12,7 @@ import DialogActions from "@mui/material/DialogActions";
import { useAuth } from "../../context/AuthContext";
import { useAlert } from "../../context/AlertContext";
import apiFetch from "../../utils/api";
import { USER_INVALIDATE } from "../../lib/queries/users";
import { iconBadgeSx } from "../../theme";
import { Card, Button, Modal, Field, TextField } from "../../ui";
import useDialogScrollLock from "../../ui/useDialogScrollLock";
@@ -142,6 +143,9 @@ export default function DashProfile({
const { data: totpQrDataUrl, isError: totpQrFailed } = useQuery({
queryKey: ["totp", "qr", totpQrUri],
enabled: !!totpQrUri,
// Purely local QR generation — the global "server data" error toast would
// misattribute a failure here; the totpQrFailed inline message covers it.
meta: { suppressGlobalErrorToast: true },
staleTime: Infinity,
// The URI embeds the TOTP secret — drop it from the cache as soon as the
// enrollment UI unmounts instead of keeping it for the default 5-min GC.
@@ -221,9 +225,13 @@ export default function DashProfile({
fullName: `${dataToSave.first_name} ${dataToSave.last_name}`.trim(),
});
// Refresh anything keyed on the current user's data so stale views
// (dashboard widgets, user lists) pick up the edited profile.
// pick up the edited profile — a self-rename must also refresh the
// domains embedding the display name (USER_INVALIDATE), not just the
// dashboard and user list.
for (const key of USER_INVALIDATE) {
queryClient.invalidateQueries({ queryKey: [key] });
}
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
queryClient.invalidateQueries({ queryKey: ["users"] });
setShowModal(false);
// The 300ms wait is load-bearing: it lets the modal's close fade finish
// before the success toast appears, so the toast doesn't flash over the
@@ -262,8 +270,9 @@ export default function DashProfile({
initial={reduce ? false : { opacity: 0, y: 12 }}
animate={reduce ? undefined : { opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.15 }}
style={{ height: "100%" }}
>
<Card>
<Card sx={{ height: "100%" }}>
<Box
sx={{
display: "flex",

View File

@@ -132,8 +132,9 @@ export default function DashSessions() {
initial={reduce ? false : { opacity: 0, y: 12 }}
animate={reduce ? undefined : { opacity: 1, y: 0 }}
transition={{ duration: 0.25, delay: 0.15 }}
style={{ height: "100%" }}
>
<Card sx={{ display: "flex", flexDirection: "column" }}>
<Card sx={{ display: "flex", flexDirection: "column", height: "100%" }}>
<Box
sx={{
display: "flex",

View File

@@ -0,0 +1,60 @@
import { FormControlLabel, Checkbox, Box, Typography } from "@mui/material";
import type { CompanySettingsCustomField } from "../../lib/queries/settings";
interface Props {
/** Company custom field definitions, in positional order (index = print key). */
fields: CompanySettingsCustomField[];
/** Currently selected positional indices. */
selected: number[];
/** Read-only (document not editable / locked by another user). */
disabled?: boolean;
onChange: (next: number[]) => void;
}
/**
* Per-document picker: choose which COMPANY custom fields print on this
* document's PDF. Selection is positional (matches the PDF `custom_<i>` keys).
* Renders nothing when the company has defined no printable custom fields.
*/
export default function CustomFieldsPrintPicker({
fields,
selected,
disabled = false,
onChange,
}: Props) {
const printable = fields.filter((f) => (f.value || "").trim());
if (printable.length === 0) return null;
const toggle = (idx: number, checked: boolean) => {
const set = new Set(selected);
if (checked) set.add(idx);
else set.delete(idx);
onChange([...set].sort((a, b) => a - b));
};
return (
<Box>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
Vlastní pole na PDF
</Typography>
{fields.map((f, idx) => {
if (!(f.value || "").trim()) return null;
const label = (f.name || "").trim() ? `${f.name}: ${f.value}` : f.value;
return (
<FormControlLabel
key={idx}
control={
<Checkbox
size="small"
checked={selected.includes(idx)}
disabled={disabled}
onChange={(e) => toggle(idx, e.target.checked)}
/>
}
label={<Typography variant="body2">{label}</Typography>}
/>
);
})}
</Box>
);
}

View File

@@ -49,10 +49,31 @@ export interface DocumentItem {
quantity: string | number;
unit: string;
unit_price: string | number;
/** Per-item discount as a percentage (0100). 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,10 +486,18 @@ 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. */
templatesSlot?: ReactNode;
/**
* Allow removing every row so the list can be empty (issued orders may be
* issued by sections alone). Default false keeps the offers/invoices rule of
* at least one item.
*/
allowEmpty?: boolean;
}
/**
@@ -460,8 +512,10 @@ export default function DocumentItemsEditor({
readOnly,
error,
showIncludedInTotal = false,
showDiscount = false,
itemDescriptionMaxLength = 5000,
templatesSlot,
allowEmpty = false,
}: DocumentItemsEditorProps) {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
@@ -491,10 +545,13 @@ export default function DocumentItemsEditor({
const addItem = () => onChange([...items, emptyDocumentItem()]);
const removeItem = (index: number) => {
if (items.length <= 1) return;
if (!allowEmpty && items.length <= 1) return;
onChange(items.filter((_, i) => i !== index));
};
// When allowEmpty, even the last row is deletable (list may go to zero).
const canDeleteRow = allowEmpty || items.length > 1;
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
@@ -561,8 +618,9 @@ export default function DocumentItemsEditor({
index={index}
currency={currency}
readOnly={readOnly}
canDelete={items.length > 1}
canDelete={canDeleteRow}
showIncludedInTotal={showIncludedInTotal}
showDiscount={showDiscount}
itemDescriptionMaxLength={itemDescriptionMaxLength}
onUpdate={(field, value) => updateItem(index, field, value)}
onRemove={() => removeItem(index)}
@@ -594,6 +652,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ě
@@ -613,8 +676,9 @@ export default function DocumentItemsEditor({
index={index}
currency={currency}
readOnly={readOnly}
canDelete={items.length > 1}
canDelete={canDeleteRow}
showIncludedInTotal={showIncludedInTotal}
showDiscount={showDiscount}
itemDescriptionMaxLength={itemDescriptionMaxLength}
onUpdate={(field, value) =>
updateItem(index, field, value)

View File

@@ -103,6 +103,10 @@ export default function OdinChat() {
const fileRef = useRef<HTMLInputElement>(null);
const threadRef = useRef<HTMLDivElement>(null);
const seededId = useRef<number | null>(null);
// Drag & drop over the chat column. The depth counter pairs enter/leave
// events bubbling from children so the overlay doesn't flicker mid-drag.
const [dragOver, setDragOver] = useState(false);
const dragDepth = useRef(0);
// Below md the conversation list collapses into a slide-in drawer.
const isMobile = useMediaQuery((t) => t.breakpoints.down("md"), {
@@ -177,17 +181,63 @@ export default function OdinChat() {
};
// Attaching only stages files; nothing is sent until Odeslat.
const onFiles = (files: FileList | null) => {
if (!files || files.length === 0) return;
const stageFiles = (files: File[]) => {
if (files.length === 0) return;
setAttachments((a) => [
...a,
...Array.from(files).map((file) => ({ id: nextUid(), file })),
...files.map((file) => ({ id: nextUid(), file })),
]);
};
const onFiles = (files: FileList | null) => {
if (!files || files.length === 0) return;
stageFiles(Array.from(files));
if (fileRef.current) fileRef.current.value = "";
};
const removeAttachment = (id: string) =>
setAttachments((a) => a.filter((s) => s.id !== id));
// Drag & drop anywhere over the chat column stages files exactly like the
// paperclip (same accept filter as the file input). Only file drags react —
// text/link drags pass through untouched — and nothing stages while busy.
const isAccepted = (f: File) =>
f.type === "application/pdf" || f.type.startsWith("image/");
const dragHasFiles = (e: React.DragEvent) =>
Array.from(e.dataTransfer.types).includes("Files");
const onDragEnter = (e: React.DragEvent) => {
if (busy || !dragHasFiles(e)) return;
e.preventDefault();
dragDepth.current += 1;
setDragOver(true);
};
const onDragOver = (e: React.DragEvent) => {
if (!dragHasFiles(e)) return;
// preventDefault permits the drop (and keeps the browser from replacing
// the app with the dropped file); while busy the drop itself is refused.
e.preventDefault();
if (busy) e.dataTransfer.dropEffect = "none";
};
const onDragLeave = () => {
if (dragDepth.current === 0) return;
dragDepth.current -= 1;
if (dragDepth.current === 0) setDragOver(false);
};
const onDrop = (e: React.DragEvent) => {
if (!dragHasFiles(e)) return;
e.preventDefault();
dragDepth.current = 0;
setDragOver(false);
if (busy) return;
const dropped = Array.from(e.dataTransfer.files);
const accepted = dropped.filter(isAccepted);
if (accepted.length === 0) {
// Nothing usable — hint instead of silently doing nothing.
if (dropped.length > 0) alert.info("Podporované soubory: PDF a obrázky");
return;
}
stageFiles(accepted);
};
const onSelect = (id: number) => {
setSidebarOpen(false);
if (id === activeId || busy) return;
@@ -467,9 +517,14 @@ export default function OdinChat() {
sidebar
)}
{/* Chat column */}
{/* Chat column — also the drop target for invoice files (overlay below). */}
<Box
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
sx={{
position: "relative",
flex: 1,
minWidth: 0,
display: "flex",
@@ -557,11 +612,14 @@ export default function OdinChat() {
{review.length > 0 && (
<Box
sx={{
maxHeight: "35vh",
maxHeight: "40vh",
overflowY: "auto",
display: "flex",
flexDirection: "column",
gap: 1,
// Flex children shrink by default — with 2+ cards they'd get
// compressed to fit instead of overflowing into the scrollbar.
"& > *": { flexShrink: 0 },
}}
>
{review.map((inv) => (
@@ -591,6 +649,63 @@ export default function OdinChat() {
onRemoveAttachment={removeAttachment}
onSubmit={submit}
/>
{/* Drop-target overlay — pointer-events pass through so the drag
events keep firing on the column beneath it. */}
{dragOver && (
<Box
sx={(t) => ({
position: "absolute",
inset: 0,
zIndex: 10,
pointerEvents: "none",
display: "flex",
alignItems: "center",
justifyContent: "center",
// Longhand on purpose — see the container border note above.
borderStyle: "dashed",
borderWidth: 2,
borderColor: "primary.main",
borderRadius: { xs: 0, md: 3 },
bgcolor: `rgba(${t.vars!.palette.primary.mainChannel} / 0.08)`,
})}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 0.5,
px: 3,
py: 2,
borderRadius: 2,
bgcolor: "background.paper",
boxShadow: 3,
}}
>
<Box
component="svg"
viewBox="0 0 24 24"
sx={{ width: 32, height: 32, color: "primary.main", mb: 0.5 }}
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</Box>
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
Přetáhněte soubory sem
</Typography>
<Typography variant="caption" color="text.secondary">
PDF nebo obrázky faktur
</Typography>
</Box>
</Box>
)}
</Box>
</Box>
);

View File

@@ -8,6 +8,7 @@ import {
useEffect,
type ReactNode,
} from "react";
import { registerQueryErrorNotifier } from "../lib/queryClient";
interface Alert {
id: string;
@@ -81,6 +82,13 @@ export function AlertProvider({ children }: { children: ReactNode }) {
[addAlert, removeAlert],
);
// Global React Query error toasts (queryClient.ts). `addAlert` is a stable
// useCallback, so this registers once on mount; re-registering the same
// handler is idempotent either way.
useEffect(() => {
registerQueryErrorNotifier((msg) => addAlert(msg, "error"));
}, [addAlert]);
return (
<AlertContext.Provider value={methods}>
<AlertStateContext.Provider value={{ alerts, removeAlert }}>

View File

@@ -253,7 +253,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return { success: false, error: data.error };
} catch {
const errorMsg =
"Chyba pripojeni. Zkontrolujte prosim pripojeni k internetu a zkuste to znovu.";
"Chyba připojení. Zkontrolujte prosím připojení k internetu a zkuste to znovu.";
setError(errorMsg);
return { success: false, error: errorMsg };
}
@@ -311,7 +311,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setError(data.error);
return { success: false, error: data.error };
} catch {
const errorMsg = "Chyba pripojeni.";
const errorMsg = "Chyba připojení.";
setError(errorMsg);
return { success: false, error: errorMsg };
}

View File

@@ -18,10 +18,8 @@ import {
getDaysInMonth,
shiftDateForMonth,
formatHoursDecimal,
calculateNightMinutes,
normalizeDateStr,
holidaysInMonth,
calculateFreeHolidayHours,
computeMzdaSummary,
getCzechWeekday,
} from "../utils/attendanceHelpers";
import type {
@@ -216,116 +214,35 @@ function computeUserTotals(
}
}
// Add fund data per user (matching PHP addFundDataToUserTotals)
const [yearStr, monthStr] = month.split("-");
const yr = parseInt(yearStr, 10);
const mo = parseInt(monthStr, 10) - 1;
// Count Mon-Fri business days in month (INCLUDING holidays).
// The fund is rawBizDays × 8 — holidays stay in the count so the
// user is paid for them via the fund. Svátek (free holiday hours) is
// computed separately as "8h per holiday the user did not work".
let rawBizDays = 0;
const cur = new Date(yr, mo, 1);
while (cur.getMonth() === mo) {
const dow = cur.getDay();
if (dow !== 0 && dow !== 6) rawBizDays++;
cur.setDate(cur.getDate() + 1);
}
const holidayDates = holidaysInMonth(yr, mo + 1);
// Rekapitulace per user — the SAME shared computation the print uses
// (computeMzdaSummary), so the screen and the printed sheet can never
// disagree. Accountant spec 2026-07: Odpracováno = worked minus
// holiday-worked; Vč. svátků = ALL worked; Přesčas = max(0, worked fond);
// Svátek = hours actually worked on holidays.
for (const uid of Object.keys(totals)) {
const t = totals[uid];
const userRecords = recordsByUser.get(Number(uid)) || [];
// Odpracováno: floor(worked / 8) × 8 — round to whole days, drop remainder.
const workedHoursRaw = t.minutes / 60;
const odpracovano = Math.floor(workedHoursRaw / 8) * 8;
// So/Ne: sum of worked hours on Sat/Sun (raw, not rounded).
const weekendHours = userRecords
.filter(
(r) =>
(r.leave_type || "work") === "work" && isWeekendDate(r.shift_date),
)
.reduce((sum, r) => sum + calculateWorkMinutesPrint(r) / 60, 0);
// Práce v noci: minutes in 22:00-06:00 across all work records.
const nightMinutes = userRecords
.filter((r) => (r.leave_type || "work") === "work")
.reduce((sum, r) => sum + calculateNightMinutes(r), 0);
// Svátek (free): 8h per holiday the user did not work.
const freeHolidayHours = calculateFreeHolidayHours(
userRecords,
holidayDates,
);
// Worked holidays: holidays the user DID work (counted toward
// Odpracováno, but their 8h must not flow into Přesčas).
const workedDatesSet = new Set(
userRecords
.filter((r) => (r.leave_type || "work") === "work")
.map((r) => normalizeDateStr(r.shift_date))
.filter(Boolean),
);
let workedHolidayCount = 0;
let workedHolidayHours = 0;
for (const hd of holidayDates) {
if (workedDatesSet.has(hd)) workedHolidayCount++;
}
// Sum the actual hours worked on holiday dates (for the KPI card's
// "fond used" total = real_work + vacation + worked_holiday + free_holiday).
for (const r of userRecords) {
if ((r.leave_type || "work") !== "work") continue;
const d = normalizeDateStr(r.shift_date);
if (d && holidayDates.includes(d)) {
workedHolidayHours += calculateWorkMinutesPrint(r) / 60;
}
}
// Fund = Mon-Fri × 8h. Holidays count as work days (already in rawBizDays).
const fund = rawBizDays * 8;
// Včetně svátků a přesčasů (mzda formula):
// odpracovano + vacation + remainder min(freeHols, workedHols × 8)
//
// Two-way logic matching the print:
// • If the user worked at least one holiday, that worked holiday's
// 8h is in Odpracováno and shouldn't also count as Přesčas. We
// subtract one 8h per worked holiday (capped at the total free
// holiday hours — can't go negative).
// • If the user did NOT work any holiday, no adjustment is needed:
// all unworked holidays are already paid via the Svátek line and
// don't flow into Přesčas, so vcetne_svatku just equals the
// work + vacation + remainder.
const remainder = workedHoursRaw - odpracovano;
const holidayAdj = Math.min(freeHolidayHours, workedHolidayCount * 8);
const vcetneSv = odpracovano - holidayAdj + t.vacation_hours + remainder;
// Přesčas = vcetneSv odpracovano (derived).
const prescas = vcetneSv - odpracovano;
const s = computeMzdaSummary(userRecords, month);
// Legacy fields (kept so existing UI doesn't break).
const workedHours = Math.round(workedHoursRaw * 10) / 10;
const workedHours = Math.round(s.workedHoursRaw * 10) / 10;
const covered = Math.round((workedHours + t.vacation_hours) * 10) / 10;
t.fund = fund;
t.business_days = rawBizDays;
t.fund = s.fund;
t.business_days = s.businessDays;
t.worked_hours = workedHours;
t.covered = covered;
t.missing = Math.max(0, Math.round((fund - covered) * 10) / 10);
t.overtime = Math.max(0, Math.round((covered - fund) * 10) / 10);
t.missing = Math.max(0, Math.round((s.fund - covered) * 10) / 10);
t.overtime = Math.max(0, Math.round((covered - s.fund) * 10) / 10);
t.worked_hours_raw = workedHoursRaw;
t.odpracovano = odpracovano;
t.vcetne_svatku = vcetneSv;
t.prescas = prescas;
t.svatek = freeHolidayHours;
t.weekend_hours = weekendHours;
t.night_minutes = nightMinutes;
t.worked_holiday_hours = workedHolidayHours;
t.worked_hours_raw = s.workedHoursRaw;
t.odpracovano = s.odpracovano;
t.vcetne_svatku = s.vcetneSvatku;
t.prescas = s.prescas;
t.svatek = s.svatekHours;
t.weekend_hours = s.weekendHours;
t.night_minutes = s.nightMinutes;
t.worked_holiday_hours = s.svatekHours;
}
return totals;
@@ -390,10 +307,23 @@ export function buildUserSectionHtml(
userData: UserTotal,
printData: PrintData,
): string {
// Build a date-keyed lookup of the user's records.
const recordsByDate = new Map<string, AttendanceRecord>();
// Build a date-keyed lookup of the user's records. A day may hold MULTIPLE
// records (two shifts, or work + partial-day vacation) — keep them ALL; a
// single-record map silently dropped every shift but the last one.
const recordsByDate = new Map<string, AttendanceRecord[]>();
for (const r of userData.records || []) {
recordsByDate.set(normalizeDateStr(r.shift_date), r);
const key = normalizeDateStr(r.shift_date);
const list = recordsByDate.get(key);
if (list) list.push(r);
else recordsByDate.set(key, [r]);
}
// Stable in-day order: by arrival time (leave records without times last).
for (const list of recordsByDate.values()) {
list.sort((a, b) =>
String(a.arrival_time || "9999").localeCompare(
String(b.arrival_time || "9999"),
),
);
}
// Iterate one row per day of the month.
@@ -407,19 +337,14 @@ export function buildUserSectionHtml(
const rows: string[] = [];
for (let d = 1; d <= daysInMonth; d++) {
const dateStr = shiftDateForMonth(yr, mo, d);
const record = recordsByDate.get(dateStr);
const dayRecords = recordsByDate.get(dateStr);
const weekend = isWeekendDate(dateStr);
const holiday = isHoliday(dateStr);
const leaveType = (record?.leave_type as string) || "work";
const rowClasses = [
weekend && "weekend",
holiday && "holiday",
leaveType === "vacation" && "vacation",
]
if (!dayRecords || dayRecords.length === 0) {
const rowClasses = [weekend && "weekend", holiday && "holiday"]
.filter(Boolean)
.join(" ");
if (!record) {
rows.push(`<tr class="${rowClasses}">
<td>${escapeHtml(formatDate(dateStr))}</td>
<td>${escapeHtml(getCzechWeekday(dateStr))}</td>
@@ -434,6 +359,18 @@ export function buildUserSectionHtml(
continue;
}
// One row PER RECORD — a day can hold two shifts, or work + partial-day
// vacation. (A single row per day silently dropped the extra shifts.)
for (const record of dayRecords) {
const leaveType = (record.leave_type as string) || "work";
const rowClasses = [
weekend && "weekend",
holiday && "holiday",
leaveType === "vacation" && "vacation",
]
.filter(Boolean)
.join(" ");
const isLeave = leaveType !== "work";
const workMinutes = calculateWorkMinutesPrint(record);
const hours = Math.floor(workMinutes / 60);
@@ -464,109 +401,47 @@ export function buildUserSectionHtml(
<td>${escapeHtml(record.notes || "")}</td>
</tr>`);
}
// ----- mzda-style summary numbers (computed here, not from userData,
// because the backend's getPrintData only returns the legacy fields). -----
// Worked minutes: sum of calculateWorkMinutesPrint across work records.
let workedMinutes = 0;
let weekendHoursRaw = 0;
let nightMinutes = 0;
for (const r of userRecords) {
const leaveType = r.leave_type || "work";
if (leaveType !== "work") continue;
const m = calculateWorkMinutesPrint(r);
workedMinutes += m;
if (isWeekendDate(r.shift_date)) {
weekendHoursRaw += m / 60;
}
nightMinutes += calculateNightMinutes(r);
}
// 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;
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;
}
// Odpracováno: floor(worked / 8) × 8.
const workedHoursRaw = workedMinutes / 60;
const odpracovano = Math.floor(workedHoursRaw / 8) * 8;
// Free Svátek: 8h per holiday date the user did not work.
const holidayDates = holidaysInMonth(yr, mo);
const workedDates = new Set(
userRecords
.filter((r) => (r.leave_type || "work") === "work")
.map((r) => normalizeDateStr(r.shift_date))
.filter(Boolean),
);
let freeHolidayHours = 0;
let workedHolidayCount = 0;
for (const hd of holidayDates) {
if (workedDates.has(hd)) workedHolidayCount++;
else freeHolidayHours += 8;
}
// Fund: count Mon-Fri (incl. holidays) × 8h.
let rawBizDays = 0;
const cur = new Date(yr, mo - 1, 1);
while (cur.getMonth() === mo - 1) {
const dow = cur.getDay();
if (dow !== 0 && dow !== 6) rawBizDays++;
cur.setDate(cur.getDate() + 1);
}
const businessDays = rawBizDays;
const fund = businessDays * 8;
// Včetně svátků a přesčasů: floor(worked/8)*8 worked_holiday*8 + vacation + remainder.
// (A worked holiday counts toward Odpracováno, but its 8h should not flow
// into Přesčas — so we subtract it here. Unworked holidays are paid via
// the fund and don't affect this line.)
const remainder = workedHoursRaw - odpracovano;
const vcetneSv =
odpracovano - workedHolidayCount * 8 + vacationHours + remainder;
// Přesčas = #2 - #1.
const prescas = vcetneSv - odpracovano;
// Rekapitulace — single shared implementation (accountant spec 2026-07):
// Odpracováno = all worked hours EXCEPT hours worked on holidays
// Vč. svátků a přesč. = ALL worked hours (line2 line1 = Svátek)
// Přesčas = max(0, worked fond)
// Svátek = hours actually worked on holiday dates
const s = computeMzdaSummary(userRecords, printData.month);
const summaryHtml = `<div class="user-summary">
<div class="summary-row">
<span class="summary-label">Odpracováno:</span>
<span class="summary-value">${formatHoursDecimal(odpracovano * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.odpracovano * 60)}h</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">${formatHoursDecimal(vcetneSv * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.vcetneSvatku * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Dovolená:</span>
<span class="summary-value">${formatHoursDecimal(vacationHours * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.vacationHours * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Přesčas:</span>
<span class="summary-value">${formatHoursDecimal(prescas * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.prescas * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Svátek:</span>
<span class="summary-value">${formatHoursDecimal(freeHolidayHours * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.svatekHours * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">So/Ne:</span>
<span class="summary-value">${formatHoursDecimal(weekendHoursRaw * 60)}h</span>
<span class="summary-value">${formatHoursDecimal(s.weekendHours * 60)}h</span>
</div>
<div class="summary-row">
<span class="summary-label">Práce v noci:</span>
<span class="summary-value">${formatHoursDecimal(nightMinutes)}h</span>
<span class="summary-value">${formatHoursDecimal(s.nightMinutes)}h</span>
</div>
<div class="summary-row summary-fund">
<span class="summary-label">Fond měsíce:</span>
<span class="summary-value">${formatHoursDecimal(fund * 60)}h (${businessDays} dnů)</span>
<span class="summary-value">${formatHoursDecimal(s.fund * 60)}h (${s.businessDays} dnů)</span>
</div>
<div class="legend">
<span class="legend-item"><span class="legend-swatch weekend"></span>Víkend (So/Ne)</span>

View File

@@ -1,6 +1,6 @@
/**
* Single source of truth for document status labels (Czech) + chip colors
* (MUI semantic) across the Offers / Invoices / Orders modules.
* (MUI semantic) across the Offers / Invoices / Orders / Projects modules.
*
* Previously every list AND detail page defined its own `STATUS_LABELS` +
* `STATUS_COLORS` maps. They drifted — most notably the issued-invoice status
@@ -46,7 +46,7 @@ export const ORDER_STATUS: Record<string, StatusMeta> = {
prijata: { label: "Přijatá", color: "info" },
v_realizaci: { label: "V realizaci", color: "warning" },
dokoncena: { label: "Dokončená", color: "success" },
stornovana: { label: "Stornována", color: "error" },
stornovana: { label: "Stornovaná", color: "error" },
};
/** ISSUED ORDER / objednávka vydaná (issued_orders). */
@@ -75,6 +75,17 @@ export const RECEIVED_INVOICE_STATUS: Record<string, StatusMeta> = {
paid: { label: "Uhrazena", color: "success" },
};
/**
* PROJECT (projects). Czech-keyed like customer orders. Colors follow the
* app-wide convention: open/in-progress = info, done = success,
* cancelled = error.
*/
export const PROJECT_STATUS: Record<string, StatusMeta> = {
aktivni: { label: "Aktivní", color: "info" },
dokonceny: { label: "Dokončený", color: "success" },
zruseny: { label: "Zrušený", color: "error" },
};
/**
* Display label for a document's official number. Drafts (deferred numbering)
* have a NULL/empty number until they are finalized — show "Koncept" instead

View File

@@ -1,28 +0,0 @@
import { queryOptions } from "@tanstack/react-query";
import { jsonQuery } from "../apiAdapter";
export const auditLogOptions = (filters: {
search?: string;
action?: string;
entityType?: string;
dateFrom?: string;
dateTo?: string;
page?: number;
}) =>
queryOptions({
queryKey: ["audit-log", filters],
queryFn: () => {
const params = new URLSearchParams();
if (filters.search) params.set("search", filters.search);
if (filters.action) params.set("action", filters.action);
if (filters.entityType) params.set("entity_type", filters.entityType);
if (filters.dateFrom) params.set("date_from", filters.dateFrom);
if (filters.dateTo) params.set("date_to", filters.dateTo);
if (filters.page) params.set("page", String(filters.page));
const qs = params.toString();
return jsonQuery<{
data: Record<string, unknown>[];
pagination: Record<string, unknown>;
}>(`/api/admin/audit-log${qs ? `?${qs}` : ""}`);
},
});

View File

@@ -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;
@@ -84,6 +85,7 @@ export interface InvoiceDetail {
bank_account_id?: number | null;
items?: InvoiceItem[];
sections?: InvoiceSection[];
selected_custom_fields?: number[];
subtotal: number;
vat_amount: number;
total: number;

View File

@@ -60,6 +60,7 @@ export interface IssuedOrderDetail extends IssuedOrder {
sections: IssuedOrderSection[];
supplier: Record<string, unknown> | null;
valid_transitions: string[];
selected_custom_fields: number[];
/** Fresh edit lock held by ANOTHER user (same shape as offers), else null. */
locked_by: {
user_id: number;
@@ -143,6 +144,9 @@ export const issuedOrderDetailOptions = (id: string | undefined) =>
// 404s (deleted/missing orders) are not transient. Retrying just spams
// GETs and keeps the detail page on an infinite spinner.
retry: false,
// IssuedOrderDetail toasts its own Czech error + navigates away (and
// suppresses it during delete) — the global QueryCache toast would double up.
meta: { suppressGlobalErrorToast: true },
});
export const issuedOrderNextNumberOptions = () =>

View File

@@ -143,6 +143,7 @@ export interface OfferItemData {
quantity: number;
unit: string;
unit_price: number;
discount?: number;
is_included_in_total: boolean;
position?: number;
}
@@ -183,6 +184,7 @@ export interface OfferDetailData {
locked_by: OfferLockInfo | null;
/** Legal next statuses, computed server-side (same contract as issued orders). */
valid_transitions: string[];
selected_custom_fields: number[];
}
export const offerDetailOptions = (id: string | undefined) =>
@@ -193,6 +195,9 @@ export const offerDetailOptions = (id: string | undefined) =>
// 404s (deleted/missing offers) are not transient. Retrying just spams
// GETs and fires the detail-page redirect toast repeatedly.
retry: false,
// OfferDetail toasts its own Czech error + navigates away (and suppresses
// it during delete) — the global QueryCache toast would double up.
meta: { suppressGlobalErrorToast: true },
});
export const offerNextNumberOptions = () =>

View File

@@ -28,6 +28,8 @@ export interface ProjectData {
quotation_number?: string;
has_nas_folder?: boolean;
project_notes?: ProjectNote[];
/** Valid status-machine targets from the current status (server-computed). */
valid_transitions?: string[];
}
export interface Project {

View File

@@ -18,6 +18,20 @@ export interface Role {
display_name: string;
}
/**
* Query-key domains to invalidate on any user create/update/delete: a user's
* display name is embedded in these domains (CLAUDE.md: "user CRUD →
* trips+attendance").
*/
export const USER_INVALIDATE: readonly string[] = [
"users",
"trips",
"attendance",
"leave-requests",
"leave",
"projects",
];
export const userListOptions = (permission?: string) =>
queryOptions({
queryKey: ["users", { permission }],

View File

@@ -1,6 +1,39 @@
import { QueryClient } from "@tanstack/react-query";
import { QueryCache, QueryClient } from "@tanstack/react-query";
/**
* Global query-error notifier. AlertContext registers its `error()` toast
* here on mount; until then failures fall back to console.error.
*/
let queryErrorNotifier: ((msg: string) => void) | null = null;
export function registerQueryErrorNotifier(fn: (msg: string) => void) {
queryErrorNotifier = fn;
}
/** Rate limit: at most one query-error toast per window (a page can have many failing queries). */
const ERROR_TOAST_WINDOW_MS = 4000;
let lastErrorToastAt = 0;
export const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
// Pages with bespoke error handling (detail pages that toast + navigate,
// purely-local queries like QR generation) opt out via query meta.
if (query.meta?.suppressGlobalErrorToast) return;
// Background refetch failure with stale data still on screen — stay silent.
if (query.state.data !== undefined) return;
// 401s are handled by apiFetch/AuthContext (token refresh / logout).
if (error instanceof Error && error.message === "Unauthorized") return;
const now = Date.now();
if (now - lastErrorToastAt < ERROR_TOAST_WINDOW_MS) return;
lastErrorToastAt = now;
if (queryErrorNotifier) {
queryErrorNotifier("Nepodařilo se načíst data ze serveru");
} else {
console.error("Query failed before alert notifier registered:", error);
}
},
}),
defaultOptions: {
queries: {
staleTime: 30_000,

View File

@@ -6,6 +6,7 @@ import { useAuth } from "../context/AuthContext";
import { useAlert } from "../context/AlertContext";
import Forbidden from "../components/Forbidden";
import { czechPlural } from "../utils/formatters";
import useDebounce from "../hooks/useDebounce";
import apiFetch from "../utils/api";
import { useApiMutation } from "../lib/queries/mutations";
import { ENTITY_TYPE_LABELS } from "../lib/entityTypeLabels";
@@ -122,6 +123,9 @@ export default function AuditLog() {
date_from: "",
date_to: "",
});
// Raw value stays in the TextField; only the debounced value hits the
// queryKey/request, so typing doesn't refire the query on every keystroke.
const debouncedSearch = useDebounce(filters.search, 300);
const [page, setPage] = useState(1);
const [perPage] = useState(50);
const [showCleanup, setShowCleanup] = useState(false);
@@ -136,7 +140,7 @@ export default function AuditLog() {
queryKey: [
"audit-log",
{
search: filters.search,
search: debouncedSearch,
action: filters.action,
entityType: filters.entity_type,
dateFrom: filters.date_from,
@@ -150,7 +154,7 @@ export default function AuditLog() {
page: String(page),
per_page: String(perPage),
});
if (filters.search) params.set("search", filters.search);
if (debouncedSearch) params.set("search", debouncedSearch);
if (filters.action) params.set("action", filters.action);
if (filters.entity_type) params.set("entity_type", filters.entity_type);
if (filters.date_from) params.set("date_from", filters.date_from);
@@ -177,6 +181,12 @@ export default function AuditLog() {
// doesn't drop to <LoadingState/> (which unmounts PageEnter and replays the
// whole entrance animation on every filter change).
placeholderData: keepPreviousData,
// logAudit() writes on every mutation app-wide and none of those
// mutations invalidate ["audit-log"], so cached data goes stale the
// moment anything happens elsewhere — always refetch on mount (same
// rationale as dashboardOptions).
staleTime: 0,
refetchOnMount: "always",
});
const logs: AuditLogEntry[] = logsData?.data ?? [];

View File

@@ -124,7 +124,7 @@ export default function Dashboard() {
});
alert.success(result?.message || "Docházka zaznamenána");
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba pripojeni");
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {
setPunching(false);
}
@@ -348,7 +348,9 @@ export default function Dashboard() {
display: "grid",
gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr 1fr" },
gap: 3,
alignItems: "start",
// stretch (not start) so the cards in a row share one height —
// even bottoms instead of ragged content-height cards.
alignItems: "stretch",
mb: 3,
}}
>
@@ -360,10 +362,18 @@ export default function Dashboard() {
<DashAttendanceToday attendance={dashData?.attendance ?? null} />
)}
{/* Pravy sloupec: projekty + nabidky */}
<Box sx={{ display: "flex", flexDirection: "column", gap: 3 }}>
{/* Pravy sloupec: projekty + nabidky — both grow so the stacked
cards fill the column to match the neighbouring cards' height. */}
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: 3,
height: "100%",
}}
>
{dashData?.projects && (
<Card sx={{ display: "flex", flexDirection: "column" }}>
<Card sx={{ display: "flex", flexDirection: "column", flex: 1 }}>
<Box
sx={{
display: "flex",
@@ -421,7 +431,7 @@ export default function Dashboard() {
)}
{dashData?.offers && (
<Card sx={{ display: "flex", flexDirection: "column" }}>
<Card sx={{ display: "flex", flexDirection: "column", flex: 1 }}>
<Box
sx={{
display: "flex",
@@ -498,7 +508,7 @@ export default function Dashboard() {
display: "grid",
gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr" },
gap: 3,
alignItems: "start",
alignItems: "stretch",
}}
>
<DashProfile

View File

@@ -27,6 +27,7 @@ import RichEditor from "../components/RichEditor";
import SectionsEditor, {
type DocumentSection,
} from "../components/document/SectionsEditor";
import CustomFieldsPrintPicker from "../components/document/CustomFieldsPrintPicker";
import {
DndContext,
closestCenter,
@@ -185,9 +186,34 @@ interface InvoiceItem {
quantity: string | number;
unit: string;
unit_price: string | number;
/** Per-item discount as a percentage (0100). */
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 +279,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 +374,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 +491,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 +555,7 @@ export default function InvoiceDetail() {
quantity: 1,
unit: "ks",
unit_price: 0,
discount: 0,
vat_rate: 21,
}),
[],
@@ -569,6 +612,9 @@ export default function InvoiceDetail() {
// Rich-text CZ/EN "Obsah" sections (printed after the items on the PDF —
// shared editor with offers/issued orders).
const [sections, setSections] = useState<DocumentSection[]>([]);
const [selectedCustomFields, setSelectedCustomFields] = useState<number[]>(
[],
);
const [items, setItems] = useState<InvoiceItem[]>(() => [
{
_key: "inv-1",
@@ -577,6 +623,7 @@ export default function InvoiceDetail() {
quantity: 1,
unit: "ks",
unit_price: 0,
discount: 0,
vat_rate: 21,
},
]);
@@ -628,6 +675,10 @@ export default function InvoiceDetail() {
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"],
@@ -751,6 +802,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
@@ -773,11 +825,15 @@ export default function InvoiceDetail() {
: [];
setSections(mappedSections);
const mappedCustomFields = inv.selected_custom_fields ?? [];
setSelectedCustomFields(mappedCustomFields);
// Capture initial snapshot for dirty-checking
initialSnapshotRef.current = JSON.stringify({
form: formData,
items: mappedItems,
sections: mappedSections,
selectedCustomFields: mappedCustomFields,
});
setDataReady(true);
@@ -848,6 +904,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,
})),
);
@@ -874,15 +931,21 @@ export default function InvoiceDetail() {
// Edit mode: captured inside the sync effect from raw query data.
// Create mode: captured on the first render after sync effects populate the form.
if (dataReady && !initialSnapshotRef.current) {
initialSnapshotRef.current = JSON.stringify({ form, items, sections });
initialSnapshotRef.current = JSON.stringify({
form,
items,
sections,
selectedCustomFields,
});
}
const isDirty = useMemo(() => {
if (!initialSnapshotRef.current) return false;
return (
JSON.stringify({ form, items, sections }) !== initialSnapshotRef.current
JSON.stringify({ form, items, sections, selectedCustomFields }) !==
initialSnapshotRef.current
);
}, [form, items, sections]);
}, [form, items, sections, selectedCustomFields]);
useEffect(() => {
if (!isDirty) return;
@@ -967,8 +1030,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) {
@@ -989,7 +1051,7 @@ export default function InvoiceDetail() {
>({
url: () => (isEdit ? `${API_BASE}/invoices/${id}` : `${API_BASE}/invoices`),
method: () => (isEdit ? "PUT" : "POST"),
invalidate: ["invoices", "orders"],
invalidate: ["invoices", "orders", "projects"],
onSuccess: (data) => {
const invoiceId = isEdit ? Number(id) : data.invoice_id;
// PDF binary generation — KEEP as raw apiFetch
@@ -1002,13 +1064,13 @@ export default function InvoiceDetail() {
const statusMutation = useApiMutation<{ status: string }, unknown>({
url: () => `${API_BASE}/invoices/${id}`,
method: () => "PUT",
invalidate: ["invoices", "orders"],
invalidate: ["invoices", "orders", "projects"],
});
const invoiceDeleteMutation = useApiMutation<void, unknown>({
url: () => `${API_BASE}/invoices/${id}`,
method: () => "DELETE",
invalidate: ["invoices", "orders"],
invalidate: ["invoices", "orders", "projects"],
});
const handleCreateSubmit = async (targetStatus?: string) => {
@@ -1038,6 +1100,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) => ({
@@ -1046,6 +1109,7 @@ export default function InvoiceDetail() {
content: s.content,
position: i,
})),
selected_custom_fields: selectedCustomFields,
};
// Only set status when a target is given (create-as-draft / create-as-live
// / finalize). Editing a live invoice sends no status — the backend keeps
@@ -1058,7 +1122,12 @@ export default function InvoiceDetail() {
const data = await saveMutation.mutateAsync(payload);
alert.success(isEdit ? "Faktura byla uložena" : "Faktura byla vytvořena");
initialSnapshotRef.current = JSON.stringify({ form, items, sections });
initialSnapshotRef.current = JSON.stringify({
form,
items,
sections,
selectedCustomFields,
});
if (!isEdit) {
navigate(`/invoices/${data.invoice_id}`);
}
@@ -1361,9 +1430,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;
@@ -1494,6 +1561,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>
@@ -1504,9 +1576,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;
@@ -1555,6 +1625,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)
@@ -2152,6 +2229,15 @@ export default function InvoiceDetail() {
]}
/>
</Field>
<Box sx={{ mt: 2 }}>
<CustomFieldsPrintPicker
fields={companySettings?.custom_fields ?? []}
selected={selectedCustomFields}
disabled={false}
onChange={setSelectedCustomFields}
/>
</Box>
</Card>
{/* Items */}
@@ -2238,6 +2324,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

View File

@@ -20,6 +20,7 @@ import {
import { normalizeDateStr } from "../utils/attendanceHelpers";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import {
invoiceListOptions,
invoiceStatsOptions,
@@ -214,6 +215,7 @@ export default function Invoices() {
const [receivedUploadOpen, setReceivedUploadOpen] = useState(false);
const { sort, order, handleSort } = useTableSort("invoice_number");
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [page, setPage] = useState(1);
const [statusFilter, setStatusFilter] = useState("");
@@ -269,6 +271,11 @@ export default function Invoices() {
invoice: Invoice | null;
}>({ show: false, invoice: null });
const [deleting, setDeleting] = useState(false);
const [paidConfirm, setPaidConfirm] = useState<{
show: boolean;
invoice: Invoice | null;
}>({ show: false, invoice: null });
const [markingPaid, setMarkingPaid] = useState(false);
const [pdfLoading, setPdfLoading] = useState<number | null>(null);
const queryClient = useQueryClient();
@@ -279,7 +286,7 @@ export default function Invoices() {
isFetching: loading,
} = usePaginatedQuery<Invoice>(
invoiceListOptions({
search,
search: debouncedSearch,
sort,
order,
page,
@@ -294,7 +301,7 @@ export default function Invoices() {
// matches what's shown. Separate from the KPI `statsQuery` above.
const listTotalsQuery = useQuery(
invoiceTotalsOptions({
search,
search: debouncedSearch,
status: statusFilter || undefined,
month: statsMonth,
year: statsYear,
@@ -336,16 +343,21 @@ export default function Invoices() {
}
};
const toggleStatus = async (inv: Invoice) => {
if (inv.status === "paid") return;
const handleMarkPaid = async () => {
if (!paidConfirm.invoice) return;
setMarkingPaid(true);
try {
const res = await apiFetch(`${API_BASE}/invoices/${inv.id}`, {
const res = await apiFetch(
`${API_BASE}/invoices/${paidConfirm.invoice.id}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status: "paid" }),
});
},
);
const data = await res.json();
if (data.success) {
setPaidConfirm({ show: false, invoice: null });
alert.success("Faktura označena jako zaplacená");
queryClient.invalidateQueries({ queryKey: ["invoices"] });
queryClient.invalidateQueries({ queryKey: ["orders"] });
@@ -355,6 +367,8 @@ export default function Invoices() {
}
} catch {
alert.error("Chyba připojení");
} finally {
setMarkingPaid(false);
}
};
@@ -557,7 +571,8 @@ export default function Invoices() {
<StatusChip
label={statusLabel(INVOICE_STATUS, inv.status)}
color={statusColor(INVOICE_STATUS, inv.status)}
onClick={() => toggleStatus(inv)}
title="Označit jako zaplacenou"
onClick={() => setPaidConfirm({ show: true, invoice: inv })}
/>
),
},
@@ -613,7 +628,8 @@ export default function Invoices() {
>
{inv.status === "paid" ? ViewIcon : EditIcon}
</IconButton>
{hasPermission("invoices.view") && (
{/* Drafts have no number yet — /file 404s for them. */}
{hasPermission("invoices.view") && inv.invoice_number && (
<IconButton
size="small"
onClick={() => handlePdf(inv)}
@@ -760,7 +776,7 @@ export default function Invoices() {
sortDir={order}
onSort={handleSort}
empty={
search || statusFilter ? (
debouncedSearch || statusFilter ? (
<EmptyState title="Žádné faktury neodpovídají filtru." />
) : (
<EmptyState
@@ -807,12 +823,23 @@ export default function Invoices() {
onClose={() => setDeleteConfirm({ show: false, invoice: null })}
onConfirm={handleDelete}
title="Smazat fakturu"
message={`Opravdu chcete smazat fakturu "${deleteConfirm.invoice?.invoice_number}"? Tato akce je nevratná.`}
message={`Opravdu chcete smazat fakturu "${documentNumberLabel(deleteConfirm.invoice?.invoice_number)}"? Tato akce je nevratná.`}
confirmText="Smazat"
cancelText="Zrušit"
confirmVariant="danger"
loading={deleting}
/>
<ConfirmDialog
isOpen={paidConfirm.show}
onClose={() => setPaidConfirm({ show: false, invoice: null })}
onConfirm={handleMarkPaid}
title="Označit fakturu jako zaplacenou"
message={`Označit fakturu "${documentNumberLabel(paidConfirm.invoice?.invoice_number)}" jako zaplacenou? Tato akce je nevratná.`}
confirmText="Označit jako zaplacenou"
cancelText="Zrušit"
loading={markingPaid}
/>
</>
</TabPanel>
</PageEnter>

View File

@@ -23,6 +23,7 @@ import SectionsEditor, {
type DocumentSection,
} from "../components/document/SectionsEditor";
import LockBanner from "../components/document/LockBanner";
import CustomFieldsPrintPicker from "../components/document/CustomFieldsPrintPicker";
import { useDocumentLock } from "../hooks/useDocumentLock";
import { useUnsavedChangesGuard } from "../hooks/useUnsavedChangesGuard";
import { useDocumentPdf } from "../hooks/useDocumentPdf";
@@ -137,6 +138,7 @@ interface IssuedOrderSavePayload {
internal_notes: string;
items: IssuedOrderItemPayload[];
sections: IssuedOrderSectionPayload[];
selected_custom_fields: number[];
status?: string;
}
@@ -164,6 +166,9 @@ export default function IssuedOrderDetail() {
emptyDocumentItem(),
]);
const [sections, setSections] = useState<DocumentSection[]>([]);
const [selectedCustomFields, setSelectedCustomFields] = useState<number[]>(
[],
);
const [errors, setErrors] = useState<Record<string, string>>({});
const [saving, setSaving] = useState(false);
// Which save action is in flight ("draft" | the live status | "save"), so
@@ -255,7 +260,7 @@ export default function IssuedOrderDetail() {
const canExport = hasPermission("orders.view");
const { isDirty, markClean } = useUnsavedChangesGuard(
{ form, items, sections },
{ form, items, sections, selectedCustomFields },
!isEdit || dataReady,
);
@@ -293,8 +298,12 @@ 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()];
: // Issued orders may be issued by sections alone — a saved order with
// no items reopens with an empty list (not a blank starter row).
[];
setItems(mappedItems);
const mappedSections =
@@ -306,6 +315,7 @@ export default function IssuedOrderDetail() {
}))
: [];
setSections(mappedSections);
setSelectedCustomFields(d.selected_custom_fields ?? []);
setLockedBy(d.locked_by ?? null);
// Acquire the edit lock when nobody holds it, the order is still
@@ -393,8 +403,18 @@ export default function IssuedOrderDetail() {
const newErrors: Record<string, string> = {};
if (!form.supplier_id) newErrors.supplier_id = "Vyberte dodavatele";
if (!form.order_date) newErrors.order_date = "Zadejte datum";
if (items.length === 0 || items.every((i) => !i.description.trim())) {
newErrors.items = "Přidejte alespoň jednu položku";
// Items are optional (an order may be issued by sections alone), but a
// completely blank order must not be finalizable: require at least one
// item with a description OR one non-empty section (title or content).
const hasItem = items.some((i) => i.description.trim());
const hasSection = sections.some(
(s) =>
(s.title_cz || "").trim() ||
(s.title || "").trim() ||
(s.content || "").replace(/<[^>]*>/g, "").trim(),
);
if (!hasItem && !hasSection) {
newErrors.items = "Přidejte alespoň jednu položku nebo obsah";
}
setErrors(newErrors);
if (Object.keys(newErrors).length > 0) return;
@@ -428,6 +448,7 @@ export default function IssuedOrderDetail() {
content: s.content,
position: i,
})),
selected_custom_fields: selectedCustomFields,
};
// Only set status when a target is given (create-as-draft / create-as-live
// / finalize). Editing a live order sends no status — the backend keeps
@@ -872,6 +893,15 @@ export default function IssuedOrderDetail() {
placeholder="Objednáváme si u Vás: (ponechte prázdné pro výchozí)"
/>
</Field>
<Box sx={{ mt: 2 }}>
<CustomFieldsPrintPicker
fields={companySettings?.custom_fields ?? []}
selected={selectedCustomFields}
disabled={!editable}
onChange={setSelectedCustomFields}
/>
</Box>
</Card>
{/* Items */}
@@ -881,6 +911,7 @@ export default function IssuedOrderDetail() {
currency={form.currency}
readOnly={!editable}
error={errors.items}
allowEmpty
/>
{/* Rich-text PDF sections — the free-form PDF content lives here */}

View File

@@ -436,7 +436,7 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
action={
hasPermission("orders.create") ? (
<Button component={RouterLink} to="/orders/issued/new">
Vytvořit objednávku
Nová vydaná objednávka
</Button>
) : undefined
}

View File

@@ -87,7 +87,7 @@ export default function LeaveRequests() {
>({
url: ({ id }) => `${API_BASE}/leave-requests/${id}`,
method: () => "DELETE",
invalidate: ["leave-requests", "leave", "attendance"],
invalidate: ["leave-requests", "leave", "attendance", "users", "dashboard"],
onSuccess: (data) => {
setCancelModal({ open: false, id: null });
alert.success(data?.message || "Žádost byla zrušena");

View File

@@ -33,6 +33,7 @@ import SectionsEditor, {
type DocumentSection,
} from "../components/document/SectionsEditor";
import LockBanner from "../components/document/LockBanner";
import CustomFieldsPrintPicker from "../components/document/CustomFieldsPrintPicker";
import { useDocumentLock } from "../hooks/useDocumentLock";
import { useUnsavedChangesGuard } from "../hooks/useUnsavedChangesGuard";
import { useDocumentPdf } from "../hooks/useDocumentPdf";
@@ -93,6 +94,7 @@ interface OfferItemPayload {
quantity: number;
unit: string;
unit_price: number;
discount: number;
is_included_in_total: boolean;
position: number;
}
@@ -113,6 +115,7 @@ interface OfferSavePayload {
language: string;
items: OfferItemPayload[];
sections: OfferSectionPayload[];
selected_custom_fields: number[];
status?: string;
}
@@ -177,6 +180,9 @@ export default function OfferDetail() {
emptyDocumentItem(),
]);
const [sections, setSections] = useState<DocumentSection[]>([]);
const [selectedCustomFields, setSelectedCustomFields] = useState<number[]>(
[],
);
const [orderInfo, setOrderInfo] = useState<OfferOrderInfo | null>(null);
const [offerStatus, setOfferStatus] = useState<string>("");
const [quotationNumber, setQuotationNumber] = useState("");
@@ -269,7 +275,7 @@ export default function OfferDetail() {
const canDelete = isEdit && !orderInfo && !isInvalidated && !isLockedByOther;
const { markClean } = useUnsavedChangesGuard(
{ form, items, sections },
{ form, items, sections, selectedCustomFields },
!loading,
);
@@ -303,6 +309,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()];
@@ -316,6 +323,7 @@ export default function OfferDetail() {
}))
: [];
setSections(mappedSections);
setSelectedCustomFields(d.selected_custom_fields ?? []);
markClean({ form: formData, items: mappedItems, sections: mappedSections });
setOfferStatus(d.status || "");
setOrderInfo(d.order ?? null);
@@ -433,6 +441,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,
})),
@@ -442,6 +451,7 @@ export default function OfferDetail() {
content: s.content,
position: i,
})),
selected_custom_fields: selectedCustomFields,
};
// Only set status when a target is given (create-as-draft / create-as-live
// / finalize). Editing a live offer sends no status — the backend keeps
@@ -926,6 +936,15 @@ export default function OfferDetail() {
/>
</Field>
</Box>
<Box sx={{ mt: 2 }}>
<CustomFieldsPrintPicker
fields={companySettings?.custom_fields ?? []}
selected={selectedCustomFields}
disabled={readOnly}
onChange={setSelectedCustomFields}
/>
</Box>
</Card>
{/* Items (drag-and-drop, offers carry the "V ceně" column) */}
@@ -936,6 +955,7 @@ export default function OfferDetail() {
readOnly={readOnly}
error={errors.items}
showIncludedInTotal
showDiscount
itemDescriptionMaxLength={8000}
templatesSlot={
itemTemplates && itemTemplates.length > 0 ? (
@@ -957,6 +977,7 @@ export default function OfferDetail() {
quantity: 1,
unit: "ks",
unit_price: template.default_price || 0,
discount: 0,
is_included_in_total: true,
},
]);

View File

@@ -11,6 +11,9 @@ import ListItemText from "@mui/material/ListItemText";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import StatusChipMenu, {
type StatusChipAction,
} from "../components/StatusChipMenu";
import apiFetch from "../utils/api";
import {
@@ -41,7 +44,6 @@ import {
Field,
TextField,
Select,
StatusChip,
FileUpload,
EmptyState,
FilterBar,
@@ -413,6 +415,21 @@ export default function Offers() {
},
});
// Quick-action finalize (draft → active) from the status chip menu. A
// status-only PUT deliberately passes the editable-state guard; the number
// is assigned in-transaction server-side (same semantics as the detail).
const activateMutation = useApiMutation<
{ id: number; status: "active" },
{ id: number }
>({
url: (input) => `${API_BASE}/offers/${input.id}`,
method: () => "PUT",
invalidate: ["offers", "orders", "projects", "invoices"],
onSuccess: () => {
alert.success("Nabídka byla aktivována");
},
});
if (!hasPermission("offers.view")) return <Forbidden />;
const handleDuplicate = async (quotation: Quotation) => {
@@ -489,6 +506,89 @@ export default function Offers() {
}
};
const handleActivate = async (q: Quotation) => {
try {
await activateMutation.mutateAsync({ id: q.id, status: "active" });
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
// Re-throw so the chip's ConfirmDialog stays open (app convention).
throw e;
}
// A finalized offer now has its official number — archive the PDF on the
// NAS, exactly like OfferDetail after finalize. Fire-and-forget: never
// block the toast/refresh — but a failure is surfaced, not swallowed.
apiFetch(`${API_BASE}/offers-pdf/${q.id}?save=1`)
.then((res) => {
if (!res.ok) alert.error("Nepodařilo se archivovat PDF nabídky na NAS");
})
.catch(() => alert.error("Nepodařilo se archivovat PDF nabídky na NAS"));
};
// "Zneplatnit" chip-menu entry — same wording as the page's existing
// invalidate ConfirmDialog and the same row mutation underneath.
const invalidateChipAction = (q: Quotation): StatusChipAction => ({
key: "invalidated",
label: "Zneplatnit",
danger: true,
confirm: {
title: "Zneplatnit nabídku",
message: `Opravdu chcete zneplatnit nabídku „${documentNumberLabel(q.quotation_number)}“? Nabídka bude pouze pro čtení a nepůjde upravovat.`,
confirmText: "Zneplatnit",
},
onAction: async () => {
try {
await invalidateMutation.mutateAsync(q.id);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
// Re-throw so the chip's ConfirmDialog stays open (app convention).
throw e;
}
},
});
// Quick actions for the status chip menu, by offer status. Only rendered
// when the user holds offers.edit (the page's mutating-action permission);
// "Vytvořit objednávku…" additionally mirrors the create-order icon's gates
// (active + no existing order + orders.create) and opens the same modal.
const statusQuickActions = (q: Quotation): StatusChipAction[] => {
switch (q.status) {
case "draft":
return [
{
key: "active",
label: "Aktivovat",
confirm: {
title: "Aktivovat nabídku",
message: `Nabídce „${documentNumberLabel(q.quotation_number)}“ bude přiděleno oficiální číslo. Aktivovat?`,
confirmText: "Aktivovat",
},
onAction: () => handleActivate(q),
},
];
case "active": {
const actions: StatusChipAction[] = [];
if (!q.order_id && hasPermission("orders.create")) {
actions.push({
key: "create-order",
label: "Vytvořit objednávku…",
onAction: () => {
setCustomerOrderNumber("");
setOrderAttachment(null);
setOrderModal({ show: true, quotation: q });
},
});
}
actions.push(invalidateChipAction(q));
return actions;
}
case "ordered":
return [invalidateChipAction(q)];
default:
// `invalidated` (and any unknown status): plain chip, no actions.
return [];
}
};
// Only show the full-page skeleton on the very first load; on subsequent
// refetches (filter/customer/tab/page change) keep the table visible (the
// Card dims via isFetching) so it doesn't flash.
@@ -572,14 +672,19 @@ export default function Offers() {
// The offer's own status is `active`/`ordered`/`invalidated`. When its
// linked order is completed, surface that as "Dokončená" (success) —
// matching the OfferDetail header chip and the completed row tint.
// Completed rows are read-only everywhere on this page, so the chip
// stays plain (no quick actions) in that derived state.
const completed =
q.status !== "invalidated" && q.order_status === "dokoncena";
return completed ? (
<StatusChip label="Dokončená" color="success" />
<StatusChipMenu label="Dokončená" color="success" />
) : (
<StatusChip
<StatusChipMenu
label={statusLabel(OFFER_STATUS, q.status)}
color={statusColor(OFFER_STATUS, q.status)}
actions={
hasPermission("offers.edit") ? statusQuickActions(q) : undefined
}
/>
);
},

View File

@@ -116,7 +116,7 @@ export default function OrderDetail() {
useEffect(() => {
if (orderQuery.error) {
alert.error("Nepodařilo se načíst objednávku");
navigate("/orders");
navigate("/orders?tab=prijate");
}
}, [orderQuery.error]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -159,13 +159,13 @@ export default function OrderDetail() {
const statusMutation = useApiMutation<{ status: string }, unknown>({
url: () => `${API_BASE}/orders/${id}`,
method: () => "PUT",
invalidate: ["orders", "invoices"],
invalidate: ["orders", "offers", "projects", "invoices"],
});
const notesMutation = useApiMutation<{ notes: string }, unknown>({
url: () => `${API_BASE}/orders/${id}`,
method: () => "PUT",
invalidate: ["orders", "invoices"],
invalidate: ["orders", "offers", "projects", "invoices"],
});
const orderDeleteMutation = useApiMutation<
@@ -174,7 +174,7 @@ export default function OrderDetail() {
>({
url: () => `${API_BASE}/orders/${id}`,
method: () => "DELETE",
invalidate: ["orders", "invoices"],
invalidate: ["orders", "offers", "projects", "invoices"],
});
if (!hasPermission("orders.view")) return <Forbidden />;
@@ -277,7 +277,7 @@ export default function OrderDetail() {
try {
await orderDeleteMutation.mutateAsync({ delete_files: deleteFiles });
alert.success("Objednávka byla smazána");
navigate("/orders");
navigate("/orders?tab=prijate");
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {
@@ -292,6 +292,11 @@ export default function OrderDetail() {
if (!order) return null;
// From a terminal state the backend offers v_realizaci as a REOPEN — label
// it "Obnovit" (not "Zahájit realizaci") and note the no-cascade semantics.
const isReopen =
order.status === "dokoncena" || order.status === "stornovana";
const itemRows: ItemRow[] = (order.items ?? []).map((item, index) => ({
...item,
_index: index,
@@ -396,7 +401,7 @@ export default function OrderDetail() {
>
<Button
component={RouterLink}
to="/orders"
to="/orders?tab=prijate"
variant="outlined"
color="inherit"
startIcon={BackIcon}
@@ -475,6 +480,8 @@ export default function OrderDetail() {
>
{statusChanging === status
? "Zpracovávám…"
: isReopen && status === "v_realizaci"
? "Obnovit"
: TRANSITION_LABELS[status] || status}
</Button>
))}
@@ -782,9 +789,15 @@ export default function OrderDetail() {
onClose={() => setStatusConfirm({ show: false, status: null })}
onConfirm={handleStatusChange}
title="Změnit stav objednávky"
message={`Opravdu chcete změnit stav objednávky "${order.order_number}" na "${statusLabel(ORDER_STATUS, statusConfirm.status)}"?${statusConfirm.status === "dokoncena" ? " Projekt bude automaticky dokončen." : ""}`}
message={
isReopen && statusConfirm.status === "v_realizaci"
? `Opravdu chcete obnovit objednávku "${order.order_number}"? Objednávka se vrátí do stavu "V realizaci". Propojený projekt zůstane beze změny.`
: `Opravdu chcete změnit stav objednávky "${order.order_number}" na "${statusLabel(ORDER_STATUS, statusConfirm.status)}"?${statusConfirm.status === "dokoncena" ? " Projekt bude automaticky dokončen." : ""}`
}
confirmText={
TRANSITION_LABELS[statusConfirm.status || ""] || "Potvrdit"
isReopen && statusConfirm.status === "v_realizaci"
? "Obnovit"
: TRANSITION_LABELS[statusConfirm.status || ""] || "Potvrdit"
}
cancelText="Zrušit"
/>

View File

@@ -122,11 +122,11 @@ export default function Orders() {
startIcon={PlusIcon}
onClick={() => navigate("/orders/issued/new")}
>
Vytvořit objednávku
Nová vydaná objednávka
</Button>
) : (
<Button startIcon={PlusIcon} onClick={() => setCreateOpen(true)}>
Vytvořit objednávku
Nová přijatá objednávka
</Button>
)
) : undefined

View File

@@ -31,22 +31,19 @@ import {
PageEnter,
headerActionsSx,
} from "../ui";
import {
PROJECT_STATUS,
ORDER_STATUS,
statusLabel,
statusColor,
} from "../lib/documentStatus";
const API_BASE = "/api/admin";
const STATUS_LABELS: Record<string, string> = {
aktivni: "Aktivní",
dokonceny: "Dokončený",
zruseny: "Zrušený",
};
const STATUS_COLORS: Record<
string,
"default" | "success" | "error" | "warning" | "info"
> = {
aktivni: "success",
dokonceny: "info",
zruseny: "default",
const TRANSITION_LABELS: Record<string, string> = {
dokonceny: "Dokončit projekt",
zruseny: "Zrušit projekt",
aktivni: "Obnovit projekt",
};
interface User {
@@ -56,7 +53,6 @@ interface User {
interface ProjectForm {
name: string;
status: string;
start_date: string;
end_date: string;
responsible_user_id: string;
@@ -85,11 +81,15 @@ export default function ProjectDetail() {
const [saving, setSaving] = useState(false);
const [form, setForm] = useState<ProjectForm>({
name: "",
status: "aktivni",
start_date: "",
end_date: "",
responsible_user_id: "",
});
const [statusChanging, setStatusChanging] = useState<string | null>(null);
const [statusConfirm, setStatusConfirm] = useState<{
show: boolean;
status: string | null;
}>({ show: false, status: null });
const [deleteConfirm, setDeleteConfirm] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -130,7 +130,6 @@ export default function ProjectDetail() {
if (project && !formInitialized.current) {
setForm({
name: project.name || "",
status: project.status || "aktivni",
start_date: (project.start_date || "").substring(0, 10),
end_date: (project.end_date || "").substring(0, 10),
responsible_user_id: project.responsible_user_id || "",
@@ -150,7 +149,6 @@ export default function ProjectDetail() {
const projectSaveMutation = useApiMutation<
{
name: string;
status: string;
start_date: string | null;
end_date: string | null;
responsible_user_id: string | null;
@@ -162,6 +160,14 @@ export default function ProjectDetail() {
invalidate: ["projects", "warehouse"],
});
// Status transitions (header buttons). A project transition may cascade to
// the linked order (and its documents), so invalidate broadly.
const statusMutation = useApiMutation<{ status: string }, unknown>({
url: () => `${API_BASE}/projects/${id}`,
method: () => "PUT",
invalidate: ["projects", "orders", "offers", "invoices", "warehouse"],
});
const projectDeleteMutation = useApiMutation<
{ delete_files: boolean },
unknown
@@ -198,7 +204,6 @@ export default function ProjectDetail() {
try {
await projectSaveMutation.mutateAsync({
name: form.name,
status: form.status,
start_date: form.start_date || null,
end_date: form.end_date || null,
responsible_user_id: form.responsible_user_id || null,
@@ -211,6 +216,51 @@ export default function ProjectDetail() {
}
};
const handleStatusChange = async () => {
if (!statusConfirm.status) return;
const newStatus = statusConfirm.status;
setStatusChanging(newStatus);
setStatusConfirm({ show: false, status: null });
try {
await statusMutation.mutateAsync({ status: newStatus });
alert.success("Stav byl změněn");
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {
setStatusChanging(null);
}
};
// Confirm message with the cascade note — the linked-order cascade only
// exists when the project actually has a linked order; reopening never
// cascades.
const statusConfirmMessage = (status: string | null): string => {
if (!status || !project) return "";
if (status === "aktivni") {
return (
'Projekt se vrátí do stavu "Aktivní".' +
(project.order_id ? " Propojená objednávka zůstane beze změny." : "")
);
}
const base = `Označit projekt "${project.project_number} ${project.name}" jako ${
status === "zruseny" ? "zrušený" : "dokončený"
}?`;
// The cascade only fires while the order is still open (prijata /
// v_realizaci) — a terminal order (e.g. after a project reopen) stays
// untouched, so don't promise a change that won't happen.
const orderCascades =
project.order_id &&
(project.order_status === "prijata" ||
project.order_status === "v_realizaci");
if (!orderCascades) return base;
return (
base +
(status === "zruseny"
? " Propojená objednávka bude automaticky stornována."
: " Propojená objednávka bude automaticky dokončena.")
);
};
const handleDelete = async () => {
setDeleting(true);
try {
@@ -335,16 +385,31 @@ export default function ProjectDetail() {
</Box>
</Typography>
<StatusChip
label={STATUS_LABELS[project.status] || project.status}
color={STATUS_COLORS[project.status] || "default"}
label={statusLabel(PROJECT_STATUS, project.status)}
color={statusColor(PROJECT_STATUS, project.status)}
/>
</Box>
</Box>
{canEdit && (
<Box sx={headerActionsSx}>
<Button onClick={handleSave} disabled={saving}>
<Button
onClick={handleSave}
disabled={saving || statusChanging !== null}
>
{saving ? "Ukládání..." : "Uložit"}
</Button>
{(project.valid_transitions ?? []).map((status) => (
<Button
key={status}
color={status === "zruseny" ? "error" : "primary"}
onClick={() => setStatusConfirm({ show: true, status })}
disabled={saving || statusChanging !== null}
>
{statusChanging === status
? "Zpracovávám…"
: TRANSITION_LABELS[status] || status}
</Button>
))}
{!project.order_id && (
<Button
variant="outlined"
@@ -408,21 +473,10 @@ export default function ProjectDetail() {
<Box
sx={{
display: "grid",
gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr 1fr" },
gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
gap: 2,
}}
>
<Field label="Stav">
<Select
value={form.status}
onChange={(v) => updateForm("status", v)}
disabled={!canEdit}
>
<MenuItem value="aktivni">Aktivní</MenuItem>
<MenuItem value="dokonceny">Dokončený</MenuItem>
<MenuItem value="zruseny">Zrušený</MenuItem>
</Select>
</Field>
<Field label="Datum zahájení">
<DateField
value={form.start_date}
@@ -556,8 +610,18 @@ export default function ProjectDetail() {
<Typography variant="caption" color="text.secondary">
Objednávka
</Typography>
<Typography variant="body2">
<Typography
variant="body2"
component="div"
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
{project.order_id ? (
<>
<Box
component={RouterLink}
to={`/orders/${project.order_id}`}
@@ -568,18 +632,14 @@ export default function ProjectDetail() {
}}
>
{project.order_number}
</Box>
{project.order_status && (
<Box
component="span"
sx={{ color: "text.secondary", ml: 1 }}
>
(
{STATUS_LABELS[project.order_status] ||
project.order_status}
)
</Box>
<StatusChip
label={statusLabel(ORDER_STATUS, project.order_status)}
color={statusColor(ORDER_STATUS, project.order_status)}
/>
)}
</Box>
</>
) : (
"—"
)}
@@ -610,6 +670,22 @@ export default function ProjectDetail() {
</Box>
</Card>
{/* Status change confirmation */}
<ConfirmDialog
isOpen={statusConfirm.show}
onClose={() => setStatusConfirm({ show: false, status: null })}
onConfirm={handleStatusChange}
title="Změnit stav projektu"
message={statusConfirmMessage(statusConfirm.status)}
confirmText={
TRANSITION_LABELS[statusConfirm.status || ""] || "Potvrdit"
}
confirmVariant={
statusConfirm.status === "zruseny" ? "danger" : "primary"
}
cancelText="Zrušit"
/>
<ConfirmDialog
isOpen={deleteConfirm}
onClose={() => {

View File

@@ -7,6 +7,9 @@ import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import StatusChipMenu, {
type StatusChipAction,
} from "../components/StatusChipMenu";
import { formatDate } from "../utils/formatters";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
@@ -30,7 +33,6 @@ import {
TextField,
Select,
DateField,
StatusChip,
CheckboxField,
LoadingState,
PageEnter,
@@ -38,29 +40,20 @@ import {
type TabDef,
type DataColumn,
} from "../ui";
import {
PROJECT_STATUS,
statusLabel,
statusColor,
statusOptions,
} from "../lib/documentStatus";
const API_BASE = "/api/admin";
const STATUS_LABELS: Record<string, string> = {
aktivni: "Aktivní",
dokonceny: "Dokončený",
zruseny: "Zrušený",
};
const STATUS_COLORS: Record<
string,
"default" | "success" | "error" | "warning" | "info"
> = {
aktivni: "success",
dokonceny: "info",
zruseny: "default",
};
// Status filter tabs (mirrors the offers page): "" = all.
const STATUS_TABS: TabDef[] = [
{ value: "", label: "Všechny" },
...Object.entries(STATUS_LABELS).map(([value, label]) => ({ value, label })),
];
const STATUS_TABS: TabDef[] = statusOptions(PROJECT_STATUS, {
value: "",
label: "Všechny",
});
interface Project {
id: number;
@@ -153,6 +146,17 @@ export default function Projects() {
},
});
// Quick status change from the list chip menu. A project transition may
// cascade to the linked order (and its documents), so invalidate broadly.
const statusMutation = useApiMutation<
{ id: number; status: string },
unknown
>({
url: ({ id }) => `${API_BASE}/projects/${id}`,
method: () => "PUT",
invalidate: ["projects", "orders", "offers", "invoices", "warehouse"],
});
const [showCreate, setShowCreate] = useState(false);
const [createForm, setCreateForm] = useState({
name: "",
@@ -268,6 +272,78 @@ export default function Projects() {
return <LoadingState />;
}
const canEditStatus = hasPermission("projects.edit");
// "Číslo Název" reference for confirm messages (name may be empty on
// legacy rows).
const projectRef = (p: Project) =>
p.name ? `${p.project_number} ${p.name}` : p.project_number;
const changeStatus = async (p: Project, status: string) => {
try {
await statusMutation.mutateAsync({ id: p.id, status });
alert.success("Stav byl změněn");
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
throw e; // rejection keeps the ConfirmDialog open (app convention)
}
};
// Quick actions per current status; unknown/legacy statuses get none
// (plain chip) — those are resolved on the detail page.
const statusActions = (p: Project): StatusChipAction[] => {
if (p.status === "aktivni") {
return [
{
key: "dokonceny",
label: "Dokončit",
confirm: {
title: "Dokončit projekt",
message:
`Označit projekt "${projectRef(p)}" jako dokončený?` +
(p.order_id
? " Propojená objednávka bude automaticky dokončena."
: ""),
confirmText: "Dokončit",
},
onAction: () => changeStatus(p, "dokonceny"),
},
{
key: "zruseny",
label: "Zrušit",
danger: true,
confirm: {
title: "Zrušit projekt",
message:
`Označit projekt "${projectRef(p)}" jako zrušený?` +
(p.order_id
? " Propojená objednávka bude automaticky stornována."
: ""),
confirmText: "Zrušit projekt",
},
onAction: () => changeStatus(p, "zruseny"),
},
];
}
if (p.status === "dokonceny" || p.status === "zruseny") {
return [
{
key: "aktivni",
label: "Obnovit",
confirm: {
title: "Obnovit projekt",
message:
'Projekt se vrátí do stavu "Aktivní".' +
(p.order_id ? " Propojená objednávka zůstane beze změny." : ""),
confirmText: "Obnovit",
},
onAction: () => changeStatus(p, "aktivni"),
},
];
}
return [];
};
const columns: DataColumn<Project>[] = [
{
key: "project_number",
@@ -315,9 +391,11 @@ export default function Projects() {
width: "10%",
sortKey: "status",
render: (p) => (
<StatusChip
label={STATUS_LABELS[p.status] || p.status}
color={STATUS_COLORS[p.status] || "default"}
<StatusChipMenu
label={statusLabel(PROJECT_STATUS, p.status)}
color={statusColor(PROJECT_STATUS, p.status)}
actions={statusActions(p)}
disabled={!canEditStatus}
/>
),
},
@@ -394,9 +472,10 @@ export default function Projects() {
const rowSx = (p: Project) => {
if (p.status === "dokonceny") {
return {
backgroundColor: "rgba(var(--mui-palette-info-mainChannel) / 0.12)",
backgroundColor: "rgba(var(--mui-palette-success-mainChannel) / 0.12)",
"&:hover": {
backgroundColor: "rgba(var(--mui-palette-info-mainChannel) / 0.18)",
backgroundColor:
"rgba(var(--mui-palette-success-mainChannel) / 0.18)",
},
};
}

View File

@@ -16,6 +16,7 @@ import {
} from "../utils/formatters";
import { normalizeDateStr } from "../utils/attendanceHelpers";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import {
companySettingsOptions,
@@ -248,6 +249,7 @@ export default function ReceivedInvoices({
const queryClient = useQueryClient();
const { sort, order, handleSort } = useTableSort("created_at");
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [editOpen, setEditOpen] = useState(false);
const [editInvoice, setEditInvoice] = useState<EditInvoice | null>(null);
@@ -257,6 +259,10 @@ export default function ReceivedInvoices({
show: boolean;
invoice: ReceivedInvoice | null;
}>({ show: false, invoice: null });
const [paidConfirm, setPaidConfirm] = useState<{
show: boolean;
invoice: ReceivedInvoice | null;
}>({ show: false, invoice: null });
const hasLoadedOnce = useRef(false);
const blobTimeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([]);
@@ -286,7 +292,7 @@ export default function ReceivedInvoices({
receivedInvoiceListOptions({
month: statsMonth,
year: statsYear,
search,
search: debouncedSearch,
sort,
order,
page,
@@ -306,7 +312,7 @@ export default function ReceivedInvoices({
receivedInvoiceTotalsOptions({
month: statsMonth,
year: statsYear,
search,
search: debouncedSearch,
}),
);
@@ -580,10 +586,14 @@ export default function ReceivedInvoices({
}
};
const toggleStatus = async (inv: ReceivedInvoice) => {
if (inv.status === "paid") return;
const handleMarkPaid = async () => {
if (!paidConfirm.invoice) return;
try {
await toggleStatusMutation.mutateAsync({ id: inv.id, status: "paid" });
await toggleStatusMutation.mutateAsync({
id: paidConfirm.invoice.id,
status: "paid",
});
setPaidConfirm({ show: false, invoice: null });
} catch (e) {
alert.error(e instanceof Error ? e.message : "Nepodařilo se změnit stav");
}
@@ -675,7 +685,8 @@ export default function ReceivedInvoices({
<StatusChip
label={statusLabel(RECEIVED_INVOICE_STATUS, inv.status)}
color={statusColor(RECEIVED_INVOICE_STATUS, inv.status)}
onClick={() => toggleStatus(inv)}
title="Označit jako uhrazenou"
onClick={() => setPaidConfirm({ show: true, invoice: inv })}
/>
),
},
@@ -855,7 +866,7 @@ export default function ReceivedInvoices({
sortDir={order}
onSort={handleSort}
empty={
search ? (
debouncedSearch ? (
<EmptyState title="Žádné faktury neodpovídají hledání." />
) : (
<EmptyState
@@ -1329,6 +1340,17 @@ export default function ReceivedInvoices({
confirmVariant="danger"
loading={deleting}
/>
<ConfirmDialog
isOpen={paidConfirm.show}
onClose={() => setPaidConfirm({ show: false, invoice: null })}
onConfirm={handleMarkPaid}
title="Označit fakturu jako uhrazenou"
message={`Označit fakturu "${paidConfirm.invoice?.invoice_number || paidConfirm.invoice?.supplier_name || ""}" jako uhrazenou?`}
confirmText="Označit jako uhrazenou"
cancelText="Zrušit"
loading={toggleStatusMutation.isPending}
/>
</>
);
}

View File

@@ -6,6 +6,9 @@ import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import StatusChipMenu, {
type StatusChipAction,
} from "../components/StatusChipMenu";
import apiFetch from "../utils/api";
import {
formatCurrency,
@@ -32,7 +35,6 @@ import {
Field,
TextField,
Select,
StatusChip,
CheckboxField,
FileUpload,
FilterBar,
@@ -180,6 +182,17 @@ export default function OrdersReceived({
},
});
// Quick status change from the table chip (StatusChipMenu). The `id` rides
// along in the input only to build the URL; UpdateOrderSchema strips it.
const statusMutation = useApiMutation<
{ id: number; status: string },
unknown
>({
url: ({ id }) => `${API_BASE}/orders/${id}`,
method: () => "PUT",
invalidate: ["orders", "offers", "projects", "invoices"],
});
const [createForm, setCreateForm] = useState({
customer_id: "",
customer_order_number: "",
@@ -352,6 +365,79 @@ export default function OrdersReceived({
return <LoadingState />;
}
// Quick actions for the status chip menu, mirroring the order status
// machine (VALID_TRANSITIONS incl. the reopen edges). Rejections propagate
// so the ConfirmDialog stays open per app convention; we toast here.
const statusActions = (o: Order): StatusChipAction[] => {
const changeStatus = (status: string) => async () => {
try {
await statusMutation.mutateAsync({ id: o.id, status });
alert.success("Stav byl změněn");
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
throw e;
}
};
const stornovat: StatusChipAction = {
key: "stornovana",
label: "Stornovat",
danger: true,
confirm: {
title: "Stornovat objednávku",
message: `Opravdu chcete stornovat objednávku „${o.order_number}“? Propojený projekt bude automaticky zrušen.`,
confirmText: "Stornovat",
},
onAction: changeStatus("stornovana"),
};
switch (o.status) {
case "prijata":
return [
{
key: "v_realizaci",
label: "Zahájit realizaci",
confirm: {
title: "Zahájit realizaci",
message: `Opravdu chcete zahájit realizaci objednávky „${o.order_number}“?`,
confirmText: "Zahájit realizaci",
},
onAction: changeStatus("v_realizaci"),
},
stornovat,
];
case "v_realizaci":
return [
{
key: "dokoncena",
label: "Dokončit",
confirm: {
title: "Dokončit objednávku",
message: `Opravdu chcete dokončit objednávku „${o.order_number}“? Propojený projekt bude automaticky dokončen.`,
confirmText: "Dokončit",
},
onAction: changeStatus("dokoncena"),
},
stornovat,
];
case "dokoncena":
case "stornovana":
// Reopen — deliberately no cascade to the linked project.
return [
{
key: "v_realizaci",
label: "Obnovit",
confirm: {
title: "Obnovit objednávku",
message: `Opravdu chcete obnovit objednávku „${o.order_number}“? Objednávka se vrátí do stavu "V realizaci". Propojený projekt zůstane beze změny.`,
confirmText: "Obnovit",
},
onAction: changeStatus("v_realizaci"),
},
];
default:
return [];
}
};
const columns: DataColumn<Order>[] = [
{
key: "order_number",
@@ -403,9 +489,11 @@ export default function OrdersReceived({
width: "13%",
sortKey: "status",
render: (o) => (
<StatusChip
<StatusChipMenu
label={statusLabel(ORDER_STATUS, o.status)}
color={statusColor(ORDER_STATUS, o.status)}
actions={statusActions(o)}
disabled={!hasPermission("orders.edit")}
/>
),
},
@@ -589,7 +677,7 @@ export default function OrdersReceived({
title="Smazat objednávku"
message={
deleteConfirm.order
? `Opravdu chcete smazat objednávku „${deleteConfirm.order.order_number}"? Bude smazán i přidružený projekt. Tato akce je nevratná.`
? `Opravdu chcete smazat objednávku „${deleteConfirm.order.order_number}? Bude smazán i přidružený projekt. Tato akce je nevratná.`
: ""
}
confirmText="Smazat"

View File

@@ -7,10 +7,11 @@ import IconButton from "@mui/material/IconButton";
import { useAuth } from "../context/AuthContext";
import { useAlert } from "../context/AlertContext";
import Forbidden from "../components/Forbidden";
import { useApiMutation } from "../lib/queries/mutations";
import { useApiMutation, apiErrorMessage } from "../lib/queries/mutations";
import {
userListOptions,
roleListOptions,
USER_INVALIDATE,
type User,
} from "../lib/queries/users";
import {
@@ -114,15 +115,6 @@ export default function Users() {
is_active: true,
});
const USER_INVALIDATE = [
"users",
"trips",
"attendance",
"leave-requests",
"leave",
"projects",
];
const saveUser = useApiMutation<UserPayload, void>({
url: () =>
editingUser ? `${API_BASE}/users/${editingUser.id}` : `${API_BASE}/users`,
@@ -168,6 +160,9 @@ export default function Users() {
input.is_active ? "Uživatel byl aktivován" : "Uživatel byl deaktivován",
);
},
onError: (err) => {
alert.error(apiErrorMessage(err, "Nepodařilo se změnit stav uživatele"));
},
});
if (!hasPermission("users.view")) return <Forbidden />;
@@ -290,6 +285,9 @@ export default function Users() {
label={u.is_active ? "Aktivní" : "Neaktivní"}
color={u.is_active ? "success" : "default"}
onClick={u.id === currentUser?.id ? undefined : () => toggleActive(u)}
title={
u.id === currentUser?.id ? undefined : "Kliknutím přepnete stav"
}
/>
),
},

View File

@@ -8,7 +8,7 @@ import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { formatKm } from "../utils/formatters";
import { vehicleListOptions } from "../lib/queries/vehicles";
import { useApiMutation } from "../lib/queries/mutations";
import { useApiMutation, apiErrorMessage } from "../lib/queries/mutations";
import {
Button,
Card,
@@ -157,6 +157,9 @@ export default function Vehicles() {
: "Vozidlo bylo deaktivováno",
);
},
onError: (err) => {
alert.error(apiErrorMessage(err, "Nepodařilo se změnit stav vozidla"));
},
});
if (!hasPermission("vehicles.manage")) return <Forbidden />;
@@ -265,6 +268,7 @@ export default function Vehicles() {
label={v.is_active ? "Aktivní" : "Neaktivní"}
color={v.is_active ? "success" : "default"}
onClick={() => toggleActive(v)}
title="Kliknutím přepnete stav"
/>
),
},

View File

@@ -266,6 +266,7 @@ export default function WarehouseLocations() {
label={l.is_active ? "Aktivní" : "Neaktivní"}
color={l.is_active ? "success" : "default"}
onClick={() => toggleActive(l)}
title="Kliknutím přepnete stav"
/>
),
},

View File

@@ -367,6 +367,7 @@ export default function WarehouseSuppliers() {
label={s.is_active ? "Aktivní" : "Neaktivní"}
color={s.is_active ? "success" : "default"}
onClick={() => toggleActive(s)}
title="Kliknutím přepnete stav"
/>
),
},

View File

@@ -4,6 +4,7 @@ import {
type PaletteColor,
type PaletteColorChannel,
} from "@mui/material/styles";
import { csCZ } from "@mui/material/locale";
const FONT_BODY = "'Plus Jakarta Sans', system-ui, sans-serif";
const FONT_HEADING = "'Urbanist', sans-serif";
@@ -25,7 +26,13 @@ export const FILLED_DARK_BG = {
info: { bg: "#1d4ed8", hover: "#1e40af" },
} as const;
export const theme = createTheme({
// The theme composes MUI's Czech component localization (csCZ) as a second
// createTheme argument (the supported deep-merge form). It only injects
// component defaultProps — Czech built-in strings for Autocomplete
// ("Žádné možnosti"), TablePagination, Alert, Pagination, … — and does not
// touch the palette / cssVariables config.
export const theme = createTheme(
{
cssVariables: {
colorSchemeSelector: "[data-theme='%s']",
},
@@ -275,7 +282,9 @@ export const theme = createTheme({
},
},
},
});
},
csCZ,
);
export const fonts = {
body: FONT_BODY,

View File

@@ -11,6 +11,7 @@ import { setLogoutAlert } from "../utils/api";
import SidebarNav from "./SidebarNav";
import LoadingState from "./LoadingState";
import ShortcutsHelp from "../components/ShortcutsHelp";
import TitleSync from "../components/TitleSync";
const DRAWER_WIDTH = 248;
@@ -98,6 +99,7 @@ export default function AppShell() {
return (
<ScopedCssBaseline>
<TitleSync />
<motion.div
initial={{ opacity: 0, scale: 0.98 }}
animate={
@@ -110,6 +112,38 @@ export default function AppShell() {
ease: [0.4, 0, 0.2, 1],
}}
>
{/* Skip link: first focusable element; visually hidden (clipped)
until keyboard focus reveals it above the drawer. */}
<Box
component="a"
href="#main-content"
sx={(theme) => ({
position: "absolute",
top: 8,
left: 8,
zIndex: theme.zIndex.drawer + 2,
width: "1px",
height: "1px",
overflow: "hidden",
clipPath: "inset(50%)",
whiteSpace: "nowrap",
px: 2,
py: 1,
borderRadius: 1,
bgcolor: theme.vars!.palette.primary.main,
color: theme.vars!.palette.primary.contrastText,
textDecoration: "none",
fontWeight: 600,
"&:focus": {
width: "auto",
height: "auto",
overflow: "visible",
clipPath: "none",
},
})}
>
Přeskočit na obsah
</Box>
<Box
sx={{
display: "flex",
@@ -209,10 +243,15 @@ export default function AppShell() {
</Box>
<Box
component="main"
id="main-content"
tabIndex={-1}
sx={{
flex: 1,
px: immersiveOnMobile ? { xs: 0, md: 3 } : { xs: 2, md: 3 },
pb: immersiveOnMobile ? { xs: 0, md: 4 } : 4,
// Skip-link target: focus lands here programmatically — the
// region-wide focus ring would be noise, not a signal.
"&:focus": { outline: "none" },
...(immersiveOnMobile && {
minHeight: 0,
overflow: { xs: "hidden", md: "visible" },

View File

@@ -57,6 +57,7 @@ export default function CustomerPicker({
size="small"
fullWidth
autoHighlight
noOptionsText="Žádní zákazníci"
renderOption={(props, c) => {
const { key, ...rest } = props as typeof props & { key: string };
return (

View File

@@ -57,6 +57,7 @@ export default function SupplierPicker({
size="small"
fullWidth
autoHighlight
noOptionsText="Žádní dodavatelé"
renderOption={(props, s) => {
const { key, ...rest } = props as typeof props & { key: string };
return (

View File

@@ -29,6 +29,13 @@ export function Tabs({
<MuiTabs
value={value}
onChange={(_, v) => onChange(v)}
// Scrollable so many tabs (e.g. 5 status filters) stay reachable on
// ~360px phones instead of clipping. When everything fits (desktop),
// scroll buttons don't render and this looks identical to "standard" —
// callers' centered flex wrappers keep shrink-wrapping the bar.
variant="scrollable"
scrollButtons="auto"
allowScrollButtonsMobile
sx={{
borderBottom: 1,
borderColor: "divider",

View File

@@ -1,3 +1,5 @@
import { reportServerVersion } from "./appVersion";
class ApiState {
showSessionExpiredAlert = false;
showLogoutAlert = false;
@@ -120,6 +122,8 @@ export const apiFetch = async (
headers,
credentials: "include",
});
// Detect a new deploy: compare the server's build version to ours.
reportServerVersion(response.headers.get("X-App-Version"));
if (response.status === 401 && state.refreshFn) {
// If the caller already unmounted (TanStack Query aborted the request),

View File

@@ -0,0 +1,48 @@
/**
* New-deploy detection for the SPA.
*
* The server stamps every response with `X-App-Version`. `apiFetch` feeds that
* header here via `reportServerVersion`. When it differs from the version baked
* into THIS bundle at build time (`BUILD_VERSION`), a deploy has happened — we
* latch it and notify subscribers (the refresh banner). We never force a
* reload; the user picks the moment (they may be mid-form).
*/
// Injected by Vite `define` at build time; falls back to "dev" in tests / when
// running unbuilt. `typeof` guard avoids a ReferenceError when undefined.
declare const __APP_VERSION__: string;
export const BUILD_VERSION: string =
typeof __APP_VERSION__ !== "undefined" ? __APP_VERSION__ : "dev";
let newVersion: string | null = null;
const listeners = new Set<() => void>();
/**
* Compare a server-reported version against this bundle's build version. Latches
* the first genuine mismatch and notifies subscribers exactly once.
*/
export function reportServerVersion(
serverVersion: string | null | undefined,
): void {
if (newVersion) return; // already latched — banner is up
if (!serverVersion || serverVersion === BUILD_VERSION) return;
newVersion = serverVersion;
for (const l of listeners) l();
}
export function subscribeNewVersion(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function getNewVersion(): string | null {
return newVersion;
}
/** Test-only: reset the module singleton between cases. */
export function __resetVersionStateForTest(): void {
newVersion = null;
listeners.clear();
}

View File

@@ -173,7 +173,10 @@ export const formatTimeOrDatetimePrint = (
const timeDate = dateMatch
? `${dateMatch[1]}-${dateMatch[2]}-${dateMatch[3]}`
: "";
if (timeDate && timeDate !== shiftDate) {
// Compare DATE PARTS: shiftDate arrives as a naive datetime off the wire
// ("2026-06-01T02:00:00"), so a raw string compare never matched and the
// overnight-only date prefix fired on every single time cell.
if (timeDate && timeDate !== normalizeDateStr(shiftDate)) {
const datePart = `${parseInt(dateMatch![3])}.${parseInt(dateMatch![2])}.`;
return `${datePart} ${extractTime(datetime)}`;
}
@@ -203,9 +206,23 @@ export const calculateWorkMinutesPrint = (record: AttendanceRecord): number => {
// Print template helpers (mzda-style counting)
// ---------------------------------------------------------------------------
/**
* Parse the calendar day of a date-only or naive-datetime string as a LOCAL
* Date. `new Date("YYYY-MM-DD")` is UTC midnight per the ECMAScript spec —
* in timezones west of UTC it renders as the PREVIOUS day, so a US viewer's
* June print started with "31. 5. Neděle" and every weekday name was shifted.
* Building the Date from its string parts keeps the calendar day identical
* in every timezone.
*/
const localDayFromString = (dateStr: string): Date => {
const m = String(dateStr).match(/^(\d{4})-(\d{2})-(\d{2})/);
if (m) return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
return new Date(dateStr);
};
/** Returns the Czech weekday name with the first letter capitalized. */
export const getCzechWeekday = (dateStr: string): string => {
const wd = new Date(dateStr).toLocaleDateString("cs-CZ", {
const wd = localDayFromString(dateStr).toLocaleDateString("cs-CZ", {
weekday: "long",
});
return wd.charAt(0).toUpperCase() + wd.slice(1);
@@ -213,7 +230,7 @@ export const getCzechWeekday = (dateStr: string): string => {
/** True if the date is a Saturday or Sunday. */
export const isWeekendDate = (dateStr: string): boolean => {
const dow = new Date(dateStr).getDay();
const dow = localDayFromString(dateStr).getDay();
return dow === 0 || dow === 6;
};
@@ -353,3 +370,94 @@ export const calculateFreeHolidayHours = (
}
return free;
};
// ---------------------------------------------------------------------------
// Mzda rekapitulace (single source — the print AND the admin screen consume
// this, so the two can never drift again; spec confirmed with the accountant
// 2026-07, see the summary lines below)
// ---------------------------------------------------------------------------
export interface MzdaSummary {
/** All worked hours in the month: arrival→departure minus recorded breaks. */
workedHoursRaw: number;
/** Odpracováno: all worked hours EXCEPT hours worked on public holidays. */
odpracovano: number;
/** Odpracováno včetně svátků a přesčasů: ALL worked hours (line2 line1 = Svátek). */
vcetneSvatku: number;
/** Dovolená: sum of vacation leave_hours (hour-based, partial days allowed). */
vacationHours: number;
/** Přesčas: worked hours above the monthly fund — max(0, worked fond). */
prescas: number;
/** Svátek: hours actually WORKED on public-holiday dates. */
svatekHours: number;
/** So/Ne: worked hours on Saturdays and Sundays. */
weekendHours: number;
/** Práce v noci: worked minutes in the 22:0006:00 window. */
nightMinutes: number;
/** Fond měsíce: MonFri (public holidays included) × 8 h. */
fund: number;
businessDays: number;
/** 8 h per holiday the user did NOT work (fond is covered by these). */
freeHolidayHours: number;
}
/** Compute the payroll recap for one user's month of records. */
export const computeMzdaSummary = (
records: AttendanceRecord[],
monthStr: string,
): MzdaSummary => {
const [yearStr, monthNumStr] = monthStr.split("-");
const yr = parseInt(yearStr, 10);
const mo = parseInt(monthNumStr, 10);
const holidayDates = holidaysInMonth(yr, mo);
const holidaySet = new Set(holidayDates);
let workedMinutes = 0;
let svatekMinutes = 0;
let weekendMinutes = 0;
let nightMinutes = 0;
let vacationHours = 0;
for (const r of records) {
const lt = r.leave_type || "work";
if (lt !== "work") {
if (lt === "vacation") vacationHours += Number(r.leave_hours) || 8;
continue;
}
const m = calculateWorkMinutesPrint(r);
workedMinutes += m;
const day = normalizeDateStr(r.shift_date);
if (holidaySet.has(day)) svatekMinutes += m;
if (isWeekendDate(day)) weekendMinutes += m;
nightMinutes += calculateNightMinutes(r);
}
// Fond: MonFri × 8 h; public holidays stay in the count (they are paid via
// the fond — an unworked holiday earns its 8 h, see freeHolidayHours).
let businessDays = 0;
const cur = new Date(yr, mo - 1, 1);
while (cur.getMonth() === mo - 1) {
const dow = cur.getDay();
if (dow !== 0 && dow !== 6) businessDays++;
cur.setDate(cur.getDate() + 1);
}
const fund = businessDays * 8;
const workedHoursRaw = workedMinutes / 60;
const svatekHours = svatekMinutes / 60;
return {
workedHoursRaw,
odpracovano: workedHoursRaw - svatekHours,
vcetneSvatku: workedHoursRaw,
vacationHours,
prescas: Math.max(0, workedHoursRaw - fund),
svatekHours,
weekendHours: weekendMinutes / 60,
nightMinutes,
fund,
businessDays,
freeHolidayHours: calculateFreeHolidayHours(records, holidayDates),
};
};

View File

@@ -33,7 +33,15 @@ export function formatMultiCurrency(
export function formatDate(dateStr: string | null | undefined): string {
if (!dateStr) return "—";
const d = new Date(dateStr);
// Date-ONLY strings ("2026-06-01") parse as UTC midnight per the spec, which
// renders as the PREVIOUS day in timezones west of UTC — a US viewer's June
// attendance print started with 31. 5. Parse the parts instead so the
// calendar day is identical in every timezone. Datetime strings keep the
// local-parse behavior (naive wire times are already local).
const m = String(dateStr).match(/^(\d{4})-(\d{2})-(\d{2})$/);
const d = m
? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]))
: new Date(dateStr);
return d.toLocaleDateString("cs-CZ");
}

View File

@@ -0,0 +1,35 @@
import { lazy } from "react";
import type { ComponentType } from "react";
const RELOAD_KEY = "spa-chunk-reloaded";
/**
* React.lazy that survives a deploy. If a page's dynamic import fails because
* its hashed chunk was removed by a newer build, reload once to fetch the fresh
* bundle (guarded by sessionStorage so a genuine load failure can't loop). On a
* successful load the guard is cleared so the next deploy can recover too.
*
* The generic mirrors React.lazy's own `ComponentType<any>` constraint — there
* is no non-any equivalent that satisfies it, so the `any` is unavoidable here.
*/
export function lazyWithReload<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
T extends ComponentType<any>,
>(factory: () => Promise<{ default: T }>) {
return lazy(() =>
factory()
.then((mod) => {
sessionStorage.removeItem(RELOAD_KEY);
return mod;
})
.catch((err: unknown) => {
if (!sessionStorage.getItem(RELOAD_KEY)) {
sessionStorage.setItem(RELOAD_KEY, "1");
window.location.reload();
// Never resolves — the reload replaces the document.
return new Promise<{ default: T }>(() => {});
}
throw err;
}),
);
}

33
src/middleware/version.ts Normal file
View File

@@ -0,0 +1,33 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import type { FastifyInstance } from "fastify";
/**
* The build version (from package.json), read once. A static `import` of the
* root package.json would pull a file outside `src` into the program and expand
* tsc's rootDir, so resolve it at runtime relative to the compiled file.
*/
export function readAppVersion(): string {
try {
const pkg = JSON.parse(
readFileSync(join(__dirname, "../../package.json"), "utf8"),
) as { version?: string };
return pkg.version ?? "0.0.0";
} catch {
return "0.0.0";
}
}
/**
* Stamp every response with `X-App-Version` so the SPA can detect a new deploy
* (the client compares it to the version baked into its own bundle and prompts
* a refresh on mismatch).
*/
export function registerVersionHeader(
app: FastifyInstance,
version: string = readAppVersion(),
): void {
app.addHook("onSend", async (_request, reply) => {
reply.header("X-App-Version", version);
});
}

View File

@@ -7,6 +7,8 @@ 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 { parseSelectedCustomFields } from "../../utils/custom-fields";
import {
formatDate,
formatNum,
@@ -33,6 +35,7 @@ function buildAddressLines(
entity: Record<string, unknown> | null,
isSupplier: boolean,
tObj: Record<string, string>,
selectedCustomFields?: number[],
): AddressResult {
if (!entity) return { name: "", lines: [] };
@@ -88,7 +91,9 @@ function buildAddressLines(
fieldMap.company_id = `${tObj.ico}${entity.company_id}`;
if (entity.vat_id) fieldMap.vat_id = `${tObj.dic}${entity.vat_id}`;
const filterCustom = Array.isArray(selectedCustomFields);
cfData.forEach((cf, i) => {
if (filterCustom && !selectedCustomFields!.includes(i)) return;
const cfName = (cf.name || "").trim();
const cfValue = (cf.value || "").trim();
const showLabel = cf.showLabel !== false;
@@ -161,6 +166,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 +214,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 +319,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 +371,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);
@@ -445,7 +458,15 @@ export default async function invoicesPdfRoutes(
}
}
const supp = buildAddressLines(settings, true, t);
const supp = buildAddressLines(
settings,
true,
t,
parseSelectedCustomFields(
(invoice as { selected_custom_fields?: unknown })
.selected_custom_fields,
),
);
const cust = buildAddressLines(customer, false, t);
const suppLinesHtml = supp.lines
@@ -489,11 +510,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)}&nbsp;%` : "—"}</td>`
: "";
const subDesc = item.item_description || "";
return `<tr>
@@ -501,6 +527,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>
@@ -1052,9 +1079,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>

View File

@@ -4,6 +4,7 @@ import { requirePermission } from "../../middleware/auth";
import { parseId, success } from "../../utils/response";
import { htmlToPdf } from "../../utils/html-to-pdf";
import { nasOrdersManager } from "../../services/nas-financials-manager";
import { parseSelectedCustomFields } from "../../utils/custom-fields";
import {
formatDate,
formatNum,
@@ -31,6 +32,7 @@ function buildAddressLines(
entity: Record<string, unknown> | null,
isCompany: boolean,
tObj: Record<string, string>,
selectedCustomFields?: number[],
): AddressResult {
if (!entity) return { name: "", lines: [] };
@@ -86,7 +88,9 @@ function buildAddressLines(
fieldMap.company_id = `${tObj.ico}${entity.company_id}`;
if (entity.vat_id) fieldMap.vat_id = `${tObj.dic}${entity.vat_id}`;
const filterCustom = Array.isArray(selectedCustomFields);
cfData.forEach((cf, i) => {
if (filterCustom && !selectedCustomFields!.includes(i)) return;
const cfName = (cf.name || "").trim();
const cfValue = (cf.value || "").trim();
const showLabel = cf.showLabel !== false;
@@ -313,7 +317,14 @@ export function renderIssuedOrderHtml(
// PO direction: our company (settings) = Odběratel (buyer);
// the sklad_suppliers record = Dodavatel (supplier).
const buyer = buildAddressLines(settings, true, t); // company → Odběratel
const buyer = buildAddressLines(
settings,
true,
t,
parseSelectedCustomFields(
(order as { selected_custom_fields?: unknown }).selected_custom_fields,
),
); // company → Odběratel
const supplierAddr = buildSupplierLines(supplier, t); // supplier → Dodavatel
const buyerLinesHtml = buyer.lines
@@ -741,8 +752,11 @@ ${indentCSS}
</tr>
</table>
<!-- Polozky -->
<div class="billing-label">${escapeHtml(order.order_text || t.billing)}</div>
<!-- Polozky — an order may be issued by sections alone; with no items the
heading, items table and total row are omitted entirely. -->
${
items.length > 0
? `<div class="billing-label">${escapeHtml(order.order_text || t.billing)}</div>
<table class="items">
<thead>
<tr>
@@ -768,7 +782,9 @@ ${indentCSS}
<span class="value">${formatCurrency(total, currency)}</span>
</div>
</div>
</div>
</div>`
: ""
}
${scopeHtml}

View File

@@ -366,6 +366,8 @@ export default async function issuedOrdersRoutes(fastify: FastifyInstance) {
return error(reply, "Dodavatel nenalezen", 400);
if (order.error === "po_number_taken")
return error(reply, "Číslo objednávky je již použito", 409);
if (order.error === "empty_document")
return error(reply, "Přidejte alespoň jednu položku nebo obsah", 400);
return error(reply, "Neznámá chyba", 500);
}
await logAudit({
@@ -408,6 +410,8 @@ export default async function issuedOrdersRoutes(fastify: FastifyInstance) {
`Neplatný přechod stavu z "${result.currentStatus}" na "${result.newStatus}"`,
400,
);
if (result.error === "empty_document")
return error(reply, "Přidejte alespoň jednu položku nebo obsah", 400);
return error(reply, "Neznámá chyba", 500);
}
await logAudit({

View File

@@ -5,6 +5,8 @@ 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 { parseSelectedCustomFields } from "../../utils/custom-fields";
import {
formatDate,
formatNum,
@@ -28,6 +30,7 @@ function buildAddressLines(
entity: Record<string, unknown> | null,
isSupplier: boolean,
t: (key: string) => string,
selectedCustomFields?: number[],
): AddressResult {
if (!entity) return { name: "", lines: [] };
@@ -84,7 +87,9 @@ function buildAddressLines(
fieldMap.company_id = `${t("ico")}: ${entity.company_id}`;
if (entity.vat_id) fieldMap.vat_id = `${t("dic")}: ${entity.vat_id}`;
const filterCustom = Array.isArray(selectedCustomFields);
cfData.forEach((cf, i) => {
if (filterCustom && !selectedCustomFields!.includes(i)) return;
const cfName = (cf.name || "").trim();
const cfValue = (cf.value || "").trim();
const showLabel = cf.showLabel !== false;
@@ -123,6 +128,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 +176,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
@@ -202,6 +214,10 @@ export function renderOfferHtml(
settings as unknown as Record<string, unknown>,
true,
t,
parseSelectedCustomFields(
(quotation as { selected_custom_fields?: unknown })
.selected_custom_fields,
),
);
const custLinesHtml = cust.lines
@@ -217,10 +233,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)}&nbsp;%` : "—"}</td>`
: "";
const subDesc = item.item_description || "";
const evenClass = i % 2 === 1 ? ' class="even"' : "";
itemsHtml += `<tr${evenClass}>
@@ -228,6 +249,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 +643,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>

View File

@@ -331,6 +331,26 @@ export default async function ordersRoutes(
entityId: id,
description: `Upravena objednávka ${result.data.order_number}`,
});
// The order→project cascade updated linked project(s) — give each its
// own audit trail entry.
for (const p of result.synced_projects ?? []) {
const verb =
p.to === "dokonceny"
? "dokončen"
: p.to === "zruseny"
? "zrušen"
: "aktivován";
await logAudit({
request,
authData: request.authData,
action: "update",
entityType: "project",
entityId: p.id,
description: `Projekt ${p.project_number ?? `#${p.id}`} automaticky ${verb} (synchronizace s objednávkou)`,
oldValues: { status: p.from },
newValues: { status: p.to },
});
}
return success(reply, { id }, 200, "Objednávka byla uložena");
},
);

View File

@@ -131,6 +131,12 @@ export default async function projectsRoutes(
const result = await updateProject(id, parsed.data);
if (!result) return error(reply, "Projekt nenalezen", 404);
if ("error" in result) {
if (result.error === "invalid_transition" && "currentStatus" in result)
return error(
reply,
`Neplatný přechod stavu z "${result.currentStatus}" na "${result.newStatus}"`,
400,
);
return error(
reply,
result.error,
@@ -138,6 +144,7 @@ export default async function projectsRoutes(
);
}
const statusChanged = result.old_status !== result.status;
await logAudit({
request,
authData: request.authData,
@@ -145,7 +152,26 @@ export default async function projectsRoutes(
entityType: "project",
entityId: id,
description: `Upraven projekt ${result.name}`,
oldValues: statusChanged ? { status: result.old_status } : undefined,
newValues: statusChanged ? { status: result.status } : undefined,
});
// The project→order cascade updated the linked order too — give the
// order its own audit trail entry.
if (result.synced_order) {
const so = result.synced_order;
await logAudit({
request,
authData: request.authData,
action: "update",
entityType: "order",
entityId: so.id,
description: `Objednávka ${so.order_number ?? `#${so.id}`} automaticky ${
so.to === "dokoncena" ? "dokončena" : "stornována"
} (synchronizace s projektem)`,
oldValues: { status: so.from },
newValues: { status: so.to },
});
}
return success(reply, { id }, 200, "Projekt byl uložen");
},
);

View File

@@ -325,6 +325,25 @@ export default async function tripsRoutes(
const body = parsed.data;
const authData = request.authData!;
// Only managers may file a trip on behalf of someone else — the same
// manager detection buildTripsWhere uses for read scoping (admin role
// bypasses permission checks entirely). Explicit Czech 403 instead of
// silently ignoring the submitted user_id.
const isManager =
authData.roleName === "admin" ||
authData.permissions.includes("trips.manage");
if (
body.user_id !== undefined &&
Number(body.user_id) !== authData.userId &&
!isManager
) {
return error(
reply,
"Nemáte oprávnění zadat jízdu za jiného uživatele",
403,
);
}
if (body.end_km < body.start_km) {
return error(
reply,

View File

@@ -16,6 +16,8 @@ const InvoiceItemSchema = z.object({
quantity: positiveNumberFromForm.default(1),
unit: z.string().max(20).nullish(),
unit_price: numberFromForm.default(0),
// Per-item discount as a percentage (0100); column is Decimal(5,2).
discount: numberInRange(0, 100).optional().default(0),
vat_rate: numberInRange(0, 100).optional().default(21.0),
position: nonNegativeNumberFromForm.optional(),
});
@@ -48,6 +50,11 @@ export const CreateInvoiceSchema = z.object({
// Rich-text CZ/EN "Obsah" sections rendered after the items on the PDF
// (mirrors issued orders — shared DocumentSectionSchema, DB-aligned limits).
sections: z.array(DocumentSectionSchema).optional(),
// Positional indices of company custom fields to print on this document's PDF.
selected_custom_fields: z
.array(z.number().int().nonnegative())
.max(50)
.optional(),
});
export const UpdateInvoiceSchema = z.object({
@@ -72,6 +79,10 @@ export const UpdateInvoiceSchema = z.object({
paid_date: nullableIsoDateString,
items: z.array(InvoiceItemSchema).optional(),
sections: z.array(DocumentSectionSchema).optional(),
selected_custom_fields: z
.array(z.number().int().nonnegative())
.max(50)
.optional(),
});
export type CreateInvoiceInput = z.infer<typeof CreateInvoiceSchema>;

View File

@@ -41,6 +41,12 @@ export const CreateIssuedOrderSchema = z.object({
// Rich-text CZ/EN sections rendered on their own PDF page (mirrors offers'
// scope_sections — shared DocumentSectionSchema, DB-aligned limits).
sections: z.array(DocumentSectionSchema).optional(),
// Positional indices of company custom fields to print on this document's
// PDF. Omitted/empty ⇒ none. Update schema derives via .partial().
selected_custom_fields: z
.array(z.number().int().nonnegative())
.max(50)
.optional(),
});
// Update = partial create MINUS the number: PO numbers are immutable

View File

@@ -3,6 +3,7 @@ import {
nonNegativeIntFromForm,
nonNegativeNumberFromForm,
positiveNumberFromForm,
numberInRange,
nullableIntIdFromForm,
booleanFromForm,
isoDateString,
@@ -17,6 +18,8 @@ const QuotationItemSchema = z.object({
quantity: positiveNumberFromForm.default(1),
unit: z.string().max(20).nullish(),
unit_price: nonNegativeNumberFromForm.default(0),
// Per-item discount as a percentage (0100); column is Decimal(5,2).
discount: numberInRange(0, 100).optional().default(0),
is_included_in_total: booleanFromForm.optional().default(true),
// Int column — a float position would 500 at Prisma.
position: nonNegativeIntFromForm.optional(),
@@ -45,6 +48,12 @@ export const CreateQuotationSchema = z.object({
scope_description: z.string().max(8000).nullish(),
items: z.array(QuotationItemSchema).optional(),
sections: z.array(ScopeSectionSchema).optional(),
// Positional indices of company custom fields to print on this document's
// PDF. Omitted/empty ⇒ none. Update schema derives via .partial().
selected_custom_fields: z
.array(z.number().int().nonnegative())
.max(50)
.optional(),
});
// Update = partial create MINUS the number: quotation numbers are immutable

View File

@@ -36,7 +36,7 @@ export const CreateOrderSchema = z.object({
quotation_id: nullableIntIdFromForm.nullish(),
customer_id: nullableIntIdFromForm.nullish(),
status: z
.enum(["prijata", "v_realizaci", "dokoncena", "zrusena"])
.enum(["prijata", "v_realizaci", "dokoncena", "stornovana"])
.optional()
.default("prijata"),
currency: z.string().max(10).optional().default("CZK"),
@@ -52,7 +52,9 @@ export const CreateOrderSchema = z.object({
export const UpdateOrderSchema = z.object({
customer_order_number: z.string().max(100).nullish(),
status: z.enum(["prijata", "v_realizaci", "dokoncena", "zrusena"]).optional(),
status: z
.enum(["prijata", "v_realizaci", "dokoncena", "stornovana"])
.optional(),
currency: z.string().max(10).optional(),
language: z.string().max(5).optional(),
scope_title: z.string().max(255).nullish(),

View File

@@ -7,6 +7,7 @@ import rateLimit from "@fastify/rate-limit";
import path from "path";
import { config } from "./config/env";
import { securityHeaders } from "./middleware/security";
import { registerVersionHeader } from "./middleware/version";
import prisma from "./config/database";
import authRoutes from "./routes/admin/auth";
@@ -100,6 +101,9 @@ async function start() {
// --- Security headers ---
app.addHook("onRequest", securityHeaders);
// --- Version header: lets the SPA detect a new deploy and prompt a refresh ---
registerVersionHeader(app);
// --- Global error handler — consistent { success, error } format ---
app.setErrorHandler(
(err: Error & { statusCode?: number }, request, reply) => {

View File

@@ -1,11 +1,16 @@
import prisma from "../config/database";
import { utcMidnightOfLocalDay } from "../utils/date";
import { lineNet } from "../utils/money";
import { toCzk } from "./exchange-rates";
import {
generateInvoiceNumber,
releaseInvoiceNumber,
assignInvoiceNumber,
} from "./numbering.service";
import {
encodeSelectedCustomFields,
parseSelectedCustomFields,
} from "../utils/custom-fields";
// Status transition rules matching PHP.
// draft -> issued is the finalize step (consumes + assigns the invoice number).
@@ -31,6 +36,8 @@ interface InvoiceItemInput {
quantity?: number;
unit?: string | null;
unit_price?: number;
/** Per-item discount as a percentage (0100). */
discount?: number;
vat_rate?: number;
position?: number;
}
@@ -165,14 +172,24 @@ function buildInvoiceWhere(
}
function computeInvoiceTotals(
items: Array<{ quantity: unknown; unit_price: unknown; vat_rate: unknown }>,
items: Array<{
quantity: unknown;
unit_price: unknown;
discount?: unknown;
vat_rate: unknown;
}>,
applyVat: boolean | null,
defaultVatRate: unknown,
) {
const { subtotal, vat: vatAmount } = computeMoney(
items,
applyVat,
(i) => (Number(i.quantity) || 0) * (Number(i.unit_price) || 0),
(i) =>
lineNet(
Number(i.quantity) || 0,
Number(i.unit_price) || 0,
Number(i.discount),
),
// Preserve original semantics: a line vat_rate of 0 (non-null, non-"") IS used.
(i) =>
i.vat_rate != null && i.vat_rate !== ""
@@ -305,6 +322,7 @@ export function invoiceTotalWithVat(inv: {
invoice_items: Array<{
quantity: { toNumber(): number } | null;
unit_price: { toNumber(): number } | null;
discount?: { toNumber(): number } | null;
vat_rate: { toNumber(): number } | null;
}>;
}) {
@@ -312,8 +330,11 @@ export function invoiceTotalWithVat(inv: {
inv.invoice_items,
inv.apply_vat,
(i) =>
(Number(i.quantity?.toNumber()) || 0) *
(Number(i.unit_price?.toNumber()) || 0),
lineNet(
Number(i.quantity?.toNumber()) || 0,
Number(i.unit_price?.toNumber()) || 0,
i.discount?.toNumber(),
),
// Preserve original `||` semantics: a line rate of 0/NaN falls through to
// the invoice default, then 21.
(i) =>
@@ -401,7 +422,12 @@ export async function getInvoiceStats(queryMonth?: number, queryYear?: number) {
const { vat } = computeMoney(
inv.invoice_items,
inv.apply_vat,
(item) => (Number(item.quantity) || 0) * (Number(item.unit_price) || 0),
(item) =>
lineNet(
Number(item.quantity) || 0,
Number(item.unit_price) || 0,
Number(item.discount),
),
(item) => Number(item.vat_rate) || Number(inv.vat_rate) || 21,
false, // accumulate raw per-line VAT; round only the per-currency sum
);
@@ -490,6 +516,9 @@ export async function getInvoice(id: number) {
customer_name: invoice.customers?.name || null,
order_number: invoice.orders?.order_number || null,
valid_transitions: VALID_TRANSITIONS[invoice.status as string] || [],
selected_custom_fields: parseSelectedCustomFields(
rest.selected_custom_fields,
),
};
}
@@ -539,6 +568,9 @@ export async function createInvoice(body: InvoiceInput) {
internal_notes: body.internal_notes
? String(body.internal_notes)
: null,
selected_custom_fields: encodeSelectedCustomFields(
body.selected_custom_fields,
),
},
});
@@ -551,6 +583,7 @@ export async function createInvoice(body: InvoiceInput) {
quantity: item.quantity ?? 1,
unit: item.unit ?? null,
unit_price: item.unit_price ?? 0,
discount: item.discount ?? 0,
vat_rate: item.vat_rate ?? 21.0,
position: item.position ?? i,
})),
@@ -629,6 +662,10 @@ export async function updateInvoice(id: number, body: InvoiceInput) {
data.due_date = body.due_date ? new Date(String(body.due_date)) : null;
if (body.tax_date !== undefined)
data.tax_date = body.tax_date ? new Date(String(body.tax_date)) : null;
if (body.selected_custom_fields !== undefined)
data.selected_custom_fields = encodeSelectedCustomFields(
body.selected_custom_fields,
);
}
// Internal notes editable in draft/issued/overdue (never printed)
@@ -688,6 +725,7 @@ export async function updateInvoice(id: number, body: InvoiceInput) {
quantity: item.quantity ?? 1,
unit: item.unit ?? null,
unit_price: item.unit_price ?? 0,
discount: item.discount ?? 0,
vat_rate: item.vat_rate ?? 21.0,
position: item.position ?? i,
})),

View File

@@ -9,6 +9,10 @@ import {
isIssuedOrderNumberTaken,
} from "./numbering.service";
import { nasOrdersManager } from "./nas-financials-manager";
import {
encodeSelectedCustomFields,
parseSelectedCustomFields,
} from "../utils/custom-fields";
export interface IssuedOrderItemInput {
description?: string | null;
@@ -125,6 +129,7 @@ const NON_STATUS_UPDATE_FIELDS = [
"language",
"order_text",
"internal_notes",
"selected_custom_fields",
"items",
"sections",
] as const;
@@ -143,6 +148,32 @@ export function computeIssuedOrderTotals(
return { total: Math.round(total * 100) / 100 };
}
/**
* An issued order may be issued by sections alone (no line items), but a
* completely blank order must not be finalizable. Content = at least one item
* with a description OR one section with a title or stripped (non-tag) content.
* Mirrors the PDF visibility test and the frontend submit guard.
*/
function hasOrderContent(
items: Array<{ description?: string | null }> | undefined,
sections:
| Array<{
title?: string | null;
title_cz?: string | null;
content?: string | null;
}>
| undefined,
): boolean {
const anyItem = (items || []).some((it) => (it.description || "").trim());
const anySection = (sections || []).some(
(s) =>
(s.title_cz || "").trim() ||
(s.title || "").trim() ||
(s.content || "").replace(/<[^>]*>/g, "").trim(),
);
return anyItem || anySection;
}
export async function listIssuedOrders(params: ListIssuedOrdersParams) {
const { page, limit, skip, sort, order } = params;
const sortField = ALLOWED_SORT_FIELDS.includes(sort) ? sort : "id";
@@ -253,6 +284,9 @@ export async function getIssuedOrder(id: number) {
supplier: order.suppliers,
supplier_name: order.suppliers?.name || null,
valid_transitions: VALID_TRANSITIONS[order.status as string] || [],
selected_custom_fields: parseSelectedCustomFields(
rest.selected_custom_fields,
),
};
}
@@ -261,6 +295,12 @@ export async function createIssuedOrder(body: IssuedOrderInput) {
return await prisma.$transaction(async (tx) => {
const status = body.status ? String(body.status) : "draft";
// A non-draft (created-as-finalized) order must not be blank — require an
// item or a non-empty section. Drafts may be saved empty (WIP).
if (status !== "draft" && !hasOrderContent(body.items, body.sections)) {
return { error: "empty_document" as const };
}
// Validate the referenced supplier exists BEFORE the insert — a dangling
// FK would otherwise surface as a P2003 500 instead of a clean 400.
const supplierId = body.supplier_id ? Number(body.supplier_id) : null;
@@ -319,6 +359,9 @@ export async function createIssuedOrder(body: IssuedOrderInput) {
internal_notes: body.internal_notes
? String(body.internal_notes)
: null,
selected_custom_fields: encodeSelectedCustomFields(
body.selected_custom_fields,
),
},
});
@@ -424,6 +467,10 @@ export async function updateIssuedOrder(id: number, body: IssuedOrderInput) {
data.internal_notes = body.internal_notes
? String(body.internal_notes)
: null;
if (body.selected_custom_fields !== undefined)
data.selected_custom_fields = encodeSelectedCustomFields(
body.selected_custom_fields,
);
}
if (body.status !== undefined) data.status = String(body.status);
@@ -437,6 +484,27 @@ export async function updateIssuedOrder(id: number, body: IssuedOrderInput) {
body.status !== undefined &&
String(body.status) === "sent";
// Finalizing a blank order is rejected — require an item or a non-empty
// section. The finalize payload carries items/sections; fall back to the
// stored rows when a partial finalize omits them.
if (finalizing) {
const itemsForCheck = Array.isArray(body.items)
? body.items
: await prisma.issued_order_items.findMany({
where: { issued_order_id: id },
select: { description: true },
});
const sectionsForCheck = Array.isArray(body.sections)
? body.sections
: await prisma.issued_order_sections.findMany({
where: { issued_order_id: id },
select: { title: true, title_cz: true, content: true },
});
if (!hasOrderContent(itemsForCheck, sectionsForCheck)) {
return { error: "empty_document" as const };
}
}
// ONE transaction for the header write, the finalize numbering AND the
// items/sections full-replace. The items replace used to run in a SECOND
// transaction after the header tx — a failure between the two left a torn

View File

@@ -1,5 +1,6 @@
import { Prisma } from "@prisma/client";
import prisma from "../config/database";
import { lineNet } from "../utils/money";
import {
generateOfferNumber,
releaseOfferNumber,
@@ -7,6 +8,10 @@ import {
assignOfferNumber,
} from "./numbering.service";
import { nasOffersManager } from "./nas-offers-manager";
import {
encodeSelectedCustomFields,
parseSelectedCustomFields,
} from "../utils/custom-fields";
interface QuotationItemInput {
description?: string;
@@ -14,6 +19,8 @@ interface QuotationItemInput {
quantity?: number;
unit?: string;
unit_price?: number;
/** Per-item discount as a percentage (0100). */
discount?: number;
is_included_in_total?: boolean;
position?: number;
}
@@ -61,6 +68,7 @@ const NON_STATUS_UPDATE_FIELDS = [
"language",
"scope_title",
"scope_description",
"selected_custom_fields",
"items",
"sections",
] as const;
@@ -122,6 +130,7 @@ type EnrichableLineItem = {
is_included_in_total?: unknown;
quantity?: unknown;
unit_price?: unknown;
discount?: unknown;
};
type EnrichableQuotation = {
quotation_items: EnrichableLineItem[];
@@ -138,7 +147,12 @@ function enrichQuotation<T extends EnrichableQuotation>(q: T) {
.filter((i) => i.is_included_in_total !== false)
.reduce(
(s: number, i) =>
s + (Number(i.quantity) || 0) * (Number(i.unit_price) || 0),
s +
lineNet(
Number(i.quantity) || 0,
Number(i.unit_price) || 0,
Number(i.discount),
),
0,
);
const { quotation_items, scope_sections, ...rest } = q;
@@ -274,6 +288,9 @@ export async function getOffer(id: number) {
// Computed server-side so the frontend renders only legal status buttons
// (same contract as getIssuedOrder).
valid_transitions: VALID_TRANSITIONS[quotation.status] || [],
selected_custom_fields: parseSelectedCustomFields(
rest.selected_custom_fields,
),
};
}
@@ -333,6 +350,9 @@ export async function createOffer(body: Record<string, unknown>) {
scope_description: body.scope_description
? String(body.scope_description)
: null,
selected_custom_fields: encodeSelectedCustomFields(
body.selected_custom_fields,
),
},
});
@@ -345,6 +365,7 @@ export async function createOffer(body: Record<string, unknown>) {
quantity: item.quantity ?? 1,
unit: item.unit ?? null,
unit_price: item.unit_price ?? 0,
discount: item.discount ?? 0,
is_included_in_total: item.is_included_in_total !== false,
position: item.position ?? i,
})),
@@ -462,6 +483,10 @@ export async function updateOffer(id: number, body: Record<string, unknown>) {
? String(body.scope_description)
: null
: undefined,
selected_custom_fields:
body.selected_custom_fields !== undefined
? encodeSelectedCustomFields(body.selected_custom_fields)
: undefined,
modified_at: new Date(),
};
@@ -480,6 +505,7 @@ export async function updateOffer(id: number, body: Record<string, unknown>) {
quantity: item.quantity ?? 1,
unit: item.unit ?? null,
unit_price: item.unit_price ?? 0,
discount: item.discount ?? 0,
is_included_in_total: item.is_included_in_total !== false,
position: item.position ?? i,
})),
@@ -602,6 +628,7 @@ export async function duplicateOffer(id: number) {
quantity: item.quantity,
unit: item.unit,
unit_price: item.unit_price,
discount: item.discount,
is_included_in_total: item.is_included_in_total,
position: item.position,
})),

View File

@@ -31,12 +31,13 @@ interface OrderSectionInput {
position?: number;
}
// Status transition rules matching PHP
// Status transition rules matching PHP, plus the deliberate reopen edges
// dokoncena/stornovana → v_realizaci (spec 2026-07-04 — status quick actions).
export const VALID_TRANSITIONS: Record<string, string[]> = {
prijata: ["v_realizaci", "stornovana"],
v_realizaci: ["dokoncena", "stornovana"],
dokoncena: [],
stornovana: [],
dokoncena: ["v_realizaci"],
stornovana: ["v_realizaci"],
};
const ORDER_ALLOWED_SORT_FIELDS = [
@@ -54,23 +55,53 @@ const ORDER_TO_PROJECT_STATUS: Record<string, string> = {
stornovana: "zruseny",
};
// Order statuses that count as terminal — a transition OUT of one is a REOPEN,
// which deliberately never cascades to the linked project(s) (spec 2026-07-04).
const TERMINAL_ORDER_STATUSES = ["dokoncena", "stornovana"];
/** Project change performed by syncProjectStatus, returned for auditing. */
export interface SyncedProject {
id: number;
project_number: string | null;
from: string | null;
to: string;
}
/**
* Propagate an order status change onto its linked project(s). No-op when the
* new status has no project-status mapping. Accepts a Prisma client (the tx
* client inside a transaction, or the base client otherwise) so both update
* branches share one implementation.
* new status has no project-status mapping, or when the change is a reopen
* (previous status terminal — reopening never cascades, spec 2026-07-04).
* Accepts a Prisma client (the tx client inside a transaction, or the base
* client otherwise) so both update branches share one implementation.
* Returns the projects it actually changed so the route can audit them.
*/
async function syncProjectStatus(
client: Prisma.TransactionClient,
orderId: number,
previousStatus: string,
newStatus: string,
): Promise<void> {
): Promise<SyncedProject[]> {
if (TERMINAL_ORDER_STATUSES.includes(previousStatus)) return [];
const projectStatus = ORDER_TO_PROJECT_STATUS[newStatus];
if (!projectStatus) return;
await client.projects.updateMany({
if (!projectStatus) return [];
const linked = await client.projects.findMany({
where: { order_id: orderId },
select: { id: true, project_number: true, status: true },
});
// Filter in JS (not via `status: { not: … }`) so NULL-status projects are
// still picked up — SQL `<>` would exclude them.
const changed = linked.filter((p) => p.status !== projectStatus);
if (changed.length === 0) return [];
await client.projects.updateMany({
where: { id: { in: changed.map((p) => p.id) } },
data: { status: projectStatus },
});
return changed.map((p) => ({
id: p.id,
project_number: p.project_number,
from: p.status,
to: projectStatus,
}));
}
// ⚠ Also called by getOrderTotals with a MINIMAL select (currency, item
@@ -640,6 +671,10 @@ export async function updateOrder(id: number, body: UpdateOrderData) {
}
}
// Projects cascaded onto by a status change — surfaced to the route for
// per-project audit rows.
let syncedProjects: SyncedProject[] = [];
const data: Record<string, unknown> = { modified_at: new Date() };
const strFields = [
"customer_order_number",
@@ -678,7 +713,12 @@ export async function updateOrder(id: number, body: UpdateOrderData) {
// Sync project status when order status changes (matching PHP)
if (body.status !== undefined && String(body.status) !== currentStatus) {
await syncProjectStatus(tx, id, String(body.status));
syncedProjects = await syncProjectStatus(
tx,
id,
currentStatus,
String(body.status),
);
}
if (Array.isArray(body.items)) {
@@ -714,11 +754,19 @@ export async function updateOrder(id: number, body: UpdateOrderData) {
// Sync project status when order status changes (matching PHP)
if (body.status !== undefined && String(body.status) !== currentStatus) {
await syncProjectStatus(prisma, id, String(body.status));
syncedProjects = await syncProjectStatus(
prisma,
id,
currentStatus,
String(body.status),
);
}
}
return { data: { id, order_number: existing.order_number } };
return {
data: { id, order_number: existing.order_number },
synced_projects: syncedProjects,
};
}
export async function deleteOrder(id: number, deleteFiles = false) {

View File

@@ -6,6 +6,7 @@ import {
} from "./numbering.service";
import { NasFileManager } from "./nas-file-manager";
import type { CreateProjectInput } from "../schemas/projects.schema";
import type { projects } from "../types";
const nasFileManager = new NasFileManager();
@@ -17,6 +18,29 @@ const ALLOWED_SORT_FIELDS = [
"created_at",
];
// Status transition rules (spec 2026-07-04 — projects gain a status machine;
// dokonceny/zruseny → aktivni is a deliberate reopen edge).
export const VALID_TRANSITIONS: Record<string, string[]> = {
aktivni: ["dokonceny", "zruseny"],
dokonceny: ["aktivni"],
zruseny: ["aktivni"],
};
const CANONICAL_STATUSES = Object.keys(VALID_TRANSITIONS);
/**
* Legal next statuses for a project. The status column is a legacy free-text
* string, so an unknown/legacy current status may move to any canonical value
* (minus itself) — tolerant, matching the updateProject validation.
*/
function validTransitionsFor(status: string | null): string[] {
const current = status ?? "";
if (Object.prototype.hasOwnProperty.call(VALID_TRANSITIONS, current)) {
return VALID_TRANSITIONS[current];
}
return CANONICAL_STATUSES.filter((s) => s !== current);
}
interface ListProjectsParams {
page: number;
limit: number;
@@ -91,13 +115,39 @@ export async function getProject(id: number) {
order_number: orders?.order_number ?? null,
order_status: orders?.status ?? null,
quotation_number: quotations?.quotation_number ?? null,
// Computed server-side so the frontend renders only legal status buttons
// (same contract as offers/orders/issued orders).
valid_transitions: validTransitionsFor(project.status),
has_nas_folder: project.project_number
? nasFileManager.projectFolderExists(project.project_number)
: false,
};
}
export async function updateProject(id: number, body: Record<string, unknown>) {
/** Order change performed by the project→order cascade, returned for auditing. */
export interface SyncedOrder {
id: number;
order_number: string | null;
from: string;
to: string;
}
// Explicit union — inference would normalize the members with `?: undefined`
// props (and narrow synced_order to `null`, its value at the return
// statement), breaking the route's `"error" in result` narrowing.
type UpdateProjectResult =
| null
| { error: string; status: number }
| { error: "invalid_transition"; currentStatus: string; newStatus: string }
| (projects & {
old_status: string | null;
synced_order: SyncedOrder | null;
});
export async function updateProject(
id: number,
body: Record<string, unknown>,
): Promise<UpdateProjectResult> {
const existing = await prisma.projects.findUnique({ where: { id } });
if (!existing) return null;
@@ -108,6 +158,25 @@ export async function updateProject(id: number, body: Record<string, unknown>) {
return { error: "Číslo projektu nelze změnit", status: 400 };
}
// Status changes must follow the transition table (offers/orders parity).
// Legacy tolerance: the column is historic free text, so an unknown current
// status may move to any canonical value.
const currentStatus = existing.status ?? "";
const statusChanges =
body.status !== undefined && String(body.status) !== currentStatus;
const newStatus = statusChanges ? String(body.status) : null;
if (statusChanges && newStatus !== null) {
const allowed = Object.prototype.hasOwnProperty.call(
VALID_TRANSITIONS,
currentStatus,
)
? VALID_TRANSITIONS[currentStatus]
: CANONICAL_STATUSES;
if (!allowed.includes(newStatus)) {
return { error: "invalid_transition" as const, currentStatus, newStatus };
}
}
// FK pre-validation (mirrors createProject): a dangling id would raise
// P2003 at Prisma and surface as a generic 500 — return the same Czech
// 400s as the create path. null still clears the FK.
@@ -164,7 +233,45 @@ export async function updateProject(id: number, body: Record<string, unknown>) {
if (body.end_date !== undefined)
data.end_date = body.end_date ? new Date(String(body.end_date)) : null;
const updated = await prisma.projects.update({ where: { id }, data });
// Project → order cascade (spec 2026-07-04): finishing/cancelling a project
// completes/cancels its linked order iff the order is still open
// (prijata/v_realizaci). Reopen (→aktivni) never touches the order, and
// completed/cancelled orders are never resurrected. Direct tx write — no
// updateOrder recursion — in the SAME transaction as the project update.
let syncedOrder: SyncedOrder | null = null;
const wantsCascade =
statusChanges &&
(newStatus === "dokonceny" || newStatus === "zruseny") &&
existing.order_id != null;
const updated = wantsCascade
? await prisma.$transaction(async (tx) => {
const row = await tx.projects.update({ where: { id }, data });
const order = await tx.orders.findUnique({
where: { id: existing.order_id! },
select: { id: true, order_number: true, status: true },
});
const orderStatus = order?.status ?? "";
if (
order &&
(orderStatus === "prijata" || orderStatus === "v_realizaci")
) {
const to = newStatus === "dokonceny" ? "dokoncena" : "stornovana";
await tx.orders.update({
where: { id: order.id },
data: { status: to, modified_at: new Date() },
});
syncedOrder = {
id: order.id,
order_number: order.order_number,
from: orderStatus,
to,
};
}
return row;
})
: await prisma.projects.update({ where: { id }, data });
if (
body.name !== undefined &&
@@ -184,7 +291,9 @@ export async function updateProject(id: number, body: Record<string, unknown>) {
}
}
return updated;
// old_status + synced_order let the route audit the status change and the
// cascaded order update.
return { ...updated, old_status: existing.status, synced_order: syncedOrder };
}
/**

View File

@@ -46,3 +46,36 @@ export function decodeCustomFields(raw: string | null): {
return { custom_fields: [], field_order: [] };
}
}
/**
* Per-document selection of which COMPANY custom fields print on a PDF.
* Stored positionally (matching the `custom_<i>` keys the PDF builder emits)
* as a JSON array string, e.g. "[0,2]". Null/empty means "none selected".
*/
export function encodeSelectedCustomFields(indices: unknown): string | null {
const clean = normalizeIndices(indices);
return clean.length > 0 ? JSON.stringify(clean) : null;
}
/** Decode the stored selection (string OR defensive array) into a clean number[]. */
export function parseSelectedCustomFields(raw: unknown): number[] {
if (raw == null) return [];
if (Array.isArray(raw)) return normalizeIndices(raw);
if (typeof raw !== "string" || raw.trim() === "") return [];
try {
return normalizeIndices(JSON.parse(raw));
} catch {
// Malformed JSON in a selection column degrades to "none" (expected
// condition — a hand-edited/legacy row should never 500 a PDF render).
return [];
}
}
function normalizeIndices(input: unknown): number[] {
if (!Array.isArray(input)) return [];
const set = new Set<number>();
for (const v of input) {
if (typeof v === "number" && Number.isInteger(v) && v >= 0) set.add(v);
}
return [...set].sort((a, b) => a - b);
}

17
src/utils/money.ts Normal file
View File

@@ -0,0 +1,17 @@
/**
* Net amount of a single document line after its per-item percentage discount
* ("Sleva"). `net = qty × unit_price × (1 discount/100)`.
*
* The discount is tolerant of null/undefined/NaN (a missing discount = none)
* and clamped to 0100 so a stray value can never make the net negative.
* Single source of truth for offers + invoices (totals, VAT base, PDFs).
*/
export function lineNet(
qty: number,
unitPrice: number,
discountPct: number | null | undefined,
): number {
const pct = Number(discountPct);
const safePct = Number.isFinite(pct) ? Math.min(100, Math.max(0, pct)) : 0;
return qty * unitPrice * (1 - safePct / 100);
}

View File

@@ -1,10 +1,20 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { readFileSync } from "node:fs";
// Bake the package.json version into the bundle so the running SPA can compare
// it to the server's X-App-Version header and detect a new deploy.
const appVersion = (
JSON.parse(readFileSync("./package.json", "utf8")) as { version: string }
).version;
export default defineConfig({
plugins: [react()],
root: ".",
publicDir: "public",
define: {
__APP_VERSION__: JSON.stringify(appVersion),
},
server: {
port: 3000,
},