Compare commits

...

19 Commits

Author SHA1 Message Date
BOHA
1a262508d4 chore(release): v2.0.5 — multi-record plan cells
A plan cell now holds up to 3 records: additive assignments + day
exceptions, via the layered entries/overrides model (no migration).
resolveCell/resolveGrid return arrays; cap enforced per layer on create;
grid renders up to 3 stacked; cell editor is a day panel (list/add/edit,
layer-aware add); dashboard "today" card shows up to 3.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:37:40 +02:00
BOHA
23ac924472 fix(plan): edit/add the clicked record + layer-aware add in exception mode
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:29:52 +02:00
BOHA
9370423fb0 feat(plan): day panel — list/add/edit up to 3 records per cell
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:16:52 +02:00
BOHA
a146fc26a3 feat(plan): grid renders up to 3 stacked records per cell
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 11:08:48 +02:00
BOHA
72888bf9cd feat(plan): resolveCell/resolveGrid return arrays; dashboard shows up to 3
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:53:26 +02:00
BOHA
80dc8a5c69 feat(plan): per-cell record cap (3) + additive overrides
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 10:46:40 +02:00
BOHA
2cfa28dc47 docs(plan): implementation plan for multi-record plan cells (v2.0.5)
Five tasks: (1) backend cap + additive overrides, (2) resolve->arrays +
coordinated frontend shape change + dashboard, (3) grid stacked render,
(4) day-panel cell editor, (5) v2.0.5 release. Backend tasks are TDD
against the real test DB; frontend tasks gate on tsc/build/Chrome (no
component-test harness).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:33:40 +02:00
BOHA
628cd54a81 docs(plan): spec for multi-record plan cells (max 3 per cell)
Feature A of 2: lets a plan cell hold up to 3 records (additive
assignments + day exceptions) via the layered entries/overrides model,
no migration. resolveCell/resolveGrid return arrays; cap enforced per
layer on create; grid shows up to 3 stacked; cell editor becomes a
day panel; dashboard today-card shows up to 3. Feature B (bulk create)
decisions captured as deferred.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:22:15 +02:00
BOHA
9ae69e09a3 fix(orders): delete NAS folder when order delete modal's checkbox is ticked
The order delete modal sends { delete_files }, but the route ignored the
body and deleteOrder never touched the NAS — so the project folder of an
order-spawned project always stayed on the share (the only way to delete
such a project is via its order, since deleteProject blocks order-linked
projects). Project delete (standalone projects) already worked.

- orders route: read delete_files from the body, pass to deleteOrder.
- orders.service deleteOrder(id, deleteFiles): select project_number and,
  after the DB transaction commits, best-effort deleteProjectFolder for
  each linked project when the flag is set. Non-fatal; idempotent.
- tests: NasFileManager.deleteProjectFolder coverage — removes by number
  prefix, no-op when absent, false when not mounted (158 -> 161 tests).

Bump version to 2.0.4.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 08:51:57 +02:00
BOHA
df83eb2091 feat(projects): auto-create NAS folder for order-spawned projects
Manual project creation already creates the 02_PROJEKTY/<number>_<name>
folder (projects.service.createProject). Projects created from an order —
both from an accepted offer (createOrderFromQuotation) and a manual
offer-less order (createOrder) — did not, so they had no NAS folder until
a user opened the project and clicked "create folder" or uploaded a file.

- orders.service: best-effort, non-fatal createProjectFolder after each
  project-creating transaction commits (mirrors createProject; gated on
  isConfigured(), logs on failure, never rolls back the order).
