Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a262508d4 | ||
|
|
23ac924472 | ||
|
|
9370423fb0 | ||
|
|
a146fc26a3 | ||
|
|
72888bf9cd | ||
|
|
80dc8a5c69 | ||
|
|
2cfa28dc47 | ||
|
|
628cd54a81 | ||
|
|
9ae69e09a3 | ||
|
|
df83eb2091 | ||
|
|
9c862034ca | ||
|
|
67d62a6df0 | ||
|
|
512f1fd92b | ||
|
|
941caf9d85 | ||
|
|
b00d18d0b3 | ||
|
|
decadd895e | ||
|
|
54f3c414f5 | ||
|
|
ca092c6166 | ||
|
|
c7f9d9aa36 |
56
CLAUDE.md
56
CLAUDE.md
@@ -14,7 +14,7 @@ Handles attendance, invoicing, leave/trips, projects, vehicles, and HR operation
|
||||
| ORM | Prisma 6.19.2 → MySQL |
|
||||
| Auth | JWT (HS256, 15 min) + TOTP 2FA (RFC 6238, otpauth) + bcryptjs |
|
||||
| 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 |
|
||||
| PDF | Puppeteer 24.x |
|
||||
| Email | nodemailer 8.x |
|
||||
@@ -35,17 +35,21 @@ src/
|
||||
├── utils/ # totp.ts, pdf.ts, email.ts, audit.ts, formatters, etc.
|
||||
├── config/ # env.ts (config singleton, Date.toJSON override)
|
||||
├── 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
|
||||
│ ├── contexts/ # AuthContext, AlertContext
|
||||
│ ├── components/ # Layout, modals, tables, editors
|
||||
│ ├── theme.ts # MUI theme — light/dark color schemes, tokens, component defaults
|
||||
│ ├── 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
|
||||
│ ├── 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
|
||||
└── __tests__/ # Vitest tests (auth, numbering)
|
||||
└── __tests__/ # Vitest tests (~14 files: auth, numbering, warehouse, plan, invoices, …)
|
||||
|
||||
prisma/
|
||||
├── schema.prisma # 32 models, MySQL, snake_case columns
|
||||
├── schema.prisma # 49 models, MySQL, snake_case columns
|
||||
└── migrations/ # Applied migrations
|
||||
|
||||
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`).
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
@@ -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`.
|
||||
- Auth state lives in `AuthContext`; use `useAuth()` hook to access it.
|
||||
- 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).
|
||||
- Custom hooks: `useApiCall`, `useListData`, `useTableSort`, `useDebounce`, `useModalLock`.
|
||||
- Styling: CSS files in `src/admin/` — no CSS-in-JS, no Tailwind. Use CSS variables.
|
||||
- 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: `usePaginatedQuery`, `useTableSort`, `useDebounce`, `useModalLock`, `useReducedMotion`.
|
||||
- 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
|
||||
|
||||
@@ -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`.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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`.
|
||||
- **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).
|
||||
**Where styling lives**
|
||||
|
||||
- **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", { … })`.
|
||||
- **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.)
|
||||
- **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.
|
||||
|
||||
**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`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
1524
docs/superpowers/plans/2026-06-08-multi-record-plan-cells.md
Normal file
1524
docs/superpowers/plans/2026-06-08-multi-record-plan-cells.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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 0–3 `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[]` (0–3) 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 2–3 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 (from–to), 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 = Mon–Fri 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
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "app-ts",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.2",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.5",
|
||||
"description": "",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
|
||||
106
src/__tests__/nas-project-folder.test.ts
Normal file
106
src/__tests__/nas-project-folder.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
@@ -58,6 +58,20 @@ beforeEach(async () => {
|
||||
await prisma.work_plan_overrides.deleteMany({
|
||||
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 () => {
|
||||
@@ -75,10 +89,9 @@ afterAll(async () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("plan.service.resolveCell", () => {
|
||||
it("returns null when nothing covers the date", async () => {
|
||||
// No entry, no override for (adminUserId, "2099-01-01")
|
||||
it("returns [] when nothing covers the date", async () => {
|
||||
const result = await resolveCell(adminUserId, "2099-01-01");
|
||||
expect(result).toBeNull();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
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");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.source).toBe("entry");
|
||||
expect(result?.note).toBe(`${N}PLC upgrade`);
|
||||
expect(result?.category).toBe("work");
|
||||
expect(result?.rangeFrom).toBe("2099-06-01");
|
||||
expect(result?.rangeTo).toBe("2099-06-10");
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].source).toBe("entry");
|
||||
expect(result[0].note).toBe(`${N}PLC upgrade`);
|
||||
expect(result[0].rangeFrom).toBe("2099-06-01");
|
||||
expect(result[0].rangeTo).toBe("2099-06-10");
|
||||
});
|
||||
|
||||
it("returns the override for that day, not the entry", async () => {
|
||||
// An entry covers 2099-06-01..2099-06-10, but an override on 2099-06-05
|
||||
// takes precedence.
|
||||
it("returns overrides (entries hidden) when an override exists", async () => {
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
@@ -124,10 +134,51 @@ describe("plan.service.resolveCell", () => {
|
||||
},
|
||||
});
|
||||
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.source).toBe("override");
|
||||
expect(result?.note).toBe(`${N}Volno po noční`);
|
||||
expect(result?.category).toBe("leave");
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].source).toBe("override");
|
||||
expect(result[0].note).toBe(`${N}Volno po noční`);
|
||||
});
|
||||
|
||||
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 () => {
|
||||
@@ -143,7 +194,7 @@ describe("plan.service.resolveCell", () => {
|
||||
},
|
||||
});
|
||||
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");
|
||||
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-04"]).toBeNull();
|
||||
expect(cells[adminUserId]["2099-06-05"]).toBeNull();
|
||||
expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-04"]).toEqual([]);
|
||||
expect(cells[adminUserId]["2099-06-05"]).toEqual([]);
|
||||
});
|
||||
|
||||
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");
|
||||
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}B`);
|
||||
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}B`);
|
||||
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);
|
||||
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", () => {
|
||||
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(
|
||||
{
|
||||
user_id: adminUserId,
|
||||
@@ -454,42 +604,45 @@ describe("plan.service.createOverride", () => {
|
||||
if ("data" in result) {
|
||||
expect(result.data.note).toBe(`${N}day off`);
|
||||
expect(result.oldData).toBeNull();
|
||||
expect(result.replacedData).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("soft-deletes the existing override and reports it in replacedData", async () => {
|
||||
await createOverride(
|
||||
it("stacks additive overrides and caps at MAX_RECORDS_PER_CELL", async () => {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const r = await createOverride(
|
||||
{
|
||||
user_id: adminUserId,
|
||||
shift_date: "2099-10-02",
|
||||
category: "leave",
|
||||
note: `${N}o${i}`,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
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,
|
||||
shift_date: "2099-10-02",
|
||||
category: "leave",
|
||||
note: `${N}first`,
|
||||
note: `${N}o3`,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
const second = await createOverride(
|
||||
{
|
||||
expect("error" in fourth).toBe(true);
|
||||
if ("error" in fourth) expect(fourth.status).toBe(400);
|
||||
// All three earlier overrides remain active — no replace happened.
|
||||
const active = await prisma.work_plan_overrides.findMany({
|
||||
where: {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2099-10-02",
|
||||
category: "sick",
|
||||
note: `${N}second`,
|
||||
shift_date: new Date("2099-10-02"),
|
||||
is_deleted: false,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
expect("data" in second).toBe(true);
|
||||
if ("data" in second) {
|
||||
expect((second.replacedData as any)?.note).toBe(`${N}first`);
|
||||
}
|
||||
|
||||
const all = await prisma.work_plan_overrides.findMany({
|
||||
where: { user_id: adminUserId, shift_date: new Date("2099-10-02") },
|
||||
});
|
||||
// The first should be soft-deleted, the second active
|
||||
expect(all.find((o) => o.note === `${N}first`)?.is_deleted).toBe(true);
|
||||
expect(all.find((o) => o.note === `${N}second`)?.is_deleted).toBe(false);
|
||||
expect(active.length).toBe(3);
|
||||
});
|
||||
|
||||
it("rejects a past date without force", async () => {
|
||||
@@ -810,7 +963,7 @@ describe("HTTP /api/admin/plan", () => {
|
||||
const body = res.json();
|
||||
expect(body.data.users).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`,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -31,6 +31,7 @@ interface Project {
|
||||
export type PlanCellModalMode =
|
||||
| { kind: "closed" }
|
||||
| { kind: "create"; userId: number; date: string }
|
||||
| { kind: "create-override"; userId: number; date: string }
|
||||
| {
|
||||
kind: "edit-range";
|
||||
entryId: number;
|
||||
@@ -64,7 +65,8 @@ export type PlanCellModalMode =
|
||||
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 {
|
||||
open: boolean;
|
||||
@@ -84,6 +86,16 @@ interface Props {
|
||||
date: string,
|
||||
) => Promise<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 = (
|
||||
@@ -112,6 +124,7 @@ export default function PlanCellModal(props: Props) {
|
||||
if (mode.kind === "view") return <ViewModal {...props} />;
|
||||
if (mode.kind === "day-in-range")
|
||||
return <DayInRangeModal {...props} mode={mode} />;
|
||||
if (mode.kind === "day") return <DayPanel {...props} mode={mode} />;
|
||||
return <EditForm {...props} />;
|
||||
}
|
||||
|
||||
@@ -131,21 +144,26 @@ function EditForm(props: Props) {
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
// Narrow mode to the kinds EditForm actually handles. The call site in
|
||||
// PlanCellModal only passes "create" | "edit-range" | "edit-override" but
|
||||
// the parameter type is the full union, so we narrow explicitly here.
|
||||
// PlanCellModal only passes "create" | "create-override" | "edit-range" |
|
||||
// "edit-override" but the parameter type is the full union, so we narrow
|
||||
// explicitly here.
|
||||
if (
|
||||
mode.kind !== "create" &&
|
||||
mode.kind !== "create-override" &&
|
||||
mode.kind !== "edit-range" &&
|
||||
mode.kind !== "edit-override"
|
||||
) {
|
||||
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 initial = (() => {
|
||||
if (mode.kind === "create") {
|
||||
if (mode.kind === "create" || mode.kind === "create-override") {
|
||||
return {
|
||||
date_from: mode.date,
|
||||
date_to: mode.date,
|
||||
@@ -190,9 +208,11 @@ function EditForm(props: Props) {
|
||||
const title =
|
||||
mode.kind === "create"
|
||||
? "Nový záznam plánu"
|
||||
: mode.kind === "edit-range"
|
||||
? "Upravit rozsah"
|
||||
: "Upravit přepsání dne";
|
||||
: mode.kind === "create-override"
|
||||
? "Nové přepsání dne"
|
||||
: mode.kind === "edit-range"
|
||||
? "Upravit rozsah"
|
||||
: "Upravit přepsání dne";
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setSubmitting(true);
|
||||
@@ -207,6 +227,17 @@ function EditForm(props: Props) {
|
||||
category,
|
||||
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") {
|
||||
await onUpdateEntry(mode.entryId, {
|
||||
date_from: dateFrom,
|
||||
@@ -249,6 +280,10 @@ function EditForm(props: Props) {
|
||||
const showRetiredCategory =
|
||||
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 (
|
||||
<>
|
||||
<Modal
|
||||
@@ -256,10 +291,10 @@ function EditForm(props: Props) {
|
||||
title={title}
|
||||
onClose={onClose}
|
||||
onSubmit={handleSubmit}
|
||||
submitText={mode.kind === "create" ? "Vytvořit" : "Uložit"}
|
||||
submitText={isCreate ? "Vytvořit" : "Uložit"}
|
||||
loading={submitting}
|
||||
>
|
||||
{mode.kind !== "create" && (
|
||||
{!isCreate && (
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
@@ -479,6 +514,7 @@ function ViewModal(props: Props) {
|
||||
onClose={onClose}
|
||||
onSubmit={onClose}
|
||||
submitText="Zavřít"
|
||||
hideCancel
|
||||
>
|
||||
<Typography sx={{ mb: 1 }}>
|
||||
<strong>Datum:</strong> {formatDate(c.shift_date)}
|
||||
@@ -505,3 +541,117 @@ function ViewModal(props: Props) {
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -290,6 +290,17 @@ const PlanGridRoot = styled(Box)(({ theme }) => ({
|
||||
},
|
||||
"& .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
|
||||
"& .plan-chip-block": {
|
||||
display: "flex",
|
||||
@@ -373,11 +384,7 @@ interface Props {
|
||||
// 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).
|
||||
pulseKey?: { userId: number; date: string; nonce: number } | null;
|
||||
onCellClick: (
|
||||
userId: number,
|
||||
date: string,
|
||||
cell: ResolvedCell | null,
|
||||
) => void;
|
||||
onCellClick: (userId: number, date: string, cells: ResolvedCell[]) => void;
|
||||
}
|
||||
|
||||
// Full Czech weekday names, indexed by Date.getUTCDay() (0 = Sunday).
|
||||
@@ -529,7 +536,8 @@ export default function PlanGrid({
|
||||
</span>
|
||||
</td>
|
||||
{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);
|
||||
// Past-day cells are read-only in the UI: an empty past
|
||||
// cell is non-interactive (no create modal, no "+" hint),
|
||||
@@ -571,29 +579,51 @@ export default function PlanGrid({
|
||||
} as CSSProperties)
|
||||
: undefined
|
||||
}
|
||||
onClick={() => onCellClick(u.id, date, cell)}
|
||||
onClick={() => onCellClick(u.id, date, cellArr)}
|
||||
aria-label={
|
||||
cell
|
||||
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
|
||||
? cellArr.length === 1
|
||||
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
|
||||
: `${u.full_name}, ${date}, ${cellArr.length} záznamy`
|
||||
: isLocked
|
||||
? `${u.full_name}, ${date}, ${past ? "uplynulý den" : "prázdné"} — bez záznamu`
|
||||
: `${u.full_name}, ${date}, prázdné — přidat záznam`
|
||||
}
|
||||
>
|
||||
<PlanRangeChips
|
||||
cell={cell}
|
||||
project={
|
||||
cell?.project_id
|
||||
? (projects.find(
|
||||
(p) => p.id === cell.project_id,
|
||||
) ?? null)
|
||||
: null
|
||||
}
|
||||
readonly={!canEdit}
|
||||
categoryLabel={
|
||||
cell ? planCategoryLabel(cell.category, catMap) : ""
|
||||
}
|
||||
/>
|
||||
{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
|
||||
cell={c}
|
||||
project={
|
||||
c.project_id
|
||||
? (projects.find(
|
||||
(p) => p.id === c.project_id,
|
||||
) ?? null)
|
||||
: null
|
||||
}
|
||||
readonly={!canEdit}
|
||||
categoryLabel={planCategoryLabel(
|
||||
c.category,
|
||||
catMap,
|
||||
)}
|
||||
showNote={cellArr.length === 1}
|
||||
/>
|
||||
</Box>
|
||||
))}
|
||||
</button>
|
||||
</td>
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ interface Props {
|
||||
project: Project | null;
|
||||
readonly?: boolean;
|
||||
categoryLabel: string;
|
||||
showNote?: boolean;
|
||||
}
|
||||
|
||||
export default function PlanRangeChips({
|
||||
@@ -13,6 +14,7 @@ export default function PlanRangeChips({
|
||||
project,
|
||||
readonly,
|
||||
categoryLabel,
|
||||
showNote = true,
|
||||
}: Props) {
|
||||
void readonly;
|
||||
if (!cell) return null;
|
||||
@@ -36,7 +38,9 @@ export default function PlanRangeChips({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{cell.note && <div className="plan-cell-note">{cell.note}</div>}
|
||||
{showNote && cell.note && (
|
||||
<div className="plan-cell-note">{cell.note}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Link as RouterLink } from "react-router-dom";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { Card, Button, EmptyState } from "../../ui";
|
||||
import { iconBadgeSx, type IconBadgeColor } from "../../theme";
|
||||
import {
|
||||
ENTITY_TYPE_LABELS,
|
||||
getActivityIconClass,
|
||||
@@ -159,17 +160,20 @@ export default function DashActivityFeed({
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 32,
|
||||
height: 32,
|
||||
borderRadius: "50%",
|
||||
flexShrink: 0,
|
||||
bgcolor: isDefault ? "grey.600" : `${badgeColor}.main`,
|
||||
color: "common.white",
|
||||
}}
|
||||
sx={[
|
||||
{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 32,
|
||||
height: 32,
|
||||
borderRadius: "50%",
|
||||
flexShrink: 0,
|
||||
},
|
||||
iconBadgeSx(
|
||||
isDefault ? "default" : (badgeColor as IconBadgeColor),
|
||||
),
|
||||
]}
|
||||
>
|
||||
{getActivityIcon(act.action)}
|
||||
</Box>
|
||||
|
||||
@@ -10,6 +10,7 @@ import DialogActions from "@mui/material/DialogActions";
|
||||
import { useAuth } from "../../context/AuthContext";
|
||||
import { useAlert } from "../../context/AlertContext";
|
||||
import apiFetch from "../../utils/api";
|
||||
import { iconBadgeSx } from "../../theme";
|
||||
import { Card, Button, Modal, Field, TextField } from "../../ui";
|
||||
import useDialogScrollLock from "../../ui/useDialogScrollLock";
|
||||
|
||||
@@ -251,17 +252,18 @@ export default function DashProfile({
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: "50%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
bgcolor: totpEnabled ? "success.main" : "grey.600",
|
||||
color: "common.white",
|
||||
}}
|
||||
sx={[
|
||||
{
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: "50%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
iconBadgeSx(totpEnabled ? "success" : "default"),
|
||||
]}
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
@@ -425,7 +427,8 @@ export default function DashProfile({
|
||||
p: 1.5,
|
||||
mb: 2,
|
||||
borderRadius: 2,
|
||||
bgcolor: "warning.light",
|
||||
bgcolor:
|
||||
"rgba(var(--mui-palette-warning-mainChannel) / 0.12)",
|
||||
color: "warning.main",
|
||||
fontSize: "0.875rem",
|
||||
}}
|
||||
|
||||
114
src/admin/components/dashboard/DashTodayPlan.tsx
Normal file
114
src/admin/components/dashboard/DashTodayPlan.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -12,9 +12,11 @@ export type ViewMode = "week" | "month";
|
||||
export type ModalMode =
|
||||
| { kind: "closed" }
|
||||
| { kind: "create"; userId: number; date: string }
|
||||
| { kind: "create-override"; userId: number; date: string }
|
||||
| { kind: "edit-range"; entryId: 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"; userId: number; date: string }
|
||||
| { kind: "view"; userId: number; date: string };
|
||||
|
||||
function isoDate(d: Date): string {
|
||||
@@ -150,16 +152,16 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
key: readonly unknown[],
|
||||
userId: number,
|
||||
dates: string[],
|
||||
mutator: (prev: ResolvedCell | null) => ResolvedCell | null,
|
||||
): Record<string, ResolvedCell | null> | null {
|
||||
mutator: (prev: ResolvedCell[]) => ResolvedCell[],
|
||||
): Record<string, ResolvedCell[]> | null {
|
||||
const prev = snapshotGrid(key);
|
||||
if (!prev) return null;
|
||||
const userPrev = prev.cells[userId] ?? {};
|
||||
const rolled: Record<string, ResolvedCell | null> = {};
|
||||
const userNext: Record<string, ResolvedCell | null> = { ...userPrev };
|
||||
const rolled: Record<string, ResolvedCell[]> = {};
|
||||
const userNext: Record<string, ResolvedCell[]> = { ...userPrev };
|
||||
for (const date of dates) {
|
||||
rolled[date] = userPrev[date] ?? null;
|
||||
userNext[date] = mutator(rolled[date]);
|
||||
rolled[date] = userPrev[date] ?? [];
|
||||
userNext[date] = mutator(rolled[date]).slice(0, 3);
|
||||
}
|
||||
qc.setQueryData(key, {
|
||||
...prev,
|
||||
@@ -244,7 +246,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// the ResolvedCell mirrors the request body.
|
||||
const days = eachDay(body.date_from, body.date_to);
|
||||
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({
|
||||
userId: body.user_id,
|
||||
date: days[0],
|
||||
@@ -255,7 +257,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
rangeTo: body.date_to,
|
||||
entryId: id,
|
||||
}),
|
||||
);
|
||||
...prev,
|
||||
]);
|
||||
// Stash the rollback on the mutation object so PlanWork can call
|
||||
// it from onError.
|
||||
(createEntry as any)._rolled = rolled;
|
||||
@@ -294,8 +297,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
let ownerUserId: number | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const cell of Object.values(byDate)) {
|
||||
if (cell && cell.entryId === id) {
|
||||
for (const cells of Object.values(byDate)) {
|
||||
if (cells.some((c) => c.entryId === id)) {
|
||||
ownerUserId = Number(uidStr);
|
||||
break;
|
||||
}
|
||||
@@ -304,20 +307,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
}
|
||||
}
|
||||
if (ownerUserId !== null) {
|
||||
const rolled = patchCells(currentGridKey, ownerUserId, days, (prev) =>
|
||||
makeEntryCell({
|
||||
userId: ownerUserId!,
|
||||
date: days[0],
|
||||
projectId:
|
||||
body.project_id === undefined
|
||||
? (prev?.project_id ?? null)
|
||||
: body.project_id,
|
||||
category: body.category ?? prev?.category ?? "work",
|
||||
note: body.note ?? prev?.note ?? "",
|
||||
rangeFrom: body.date_from,
|
||||
rangeTo: body.date_to,
|
||||
entryId: id,
|
||||
}),
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
ownerUserId,
|
||||
days,
|
||||
(prev) => {
|
||||
const existing = prev.find((c) => c.entryId === id) ?? null;
|
||||
const updated = makeEntryCell({
|
||||
userId: ownerUserId!,
|
||||
date: days[0],
|
||||
projectId:
|
||||
body.project_id === undefined
|
||||
? (existing?.project_id ?? null)
|
||||
: body.project_id,
|
||||
category: body.category ?? existing?.category ?? "work",
|
||||
note: body.note ?? existing?.note ?? "",
|
||||
rangeFrom: body.date_from,
|
||||
rangeTo: body.date_to,
|
||||
entryId: id,
|
||||
});
|
||||
return [updated, ...prev.filter((c) => c.entryId !== id)];
|
||||
},
|
||||
);
|
||||
(updateEntry as any)._rolled = rolled;
|
||||
}
|
||||
@@ -338,24 +348,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [, cell] of Object.entries(byDate)) {
|
||||
if (
|
||||
cell &&
|
||||
cell.entryId === vars.id &&
|
||||
cell.rangeFrom &&
|
||||
cell.rangeTo
|
||||
) {
|
||||
const days = eachDay(cell.rangeFrom, cell.rangeTo);
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
days,
|
||||
() => null,
|
||||
);
|
||||
(deleteEntry as any)._rolled = rolled;
|
||||
let range: { from: string; to: string } | null = null;
|
||||
for (const cells of Object.values(byDate)) {
|
||||
const hit = cells.find(
|
||||
(c) => c.entryId === vars.id && c.rangeFrom && c.rangeTo,
|
||||
);
|
||||
if (hit) {
|
||||
range = { from: hit.rangeFrom!, to: hit.rangeTo! };
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (range) {
|
||||
const days = eachDay(range.from, range.to);
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
days,
|
||||
(prev) => prev.filter((c) => c.entryId !== vars.id),
|
||||
);
|
||||
(deleteEntry as any)._rolled = rolled;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
invalidate();
|
||||
@@ -375,7 +388,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
currentGridKey,
|
||||
vars.user_id,
|
||||
[vars.shift_date],
|
||||
() =>
|
||||
(prev) => [
|
||||
makeOverrideCell({
|
||||
userId: vars.user_id,
|
||||
date: vars.shift_date,
|
||||
@@ -384,6 +397,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
note: vars.note,
|
||||
overrideId: id,
|
||||
}),
|
||||
...prev,
|
||||
],
|
||||
);
|
||||
(createOverride as any)._rolled = rolled;
|
||||
invalidate();
|
||||
@@ -411,21 +426,30 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === vars.id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
if (cells.some((c) => c.overrideId === vars.id)) {
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
[date],
|
||||
(prev) =>
|
||||
makeOverrideCell({
|
||||
(prev) => {
|
||||
const existing =
|
||||
prev.find((c) => c.overrideId === vars.id) ?? null;
|
||||
const updated = makeOverrideCell({
|
||||
userId: Number(uidStr),
|
||||
date,
|
||||
projectId: vars.body.project_id ?? prev?.project_id ?? null,
|
||||
category: vars.body.category ?? prev?.category ?? "work",
|
||||
note: vars.body.note ?? prev?.note ?? "",
|
||||
projectId:
|
||||
vars.body.project_id ?? existing?.project_id ?? null,
|
||||
category:
|
||||
vars.body.category ?? existing?.category ?? "work",
|
||||
note: vars.body.note ?? existing?.note ?? "",
|
||||
overrideId: vars.id,
|
||||
}),
|
||||
});
|
||||
return [
|
||||
updated,
|
||||
...prev.filter((c) => c.overrideId !== vars.id),
|
||||
];
|
||||
},
|
||||
);
|
||||
(updateOverride as any)._rolled = rolled;
|
||||
break;
|
||||
@@ -446,13 +470,13 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === vars.id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
if (cells.some((c) => c.overrideId === vars.id)) {
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
[date],
|
||||
() => null,
|
||||
(prev) => prev.filter((c) => c.overrideId !== vars.id),
|
||||
);
|
||||
(deleteOverride as any)._rolled = rolled;
|
||||
break;
|
||||
@@ -472,15 +496,15 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// directly without the "weak type" mismatch a `{ _rolled? }` param causes.
|
||||
function rollbackMutation(mutation: unknown, userId: number) {
|
||||
const stash = mutation as {
|
||||
_rolled?: Record<string, ResolvedCell | null> | null;
|
||||
_rolled?: Record<string, ResolvedCell[]> | null;
|
||||
};
|
||||
if (!stash._rolled) return;
|
||||
const prev = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (!prev) return;
|
||||
const userPrev = prev.cells[userId] ?? {};
|
||||
const userNext = { ...userPrev };
|
||||
for (const [date, cell] of Object.entries(stash._rolled)) {
|
||||
userNext[date] = cell;
|
||||
for (const [date, cells] of Object.entries(stash._rolled)) {
|
||||
userNext[date] = cells;
|
||||
}
|
||||
qc.setQueryData(currentGridKey, {
|
||||
...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(
|
||||
grid: GridData | undefined,
|
||||
userId: number,
|
||||
date: string,
|
||||
): ResolvedCell | null {
|
||||
return grid?.cells?.[userId]?.[date] ?? null;
|
||||
return getCells(grid, userId, date)[0] ?? null;
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ export interface GridData {
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
users: PlanUser[];
|
||||
cells: Record<number, Record<string, ResolvedCell | null>>;
|
||||
cells: Record<number, Record<string, ResolvedCell[]>>;
|
||||
}
|
||||
|
||||
export const planKeys = {
|
||||
|
||||
@@ -5,6 +5,7 @@ import Typography from "@mui/material/Typography";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { companySettingsOptions } from "../lib/queries/settings";
|
||||
import { iconBadgeSx } from "../theme";
|
||||
import {
|
||||
attendanceHistoryOptions,
|
||||
type AttendanceRecord,
|
||||
@@ -533,17 +534,18 @@ export default function AttendanceHistory() {
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 2,
|
||||
bgcolor: "info.main",
|
||||
color: "#fff",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
sx={[
|
||||
{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 2,
|
||||
flexShrink: 0,
|
||||
},
|
||||
iconBadgeSx("info"),
|
||||
]}
|
||||
>
|
||||
<svg
|
||||
width="24"
|
||||
|
||||
@@ -12,12 +12,16 @@ import { require2FAOptions } from "../lib/queries/settings";
|
||||
import { getCzechDate } from "../utils/dashboardHelpers";
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import { Card, Button, StatusChip, PageEnter } from "../ui";
|
||||
import { iconBadgeSx } from "../theme";
|
||||
import DashKpiCards from "../components/dashboard/DashKpiCards";
|
||||
import DashQuickActions from "../components/dashboard/DashQuickActions";
|
||||
import DashActivityFeed from "../components/dashboard/DashActivityFeed";
|
||||
import DashAttendanceToday from "../components/dashboard/DashAttendanceToday";
|
||||
import DashProfile from "../components/dashboard/DashProfile";
|
||||
import DashSessions from "../components/dashboard/DashSessions";
|
||||
import DashTodayPlan, {
|
||||
type TodayPlan,
|
||||
} from "../components/dashboard/DashTodayPlan";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -68,6 +72,7 @@ interface DashData {
|
||||
pending_orders?: number;
|
||||
unpaid_invoices?: number;
|
||||
pending_leave_requests?: number;
|
||||
today_plan?: TodayPlan[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -253,17 +258,18 @@ export default function Dashboard() {
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: "50%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
bgcolor: "error.main",
|
||||
color: "#fff",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
sx={[
|
||||
{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: "50%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
iconBadgeSx("error"),
|
||||
]}
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
@@ -315,6 +321,13 @@ export default function Dashboard() {
|
||||
<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 */}
|
||||
{!dashLoading && (
|
||||
<DashQuickActions
|
||||
|
||||
@@ -64,6 +64,7 @@ import {
|
||||
LoadingState,
|
||||
PageEnter,
|
||||
RichTextView,
|
||||
headerActionsSx,
|
||||
} from "../ui";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
@@ -1114,14 +1115,7 @@ export default function InvoiceDetail() {
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Box sx={headerActionsSx}>
|
||||
{hasPermission("invoices.export") && (
|
||||
<Button
|
||||
onClick={() => handleViewPdf(invoice.language || "cs")}
|
||||
@@ -1140,7 +1134,11 @@ export default function InvoiceDetail() {
|
||||
</Button>
|
||||
)}
|
||||
{hasPermission("invoices.delete") && (
|
||||
<Button onClick={() => setDeleteConfirm(true)} color="error">
|
||||
<Button
|
||||
onClick={() => setDeleteConfirm(true)}
|
||||
variant="outlined"
|
||||
color="error"
|
||||
>
|
||||
Smazat
|
||||
</Button>
|
||||
)}
|
||||
@@ -1656,14 +1654,7 @@ export default function InvoiceDetail() {
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Box sx={headerActionsSx}>
|
||||
{isEdit && invoice && hasPermission("invoices.export") && (
|
||||
<Button
|
||||
onClick={() => handleViewPdf(invoice.language || "cs")}
|
||||
@@ -1710,7 +1701,11 @@ export default function InvoiceDetail() {
|
||||
</Button>
|
||||
))}
|
||||
{hasPermission("invoices.delete") && (
|
||||
<Button onClick={() => setDeleteConfirm(true)} color="error">
|
||||
<Button
|
||||
onClick={() => setDeleteConfirm(true)}
|
||||
variant="outlined"
|
||||
color="error"
|
||||
>
|
||||
Smazat
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -74,6 +74,7 @@ import {
|
||||
EmptyState,
|
||||
LoadingState,
|
||||
PageEnter,
|
||||
headerActionsSx,
|
||||
} from "../ui";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
@@ -1118,14 +1119,7 @@ export default function OfferDetail() {
|
||||
{isCompleted && <StatusChip label="Dokončeno" color="success" />}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Box sx={headerActionsSx}>
|
||||
{isEdit && hasPermission("offers.export") && (
|
||||
<Button
|
||||
onClick={handlePdf}
|
||||
@@ -1184,7 +1178,11 @@ export default function OfferDetail() {
|
||||
</Button>
|
||||
)}
|
||||
{isEdit && hasPermission("offers.delete") && (
|
||||
<Button onClick={() => setDeleteConfirm(true)} color="error">
|
||||
<Button
|
||||
onClick={() => setDeleteConfirm(true)}
|
||||
variant="outlined"
|
||||
color="error"
|
||||
>
|
||||
Smazat
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
LoadingState,
|
||||
PageEnter,
|
||||
RichTextView,
|
||||
headerActionsSx,
|
||||
type DataColumn,
|
||||
} from "../ui";
|
||||
|
||||
@@ -424,14 +425,7 @@ export default function OrderDetail() {
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Box sx={headerActionsSx}>
|
||||
{order.invoice ? (
|
||||
<Button
|
||||
component={RouterLink}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useAlert } from "../context/AlertContext";
|
||||
import {
|
||||
usePlanWork,
|
||||
getCell,
|
||||
getCells,
|
||||
type ModalMode as HookModalMode,
|
||||
} from "../hooks/usePlanWork";
|
||||
import type { PlanCellModalMode } from "../components/PlanCellModal";
|
||||
@@ -17,7 +18,11 @@ import PlanCategoriesModal from "../components/PlanCategoriesModal";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { Button, Alert, LoadingState, PageEnter } from "../ui";
|
||||
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.
|
||||
|
||||
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.
|
||||
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(
|
||||
(userId: number, date: string) => {
|
||||
(userId: number, date: string, source: "entry" | "override" = "entry") => {
|
||||
setModalCell(null);
|
||||
setHookModal({ kind: "create", userId, date });
|
||||
if (source === "override") {
|
||||
setHookModal({ kind: "create-override", userId, date });
|
||||
} else {
|
||||
setHookModal({ kind: "create", userId, date });
|
||||
}
|
||||
},
|
||||
[setHookModal],
|
||||
);
|
||||
|
||||
const openCell = useCallback(
|
||||
(userId: number, date: string) => {
|
||||
const cell = getCell(grid, userId, date);
|
||||
(userId: number, date: string, cells: ResolvedCell[]) => {
|
||||
const primary = cells[0] ?? null;
|
||||
// Past-date guard: the server rejects create/edit on past dates with
|
||||
// a 403 (see assertNotPastDate in plan.service.ts). To keep the user
|
||||
// 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).
|
||||
if (isPastDate(date, todayIsoLocal())) {
|
||||
if (!cell) {
|
||||
// Empty past cell — nothing to show or edit.
|
||||
return;
|
||||
}
|
||||
setModalCell(cell);
|
||||
if (!primary) return;
|
||||
setModalCell(primary);
|
||||
setHookModal({ kind: "view", userId, date });
|
||||
return;
|
||||
}
|
||||
if (!cell) {
|
||||
// Empty cell — open the create modal if the user can edit, otherwise
|
||||
// there's nothing to view.
|
||||
if (cells.length === 0) {
|
||||
if (canEdit) openCreate(userId, date);
|
||||
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);
|
||||
if (cell.source === "entry" && cell.entryId !== null) {
|
||||
if (canEdit) {
|
||||
// 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({
|
||||
kind: "day-in-range",
|
||||
entryId: cell.entryId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (cell.rangeFrom && cell.rangeTo && cell.rangeFrom !== cell.rangeTo) {
|
||||
setHookModal({
|
||||
kind: "day-in-range",
|
||||
entryId: cell.entryId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
} else {
|
||||
setHookModal({
|
||||
kind: "edit-range",
|
||||
entryId: cell.entryId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Read-only view
|
||||
setHookModal({ kind: "view", userId, date });
|
||||
return;
|
||||
}
|
||||
if (cell.source === "override" && cell.overrideId !== null) {
|
||||
if (canEdit) {
|
||||
setHookModal({
|
||||
kind: "edit-override",
|
||||
overrideId: cell.overrideId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
} else {
|
||||
setHookModal({ kind: "view", userId, date });
|
||||
}
|
||||
return;
|
||||
setHookModal({
|
||||
kind: "edit-override",
|
||||
overrideId: cell.overrideId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
}
|
||||
// No source — treat as empty
|
||||
if (canEdit) openCreate(userId, date);
|
||||
},
|
||||
[grid, canEdit, openCreate, setHookModal],
|
||||
[setHookModal],
|
||||
);
|
||||
|
||||
const closeModal = useCallback(() => {
|
||||
@@ -280,11 +287,14 @@ export default function PlanWork() {
|
||||
|
||||
// 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.
|
||||
// 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(
|
||||
(entryId: number, userId: number, date: string) => {
|
||||
const cell = getCell(grid, userId, date);
|
||||
if (!cell) return;
|
||||
setModalCell(cell);
|
||||
if (!modalCell) return;
|
||||
setHookModal({
|
||||
kind: "edit-range",
|
||||
entryId,
|
||||
@@ -292,7 +302,7 @@ export default function PlanWork() {
|
||||
date,
|
||||
});
|
||||
},
|
||||
[grid, setHookModal],
|
||||
[modalCell, setHookModal],
|
||||
);
|
||||
|
||||
// --- Mutation wrappers -----------------------------------------------------
|
||||
@@ -327,8 +337,9 @@ export default function PlanWork() {
|
||||
let firstDate: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.entryId === id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.entryId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
firstDate = body.date_from ?? date;
|
||||
break;
|
||||
@@ -357,10 +368,11 @@ export default function PlanWork() {
|
||||
let firstDate: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.entryId === id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.entryId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
firstDate = cell.rangeFrom ?? date;
|
||||
firstDate = hit.rangeFrom ?? date;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -402,8 +414,9 @@ export default function PlanWork() {
|
||||
let date: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [d, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === id) {
|
||||
for (const [d, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.overrideId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
date = d;
|
||||
break;
|
||||
@@ -431,8 +444,9 @@ export default function PlanWork() {
|
||||
let date: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [d, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === id) {
|
||||
for (const [d, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.overrideId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
date = d;
|
||||
break;
|
||||
@@ -455,11 +469,14 @@ export default function PlanWork() {
|
||||
);
|
||||
|
||||
// "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
|
||||
// create a new override mirroring its fields, locked to a single date.
|
||||
// override for the clicked date. We mirror the CLICKED record's fields
|
||||
// (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(
|
||||
async (entryId: number, userId: number, date: string) => {
|
||||
const cell = getCell(grid, userId, date);
|
||||
const cell = modalCell;
|
||||
if (!cell) {
|
||||
alert.error("Nepodařilo se najít zdrojový záznam");
|
||||
return;
|
||||
@@ -483,7 +500,7 @@ export default function PlanWork() {
|
||||
// symmetry with the modal contract.
|
||||
void entryId;
|
||||
},
|
||||
[grid, createOverride, alert, firePulse, rollbackMutation],
|
||||
[modalCell, createOverride, alert, firePulse, rollbackMutation],
|
||||
);
|
||||
|
||||
// --- Modal key for remount-on-mode-change ----------------------------------
|
||||
@@ -504,6 +521,9 @@ export default function PlanWork() {
|
||||
const modalMode: PlanCellModalMode = useMemo(() => {
|
||||
if (hookModal.kind === "closed") return { kind: "closed" };
|
||||
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 (!modalCell) return { kind: "closed" };
|
||||
return {
|
||||
@@ -536,8 +556,16 @@ export default function PlanWork() {
|
||||
},
|
||||
} 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" };
|
||||
}, [hookModal, modalCell]);
|
||||
}, [hookModal, modalCell, grid]);
|
||||
|
||||
if (!canEdit && !hasPermission("attendance.record")) {
|
||||
// Hard block for users who have neither manage nor record permission.
|
||||
@@ -691,6 +719,8 @@ export default function PlanWork() {
|
||||
onDeleteOverride={deleteOverrideFn}
|
||||
onCreateOverrideFromRange={createOverrideFromRange}
|
||||
onSwitchToEditRange={switchToEditRange}
|
||||
onAddRecord={openCreate}
|
||||
onEditRecord={editRecord}
|
||||
/>
|
||||
<PlanCategoriesModal
|
||||
isOpen={catModalOpen}
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
ConfirmDialog,
|
||||
LoadingState,
|
||||
PageEnter,
|
||||
headerActionsSx,
|
||||
} from "../ui";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
@@ -320,14 +321,7 @@ export default function ProjectDetail() {
|
||||
</Box>
|
||||
</Box>
|
||||
{canEdit && (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Box sx={headerActionsSx}>
|
||||
<Button onClick={handleSave} disabled={saving}>
|
||||
{saving ? "Ukládání..." : "Uložit"}
|
||||
</Button>
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import apiFetch from "../utils/api";
|
||||
import { iconBadgeSx } from "../theme";
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
const PlusIcon = (
|
||||
@@ -842,17 +843,18 @@ export default function Settings() {
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: "50%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
bgcolor: require2FA ? "success.light" : "action.hover",
|
||||
color: require2FA ? "success.main" : "text.secondary",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
sx={[
|
||||
{
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: "50%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
iconBadgeSx(require2FA ? "success" : "default"),
|
||||
]}
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
|
||||
@@ -157,7 +157,7 @@ export default function WarehouseInventory() {
|
||||
/>
|
||||
</Box>
|
||||
{statusFilter && (
|
||||
<Button variant="outlined" onClick={resetFilters}>
|
||||
<Button variant="outlined" color="inherit" onClick={resetFilters}>
|
||||
Zrušit filtry
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
PageHeader,
|
||||
PageEnter,
|
||||
ConfirmDialog,
|
||||
headerActionsSx,
|
||||
type DataColumn,
|
||||
} from "../ui";
|
||||
|
||||
@@ -192,7 +193,7 @@ export default function WarehouseInventoryDetail() {
|
||||
<PageHeader
|
||||
title={s.session_number || "Inventura"}
|
||||
actions={
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<Box sx={headerActionsSx}>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to="/warehouse/inventory"
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
PageHeader,
|
||||
ConfirmDialog,
|
||||
PageEnter,
|
||||
headerActionsSx,
|
||||
type DataColumn,
|
||||
} from "../ui";
|
||||
|
||||
@@ -233,7 +234,7 @@ export default function WarehouseIssueDetail() {
|
||||
: undefined
|
||||
}
|
||||
actions={
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<Box sx={headerActionsSx}>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to="/warehouse/issues"
|
||||
|
||||
@@ -248,7 +248,7 @@ export default function WarehouseIssues() {
|
||||
/>
|
||||
</Box>
|
||||
{hasActiveFilters && (
|
||||
<Button variant="outlined" onClick={resetFilters}>
|
||||
<Button variant="outlined" color="inherit" onClick={resetFilters}>
|
||||
Zrušit filtry
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
PageHeader,
|
||||
ConfirmDialog,
|
||||
PageEnter,
|
||||
headerActionsSx,
|
||||
type DataColumn,
|
||||
} from "../ui";
|
||||
|
||||
@@ -233,7 +234,7 @@ export default function WarehouseItemDetail() {
|
||||
|
||||
// Edit / view mode action buttons
|
||||
const headerActions = canManage ? (
|
||||
<Box sx={{ display: "flex", gap: 1 }}>
|
||||
<Box sx={headerActionsSx}>
|
||||
{editing || isNew ? (
|
||||
<>
|
||||
{!isNew && (
|
||||
@@ -362,7 +363,7 @@ export default function WarehouseItemDetail() {
|
||||
title={title}
|
||||
subtitle={subtitle}
|
||||
actions={
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<Box sx={headerActionsSx}>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to="/warehouse/items"
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
PageHeader,
|
||||
ConfirmDialog,
|
||||
PageEnter,
|
||||
headerActionsSx,
|
||||
type DataColumn,
|
||||
} from "../ui";
|
||||
|
||||
@@ -301,7 +302,7 @@ export default function WarehouseReceiptDetail() {
|
||||
title={r.receipt_number || "Nový doklad"}
|
||||
subtitle={r.supplier?.name}
|
||||
actions={
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<Box sx={headerActionsSx}>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to="/warehouse/receipts"
|
||||
|
||||
@@ -247,7 +247,7 @@ export default function WarehouseReceipts() {
|
||||
/>
|
||||
</Box>
|
||||
{hasActiveFilters && (
|
||||
<Button variant="outlined" onClick={resetFilters}>
|
||||
<Button variant="outlined" color="inherit" onClick={resetFilters}>
|
||||
Zrušit filtry
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -376,7 +376,7 @@ export default function WarehouseReservations() {
|
||||
</Box>
|
||||
)}
|
||||
{hasActiveFilters && (
|
||||
<Button variant="outlined" onClick={resetFilters}>
|
||||
<Button variant="outlined" color="inherit" onClick={resetFilters}>
|
||||
Zrušit filtry
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -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_HEADING = "'Urbanist', sans-serif";
|
||||
@@ -7,6 +7,19 @@ const FONT_MONO = "'DM Mono', Menlo, monospace";
|
||||
// Standard Material easing (matches the legacy --transition cubic-bezier).
|
||||
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({
|
||||
cssVariables: {
|
||||
colorSchemeSelector: "[data-theme='%s']",
|
||||
@@ -80,6 +93,47 @@ export const theme = createTheme({
|
||||
},
|
||||
"&: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: {
|
||||
@@ -99,6 +153,54 @@ export const theme = createTheme({
|
||||
fontWeight: 700,
|
||||
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: {
|
||||
@@ -124,3 +226,29 @@ export const fonts = {
|
||||
heading: FONT_HEADING,
|
||||
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 }) : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import type { SxProps, Theme } from "@mui/material/styles";
|
||||
|
||||
export interface PageHeaderProps {
|
||||
title: string;
|
||||
@@ -8,6 +9,26 @@ export interface PageHeaderProps {
|
||||
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,
|
||||
* action controls on the right. No framer-motion — pages add their own entrance.
|
||||
@@ -36,19 +57,7 @@ export default function PageHeader({
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
{actions && (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
gap: 1,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
{actions}
|
||||
</Box>
|
||||
)}
|
||||
{actions && <Box sx={headerActionsSx}>{actions}</Box>}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Card from "./Card";
|
||||
import { iconBadgeSx } from "../theme";
|
||||
|
||||
export type StatCardColor =
|
||||
| "default"
|
||||
@@ -30,27 +31,23 @@ export default function StatCard({
|
||||
color = "default",
|
||||
footer,
|
||||
}: 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 (
|
||||
<Card>
|
||||
<Box sx={{ display: "flex", alignItems: "flex-start", gap: 1.5 }}>
|
||||
{icon && (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
bgcolor: iconBg,
|
||||
color: iconColor,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
sx={[
|
||||
{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
flexShrink: 0,
|
||||
},
|
||||
iconBadgeSx(color),
|
||||
]}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
|
||||
@@ -18,7 +18,7 @@ export { default as Pagination } from "./Pagination";
|
||||
export { default as DateField } from "./DateField";
|
||||
export { default as MonthField } from "./MonthField";
|
||||
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 LoadingState } from "./LoadingState";
|
||||
export { default as FilterBar } from "./FilterBar";
|
||||
|
||||
@@ -4,6 +4,7 @@ import { requireAuth } from "../../middleware/auth";
|
||||
import { success } from "../../utils/response";
|
||||
import { localTimeStr } from "../../utils/date";
|
||||
import { toCzk } from "../../services/exchange-rates";
|
||||
import { resolveCell } from "../../services/plan.service";
|
||||
|
||||
export default async function dashboardRoutes(
|
||||
fastify: FastifyInstance,
|
||||
@@ -42,6 +43,30 @@ export default async function dashboardRoutes(
|
||||
result.my_shift = { has_ongoing: myShift !== null };
|
||||
}
|
||||
|
||||
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
|
||||
// resolveCell returns 0–3 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
|
||||
if (has("attendance.manage")) {
|
||||
const [todayAttendance, onLeaveToday, usersCount] = await Promise.all([
|
||||
|
||||
@@ -310,7 +310,9 @@ export default async function ordersRoutes(
|
||||
const id = parseId(request.params.id, reply);
|
||||
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!);
|
||||
|
||||
await logAudit({
|
||||
|
||||
@@ -328,18 +328,6 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
);
|
||||
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({
|
||||
request,
|
||||
authData: request.authData,
|
||||
|
||||
@@ -105,8 +105,12 @@ interface DownloadResult {
|
||||
export class NasFileManager {
|
||||
private readonly basePath: string;
|
||||
|
||||
constructor() {
|
||||
this.basePath = path.resolve(config.nas.path).replace(/\\/g, "/");
|
||||
constructor(basePath?: string) {
|
||||
// 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 {
|
||||
|
||||
@@ -5,6 +5,11 @@ import {
|
||||
releaseSharedNumber,
|
||||
isOrderNumberTaken,
|
||||
} 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 {
|
||||
description?: string | null;
|
||||
@@ -262,6 +267,23 @@ export async function createOrderFromQuotation(
|
||||
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 {
|
||||
data: {
|
||||
order_id: result.order.id,
|
||||
@@ -297,7 +319,7 @@ export async function createOrder(
|
||||
attachmentName?: string | null,
|
||||
) {
|
||||
try {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const orderNumber =
|
||||
body.order_number !== undefined && body.order_number !== null
|
||||
? String(body.order_number)
|
||||
@@ -362,6 +384,8 @@ export async function createOrder(
|
||||
}
|
||||
|
||||
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
|
||||
// order's number (same shared pool) exactly like the from-quotation flow.
|
||||
if (body.create_project !== false && body.quotation_id == null) {
|
||||
@@ -375,14 +399,42 @@ export async function createOrder(
|
||||
},
|
||||
});
|
||||
projectId = project.id;
|
||||
if (project.project_number) {
|
||||
createdProject = {
|
||||
project_number: project.project_number,
|
||||
name: project.name || "",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: order.id,
|
||||
order_number: order.order_number,
|
||||
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) {
|
||||
if (err instanceof Error && "status" in err) {
|
||||
return {
|
||||
@@ -536,15 +588,17 @@ export async function updateOrder(id: number, body: UpdateOrderData) {
|
||||
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 } });
|
||||
if (!existing)
|
||||
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({
|
||||
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,
|
||||
@@ -610,6 +664,24 @@ export async function deleteOrder(id: number) {
|
||||
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
|
||||
? new Date(existing.created_at).getFullYear()
|
||||
: new Date().getFullYear();
|
||||
|
||||
@@ -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
|
||||
* 0–MAX_RECORDS_PER_CELL records.
|
||||
*
|
||||
* Precedence: override > entry > null.
|
||||
* Soft-deleted rows are ignored (is_deleted = false filter).
|
||||
* If multiple entries cover the same day, the latest by created_at wins
|
||||
* and a warning is logged.
|
||||
* Layering: if any override exists for the day, the overrides are returned
|
||||
* (newest-first) and the range entries are hidden; otherwise the range
|
||||
* entries covering the day are returned (newest-first). Soft-deleted rows
|
||||
* 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
|
||||
* from it and Prisma handles timezone conversion against the MySQL
|
||||
@@ -122,31 +124,31 @@ export interface ResolvedCell {
|
||||
export async function resolveCell(
|
||||
userId: number,
|
||||
dateStr: string,
|
||||
): Promise<ResolvedCell | null> {
|
||||
): Promise<ResolvedCell[]> {
|
||||
const date = new Date(dateStr);
|
||||
|
||||
// 1. Single-day override for this exact date
|
||||
const override = await prisma.work_plan_overrides.findFirst({
|
||||
const overrides = await prisma.work_plan_overrides.findMany({
|
||||
where: { user_id: userId, shift_date: date, is_deleted: false },
|
||||
orderBy: { created_at: "desc" },
|
||||
take: MAX_RECORDS_PER_CELL,
|
||||
include: { projects: projectSelect },
|
||||
});
|
||||
if (override) {
|
||||
return {
|
||||
source: "override",
|
||||
if (overrides.length > 0) {
|
||||
return overrides.map((o) => ({
|
||||
source: "override" as const,
|
||||
entryId: null,
|
||||
overrideId: override.id,
|
||||
user_id: override.user_id,
|
||||
overrideId: o.id,
|
||||
user_id: o.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: override.project_id,
|
||||
...projectFields(override.projects),
|
||||
category: override.category,
|
||||
note: override.note,
|
||||
project_id: o.project_id,
|
||||
...projectFields(o.projects),
|
||||
category: o.category,
|
||||
note: o.note,
|
||||
rangeFrom: null,
|
||||
rangeTo: null,
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
// 2. Range entry that covers the day
|
||||
const entries = await prisma.work_plan_entries.findMany({
|
||||
where: {
|
||||
user_id: userId,
|
||||
@@ -155,24 +157,11 @@ export async function resolveCell(
|
||||
is_deleted: false,
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
take: MAX_RECORDS_PER_CELL,
|
||||
include: { projects: projectSelect },
|
||||
});
|
||||
|
||||
if (entries.length === 0) return null;
|
||||
|
||||
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",
|
||||
return entries.map((entry) => ({
|
||||
source: "entry" as const,
|
||||
entryId: entry.id,
|
||||
overrideId: null,
|
||||
user_id: entry.user_id,
|
||||
@@ -183,12 +172,14 @@ export async function resolveCell(
|
||||
note: entry.note,
|
||||
rangeFrom: entry.date_from.toISOString().slice(0, 10),
|
||||
rangeTo: entry.date_to.toISOString().slice(0, 10),
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the effective plan cell for every (userId, date) in the
|
||||
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell | null.
|
||||
* Compute the effective plan records for every (userId, date) in the
|
||||
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell[]
|
||||
* (0–MAX_RECORDS_PER_CELL records, same layering as resolveCell; empty
|
||||
* days are []).
|
||||
*
|
||||
* Implementation: load all entries and overrides for the range in two
|
||||
* queries, then iterate the dates and resolve each cell in O(1) per
|
||||
@@ -198,7 +189,7 @@ export async function resolveGrid(
|
||||
userIds: number[],
|
||||
dateFromStr: string,
|
||||
dateToStr: string,
|
||||
): Promise<Record<number, Record<string, ResolvedCell | null>>> {
|
||||
): Promise<Record<number, Record<string, ResolvedCell[]>>> {
|
||||
const dateFrom = new Date(dateFromStr);
|
||||
const dateTo = new Date(dateToStr);
|
||||
|
||||
@@ -219,11 +210,11 @@ export async function resolveGrid(
|
||||
is_deleted: false,
|
||||
shift_date: { gte: dateFrom, lte: dateTo },
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
include: { projects: projectSelect },
|
||||
}),
|
||||
]);
|
||||
|
||||
// Build a date list (inclusive)
|
||||
const dates: string[] = [];
|
||||
for (
|
||||
let d = new Date(dateFrom);
|
||||
@@ -233,56 +224,52 @@ export async function resolveGrid(
|
||||
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) {
|
||||
result[uid] = {};
|
||||
for (const dateStr of dates) {
|
||||
// Override first
|
||||
const override = overrides.find(
|
||||
(o) =>
|
||||
o.user_id === uid &&
|
||||
o.shift_date.toISOString().slice(0, 10) === dateStr,
|
||||
);
|
||||
if (override) {
|
||||
result[uid][dateStr] = {
|
||||
source: "override",
|
||||
const day = new Date(dateStr);
|
||||
const dayOverrides = overrides
|
||||
.filter(
|
||||
(o) =>
|
||||
o.user_id === uid &&
|
||||
o.shift_date.toISOString().slice(0, 10) === dateStr,
|
||||
)
|
||||
.slice(0, MAX_RECORDS_PER_CELL);
|
||||
if (dayOverrides.length > 0) {
|
||||
result[uid][dateStr] = dayOverrides.map((o) => ({
|
||||
source: "override" as const,
|
||||
entryId: null,
|
||||
overrideId: override.id,
|
||||
user_id: override.user_id,
|
||||
overrideId: o.id,
|
||||
user_id: o.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: override.project_id,
|
||||
...projectFields(override.projects),
|
||||
category: override.category,
|
||||
note: override.note,
|
||||
project_id: o.project_id,
|
||||
...projectFields(o.projects),
|
||||
category: o.category,
|
||||
note: o.note,
|
||||
rangeFrom: null,
|
||||
rangeTo: null,
|
||||
};
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
// First (latest by created_at) matching entry
|
||||
const entry = entries.find(
|
||||
(e) =>
|
||||
e.user_id === uid &&
|
||||
e.date_from <= new Date(dateStr) &&
|
||||
e.date_to >= new Date(dateStr),
|
||||
);
|
||||
if (entry) {
|
||||
result[uid][dateStr] = {
|
||||
source: "entry",
|
||||
entryId: entry.id,
|
||||
overrideId: null,
|
||||
user_id: entry.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: entry.project_id,
|
||||
...projectFields(entry.projects),
|
||||
category: entry.category,
|
||||
note: entry.note,
|
||||
rangeFrom: entry.date_from.toISOString().slice(0, 10),
|
||||
rangeTo: entry.date_to.toISOString().slice(0, 10),
|
||||
};
|
||||
} else {
|
||||
result[uid][dateStr] = null;
|
||||
}
|
||||
const dayEntries = entries
|
||||
.filter(
|
||||
(e) => e.user_id === uid && e.date_from <= day && e.date_to >= day,
|
||||
)
|
||||
.slice(0, MAX_RECORDS_PER_CELL);
|
||||
result[uid][dateStr] = dayEntries.map((e) => ({
|
||||
source: "entry" as const,
|
||||
entryId: e.id,
|
||||
overrideId: null,
|
||||
user_id: e.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: e.project_id,
|
||||
...projectFields(e.projects),
|
||||
category: e.category,
|
||||
note: e.note,
|
||||
rangeFrom: e.date_from.toISOString().slice(0, 10),
|
||||
rangeTo: e.date_to.toISOString().slice(0, 10),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,22 +364,14 @@ export function assertNotPastDate(
|
||||
* where `oldData` is null for creates and the pre-update snapshot for
|
||||
* 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 }`.
|
||||
*/
|
||||
export type Result<T> =
|
||||
| {
|
||||
data: T;
|
||||
oldData: unknown | null;
|
||||
replacedData?: unknown | null;
|
||||
/** Human-readable Czech subject for the audit-log row. */
|
||||
description?: string;
|
||||
/** Audit description for the `replacedData` soft-delete row, if any. */
|
||||
replacedDescription?: string;
|
||||
}
|
||||
| { error: string; status: number };
|
||||
|
||||
@@ -401,6 +380,46 @@ function toDateOnly(dateStr: string): Date {
|
||||
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. */
|
||||
export async function createEntry(
|
||||
input: {
|
||||
@@ -442,6 +461,13 @@ export async function createEntry(
|
||||
const catErr = await assertActiveCategory(input.category);
|
||||
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({
|
||||
data: {
|
||||
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
|
||||
* same (user_id, shift_date) — soft-deletes the old one. Past dates
|
||||
* require force=true.
|
||||
*
|
||||
* 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.
|
||||
* Create a work_plan_overrides row. Additive: stacks up to
|
||||
* MAX_RECORDS_PER_CELL active overrides per (user_id, shift_date); a create
|
||||
* past the cap returns { error, status: 400 }. Past dates require force=true.
|
||||
* Returns { data, oldData: null, description }.
|
||||
*/
|
||||
export async function createOverride(
|
||||
input: {
|
||||
@@ -601,49 +624,41 @@ export async function createOverride(
|
||||
const catErr = await assertActiveCategory(input.category);
|
||||
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 { created, replaced } = await prisma.$transaction(async (tx) => {
|
||||
const existing = await tx.work_plan_overrides.findFirst({
|
||||
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 },
|
||||
// Additive up to MAX_RECORDS_PER_CELL. (This previously REPLACED the existing
|
||||
// override; multi-record cells stack instead.) count+create runs in one
|
||||
// transaction; a concurrent create could in theory add one extra row, but
|
||||
// resolve display caps at MAX_RECORDS_PER_CELL so that is benign.
|
||||
let created;
|
||||
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 (count >= MAX_RECORDS_PER_CELL) {
|
||||
throw Object.assign(new Error("cap"), { __cap: true });
|
||||
}
|
||||
return tx.work_plan_overrides.create({
|
||||
data: {
|
||||
user_id: input.user_id,
|
||||
shift_date: date,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
created_by: actorUserId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const createdRow = await tx.work_plan_overrides.create({
|
||||
data: {
|
||||
user_id: input.user_id,
|
||||
shift_date: date,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
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(
|
||||
created.user_id,
|
||||
@@ -658,26 +673,7 @@ export async function createOverride(
|
||||
force,
|
||||
});
|
||||
|
||||
let replacedDescription: string | undefined;
|
||||
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,
|
||||
};
|
||||
return { data: created, oldData: null, description };
|
||||
}
|
||||
|
||||
/** Update a work_plan_overrides row. */
|
||||
|
||||
@@ -189,10 +189,16 @@ export async function createProject(data: CreateProjectInput) {
|
||||
});
|
||||
|
||||
if (project.project_number && nasFileManager.isConfigured()) {
|
||||
nasFileManager.createProjectFolder(
|
||||
const created = nasFileManager.createProjectFolder(
|
||||
project.project_number,
|
||||
project.name || "",
|
||||
);
|
||||
if (!created) {
|
||||
console.error(
|
||||
"[projects.service] NAS folder not created for project",
|
||||
project.project_number,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return project;
|
||||
|
||||
Reference in New Issue
Block a user