- projects.service: log when the existing auto-create returns false
  (was silently discarded — CLAUDE.md known-issue #4).
- nas-file-manager: optional constructor basePath seam for tests.
- tests: NasFileManager.createProjectFolder coverage — naming, idempotency,
  Czech diacritics, empty name, not-mounted (152 -> 158 tests).

Bump version to 2.0.3.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 08:43:59 +02:00
BOHA
9c862034ca chore(release): v2.0.2 — dashboard "today's assignment" card
- New "Vaše dnešní zařazení" dashboard card: shows the logged-in user's
  work-plan entry for today (category + project/site + note, multi-day
  range badge), with a muted empty state.

No DB migrations. tsc -b --noEmit, npm run build, vitest 152/152 clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 22:26:02 +02:00
BOHA
67d62a6df0 fix(dashboard): rename today-plan card to "Vaše dnešní zařazení"
Clearer, formal (matches the app's Vy/Vaše tone) and category-agnostic
(reads fine for work and absence days) so the employee plainly sees what
they're assigned to. Was "Můj plán na dnešek".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 22:25:35 +02:00
BOHA
512f1fd92b feat(dashboard): show the user's work plan for today
Adds a "Můj plán na dnešek" card near the clock-in: for the logged-in
user it shows today's work-plan entry — category (coloured dot + label),
the project/site (the "where"), the note, and a "součást rozsahu …" badge
only for genuinely multi-day ranges. A muted "Pro dnešek nemáte
naplánováno." empty state when nothing is scheduled.

Server: GET /api/admin/dashboard now returns today_plan, reusing
plan.service resolveCell (override-beats-range precedence) for the current
user + today's local (Prague) date, enriched with the category label +
colour so the widget needs no extra query. Gated by attendance.record /
attendance.manage (the plan permission); omitted otherwise. No migration.

Verified in Chrome: renders today's entry (Práce · OBJ-2026-006 — koko)
with the category colour. tsc -b --noEmit, npm run build, vitest 152/152.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 22:22:07 +02:00
BOHA
941caf9d85 chore(release): v2.0.1 — button/icon consistency + mobile header actions
UI consistency pass on top of v2.0.0:
- Colored button text unified to white on all filled controls (both
  themes); darker dark-mode fills so white stays legible.
- Icon badges unified via a shared iconBadgeSx (solid tile + white glyph).
- Detail-page header action buttons stack one-per-row on mobile.
- Dropped the duplicate "Zrušit" in the plan view-cell modal.

No DB migrations. tsc -b --noEmit, npm run build, vitest 152/152 clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:55:20 +02:00
BOHA
b00d18d0b3 fix(plan): drop duplicate 'Zrušit' in the view-mode cell modal
The read-only plan-cell detail modal (view mode) already has a "Zavřít"
submit button, but the kit Modal also rendered its built-in "Zrušit"
cancel — two buttons that do the same thing. Pass hideCancel so only
"Zavřít" remains (same fix as the category-management modal).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:54:42 +02:00
BOHA
decadd895e fix(ui): stack detail-page header action buttons one-per-row on mobile
Detail-page headers put their action buttons in a flex row with
flexWrap:"wrap", so on a phone the 2-4 buttons (Potvrzení / Zahájit
realizaci / Smazat, etc.) wrapped into a ragged grid.

New shared `headerActionsSx` (ui/PageHeader): on xs it's a full-width
column (each button its own full-width row); from sm up it's the usual
right-aligned wrapping row — desktop unchanged. A StatusChip kept in the
same group stays its natural size (alignSelf) instead of stretching.

Applied to PageHeader's own actions slot and every detail-page header
action group: Order/Offer/Invoice (both views)/Project + the Warehouse
Receipt/Issue/Item/Inventory detail headers.

Verified in Chrome at 430px on OrderDetail: the group is flexDirection
column with all three buttons at the same x, full-width, stacked. tsc -b
--noEmit, npm run build, vitest 152/152 clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:44:22 +02:00
BOHA
54f3c414f5 fix(ui): unify icon badges — solid tile + white glyph via shared helper
The labelled icon-badge tiles were inconsistent: some used a same-hue
light tile + colored glyph (e.g. the Settings 2FA row: success.light tile
+ success.main glyph — low contrast, the reported "badly visible" icon),
and the solid-tile ones used the bright .main fill in dark mode without
darkening, so a white glyph on bright green/amber was low-contrast too
(DashProfile's success badge was ~1.9:1).

Add a single `iconBadgeSx(color)` helper (theme.ts): solid `<color>.main`
fill + white glyph, darkened in dark mode (FILLED_DARK_BG) so white stays
legible; `default` = neutral grey. Applied to every badge so they can't
drift: StatCard, DashActivityFeed, DashProfile (2FA badge), Dashboard
(2FA banner icon), AttendanceHistory (month tile), and the Settings 2FA
row tile (now solid green when required / grey when optional + white lock,
instead of the low-contrast light-green tile). Also switched DashProfile's
backup-codes warning callout from warning.light to a subtle warning wash
so its amber text stays readable in dark mode.

tsc -b --noEmit, npm run build, vitest 152/152 all clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:34:06 +02:00
BOHA
ca092c6166 fix(ui): unify colored-control text — white on all filled, both themes
The text color on filled colored controls was inconsistent: contained
primary resolved to white in both schemes, but error/success/warning/info
used a per-scheme contrastText (#fff light, #1a1a1a dark). So in DARK mode
a primary (red) button showed white text while an error (red) button —
e.g. every ConfirmDialog delete confirm, the contained "Smazat", and the
dashboard quick-action tiles — showed near-black text. "Black text on one
red button, white on another."

Unify on a single rule: every FILLED colored surface gets WHITE text/glyph
in BOTH themes. The palette .main stays bright in dark mode (it drives text,
outlined buttons and row tints), but a bright fill makes white illegible, so
filled surfaces drop to a darker fill in dark mode (new FILLED_DARK_BG, ≈ the
light-scheme shades; all ≥4.5:1 with white):
- theme MuiButton: contained error/success/warning/info -> white text +
  darker dark-mode fill (disabled state preserved).
- theme MuiChip: filled error/success/warning/info -> white label + darker
  dark-mode fill (covers StatusChip + status pills).
- StatCard icon badges: white glyph + darker dark-mode tile.

Plus two consistency cleanups:
- Detail-page "Smazat" unified to variant=outlined color=error (Offer +
  Invoice now match Order/Project/Warehouse; the contained->confirm pattern
  stays: subtle trigger, strong contained confirm dialog).
- "Zrušit filtry" reset buttons -> color=inherit (neutral), matching the
  rest of the secondary-button family (were default outlined-primary).

Neutral (color=inherit) text/outlined buttons were already correct (label =
ambient text color) and are untouched. tsc -b --noEmit, npm run build and
vitest 152/152 all clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 20:41:50 +02:00
BOHA
c7f9d9aa36 docs(claude): update for completed MUI migration + v2.0.0
Bring CLAUDE.md in line with the current codebase:

- Tech Stack: add Material UI v7 (Emotion) to the frontend row.
- Project Structure: ~105 .tsx (was 57), 49 models (was 32); add the
  ui/ kit, lib/ (React Query), theme.ts and GlobalStyles.tsx; fix
  contexts/ -> context/; correct the hooks list (drop the nonexistent
  useApiCall/useListData); refresh the components/ + __tests__ notes.
- Testing: drop "coverage is minimal: only auth and numbering" — the
  suite is ~14 files / 152 tests across many areas.
- Frontend Conventions: styling is MUI/Emotion (no .css files, use
  theme.vars), data layer is React Query, token responses carry
  expires_in.
- "MUI Migration (in progress)" -> "Styling & MUI (complete, v2.0.0)":
  zero custom CSS; where styling lives (theme/GlobalStyles/kit); and the
  conventions learned (channel-alpha row tints not solid .light, solid
  tile + white-glyph icon badges, single mui-mode theme key, dialog
  scroll-lock). Removed the stale "data-theme drives MUI and legacy CSS".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 20:12:08 +02:00
42 changed files with 3144 additions and 539 deletions

View File

@@ -14,7 +14,7 @@ Handles attendance, invoicing, leave/trips, projects, vehicles, and HR operation
| ORM | Prisma 6.19.2 → MySQL | | ORM | Prisma 6.19.2 → MySQL |
| Auth | JWT (HS256, 15 min) + TOTP 2FA (RFC 6238, otpauth) + bcryptjs | | Auth | JWT (HS256, 15 min) + TOTP 2FA (RFC 6238, otpauth) + bcryptjs |
| Validation | Zod 4.3.6 | | Validation | Zod 4.3.6 |
| Frontend | React 18.3.1 + Vite 8.0.0 | | Frontend | React 18.3.1 + Vite 8.0.0 + Material UI v7 (Emotion) |
| Testing | Vitest 4.1.0 + Supertest | | Testing | Vitest 4.1.0 + Supertest |
| PDF | Puppeteer 24.x | | PDF | Puppeteer 24.x |
| Email | nodemailer 8.x | | Email | nodemailer 8.x |
@@ -35,17 +35,21 @@ src/
├── utils/ # totp.ts, pdf.ts, email.ts, audit.ts, formatters, etc. ├── utils/ # totp.ts, pdf.ts, email.ts, audit.ts, formatters, etc.
├── config/ # env.ts (config singleton, Date.toJSON override) ├── config/ # env.ts (config singleton, Date.toJSON override)
├── types/ # index.ts (AuthData, JwtPayload, ApiResponse, re-exports from Prisma) ├── types/ # index.ts (AuthData, JwtPayload, ApiResponse, re-exports from Prisma)
├── admin/ # React 18 frontend (57 .tsx files) ├── admin/ # React 18 + Material UI frontend (~105 .tsx files)
│ ├── AdminApp.tsx # Router + lazy-loaded pages │ ├── AdminApp.tsx # Router + lazy-loaded pages
│ ├── contexts/ # AuthContext, AlertContext │ ├── theme.ts # MUI theme — light/dark color schemes, tokens, component defaults
│ ├── components/ # Layout, modals, tables, editors │ ├── GlobalStyles.tsx # App-wide global styles via MUI <GlobalStyles> (reset, typography, utilities)
│ ├── ui/ # MUI component kit (AppShell, Button, DataTable, Modal, …) — pages import from here
│ ├── context/ # AuthContext, AlertContext (ThemeContext lives in src/context/)
│ ├── components/ # Non-page components: RichEditor (Quill), PlanGrid, file manager, dashboard/ + warehouse/ widgets
│ ├── pages/ # One file per page/feature │ ├── pages/ # One file per page/feature
│ ├── hooks/ # useApiCall, useListData, useTableSort, etc. │ ├── lib/ # React Query options & mutations (queries/) + shared label maps
│ ├── hooks/ # usePaginatedQuery, useTableSort, useDebounce, useReducedMotion, …
│ └── utils/ # api.ts (fetch wrapper with token refresh), formatters, helpers │ └── utils/ # api.ts (fetch wrapper with token refresh), formatters, helpers
└── __tests__/ # Vitest tests (auth, numbering) └── __tests__/ # Vitest tests (~14 files: auth, numbering, warehouse, plan, invoices, …)
prisma/ prisma/
├── schema.prisma # 32 models, MySQL, snake_case columns ├── schema.prisma # 49 models, MySQL, snake_case columns
└── migrations/ # Applied migrations └── migrations/ # Applied migrations
dist/ # Compiled server (CommonJS, ES2022) dist/ # Compiled server (CommonJS, ES2022)
@@ -236,7 +240,7 @@ if ("error" in body) return error(reply, body.error, 400);
Tests live in `src/__tests__/`. They use Vitest + Supertest against a real test database (`.env.test`). Tests live in `src/__tests__/`. They use Vitest + Supertest against a real test database (`.env.test`).
- Test coverage is minimal: only `auth` and `numbering` are tested. - The suite spans ~14 files / 152 tests — auth, numbering, warehouse, plan, invoices, exchange-rates, schema coercion, NAS file manager, env, manual-create. Server-side only (no component tests yet).
- Use `buildApp()` helper to spin up the Fastify instance for tests. - Use `buildApp()` helper to spin up the Fastify instance for tests.
- Tests use `vitest.config.ts` with `environment: 'node'` and 15s timeout. - Tests use `vitest.config.ts` with `environment: 'node'` and 15s timeout.
- **Do not mock Prisma** — tests hit a real database to catch schema/query bugs. - **Do not mock Prisma** — tests hit a real database to catch schema/query bugs.
@@ -250,9 +254,9 @@ When adding new features, add tests in `src/__tests__/`. Name test files `<featu
- Pages are lazy-loaded via `React.lazy()` in `AdminApp.tsx`. - Pages are lazy-loaded via `React.lazy()` in `AdminApp.tsx`.
- Auth state lives in `AuthContext`; use `useAuth()` hook to access it. - Auth state lives in `AuthContext`; use `useAuth()` hook to access it.
- Alerts/toasts use `AlertContext`; use `useAlert()` to show them. - Alerts/toasts use `AlertContext`; use `useAlert()` to show them.
- API calls go through `src/admin/utils/api.ts` which handles token refresh automatically (deduplicates concurrent refresh calls). - Data fetching uses **React Query** (query options + mutations in `src/admin/lib/queries/`); `src/admin/utils/api.ts` (`apiFetch`) handles token refresh automatically dedupes concurrent refreshes, and token responses carry `expires_in` so the client refreshes BEFORE expiry (no reactive 401 churn).
- Custom hooks: `useApiCall`, `useListData`, `useTableSort`, `useDebounce`, `useModalLock`. - Custom hooks: `usePaginatedQuery`, `useTableSort`, `useDebounce`, `useModalLock`, `useReducedMotion`.
- Styling: CSS files in `src/admin/` — no CSS-in-JS, no Tailwind. Use CSS variables. - Styling: **Material UI v7** (Emotion) — theme in `src/admin/theme.ts`, `sx`/`styled()` in components, app-wide rules in `GlobalStyles.tsx`. **No hand-written `.css` files, no Tailwind.** Use `theme.vars` for colours so light/dark resolve automatically.
### Query Invalidation Convention ### Query Invalidation Convention
@@ -274,16 +278,30 @@ When entity A embeds/references entity B, A's mutation handlers invalidate B's d
--- ---
## Frontend — MUI Migration (in progress) ## Frontend — Styling & MUI (migration complete, shipped in v2.0.0)
The admin frontend is being migrated off ~7,100 lines of hand-written CSS onto **MUI (Material UI v7)** — a "Soft-SaaS shell + dense tables" look, dark/light preserved, **incremental and always shippable**. The admin frontend is **fully on Material UI v7** (Emotion). The old ~7,100 lines of hand-written CSS are gone — **there are no custom `.css` files in `src/admin`**; the only stylesheets imported anywhere are the two third-party libs (`react-quill-new/dist/quill.snow.css`, `leaflet/dist/leaflet.css`). Look-and-feel is "Soft-SaaS shell + dense tables", dark/light preserved. Full history/decisions/gotchas live in agent memory (`project_mui_migration.md`); the original spec/plans are under `docs/superpowers/`.
- **Spec:** `docs/superpowers/specs/2026-06-06-css-mui-migration-design.md`. **Per-phase plans:** `docs/superpowers/plans/2026-06-06-mui-migration-phase-*.md`. **Where styling lives**
- **Progress is tracked in agent memory** (`project_mui_migration.md` — what's merged, what's next). **Keep it updated as each phase merges.** Memory practice generally: durable, non-obvious facts about ongoing work / decisions / gotchas belong in the agent memory store (one fact per file, indexed in `MEMORY.md`), not left only in chat.
- **Migrating a page:** mirror `src/admin/pages/Vehicles.tsx` (the pilot). Import only from the **`src/admin/ui/` kit** — never `@mui/*` directly in pages. **Preserve ALL data logic verbatim** (hooks, mutations, `invalidate` arrays, validation, permissions); change only presentation; drop the page's `admin-*` CSS usage. Per page: plan → subagent-driven build → spec + code-quality review → user visual check → merge. - **Theme — `src/admin/theme.ts`:** `cssVariables` with `colorSchemeSelector: "[data-theme='%s']"`, light + dark `colorSchemes`, tokens, component defaults. Use **`theme.vars!.palette.*`** (the `vars` field is typed optional → `!`) so colours resolve per scheme; for alpha use the channel tokens — `rgba(${theme.vars!.palette.primary.mainChannel} / 0.12)`; for per-scheme one-offs use `theme.applyStyles("dark", { … })`.
- **Kit (`src/admin/ui/`):** AppShell, Button, Card, TextField, Select (string-based — convert ids at the boundary), DateField (date-fns v4, `dd.MM.yyyy`, cs), Modal, ConfirmDialog (optional `children` + content freeze), DataTable (sortable via `sortKey`/`sortBy`/`onSort`), Pagination, Tabs/TabPanel, StatusChip, CheckboxField, SwitchField, Field, Alert. Theme + tokens in `src/admin/theme.ts`; one `data-theme` attribute drives MUI **and** legacy CSS. Dev-only `/ui-kit` showcase route. - **Global rules — `src/admin/GlobalStyles.tsx`:** reset, typography, scrollbar, `::selection`, view-transition timing, and the utility classes (`.text-*`, `.flex-*`, `.mb-*`, ), all theme-aware. (The pre-React bootstrap spinner is inlined in `src/App.tsx` because it mounts before MUI.)
- **Gates every step:** `npx tsc -b --noEmit` (NOT `-p tsconfig.json` — that's a vacuous solution file that checks nothing), `npm run build`, `npx vitest run`. - **Component kit — `src/admin/ui/`:** AppShell, Button, Card, TextField, Select (string-based — convert ids at the boundary), DateField/MonthField/TimeField (date-fns v4, cs), Modal, ConfirmDialog (optional `children` + content freeze), DataTable (sortable + mobile card layout + `rowSx`/`rowDanger`/`rowInactive`), Pagination, Tabs/TabPanel, StatusChip, CheckboxField/SwitchField, Field, Alert, PageHeader, FilterBar, StatCard, ProgressBar, FileUpload, EmptyState, LoadingState, ThemeToggle, PageEnter (staggered page entrance), RichEditorRoot/RichTextView (Quill). Dev-only `/ui-kit` showcase route.
- **Dialog gotchas (solved in the kit — don't reintroduce):** dialogs lock `<html>` via `useDialogScrollLock` (MUI only locks `<body>`, and `html{overflow-x:hidden}` makes `<html>` the scroll container); Modal/ConfirmDialog freeze title/label/loading through the close fade (derive-state-from-props) so nothing flashes during the transition. Login renders OUTSIDE the AppShell (sibling route).
**Building / editing pages**
- Pages import from the **kit** (`src/admin/ui/`); reach for `@mui/material` (`styled`/`sx`) directly only for one-off layout or infra (theme, GlobalStyles, the Quill/Leaflet wrappers).
- Wrap a page's top-level sections in `<PageEnter>`. Filters go in `<FilterBar>` with **bare** controls (no `<Field>` label) at the standard widths.
- When refactoring, **preserve ALL data logic verbatim** (hooks, mutations, `invalidate` arrays, validation, permissions); change only presentation.
**Conventions learned — don't regress**
- **Status row tints** = subtle channel-alpha washes (`rgba(var(--mui-palette-X-mainChannel) / 0.12)`), NEVER a solid `.light` fill: `.light` is a light colour in BOTH schemes, so white dark-mode text on it is invisible. Voided/disabled rows = `opacity` + muted text.
- **Icon badges** = solid `X.main` tile + **white** glyph (not an `X.light` tile + `X.main` glyph — that's low-contrast).
- **Theme is single-source:** `src/context/ThemeContext.tsx` owns the `<html data-theme>` attribute + the View-Transitions cross-fade, and persists under MUI's **`mui-mode`** localStorage key (the same key MUI reads on mount). Do NOT add a second theme key — that desyncs page vs toggle on refresh.
- **Dialogs** lock `<html>` via `useDialogScrollLock` (MUI only locks `<body>`, and `html{overflow-x:hidden}` makes `<html>` the scroller); Modal/ConfirmDialog freeze title/label/loading through the close fade so nothing flashes. Login renders OUTSIDE AppShell.
**Gates every change:** `npx tsc -b --noEmit` (NOT `-p tsconfig.json` — a vacuous solution file that checks nothing), `npm run build`, `npx vitest run`.
--- ---

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,208 @@
# Design — Multi-record plan cells (max 3 per cell)
**Date:** 2026-06-08
**Status:** Approved (brainstorming) — ready for implementation plan
**Feature A of 2.** Feature B (bulk plan creation) is a separate later cycle — see "Deferred: Feature B" at the end.
---
## Goal
Today a plan cell (one person, one day) resolves to **exactly one** record: an
override hides the planned range, and overlapping range entries collapse to
"newest wins". The work plan should instead let a cell hold **up to 3 records**,
so a person can have several assignments on the same day (additive) _and_ still
get one-day exceptions to a planned range.
This is the enabling model change. The eventual "bulk assign a project to many
employees over a date range" form (Feature B) will create records under this
model and respect the 3-per-cell cap.
## Use cases (both required)
1. **Additive** — several projects/tasks the same day (e.g. morning project A,
afternoon project B). Both records show in the cell.
2. **Day exception** — assigned to a multi-day range, but one day differs;
replace just that day without splitting the range.
## Non-goals / out of scope
- No bulk-create UI (Feature B).
- No database migration — the tables already allow multiple rows per
(user, day) (the old `work_plan_overrides` uniqueness constraint was dropped in
migration `20260605122718_drop_wpo_unique_constraint`).
- The max is a fixed constant (3), not user-configurable.
---
## Model — "layered" (approved)
Keep the two existing tables and their meaning; stop collapsing them to one
record.
- **`work_plan_entries` (ranges) = the normal-plan layer.** Multiple active
ranges may cover the same day → the **additive** case.
- **`work_plan_overrides` (single-day) = the exception layer.** When a day has
≥1 active override, the overrides **replace** the range entries for that day
(today's "override beats entry" rule, kept) → the **day-exception** case.
### Resolution rule
For a given `(user, day)`:
1. Active overrides for that exact day (`is_deleted = false`). If any →
the cell is the overrides, **newest-first, capped at 3**.
2. Otherwise → active entries covering that day
(`date_from ≤ day ≤ date_to`, `is_deleted = false`), **newest-first, capped at 3**.
3. Otherwise → empty.
The cell is therefore an array of 03 `ResolvedCell` items, all from a single
layer (overrides **or** entries, never mixed). This preserves the "exception
replaces the day" semantic while allowing additive stacking within each layer.
**Known limitation (accepted):** a range entry and an exception override cannot
show together on the same day — an override is all-or-nothing for that day. This
matches what "exception" means.
### Cap (max 3 per cell)
`MAX_RECORDS_PER_CELL = 3` (single constant in `plan.service.ts`).
Enforced on create, per layer, per day:
- **`createOverride`** — reject if the `(user, day)` already has 3 active
overrides.
- **`createEntry`** — reject if **any** day in the new `[date_from, date_to]`
range is already covered by 3 active entries for that user. The error names the
first offending date (Czech message). Cap counts entries regardless of whether
they are currently hidden by an override (simpler and predictable).
`createOverride` **changes from replace-semantics to additive-with-cap**: it no
longer soft-deletes the existing override for that day. The transaction +
row-lock that protected the old "at most one active override" invariant is
repurposed to enforce "at most 3" under concurrency. The `replacedData` /
`replacedDescription` plumbing (and the route branch that logged the replaced
row's soft-delete) is removed.
---
## Backend changes
### `src/services/plan.service.ts`
- `ResolvedCell` interface unchanged (still one record).
- `resolveCell(userId, dateStr)` → returns `ResolvedCell[]` (03) using the
resolution rule above. Replaces the current single-result + "newest wins"
`console.warn`.
- `resolveGrid(userIds, from, to)``cells[userId][dateStr]` becomes
`ResolvedCell[]` (empty array, not `null`, for no records). Same two-query
load; per (user, day) build the capped array from the right layer.
- `createEntry` → add the per-day entry-cap check before insert.
- `createOverride` → drop the soft-delete-replace; add the override-cap check;
keep the transaction/lock for race safety; drop `replacedData`.
- Add `export const MAX_RECORDS_PER_CELL = 3;`.
### `src/routes/admin/plan.ts`
- `POST /plan/overrides` — remove the `result.replacedData` audit branch (no
longer produced). Everything else unchanged (cap errors surface via the normal
`{ error, status }` path).
### `src/routes/admin/dashboard.ts`
- `today_plan` is built from `resolveCell` → now an **array**. Map each record
with its category label + colour (the existing enrichment, applied per item).
`result.today_plan` becomes `TodayPlan[]` (possibly empty).
---
## Frontend changes
### Types — `src/admin/lib/queries/plan.ts`
- `GridData.cells: Record<number, Record<string, ResolvedCell[]>>` (was
`ResolvedCell | null`).
### Grid — `src/admin/components/PlanGrid.tsx` + `PlanRangeChips.tsx`
- A cell renders **up to 3 stacked records**, each a compact row: category
colour bar + category label + project (mono). When the cell has **exactly one**
record, also show its note (2-line clamp), as today. With 23 records, notes
are omitted for density.
- `--cat-color` is set per record row (not per cell).
- `onCellClick(userId, date, cells)` passes the **array**. Empty cell → still a
one-click create. Occupied cell → opens the day panel (below).
- Past-day / read-only / weekend / today styling unchanged.
```
┌─ Jan N. · Čt 12 ───────┐
│▌ PRÁCE · 26710001 │
│▌ DOVOLENÁ │
│▌ ŠKOLENÍ · 26710044 │
└────────────────────────┘ ▌ = category colour bar
```
### Cell editor — `src/admin/components/PlanCellModal.tsx`
New top-level **day-panel** mode shown when a cell has ≥1 record:
- Lists the day's records (each: colour bar, category, project, optional note)
with **edit (✎)** and **delete (🗑)** per record.
- **"+ Přidat záznam"** button, disabled at 3 with a hint
("Maximum 3 záznamy na den"). Add targets the **showing layer**: an entry in
normal mode, an override in exception mode — so the panel reads simply as
"records for this day" and the entry/override distinction stays invisible.
- Editing a record reuses the existing `EditForm`. Editing a record that belongs
to a **multi-day range** still routes through the existing `day-in-range`
chooser ("edit whole range" vs "carve out this day" = create override).
- Empty cell skips the panel and opens the create form directly (current
behaviour).
`PlanWork.tsx` wires the new panel: cell-click opens it with the array; the
panel's per-record actions reuse the existing entry/override create/update/delete
mutations and `invalidate: ["plan"]`.
### Dashboard — `DashTodayPlan.tsx` + `Dashboard.tsx`
- `today_plan` prop becomes `TodayPlan[]`. Render up to 3 records stacked
(reuse the existing single-record card layout per item). Empty array → the
existing "Pro dnešek nemáte naplánováno." state.
---
## Testing (`src/__tests__/plan.test.ts`)
Update existing assertions for the array shape, and add:
- `resolveCell` returns `[]` for an empty day; one item for a single entry; the
override layer (entries hidden) when an override exists.
- **Additive:** two entries covering the same day → both returned (newest first).
- **Cap display:** 4 overlapping entries on a day → only 3 returned.
- **Cap enforcement:** `createEntry` rejects when a day in range already has 3
entries (error names the date); `createOverride` rejects at 3 overrides.
- **Additive overrides:** `createOverride` no longer soft-deletes the prior
override; two overrides on a day coexist.
- `resolveGrid` cell arrays match `resolveCell` for the same (user, day).
Gates: `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`.
## Rollout
Ships as its own release (**v2.0.5**) via the standard process (commit → tag →
Gitea → tarball → prod deploy → health check). No migration step.
---
## Deferred: Feature B (bulk plan creation) — decisions captured
A later, separate spec + cycle. Locked decisions from this brainstorming:
- **Form:** select one project, a date range (fromto), and multiple employees;
create the assignment for all of them at once.
- **Category:** a category picker in the bulk form, **default Práce**.
- **Weekends:** an **"include weekends" checkbox** (off = MonFri only, which
requires splitting each person into per-work-week entries; on = one continuous
range).
- **Conflict handling:** governed by this feature's **max-3-per-cell** rule — for
each employee/day, create the record only if the cell is under the cap;
otherwise **skip** that day (no error).

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "app-ts", "name": "app-ts",
"version": "2.0.0", "version": "2.0.2",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "app-ts", "name": "app-ts",
"version": "2.0.0", "version": "2.0.2",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1", "@dnd-kit/core": "^6.3.1",

View File

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

View File

@@ -0,0 +1,106 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import fs from "fs";
import os from "os";
import path from "path";
import { NasFileManager } from "../services/nas-file-manager";
/**
* Folder auto-creation primitive used by both the manual project-create path
* (projects.service createProject) and the order→project paths (orders.service
* createOrder / createOrderFromQuotation). Uses an isolated temp dir via the
* constructor seam so it is deterministic and passes even where the real NAS
* (Z:) is not mounted.
*/
describe("NasFileManager.createProjectFolder", () => {
let tmpBase: string;
let nas: NasFileManager;
beforeEach(() => {
tmpBase = fs.mkdtempSync(path.join(os.tmpdir(), "nas-proj-"));
nas = new NasFileManager(tmpBase);
});
afterEach(() => {
fs.rmSync(tmpBase, { recursive: true, force: true });
});
it("creates a <number>_<name> folder for a new project", () => {
const ok = nas.createProjectFolder("26710001", "Rekonstrukce haly");
expect(ok).toBe(true);
expect(
fs.existsSync(path.join(tmpBase, "26710001_Rekonstrukce_haly")),
).toBe(true);
});
it("is idempotent — a second call does not create a duplicate", () => {
expect(nas.createProjectFolder("26710002", "Hala")).toBe(true);
expect(nas.createProjectFolder("26710002", "Hala")).toBe(true);
const matches = fs
.readdirSync(tmpBase)
.filter((e) => e.startsWith("26710002_"));
expect(matches).toEqual(["26710002_Hala"]);
});
it("preserves Czech diacritics (no transliteration)", () => {
expect(nas.createProjectFolder("26710003", "Měření haly")).toBe(true);
expect(fs.existsSync(path.join(tmpBase, "26710003_Měření_haly"))).toBe(
true,
);
});
it("strips illegal characters and collapses spaces", () => {
expect(nas.createProjectFolder("26710004", "A / B: C")).toBe(true);
expect(fs.existsSync(path.join(tmpBase, "26710004_A_B_C"))).toBe(true);
});
it("handles an empty name without crashing (trailing underscore)", () => {
expect(nas.createProjectFolder("26710005", "")).toBe(true);
expect(fs.existsSync(path.join(tmpBase, "26710005_"))).toBe(true);
});
it("returns false and creates nothing when the NAS base is not mounted", () => {
const missing = new NasFileManager(
path.join(tmpBase, "does-not-exist-subdir"),
);
expect(missing.createProjectFolder("26710006", "X")).toBe(false);
expect(fs.existsSync(path.join(tmpBase, "does-not-exist-subdir"))).toBe(
false,
);
});
});
/**
* Folder deletion primitive used by the "delete folder" checkbox on both the
* order delete (orders.service deleteOrder) and project delete (projects.service
* deleteProject) paths. Matches the project by number prefix.
*/
describe("NasFileManager.deleteProjectFolder", () => {
let tmpBase: string;
let nas: NasFileManager;
beforeEach(() => {
tmpBase = fs.mkdtempSync(path.join(os.tmpdir(), "nas-del-"));
nas = new NasFileManager(tmpBase);
});
afterEach(() => {
fs.rmSync(tmpBase, { recursive: true, force: true });
});
it("removes an existing project folder (matched by number prefix)", async () => {
nas.createProjectFolder("26710010", "Hala");
expect(fs.existsSync(path.join(tmpBase, "26710010_Hala"))).toBe(true);
const ok = await nas.deleteProjectFolder("26710010");
expect(ok).toBe(true);
expect(fs.existsSync(path.join(tmpBase, "26710010_Hala"))).toBe(false);
});
it("is a no-op (returns true) when no folder exists for the number", async () => {
expect(await nas.deleteProjectFolder("26710011")).toBe(true);
});
it("returns false when the NAS base is not mounted", async () => {
const missing = new NasFileManager(path.join(tmpBase, "nope"));
expect(await missing.deleteProjectFolder("26710012")).toBe(false);
});
});

View File

@@ -58,6 +58,20 @@ beforeEach(async () => {
await prisma.work_plan_overrides.deleteMany({ await prisma.work_plan_overrides.deleteMany({
where: { note: { contains: N } }, where: { note: { contains: N } },
}); });
// Also clean up empty-note rows on the specific test dates used by the
// "allows an empty note" tests. These rows are not caught by the prefix
// filter above, and would cause the per-cell cap check to reject them
// once three accumulate across runs.
await prisma.work_plan_entries.deleteMany({
where: {
date_from: {
in: [
new Date("2099-07-15T00:00:00.000Z"),
new Date("2097-08-05T00:00:00.000Z"),
],
},
},
});
}); });
afterAll(async () => { afterAll(async () => {
@@ -75,10 +89,9 @@ afterAll(async () => {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
describe("plan.service.resolveCell", () => { describe("plan.service.resolveCell", () => {
it("returns null when nothing covers the date", async () => { it("returns [] when nothing covers the date", async () => {
// No entry, no override for (adminUserId, "2099-01-01")
const result = await resolveCell(adminUserId, "2099-01-01"); const result = await resolveCell(adminUserId, "2099-01-01");
expect(result).toBeNull(); expect(result).toEqual([]);
}); });
it("returns the entry that covers the date", async () => { it("returns the entry that covers the date", async () => {
@@ -93,17 +106,14 @@ describe("plan.service.resolveCell", () => {
}, },
}); });
const result = await resolveCell(adminUserId, "2099-06-05"); const result = await resolveCell(adminUserId, "2099-06-05");
expect(result).not.toBeNull(); expect(result.length).toBe(1);
expect(result?.source).toBe("entry"); expect(result[0].source).toBe("entry");
expect(result?.note).toBe(`${N}PLC upgrade`); expect(result[0].note).toBe(`${N}PLC upgrade`);
expect(result?.category).toBe("work"); expect(result[0].rangeFrom).toBe("2099-06-01");
expect(result?.rangeFrom).toBe("2099-06-01"); expect(result[0].rangeTo).toBe("2099-06-10");
expect(result?.rangeTo).toBe("2099-06-10");
}); });
it("returns the override for that day, not the entry", async () => { it("returns overrides (entries hidden) when an override exists", async () => {
// An entry covers 2099-06-01..2099-06-10, but an override on 2099-06-05
// takes precedence.
await prisma.work_plan_entries.create({ await prisma.work_plan_entries.create({
data: { data: {
user_id: adminUserId, user_id: adminUserId,
@@ -124,10 +134,51 @@ describe("plan.service.resolveCell", () => {
}, },
}); });
const result = await resolveCell(adminUserId, "2099-06-05"); const result = await resolveCell(adminUserId, "2099-06-05");
expect(result).not.toBeNull(); expect(result.length).toBe(1);
expect(result?.source).toBe("override"); expect(result[0].source).toBe("override");
expect(result?.note).toBe(`${N}Volno po noční`); expect(result[0].note).toBe(`${N}Volno po noční`);
expect(result?.category).toBe("leave"); });
it("returns multiple additive entries newest-first", async () => {
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-01"),
date_to: new Date("2099-06-10"),
category: "work",
note: `${N}first`,
created_by: adminUserId,
},
});
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-05"),
date_to: new Date("2099-06-05"),
category: "work",
note: `${N}second`,
created_by: adminUserId,
},
});
const result = await resolveCell(adminUserId, "2099-06-05");
expect(result.length).toBe(2);
expect(result[0].note).toBe(`${N}second`); // newest first
});
it("caps the returned records at MAX_RECORDS_PER_CELL", async () => {
for (let i = 0; i < 4; i++) {
await prisma.work_plan_overrides.create({
data: {
user_id: adminUserId,
shift_date: new Date("2099-06-06"),
category: "leave",
note: `${N}cap${i}`,
created_by: adminUserId,
},
});
}
const result = await resolveCell(adminUserId, "2099-06-06");
expect(result.length).toBe(3);
}); });
it("ignores soft-deleted entries and overrides", async () => { it("ignores soft-deleted entries and overrides", async () => {
@@ -143,7 +194,7 @@ describe("plan.service.resolveCell", () => {
}, },
}); });
const result = await resolveCell(adminUserId, "2099-06-05"); const result = await resolveCell(adminUserId, "2099-06-05");
expect(result).toBeNull(); expect(result).toEqual([]);
}); });
}); });
@@ -164,11 +215,11 @@ describe("plan.service.resolveGrid", () => {
}, },
}); });
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-05"); const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-05");
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`); expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}A`); expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`); expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-04"]).toBeNull(); expect(cells[adminUserId]["2099-06-04"]).toEqual([]);
expect(cells[adminUserId]["2099-06-05"]).toBeNull(); expect(cells[adminUserId]["2099-06-05"]).toEqual([]);
}); });
it("applies override on a covered day", async () => { it("applies override on a covered day", async () => {
@@ -192,9 +243,78 @@ describe("plan.service.resolveGrid", () => {
}, },
}); });
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-03"); const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-03");
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`); expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}B`); expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}B`);
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`); expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
});
it("stacks additive entries newest-first and caps the day at MAX_RECORDS_PER_CELL", async () => {
// Two entries cover 2099-06-12 → both appear, newest-first. A 3rd entry
// covering the same day and a 4th overlapping one push past the cap, so the
// day must still return exactly 3 (mirrors resolveCell's cap behaviour).
//
// created_at is @db.Timestamp(0) (second precision, MySQL TIMESTAMP range
// tops out at 2038), so rows created in the same second tie on the
// `created_at desc` sort. We set explicit, distinct in-range created_at
// values so the newest-first assertion is deterministic.
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-11"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g1`,
created_by: adminUserId,
created_at: new Date("2037-06-01T08:00:00.000Z"),
},
});
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-12"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g2`,
created_by: adminUserId,
created_at: new Date("2037-06-01T09:00:00.000Z"), // newer than g1
},
});
// Two-entry day: assert length 2 and newest-first ordering.
const twoDay = await resolveGrid([adminUserId], "2099-06-11", "2099-06-12");
expect(twoDay[adminUserId]["2099-06-12"].length).toBe(2);
expect(twoDay[adminUserId]["2099-06-12"][0].note).toBe(`${N}g2`); // newest first
// Day with no second entry stays single.
expect(twoDay[adminUserId]["2099-06-11"].length).toBe(1);
// Add a 3rd and a 4th overlapping entry on 2099-06-12 to exceed the cap.
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-12"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g3`,
created_by: adminUserId,
created_at: new Date("2037-06-01T10:00:00.000Z"),
},
});
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-12"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g4`,
created_by: adminUserId,
created_at: new Date("2037-06-01T11:00:00.000Z"),
},
});
const cappedDay = await resolveGrid(
[adminUserId],
"2099-06-12",
"2099-06-12",
);
expect(cappedDay[adminUserId]["2099-06-12"].length).toBe(3);
}); });
}); });
@@ -341,6 +461,36 @@ describe("plan.service.createEntry", () => {
expect("error" in result).toBe(true); expect("error" in result).toBe(true);
if ("error" in result) expect(result.status).toBe(403); if ("error" in result) expect(result.status).toBe(403);
}); });
it("rejects a 4th entry covering a day already at the cap", async () => {
for (let i = 0; i < 3; i++) {
const r = await createEntry(
{
user_id: adminUserId,
date_from: "2099-07-20",
date_to: "2099-07-20",
category: "work",
note: `${N}e${i}`,
},
adminUserId,
false,
);
expect("data" in r).toBe(true);
}
const fourth = await createEntry(
{
user_id: adminUserId,
date_from: "2099-07-20",
date_to: "2099-07-20",
category: "work",
note: `${N}e3`,
},
adminUserId,
false,
);
expect("error" in fourth).toBe(true);
if ("error" in fourth) expect(fourth.status).toBe(400);
});
}); });
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -439,7 +589,7 @@ describe("plan.service.deleteEntry", () => {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
describe("plan.service.createOverride", () => { describe("plan.service.createOverride", () => {
it("creates an override and returns { data, oldData: null, replacedData: null }", async () => { it("creates an override and returns { data, oldData: null }", async () => {
const result = await createOverride( const result = await createOverride(
{ {
user_id: adminUserId, user_id: adminUserId,
@@ -454,42 +604,45 @@ describe("plan.service.createOverride", () => {
if ("data" in result) { if ("data" in result) {
expect(result.data.note).toBe(`${N}day off`); expect(result.data.note).toBe(`${N}day off`);
expect(result.oldData).toBeNull(); expect(result.oldData).toBeNull();
expect(result.replacedData).toBeNull();
} }
}); });
it("soft-deletes the existing override and reports it in replacedData", async () => { it("stacks additive overrides and caps at MAX_RECORDS_PER_CELL", async () => {
await createOverride( for (let i = 0; i < 3; i++) {
const r = await createOverride(
{ {
user_id: adminUserId, user_id: adminUserId,
shift_date: "2099-10-02", shift_date: "2099-10-02",
category: "leave", category: "leave",
note: `${N}first`, note: `${N}o${i}`,
}, },
adminUserId, adminUserId,
false, false,
); );
const second = await createOverride( expect("data" in r).toBe(true);
}
// A 4th record on the same day is rejected by the cap.
const fourth = await createOverride(
{ {
user_id: adminUserId, user_id: adminUserId,
shift_date: "2099-10-02", shift_date: "2099-10-02",
category: "sick", category: "leave",
note: `${N}second`, note: `${N}o3`,
}, },
adminUserId, adminUserId,
false, false,
); );
expect("data" in second).toBe(true); expect("error" in fourth).toBe(true);
if ("data" in second) { if ("error" in fourth) expect(fourth.status).toBe(400);
expect((second.replacedData as any)?.note).toBe(`${N}first`); // All three earlier overrides remain active — no replace happened.
} const active = await prisma.work_plan_overrides.findMany({
where: {
const all = await prisma.work_plan_overrides.findMany({ user_id: adminUserId,
where: { user_id: adminUserId, shift_date: new Date("2099-10-02") }, shift_date: new Date("2099-10-02"),
is_deleted: false,
},
}); });
// The first should be soft-deleted, the second active expect(active.length).toBe(3);
expect(all.find((o) => o.note === `${N}first`)?.is_deleted).toBe(true);
expect(all.find((o) => o.note === `${N}second`)?.is_deleted).toBe(false);
}); });
it("rejects a past date without force", async () => { it("rejects a past date without force", async () => {
@@ -810,7 +963,7 @@ describe("HTTP /api/admin/plan", () => {
const body = res.json(); const body = res.json();
expect(body.data.users).toBeDefined(); expect(body.data.users).toBeDefined();
expect(body.data.cells[adminUserId]).toBeDefined(); expect(body.data.cells[adminUserId]).toBeDefined();
expect(body.data.cells[adminUserId]["2097-06-01"].note).toBe( expect(body.data.cells[adminUserId]["2097-06-01"][0].note).toBe(
`${N}grid test`, `${N}grid test`,
); );
}); });

View File

@@ -31,6 +31,7 @@ interface Project {
export type PlanCellModalMode = export type PlanCellModalMode =
| { kind: "closed" } | { kind: "closed" }
| { kind: "create"; userId: number; date: string } | { kind: "create"; userId: number; date: string }
| { kind: "create-override"; userId: number; date: string }
| { | {
kind: "edit-range"; kind: "edit-range";
entryId: number; entryId: number;
@@ -64,7 +65,8 @@ export type PlanCellModalMode =
note: string; note: string;
}; };
} }
| { kind: "view"; userId: number; date: string; cell: ResolvedCell }; | { kind: "view"; userId: number; date: string; cell: ResolvedCell }
| { kind: "day"; userId: number; date: string; cells: ResolvedCell[] };
interface Props { interface Props {
open: boolean; open: boolean;
@@ -84,6 +86,16 @@ interface Props {
date: string, date: string,
) => Promise<void>; ) => Promise<void>;
onSwitchToEditRange: (entryId: number, userId: number, date: string) => void; onSwitchToEditRange: (entryId: number, userId: number, date: string) => void;
/** Open the create form for a brand-new record on (userId, date). The
* `source` picks the layer the new record lands in: "entry" in normal mode,
* "override" in exception mode (a day whose shown records are overrides). */
onAddRecord: (
userId: number,
date: string,
source: "entry" | "override",
) => void;
/** Open the right editor for one of the day's existing records. */
onEditRecord: (cell: ResolvedCell, userId: number, date: string) => void;
} }
const TrashIcon = ( const TrashIcon = (
@@ -112,6 +124,7 @@ export default function PlanCellModal(props: Props) {
if (mode.kind === "view") return <ViewModal {...props} />; if (mode.kind === "view") return <ViewModal {...props} />;
if (mode.kind === "day-in-range") if (mode.kind === "day-in-range")
return <DayInRangeModal {...props} mode={mode} />; return <DayInRangeModal {...props} mode={mode} />;
if (mode.kind === "day") return <DayPanel {...props} mode={mode} />;
return <EditForm {...props} />; return <EditForm {...props} />;
} }
@@ -131,21 +144,26 @@ function EditForm(props: Props) {
const [confirmDelete, setConfirmDelete] = useState(false); const [confirmDelete, setConfirmDelete] = useState(false);
// Narrow mode to the kinds EditForm actually handles. The call site in // Narrow mode to the kinds EditForm actually handles. The call site in
// PlanCellModal only passes "create" | "edit-range" | "edit-override" but // PlanCellModal only passes "create" | "create-override" | "edit-range" |
// the parameter type is the full union, so we narrow explicitly here. // "edit-override" but the parameter type is the full union, so we narrow
// explicitly here.
if ( if (
mode.kind !== "create" && mode.kind !== "create" &&
mode.kind !== "create-override" &&
mode.kind !== "edit-range" && mode.kind !== "edit-range" &&
mode.kind !== "edit-override" mode.kind !== "edit-override"
) { ) {
return null; return null;
} }
const isOverride = mode.kind === "edit-override"; // An override is a single-day record — both editing one ("edit-override")
// and creating one ("create-override") lock the date and hide the range UI.
const isOverride =
mode.kind === "edit-override" || mode.kind === "create-override";
const activeCategories = props.categories.filter((c) => c.is_active); const activeCategories = props.categories.filter((c) => c.is_active);
const initial = (() => { const initial = (() => {
if (mode.kind === "create") { if (mode.kind === "create" || mode.kind === "create-override") {
return { return {
date_from: mode.date, date_from: mode.date,
date_to: mode.date, date_to: mode.date,
@@ -190,6 +208,8 @@ function EditForm(props: Props) {
const title = const title =
mode.kind === "create" mode.kind === "create"
? "Nový záznam plánu" ? "Nový záznam plánu"
: mode.kind === "create-override"
? "Nové přepsání dne"
: mode.kind === "edit-range" : mode.kind === "edit-range"
? "Upravit rozsah" ? "Upravit rozsah"
: "Upravit přepsání dne"; : "Upravit přepsání dne";
@@ -207,6 +227,17 @@ function EditForm(props: Props) {
category, category,
note, note,
}); });
} else if (mode.kind === "create-override") {
// An override is a single day — lock it to mode.date regardless of
// any local dateFrom/isRange state (the date field is disabled for
// overrides, but be explicit).
await onSaveOverride({
user_id: mode.userId,
shift_date: mode.date,
project_id: projectId,
category,
note,
});
} else if (mode.kind === "edit-range") { } else if (mode.kind === "edit-range") {
await onUpdateEntry(mode.entryId, { await onUpdateEntry(mode.entryId, {
date_from: dateFrom, date_from: dateFrom,
@@ -249,6 +280,10 @@ function EditForm(props: Props) {
const showRetiredCategory = const showRetiredCategory =
category && !activeCategories.some((c) => c.key === category); category && !activeCategories.some((c) => c.key === category);
// Both create flows ("create" entry, "create-override") show "Vytvořit" and
// have no Smazat button (there is no existing row to delete yet).
const isCreate = mode.kind === "create" || mode.kind === "create-override";
return ( return (
<> <>
<Modal <Modal
@@ -256,10 +291,10 @@ function EditForm(props: Props) {
title={title} title={title}
onClose={onClose} onClose={onClose}
onSubmit={handleSubmit} onSubmit={handleSubmit}
submitText={mode.kind === "create" ? "Vytvořit" : "Uložit"} submitText={isCreate ? "Vytvořit" : "Uložit"}
loading={submitting} loading={submitting}
> >
{mode.kind !== "create" && ( {!isCreate && (
<Box sx={{ mb: 2 }}> <Box sx={{ mb: 2 }}>
<Button <Button
variant="outlined" variant="outlined"
@@ -479,6 +514,7 @@ function ViewModal(props: Props) {
onClose={onClose} onClose={onClose}
onSubmit={onClose} onSubmit={onClose}
submitText="Zavřít" submitText="Zavřít"
hideCancel
> >
<Typography sx={{ mb: 1 }}> <Typography sx={{ mb: 1 }}>
<strong>Datum:</strong> {formatDate(c.shift_date)} <strong>Datum:</strong> {formatDate(c.shift_date)}
@@ -505,3 +541,117 @@ function ViewModal(props: Props) {
</Modal> </Modal>
); );
} }
const EditIcon = (
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
>
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
<path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
</svg>
);
function DayPanel(
props: Props & { mode: Extract<PlanCellModalMode, { kind: "day" }> },
) {
const { mode, onClose, onAddRecord, onEditRecord, categories } = props;
const catMap = Object.fromEntries(categories.map((x) => [x.key, x]));
const atCap = mode.cells.length >= 3;
const free = 3 - mode.cells.length;
// A day is in "exception mode" when its shown records are overrides. Cells
// are single-layer (all overrides OR all entries), so cells[0] is enough.
// "+ Přidat záznam" must add to the layer that's showing — an override here,
// otherwise resolveCell would hide a freshly-created entry behind the
// existing override after refetch.
const isOverrideMode = mode.cells[0]?.source === "override";
return (
<Modal
isOpen
title={`Plán — ${formatDate(mode.date)}`}
onClose={onClose}
onSubmit={onClose}
submitText="Zavřít"
hideCancel
>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.25, mb: 2 }}>
{mode.cells.map((c, i) => {
const color =
catMap[c.category]?.color || "var(--mui-palette-divider)";
const projectLabel = cellProjectLabel(c);
return (
<Card
key={
c.entryId != null
? c.entryId
: c.overrideId != null
? `o${c.overrideId}`
: i
}
variant="outlined"
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Box
sx={{
width: 4,
alignSelf: "stretch",
minHeight: 28,
borderRadius: 2,
bgcolor: color,
}}
/>
<Box sx={{ flex: 1, minWidth: 0 }}>
<Typography sx={{ fontWeight: 600, fontSize: "0.85rem" }}>
{planCategoryLabel(c.category, catMap)}
{projectLabel ? ` · ${projectLabel}` : ""}
</Typography>
{c.note && (
<Typography variant="body2" color="text.secondary" noWrap>
{c.note}
</Typography>
)}
</Box>
<Button
variant="outlined"
color="inherit"
startIcon={EditIcon}
onClick={() => onEditRecord(c, mode.userId, mode.date)}
>
Upravit
</Button>
</Box>
</Card>
);
})}
</Box>
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Button
variant="contained"
color="primary"
disabled={atCap}
onClick={() =>
onAddRecord(
mode.userId,
mode.date,
isOverrideMode ? "override" : "entry",
)
}
>
+ Přidat záznam
</Button>
<Typography variant="caption" color="text.secondary">
{atCap
? "Maximum 3 záznamy na den"
: `${free} ${free === 1 ? "volné místo" : "volná místa"}`}
</Typography>
</Box>
</Modal>
);
}

View File

@@ -290,6 +290,17 @@ const PlanGridRoot = styled(Box)(({ theme }) => ({
}, },
"& .plan-cell--pulse": { animation: "plan-cell-pulse 600ms ease-out" }, "& .plan-cell--pulse": { animation: "plan-cell-pulse 600ms ease-out" },
"& .plan-cell-record": {
display: "block",
width: "100%",
minWidth: 0,
},
"& .plan-cell-record + .plan-cell-record": {
marginTop: 5,
paddingTop: 5,
borderTop: `1px dashed ${theme.vars!.palette.divider}`,
},
// Chips inside a cell // Chips inside a cell
"& .plan-chip-block": { "& .plan-chip-block": {
display: "flex", display: "flex",
@@ -373,11 +384,7 @@ interface Props {
// the value so back-to-back mutations on the same cell re-trigger // the value so back-to-back mutations on the same cell re-trigger
// the animation (React needs a new key to re-mount the class). // the animation (React needs a new key to re-mount the class).
pulseKey?: { userId: number; date: string; nonce: number } | null; pulseKey?: { userId: number; date: string; nonce: number } | null;
onCellClick: ( onCellClick: (userId: number, date: string, cells: ResolvedCell[]) => void;
userId: number,
date: string,
cell: ResolvedCell | null,
) => void;
} }
// Full Czech weekday names, indexed by Date.getUTCDay() (0 = Sunday). // Full Czech weekday names, indexed by Date.getUTCDay() (0 = Sunday).
@@ -529,7 +536,8 @@ export default function PlanGrid({
</span> </span>
</td> </td>
{users.map((u) => { {users.map((u) => {
const cell = data.cells[u.id]?.[date] ?? null; const cellArr = data.cells[u.id]?.[date] ?? [];
const cell = cellArr[0] ?? null;
const past = isPastDate(date, today); const past = isPastDate(date, today);
// Past-day cells are read-only in the UI: an empty past // Past-day cells are read-only in the UI: an empty past
// cell is non-interactive (no create modal, no "+" hint), // cell is non-interactive (no create modal, no "+" hint),
@@ -571,29 +579,51 @@ export default function PlanGrid({
} as CSSProperties) } as CSSProperties)
: undefined : undefined
} }
onClick={() => onCellClick(u.id, date, cell)} onClick={() => onCellClick(u.id, date, cellArr)}
aria-label={ aria-label={
cell cell
? cellArr.length === 1
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}` ? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
: `${u.full_name}, ${date}, ${cellArr.length} záznamy`
: isLocked : isLocked
? `${u.full_name}, ${date}, ${past ? "uplynulý den" : "prázdné"} — bez záznamu` ? `${u.full_name}, ${date}, ${past ? "uplynulý den" : "prázdné"} — bez záznamu`
: `${u.full_name}, ${date}, prázdné — přidat záznam` : `${u.full_name}, ${date}, prázdné — přidat záznam`
} }
>
{cellArr.map((c, i) => (
<Box
key={
c.entryId != null
? c.entryId
: c.overrideId != null
? `o${c.overrideId}`
: i
}
className="plan-cell-record"
style={
{
"--cat-color": catMap[c.category]?.color,
} as CSSProperties
}
> >
<PlanRangeChips <PlanRangeChips
cell={cell} cell={c}
project={ project={
cell?.project_id c.project_id
? (projects.find( ? (projects.find(
(p) => p.id === cell.project_id, (p) => p.id === c.project_id,
) ?? null) ) ?? null)
: null : null
} }
readonly={!canEdit} readonly={!canEdit}
categoryLabel={ categoryLabel={planCategoryLabel(
cell ? planCategoryLabel(cell.category, catMap) : "" c.category,
} catMap,
)}
showNote={cellArr.length === 1}
/> />
</Box>
))}
</button> </button>
</td> </td>
); );

View File

@@ -6,6 +6,7 @@ interface Props {
project: Project | null; project: Project | null;
readonly?: boolean; readonly?: boolean;
categoryLabel: string; categoryLabel: string;
showNote?: boolean;
} }
export default function PlanRangeChips({ export default function PlanRangeChips({
@@ -13,6 +14,7 @@ export default function PlanRangeChips({
project, project,
readonly, readonly,
categoryLabel, categoryLabel,
showNote = true,
}: Props) { }: Props) {
void readonly; void readonly;
if (!cell) return null; if (!cell) return null;
@@ -36,7 +38,9 @@ export default function PlanRangeChips({
</span> </span>
)} )}
</div> </div>
{cell.note && <div className="plan-cell-note">{cell.note}</div>} {showNote && cell.note && (
<div className="plan-cell-note">{cell.note}</div>
)}
</div> </div>
); );
} }

View File

@@ -2,6 +2,7 @@ import { Link as RouterLink } from "react-router-dom";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import { Card, Button, EmptyState } from "../../ui"; import { Card, Button, EmptyState } from "../../ui";
import { iconBadgeSx, type IconBadgeColor } from "../../theme";
import { import {
ENTITY_TYPE_LABELS, ENTITY_TYPE_LABELS,
getActivityIconClass, getActivityIconClass,
@@ -159,7 +160,8 @@ export default function DashActivityFeed({
}} }}
> >
<Box <Box
sx={{ sx={[
{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
@@ -167,9 +169,11 @@ export default function DashActivityFeed({
height: 32, height: 32,
borderRadius: "50%", borderRadius: "50%",
flexShrink: 0, flexShrink: 0,
bgcolor: isDefault ? "grey.600" : `${badgeColor}.main`, },
color: "common.white", iconBadgeSx(
}} isDefault ? "default" : (badgeColor as IconBadgeColor),
),
]}
> >
{getActivityIcon(act.action)} {getActivityIcon(act.action)}
</Box> </Box>

View File

@@ -10,6 +10,7 @@ import DialogActions from "@mui/material/DialogActions";
import { useAuth } from "../../context/AuthContext"; import { useAuth } from "../../context/AuthContext";
import { useAlert } from "../../context/AlertContext"; import { useAlert } from "../../context/AlertContext";
import apiFetch from "../../utils/api"; import apiFetch from "../../utils/api";
import { iconBadgeSx } from "../../theme";
import { Card, Button, Modal, Field, TextField } from "../../ui"; import { Card, Button, Modal, Field, TextField } from "../../ui";
import useDialogScrollLock from "../../ui/useDialogScrollLock"; import useDialogScrollLock from "../../ui/useDialogScrollLock";
@@ -251,7 +252,8 @@ export default function DashProfile({
> >
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}> <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Box <Box
sx={{ sx={[
{
width: 36, width: 36,
height: 36, height: 36,
borderRadius: "50%", borderRadius: "50%",
@@ -259,9 +261,9 @@ export default function DashProfile({
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
flexShrink: 0, flexShrink: 0,
bgcolor: totpEnabled ? "success.main" : "grey.600", },
color: "common.white", iconBadgeSx(totpEnabled ? "success" : "default"),
}} ]}
> >
<svg <svg
width="18" width="18"
@@ -425,7 +427,8 @@ export default function DashProfile({
p: 1.5, p: 1.5,
mb: 2, mb: 2,
borderRadius: 2, borderRadius: 2,
bgcolor: "warning.light", bgcolor:
"rgba(var(--mui-palette-warning-mainChannel) / 0.12)",
color: "warning.main", color: "warning.main",
fontSize: "0.875rem", fontSize: "0.875rem",
}} }}

View File

@@ -0,0 +1,114 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Card } from "../../ui";
import { formatDate } from "../../utils/formatters";
/** One resolved plan record for today (see GET /api/admin/dashboard). */
export interface TodayPlan {
shift_date: string;
category: string;
category_label: string;
category_color: string | null;
project_id: number | null;
project_number: string | null;
project_name: string | null;
note: string;
source: "entry" | "override";
rangeFrom: string | null;
rangeTo: string | null;
}
function projectLabel(p: TodayPlan): string {
const parts = [p.project_number, p.project_name].filter(Boolean);
return parts.length > 0 ? parts.join(" — ") : "Bez projektu";
}
function PlanRow({ plan }: { plan: TodayPlan }) {
const color = plan.category_color || "var(--mui-palette-primary-main)";
return (
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
<Box
sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}
>
<Box
sx={{
display: "inline-flex",
alignItems: "center",
gap: 0.75,
px: 1.25,
py: 0.5,
borderRadius: 999,
border: 1,
borderColor: "divider",
bgcolor: `color-mix(in srgb, ${color} 12%, transparent)`,
}}
>
<Box
sx={{
width: 10,
height: 10,
borderRadius: "50%",
bgcolor: color,
flexShrink: 0,
}}
/>
<Typography
component="span"
sx={{ fontWeight: 700, fontSize: "0.8rem" }}
>
{plan.category_label}
</Typography>
</Box>
{plan.rangeFrom && plan.rangeTo && plan.rangeFrom !== plan.rangeTo && (
<Typography variant="caption" color="text.secondary">
součást rozsahu {formatDate(plan.rangeFrom)} {" "}
{formatDate(plan.rangeTo)}
</Typography>
)}
</Box>
<Typography variant="h6" sx={{ lineHeight: 1.25 }}>
{projectLabel(plan)}
</Typography>
{plan.note && (
<Typography variant="body2" color="text.secondary">
{plan.note}
</Typography>
)}
</Box>
);
}
/** "Vaše dnešní zařazení" — the logged-in user's resolved plan record(s) for
* today (up to 3). Empty array = nothing scheduled. */
export default function DashTodayPlan({ plans }: { plans: TodayPlan[] }) {
return (
<Card sx={{ mb: 3 }}>
<Typography
variant="subtitle2"
sx={{ mb: 1.5, fontWeight: 600, color: "text.secondary" }}
>
Vaše dnešní zařazení
</Typography>
{plans.length > 0 ? (
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
{plans.map((p, i) => (
<Box
key={i}
sx={{
pt: i === 0 ? 0 : 2,
borderTop: i === 0 ? 0 : 1,
borderColor: "divider",
}}
>
<PlanRow plan={p} />
</Box>
))}
</Box>
) : (
<Typography variant="body2" color="text.secondary">
Pro dnešek nemáte naplánováno.
</Typography>
)}
</Card>
);
}

View File

@@ -12,9 +12,11 @@ export type ViewMode = "week" | "month";
export type ModalMode = export type ModalMode =
| { kind: "closed" } | { kind: "closed" }
| { kind: "create"; userId: number; date: string } | { kind: "create"; userId: number; date: string }
| { kind: "create-override"; userId: number; date: string }
| { kind: "edit-range"; entryId: number; userId: number; date: string } | { kind: "edit-range"; entryId: number; userId: number; date: string }
| { kind: "edit-override"; overrideId: number; userId: number; date: string } | { kind: "edit-override"; overrideId: number; userId: number; date: string }
| { kind: "day-in-range"; userId: number; date: string; entryId: number } | { kind: "day-in-range"; userId: number; date: string; entryId: number }
| { kind: "day"; userId: number; date: string }
| { kind: "view"; userId: number; date: string }; | { kind: "view"; userId: number; date: string };
function isoDate(d: Date): string { function isoDate(d: Date): string {
@@ -150,16 +152,16 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
key: readonly unknown[], key: readonly unknown[],
userId: number, userId: number,
dates: string[], dates: string[],
mutator: (prev: ResolvedCell | null) => ResolvedCell | null, mutator: (prev: ResolvedCell[]) => ResolvedCell[],
): Record<string, ResolvedCell | null> | null { ): Record<string, ResolvedCell[]> | null {
const prev = snapshotGrid(key); const prev = snapshotGrid(key);
if (!prev) return null; if (!prev) return null;
const userPrev = prev.cells[userId] ?? {}; const userPrev = prev.cells[userId] ?? {};
const rolled: Record<string, ResolvedCell | null> = {}; const rolled: Record<string, ResolvedCell[]> = {};
const userNext: Record<string, ResolvedCell | null> = { ...userPrev }; const userNext: Record<string, ResolvedCell[]> = { ...userPrev };
for (const date of dates) { for (const date of dates) {
rolled[date] = userPrev[date] ?? null; rolled[date] = userPrev[date] ?? [];
userNext[date] = mutator(rolled[date]); userNext[date] = mutator(rolled[date]).slice(0, 3);
} }
qc.setQueryData(key, { qc.setQueryData(key, {
...prev, ...prev,
@@ -244,7 +246,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
// the ResolvedCell mirrors the request body. // the ResolvedCell mirrors the request body.
const days = eachDay(body.date_from, body.date_to); const days = eachDay(body.date_from, body.date_to);
const id = data && typeof data.id === "number" ? data.id : null; const id = data && typeof data.id === "number" ? data.id : null;
const rolled = patchCells(currentGridKey, body.user_id, days, () => const rolled = patchCells(currentGridKey, body.user_id, days, (prev) => [
makeEntryCell({ makeEntryCell({
userId: body.user_id, userId: body.user_id,
date: days[0], date: days[0],
@@ -255,7 +257,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
rangeTo: body.date_to, rangeTo: body.date_to,
entryId: id, entryId: id,
}), }),
); ...prev,
]);
// Stash the rollback on the mutation object so PlanWork can call // Stash the rollback on the mutation object so PlanWork can call
// it from onError. // it from onError.
(createEntry as any)._rolled = rolled; (createEntry as any)._rolled = rolled;
@@ -294,8 +297,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
let ownerUserId: number | null = null; let ownerUserId: number | null = null;
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const cell of Object.values(byDate)) { for (const cells of Object.values(byDate)) {
if (cell && cell.entryId === id) { if (cells.some((c) => c.entryId === id)) {
ownerUserId = Number(uidStr); ownerUserId = Number(uidStr);
break; break;
} }
@@ -304,20 +307,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
} }
} }
if (ownerUserId !== null) { if (ownerUserId !== null) {
const rolled = patchCells(currentGridKey, ownerUserId, days, (prev) => const rolled = patchCells(
makeEntryCell({ currentGridKey,
ownerUserId,
days,
(prev) => {
const existing = prev.find((c) => c.entryId === id) ?? null;
const updated = makeEntryCell({
userId: ownerUserId!, userId: ownerUserId!,
date: days[0], date: days[0],
projectId: projectId:
body.project_id === undefined body.project_id === undefined
? (prev?.project_id ?? null) ? (existing?.project_id ?? null)
: body.project_id, : body.project_id,
category: body.category ?? prev?.category ?? "work", category: body.category ?? existing?.category ?? "work",
note: body.note ?? prev?.note ?? "", note: body.note ?? existing?.note ?? "",
rangeFrom: body.date_from, rangeFrom: body.date_from,
rangeTo: body.date_to, rangeTo: body.date_to,
entryId: id, entryId: id,
}), });
return [updated, ...prev.filter((c) => c.entryId !== id)];
},
); );
(updateEntry as any)._rolled = rolled; (updateEntry as any)._rolled = rolled;
} }
@@ -338,26 +348,29 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
const grid = qc.getQueryData<GridData>(currentGridKey as any); const grid = qc.getQueryData<GridData>(currentGridKey as any);
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [, cell] of Object.entries(byDate)) { let range: { from: string; to: string } | null = null;
if ( for (const cells of Object.values(byDate)) {
cell && const hit = cells.find(
cell.entryId === vars.id && (c) => c.entryId === vars.id && c.rangeFrom && c.rangeTo,
cell.rangeFrom && );
cell.rangeTo if (hit) {
) { range = { from: hit.rangeFrom!, to: hit.rangeTo! };
const days = eachDay(cell.rangeFrom, cell.rangeTo); break;
}
}
if (range) {
const days = eachDay(range.from, range.to);
const rolled = patchCells( const rolled = patchCells(
currentGridKey, currentGridKey,
Number(uidStr), Number(uidStr),
days, days,
() => null, (prev) => prev.filter((c) => c.entryId !== vars.id),
); );
(deleteEntry as any)._rolled = rolled; (deleteEntry as any)._rolled = rolled;
break; break;
} }
} }
} }
}
invalidate(); invalidate();
}, },
}); });
@@ -375,7 +388,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
currentGridKey, currentGridKey,
vars.user_id, vars.user_id,
[vars.shift_date], [vars.shift_date],
() => (prev) => [
makeOverrideCell({ makeOverrideCell({
userId: vars.user_id, userId: vars.user_id,
date: vars.shift_date, date: vars.shift_date,
@@ -384,6 +397,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
note: vars.note, note: vars.note,
overrideId: id, overrideId: id,
}), }),
...prev,
],
); );
(createOverride as any)._rolled = rolled; (createOverride as any)._rolled = rolled;
invalidate(); invalidate();
@@ -411,21 +426,30 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
const grid = qc.getQueryData<GridData>(currentGridKey as any); const grid = qc.getQueryData<GridData>(currentGridKey as any);
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) { for (const [date, cells] of Object.entries(byDate)) {
if (cell && cell.overrideId === vars.id) { if (cells.some((c) => c.overrideId === vars.id)) {
const rolled = patchCells( const rolled = patchCells(
currentGridKey, currentGridKey,
Number(uidStr), Number(uidStr),
[date], [date],
(prev) => (prev) => {
makeOverrideCell({ const existing =
prev.find((c) => c.overrideId === vars.id) ?? null;
const updated = makeOverrideCell({
userId: Number(uidStr), userId: Number(uidStr),
date, date,
projectId: vars.body.project_id ?? prev?.project_id ?? null, projectId:
category: vars.body.category ?? prev?.category ?? "work", vars.body.project_id ?? existing?.project_id ?? null,
note: vars.body.note ?? prev?.note ?? "", category:
vars.body.category ?? existing?.category ?? "work",
note: vars.body.note ?? existing?.note ?? "",
overrideId: vars.id, overrideId: vars.id,
}), });
return [
updated,
...prev.filter((c) => c.overrideId !== vars.id),
];
},
); );
(updateOverride as any)._rolled = rolled; (updateOverride as any)._rolled = rolled;
break; break;
@@ -446,13 +470,13 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
const grid = qc.getQueryData<GridData>(currentGridKey as any); const grid = qc.getQueryData<GridData>(currentGridKey as any);
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) { for (const [date, cells] of Object.entries(byDate)) {
if (cell && cell.overrideId === vars.id) { if (cells.some((c) => c.overrideId === vars.id)) {
const rolled = patchCells( const rolled = patchCells(
currentGridKey, currentGridKey,
Number(uidStr), Number(uidStr),
[date], [date],
() => null, (prev) => prev.filter((c) => c.overrideId !== vars.id),
); );
(deleteOverride as any)._rolled = rolled; (deleteOverride as any)._rolled = rolled;
break; break;
@@ -472,15 +496,15 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
// directly without the "weak type" mismatch a `{ _rolled? }` param causes. // directly without the "weak type" mismatch a `{ _rolled? }` param causes.
function rollbackMutation(mutation: unknown, userId: number) { function rollbackMutation(mutation: unknown, userId: number) {
const stash = mutation as { const stash = mutation as {
_rolled?: Record<string, ResolvedCell | null> | null; _rolled?: Record<string, ResolvedCell[]> | null;
}; };
if (!stash._rolled) return; if (!stash._rolled) return;
const prev = qc.getQueryData<GridData>(currentGridKey as any); const prev = qc.getQueryData<GridData>(currentGridKey as any);
if (!prev) return; if (!prev) return;
const userPrev = prev.cells[userId] ?? {}; const userPrev = prev.cells[userId] ?? {};
const userNext = { ...userPrev }; const userNext = { ...userPrev };
for (const [date, cell] of Object.entries(stash._rolled)) { for (const [date, cells] of Object.entries(stash._rolled)) {
userNext[date] = cell; userNext[date] = cells;
} }
qc.setQueryData(currentGridKey, { qc.setQueryData(currentGridKey, {
...prev, ...prev,
@@ -518,10 +542,18 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
}; };
} }
export function getCells(
grid: GridData | undefined,
userId: number,
date: string,
): ResolvedCell[] {
return grid?.cells?.[userId]?.[date] ?? [];
}
export function getCell( export function getCell(
grid: GridData | undefined, grid: GridData | undefined,
userId: number, userId: number,
date: string, date: string,
): ResolvedCell | null { ): ResolvedCell | null {
return grid?.cells?.[userId]?.[date] ?? null; return getCells(grid, userId, date)[0] ?? null;
} }

View File

@@ -81,7 +81,7 @@ export interface GridData {
date_from: string; date_from: string;
date_to: string; date_to: string;
users: PlanUser[]; users: PlanUser[];
cells: Record<number, Record<string, ResolvedCell | null>>; cells: Record<number, Record<string, ResolvedCell[]>>;
} }
export const planKeys = { export const planKeys = {

View File

@@ -5,6 +5,7 @@ import Typography from "@mui/material/Typography";
import { useAuth } from "../context/AuthContext"; import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden"; import Forbidden from "../components/Forbidden";
import { companySettingsOptions } from "../lib/queries/settings"; import { companySettingsOptions } from "../lib/queries/settings";
import { iconBadgeSx } from "../theme";
import { import {
attendanceHistoryOptions, attendanceHistoryOptions,
type AttendanceRecord, type AttendanceRecord,
@@ -533,17 +534,18 @@ export default function AttendanceHistory() {
}} }}
> >
<Box <Box
sx={{ sx={[
{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
width: 44, width: 44,
height: 44, height: 44,
borderRadius: 2, borderRadius: 2,
bgcolor: "info.main",
color: "#fff",
flexShrink: 0, flexShrink: 0,
}} },
iconBadgeSx("info"),
]}
> >
<svg <svg
width="24" width="24"

View File

@@ -12,12 +12,16 @@ import { require2FAOptions } from "../lib/queries/settings";
import { getCzechDate } from "../utils/dashboardHelpers"; import { getCzechDate } from "../utils/dashboardHelpers";
import { useApiMutation } from "../lib/queries/mutations"; import { useApiMutation } from "../lib/queries/mutations";
import { Card, Button, StatusChip, PageEnter } from "../ui"; import { Card, Button, StatusChip, PageEnter } from "../ui";
import { iconBadgeSx } from "../theme";
import DashKpiCards from "../components/dashboard/DashKpiCards"; import DashKpiCards from "../components/dashboard/DashKpiCards";
import DashQuickActions from "../components/dashboard/DashQuickActions"; import DashQuickActions from "../components/dashboard/DashQuickActions";
import DashActivityFeed from "../components/dashboard/DashActivityFeed"; import DashActivityFeed from "../components/dashboard/DashActivityFeed";
import DashAttendanceToday from "../components/dashboard/DashAttendanceToday"; import DashAttendanceToday from "../components/dashboard/DashAttendanceToday";
import DashProfile from "../components/dashboard/DashProfile"; import DashProfile from "../components/dashboard/DashProfile";
import DashSessions from "../components/dashboard/DashSessions"; import DashSessions from "../components/dashboard/DashSessions";
import DashTodayPlan, {
type TodayPlan,
} from "../components/dashboard/DashTodayPlan";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
@@ -68,6 +72,7 @@ interface DashData {
pending_orders?: number; pending_orders?: number;
unpaid_invoices?: number; unpaid_invoices?: number;
pending_leave_requests?: number; pending_leave_requests?: number;
today_plan?: TodayPlan[];
[key: string]: unknown; [key: string]: unknown;
} }
@@ -253,17 +258,18 @@ export default function Dashboard() {
> >
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}> <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Box <Box
sx={{ sx={[
{
width: 40, width: 40,
height: 40, height: 40,
borderRadius: "50%", borderRadius: "50%",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
bgcolor: "error.main",
color: "#fff",
flexShrink: 0, flexShrink: 0,
}} },
iconBadgeSx("error"),
]}
> >
<svg <svg
width="20" width="20"
@@ -315,6 +321,13 @@ export default function Dashboard() {
<DashKpiCards dashData={dashData ?? null} /> <DashKpiCards dashData={dashData ?? null} />
)} )}
{/* My work plan for today — paired with the clock-in below */}
{!dashLoading &&
(hasPermission("attendance.record") ||
hasPermission("attendance.manage")) && (
<DashTodayPlan plans={dashData?.today_plan ?? []} />
)}
{/* Quick actions */} {/* Quick actions */}
{!dashLoading && ( {!dashLoading && (
<DashQuickActions <DashQuickActions

View File

@@ -64,6 +64,7 @@ import {
LoadingState, LoadingState,
PageEnter, PageEnter,
RichTextView, RichTextView,
headerActionsSx,
} from "../ui"; } from "../ui";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
@@ -1114,14 +1115,7 @@ export default function InvoiceDetail() {
/> />
</Box> </Box>
</Box> </Box>
<Box <Box sx={headerActionsSx}>
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
{hasPermission("invoices.export") && ( {hasPermission("invoices.export") && (
<Button <Button
onClick={() => handleViewPdf(invoice.language || "cs")} onClick={() => handleViewPdf(invoice.language || "cs")}
@@ -1140,7 +1134,11 @@ export default function InvoiceDetail() {
</Button> </Button>
)} )}
{hasPermission("invoices.delete") && ( {hasPermission("invoices.delete") && (
<Button onClick={() => setDeleteConfirm(true)} color="error"> <Button
onClick={() => setDeleteConfirm(true)}
variant="outlined"
color="error"
>
Smazat Smazat
</Button> </Button>
)} )}
@@ -1656,14 +1654,7 @@ export default function InvoiceDetail() {
)} )}
</Box> </Box>
</Box> </Box>
<Box <Box sx={headerActionsSx}>
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
{isEdit && invoice && hasPermission("invoices.export") && ( {isEdit && invoice && hasPermission("invoices.export") && (
<Button <Button
onClick={() => handleViewPdf(invoice.language || "cs")} onClick={() => handleViewPdf(invoice.language || "cs")}
@@ -1710,7 +1701,11 @@ export default function InvoiceDetail() {
</Button> </Button>
))} ))}
{hasPermission("invoices.delete") && ( {hasPermission("invoices.delete") && (
<Button onClick={() => setDeleteConfirm(true)} color="error"> <Button
onClick={() => setDeleteConfirm(true)}
variant="outlined"
color="error"
>
Smazat Smazat
</Button> </Button>
)} )}

View File

@@ -74,6 +74,7 @@ import {
EmptyState, EmptyState,
LoadingState, LoadingState,
PageEnter, PageEnter,
headerActionsSx,
} from "../ui"; } from "../ui";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
@@ -1118,14 +1119,7 @@ export default function OfferDetail() {
{isCompleted && <StatusChip label="Dokončeno" color="success" />} {isCompleted && <StatusChip label="Dokončeno" color="success" />}
</Box> </Box>
</Box> </Box>
<Box <Box sx={headerActionsSx}>
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
{isEdit && hasPermission("offers.export") && ( {isEdit && hasPermission("offers.export") && (
<Button <Button
onClick={handlePdf} onClick={handlePdf}
@@ -1184,7 +1178,11 @@ export default function OfferDetail() {
</Button> </Button>
)} )}
{isEdit && hasPermission("offers.delete") && ( {isEdit && hasPermission("offers.delete") && (
<Button onClick={() => setDeleteConfirm(true)} color="error"> <Button
onClick={() => setDeleteConfirm(true)}
variant="outlined"
color="error"
>
Smazat Smazat
</Button> </Button>
)} )}

View File

@@ -32,6 +32,7 @@ import {
LoadingState, LoadingState,
PageEnter, PageEnter,
RichTextView, RichTextView,
headerActionsSx,
type DataColumn, type DataColumn,
} from "../ui"; } from "../ui";
@@ -424,14 +425,7 @@ export default function OrderDetail() {
/> />
</Box> </Box>
</Box> </Box>
<Box <Box sx={headerActionsSx}>
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
{order.invoice ? ( {order.invoice ? (
<Button <Button
component={RouterLink} component={RouterLink}

View File

@@ -8,6 +8,7 @@ import { useAlert } from "../context/AlertContext";
import { import {
usePlanWork, usePlanWork,
getCell, getCell,
getCells,
type ModalMode as HookModalMode, type ModalMode as HookModalMode,
} from "../hooks/usePlanWork"; } from "../hooks/usePlanWork";
import type { PlanCellModalMode } from "../components/PlanCellModal"; import type { PlanCellModalMode } from "../components/PlanCellModal";
@@ -17,7 +18,11 @@ import PlanCategoriesModal from "../components/PlanCategoriesModal";
import Forbidden from "../components/Forbidden"; import Forbidden from "../components/Forbidden";
import { Button, Alert, LoadingState, PageEnter } from "../ui"; import { Button, Alert, LoadingState, PageEnter } from "../ui";
import { projectListOptions, type Project } from "../lib/queries/projects"; import { projectListOptions, type Project } from "../lib/queries/projects";
import { planCategoriesOptions, type PlanCategory } from "../lib/queries/plan"; import {
planCategoriesOptions,
type PlanCategory,
type ResolvedCell,
} from "../lib/queries/plan";
// plan.css is imported once globally in AdminApp.tsx — no per-page re-import. // plan.css is imported once globally in AdminApp.tsx — no per-page re-import.
const MONTH_NAMES = [ const MONTH_NAMES = [
@@ -193,84 +198,86 @@ export default function PlanWork() {
// Null when the modal is closed or in a "create" state with no source cell. // Null when the modal is closed or in a "create" state with no source cell.
const [modalCell, setModalCell] = useState<ReturnType<typeof getCell>>(null); const [modalCell, setModalCell] = useState<ReturnType<typeof getCell>>(null);
// Open the create form for a brand-new record. `source` picks the layer:
// "entry" (default) opens the normal create form; "override" opens the
// single-day create-override form. The day panel passes "override" when the
// day is in exception mode so the new record lands in the same layer that's
// showing (otherwise resolveCell would hide a new entry behind the override).
const openCreate = useCallback( const openCreate = useCallback(
(userId: number, date: string) => { (userId: number, date: string, source: "entry" | "override" = "entry") => {
setModalCell(null); setModalCell(null);
if (source === "override") {
setHookModal({ kind: "create-override", userId, date });
} else {
setHookModal({ kind: "create", userId, date }); setHookModal({ kind: "create", userId, date });
}
}, },
[setHookModal], [setHookModal],
); );
const openCell = useCallback( const openCell = useCallback(
(userId: number, date: string) => { (userId: number, date: string, cells: ResolvedCell[]) => {
const cell = getCell(grid, userId, date); const primary = cells[0] ?? null;
// Past-date guard: the server rejects create/edit on past dates with // Past-date guard: the server rejects create/edit on past dates with
// a 403 (see assertNotPastDate in plan.service.ts). To keep the user // a 403 (see assertNotPastDate in plan.service.ts). To keep the user
// out of the "click → modal opens → error toast" state, route any // out of the "click → modal opens → error toast" state, route any
// past-day click to view mode (or to no-op if there's no record). // past-day click to view mode (or to no-op if there's no record).
if (isPastDate(date, todayIsoLocal())) { if (isPastDate(date, todayIsoLocal())) {
if (!cell) { if (!primary) return;
// Empty past cell — nothing to show or edit. setModalCell(primary);
return;
}
setModalCell(cell);
setHookModal({ kind: "view", userId, date }); setHookModal({ kind: "view", userId, date });
return; return;
} }
if (!cell) { if (cells.length === 0) {
// Empty cell — open the create modal if the user can edit, otherwise
// there's nothing to view.
if (canEdit) openCreate(userId, date); if (canEdit) openCreate(userId, date);
return; return;
} }
if (!canEdit) {
setModalCell(primary);
setHookModal({ kind: "view", userId, date });
return;
}
setHookModal({ kind: "day", userId, date });
},
[canEdit, openCreate, setHookModal],
);
// Open the correct editor for one record from the day panel. This is the
// per-record version of the old openCell branch logic: a multi-day entry
// routes through the day-in-range chooser; a single-day entry → edit-range;
// an override → edit-override.
const editRecord = useCallback(
(cell: ReturnType<typeof getCell>, userId: number, date: string) => {
if (!cell) return;
setModalCell(cell); setModalCell(cell);
if (cell.source === "entry" && cell.entryId !== null) { if (cell.source === "entry" && cell.entryId !== null) {
if (canEdit) { if (cell.rangeFrom && cell.rangeTo && cell.rangeFrom !== cell.rangeTo) {
// A multi-day entry clicked on a single day → "day-in-range" so the
// user can decide between editing the range or creating a one-day
// override.
if (
cell.rangeFrom &&
cell.rangeTo &&
cell.rangeFrom !== cell.rangeTo
) {
setHookModal({ setHookModal({
kind: "day-in-range", kind: "day-in-range",
entryId: cell.entryId, entryId: cell.entryId,
userId, userId,
date, date,
}); });
return; } else {
}
setHookModal({ setHookModal({
kind: "edit-range", kind: "edit-range",
entryId: cell.entryId, entryId: cell.entryId,
userId, userId,
date, date,
}); });
return;
} }
// Read-only view
setHookModal({ kind: "view", userId, date });
return; return;
} }
if (cell.source === "override" && cell.overrideId !== null) { if (cell.source === "override" && cell.overrideId !== null) {
if (canEdit) {
setHookModal({ setHookModal({
kind: "edit-override", kind: "edit-override",
overrideId: cell.overrideId, overrideId: cell.overrideId,
userId, userId,
date, date,
}); });
} else {
setHookModal({ kind: "view", userId, date });
} }
return;
}
// No source — treat as empty
if (canEdit) openCreate(userId, date);
}, },
[grid, canEdit, openCreate, setHookModal], [setHookModal],
); );
const closeModal = useCallback(() => { const closeModal = useCallback(() => {
@@ -280,11 +287,14 @@ export default function PlanWork() {
// Switch the modal from "day-in-range" to "edit-range" mode, keeping the // Switch the modal from "day-in-range" to "edit-range" mode, keeping the
// same cell context so the EditForm opens with the range's values. // same cell context so the EditForm opens with the range's values.
// Uses `modalCell` — the record the user actually clicked in the day panel
// (captured by editRecord) — NOT getCell (which returns the PRIMARY record).
// On a day with 2+ records these differ; using the primary would edit the
// wrong range. modalCell is already set to the clicked record at this point
// (editRecord → day-in-range → here).
const switchToEditRange = useCallback( const switchToEditRange = useCallback(
(entryId: number, userId: number, date: string) => { (entryId: number, userId: number, date: string) => {
const cell = getCell(grid, userId, date); if (!modalCell) return;
if (!cell) return;
setModalCell(cell);
setHookModal({ setHookModal({
kind: "edit-range", kind: "edit-range",
entryId, entryId,
@@ -292,7 +302,7 @@ export default function PlanWork() {
date, date,
}); });
}, },
[grid, setHookModal], [modalCell, setHookModal],
); );
// --- Mutation wrappers ----------------------------------------------------- // --- Mutation wrappers -----------------------------------------------------
@@ -327,8 +337,9 @@ export default function PlanWork() {
let firstDate: string | null = null; let firstDate: string | null = null;
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) { for (const [date, cells] of Object.entries(byDate)) {
if (cell && cell.entryId === id) { const hit = cells.find((c) => c.entryId === id);
if (hit) {
userId = Number(uidStr); userId = Number(uidStr);
firstDate = body.date_from ?? date; firstDate = body.date_from ?? date;
break; break;
@@ -357,10 +368,11 @@ export default function PlanWork() {
let firstDate: string | null = null; let firstDate: string | null = null;
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) { for (const [date, cells] of Object.entries(byDate)) {
if (cell && cell.entryId === id) { const hit = cells.find((c) => c.entryId === id);
if (hit) {
userId = Number(uidStr); userId = Number(uidStr);
firstDate = cell.rangeFrom ?? date; firstDate = hit.rangeFrom ?? date;
break; break;
} }
} }
@@ -402,8 +414,9 @@ export default function PlanWork() {
let date: string | null = null; let date: string | null = null;
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [d, cell] of Object.entries(byDate)) { for (const [d, cells] of Object.entries(byDate)) {
if (cell && cell.overrideId === id) { const hit = cells.find((c) => c.overrideId === id);
if (hit) {
userId = Number(uidStr); userId = Number(uidStr);
date = d; date = d;
break; break;
@@ -431,8 +444,9 @@ export default function PlanWork() {
let date: string | null = null; let date: string | null = null;
if (grid) { if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) { for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [d, cell] of Object.entries(byDate)) { for (const [d, cells] of Object.entries(byDate)) {
if (cell && cell.overrideId === id) { const hit = cells.find((c) => c.overrideId === id);
if (hit) {
userId = Number(uidStr); userId = Number(uidStr);
date = d; date = d;
break; break;
@@ -455,11 +469,14 @@ export default function PlanWork() {
); );
// "Create override from range" — turn a multi-day entry into a one-day // "Create override from range" — turn a multi-day entry into a one-day
// override for the clicked date. We look up the cell's source entry and // override for the clicked date. We mirror the CLICKED record's fields
// create a new override mirroring its fields, locked to a single date. // (modalCell, captured by editRecord) — NOT getCell, which returns the
// PRIMARY record. On a day with 2+ records the clicked entry can differ
// from the primary; carving from the primary would copy the wrong
// project/category/note into the override.
const createOverrideFromRange = useCallback( const createOverrideFromRange = useCallback(
async (entryId: number, userId: number, date: string) => { async (entryId: number, userId: number, date: string) => {
const cell = getCell(grid, userId, date); const cell = modalCell;
if (!cell) { if (!cell) {
alert.error("Nepodařilo se najít zdrojový záznam"); alert.error("Nepodařilo se najít zdrojový záznam");
return; return;
@@ -483,7 +500,7 @@ export default function PlanWork() {
// symmetry with the modal contract. // symmetry with the modal contract.
void entryId; void entryId;
}, },
[grid, createOverride, alert, firePulse, rollbackMutation], [modalCell, createOverride, alert, firePulse, rollbackMutation],
); );
// --- Modal key for remount-on-mode-change ---------------------------------- // --- Modal key for remount-on-mode-change ----------------------------------
@@ -504,6 +521,9 @@ export default function PlanWork() {
const modalMode: PlanCellModalMode = useMemo(() => { const modalMode: PlanCellModalMode = useMemo(() => {
if (hookModal.kind === "closed") return { kind: "closed" }; if (hookModal.kind === "closed") return { kind: "closed" };
if (hookModal.kind === "create") return hookModal; if (hookModal.kind === "create") return hookModal;
// create-override carries the same userId/date payload as create and needs
// no merged cell/range — pass it straight through (EditForm handles it).
if (hookModal.kind === "create-override") return hookModal;
if (hookModal.kind === "view") { if (hookModal.kind === "view") {
if (!modalCell) return { kind: "closed" }; if (!modalCell) return { kind: "closed" };
return { return {
@@ -536,8 +556,16 @@ export default function PlanWork() {
}, },
} as PlanCellModalMode; } as PlanCellModalMode;
} }
if (hookModal.kind === "day") {
return {
kind: "day",
userId: hookModal.userId,
date: hookModal.date,
cells: getCells(grid, hookModal.userId, hookModal.date),
};
}
return { kind: "closed" }; return { kind: "closed" };
}, [hookModal, modalCell]); }, [hookModal, modalCell, grid]);
if (!canEdit && !hasPermission("attendance.record")) { if (!canEdit && !hasPermission("attendance.record")) {
// Hard block for users who have neither manage nor record permission. // Hard block for users who have neither manage nor record permission.
@@ -691,6 +719,8 @@ export default function PlanWork() {
onDeleteOverride={deleteOverrideFn} onDeleteOverride={deleteOverrideFn}
onCreateOverrideFromRange={createOverrideFromRange} onCreateOverrideFromRange={createOverrideFromRange}
onSwitchToEditRange={switchToEditRange} onSwitchToEditRange={switchToEditRange}
onAddRecord={openCreate}
onEditRecord={editRecord}
/> />
<PlanCategoriesModal <PlanCategoriesModal
isOpen={catModalOpen} isOpen={catModalOpen}

View File

@@ -29,6 +29,7 @@ import {
ConfirmDialog, ConfirmDialog,
LoadingState, LoadingState,
PageEnter, PageEnter,
headerActionsSx,
} from "../ui"; } from "../ui";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
@@ -320,14 +321,7 @@ export default function ProjectDetail() {
</Box> </Box>
</Box> </Box>
{canEdit && ( {canEdit && (
<Box <Box sx={headerActionsSx}>
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
<Button onClick={handleSave} disabled={saving}> <Button onClick={handleSave} disabled={saving}>
{saving ? "Ukládání..." : "Uložit"} {saving ? "Ukládání..." : "Uložit"}
</Button> </Button>

View File

@@ -33,6 +33,7 @@ import {
import { useApiMutation } from "../lib/queries/mutations"; import { useApiMutation } from "../lib/queries/mutations";
import apiFetch from "../utils/api"; import apiFetch from "../utils/api";
import { iconBadgeSx } from "../theme";
const API_BASE = "/api/admin"; const API_BASE = "/api/admin";
const PlusIcon = ( const PlusIcon = (
@@ -842,17 +843,18 @@ export default function Settings() {
> >
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}> <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Box <Box
sx={{ sx={[
{
width: 36, width: 36,
height: 36, height: 36,
borderRadius: "50%", borderRadius: "50%",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
bgcolor: require2FA ? "success.light" : "action.hover",
color: require2FA ? "success.main" : "text.secondary",
flexShrink: 0, flexShrink: 0,
}} },
iconBadgeSx(require2FA ? "success" : "default"),
]}
> >
<svg <svg
width="18" width="18"

View File

@@ -157,7 +157,7 @@ export default function WarehouseInventory() {
/> />
</Box> </Box>
{statusFilter && ( {statusFilter && (
<Button variant="outlined" onClick={resetFilters}> <Button variant="outlined" color="inherit" onClick={resetFilters}>
Zrušit filtry Zrušit filtry
</Button> </Button>
)} )}

View File

@@ -24,6 +24,7 @@ import {
PageHeader, PageHeader,
PageEnter, PageEnter,
ConfirmDialog, ConfirmDialog,
headerActionsSx,
type DataColumn, type DataColumn,
} from "../ui"; } from "../ui";
@@ -192,7 +193,7 @@ export default function WarehouseInventoryDetail() {
<PageHeader <PageHeader
title={s.session_number || "Inventura"} title={s.session_number || "Inventura"}
actions={ actions={
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}> <Box sx={headerActionsSx}>
<Button <Button
component={RouterLink} component={RouterLink}
to="/warehouse/inventory" to="/warehouse/inventory"

View File

@@ -24,6 +24,7 @@ import {
PageHeader, PageHeader,
ConfirmDialog, ConfirmDialog,
PageEnter, PageEnter,
headerActionsSx,
type DataColumn, type DataColumn,
} from "../ui"; } from "../ui";
@@ -233,7 +234,7 @@ export default function WarehouseIssueDetail() {
: undefined : undefined
} }
actions={ actions={
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}> <Box sx={headerActionsSx}>
<Button <Button
component={RouterLink} component={RouterLink}
to="/warehouse/issues" to="/warehouse/issues"

View File

@@ -248,7 +248,7 @@ export default function WarehouseIssues() {
/> />
</Box> </Box>
{hasActiveFilters && ( {hasActiveFilters && (
<Button variant="outlined" onClick={resetFilters}> <Button variant="outlined" color="inherit" onClick={resetFilters}>
Zrušit filtry Zrušit filtry
</Button> </Button>
)} )}

View File

@@ -29,6 +29,7 @@ import {
PageHeader, PageHeader,
ConfirmDialog, ConfirmDialog,
PageEnter, PageEnter,
headerActionsSx,
type DataColumn, type DataColumn,
} from "../ui"; } from "../ui";
@@ -233,7 +234,7 @@ export default function WarehouseItemDetail() {
// Edit / view mode action buttons // Edit / view mode action buttons
const headerActions = canManage ? ( const headerActions = canManage ? (
<Box sx={{ display: "flex", gap: 1 }}> <Box sx={headerActionsSx}>
{editing || isNew ? ( {editing || isNew ? (
<> <>
{!isNew && ( {!isNew && (
@@ -362,7 +363,7 @@ export default function WarehouseItemDetail() {
title={title} title={title}
subtitle={subtitle} subtitle={subtitle}
actions={ actions={
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}> <Box sx={headerActionsSx}>
<Button <Button
component={RouterLink} component={RouterLink}
to="/warehouse/items" to="/warehouse/items"

View File

@@ -26,6 +26,7 @@ import {
PageHeader, PageHeader,
ConfirmDialog, ConfirmDialog,
PageEnter, PageEnter,
headerActionsSx,
type DataColumn, type DataColumn,
} from "../ui"; } from "../ui";
@@ -301,7 +302,7 @@ export default function WarehouseReceiptDetail() {
title={r.receipt_number || "Nový doklad"} title={r.receipt_number || "Nový doklad"}
subtitle={r.supplier?.name} subtitle={r.supplier?.name}
actions={ actions={
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}> <Box sx={headerActionsSx}>
<Button <Button
component={RouterLink} component={RouterLink}
to="/warehouse/receipts" to="/warehouse/receipts"

View File

@@ -247,7 +247,7 @@ export default function WarehouseReceipts() {
/> />
</Box> </Box>
{hasActiveFilters && ( {hasActiveFilters && (
<Button variant="outlined" onClick={resetFilters}> <Button variant="outlined" color="inherit" onClick={resetFilters}>
Zrušit filtry Zrušit filtry
</Button> </Button>
)} )}

View File

@@ -376,7 +376,7 @@ export default function WarehouseReservations() {
</Box> </Box>
)} )}
{hasActiveFilters && ( {hasActiveFilters && (
<Button variant="outlined" onClick={resetFilters}> <Button variant="outlined" color="inherit" onClick={resetFilters}>
Zrušit filtry Zrušit filtry
</Button> </Button>
)} )}

View File

@@ -1,4 +1,4 @@
import { createTheme } from "@mui/material/styles"; import { createTheme, type Theme } from "@mui/material/styles";
const FONT_BODY = "'Plus Jakarta Sans', system-ui, sans-serif"; const FONT_BODY = "'Plus Jakarta Sans', system-ui, sans-serif";
const FONT_HEADING = "'Urbanist', sans-serif"; const FONT_HEADING = "'Urbanist', sans-serif";
@@ -7,6 +7,19 @@ const FONT_MONO = "'DM Mono', Menlo, monospace";
// Standard Material easing (matches the legacy --transition cubic-bezier). // Standard Material easing (matches the legacy --transition cubic-bezier).
const EASE = "cubic-bezier(0.4, 0, 0.2, 1)"; const EASE = "cubic-bezier(0.4, 0, 0.2, 1)";
// Dark-mode fills for FILLED colored surfaces (contained buttons, filled chips,
// StatCard badges). The palette .main stays BRIGHT in dark mode (it drives text,
// outlined buttons and row tints), but a bright fill makes WHITE text/glyphs
// illegible — so filled surfaces drop to these darker shades (≈ the light-scheme
// values) in dark mode. One rule everywhere: filled colored = white text,
// readable in both themes. Light mode needs no override (its .main is dark).
export const FILLED_DARK_BG = {
error: { bg: "#dc2626", hover: "#b91c1c" },
success: { bg: "#15803d", hover: "#166534" },
warning: { bg: "#b45309", hover: "#92400e" },
info: { bg: "#1d4ed8", hover: "#1e40af" },
} as const;
export const theme = createTheme({ export const theme = createTheme({
cssVariables: { cssVariables: {
colorSchemeSelector: "[data-theme='%s']", colorSchemeSelector: "[data-theme='%s']",
@@ -80,6 +93,47 @@ export const theme = createTheme({
}, },
"&:active": { transform: "translateY(0) scale(0.97)" }, "&:active": { transform: "translateY(0) scale(0.97)" },
}, },
// Filled colored buttons: WHITE text in BOTH themes (was per-scheme
// contrastText → near-black text on colored fills in dark mode, which
// also clashed with the always-white primary — "black text on one red
// button, white on another"). In dark mode the fill drops to a darker
// shade so white stays legible.
containedError: ({ theme }) => ({
color: "#fff",
...theme.applyStyles("dark", {
"&:not(.Mui-disabled)": {
backgroundColor: FILLED_DARK_BG.error.bg,
"&:hover": { backgroundColor: FILLED_DARK_BG.error.hover },
},
}),
}),
containedSuccess: ({ theme }) => ({
color: "#fff",
...theme.applyStyles("dark", {
"&:not(.Mui-disabled)": {
backgroundColor: FILLED_DARK_BG.success.bg,
"&:hover": { backgroundColor: FILLED_DARK_BG.success.hover },
},
}),
}),
containedWarning: ({ theme }) => ({
color: "#fff",
...theme.applyStyles("dark", {
"&:not(.Mui-disabled)": {
backgroundColor: FILLED_DARK_BG.warning.bg,
"&:hover": { backgroundColor: FILLED_DARK_BG.warning.hover },
},
}),
}),
containedInfo: ({ theme }) => ({
color: "#fff",
...theme.applyStyles("dark", {
"&:not(.Mui-disabled)": {
backgroundColor: FILLED_DARK_BG.info.bg,
"&:hover": { backgroundColor: FILLED_DARK_BG.info.hover },
},
}),
}),
}, },
}, },
MuiCard: { MuiCard: {
@@ -99,6 +153,54 @@ export const theme = createTheme({
fontWeight: 700, fontWeight: 700,
transition: `background-color 200ms ${EASE}, box-shadow 200ms ${EASE}`, transition: `background-color 200ms ${EASE}, box-shadow 200ms ${EASE}`,
}, },
// Filled colored chips follow the same rule as filled buttons: white
// label in both themes, darker fill in dark mode so white stays legible.
// (Chip has no per-color `filledX` key, so target the color class and
// scope to the filled variant.)
colorError: ({ theme }) => ({
"&.MuiChip-filled": {
color: "#fff",
...theme.applyStyles("dark", {
backgroundColor: FILLED_DARK_BG.error.bg,
"&.MuiChip-clickable:hover": {
backgroundColor: FILLED_DARK_BG.error.hover,
},
}),
},
}),
colorSuccess: ({ theme }) => ({
"&.MuiChip-filled": {
color: "#fff",
...theme.applyStyles("dark", {
backgroundColor: FILLED_DARK_BG.success.bg,
"&.MuiChip-clickable:hover": {
backgroundColor: FILLED_DARK_BG.success.hover,
},
}),
},
}),
colorWarning: ({ theme }) => ({
"&.MuiChip-filled": {
color: "#fff",
...theme.applyStyles("dark", {
backgroundColor: FILLED_DARK_BG.warning.bg,
"&.MuiChip-clickable:hover": {
backgroundColor: FILLED_DARK_BG.warning.hover,
},
}),
},
}),
colorInfo: ({ theme }) => ({
"&.MuiChip-filled": {
color: "#fff",
...theme.applyStyles("dark", {
backgroundColor: FILLED_DARK_BG.info.bg,
"&.MuiChip-clickable:hover": {
backgroundColor: FILLED_DARK_BG.info.hover,
},
}),
},
}),
}, },
}, },
MuiOutlinedInput: { MuiOutlinedInput: {
@@ -124,3 +226,29 @@ export const fonts = {
heading: FONT_HEADING, heading: FONT_HEADING,
mono: FONT_MONO, mono: FONT_MONO,
}; };
export type IconBadgeColor =
| "default"
| "primary"
| "success"
| "warning"
| "error"
| "info";
/**
* sx fragment for a solid icon-badge tile: a `<color>.main` fill with a WHITE
* glyph, darkened in dark mode (FILLED_DARK_BG) so white stays legible on the
* otherwise-bright success/warning/info/error fills. `default` = neutral grey.
* Single source of truth for every labelled icon badge — use in an sx array
* next to the tile's size/shape so they can never drift apart:
* sx={[{ width: 40, height: 40, borderRadius: 2, display: "flex", … }, iconBadgeSx(color)]}
*/
export function iconBadgeSx(color: IconBadgeColor) {
const bg = color === "default" ? "grey.600" : `${color}.main`;
const darkBg = (FILLED_DARK_BG as Record<string, { bg: string }>)[color]?.bg;
return (theme: Theme) => ({
bgcolor: bg,
color: "common.white",
...(darkBg ? theme.applyStyles("dark", { backgroundColor: darkBg }) : {}),
});
}

View File

@@ -1,6 +1,7 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import type { SxProps, Theme } from "@mui/material/styles";
export interface PageHeaderProps { export interface PageHeaderProps {
title: string; title: string;
@@ -8,6 +9,26 @@ export interface PageHeaderProps {
actions?: ReactNode; actions?: ReactNode;
} }
/**
* Shared sx for a header action-button group. On mobile each button gets its
* own full-width row (column + stretch); from `sm` up it's the usual right-
* aligned wrapping row. Use on the Box that wraps the header's action Buttons
* (page headers + detail-page headers) so the mobile layout is identical
* everywhere — no more buttons wrapping into a ragged grid on phones.
*/
export const headerActionsSx: SxProps<Theme> = {
display: "flex",
flexDirection: { xs: "column", sm: "row" },
alignItems: { xs: "stretch", sm: "center" },
justifyContent: { sm: "flex-end" },
flexWrap: { sm: "wrap" },
gap: 1,
width: { xs: "100%", sm: "auto" },
// Some detail-page headers keep a StatusChip in this same group — keep it at
// its natural size on mobile instead of stretching it into a full-width bar.
"& > .MuiChip-root": { alignSelf: { xs: "flex-start", sm: "auto" } },
};
/** /**
* Standard page header: title (+ optional subtitle) on the left, * Standard page header: title (+ optional subtitle) on the left,
* action controls on the right. No framer-motion — pages add their own entrance. * action controls on the right. No framer-motion — pages add their own entrance.
@@ -36,19 +57,7 @@ export default function PageHeader({
</Typography> </Typography>
)} )}
</Box> </Box>
{actions && ( {actions && <Box sx={headerActionsSx}>{actions}</Box>}
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
gap: 1,
flexWrap: "wrap",
}}
>
{actions}
</Box>
)}
</Box> </Box>
); );
} }

View File

@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import Card from "./Card"; import Card from "./Card";
import { iconBadgeSx } from "../theme";
export type StatCardColor = export type StatCardColor =
| "default" | "default"
@@ -30,27 +31,23 @@ export default function StatCard({
color = "default", color = "default",
footer, footer,
}: StatCardProps) { }: StatCardProps) {
// Solid tile + white glyph: high-contrast in both themes (the old light tint
// left the icon dark/low-visibility, esp. for the default variant).
const iconBg = color === "default" ? "grey.600" : `${color}.main`;
const iconColor = "common.white";
return ( return (
<Card> <Card>
<Box sx={{ display: "flex", alignItems: "flex-start", gap: 1.5 }}> <Box sx={{ display: "flex", alignItems: "flex-start", gap: 1.5 }}>
{icon && ( {icon && (
<Box <Box
sx={{ sx={[
{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
width: 40, width: 40,
height: 40, height: 40,
borderRadius: 2, borderRadius: 2,
bgcolor: iconBg,
color: iconColor,
flexShrink: 0, flexShrink: 0,
}} },
iconBadgeSx(color),
]}
> >
{icon} {icon}
</Box> </Box>

View File

@@ -18,7 +18,7 @@ export { default as Pagination } from "./Pagination";
export { default as DateField } from "./DateField"; export { default as DateField } from "./DateField";
export { default as MonthField } from "./MonthField"; export { default as MonthField } from "./MonthField";
export { default as TimeField } from "./TimeField"; export { default as TimeField } from "./TimeField";
export { default as PageHeader } from "./PageHeader"; export { default as PageHeader, headerActionsSx } from "./PageHeader";
export { default as EmptyState } from "./EmptyState"; export { default as EmptyState } from "./EmptyState";
export { default as LoadingState } from "./LoadingState"; export { default as LoadingState } from "./LoadingState";
export { default as FilterBar } from "./FilterBar"; export { default as FilterBar } from "./FilterBar";

View File

@@ -4,6 +4,7 @@ import { requireAuth } from "../../middleware/auth";
import { success } from "../../utils/response"; import { success } from "../../utils/response";
import { localTimeStr } from "../../utils/date"; import { localTimeStr } from "../../utils/date";
import { toCzk } from "../../services/exchange-rates"; import { toCzk } from "../../services/exchange-rates";
import { resolveCell } from "../../services/plan.service";
export default async function dashboardRoutes( export default async function dashboardRoutes(
fastify: FastifyInstance, fastify: FastifyInstance,
@@ -42,6 +43,30 @@ export default async function dashboardRoutes(
result.my_shift = { has_ongoing: myShift !== null }; result.my_shift = { has_ongoing: myShift !== null };
} }
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
// resolveCell returns 03 records (override-beats-range layering); an empty
// array means the user has plan access but nothing is scheduled today. Each
// record's category key is enriched with its label + colour so the widget
// needs no extra query. todayStr uses local (Europe/Prague) calendar date —
// the plan's @db.Date day.
if (has("attendance.record") || has("attendance.manage")) {
const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
const cells = await resolveCell(userId, todayStr);
result.today_plan = await Promise.all(
cells.map(async (cell) => {
const cat = await prisma.plan_categories.findUnique({
where: { key: cell.category },
select: { label: true, color: true },
});
return {
...cell,
category_label: cat?.label ?? cell.category,
category_color: cat?.color ?? null,
};
}),
);
}
// Attendance admin — only for attendance.manage // Attendance admin — only for attendance.manage
if (has("attendance.manage")) { if (has("attendance.manage")) {
const [todayAttendance, onLeaveToday, usersCount] = await Promise.all([ const [todayAttendance, onLeaveToday, usersCount] = await Promise.all([

View File

@@ -310,7 +310,9 @@ export default async function ordersRoutes(
const id = parseId(request.params.id, reply); const id = parseId(request.params.id, reply);
if (id === null) return; if (id === null) return;
const result = await deleteOrder(id); const body = request.body as Record<string, unknown> | undefined;
const deleteFiles = !!body?.delete_files;
const result = await deleteOrder(id, deleteFiles);
if ("error" in result) return error(reply, result.error!, result.status!); if ("error" in result) return error(reply, result.error!, result.status!);
await logAudit({ await logAudit({

View File

@@ -328,18 +328,6 @@ export default async function planRoutes(app: FastifyInstance) {
); );
if ("error" in result) return error(reply, result.error, result.status); if ("error" in result) return error(reply, result.error, result.status);
// If the create replaced an existing active override, log the soft-delete first.
if (result.replacedData) {
await logAudit({
request,
authData: request.authData,
action: "delete",
entityType: "work_plan_override",
entityId: (result.replacedData as any).id,
oldValues: result.replacedData as Record<string, unknown>,
description: result.replacedDescription,
});
}
await logAudit({ await logAudit({
request, request,
authData: request.authData, authData: request.authData,

View File

@@ -105,8 +105,12 @@ interface DownloadResult {
export class NasFileManager { export class NasFileManager {
private readonly basePath: string; private readonly basePath: string;
constructor() { constructor(basePath?: string) {
this.basePath = path.resolve(config.nas.path).replace(/\\/g, "/"); // basePath is an injection seam for tests; production callers pass nothing
// and get the configured NAS_PATH.
this.basePath = path
.resolve(basePath ?? config.nas.path)
.replace(/\\/g, "/");
} }
public isConfigured(): boolean { public isConfigured(): boolean {

View File

@@ -5,6 +5,11 @@ import {
releaseSharedNumber, releaseSharedNumber,
isOrderNumberTaken, isOrderNumberTaken,
} from "./numbering.service"; } from "./numbering.service";
import { NasFileManager } from "./nas-file-manager";
// Best-effort NAS folder creation for order-spawned projects, mirroring
// projects.service. Stateless singleton; reads NAS_PATH at construction.
const nasFileManager = new NasFileManager();
interface OrderItemInput { interface OrderItemInput {
description?: string | null; description?: string | null;
@@ -262,6 +267,23 @@ export async function createOrderFromQuotation(
return { order, project, orderNumber }; return { order, project, orderNumber };
}); });
// Best-effort NAS project folder, outside the transaction (mirrors
// createProject). A project created from an accepted offer must get the same
// 02_PROJEKTY/<number>_<name> folder as a manually-created one. Non-fatal: a
// NAS outage must never roll back the order.
if (result.project.project_number && nasFileManager.isConfigured()) {
const created = nasFileManager.createProjectFolder(
result.project.project_number,
result.project.name || "",
);
if (!created) {
console.error(
"[orders.service] NAS folder not created for project",
result.project.project_number,
);
}
}
return { return {
data: { data: {
order_id: result.order.id, order_id: result.order.id,
@@ -297,7 +319,7 @@ export async function createOrder(
attachmentName?: string | null, attachmentName?: string | null,
) { ) {
try { try {
return await prisma.$transaction(async (tx) => { const result = await prisma.$transaction(async (tx) => {
const orderNumber = const orderNumber =
body.order_number !== undefined && body.order_number !== null body.order_number !== undefined && body.order_number !== null
? String(body.order_number) ? String(body.order_number)
@@ -362,6 +384,8 @@ export async function createOrder(
} }
let projectId: number | undefined; let projectId: number | undefined;
let createdProject: { project_number: string; name: string } | null =
null;
// Only auto-create a project for genuine offer-less orders; share the // Only auto-create a project for genuine offer-less orders; share the
// order's number (same shared pool) exactly like the from-quotation flow. // order's number (same shared pool) exactly like the from-quotation flow.
if (body.create_project !== false && body.quotation_id == null) { if (body.create_project !== false && body.quotation_id == null) {
@@ -375,14 +399,42 @@ export async function createOrder(
}, },
}); });
projectId = project.id; projectId = project.id;
if (project.project_number) {
createdProject = {
project_number: project.project_number,
name: project.name || "",
};
}
} }
return { return {
id: order.id, id: order.id,
order_number: order.order_number, order_number: order.order_number,
project_id: projectId, project_id: projectId,
createdProject,
}; };
}); });
// Best-effort NAS project folder, outside the transaction (mirrors
// createProject). Non-fatal so a NAS outage can't roll back the order.
if (result.createdProject && nasFileManager.isConfigured()) {
const created = nasFileManager.createProjectFolder(
result.createdProject.project_number,
result.createdProject.name,
);
if (!created) {
console.error(
"[orders.service] NAS folder not created for project",
result.createdProject.project_number,
);
}
}
return {
id: result.id,
order_number: result.order_number,
project_id: result.project_id,
};
} catch (err) { } catch (err) {
if (err instanceof Error && "status" in err) { if (err instanceof Error && "status" in err) {
return { return {
@@ -536,15 +588,17 @@ export async function updateOrder(id: number, body: UpdateOrderData) {
return { data: { id, order_number: existing.order_number } }; return { data: { id, order_number: existing.order_number } };
} }
export async function deleteOrder(id: number) { export async function deleteOrder(id: number, deleteFiles = false) {
const existing = await prisma.orders.findUnique({ where: { id } }); const existing = await prisma.orders.findUnique({ where: { id } });
if (!existing) if (!existing)
return { error: "Objednávka nenalezena", status: 404 } as const; return { error: "Objednávka nenalezena", status: 404 } as const;
// Fetch linked projects before the transaction for number release later // Fetch linked projects before the transaction for number release and
// (optional) NAS folder cleanup later. project_number is needed to locate
// the folder on the share.
const linkedProjects = await prisma.projects.findMany({ const linkedProjects = await prisma.projects.findMany({
where: { order_id: id }, where: { order_id: id },
select: { id: true, created_at: true }, select: { id: true, created_at: true, project_number: true },
}); });
// Guard: projects may have non-cascaded warehouse refs (sklad_issues, // Guard: projects may have non-cascaded warehouse refs (sklad_issues,
@@ -610,6 +664,24 @@ export async function deleteOrder(id: number) {
await tx.orders.delete({ where: { id } }); await tx.orders.delete({ where: { id } });
}); });
// Best-effort NAS folder cleanup for the order's project(s), outside the
// transaction and only when the user ticked the "delete folder" checkbox in
// the order delete modal. Non-fatal: a NAS error must not undo the
// already-committed DB delete. deleteProjectFolder is idempotent — it returns
// true (no-op) when the folder is already absent.
if (deleteFiles && nasFileManager.isConfigured()) {
for (const p of linkedProjects) {
if (!p.project_number) continue;
const ok = await nasFileManager.deleteProjectFolder(p.project_number);
if (!ok) {
console.error(
"[orders.service] NAS folder not deleted for project",
p.project_number,
);
}
}
}
const year = existing.created_at const year = existing.created_at
? new Date(existing.created_at).getFullYear() ? new Date(existing.created_at).getFullYear()
: new Date().getFullYear(); : new Date().getFullYear();

View File

@@ -108,12 +108,14 @@ export interface ResolvedCell {
} }
/** /**
* Compute the effective plan cell for (userId, dateStr). * Compute the effective plan records for (userId, dateStr) as an array of
* 0MAX_RECORDS_PER_CELL records.
* *
* Precedence: override > entry > null. * Layering: if any override exists for the day, the overrides are returned
* Soft-deleted rows are ignored (is_deleted = false filter). * (newest-first) and the range entries are hidden; otherwise the range
* If multiple entries cover the same day, the latest by created_at wins * entries covering the day are returned (newest-first). Soft-deleted rows
* and a warning is logged. * are ignored (is_deleted = false filter). The result is capped at
* MAX_RECORDS_PER_CELL.
* *
* dateStr must be a YYYY-MM-DD string. The function builds a JS Date * dateStr must be a YYYY-MM-DD string. The function builds a JS Date
* from it and Prisma handles timezone conversion against the MySQL * from it and Prisma handles timezone conversion against the MySQL
@@ -122,31 +124,31 @@ export interface ResolvedCell {
export async function resolveCell( export async function resolveCell(
userId: number, userId: number,
dateStr: string, dateStr: string,
): Promise<ResolvedCell | null> { ): Promise<ResolvedCell[]> {
const date = new Date(dateStr); const date = new Date(dateStr);
// 1. Single-day override for this exact date const overrides = await prisma.work_plan_overrides.findMany({
const override = await prisma.work_plan_overrides.findFirst({
where: { user_id: userId, shift_date: date, is_deleted: false }, where: { user_id: userId, shift_date: date, is_deleted: false },
orderBy: { created_at: "desc" },
take: MAX_RECORDS_PER_CELL,
include: { projects: projectSelect }, include: { projects: projectSelect },
}); });
if (override) { if (overrides.length > 0) {
return { return overrides.map((o) => ({
source: "override", source: "override" as const,
entryId: null, entryId: null,
overrideId: override.id, overrideId: o.id,
user_id: override.user_id, user_id: o.user_id,
shift_date: dateStr, shift_date: dateStr,
project_id: override.project_id, project_id: o.project_id,
...projectFields(override.projects), ...projectFields(o.projects),
category: override.category, category: o.category,
note: override.note, note: o.note,
rangeFrom: null, rangeFrom: null,
rangeTo: null, rangeTo: null,
}; }));
} }
// 2. Range entry that covers the day
const entries = await prisma.work_plan_entries.findMany({ const entries = await prisma.work_plan_entries.findMany({
where: { where: {
user_id: userId, user_id: userId,
@@ -155,24 +157,11 @@ export async function resolveCell(
is_deleted: false, is_deleted: false,
}, },
orderBy: { created_at: "desc" }, orderBy: { created_at: "desc" },
take: MAX_RECORDS_PER_CELL,
include: { projects: projectSelect }, include: { projects: projectSelect },
}); });
return entries.map((entry) => ({
if (entries.length === 0) return null; source: "entry" as const,
if (entries.length > 1) {
// Multiple entries overlap. Use the latest. A persistent audit-log
// entry would be ideal here, but logAudit() currently requires a
// FastifyRequest — services have no request. Use console.warn as a
// stand-in until a service-context audit logger is introduced.
console.warn(
`[plan.service] multiple entries cover user ${userId} on ${dateStr}; using the latest (entry id ${entries[0].id})`,
);
}
const entry = entries[0];
return {
source: "entry",
entryId: entry.id, entryId: entry.id,
overrideId: null, overrideId: null,
user_id: entry.user_id, user_id: entry.user_id,
@@ -183,12 +172,14 @@ export async function resolveCell(
note: entry.note, note: entry.note,
rangeFrom: entry.date_from.toISOString().slice(0, 10), rangeFrom: entry.date_from.toISOString().slice(0, 10),
rangeTo: entry.date_to.toISOString().slice(0, 10), rangeTo: entry.date_to.toISOString().slice(0, 10),
}; }));
} }
/** /**
* Compute the effective plan cell for every (userId, date) in the * Compute the effective plan records for every (userId, date) in the
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell | null. * given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell[]
* (0MAX_RECORDS_PER_CELL records, same layering as resolveCell; empty
* days are []).
* *
* Implementation: load all entries and overrides for the range in two * Implementation: load all entries and overrides for the range in two
* queries, then iterate the dates and resolve each cell in O(1) per * queries, then iterate the dates and resolve each cell in O(1) per
@@ -198,7 +189,7 @@ export async function resolveGrid(
userIds: number[], userIds: number[],
dateFromStr: string, dateFromStr: string,
dateToStr: string, dateToStr: string,
): Promise<Record<number, Record<string, ResolvedCell | null>>> { ): Promise<Record<number, Record<string, ResolvedCell[]>>> {
const dateFrom = new Date(dateFromStr); const dateFrom = new Date(dateFromStr);
const dateTo = new Date(dateToStr); const dateTo = new Date(dateToStr);
@@ -219,11 +210,11 @@ export async function resolveGrid(
is_deleted: false, is_deleted: false,
shift_date: { gte: dateFrom, lte: dateTo }, shift_date: { gte: dateFrom, lte: dateTo },
}, },
orderBy: { created_at: "desc" },
include: { projects: projectSelect }, include: { projects: projectSelect },
}), }),
]); ]);
// Build a date list (inclusive)
const dates: string[] = []; const dates: string[] = [];
for ( for (
let d = new Date(dateFrom); let d = new Date(dateFrom);
@@ -233,56 +224,52 @@ export async function resolveGrid(
dates.push(d.toISOString().slice(0, 10)); dates.push(d.toISOString().slice(0, 10));
} }
const result: Record<number, Record<string, ResolvedCell | null>> = {}; const result: Record<number, Record<string, ResolvedCell[]>> = {};
for (const uid of userIds) { for (const uid of userIds) {
result[uid] = {}; result[uid] = {};
for (const dateStr of dates) { for (const dateStr of dates) {
// Override first const day = new Date(dateStr);
const override = overrides.find( const dayOverrides = overrides
.filter(
(o) => (o) =>
o.user_id === uid && o.user_id === uid &&
o.shift_date.toISOString().slice(0, 10) === dateStr, o.shift_date.toISOString().slice(0, 10) === dateStr,
); )
if (override) { .slice(0, MAX_RECORDS_PER_CELL);
result[uid][dateStr] = { if (dayOverrides.length > 0) {
source: "override", result[uid][dateStr] = dayOverrides.map((o) => ({
source: "override" as const,
entryId: null, entryId: null,
overrideId: override.id, overrideId: o.id,
user_id: override.user_id, user_id: o.user_id,
shift_date: dateStr, shift_date: dateStr,
project_id: override.project_id, project_id: o.project_id,
...projectFields(override.projects), ...projectFields(o.projects),
category: override.category, category: o.category,
note: override.note, note: o.note,
rangeFrom: null, rangeFrom: null,
rangeTo: null, rangeTo: null,
}; }));
continue; continue;
} }
// First (latest by created_at) matching entry const dayEntries = entries
const entry = entries.find( .filter(
(e) => (e) => e.user_id === uid && e.date_from <= day && e.date_to >= day,
e.user_id === uid && )
e.date_from <= new Date(dateStr) && .slice(0, MAX_RECORDS_PER_CELL);
e.date_to >= new Date(dateStr), result[uid][dateStr] = dayEntries.map((e) => ({
); source: "entry" as const,
if (entry) { entryId: e.id,
result[uid][dateStr] = {
source: "entry",
entryId: entry.id,
overrideId: null, overrideId: null,
user_id: entry.user_id, user_id: e.user_id,
shift_date: dateStr, shift_date: dateStr,
project_id: entry.project_id, project_id: e.project_id,
...projectFields(entry.projects), ...projectFields(e.projects),
category: entry.category, category: e.category,
note: entry.note, note: e.note,
rangeFrom: entry.date_from.toISOString().slice(0, 10), rangeFrom: e.date_from.toISOString().slice(0, 10),
rangeTo: entry.date_to.toISOString().slice(0, 10), rangeTo: e.date_to.toISOString().slice(0, 10),
}; }));
} else {
result[uid][dateStr] = null;
}
} }
} }
@@ -377,22 +364,14 @@ export function assertNotPastDate(
* where `oldData` is null for creates and the pre-update snapshot for * where `oldData` is null for creates and the pre-update snapshot for
* updates / deletes (so the route handler can call `logAudit` with it). * updates / deletes (so the route handler can call `logAudit` with it).
* *
* The optional `replacedData` field is set only by `createOverride` when
* an existing active override for the same (user, date) was soft-deleted
* before creating the new one. The route handler uses it to emit a
* second audit-log entry for the deletion of the replaced row.
*
* On failure returns `{ error, status }`. * On failure returns `{ error, status }`.
*/ */
export type Result<T> = export type Result<T> =
| { | {
data: T; data: T;
oldData: unknown | null; oldData: unknown | null;
replacedData?: unknown | null;
/** Human-readable Czech subject for the audit-log row. */ /** Human-readable Czech subject for the audit-log row. */
description?: string; description?: string;
/** Audit description for the `replacedData` soft-delete row, if any. */
replacedDescription?: string;
} }
| { error: string; status: number }; | { error: string; status: number };
@@ -401,6 +380,46 @@ function toDateOnly(dateStr: string): Date {
return new Date(dateStr + "T00:00:00.000Z"); return new Date(dateStr + "T00:00:00.000Z");
} }
/** Maximum number of records (entries OR overrides) shown per cell per day. */
export const MAX_RECORDS_PER_CELL = 3;
/**
* Returns { error, status } if creating an entry over [dateFromStr, dateToStr]
* would push any single day past MAX_RECORDS_PER_CELL active entries for the
* user. Names the first offending date. Counts entries regardless of whether an
* override currently hides them (simpler and predictable).
*/
async function assertEntryCapAvailable(
userId: number,
dateFromStr: string,
dateToStr: string,
): Promise<{ error: string; status: number } | null> {
const from = toDateOnly(dateFromStr);
const to = toDateOnly(dateToStr);
const existing = await prisma.work_plan_entries.findMany({
where: {
user_id: userId,
is_deleted: false,
date_from: { lte: to },
date_to: { gte: from },
},
select: { date_from: true, date_to: true },
});
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
const day = new Date(d);
const count = existing.filter(
(e) => e.date_from <= day && e.date_to >= day,
).length;
if (count >= MAX_RECORDS_PER_CELL) {
return {
error: `Na den ${day.toISOString().slice(0, 10)} jsou již ${MAX_RECORDS_PER_CELL} záznamy (maximum).`,
status: 400,
};
}
}
return null;
}
/** Create a work_plan_entries row. Past dates require force=true. */ /** Create a work_plan_entries row. Past dates require force=true. */
export async function createEntry( export async function createEntry(
input: { input: {
@@ -442,6 +461,13 @@ export async function createEntry(
const catErr = await assertActiveCategory(input.category); const catErr = await assertActiveCategory(input.category);
if (catErr) return catErr; if (catErr) return catErr;
const capErr = await assertEntryCapAvailable(
input.user_id,
input.date_from,
input.date_to,
);
if (capErr) return capErr;
const created = await prisma.work_plan_entries.create({ const created = await prisma.work_plan_entries.create({
data: { data: {
user_id: input.user_id, user_id: input.user_id,
@@ -576,13 +602,10 @@ export async function deleteEntry(
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/** /**
* Create a work_plan_overrides row. Replaces any active override for the * Create a work_plan_overrides row. Additive: stacks up to
* same (user_id, shift_date) — soft-deletes the old one. Past dates * MAX_RECORDS_PER_CELL active overrides per (user_id, shift_date); a create
* require force=true. * past the cap returns { error, status: 400 }. Past dates require force=true.
* * Returns { data, oldData: null, description }.
* Returns { data, oldData: null, replacedData: existing_or_null } so the
* route handler can emit two audit log rows: one for the soft-deleted
* previous override, and one for the new one.
*/ */
export async function createOverride( export async function createOverride(
input: { input: {
@@ -601,37 +624,22 @@ export async function createOverride(
const catErr = await assertActiveCategory(input.category); const catErr = await assertActiveCategory(input.category);
if (catErr) return catErr; if (catErr) return catErr;
// Application-level enforcement of "at most one active override per
// (user_id, shift_date)". The previous DB unique constraint was dropped
// (see migration 20260605122718_drop_wpo_unique_constraint) because
// MySQL unique indexes don't ignore soft-deleted rows, which would have
// blocked legitimate soft-delete-then-create replacement.
//
// Race protection: wrap the soft-delete + create in a transaction with
// SELECT ... FOR UPDATE on the colliding row so two concurrent requests
// can't both create active overrides for the same user-day.
const date = toDateOnly(input.shift_date); const date = toDateOnly(input.shift_date);
const { created, replaced } = await prisma.$transaction(async (tx) => { // Additive up to MAX_RECORDS_PER_CELL. (This previously REPLACED the existing
const existing = await tx.work_plan_overrides.findFirst({ // override; multi-record cells stack instead.) count+create runs in one
where: { // transaction; a concurrent create could in theory add one extra row, but
user_id: input.user_id, // resolve display caps at MAX_RECORDS_PER_CELL so that is benign.
shift_date: date, let created;
is_deleted: false, try {
}, created = await prisma.$transaction(async (tx) => {
}); const count = await tx.work_plan_overrides.count({
where: { user_id: input.user_id, shift_date: date, is_deleted: false },
if (existing) {
// Lock the row before update so a concurrent createOverride for the
// same (user, date) waits and sees the soft-deleted state.
await tx.$executeRaw`SELECT id FROM work_plan_overrides WHERE id = ${existing.id} FOR UPDATE`;
await tx.work_plan_overrides.update({
where: { id: existing.id },
data: { is_deleted: true },
}); });
if (count >= MAX_RECORDS_PER_CELL) {
throw Object.assign(new Error("cap"), { __cap: true });
} }
return tx.work_plan_overrides.create({
const createdRow = await tx.work_plan_overrides.create({
data: { data: {
user_id: input.user_id, user_id: input.user_id,
shift_date: date, shift_date: date,
@@ -641,9 +649,16 @@ export async function createOverride(
created_by: actorUserId, created_by: actorUserId,
}, },
}); });
return { created: createdRow, replaced: existing };
}); });
} catch (e) {
if (e && typeof e === "object" && "__cap" in e) {
return {
error: `Na tento den jsou již ${MAX_RECORDS_PER_CELL} záznamy (maximum).`,
status: 400,
};
}
throw e;
}
const { userName, projectName } = await resolvePlanLabels( const { userName, projectName } = await resolvePlanLabels(
created.user_id, created.user_id,
@@ -658,26 +673,7 @@ export async function createOverride(
force, force,
}); });
let replacedDescription: string | undefined; return { data: created, oldData: null, description };
if (replaced) {
const r = await resolvePlanLabels(replaced.user_id, replaced.project_id);
replacedDescription = buildPlanAuditDescription({
userName: r.userName,
categoryLabel: await resolveCategoryLabel(replaced.category),
projectName: r.projectName,
dateFrom: isoDay(replaced.shift_date),
dateTo: isoDay(replaced.shift_date),
suffix: "nahrazeno novým záznamem",
});
}
return {
data: created,
oldData: null,
replacedData: replaced,
description,
replacedDescription,
};
} }
/** Update a work_plan_overrides row. */ /** Update a work_plan_overrides row. */

View File

@@ -189,10 +189,16 @@ export async function createProject(data: CreateProjectInput) {
}); });
if (project.project_number && nasFileManager.isConfigured()) { if (project.project_number && nasFileManager.isConfigured()) {
nasFileManager.createProjectFolder( const created = nasFileManager.createProjectFolder(
project.project_number, project.project_number,
project.name || "", project.name || "",
); );
if (!created) {
console.error(
"[projects.service] NAS folder not created for project",
project.project_number,
);
}
} }
return project; return project;