Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e082a6ef06 | ||
|
|
1662453d9c | ||
|
|
9dd2e07f19 | ||
|
|
18064a972c | ||
|
|
996835dae5 | ||
|
|
c73b980ce7 | ||
|
|
dafa6d6aab | ||
|
|
80803cc868 | ||
|
|
55fa4045ad | ||
|
|
7f156cc721 | ||
|
|
e0d2fccf50 | ||
|
|
a1c251650b | ||
|
|
103908cfb8 | ||
|
|
449a1a2243 | ||
|
|
337feb8b3a | ||
|
|
bc62d32efc | ||
|
|
30dd5a3f3b | ||
|
|
5140d23d73 | ||
|
|
a373102f3a | ||
|
|
49ec3482ae | ||
|
|
f6cdfb9801 | ||
|
|
bd9dc8d103 | ||
|
|
0c5d0ee2f7 | ||
|
|
fdf180809d | ||
|
|
52f3da73ad | ||
|
|
83aba93a98 | ||
|
|
744baec2ec | ||
|
|
1f05ef6a55 | ||
|
|
94a9fb8b5a | ||
|
|
9c582e1a43 | ||
|
|
9ae49c0d6a | ||
|
|
522afefc80 | ||
|
|
c5f986adc1 | ||
|
|
379725a096 | ||
|
|
05596642bc | ||
|
|
58bf0348d7 | ||
|
|
55a2c50f79 | ||
|
|
86e4cbf345 |
44
CLAUDE.md
44
CLAUDE.md
@@ -104,7 +104,7 @@ TOTP_ENCRYPTION_KEY=<64-char hex string>
|
||||
Optional (with defaults):
|
||||
|
||||
```
|
||||
PORT=3001 # Production port (dev default: 3000)
|
||||
PORT=3001 # Production port (dev default: 3050, hardcoded in server.ts)
|
||||
HOST=127.0.0.1
|
||||
APP_ENV=local|production # Default: local. Controls CSP, CORS, HSTS
|
||||
ACCESS_TOKEN_EXPIRY=900 # 15 minutes
|
||||
@@ -364,6 +364,44 @@ npx prisma migrate resolve --applied <migration_name>
|
||||
|
||||
---
|
||||
|
||||
## Conventions (enforced — verified by the 2026-06-06 audit)
|
||||
|
||||
These are the unified rules across the codebase. Follow them for new code; the
|
||||
audit found and fixed the deviations. Full report: `docs/codebase-audit-2026-06-06.md`.
|
||||
|
||||
**Routes**
|
||||
|
||||
- **Responses:** always `success(reply, data[, status, message])` / `error(reply, msg, status)` / the paginated helper. Never raw `reply.send({ success: true, ... })`. (Some legacy files still do — convert when you touch them.)
|
||||
- **Route ids:** parse numeric params with `parseId((request.params as any).id, reply)` then `if (id === null) return;`. Do not use raw `parseInt` (it yields `NaN`, not a 400).
|
||||
- **Bodies:** validate every body with `parseBody(Schema, request.body)` → `if ("error" in body) return error(reply, body.error, 400)`.
|
||||
- **Permissions:** guard with `requirePermission` / `requireAnyPermission`. The admin shortcut is `authData.roleName === "admin"`. ⚠️ `AuthData` has **`roleName`**, not `role` (`role` only exists on `JwtPayload`). Don't type `authData` as `any` — it hides exactly this bug.
|
||||
- **Audit:** call `logAudit` on every create/update/delete (and on security-relevant actions like session/token termination) with `oldValues`/`newValues`.
|
||||
|
||||
**Services**
|
||||
|
||||
- Plain exported async functions; return `{ data }` or `{ error, status }` (preferred over discriminated unions). Services own Prisma; routes stay thin.
|
||||
- Respect soft-delete (`is_deleted: false`) in reads where the model has it.
|
||||
|
||||
**Schemas (Zod 4)**
|
||||
|
||||
- Use Zod 4 idioms: `z.strictObject({...})` / `z.looseObject({...})` (not deprecated `.strict()` / `.passthrough()`).
|
||||
- Shared coercion helpers (number-from-form, nullable-number, boolean-from-form) belong in `src/schemas/common.ts` — don't copy-paste the `z.union([z.number(), z.string()]).transform(Number)` idiom (it's duplicated ~150× today; consolidating is a tracked follow-up). New number coercions should guard against `NaN`.
|
||||
- User-facing messages in **Czech**; identifiers/keys in English.
|
||||
|
||||
**Frontend**
|
||||
|
||||
- **Query invalidation:** invalidate the **broad domain key** (`["offers"]`, not `["offers","list"]`). Prefix-matching covers sub-queries.
|
||||
- **Single source of truth for shared maps:** audit `entity_type` → Czech label lives in `src/admin/lib/entityTypeLabels.ts` and MUST be keyed to the server's `EntityType` values (add the new key there when you add an entity type). Plan categories come from the DB via `lib/queries/plan.ts`. Don't duplicate label maps across files or across server/client.
|
||||
- Prefer deriving state over `useEffect`; use React Query for fetching, not effects.
|
||||
|
||||
**Dates (two deliberate regimes — don't "fix" either)**
|
||||
|
||||
- **Plan module** does all date-only math in **UTC** (`setUTCDate`, `toISOString().slice(0,10)`) because its columns are `@db.Date` (UTC-midnight). Correct and stable.
|
||||
- **Attendance/leave** writes `@db.Date` at **local noon** (`new Date(y, m, d, 12, 0, 0)`).
|
||||
- **Frontend "today" / date-string round-trips:** use `utils/date.ts` `localDateStr` (server) / `normalizeDateStr` (client). **Never** use `new Date().toISOString().split("T")[0]` for "today" — it's the UTC date and is a day early during the late-evening Prague window.
|
||||
|
||||
---
|
||||
|
||||
## Known Issues & Gotchas
|
||||
|
||||
1. **Date.prototype.toJSON override** — global monkey-patch in `src/config/env.ts`. Side-effects on third-party libraries that serialize dates. Do not remove without migrating all date serialization.
|
||||
@@ -372,9 +410,9 @@ npx prisma migrate resolve --applied <migration_name>
|
||||
|
||||
3. **Mixed error patterns** — Some services return `{ error, status }`, others return discriminated unions `{ type: 'success' | 'error' }`. Prefer `{ error, status }` for consistency with existing routes.
|
||||
|
||||
4. **Silent error catches** — A few service functions swallow errors in catch blocks. Always log at minimum; never use empty catch blocks.
|
||||
4. **Never swallow errors** — log at minimum; never use empty `catch` blocks. The service layer logs via `console.*` (there is no request-scoped pino logger in services). The NAS managers' previously-silent filesystem catches are now logged. One exception: a `catch` that handles an _expected_ condition (e.g. `ENOENT` used as an existence check) may stay silent **only with a comment** saying so.
|
||||
|
||||
5. **HTML sanitization gap** — Rich text fields in invoices use DOMPurify, but quotation scope and order scope fields may not. If modifying those, add sanitization.
|
||||
5. **HTML sanitization is in place — keep applying it** — Rich-text fields (invoice notes, quotation scope, order notes) ARE sanitized: server-side DOMPurify (jsdom) plus a `cleanQuillHtml` regex pass at all three PDF routes, and the frontend sanitizes before every `dangerouslySetInnerHTML` (InvoiceDetail, OrderDetail). (The old "sanitization gap" note was stale — verified by the 2026-06-06 audit.) When you add ANY new rich-text/HTML field, apply the same sanitization on BOTH the PDF path and the render path.
|
||||
|
||||
6. **Puppeteer PDF generation** — Runs a headless browser. Input to the HTML template must be sanitized. Do not pass unsanitized user data into PDF templates.
|
||||
|
||||
|
||||
90
docs/codebase-audit-2026-06-06.md
Normal file
90
docs/codebase-audit-2026-06-06.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Codebase Consistency & Best-Practices Audit — 2026-06-06 (overnight)
|
||||
|
||||
**Branch:** `chore/codebase-consistency-audit` (off `master` @ v1.9.0). Nothing here is pushed or deployed; for user review in the morning.
|
||||
|
||||
**Mandate (from user):** scan the whole codebase, find inconsistencies, unify manners/conventions, apply best practices (use context7 for library docs). Edit CLAUDE.md to codify rules. Work only in the project dir. Use many agents.
|
||||
|
||||
**Operating rules I'm following (self-imposed for safe autonomous work):**
|
||||
|
||||
- Isolated branch only. Never touch `master`, never push, never deploy, never touch prod/DB.
|
||||
- Keep `tsc` (server+client) at 0 and `vitest` green after every change set.
|
||||
- Prefer documenting risky/large refactors over auto-applying them. Auto-apply only safe, verified, mechanical unifications.
|
||||
- Don't `git add -A`; stage explicit paths.
|
||||
|
||||
---
|
||||
|
||||
## 🔴 CRITICAL FINDINGS (need user action)
|
||||
|
||||
### C1 — v1.9.0 production regression: plan edit-modal delete button missing
|
||||
|
||||
- **Cause:** `FormModal`'s `footerLeft` / `hideCloseButton` props + modal animations lived only in the user's _uncommitted_ working tree. Committed `PlanCellModal.tsx:225` (and the modal system) depend on `footerLeft`. Releases build from committed code (WIP stashed), so v1.9.0 shipped a `FormModal` without the footer-left slot → the **delete button in the plan entry/override edit modal does not render in production**. Also caused a committed-code `tsc` error (TS2322).
|
||||
- **Impact:** plan entry/override deletion via the edit modal is broken in prod v1.9.0. Category management is NOT affected (it uses `hideFooter` + in-body delete). Minor cosmetic: modal entry animation, `hideCloseButton`.
|
||||
- **Fix:** committed the modal enhancements (`86e4cbf` on this branch). **Needs a patch release (v1.9.1) to fix prod.**
|
||||
- **Status:** fixed on branch; prod patch pending user.
|
||||
|
||||
### C2 — test suite was red on master/v1.9.0 (2 failing auth tests)
|
||||
|
||||
- **Cause:** the JWT log-noise fix (`88c9b7c`) stopped logging expected invalid/expired tokens, but `auth.service.test.ts` still asserted it logged. The wrong auth test file (`auth.test.ts`) was run when that change landed, so 2 failing tests shipped on master.
|
||||
- **Fix:** updated the tests to assert null + no-log for `JsonWebTokenError` cases (`55a2c50`). Suite back to **134/134**.
|
||||
- **Status:** fixed on branch. (No runtime impact; CI/test hygiene + would also be cleared by the v1.9.1 patch.)
|
||||
|
||||
---
|
||||
|
||||
## Findings log
|
||||
|
||||
(Discovery sweep results appended below as agents report. Severity: critical/high/medium/low. Fix class: safe-auto / needs-judgment / manual.)
|
||||
|
||||
## Changes applied on this branch (all verified: server+client tsc 0, vitest 134, build 0)
|
||||
|
||||
Correctness / bugs:
|
||||
|
||||
- `86e4cbf` **C1** modal `footerLeft`/`hideCloseButton` enhancements committed (fixes v1.9.0 regression + tsc error).
|
||||
- `55a2c50` **C2** fix 2 failing `verifyAccessToken` tests (red on master).
|
||||
- `379725a` **H1/H4** `isAdminLike` reads `roleName` not `role` (admins were self-scoped on /entries,/overrides); dropped 4 stale `as any` category casts.
|
||||
- `c5f986a` **H5** corrected + unified audit `entity_type` label map (was showing raw English for invoice/order/quotation/trip/vehicle + all warehouse\_\*).
|
||||
- `1f05ef6` date: `todayLocalStr()` replaces 11 UTC-`today` defaults (off-by-one in post-midnight Prague).
|
||||
- `744baec` security: audit-log session termination (single + all-others); new `session` EntityType.
|
||||
|
||||
Consistency / cleanup:
|
||||
|
||||
- `9ae49c0` parseId (trips/sessions), broad `["offers"]` invalidation, Czech messages (attendance/orders/offers/project-files), Zod 4 `z.strictObject`.
|
||||
- `522afef` undefined `--danger-color`→`--danger`, dedup `formatDate` + `require2FAOptions`, removed dead `systemSettingsOptions`, dropped double `plan.css` import.
|
||||
- `9c582e1` **H2/H3** log the 30 silent NAS filesystem catches (kept 3 ENOENT-expected as deliberate no-logs).
|
||||
|
||||
Docs:
|
||||
|
||||
- `94a9fb8` CLAUDE.md: codified "Conventions (enforced)" section; corrected stale known-issues #4 (NAS) and #5 (sanitization is in place, not a gap).
|
||||
- `58bf034`/`0559664` this report + full 84-finding catalog (`codebase-audit-findings-2026-06-06.md`).
|
||||
|
||||
## Remaining recommendations (NOT auto-applied — for your review)
|
||||
|
||||
Deliberately left for review (too broad/behavior-risky to apply unattended, or low value):
|
||||
|
||||
- **`reply.send` → helpers** (medium): ~1/3 of route files use raw `reply.send({success:true,...})` instead of `success()/paginated()`. Mechanical but touches many files + response-shape sensitive — convert per-file when touched. (List in findings catalog, dimension `routes`.)
|
||||
- **Zod coercion helpers** (medium): the number/nullable-number/boolean-from-form coercions are copy-pasted ~150×; extract to `src/schemas/common.ts` (with a `NaN` guard — current coercion silently yields `NaN`). Big mechanical sweep — do with review.
|
||||
- **console.\* → request logger** (medium): services log via `console.*` (bypasses pino/log-level). Architectural; needs a service-logging strategy.
|
||||
- **`markOverdueInvoices`** (medium): swallows the DB-update failure and returns void, so the route treats a failed update as success — surface the error. Also it compares a `@db.Date` due_date against full `new Date()` (flips "overdue" on the due day) — compare date-only.
|
||||
- **Dead exports** (low): `previewPattern()` (numbering.service), `usersQuery`/`planKeys.users()` (lib/queries/plan) — unused API surface; remove or wire up.
|
||||
- **`ShiftFormModal`** (low): inline styles use `--danger-color`/`--success-color`/etc. (undefined; rely on fallbacks) — switch to the `--danger`/`--success` design tokens.
|
||||
- **`.env.example` drift** (low): out of sync with vars read in `config/env.ts` — regenerate.
|
||||
- **`@/*` path alias** (low): declared in tsconfig but not wired into Vite/vitest — either wire it up or remove.
|
||||
- **warehouse soft-delete test** (low): a test named "soft delete" asserts a hard delete its own comment flags as buggy — clarify intent.
|
||||
- **TOTP verify** doesn't increment failed-login counter (relies on rate limit); **HSTS** lacks `preload` — security hardening, low.
|
||||
|
||||
Full detail + file:line for every item: `docs/codebase-audit-findings-2026-06-06.md`.
|
||||
|
||||
## Progress tracker
|
||||
|
||||
- [x] Branch + clean baseline (tsc server 0 / client 0; vitest 134).
|
||||
- [x] C1 modal regression + C2 red tests found & fixed (134/134).
|
||||
- [x] Discovery sweep (16 parallel dimensions, 84 findings).
|
||||
- [x] Synthesis + prioritization (high + safe-auto).
|
||||
- [x] Safe unifications applied (12 commits, each verified green).
|
||||
- [x] CLAUDE.md updated with codified conventions.
|
||||
- [x] Remaining items documented as a review roadmap.
|
||||
- [x] Final verification.
|
||||
|
||||
## ⚠️ Action for you in the morning
|
||||
|
||||
- **v1.9.1 patch:** C1 (plan edit-modal delete button) + C2 (red tests) affect production v1.9.0. Merge this branch (or cherry-pick `86e4cbf`,`55a2c50`,`379725a`,`c5f986a`) and cut a patch.
|
||||
- Review this branch (`chore/codebase-consistency-audit`, 12 commits) and merge what you like. Nothing here is pushed or deployed.
|
||||
544
docs/codebase-audit-findings-2026-06-06.md
Normal file
544
docs/codebase-audit-findings-2026-06-06.md
Normal file
@@ -0,0 +1,544 @@
|
||||
# Codebase Audit — Full Findings Catalog (2026-06-06)
|
||||
|
||||
Generated from the 16-dimension discovery sweep. 84 findings (high 5, medium 31, low 48).
|
||||
|
||||
## Dimension summaries
|
||||
|
||||
**svc-errors** — test2
|
||||
|
||||
**routes** — Route handlers in src/routes/admin/* are largely consistent and follow the documented patterns well: nearly every route uses a requirePermission/requireAnyPermission/requireAuth guard, validates bodies via parseBody(ZodSchema, ...) with the uniform `if ("error" in parsed) return error(reply, parsed.error, 400)` shape, uses parseId for numeric route params in most files, and logs audit entries on create/update/delete with old/new values. The warehouse, customers, invoices, projects, roles, and auth/totp files are exemplary. The real issues are: (1) a genuine authorization/visibility bug in plan.ts where the admin check reads a non-existent field; (2) a recurring style violation where roughly a third of files send raw `reply.send({ success: true, ... })` instead of the success()/paginated() helpers that CLAUDE.md mandates; (3) two security-relevant session-termination mutations with no audit logging; and (4) inconsistent ID parsing (raw parseInt vs the parseId helper) in trips.ts and sessions.ts. HTTP status codes are generally correct (201 on create, 404 not-found, 409 conflict, 403 permission), with one cluster of not-found/validation responses in project-files.ts falling back to the default 400.
|
||||
|
||||
**schemas** — The 21 Zod schema files in src/schemas/* are consistently organized (one file per entity, Create/Update pairs, z.infer type exports, Czech user-facing messages — all intentional and good). Every route body is validated via the shared parseBody helper (src/schemas/common.ts) — coverage is complete; the handful of raw `request.body` reads (attendance.ts, orders.ts, projects.ts, project-files.ts) either re-dispatch to parseBody with branch-specific schemas or do narrow manual checks, so there is no unvalidated-body gap. The dominant real issue is massive duplication of three coercion idioms — a number-from-form `z.union([z.number(),z.string()]).transform(v=>Number(v))`, a nullable variant with `z.null()`, and a boolean-from-form `z.preprocess(v=>v===true||v===1||v==="1", z.boolean())` — copy-pasted ~150+ times across files instead of living as shared helpers in common.ts. Secondary issues: the number coercion is unsafe (no NaN guard in most places, so "abc" silently becomes NaN), email validation is applied inconsistently (only users/profile, not customers/warehouse/settings), error-message language is mixed (Czech vs English "Must be a valid number"), no schemas use strict object mode so unknown keys are silently stripped, and the two inline route schemas use Zod-3-deprecated `.strict()`/`.passthrough()` rather than Zod 4's `z.strictObject()`/`z.looseObject()`. Severity is mostly low/medium: these are maintainability and robustness gaps, not security holes (the app is on Zod 4.3.6, so the modern helpers are available).
|
||||
|
||||
**logging** — Overall the codebase handles errors deliberately: routes use Fastify's pino logger (request.log.*/app.log.*), the global error handler logs unhandled exceptions, audit failures are logged and treated as non-fatal, and a couple of catch blocks (auth.ts verifyAccessToken, attendance/leave duplicate-record handling) are intentionally selective with good comments. The two real systemic issues are: (1) the NAS file/financials managers (src/services/nas-file-manager.ts, src/services/nas-financials-manager.ts) contain ~25 empty/silent catch blocks that swallow genuine filesystem operation failures (delete/mkdir/write/rename) with zero logging, returning only a generic Czech string — directly violating the CLAUDE.md "never silently swallow errors" rule and making NAS issues undebuggable; and (2) all service-layer error logging uses console.* instead of the configured pino logger, so those messages bypass structured logging and the production log-level config. A secondary correctness smell: markOverdueInvoices swallows DB-update failures and returns void, so its route caller treats a failed update as success. Frontend error handling is consistent (alert.error with Czech fallback); a few best-effort .catch(()=>{}) swallows on background calls are defensible but undocumented.
|
||||
|
||||
**prisma** — Solid Prisma usage overall. Real issues in findings.
|
||||
|
||||
**security** — Auth and crypto fundamentals are solid: refresh tokens are SHA-256-hashed with rotation + reuse detection (replaced_at/replaced_by_hash + FOR UPDATE), TOTP has counter-based replay protection, password comparison is timing-safe (dummy bcrypt hash on user-not-found/locked/inactive), TOTP secrets are AES-256-GCM encrypted, account lockout + per-route rate limits exist, bcrypt cost is 12, and JWT verification pins HS256. Contrary to CLAUDE.md "known issue #5", HTML sanitization for invoice notes, quotation scope, and order notes is NOT missing: DOMPurify (jsdom) is applied at all three server-side PDF routes plus a regex-based cleanQuillHtml second pass, and both frontend render sites (InvoiceDetail, OrderDetail) sanitize before dangerouslySetInnerHTML. NAS file access has strong path-traversal defenses (rejects "..", null bytes, confines to base, rejects symlink components, MIME/extension allowlist). The real gaps are narrower: the TOTP-code verification step does not increment failed-login counters (relies only on a 5/min rate limit), HSTS lacks preload, and the server-side invoice/offer PDF endpoints serve attacker-influenced (but sanitized) HTML as same-origin text/html. No SQL injection found — all $queryRaw uses are parameterized tagged templates.
|
||||
|
||||
**dates** — Date handling splits into two well-reasoned, internally-consistent regimes plus a set of genuine off-by-one bugs at the boundary between them. (1) The plan module (src/services/plan.service.ts, src/admin/pages/PlanWork.tsx, usePlanWork.ts, PlanGrid.tsx) deliberately does ALL date-only arithmetic in UTC (setUTCDate/getUTCDate, toISOString().slice(0,10), proper ISO-8601 week calc). Because every column it touches is `@db.Date` (stored at UTC-midnight by Prisma), this is correct and stable — explicitly documented at plan.service.ts:63-67 and 342-352. Do not "fix" it. (2) The attendance/leave server code constructs `@db.Date` writes at LOCAL noon (new Date(y,m,d,12,0,0)), which is the robust convention. The real problems: a repeated frontend pattern `new Date().toISOString().split("T")[0]` for "today" defaults computes the UTC date, giving yesterday in the late-evening Prague window; the invoices/received-invoices/trips edit forms round-trip API date strings through `new Date(x).toISOString().split(...)` instead of the existing string-slice helper `normalizeDateStr`, risking a shift; trips' raw API datetime string is fed into a native <input type=date> (blank on mobile); markOverdueInvoices compares a `@db.Date` due_date against full `new Date()` so invoices flip to "overdue" on their due day; and getCzechDate uses a non-ISO local week formula that disagrees with PlanWork's ISO week. A correct local-date string helper (utils/date.ts localDateStr, and frontend normalizeDateStr) already exists but isn't used in the offending spots.
|
||||
|
||||
**ts-safety** — Both tsconfigs enable `strict: true` and there are zero `@ts-ignore`/`@ts-nocheck` directives, so the baseline is good. The real risk is concentrated, not diffuse: 77 `any` occurrences cluster in the work-plan stack (plan.service.ts, routes/admin/plan.ts, hooks/usePlanWork.ts) and a few PDF/HTML builders. The single most important finding is a latent authorization-scoping bug masked by an `any`-typed parameter in plan.ts (`isAdminLike` reads `authData.role`, but `AuthData` only has `roleName`), which makes admins always scope to their own plan rows. Systemically, ~47 of 107 exported service functions have no explicit return type, which forces `(result as any).status` casts in route handlers (projects.ts, quotations.ts) because the inferred error union isn't uniform. There is also a genuinely duplicated/contradictory `PaginationMeta` shape defined three times with diverging fields. Non-null assertions are mostly the defensible `request.authData!` post-auth pattern and are not a concern.
|
||||
|
||||
**rq-data** — The frontend data layer is built on a clean, idiomatic foundation: every read is a `queryOptions()` factory in `src/admin/lib/queries/*` (TanStack Query v5 best practice), data flows through a thin `apiAdapter.ts` (jsonQuery/paginatedJsonQuery) that unwraps the `{success,data}` envelope and throws on error, and a purpose-built `useApiMutation` hook (lib/queries/mutations.ts) wraps `useMutation` + apiFetch + broad invalidation exactly as the docs recommend. The factory pattern is consistently applied for queries and `useApiMutation` is adopted in 34 files. The real weakness is on the WRITE side: a large minority of mutations bypass `useApiMutation` and hand-roll `apiFetch` + `await response.json()` + manual `invalidateQueries` + `try/catch alert("Chyba připojení")` (14 files, ~27 sites), duplicating the exact logic the hook exists to centralize. Within that hand-rolled code the broad-domain invalidation convention from CLAUDE.md is violated in OfferDetail.tsx (uses narrow `["offers","list"]` while Offers.tsx uses broad `["offers"]`). useAttendanceAdmin.ts runs an entirely parallel data system (manual fetchData + setTimeout(300) instead of query factories). Query-key conventions themselves are sound; minor smells are a duplicated `require2FAOptions` factory and an unused deprecated alias. None of these are correctness bugs — they are consistency/maintainability gaps. Best-practice basis: TanStack Query v5 docs (/tanstack/query) confirm prefix-matching invalidation (validating the broad-key convention) and the useMutation→onSuccess→invalidateQueries pattern that useApiMutation implements.
|
||||
|
||||
**react** — The frontend is mostly modern and disciplined: data flows through TanStack Query via lib/queries/*, lazy-loading is consistent for every page in AdminApp.tsx, and there are two solid reusable modal primitives (FormModal, ConfirmModal) used in 34 files. The real issues are concentrated and concrete: (1) one large hook (useAttendanceAdmin.ts, ~830 lines) opts out of TanStack Query and hand-rolls fetching with useEffect/useState, complete with silent empty catches and no race-condition guard — the single biggest consistency/best-practice gap; (2) two editable, mutable lists use the array index as React key (OrderConfirmationModal items, OfferDetail scope sections), which the React docs flag as a correctness bug because rows are deleted/reordered while holding controlled-input state; (3) modal usage is inconsistent — alongside FormModal/ConfirmModal, ~7 components hand-roll the admin-modal-overlay markup with diverging accessibility (DashProfile/DashQuickActions omit role="dialog"/aria-modal entirely; none of the hand-rolled ones wire Esc-to-close that FormModal provides). Several "sync server data into form state via useEffect" effects exist (InvoiceDetail, OfferDetail, CompanySettings, Settings); these use a one-shot ref/flag guard and are an accepted-but-not-ideal pattern per the React "You Might Not Need an Effect" guidance, so they are reported as low severity. Per React docs I pulled: avoid adjusting/resetting state on prop change in an Effect (prefer key-reset or compute during render), and data-fetching effects need an ignore/abort cleanup to avoid stale overwrites.
|
||||
|
||||
**css** — The admin CSS is a single global stylesheet assembled from 19 per-feature files, all imported in AdminApp.tsx (so every selector shares one global namespace — the file split is purely organizational, not scoped). Theming is well-architected and consistent: a central variables.css drives a token system via [data-theme="dark"]/[data-theme="light"] (no prefers-color-scheme mixing), and the large majority of color usage correctly references CSS variables. Genuine issues are: (1) one undefined variable (--danger-color) used in base.css; (2) an inconsistent class-naming scheme — most files use either admin-* or a feature prefix (plan-*, dash-*, fm-*, attendance-*, offers-*), but warehouse uses admin-warehouse-*, invoices mixes admin-badge-*/invoice-*/received-*, and a block of leave badges in components.css drops the admin- prefix entirely; (3) heavy duplication of the badge color recipe (background: color-mix(... 15%) + matching text color) across leave/order/project/invoice/attendance badges, with two different recipes (--success-soft vs color-mix --success 15%) used for the same semantic color; and (4) several defined-but-unused tokens plus an empty responsive.css stub and a double-import of plan.css. Hardcoded hex outside variables.css is mostly legitimate (#fff text on accent backgrounds, feature-scoped local theme token blocks in plan.css/layout.css), not a real problem.
|
||||
|
||||
**naming** — Naming in this codebase is broadly consistent and mostly intentional. Backend `src/` is overwhelmingly kebab-case for files (94 kebab vs 5 camelCase), service functions follow a clean `list*` (collections) / `get*` (single) / `create|update|delete*` (mutations) scheme with no fetch/load mixing, route verbs map cleanly to fastify methods, and Czech appears only in user-facing string literals (a documented, intentional choice — not an identifier problem). The frontend leans on its own consistent conventions: `handle*` event handlers (148 vs 8 `on*`, where the `on*` cases are local DOM listeners — idiomatic), `is*/has*` for boolean props/fields, and `*Options` for TanStack query factories (55 of them). The real, genuine deviations are a small cluster of files added during the "plan" feature work that broke the surrounding kebab-case convention (`planCategory.schema.ts`, `planCategory.service.ts`, `planAuditDescription.ts` and their tests), and the `plan.ts` query module that uses `gridQuery`/`usersQuery` instead of the established `*Options` suffix. The `.service.ts` suffix is applied to 10 of 20 service files, but this tracks a defensible entity-CRUD-vs-infra split rather than randomness. These are low-to-medium consistency gaps, not correctness issues; most fixes are renames with cross-file import ripples, so few qualify as safe-auto.
|
||||
|
||||
**deadcode** — The codebase is generally well-factored (date helpers in src/utils/date.ts and frontend formatters are correctly centralized and reused). The real dead-code/duplication problems are concentrated in two areas: (1) the three PDF route files (invoices-pdf.ts, orders-pdf.ts, offers-pdf.ts) each redefine the same set of HTML/number helpers (escapeHtml, formatNum, formatCurrency, formatDate, cleanQuillHtml) plus an identical JSDOM+DOMPurify bootstrap — and the copies have already diverged (one uses a regular space as a thousands separator where the others use a non-breaking space); and (2) a handful of genuinely unused exports and one orphan component file. escapeHtml alone is independently defined six times across server and frontend. There are no leftover debug console.logs in the conventional sense — service-layer console.* calls are the established (consistent) logging pattern here since services have no Fastify logger, and the one documented console.warn in plan.service.ts is intentional. No commented-out code blocks of note were found.
|
||||
|
||||
**i18n** — Localization is overwhelmingly correct and intentional: all React UI labels, placeholders, titles, button text, alert/toast messages, and the large majority of backend error strings are Czech with correct gender agreement (nenalezen/nenalezena/nenalezeno), while code identifiers, enum values, internal sentinels (e.g. EMAIL_EXISTS), env-validation throws, console.error logs, and dev-only React invariant throws ("useAuth must be used within...") are English — all intentional and not flagged. The genuine gaps are narrow: (1) a handful of English user-facing API error strings that leak to the client ("Missing attendance_id"/"Missing id" in attendance.ts, and "Unauthorized"/"Request failed (n)"/"Invalid JSON response" thrown in the frontend query layer that ProjectFileManager renders verbatim); (2) the parseBody helper surfaces raw Zod messages, so any validator lacking a custom Czech message leaks Zod's default English (enums, .max() length caps, TOTP token .min(1)); and (3) inconsistent Czech phrasing for "not found" — the compact "nenalezen*" form (92 uses) vs the verbose "nebyl/nebyla nalezen*" form (16 uses), sometimes for the identical entity ("Projekt nenalezen" vs "Projekt nebyl nalezen"). No mixed tone, no English UI chrome.
|
||||
|
||||
**tests part2b** — remaining two low findings
|
||||
|
||||
**config-structure** — The build/config layout is coherent: a project-references tsconfig.json splits server (CJS, ES2022, excludes src/admin) from app (ES2020, bundler resolution), with matching vite/vitest configs and env validation in src/config/env.ts. The main structural problem is the absence of a shared constants/types module spanning server and src/admin: domain label maps (entity-type, action, leave-type) and the canonical EntityType value list are duplicated and have DRIFTED. Most seriously, the frontend audit-log label/filter maps use PHP-legacy entity-type keys (offers_quotation, invoices_invoice, projects_project, trips, vehicles) that no longer match what the TS server writes (quotation, invoice, project, trip, vehicle) — a functional bug caused by the duplication. Secondary issues: a configured-but-unused @/* path alias (also absent from vite resolve), a package.json db:push script contradicting the CLAUDE.md golden rule, and .env.example drift vs config/env.ts. The one piece of genuine cross-boundary sharing (czech-holidays imported by src/admin from src/utils) is inconsistent with how everything else is duplicated and is structurally fragile.
|
||||
|
||||
## Findings
|
||||
|
||||
### 1. [HIGH/needs-judgment] Frontend audit-type label/filter maps use legacy keys that don't match server-written entity_type values
|
||||
- **dimension:** config-structure
|
||||
- **where:** src/admin/pages/AuditLog.tsx:47-66; src/admin/utils/dashboardHelpers.ts:21-40; src/types/index.ts:121-149; src/services/audit.ts:30,43; src/routes/admin/audit-log.ts:34; src/admin/lib/queries/auditLog.ts:18
|
||||
- **problem:** The server's canonical EntityType union (src/types/index.ts) and every logAudit() call write values like 'invoice', 'customer', 'quotation', 'order', 'project', 'trip', 'vehicle' (e.g. invoices.ts:134 entityType:'invoice', vehicles.ts:68 'vehicle', quotations.ts:80 'quotation'). But the frontend ENTITY_TYPE_LABELS maps (duplicated identically in AuditLog.tsx and dashboardHelpers.ts) key on PHP-legacy values: offers_quotation, offers_customer, orders_order, invoices_invoice, projects_project, trips, vehicles. Two consequences: (1) the audit log UI falls back to showing raw entity_type strings for most entities because the lookup misses; (2) ENTITY_OPTIONS (derived from this map) feeds the entity-type filter dropdown, which sends e.g. entity_type=invoices_invoice to audit-log.ts:34 where it is exact-matched (where.entity_type = String(...)), so filtering by Faktura/Objednavka/Projekt/Jizda/Vozidlo returns zero rows.
|
||||
- **fix:** Make EntityType a single runtime source of truth (an `as const` array exported from a module importable by both server and src/admin) and derive both the TS union and the label maps from it, or at minimum fix the frontend keys to match the server values (invoice, customer, quotation, order, project, trip, vehicle) and de-duplicate the two copies. Add a small test asserting every EntityType value has a label.
|
||||
|
||||
### 2. [HIGH/needs-judgment] NAS file manager swallows real filesystem failures with empty catch blocks and zero logging
|
||||
- **dimension:** logging
|
||||
- **where:** src/services/nas-file-manager.ts:118; src/services/nas-file-manager.ts:139; src/services/nas-file-manager.ts:153; src/services/nas-file-manager.ts:176; src/services/nas-file-manager.ts:426; src/services/nas-file-manager.ts:531; src/services/nas-file-manager.ts:679
|
||||
- **problem:** nas-file-manager.ts has ~25 catch blocks and not a single logging call (Grep for console./.log./logger returns no matches). While many are legitimate existence/control-flow checks where the error is expected (e.g. lines 471-473, 525-527, 666-668), several swallow genuine operation failures: deleteProjectFolder (118), createProjectFolder (139), delete (426) returning 'Nepodařilo se smazat...', createFolder mkdir (531) returning 'Nepodařilo se vytvořit složku', and countItems (679). The underlying OS error (EACCES, ENOSPC, network share down, etc.) is discarded, so when a NAS operation fails in production there is nothing in the logs to diagnose it. This directly violates the CLAUDE.md rule: 'Never silently swallow errors. Even if a failure is non-fatal, log it.'
|
||||
- **fix:** In the catch blocks that represent actual operation failures (delete, mkdir, rename move, write, copy), capture the error and log it via the Fastify logger before returning the generic Czech message. Since these are service methods without request context, either accept an optional logger/request param or have the calling route log the returned error with the original cause. At minimum, distinguish 'expected ENOENT existence check' catches (which can stay silent) from 'operation should have succeeded' catches (which must log).
|
||||
|
||||
### 3. [HIGH/needs-judgment] NAS financials manager swallows write/read/delete/mkdir errors without logging
|
||||
- **dimension:** logging
|
||||
- **where:** src/services/nas-financials-manager.ts:135; src/services/nas-financials-manager.ts:151; src/services/nas-financials-manager.ts:163; src/services/nas-financials-manager.ts:184
|
||||
- **problem:** saveReceivedInvoice (135) catches a writeFileSync failure and returns the error string to the caller but never logs it server-side. readReceivedInvoice (151-153), deleteReceivedInvoice (163-165) and ensureDir (184-186) use fully empty 'catch { return null/false }' blocks that discard the filesystem error entirely. A failed received-invoice save/read/delete on the network share leaves no server-side trace, again violating the 'never silently swallow' rule.
|
||||
- **fix:** Log the caught error (with the resolved path) before returning null/false/error-string. As with nas-file-manager, thread the Fastify logger in or log the returned error at the route layer. The empty 'catch {}' forms at 151/163/184 are the worst offenders — they should at least preserve the error variable and log it.
|
||||
|
||||
### 4. [HIGH/needs-judgment] plan.ts admin check reads non-existent authData.role field — admins cannot see other users' plan rows
|
||||
- **dimension:** routes
|
||||
- **where:** src/routes/admin/plan.ts:43-45; src/routes/admin/plan.ts:120; src/routes/admin/plan.ts:142; src/services/plan.service.ts:780; src/services/plan.service.ts:799; src/types/index.ts:51
|
||||
- **problem:** isAdminLike() does `return authData?.role === 'admin'`, but the AuthData interface (src/types/index.ts:51) has `roleName`, not `role`. Every other consumer in the codebase uses `roleName` (middleware/auth.ts:47,69; users.ts:109; services/auth.ts). So `authData.role` is always undefined and isAdminLike() always returns false. It is passed as the `isAdmin` argument to listEntries()/listOverrides() (plan.ts:120,142), where plan.service.ts:780/799 do `effectiveUserId = isAdmin ? query.user_id : actorUserId`. Net effect: GET /plan/entries and GET /plan/overrides silently ignore the user_id query param for everyone, including admins, so an admin can never read another employee's raw plan/override rows. (Security direction is safe — it over-restricts rather than leaking — but the feature is broken for admins.)
|
||||
- **fix:** Change isAdminLike to use the documented role/permission model: either `authData?.roleName === 'admin'` to match middleware/auth.ts, or better, check the relevant permission (e.g. authData.permissions.includes('attendance.manage')) consistent with how trips.ts:22 and attendance.ts:208 distinguish admin vs self. Also drop the `any` type on the parameter and type it as AuthData.
|
||||
|
||||
### 5. [HIGH/needs-judgment] `any`-typed param hides admin-scoping bug: isAdminLike reads nonexistent `authData.role`
|
||||
- **dimension:** ts-safety
|
||||
- **where:** src/routes/admin/plan.ts:43; src/routes/admin/plan.ts:44; src/routes/admin/plan.ts:120; src/routes/admin/plan.ts:142; src/types/index.ts:44; src/services/plan.service.ts:780; src/services/plan.service.ts:799
|
||||
- **problem:** `isAdminLike(authData: any)` returns `authData?.role === "admin"`. The `AuthData` type (types/index.ts:44) has NO `role` field — the admin role is on `roleName` (used correctly everywhere else: auth.ts:47/69, users.ts:109). Because the parameter is typed `any`, the compiler cannot flag that `.role` is always `undefined`, so `isAdminLike` always returns `false`. It is passed as the `isAdmin` arg to `listEntries`/`listOverrides`, where `effectiveUserId = isAdmin ? query.user_id : actorUserId`. Result: an admin querying another user's plan is silently scoped to their own rows; the `user_id` query param is ignored for everyone. The `any` is the direct cause the type system did not catch the `role` vs `roleName` typo.
|
||||
- **fix:** Type the parameter as `AuthData | null | undefined` (or reuse the existing `roleName === "admin"` convention) and change the comparison to `authData?.roleName === "admin"`. This both fixes the bug and lets the compiler verify the field exists. Add/confirm a list-scoping test for the cross-user admin case.
|
||||
|
||||
### 6. [MEDIUM/needs-judgment] Domain label maps duplicated verbatim across frontend files (and diverging)
|
||||
- **dimension:** config-structure
|
||||
- **where:** src/admin/utils/dashboardHelpers.ts:1-47; src/admin/pages/AuditLog.tsx:17-66; src/admin/utils/attendanceHelpers.ts:80-97; src/admin/components/ShiftFormModal.tsx:338-340
|
||||
- **problem:** ENTITY_TYPE_LABELS and ACTION_LABELS exist as near-identical copies in dashboardHelpers.ts and AuditLog.tsx, and have already diverged: ACTION_LABELS.create is 'Vytvoreni' in AuditLog but 'Vytvoril' in dashboardHelpers, and AuditLog's copy has extra entries (view, activate, deactivate, password_change, ...). Separately, leave-type labels (vacation->'Dovolena', sick->'Nemoc', unpaid->'Neplacene volno') are repeated in dashboardHelpers.ts:2-4, attendanceHelpers.ts:83-85, and inline <option> values in ShiftFormModal.tsx. There is no shared constants module, so these will keep drifting.
|
||||
- **fix:** Extract one constants module (e.g. src/admin/constants/labels.ts) holding ENTITY_TYPE_LABELS, ACTION_LABELS, LEAVE_TYPE_LABELS and import it everywhere; ideally co-locate with the shared EntityType list from the audit-labels finding.
|
||||
|
||||
### 7. [MEDIUM/safe-auto] Undefined CSS variable --danger-color used in base.css
|
||||
- **dimension:** css
|
||||
- **where:** src/admin/base.css:268
|
||||
- **problem:** .admin-error-stack sets color: var(--danger-color), but no file defines --danger-color (variables.css defines --danger, --error, --accent-color, etc., but never --danger-color). The property has no fallback, so the error-stack text color resolves to the inherited/initial color instead of the intended danger red. This is a copy-paste/naming bug, not an intentional choice.
|
||||
- **fix:** Change to color: var(--danger) (the intended token). Optionally add a --danger-color alias in variables.css if other call sites expect it, but a grep shows base.css:268 is the only consumer.
|
||||
|
||||
### 8. [MEDIUM/needs-judgment] Duplicated badge color recipe across 5 feature areas
|
||||
- **dimension:** css
|
||||
- **where:** src/admin/components.css:142; src/admin/components.css:160; src/admin/components.css:178; src/admin/invoices.css:5; src/admin/attendance.css:333
|
||||
- **problem:** The same status-badge formula — background: color-mix(in srgb, var(--X) 15%, transparent); color: var(--X) — is hand-repeated for every semantic color across leave badges (badge-pending/approved/rejected, components.css:142-152), order badges (admin-badge-order-*, :160-174), project badges (admin-badge-project-*, :178-188), invoice badges (admin-badge-invoice-*, invoices.css:5-17), and attendance leave badges (badge-vacation/sick/holiday, attendance.css:333-345). E.g. info-15% is duplicated 4x and danger-15% 4x. Worse, the recipe is inconsistent with the generic badges right above it: admin-badge-success/info/danger (components.css:106-128) use the --*-soft tokens instead of color-mix 15%, so two different visual recipes exist for the same semantic 'success/danger badge'.
|
||||
- **fix:** Introduce semantic helper classes (e.g. .admin-badge-tone-success/info/warning/danger/muted) defined once, and have the leave/order/project/invoice/attendance status classes compose them, or apply the tone class in TSX. Pick one recipe (either --*-soft or color-mix 15%) so the same status reads identically everywhere. This removes ~20 near-identical rules.
|
||||
|
||||
### 9. [MEDIUM/needs-judgment] "Today" form defaults use UTC date (new Date().toISOString().split("T")[0]) → off-by-one in late evening
|
||||
- **dimension:** dates
|
||||
- **where:** src/admin/pages/InvoiceDetail.tsx:329; src/admin/pages/InvoiceDetail.tsx:331; src/admin/pages/Attendance.tsx:143; src/admin/pages/Attendance.tsx:144; src/admin/pages/Attendance.tsx:337; src/admin/pages/Attendance.tsx:338; src/admin/pages/AttendanceCreate.tsx:49; src/admin/pages/Trips.tsx:56; src/admin/pages/Trips.tsx:120; src/admin/components/dashboard/DashQuickActions.tsx:77
|
||||
- **problem:** These default-date initializers compute today's date with new Date().toISOString().split("T")[0], which returns the UTC date. The whole app is intentionally Europe/Prague local time (config/env.ts), and Prague is always ahead of UTC. So between ~22:00–24:00 (summer) / ~23:00–24:00 (winter) local, UTC is still the previous day and the form pre-fills yesterday's date for trip_date, shift_date, leave date_from/date_to, invoice issue/tax dates. A user creating an attendance/trip/leave record late in the evening silently gets the wrong day.
|
||||
- **fix:** Replace with a local-date string built from local getters. A correct helper already exists server-side (utils/date.ts localDateStr); add/import an equivalent frontend helper, e.g. `const d=new Date(); const today=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}``, and use it for every "today" default. Note InvoiceDetail.tsx:330 due_date = new Date(Date.now()+14*86400000).toISOString()... has the same issue and should derive from the local issue_date instead.
|
||||
|
||||
### 10. [MEDIUM/needs-judgment] Edit forms round-trip API date strings through new Date().toISOString() instead of string slicing
|
||||
- **dimension:** dates
|
||||
- **where:** src/admin/pages/InvoiceDetail.tsx:481; src/admin/pages/InvoiceDetail.tsx:484; src/admin/pages/InvoiceDetail.tsx:487; src/admin/pages/InvoiceDetail.tsx:658; src/admin/pages/ReceivedInvoices.tsx:373-377
|
||||
- **problem:** When populating a date <input>/AdminDatePicker from an API value, these do new Date(inv.issue_date).toISOString().split("T")[0]. The API value is already a local-time string (Date.toJSON override drops the Z), so new Date() parses it as local, then toISOString() converts back to UTC. For @db.Date values (read back as UTC-midnight → local +1/+2h) this currently lands on the right day in Prague, but it is fragile: it depends on the offset always being positive and the time-of-day being near midnight. The codebase already has the correct, timezone-safe primitive — normalizeDateStr (src/admin/utils/attendanceHelpers.ts:309), which regex-slices the YYYY-MM-DD prefix off the string without ever constructing a Date.
|
||||
- **fix:** Use normalizeDateStr(inv.issue_date) / a string slice for date-only fields instead of routing through new Date().toISOString(). For computedDueDate (InvoiceDetail.tsx:654-659) the date-only UTC math is self-consistent, but switching to plain string/day arithmetic via the same helper removes the latent risk.
|
||||
|
||||
### 11. [MEDIUM/needs-judgment] Raw API datetime string assigned to a native <input type=date> value (mobile blanks the field)
|
||||
- **dimension:** dates
|
||||
- **where:** src/admin/pages/Trips.tsx:140; src/admin/components/AdminDatePicker.tsx:92-96
|
||||
- **problem:** openEditModal sets form.trip_date = trip.trip_date, but trip_date is a @db.Date serialized by the toJSON override as a full datetime string like "2026-06-05T02:00:00" (routes/admin/trips.ts returns the Prisma object directly). On desktop AdminDatePicker uses date-fns parse(val,"yyyy-MM-dd",...) which tolerates the trailing time, so it works. But on touch devices (AdminDatePicker.tsx:127-140) it renders <input type="date" value="2026-06-05T02:00:00">, which is not a valid date-input value — browsers show it blank, so the user appears to have no date and may submit an empty/changed value.
|
||||
- **fix:** Normalize before seeding the form: trip_date: normalizeDateStr(trip.trip_date). More robustly, have AdminDatePicker's NativeInput coerce its value to the date prefix for mode="date" so any caller passing a datetime string is handled.
|
||||
|
||||
### 12. [MEDIUM/needs-judgment] markOverdueInvoices flips invoices to "overdue" on their due date (date-only column vs full now())
|
||||
- **dimension:** dates
|
||||
- **where:** src/services/invoices.service.ts:78-85
|
||||
- **problem:** due_date is a @db.Date column (stored at UTC-midnight, e.g. 2026-06-06T00:00:00Z for "due 2026-06-06"). The query `due_date: { lt: new Date() }` compares it against the current full timestamp. Any time after local midnight on the due day, now() (e.g. 2026-06-06T06:00Z) is already greater than the stored UTC-midnight, so an invoice due *today* is immediately marked overdue. An invoice is normally not overdue until the day after its due date.
|
||||
- **fix:** Compare against local start-of-today, not now(): build today = new Date(y,m,d,0,0,0) from local getters and use `due_date: { lt: today }` (and the reverse branch `gte: today`). This makes the boundary inclusive of the due day. Confirm the intended business rule with the user (due-day inclusive vs exclusive) before changing.
|
||||
|
||||
### 13. [MEDIUM/needs-judgment] Three PDF route files duplicate the same helper set (escapeHtml, formatNum, formatCurrency, formatDate, cleanQuillHtml, DOMPurify bootstrap)
|
||||
- **dimension:** deadcode
|
||||
- **where:** src/routes/admin/invoices-pdf.ts:14; src/routes/admin/invoices-pdf.ts:19; src/routes/admin/invoices-pdf.ts:26; src/routes/admin/invoices-pdf.ts:35; src/routes/admin/invoices-pdf.ts:44; src/routes/admin/orders-pdf.ts:12; src/routes/admin/orders-pdf.ts:34; src/routes/admin/orders-pdf.ts:41; src/routes/admin/orders-pdf.ts:50; src/routes/admin/orders-pdf.ts:59; src/routes/admin/offers-pdf.ts:11; src/routes/admin/offers-pdf.ts:14; src/routes/admin/offers-pdf.ts:22; src/routes/admin/offers-pdf.ts:31; src/routes/admin/offers-pdf.ts:51; src/routes/admin/offers-pdf.ts:61
|
||||
- **problem:** All three PDF generation routes independently define near-identical formatDate, formatNum, escapeHtml, and cleanQuillHtml functions, plus the same `const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window);` bootstrap. The duplication has already caused a real divergence: orders-pdf.ts (formatNum, line 45) uses a regular ASCII space ' ' for the thousands separator, while invoices-pdf.ts (line 30) and offers-pdf.ts (line 26) use a non-breaking space ' '. This is exactly the failure mode duplication creates — the copies drift and produce inconsistent output (orders invoices can line-wrap mid-number where the others won't). cleanQuillHtml/escapeHtml are security-sensitive sanitizers, so divergence here is more than cosmetic.
|
||||
- **fix:** Extract the shared PDF helpers into a single module (e.g. src/utils/pdf-format.ts or extend src/utils/html-to-pdf.ts): escapeHtml, formatNum(value, decimals), formatCurrency, formatDate, cleanQuillHtml, and a shared DOMPurify instance. Import them in all three *-pdf.ts files. Pick one canonical thousands separator (the non-breaking space is correct for print) so output is consistent across invoice/order/offer PDFs.
|
||||
|
||||
### 14. [MEDIUM/safe-auto] English user-facing API error strings in attendance route
|
||||
- **dimension:** i18n
|
||||
- **where:** src/routes/admin/attendance.ts:188; src/routes/admin/attendance.ts:196
|
||||
- **problem:** Two error() responses send raw English to the client: error(reply, "Missing attendance_id", 400) and error(reply, "Missing id", 400). Every other validation/not-found message in this file and across all routes is Czech (e.g. "Záznam nenalezen", "Nedostatečná oprávnění"). error() sends the string straight into the API envelope, so a user hitting these endpoints without the param sees an English message.
|
||||
- **fix:** Replace with Czech equivalents, e.g. "Chybí ID docházky" and "Chybí ID" (or reuse the existing parseId/"Neplatné ID" pattern). Mechanical, no behavior change.
|
||||
|
||||
### 15. [MEDIUM/needs-judgment] Frontend query layer throws English errors that render in the UI
|
||||
- **dimension:** i18n
|
||||
- **where:** src/admin/lib/queries/projects.ts:96; src/admin/lib/queries/projects.ts:102; src/admin/lib/apiAdapter.ts:16; src/admin/lib/apiAdapter.ts:23; src/admin/lib/apiAdapter.ts:27; src/admin/lib/apiAdapter.ts:52; src/admin/lib/apiAdapter.ts:64; src/admin/lib/apiAdapter.ts:68; src/admin/lib/queries/mutations.ts:51; src/admin/lib/queries/mutations.ts:56; src/admin/components/ProjectFileManager.tsx:230
|
||||
- **problem:** The TanStack Query helpers throw new Error with English literals: "Unauthorized", "Invalid JSON response", and `Request failed (${status})`. ProjectFileManager.tsx:230-232 renders filesError.message verbatim (only falling back to the Czech "Nepodařilo se načíst soubory" when message is empty), so on a 401 or non-JSON/unknown-status response the user sees English ("Unauthorized", "Request failed (500)"). ErrorBoundary.tsx:30 likewise renders error.message under a Czech heading. The server-supplied result.error is Czech, but these client-side fallbacks are not. Note projects.ts:94 already does this right with the Czech "Chyba připojení", making the English siblings inconsistent.
|
||||
- **fix:** Czech-ify the user-visible fallbacks: "Unauthorized" -> e.g. "Přihlášení vypršelo" / "Nejste přihlášeni", "Request failed (n)" -> "Požadavek selhal (n)", "Invalid JSON response" -> "Neplatná odpověď serveru". These are user-facing message strings, not error codes, so translating them is safe; just confirm no code branches on the literal message text (none observed).
|
||||
|
||||
### 16. [MEDIUM/needs-judgment] Service-layer logging uses console.* instead of the configured Fastify/pino logger
|
||||
- **dimension:** logging
|
||||
- **where:** src/services/audit.ts:57; src/services/mailer.ts:34; src/services/invoices.service.ts:88; src/services/exchange-rates.ts:47; src/services/leave-notification.ts:120; src/services/invoice-alerts.ts:220; src/services/invoice-alerts.ts:224; src/services/plan.service.ts:168; src/utils/totp.ts:27; src/services/auth.ts:363
|
||||
- **problem:** server.ts:40-41 configures a pino logger (level 'warn' in production, 'info' in dev) and routes correctly use request.log.*/app.log.*. But every service/util logs via console.error/warn/log. These messages bypass pino's structured JSON output, log-level filtering (in production console.log/info still print regardless of the 'warn' level), and any future log transport/aggregation. CLAUDE.md's error-handling guidance explicitly shows app.log.error(e, 'context') as the pattern. invoice-alerts.ts:224 and plan.service.ts:168 in particular emit console.log/console.warn that will print in production despite the configured warn level.
|
||||
- **fix:** Standardize service logging on the Fastify logger. Since services are plain functions without app context, the cleanest fix is to pass the request/logger into service calls that can log, or export a shared logger instance (e.g. the pino instance from the app) that services import. The CLAUDE.md known-issue list already flags 'Mixed error patterns'; this is the logging analogue. If a full refactor is out of scope, at least demote informational console.log calls (invoice-alerts.ts:224) so they don't spam production stdout.
|
||||
|
||||
### 17. [MEDIUM/needs-judgment] markOverdueInvoices swallows DB failure and returns void, so the route treats failure as success
|
||||
- **dimension:** logging
|
||||
- **where:** src/services/invoices.service.ts:76; src/services/invoices.service.ts:87; src/routes/admin/invoices.ts:37
|
||||
- **problem:** markOverdueInvoices() wraps two updateMany calls in try/catch, logs to console.error on failure, and returns nothing. It is invoked from an onRequest hook (invoices.ts:33-39) on every GET (throttled hourly). Because the error is fully swallowed and not surfaced, a persistent DB failure to flip overdue statuses is invisible to the request path and only visible via console (which, per the previous finding, isn't even in the structured log). The throttled best-effort design is reasonable, but the failure should be logged through the Fastify logger that the hook has access to (request.log).
|
||||
- **fix:** Either keep the best-effort behavior but pass request.log into markOverdueInvoices (or log at the hook: wrap the await in try/catch and request.log.error(err, 'markOverdueInvoices failed')), so failures land in the structured production log instead of bare console.error. Do not change it to throw — that would break unrelated GET requests.
|
||||
|
||||
### 18. [MEDIUM/needs-judgment] camelCase 'plan*' files break the kebab-case convention of the backend src/ tree
|
||||
- **dimension:** naming
|
||||
- **where:** src/schemas/planCategory.schema.ts; src/services/planCategory.service.ts; src/utils/planAuditDescription.ts; src/utils/planAuditDescription.test.ts; src/services/planCategory.test.ts
|
||||
- **problem:** The backend src/ tree (excluding src/admin) is kebab-case for 94 of 99 .ts files. Sibling files in the same directories establish the convention clearly: src/schemas uses bank-accounts.schema.ts, received-invoices.schema.ts, scope-templates.schema.ts; src/services uses exchange-rates.ts, nas-file-manager.ts, invoice-alerts.ts; src/utils uses czech-holidays.ts, html-to-pdf.ts. The only 5 camelCase backend files are this 'plan' feature cluster (planCategory.schema.ts, planCategory.service.ts, planAuditDescription.ts plus two test files). Note the same feature's other files DO follow the convention (plan.schema.ts, plan.service.ts), so this is internal inconsistency within one feature, not a sub-convention.
|
||||
- **fix:** Rename to kebab-case to match the directory convention: plan-category.schema.ts, plan-category.service.ts, plan-audit-description.ts (and matching .test.ts files), updating their import paths. Mechanical but touches importers, so verify references after renaming.
|
||||
|
||||
### 19. [MEDIUM/needs-judgment] createInvoice header and items not atomic
|
||||
- **dimension:** prisma
|
||||
- **where:** src/services/invoices.service.ts:345-388
|
||||
- **problem:** invoices.create then a separate invoice_items.createMany with no transaction; a failure leaves a header without items plus a consumed sequence. updateInvoice 469-485, createOrder, createOffer all wrap header and children in a transaction.
|
||||
- **fix:** Wrap both writes in one transaction; move generateInvoiceNumber inside it.
|
||||
|
||||
### 20. [MEDIUM/needs-judgment] N1 in getBelowMinimumItems per-item aggregate in a loop
|
||||
- **dimension:** prisma
|
||||
- **where:** src/services/warehouse.service.ts:232-261; src/services/warehouse.service.ts:199-205
|
||||
- **problem:** getItemTotalStock with item.id called inside the loop; each runs its own sklad_batches aggregate, N1 round trips scaling with the catalog.
|
||||
- **fix:** One sklad_batches groupBy on item_id with is_consumed false summing quantity; build an id to total map; filter in memory.
|
||||
|
||||
### 21. [MEDIUM/manual] useAttendanceAdmin hook bypasses TanStack Query and hand-rolls fetching (with silent catches + race condition)
|
||||
- **dimension:** react
|
||||
- **where:** src/admin/hooks/useAttendanceAdmin.ts:818; src/admin/hooks/useAttendanceAdmin.ts:837; src/admin/hooks/useAttendanceAdmin.ts:866; src/admin/hooks/useAttendanceAdmin.ts:915
|
||||
- **problem:** The whole AttendanceAdmin data layer loads projects, users, attendance records and leave balances with manual apiFetch inside useEffect + useState, instead of the TanStack Query pattern the rest of the app standardizes on (lib/queries/*). Consequences: (a) no caching/dedupe/refetch story consistent with other pages; (b) the load effects swallow errors with empty `catch { /* silent */ }` blocks (lines 827-829, 856-858), which also violates the project's 'never silently swallow errors' rule; (c) fetchData (line 866) re-runs on every month/filterUserId change with no abort or ignore flag, so a slow earlier response can overwrite a newer one — exactly the race the React docs warn about for effect-based fetching. The kept eslint-disable on the deps (line 909) is a symptom of fighting the linter rather than modeling this as a query.
|
||||
- **fix:** Migrate these loads to useQuery options in src/admin/lib/queries/attendance.ts (projectListOptions, attendanceUsersOptions, attendance records keyed by [month,filterUserId], balances keyed by year). That removes all four effects, the manual loading state, the silent catches, and the race condition for free. If a full migration is out of scope now, at minimum add an `ignore`/AbortController guard in fetchData and log the caught errors via the alert/log path instead of empty catches.
|
||||
|
||||
### 22. [MEDIUM/needs-judgment] Array index used as React key on editable, mutable lists
|
||||
- **dimension:** react
|
||||
- **where:** src/admin/components/OrderConfirmationModal.tsx:247; src/admin/pages/OfferDetail.tsx:1500
|
||||
- **problem:** Both lists render rows with controlled inputs and support remove/add (and OfferDetail also reorders) yet key by index. OrderConfirmationModal: items.map((item,i)=><tr key={i}>) with updateItem(i,...) and removeItem via prev.filter((_,i)=>i!==index) (line 88). OfferDetail: sections.map((section,idx)=><div key={idx}>) with delete via prev.filter((_,i)=>i!==idx) (line 1594) and swap-reorder (lines 1540/1567). Per React docs, indices as keys on a list whose order/length changes cause React to reuse the wrong DOM node and component state — here that means after deleting a row the input values/focus shift to the wrong row. This is a genuine correctness bug, not a style nit.
|
||||
- **fix:** Key by a stable id. ConfirmationItem/ScopeSection should carry a stable client id (e.g. crypto.randomUUID() assigned when the row is created, or the server item id when present) and use key={item.id}. Read-only, non-reordering tables (Warehouse recentMovements, WarehouseReports rows) can keep index keys but ideally use the row's domain id.
|
||||
|
||||
### 23. [MEDIUM/needs-judgment] Inconsistent modal implementation: FormModal/ConfirmModal vs hand-rolled overlays with diverging accessibility
|
||||
- **dimension:** react
|
||||
- **where:** src/admin/components/FormModal.tsx:88; src/admin/components/dashboard/DashProfile.tsx:266; src/admin/components/dashboard/DashProfile.tsx:405; src/admin/components/dashboard/DashProfile.tsx:660; src/admin/components/dashboard/DashQuickActions.tsx:321; src/admin/components/BulkAttendanceModal.tsx:47; src/admin/components/ShiftFormModal.tsx:252; src/admin/components/OrderConfirmationModal.tsx:108; src/admin/pages/WarehouseLocations.tsx:339; src/admin/pages/Attendance.tsx:936
|
||||
- **problem:** There are two good reusable modal primitives (FormModal handles body-scroll lock, Esc-to-close, role=dialog/aria-modal/aria-labelledby, focus-grouped footer; ConfirmModal similar), but at least 7 components reimplement the admin-modal-overlay + backdrop + motion markup by hand with inconsistent behavior. DashProfile's three modals (lines 266/405/660) and DashQuickActions (line 321) omit role="dialog", aria-modal, and aria-labelledby entirely; none of the hand-rolled overlays wire Esc-to-close (only FormModal/ConfirmModal do). BulkAttendanceModal/ShiftFormModal/OrderConfirmationModal include the ARIA roles but still lack Esc handling. The result is duplicated markup and an accessibility/UX behavior that varies modal-to-modal.
|
||||
- **fix:** For the smaller content modals (DashProfile edit-profile, 2FA setup/disable, DashQuickActions trip modal) switch to FormModal — they fit its API and would inherit Esc/lock/ARIA. For the large complex forms (ShiftFormModal, BulkAttendanceModal, OrderConfirmationModal) where FormModal's per-child stagger animation is awkward, factor the overlay+backdrop+Esc+ARIA shell into a shared ModalShell component and have these consume it, so a11y/Esc behavior is uniform. At minimum, add role="dialog"/aria-modal/aria-labelledby to the DashProfile/DashQuickActions overlays.
|
||||
|
||||
### 24. [MEDIUM/safe-auto] Raw reply.send({ success: true, ... }) used instead of success()/paginated() helpers
|
||||
- **dimension:** routes
|
||||
- **where:** src/routes/admin/attendance.ts:32; src/routes/admin/attendance.ts:108; src/routes/admin/attendance.ts:118; src/routes/admin/attendance.ts:128; src/routes/admin/attendance.ts:142; src/routes/admin/attendance.ts:165; src/routes/admin/attendance.ts:179; src/routes/admin/attendance.ts:190; src/routes/admin/attendance.ts:203; src/routes/admin/attendance.ts:235; src/routes/admin/trips.ts:73; src/routes/admin/leave-requests.ts:57; src/routes/admin/invoices.ts:62; src/routes/admin/projects.ts:41; src/routes/admin/received-invoices.ts:80; src/routes/admin/customers.ts:100
|
||||
- **problem:** CLAUDE.md explicitly states: 'Use the success() and error() helpers in routes — never write raw reply.send().' Many handlers hand-roll the envelope. The paginated-list cases (attendance.ts:235, trips.ts:73, leave-requests.ts:57, invoices.ts:62, projects.ts:41, received-invoices.ts:80, customers.ts:100) duplicate exactly what paginated(reply, data, meta) produces; the single-object cases (attendance.ts:32,108,118,...) duplicate success(reply, data). This is purely a consistency/maintainability gap (the shapes happen to match today), but it bypasses the central helper, so any future change to the response envelope or status handling won't propagate.
|
||||
- **fix:** Replace the raw `return reply.send({ success: true, data, pagination })` calls with `return paginated(reply, data, buildPaginationMeta(total, page, limit))`, and `return reply.send({ success: true, data })` with `return success(reply, data)`. attendance.ts and customers.ts already import these helpers; trips/leave-requests/invoices/projects/received-invoices import paginated where needed.
|
||||
|
||||
### 25. [MEDIUM/needs-judgment] Session-termination mutations have no audit logging
|
||||
- **dimension:** routes
|
||||
- **where:** src/routes/admin/sessions.ts:80-99; src/routes/admin/sessions.ts:102-127
|
||||
- **problem:** DELETE /sessions/:id (revoke a specific refresh token) and DELETE /sessions?action=all (revoke all other sessions) mutate security-relevant state — they invalidate refresh tokens — but call no logAudit(). CLAUDE.md and the database conventions say data that is created/updated/deleted should be audit-logged, and these are exactly the kind of security events (forced logout / session revocation) that belong in the forensic trail. Every other mutating route in the module logs an audit entry; these two are the notable omissions among security-sensitive endpoints.
|
||||
- **fix:** Add logAudit() calls after the successful update/updateMany in both handlers (e.g. action 'delete' or 'logout', entityType 'session' or 'refresh_token', entityId the session id for the single case), mirroring the audit pattern used in totp.ts and auth.ts for login/logout events.
|
||||
|
||||
### 26. [MEDIUM/needs-judgment] Two competing mutation patterns coexist; ~27 raw apiFetch mutations bypass useApiMutation
|
||||
- **dimension:** rq-data
|
||||
- **where:** src/admin/lib/queries/mutations.ts:88; src/admin/pages/WarehouseReservations.tsx:106; src/admin/pages/WarehouseReservations.tsx:136; src/admin/pages/Invoices.tsx:208; src/admin/pages/Invoices.tsx:234; src/admin/pages/Offers.tsx:222; src/admin/pages/OfferDetail.tsx:734; src/admin/pages/OfferDetail.tsx:757; src/admin/pages/OfferDetail.tsx:782; src/admin/hooks/useAttendanceAdmin.ts:1039
|
||||
- **problem:** The project ships a dedicated useApiMutation hook (mutations.ts) that wraps useMutation + apiFetch + envelope unwrapping + broad invalidation, and it is adopted in 34 files. But 14 files (~27 call sites) still hand-roll the same flow: `const response = await apiFetch(url,{method:...}); const result = await response.json(); if(result.success){ queryClient.invalidateQueries(...); alert.success(...) } else { alert.error(...) } } catch { alert.error('Chyba připojení') }`. This duplicates exactly what useApiMutation centralizes (error throwing as ApiError, success/error branching, invalidation), and the two paths diverge in behavior: useApiMutation throws typed ApiError with .status so callers can branch on HTTP code, whereas the raw path collapses all failures into a generic Czech 'Chyba připojení' string and never exposes status. This is the dominant inconsistency in the data layer. TanStack v5 docs document the useMutation→onSuccess→invalidateQueries flow that useApiMutation implements; the raw path is the non-idiomatic outlier.
|
||||
- **fix:** Standardize new and touched mutations on useApiMutation (pass `invalidate: ["warehouse"]` etc. instead of manual invalidateQueries, and use mutate/mutateAsync's onSuccess/onError for UI side-effects). Migrate the raw-apiFetch mutation sites incrementally, starting with the simplest CRUD pages (WarehouseReservations, Invoices delete/toggleStatus). Document useApiMutation as the canonical mutation entry point in CLAUDE.md's Frontend Conventions so the pattern stops regrowing.
|
||||
|
||||
### 27. [MEDIUM/safe-auto] Broad-domain invalidation convention violated: OfferDetail uses narrow ["offers","list"]
|
||||
- **dimension:** rq-data
|
||||
- **where:** src/admin/pages/OfferDetail.tsx:681; src/admin/pages/OfferDetail.tsx:693; src/admin/pages/OfferDetail.tsx:739; src/admin/pages/OfferDetail.tsx:765; src/admin/pages/OfferDetail.tsx:792; src/admin/pages/Offers.tsx:227
|
||||
- **problem:** CLAUDE.md mandates invalidating the broad domain key (`["offers"]` over `["offers","list"]`) because React Query prefix-matches. OfferDetail.tsx invalidates the narrow key `["offers","list"]` in five handlers (save edit/create, create order, invalidate, delete), while the sibling Offers.tsx (line 227) and CompanySettings.tsx (line 437) correctly invalidate broad `["offers"]`. Consequence: the narrow key does NOT prefix-match the offer-detail cache entry `["offers", id]` (offerDetailOptions, offers.ts:144) nor `["offers","next-number"]`, so after editing an offer the detail query for OTHER offers / next-number stays stale until refetched by other means. The TanStack v5 docs' prefix-match example (`invalidateQueries({queryKey:['projects']})`) is the exact rationale CLAUDE.md cites — OfferDetail is the lone violator.
|
||||
- **fix:** Change the five `["offers","list"]` invalidations in OfferDetail.tsx to broad `["offers"]` to match the convention and the rest of the offers code. (The delete handler additionally removeQueries(["offers",id]) which is fine to keep.) Mechanical and behavior-safe: broadening only marks more inactive queries stale; active ones already refetch.
|
||||
|
||||
### 28. [MEDIUM/manual] useAttendanceAdmin runs a parallel data system instead of query factories / useApiMutation
|
||||
- **dimension:** rq-data
|
||||
- **where:** src/admin/hooks/useAttendanceAdmin.ts:1049; src/admin/hooks/useAttendanceAdmin.ts:1050; src/admin/hooks/useAttendanceAdmin.ts:1121; src/admin/hooks/useAttendanceAdmin.ts:1256; src/admin/hooks/useAttendanceAdmin.ts:1286
|
||||
- **problem:** This 1200+ line hook does its own data orchestration: each mutation does `queryClient.invalidateQueries(["attendance"])` AND `await fetchData(false)` AND `await new Promise(r=>setTimeout(r,300))` to wait for the manual refetch (e.g. lines 1049-1052, 1121-1123). It runs a hand-rolled `fetchData` alongside React Query rather than relying on the attendance.ts queryOptions factories and letting invalidation drive refetch. The fixed 300ms sleep is a race-condition smell (it guesses how long the refetch takes) and the double invalidate+fetchData duplicates work. This is the single largest divergence from the otherwise-consistent data layer.
|
||||
- **fix:** Treat as a larger refactor (out of scope for safe-auto): migrate the hook's reads to the attendance.ts queryOptions factories and its writes to useApiMutation so invalidation alone drives refetch, removing fetchData and the setTimeout(300). At minimum, drop the redundant manual fetchData+sleep where invalidateQueries already covers it. Flag for a dedicated cleanup ticket.
|
||||
|
||||
### 29. [MEDIUM/needs-judgment] Three coercion idioms duplicated ~150+ times instead of shared helpers
|
||||
- **dimension:** schemas
|
||||
- **where:** src/schemas/common.ts (only has parseBody); src/schemas/invoices.schema.ts:5-33; src/schemas/orders.schema.ts:6-27; src/schemas/warehouse.schema.ts:85-219; src/schemas/attendance.schema.ts:19-145; src/schemas/settings.schema.ts:15-62; src/schemas/trips.schema.ts:4-37; src/schemas/vehicles.schema.ts:8-39; src/schemas/bank-accounts.schema.ts:14-34; src/schemas/received-invoices.schema.ts:5-60
|
||||
- **problem:** The same three sub-schemas are copy-pasted across nearly every file: (1) number-from-form `z.union([z.number(), z.string()]).transform((v) => Number(v))`, (2) its nullable form `z.union([z.number(), z.string(), z.null()]).transform((v) => (v === null ? null : Number(v)))`, and (3) boolean-from-form `z.preprocess((v) => v === true || v === 1 || v === '1', z.boolean())`. There are 150+ occurrences. common.ts only exports parseBody — no shared id/number/bool/date primitives exist, even though plan.schema.ts (intFromForm/isoDate) and planCategory.schema.ts (hexColor) already prove the team knows how to factor these out locally. This is the single biggest source of drift: any fix to coercion behavior must be applied in dozens of places.
|
||||
- **fix:** Add shared exports to src/schemas/common.ts, e.g. `numFromForm`, `nullableNumFromForm`, `boolFromForm`, `idFromForm`, `isoDate`, and import them everywhere. Zod 4 (in use here, v4.3.6) provides `z.coerce.number()` and `z.stringbool()` which replace idioms (1) and (3) outright; per Zod 4 docs `z.stringbool()` throws on unrecognized strings (safer than the silent preprocess). Consolidating also lets you fix the NaN bug (next finding) in one spot.
|
||||
|
||||
### 30. [MEDIUM/needs-judgment] Number coercion silently produces NaN (no validation guard in most files)
|
||||
- **dimension:** schemas
|
||||
- **where:** src/schemas/trips.schema.ts:4,12-13; src/schemas/vehicles.schema.ts:8-17,29-34; src/schemas/invoices.schema.ts:26-29,48-52,89-92; src/schemas/settings.schema.ts:15-62; src/schemas/attendance.schema.ts:20-37,90-129; src/schemas/received-invoices.schema.ts:5-6,35-60; src/schemas/bank-accounts.schema.ts:14-18,31-34
|
||||
- **problem:** Most `.transform((v) => Number(v))` coercions have no follow-up refine, so a non-numeric string parses to `NaN` and passes validation. e.g. CreateTripSchema vehicle_id/start_km/end_km (trips.schema.ts:4,12,13) accept garbage as NaN; settings break_threshold_hours, clock_rounding_minutes, max_login_attempts etc. all coerce to NaN silently. Notably this is applied INCONSISTENTLY: orders.schema.ts and offers.schema.ts DO add `.refine((v) => !Number.isNaN(v), ...)` after every numeric transform, and invoices.schema.ts:8-12 throws inside the transform for quantity — so the same project has three different behaviors for the identical concern. NaN then flows into Prisma/business logic.
|
||||
- **fix:** Standardize on one safe numeric primitive (ideally the shared helper from the previous finding) that rejects NaN — e.g. `z.coerce.number()` which natively errors on non-numeric input, or `.refine((v) => !Number.isNaN(v))`. Apply it uniformly so trips/vehicles/settings/attendance match the stricter orders/offers behavior.
|
||||
|
||||
### 31. [MEDIUM/needs-judgment] Email validation applied inconsistently across schemas
|
||||
- **dimension:** schemas
|
||||
- **where:** src/schemas/users.schema.ts:5,21; src/schemas/profile.schema.ts:4; src/schemas/customers.schema.ts (no email field, but); src/schemas/warehouse.schema.ts:30,42; src/schemas/settings.schema.ts:38-41
|
||||
- **problem:** Email fields are validated as proper emails only in users.schema.ts and profile.schema.ts via `z.string().email(...)`. Other schemas that accept email-typed data use plain `z.string().nullish()` with no format check: warehouse supplier `email` (warehouse.schema.ts:30,42), and company-settings `invoice_alert_email`, `leave_notify_email`, `smtp_from` (settings.schema.ts:38-40). The notify/alert emails in settings are used to actually send mail, so an invalid value is a silent operational failure.
|
||||
- **fix:** Apply email-format validation to the email-typed fields in warehouse and settings schemas (e.g. `z.string().email(...).nullish()`, allowing empty/null). Note: Zod 4 prefers the top-level `z.email()` over the now-deprecated `z.string().email()`; consider migrating the existing users/profile usages too for consistency.
|
||||
|
||||
### 32. [MEDIUM/needs-judgment] Services return error with no status, forcing routes to hardcode or cast the HTTP code
|
||||
- **dimension:** svc-errors
|
||||
- **where:** src/services/attendance.service.ts:376; src/routes/admin/attendance.ts:50; src/routes/admin/projects.ts:73; src/routes/admin/quotations.ts:286
|
||||
- **problem:** Many service functions return an error object with NO status field, while the documented convention is error plus status. Routes compensate inconsistently: attendance hardcodes the status at the call site (400 at attendance.ts:50, 404 at :70 for the same shape), and projects/quotations cast result.status with as-any. The same conceptual error yields 400 from one route and 404 from another by call-site choice, not service intent.
|
||||
- **fix:** Make every error path return error plus status. Then collapse route call sites to the uniform check already used by plan.ts, removing the as-any casts.
|
||||
|
||||
### 33. [MEDIUM/needs-judgment] String-sentinel error values decoded by routes instead of self-describing error plus status
|
||||
- **dimension:** svc-errors
|
||||
- **where:** src/services/invoices.service.ts:393; src/services/offers.service.ts:231; src/services/projects.service.ts:149; src/routes/admin/invoices.ts:165
|
||||
- **problem:** updateInvoice, deleteProject and updateOffer return machine-codes as the error string (not_found, has_order, invalidated) without a status. The Czech message and HTTP status are reconstructed in the route via if/else chains ending in a fall-through 500 Neznama chyba. This splits one entity error vocabulary across two files and is easy to desync.
|
||||
- **fix:** Return the final Czech message plus status directly, as updateOrder/createOffer already do. The route then needs only the uniform one-line check and the 500 fall-throughs disappear.
|
||||
|
||||
### 34. [MEDIUM/needs-judgment] Duplicated and contradictory `PaginationMeta` / pagination shape (3 definitions)
|
||||
- **dimension:** ts-safety
|
||||
- **where:** src/types/index.ts:85; src/admin/lib/apiAdapter.ts:33; src/admin/hooks/usePaginatedQuery.ts:8
|
||||
- **problem:** The pagination response shape is declared three times with diverging fields. The server type `PaginationMeta` (types/index.ts:85) has `page, limit, per_page, total, total_pages`. The frontend `PaginationMeta` (apiAdapter.ts:33) drops `limit` entirely (`total, page, per_page, total_pages`). A third inline `PaginatedResult.pagination` (usePaginatedQuery.ts:8-16) re-declares the same fields again. These are independent definitions that can drift; the missing `limit` on the frontend copy means a consumer expecting the server contract is silently incompatible.
|
||||
- **fix:** Pick one canonical `PaginationMeta` (the server one in types/index.ts is the contract) and have the frontend import/derive from it, or at minimum collapse apiAdapter.ts and usePaginatedQuery.ts onto a single shared interface so the `limit` discrepancy is resolved and can't drift.
|
||||
|
||||
### 35. [MEDIUM/needs-judgment] Missing return types on ~47 of 107 exported service functions force `as any` casts in routes
|
||||
- **dimension:** ts-safety
|
||||
- **where:** src/services/projects.service.ts:95; src/routes/admin/projects.ts:73; src/routes/admin/projects.ts:106; src/routes/admin/quotations.ts:286; src/services/users.service.ts:59; src/services/offers.service.ts:161; src/services/invoices.service.ts:339
|
||||
- **problem:** Roughly 47 of 107 exported `async function`s in src/services have no explicit return type and rely on inference. For functions like `updateProject` (projects.service.ts:95) the inferred type is a union of `null | { error, status } | <prismaRow>`; after `"error" in result` narrowing the row branch still has no `status`, so route handlers reach for `(result as any).status ?? 400` (projects.ts:73, projects.ts:106, quotations.ts:286) to read a field the compiler can't guarantee. The `any` cast erases all type checking on the result at exactly the error-handling boundary. The standard `{ data } | { error, status }` service contract documented in CLAUDE.md is not enforced because the return type is left implicit.
|
||||
- **fix:** Annotate service functions with an explicit discriminated return type (e.g. a shared `ServiceResult<T> = { data: T } | { error: string; status: number }`, or `Result<T>` like plan.service.ts:387 already defines). With a uniform `status` on the error branch, the `(result as any).status` casts in routes can be deleted and become type-safe. This is the systemic root cause of the route-level casts.
|
||||
|
||||
### 36. [MEDIUM/needs-judgment] Heavy `any` in usePlanWork mutations plus mutation-object monkey-patching (`(createEntry as any)._rolled`)
|
||||
- **dimension:** ts-safety
|
||||
- **where:** src/admin/hooks/usePlanWork.ts:235; src/admin/hooks/usePlanWork.ts:241; src/admin/hooks/usePlanWork.ts:261; src/admin/hooks/usePlanWork.ts:273; src/admin/hooks/usePlanWork.ts:322; src/admin/hooks/usePlanWork.ts:355; src/admin/hooks/usePlanWork.ts:388; src/admin/hooks/usePlanWork.ts:430; src/admin/hooks/usePlanWork.ts:457; src/admin/hooks/usePlanWork.ts:478
|
||||
- **problem:** The plan-work optimistic-update hook is the single densest `any` site in the frontend (20 occurrences). Mutation `mutationFn`/`onSuccess` bodies and vars are typed `any` (e.g. `(body: any)`, `(data: any, body: any)`), and rollback state is stored by mutating the mutation object: `(createEntry as any)._rolled = rolled` (and 5 more `_rolled` writes). `qc.getQueryData<GridData>(currentGridKey as any)` also casts the typed query key away. This defeats type safety on the optimistic-update path where cell-patching correctness matters most, and the `_rolled` side-channel is invisible to the type system, so a typo in the property name would silently break rollback.
|
||||
- **fix:** Type the mutation bodies with the request DTOs (the plan entry/override create/update shapes already exist in schemas/ and lib/queries/plan.ts) and `onSuccess` data with the API response type. Replace the `(mutation as any)._rolled` side-channel with React Query's `onMutate`/context return value (the supported, fully-typed rollback mechanism), which removes the casts.
|
||||
|
||||
### 37. [LOW/safe-auto] Configured @/* path alias is unused and not wired into the Vite/vitest build
|
||||
- **dimension:** config-structure
|
||||
- **where:** tsconfig.app.json:19-22; tsconfig.server.json:16-19; vite.config.ts:4-32; vitest.config.ts:5-14
|
||||
- **problem:** Both tsconfig.app.json and tsconfig.server.json declare baseUrl:'.' with paths {'@/*':['src/*']}, but a search for imports from '@/' across src returns zero matches — the alias is dead config. Worse, if someone did adopt it, vite.config.ts and vitest.config.ts define no matching resolve.alias, so TypeScript would resolve it but the Vite client build and Vitest would fail at runtime. The codebase consistently uses relative imports instead.
|
||||
- **fix:** Either remove the baseUrl/paths block from both tsconfigs to avoid implying an alias convention the bundler does not support, or commit to it by adding the matching resolve.alias in vite.config.ts/vitest.config.ts and migrating imports. Removal is the lower-risk option given current usage.
|
||||
|
||||
### 38. [LOW/needs-judgment] package.json db:push / db:pull scripts contradict the documented migration golden rule
|
||||
- **dimension:** config-structure
|
||||
- **where:** package.json:16-17; CLAUDE.md
|
||||
- **problem:** CLAUDE.md states the golden rule 'NEVER use prisma db push' (it bypasses migration history and causes drift), yet package.json exposes "db:push": "prisma db push" (and "db:pull": "prisma db pull") as first-class npm scripts, which invites exactly the prohibited workflow. The documented schema-change path is prisma migrate dev, which has no script alias.
|
||||
- **fix:** Remove the db:push (and likely db:pull) scripts, or rename/guard them so they can't be run casually; add a db:migrate script wrapping `prisma migrate dev` to match the documented workflow.
|
||||
|
||||
### 39. [LOW/needs-judgment] Cross-boundary import of a server util by the client is inconsistent and structurally fragile
|
||||
- **dimension:** config-structure
|
||||
- **where:** src/admin/utils/attendanceHelpers.ts:1; src/admin/hooks/useAttendanceAdmin.ts:4; src/utils/czech-holidays.ts:1-8; tsconfig.server.json:21-30
|
||||
- **problem:** src/admin code imports getHolidays/isHoliday from the server-side util src/utils/czech-holidays via '../../utils/czech-holidays'. This is the ONLY place server logic is genuinely shared with the client; every other shared concern (formatters, label maps, EntityType) is duplicated instead, so the sharing strategy is inconsistent. It also reaches across the build boundary: tsconfig.server.json compiles src/utils into the server bundle while Vite separately bundles the same file into the client. It works today only because czech-holidays has no Node-only dependencies (it imports just ./date). If czech-holidays ever pulls in a Node API (fs, crypto, prisma), the client build breaks silently.
|
||||
- **fix:** Decide on one strategy: either introduce a dedicated src/shared/ (or src/common/) module for genuinely isomorphic helpers like czech-holidays and date formatters, referenced by both builds with an explicit boundary, or duplicate intentionally. Avoid ad-hoc src/admin -> src/utils relative imports that silently couple the two bundles.
|
||||
|
||||
### 40. [LOW/safe-auto] .env.example has drifted from the variables actually read in config/env.ts
|
||||
- **dimension:** config-structure
|
||||
- **where:** .env.example:1-32; src/config/env.ts:55-110
|
||||
- **problem:** config/env.ts reads several env vars absent from .env.example: TOTP_ALGORITHM, TOTP_DIGITS, TOTP_PERIOD, LOGIN_TOKEN_EXPIRY_MINUTES, NAS_FINANCIALS_PATH, NAS_OFFERS_PATH, SMTP_FROM_NAME, INVOICE_ALERT_EMAIL, RATE_LIMIT_MAX/WINDOW/LOGIN/TOTP/REFRESH, and TRUST_PROXY. All have defaults so nothing breaks, but the example file no longer documents the full configuration surface, making prod tuning (rate limits, trust proxy) undiscoverable.
|
||||
- **fix:** Add the missing optional variables (with their default values as comments) to .env.example so it stays a complete reference for config/env.ts.
|
||||
|
||||
### 41. [LOW/manual] Inconsistent badge/class naming scheme (admin- prefix dropped)
|
||||
- **dimension:** css
|
||||
- **where:** src/admin/components.css:142; src/admin/components.css:146; src/admin/components.css:150; src/admin/components.css:154; src/admin/attendance.css:333; src/admin/invoices.css:24; src/admin/invoices.css:70
|
||||
- **problem:** Class naming is inconsistent within the single global namespace. Most badges use admin-badge-* (admin-badge-order-prijata, admin-badge-invoice-paid), but the leave-status badges in components.css:142-154 are bare badge-pending/badge-approved/badge-rejected/badge-cancelled, and attendance.css reuses bare badge-vacation/sick/holiday/unpaid. invoices.css mixes three schemes in one file: admin-badge-invoice-* (:5), invoice-month-* (:24), and received-upload-* (:70). Because all CSS is global, these bare badge-* names risk collision and make the convention ambiguous (admin-* for shared vs feature-prefix for page-local).
|
||||
- **fix:** Document and enforce one rule: shared/reusable components use admin-*, page-local elements use a feature prefix (already done for plan-*, dash-*, fm-*). Rename bare badge-* to admin-badge-* (or feature-prefix them) — coordinate the matching className strings in the TSX. Not safe-auto because it requires synchronized TSX edits.
|
||||
|
||||
### 42. [LOW/needs-judgment] Defined-but-unused CSS variables (dead tokens)
|
||||
- **dimension:** css
|
||||
- **where:** src/admin/variables.css:27; src/admin/variables.css:34; src/admin/variables.css:14; src/admin/variables.css:15; src/admin/variables.css:26
|
||||
- **problem:** Several tokens are declared but never referenced anywhere in *.css: --gradient-subtle (variables.css:27), --transition-slow (:34), --space-10 (:14) and --space-12 (:15). Additionally --gradient (:26) is used only once (attendance.css:220) and is just a duplicate literal of --accent-color (#d63031), so it is a redundant alias rather than a real gradient token. These are dead/redundant and add noise to the token system.
|
||||
- **fix:** Remove the unused tokens, or wire them up if intended. For --gradient, either point attendance.css:220 at var(--accent-color) and delete --gradient, or rename it to something meaningful. Verify against TSX inline styles before deleting (grep showed no CSS consumers).
|
||||
|
||||
### 43. [LOW/needs-judgment] Empty responsive.css stub imported into the bundle
|
||||
- **dimension:** css
|
||||
- **where:** src/admin/responsive.css:1; src/admin/AdminApp.tsx:22
|
||||
- **problem:** responsive.css contains only a 6-line comment ('reserved for responsive rules that span multiple components') and no rules, yet is imported at AdminApp.tsx:22. All responsive media queries actually live in their per-feature files (forms.css, layout.css, components.css, etc.), so the file is dead. It is harmless but misleading — a reader may expect cross-cutting breakpoints to live here.
|
||||
- **fix:** Either delete the file and its import, or actually consolidate the repeated breakpoints here. Note there is no shared breakpoint token: 480/640/768/1024 recur across ~15 files as raw px (e.g. forms.css:293-312, components.css, layout.css). If kept, this file is the natural place to at least document the canonical breakpoint set.
|
||||
|
||||
### 44. [LOW/safe-auto] plan.css imported twice
|
||||
- **dimension:** css
|
||||
- **where:** src/admin/AdminApp.tsx:26; src/admin/pages/PlanWork.tsx:18
|
||||
- **problem:** plan.css is imported globally in AdminApp.tsx:26 (alongside all other stylesheets) and again in PlanWork.tsx:18. Since AdminApp already loads it globally, the second import is redundant. The bundler de-dupes so there is no runtime double-application, but it is inconsistent — no other page re-imports its own CSS (e.g. WarehousePage does not re-import warehouse.css), so this is an outlier that suggests uncertainty about the loading model.
|
||||
- **fix:** Remove the import at PlanWork.tsx:18 to match the convention that all admin CSS is loaded once in AdminApp.tsx. Low risk since the global import already covers it.
|
||||
|
||||
### 45. [LOW/needs-judgment] getCzechDate week number uses a non-ISO local formula that disagrees with the plan module's ISO week
|
||||
- **dimension:** dates
|
||||
- **where:** src/admin/utils/dashboardHelpers.ts:75-78; src/admin/pages/PlanWork.tsx:61-69
|
||||
- **problem:** The dashboard header (getCzechDate) computes "Týden N" with a homegrown formula: Math.ceil(((now - Jan1)/86400000 + Jan1.getDay() + 1)/7) using local getters. This is not ISO-8601 (ISO weeks start Monday; week 1 is the week containing the first Thursday) and is also locale-dependent via getDay(). PlanWork.tsx:61-69 implements a correct ISO-8601 week (Thursday-anchored, UTC). For dates near year boundaries the two will display different week numbers for the same day, an internal inconsistency users can notice.
|
||||
- **fix:** Extract PlanWork's isoWeekNumber into a shared util and reuse it in getCzechDate so the week number is computed one consistent (ISO) way across the UI.
|
||||
|
||||
### 46. [LOW/needs-judgment] Two divergent conventions for writing @db.Date columns (UTC-midnight vs local-noon)
|
||||
- **dimension:** dates
|
||||
- **where:** src/routes/admin/trips.ts:234; src/routes/admin/trips.ts:294; src/services/invoices.service.ts:362-364; src/services/attendance.service.ts:1176; src/services/attendance.service.ts:1227-1234
|
||||
- **problem:** Date-only (@db.Date) columns are written two different ways. Trips and invoices do new Date(String(body.x)) where body.x is "YYYY-MM-DD" → UTC-midnight. Attendance constructs new Date(year,month,day,12,0,0) → local noon. Both currently store the correct date in Prague only because the local offset is always positive and 12:00 local is comfortably inside the day in UTC. The local-noon form is the robust one (immune to offset sign and DST edges); the UTC-midnight form is the fragile one. Mixing them is an inconsistency that invites a future off-by-one if anyone copies the wrong pattern or the deployment TZ ever changes.
|
||||
- **fix:** Standardize on one convention for @db.Date writes — prefer the local-noon construction (or a single shared helper like dateOnly("YYYY-MM-DD")) and use it in trips/invoices too. Behavior is unchanged for Prague today, so this is a consistency/robustness cleanup, not an urgent fix.
|
||||
|
||||
### 47. [LOW/needs-judgment] escapeHtml is defined six times across the codebase
|
||||
- **dimension:** deadcode
|
||||
- **where:** src/routes/admin/invoices-pdf.ts:35; src/routes/admin/orders-pdf.ts:50; src/routes/admin/offers-pdf.ts:51; src/services/invoice-alerts.ts:18; src/services/leave-notification.ts:21; src/admin/hooks/useAttendanceAdmin.ts:341
|
||||
- **problem:** There are six separate definitions of an escapeHtml(str) function. Five escape &,<,>," identically; the sixth (useAttendanceAdmin.ts:341) additionally escapes the single quote ('). They are used for HTML email bodies, PDF templates, and print HTML — all contexts where consistent escaping matters. The subtle difference (one escapes the apostrophe, the others don't) is the kind of inconsistency that hides XSS/output bugs.
|
||||
- **fix:** Move escapeHtml into a single shared util (server-side src/utils, plus one for the frontend, or share via a common module). Standardize on the stricter variant that also escapes the single quote. Replace the six local copies with imports.
|
||||
|
||||
### 48. [LOW/safe-auto] formatDate duplicated between two frontend util files
|
||||
- **dimension:** deadcode
|
||||
- **where:** src/admin/utils/formatters.ts:20; src/admin/utils/attendanceHelpers.ts:24
|
||||
- **problem:** formatters.ts exports `formatDate(dateStr)` => `d.toLocaleDateString('cs-CZ')` with a '—' fallback, and attendanceHelpers.ts exports an identical `formatDate` (same body, same '—' fallback). Both are imported across the app, so two names resolve to the same logic in different modules — a maintenance hazard if one is changed.
|
||||
- **fix:** Keep the canonical formatDate in formatters.ts and have attendanceHelpers re-export or import it instead of redefining. Update attendanceHelpers consumers to the shared one.
|
||||
|
||||
### 49. [LOW/safe-auto] Dead export: previewPattern() in numbering.service.ts
|
||||
- **dimension:** deadcode
|
||||
- **where:** src/services/numbering.service.ts:343
|
||||
- **problem:** `previewPattern(pattern, prefix, code)` is exported but has zero references anywhere in src (verified by grep across .ts/.tsx). It is the only public function in the numbering service with no callers; all sibling preview/generate functions are used.
|
||||
- **fix:** Remove previewPattern, or wire it into the settings UI/route that previews a numbering pattern if that was its intent. As-is it is dead code.
|
||||
|
||||
### 50. [LOW/safe-auto] Dead export: usersQuery + planKeys.users() in plan query module
|
||||
- **dimension:** deadcode
|
||||
- **where:** src/admin/lib/queries/plan.ts:111; src/admin/lib/queries/plan.ts:95
|
||||
- **problem:** `usersQuery()` (plan.ts:111) is exported but never imported or used by any component/page. Its query key `planKeys.users()` (plan.ts:95) is referenced only by usersQuery itself. The `/api/admin/plan/users` endpoint string appears only inside this dead query (the PlanWork grid gets its users from the grid payload instead). So the frontend query, its key entry, and the `users: () => ['plan','users']` key are an orphaned cluster. (The backend route src/routes/admin/plan.ts:63 still exists and was not assessed as dead from the server side.)
|
||||
- **fix:** Remove usersQuery and the planKeys.users key entry. Separately confirm whether the backend GET /plan/users route still has any consumer; if not, it can be removed too.
|
||||
|
||||
### 51. [LOW/needs-judgment] Dead export: getMonthlyWorkFund() in czech-holidays.ts
|
||||
- **dimension:** deadcode
|
||||
- **where:** src/utils/czech-holidays.ts:95
|
||||
- **problem:** `getMonthlyWorkFund(...)` is exported but has zero references across src (verified by grep). Sibling exports getHolidays/isHoliday/getBusinessDaysInMonth are all used; this one is not.
|
||||
- **fix:** Remove getMonthlyWorkFund, or use it where monthly work-fund hours are currently computed inline (e.g. attendance.service.ts computes fund hours as `getBusinessDaysInMonth(...) * 8` in several places — that inline math is what this helper appears intended to replace).
|
||||
|
||||
### 52. [LOW/needs-judgment] Unused file: ReservationPicker.tsx
|
||||
- **dimension:** deadcode
|
||||
- **where:** src/admin/components/warehouse/ReservationPicker.tsx:11
|
||||
- **problem:** The whole file (54 lines, default export ReservationPicker) has no importers anywhere in the project — grep for 'ReservationPicker' returns only self-references inside the file. The sibling warehouse pickers (ItemPicker, BatchPicker, SupplierSelect, LocationSelect) are all imported and used; this one is an orphan.
|
||||
- **fix:** Delete src/admin/components/warehouse/ReservationPicker.tsx, or wire it into the warehouse issue/reservation flow if it was intended for an unfinished feature.
|
||||
|
||||
### 53. [LOW/safe-auto] Inconsistent Czech phrasing for "not found" (nenalezen vs nebyl nalezen)
|
||||
- **dimension:** i18n
|
||||
- **where:** src/routes/admin/project-files.ts:61; src/routes/admin/project-files.ts:73; src/routes/admin/project-files.ts:92; src/routes/admin/project-files.ts:112; src/routes/admin/project-files.ts:165; src/routes/admin/project-files.ts:228; src/routes/admin/project-files.ts:270; src/services/warehouse.service.ts:967; src/services/warehouse.service.ts:1021; src/routes/admin/projects.ts:56
|
||||
- **problem:** Two phrasings express the same concept. The dominant, compact form "nenalezen/nenalezena/nenalezeno" appears ~92 times across routes/services; the verbose form "nebyl/nebyla nalezen*" appears ~16 times (all of project-files.ts plus warehouse.service.ts reservations/inventory). The clash is sometimes on the identical entity: projects.ts:56 "Projekt nenalezen" vs project-files.ts:61 "Projekt nebyl nalezen"; warehouse routes "Kategorie nenalezena"/"Dodavatel nenalezen" vs warehouse.service.ts "Rezervace nebyla nalezena"/"Inventarizace nebyla nalezena". Same product, two wordings for the same 404.
|
||||
- **fix:** Standardize on the dominant compact form ("Projekt nenalezen", "Soubor nenalezen", "Složka nenalezena", "Rezervace nenalezena", "Inventarizace nenalezena"). Pure string normalization, no logic change. Low priority polish.
|
||||
|
||||
### 54. [LOW/needs-judgment] parseBody leaks default English Zod messages for validators without a custom message
|
||||
- **dimension:** i18n
|
||||
- **where:** src/schemas/common.ts:12; src/schemas/received-invoices.schema.ts:27; src/schemas/attendance.schema.ts:25; src/schemas/leave-requests.schema.ts:4; src/schemas/offers.schema.ts:92; src/schemas/orders.schema.ts:93; src/schemas/attendance.schema.ts:8; src/schemas/plan.schema.ts:42; src/schemas/auth.schema.ts:26
|
||||
- **problem:** parseBody (common.ts:12) joins each Zod issue's .message and returns it directly as the user-facing API error. Fields with explicit Czech messages (e.g. .min(1, "Název je povinný")) are fine, but validators relying on Zod defaults emit English to the user: z.enum([...]) without a message -> "Invalid enum value..."; .max(500) on note/address -> "String must contain at most 500 character(s)"; TOTP secret/code .min(1) (auth.schema.ts:26-33) -> "String must contain at least 1 character(s)". Most are hard for a normal user to trigger (enum values come from dropdowns), but the length caps on free-text note/address fields are reachable.
|
||||
- **fix:** Add Czech messages to the user-reachable validators (the free-text .max() caps and any enum a user could submit), or centralize a Czech errorMap on the Zod instance so defaults are Czech globally. Lower urgency for purely internal enums/tokens. Treat as needs-judgment because deciding which validators are user-reachable requires per-field review.
|
||||
|
||||
### 55. [LOW/safe-auto] Best-effort frontend background calls swallow errors silently with .catch(() => {})
|
||||
- **dimension:** logging
|
||||
- **where:** src/admin/pages/Attendance.tsx:235; src/admin/pages/Attendance.tsx:238; src/admin/pages/InvoiceDetail.tsx:778
|
||||
- **problem:** Three fire-and-forget calls (reverse-geocode address update, and post-save PDF pre-generation) use '.catch(() => {})' with no logging. These are genuinely non-critical side effects, so failing silently is a defensible product choice, but the empty handler gives no breadcrumb when the address never updates or the PDF isn't pre-generated. Unlike the rest of the frontend, which consistently surfaces errors via alert.error with a Czech fallback, these are invisible.
|
||||
- **fix:** Add a console.warn (or a debug-level log) in the catch so the swallow is intentional-and-traceable rather than fully silent, e.g. '.catch((e) => console.warn("address update failed", e))'. No user-facing alert is warranted for these background ops.
|
||||
|
||||
### 56. [LOW/needs-judgment] plan.ts query factories use '*Query' suffix instead of the established '*Options' convention
|
||||
- **dimension:** naming
|
||||
- **where:** src/admin/lib/queries/plan.ts:98; src/admin/lib/queries/plan.ts:111
|
||||
- **problem:** Across src/admin/lib/queries, 55 query factories use the '*Options' suffix (userListOptions, orderListOptions, attendanceBalancesOptions, planCategoriesOptions, etc.). plan.ts itself uses planCategoriesOptions correctly, but then defines gridQuery (line 98) and usersQuery (line 111) with a '*Query' suffix instead. These are the only two '*Query'-suffixed factories in the whole queries directory, so the names read as a different kind of thing than they are (they are queryOptions() factories identical in shape to the *Options ones).
|
||||
- **fix:** Rename gridQuery -> planGridOptions and usersQuery -> planUsersOptions for parity with the surrounding 55 *Options factories. Both are used inside the same module/feature, so the blast radius is small.
|
||||
|
||||
### 57. [LOW/needs-judgment] '.service.ts' suffix applied to only half of service files, with two borderline cases
|
||||
- **dimension:** naming
|
||||
- **where:** src/services/exchange-rates.ts; src/services/system-settings.ts; src/services/numbering.service.ts
|
||||
- **problem:** Of 20 files in src/services, exactly 10 carry the '.service.ts' suffix and 10 do not. The split largely tracks a sensible distinction (entity CRUD services like invoices.service.ts / users.service.ts are suffixed; infra/integration helpers like mailer.ts, audit.ts, nas-*-manager.ts, leave-notification.ts are not), so this is not pure randomness. However the boundary is fuzzy: exchange-rates.ts (exports getRate/toCzk) and system-settings.ts (exports getSystemSettings) are read/query services that resemble the suffixed group but lack the suffix, while numbering.service.ts is suffixed despite being a low-level sequence helper. A reader cannot rely on the suffix to predict a file's role.
|
||||
- **fix:** Document the intended rule in CLAUDE.md (e.g. '*.service.ts = entity business-logic services; bare name = infra/integration helpers') and rename the borderline files to match it, OR drop the suffix entirely since the directory name 'services/' already conveys the role. Either way pick one rule; do not leave it implicit.
|
||||
|
||||
### 58. [LOW/needs-judgment] queryKey helper naming: only 'plan' defines a 'planKeys' key-factory object; other domains inline keys
|
||||
- **dimension:** naming
|
||||
- **where:** src/admin/lib/queries/plan.ts:87
|
||||
- **problem:** plan.ts introduces a dedicated planKeys object (all/grid/entries/overrides/users) to centralize query keys, which is a good pattern. But it is the only domain in src/admin/lib/queries that does so; every other module (users.ts, orders.ts, invoices.ts, trips.ts, etc.) inlines its queryKey arrays directly inside each *Options factory. The result is two coexisting key-management styles with no documented reason, so a contributor cannot tell which pattern to follow when adding a query.
|
||||
- **fix:** Decide on one approach: either adopt the planKeys-style key-factory object per domain (more robust against typos and easier invalidation), or treat planKeys as a deliberate exception and note it. Low priority — purely a consistency/discoverability issue, no behavior impact.
|
||||
|
||||
### 59. [LOW/needs-judgment] getInvoiceStats walks the dataset four times with sequential per-invoice currency conversion
|
||||
- **dimension:** prisma
|
||||
- **where:** src/services/invoices.service.ts:247-256; src/services/invoices.service.ts:284-297
|
||||
- **problem:** sumCzk awaits toCzk per invoice in a loop, called three times plus a fourth VAT loop; serializes many awaits. Cached so it is await overhead not network.
|
||||
- **fix:** Pre-fetch the rate map once and convert synchronously, or resolve conversions together. Low priority.
|
||||
|
||||
### 60. [LOW/needs-judgment] getBalances runs a sequential leave_balances query per user
|
||||
- **dimension:** prisma
|
||||
- **where:** src/services/attendance.service.ts:490-504; src/services/attendance.service.ts:944-946
|
||||
- **problem:** Loops users running leave_balances findFirst each; getPrintData already uses one findMany for the year then a map, so this is inconsistent.
|
||||
- **fix:** One findMany filtered by user_id in the list and year; index by user_id.
|
||||
|
||||
### 61. [LOW/needs-judgment] enrich and body handlers typed as any, dropping Prisma types
|
||||
- **dimension:** prisma
|
||||
- **where:** src/services/orders.service.ts:41; src/services/offers.service.ts:49; src/services/invoices.service.ts:339; src/services/invoices.service.ts:391; src/services/projects.service.ts:95
|
||||
- **problem:** enrichOrder and enrichQuotation and several handlers take any, losing the types Prisma generates for includes and mapped rows; code otherwise strict TS, deriving a getPayload type at attendance.service.ts 23-28.
|
||||
- **fix:** Type enrich inputs with the Prisma getPayload helper; tighten bodies to existing input interfaces.
|
||||
|
||||
### 62. [LOW/needs-judgment] Server data synced into form state via useEffect instead of derived/key-reset (accepted-but-not-ideal)
|
||||
- **dimension:** react
|
||||
- **where:** src/admin/pages/InvoiceDetail.tsx:371; src/admin/pages/InvoiceDetail.tsx:454; src/admin/pages/OfferDetail.tsx:383; src/admin/pages/OfferDetail.tsx:428; src/admin/pages/CompanySettings.tsx:256; src/admin/pages/Settings.tsx:213
|
||||
- **problem:** Multiple pages copy query data into local form state inside an effect, guarded by a one-shot ref/flag (formInitializedRef / dataReady / sysFormInitialized) or a derived-default merge (InvoiceDetail:371, OfferDetail:383 adjust currency/vat from companySettings on prop change). The React 'You Might Not Need an Effect' guidance explicitly lists 'adjusting/resetting state on prop change in an Effect' as an anti-pattern (causes an extra render with stale data) and recommends either computing during render or resetting state with a `key`. The flag-guarded population effects are the commonly-accepted compromise for editable forms seeded from server data, so this is low severity, but it is the same family of effect the docs steer away from.
|
||||
- **fix:** Where feasible, prefer resetting form state by giving the editor a key (e.g. key={id} on the detail component) so a fresh mount re-seeds state without an effect, and compute the companySettings-derived defaults (currency/vat) during render rather than patching state in an effect. Treat as cleanup, not a blocker — the current guards prevent the worst (re-clobbering user edits).
|
||||
|
||||
### 63. [LOW/manual] 2FA/profile state prop-drilled through DashProfile (18 props)
|
||||
- **dimension:** react
|
||||
- **where:** src/admin/components/dashboard/DashProfile.tsx:10; src/admin/components/dashboard/DashProfile.tsx:40
|
||||
- **problem:** DashProfile receives 18 props, ~14 of which are a single concern: the 2FA enrollment/disable flow state and its setters (totpEnabled, totpLoading, totpSubmitting, totpSecret, totpQrUri, totpCode/setTotpCode, backupCodes/setBackupCodes, show2FASetup/setShow2FASetup, show2FADisable/setShow2FADisable, disableCode/setDisableCode, plus onStart/onConfirm/onDisable callbacks). This is all owned by the Dashboard parent and threaded down, making the component signature brittle and the 2FA logic split across two files.
|
||||
- **fix:** Encapsulate the 2FA flow in a dedicated hook (e.g. use2FA()) colocated with DashProfile, or move the 2FA modals fully into DashProfile and have it own that state. The parent then passes only totpEnabled (or nothing). This is a maintainability refinement, not a bug.
|
||||
|
||||
### 64. [LOW/safe-auto] Minor: derived-state effect in ItemPicker resets activeIndex via useEffect
|
||||
- **dimension:** react
|
||||
- **where:** src/admin/components/warehouse/ItemPicker.tsx:48
|
||||
- **problem:** The effect at line 48 watches [items, activeIndex] to reset the highlighted index when the result list shrinks. This is derived state maintained through an effect (the docs' 'you might not need an effect' territory) and introduces an extra render cycle; it also lists activeIndex in deps while setting it, which is benign here only because of the guard. Low impact — the component otherwise correctly uses refs for keyboard nav.
|
||||
- **fix:** Clamp activeIndex during render (e.g. const safeActive = activeIndex >= items.length ? -1 : activeIndex) or reset it in the same handler that changes the search/items rather than reacting in an effect. Optional cleanup.
|
||||
|
||||
### 65. [LOW/safe-auto] Inconsistent numeric ID parsing — raw parseInt instead of the parseId helper
|
||||
- **dimension:** routes
|
||||
- **where:** src/routes/admin/trips.ts:192-193; src/routes/admin/trips.ts:264-265; src/routes/admin/trips.ts:338-339; src/routes/admin/sessions.ts:84-85
|
||||
- **problem:** response.ts exports parseId(raw, reply) specifically to centralize param-id parsing (it rejects NaN and id<=0 with a uniform 400 'Neplatné ID'). Most files use it, but trips.ts and sessions.ts hand-roll `parseInt(...,10)` + `isNaN` checks. Besides the duplication, the hand-rolled versions accept id <= 0 (e.g. 0 or negative) because they only check isNaN, whereas parseId also rejects id <= 0 — a subtle behavioral divergence. Error messages also differ ('Neplatné ID vozidla', 'Neplatné ID relace' vs the helper's 'Neplatné ID').
|
||||
- **fix:** Replace the parseInt/isNaN blocks with `const id = parseId(request.params.id, reply); if (id === null) return;` (trips.ts uses request.params.id / vehicleId; keep a tailored message only if the distinct wording is desired). This unifies the <=0 rejection and the 400 response shape.
|
||||
|
||||
### 66. [LOW/needs-judgment] Several not-found / precondition errors in project-files.ts fall back to default 400 instead of an explicit status
|
||||
- **dimension:** routes
|
||||
- **where:** src/routes/admin/project-files.ts:68; src/routes/admin/project-files.ts:69; src/routes/admin/project-files.ts:88; src/routes/admin/project-files.ts:114; src/routes/admin/project-files.ts:124; src/routes/admin/project-files.ts:138; src/routes/admin/project-files.ts:179; src/routes/admin/project-files.ts:202; src/routes/admin/project-files.ts:229; src/routes/admin/project-files.ts:241; src/routes/admin/project-files.ts:279
|
||||
- **problem:** Within the same file, downloadFile-not-found correctly returns error(reply, 'Soubor nebyl nalezen', 404) (line 73) and listFiles folder-not-found returns 404 (line 92), but the parallel 'Projekt nemá číslo projektu' (88,114,229), required-path messages (68,279), and fm-returned-error passthroughs (138,202,241) all omit the status and silently use the helper's default 400. Most are genuinely validation/precondition (400 is fine), but 'Projekt nemá číslo projektu' is a state precondition inconsistently a 400 here vs config-missing cases returning 500, and the omitted statuses make intent unclear. Consistency/clarity issue, not a correctness bug.
|
||||
- **fix:** Pass an explicit status to each error() call so the intended HTTP semantics are visible and uniform (400 for client validation, 404/409/422 for state preconditions as appropriate). At minimum make the 'Projekt nemá číslo projektu' and required-path messages explicit rather than relying on the default.
|
||||
|
||||
### 67. [LOW/safe-auto] Redundant non-null assertions on parseBody result (body.data!) in plan.ts
|
||||
- **dimension:** routes
|
||||
- **where:** src/routes/admin/plan.ts:170; src/routes/admin/plan.ts:194; src/routes/admin/plan.ts:238-242; src/routes/admin/plan.ts:267; src/routes/admin/plan.ts:319; src/routes/admin/plan.ts:361
|
||||
- **problem:** plan.ts writes `const body = parseBody(...); if ('error' in body) return ...; ... body.data!`. parseBody returns `{ data: T } | { error: string }` (schemas/common.ts:3-6), so after the `'error' in body` guard TypeScript already narrows body to `{ data: T }` and `.data` is non-null. Every other route file uses the cleaner `const parsed = parseBody(...); if ('error' in parsed) return ...; const body = parsed.data;` form without the `!`. The `!` is harmless but inconsistent and signals (falsely) that data might be nullable.
|
||||
- **fix:** Adopt the prevailing pattern: bind `const parsed = parseBody(...)`, guard, then `const body = parsed.data` without the non-null assertion, matching customers.ts / warehouse.ts / attendance.ts.
|
||||
|
||||
### 68. [LOW/needs-judgment] usePlanWork re-implements the gridQuery factory inline with untyped apiFetch parsing
|
||||
- **dimension:** rq-data
|
||||
- **where:** src/admin/hooks/usePlanWork.ts:87; src/admin/lib/queries/plan.ts:98
|
||||
- **problem:** plan.ts exports a `gridQuery(dateFrom,dateTo,view)` queryOptions factory (line 98) that uses jsonQuery<GridData> for type-safe envelope handling. usePlanWork.ts:87 ignores it and inlines its own useQuery with `apiFetch(...).then(r=>r.json().then((b:any)=>b.data as GridData))` — duplicating the URL construction, skipping jsonQuery's `!response.ok || !result.success` error check (so a backend `{success:false}` silently yields undefined data instead of throwing), and using `b:any`. The planKeys factory is reused for the key, but the queryFn diverges. This is the only place a query bypasses the apiAdapter.
|
||||
- **fix:** Replace the inline useQuery body with the existing gridQuery factory: `useQuery({ ...gridQuery(isoDate(range.from), isoDate(range.to), view), placeholderData: keepPreviousData })`. Restores jsonQuery's error handling and removes the `any`. Low risk but should be eyeballed since the hook also reads this query's cache key elsewhere (key is unchanged, so cache stays compatible).
|
||||
|
||||
### 69. [LOW/safe-auto] Duplicate require2FAOptions factory (dead copy in dashboard.ts) and unused deprecated systemSettingsOptions alias
|
||||
- **dimension:** rq-data
|
||||
- **where:** src/admin/lib/queries/dashboard.ts:12; src/admin/lib/queries/settings.ts:82; src/admin/lib/queries/settings.ts:80
|
||||
- **problem:** `require2FAOptions` is defined identically in two query files — dashboard.ts:12 and settings.ts:82 — both with the same key `["settings","2fa"]` and same URL. Both consumers (Dashboard.tsx:10, Settings.tsx:14) import the settings.ts copy, so the dashboard.ts copy is dead code. Because keys match it is not a cache-collision bug, but two sources of truth for one query is a maintenance hazard (edit one, miss the other). Separately, settings.ts:80 exports a `/** @deprecated */ systemSettingsOptions = systemInfoOptions` alias that has no importers (only systemInfoOptions is used).
|
||||
- **fix:** Delete the duplicate require2FAOptions from dashboard.ts:12 (keep the settings.ts canonical one). Delete the unused deprecated systemSettingsOptions alias at settings.ts:80. Both are confirmed unreferenced by grep, so removal is mechanical and behavior-free.
|
||||
|
||||
### 70. [LOW/needs-judgment] Inconsistent filter-key serialization across list query factories
|
||||
- **dimension:** rq-data
|
||||
- **where:** src/admin/lib/queries/invoices.ts:129; src/admin/lib/queries/invoices.ts:157; src/admin/lib/queries/trips.ts:40; src/admin/lib/queries/warehouse.ts:194; src/admin/lib/queries/projects.ts:45
|
||||
- **problem:** List factories are inconsistent in how the filters object becomes part of the query key. Most spread the raw filters object directly (invoices.ts:129 `["invoices","list",filters]`; warehouse, projects, offers, audit-log do the same), but trips.ts:40 and invoices received (invoices.ts:157) instead spell out an explicit object literal of the same fields. Functionally both work (React Query hashes the key deterministically and ignores object key order), but the inconsistency is gratuitous: the explicit form silently drops any new filter field that isn't manually listed, whereas the spread form auto-includes it. Not a bug today, just a divergence and a latent footgun for the spelled-out ones.
|
||||
- **fix:** Pick one convention (spreading the filters object is the simpler, more future-proof choice) and apply it uniformly. Low priority — cosmetic consistency, no behavior change. Verify each endpoint's filters object contains only key-relevant fields before spreading.
|
||||
|
||||
### 71. [LOW/needs-judgment] Wrong TOTP code does not increment failed-login attempts (relies on rate limit only)
|
||||
- **dimension:** security
|
||||
- **where:** src/routes/admin/auth.ts:160-163; src/services/system-settings.ts
|
||||
- **problem:** In the /login/totp handler, an invalid TOTP code returns 'Neplatný TOTP kód' (line 161-163) without touching failed_login_attempts or locked_until. The password stage (auth.ts service) and the backup-code endpoint (totp.ts:315-335) both implement lockout, but the primary TOTP step does not. The only protection against TOTP brute force after a valid login_token is the per-minute rate limit (config.rateLimit.loginTotp, default 5/min). The login_token lives 5 minutes and a fresh one can be re-minted by re-submitting the password, so a determined attacker who has the password gets a sustained ~5 guesses/minute against a 6-digit (1M) space without ever tripping account lockout.
|
||||
- **fix:** On invalid TOTP code in /login/totp, increment failed_login_attempts inside a transaction and set locked_until when it reaches max_login_attempts, mirroring the backup-verify logic. This makes the second factor enforce the same lockout policy as the first.
|
||||
|
||||
### 72. [LOW/needs-judgment] Server-side PDF endpoints return attacker-influenceable HTML as same-origin text/html
|
||||
- **dimension:** security
|
||||
- **where:** src/routes/admin/invoices-pdf.ts:1076; src/routes/admin/offers-pdf.ts:764; src/routes/admin/invoices-pdf.ts:521; src/routes/admin/offers-pdf.ts:357
|
||||
- **problem:** In non-save mode, the invoices-pdf and offers-pdf routes render the full document HTML and send it with reply.type('text/html').send(html) directly to the browser (not application/pdf). The notes/scope content is user-controlled rich text. It IS sanitized (DOMPurify.sanitize wrapped by cleanQuillHtml), so this is defense-in-depth rather than an open hole, but serving same-origin HTML built from user data is fragile: any future regression in the sanitizer, or any unescaped interpolation added to these large templates, becomes stored XSS on the app origin. The production CSP (security.ts:24-36) does mitigate inline script, but these PDF responses are served by the same Fastify app and inherit that origin.
|
||||
- **fix:** Prefer returning application/pdf (render via htmlToPdf) to the client instead of raw HTML, as the orders-pdf route already does (orders-pdf.ts:889-892). If an HTML preview must be served, consider a Content-Disposition or a sandboxed delivery path. At minimum, keep the DOMPurify + cleanQuillHtml layering and avoid adding any non-escapeHtml interpolation of DB/user fields into these templates.
|
||||
|
||||
### 73. [LOW/needs-judgment] Scope/notes rich-text is sanitized only at render time, never on write
|
||||
- **dimension:** security
|
||||
- **where:** src/routes/admin/invoices-pdf.ts:521; src/routes/admin/orders-pdf.ts:409; src/admin/pages/InvoiceDetail.tsx:1206; src/admin/pages/OrderDetail.tsx:687
|
||||
- **problem:** Invoice notes and quotation/order scope HTML are stored raw in the DB and sanitized at every read/render site (3 PDF routes + 2 frontend render sites). This is consistent and currently complete, but it means correctness depends on every present and future consumer remembering to sanitize. Any new feature that renders these fields (e.g. an email body, a new export, an admin preview) without DOMPurify reintroduces stored XSS. Sanitizing on write would make the stored value safe-by-default for all consumers.
|
||||
- **fix:** Consider sanitizing rich-text scope/notes once on the write path (in the quotations/orders/invoices create+update services or Zod transforms) so stored data is already clean, treating render-time sanitization as defense-in-depth. Not urgent given current coverage is complete; flagging so the invariant is documented and enforced centrally.
|
||||
|
||||
### 74. [LOW/needs-judgment] HSTS header omits preload and is gated entirely on APP_ENV=production
|
||||
- **dimension:** security
|
||||
- **where:** src/middleware/security.ts:18-22; src/middleware/security.ts:23-36
|
||||
- **problem:** Strict-Transport-Security is set to 'max-age=31536000; includeSubDomains' without 'preload', and both HSTS and the full CSP are only emitted when config.isProduction (APP_ENV==='production'). The max-age/includeSubDomains is good, but without preload the first-visit TLS-strip window remains. More notably, all CSP protection is absent in any non-production deployment (e.g. a staging box on real DNS), so the same app code runs without script-src/frame-ancestors restrictions there.
|
||||
- **fix:** Add 'preload' to the HSTS value if the domain is (or will be) submitted to the preload list. Consider emitting at least a baseline CSP and the security headers in non-local non-production environments too, so staging/preprod is not left unprotected.
|
||||
|
||||
### 75. [LOW/needs-judgment] TOTP backup-code comparison does not stop at first match (minor timing/clarity)
|
||||
- **dimension:** security
|
||||
- **where:** src/routes/admin/totp.ts:307-312
|
||||
- **problem:** The backup-code verify loop runs bcrypt.compare against every stored hash and records matchIndex but never breaks, so it always performs all 8 comparisons. This is intentional-looking constant-time behavior, but the loop also lets a later match overwrite an earlier one and does an unnecessary 8x bcrypt work per attempt. With bcryptCost=12, 8 comparisons per submission under a 5/min rate limit is a small but real CPU amplification, and the non-break pattern is easy to misread. The CLAUDE.md error-handling rule is not violated here; this is a robustness nit.
|
||||
- **fix:** Either document that the full-scan is deliberate constant-time, or break on first match. Given backup codes are unique random values, breaking on match is safe and reduces bcrypt load; combine with the existing lockout to keep brute-force resistance.
|
||||
|
||||
### 76. [LOW/safe-auto] Error-message language mixed Czech/English within schemas
|
||||
- **dimension:** schemas
|
||||
- **where:** src/schemas/orders.schema.ts:9,16,26,37,45,71,81,106; src/schemas/offers.schema.ts:9,16,26,37,56,87; src/schemas/invoices.schema.ts:10,19 (thrown Error strings)
|
||||
- **problem:** Project convention is Czech for user-facing messages. Most schemas follow this, but orders.schema.ts and offers.schema.ts mix English `{ message: 'Must be a valid number' }` (orders:9,16,26,37,71,81,106; offers:9,16,26,37,56,87) alongside Czech `'Musí být platné číslo'` (orders:55,60; offers:47) in the SAME file for the same validation. parseBody surfaces issue.message directly to the client (common.ts:12), so end users can see the English strings. invoices.schema.ts:10,19 also throw English `'Invalid quantity'`/`'Invalid unit_price'`.
|
||||
- **fix:** Translate the English validation messages to Czech to match the rest of the codebase (e.g. 'Musí být platné číslo'). If a shared numeric helper is introduced (finding 1), it can carry one canonical Czech message and eliminate the divergence.
|
||||
|
||||
### 77. [LOW/safe-auto] Inline route schemas use Zod-3-deprecated .strict()/.passthrough()
|
||||
- **dimension:** schemas
|
||||
- **where:** src/routes/admin/audit-log.ts:15-20; .strict(); src/routes/admin/orders-pdf.ts:15-30; .passthrough()
|
||||
- **problem:** The only two object-mode modifiers in the codebase use the Zod 3 forms `.strict()` (audit-log.ts:20) and `.passthrough()` (orders-pdf.ts:30). Per the Zod 4 changelog (the project is on zod ^4.3.6) these are deprecated in favor of the top-level `z.strictObject({...})` and `z.looseObject({...})`. They still work but are flagged for removal and are inconsistent with a Zod-4 codebase.
|
||||
- **fix:** Migrate to `z.strictObject({ days: ..., confirm: ... })` and `z.looseObject({ items: ... })` respectively. Mechanical, no behavior change.
|
||||
|
||||
### 78. [LOW/needs-judgment] No schemas use strict object mode — unknown keys silently stripped everywhere
|
||||
- **dimension:** schemas
|
||||
- **where:** src/schemas/common.ts:8 (schema.parse, default strip); all src/schemas/*.schema.ts object definitions
|
||||
- **problem:** Every body schema is a default `z.object(...)`, which strips unknown keys silently. Only audit-log.ts uses `.strict()`. For mutation endpoints this means a client typo (e.g. `is_activ` instead of `is_active`) is silently dropped rather than rejected, masking client bugs. This is a deliberate-tradeoff call (lenient APIs are sometimes intentional), so flagged as low, but the near-total absence of strictness combined with the broad Create/Update surface is worth a conscious decision rather than an accident.
|
||||
- **fix:** Decide on a policy: either keep lenient (document it) or adopt `z.strictObject` for Create/Update bodies to catch client mistakes early. If adopting strict, do it via the shared pattern so it is uniform; watch for fields the frontend sends but the schema omits (audit before flipping).
|
||||
|
||||
### 79. [LOW/needs-judgment] Duplicated ScopeSection/Item sub-schemas across offers/orders/scope-templates
|
||||
- **dimension:** schemas
|
||||
- **where:** src/schemas/offers.schema.ts:3-39 (QuotationItemSchema, ScopeSectionSchema); src/schemas/orders.schema.ts:3-39 (OrderItemSchema, OrderSectionSchema); src/schemas/scope-templates.schema.ts:3-11 (ScopeSectionSchema); src/schemas/invoices.schema.ts:3-34 (InvoiceItemSchema)
|
||||
- **problem:** QuotationItemSchema (offers:3-28) and OrderItemSchema (orders:3-28) are byte-for-byte identical. OrderSectionSchema (orders:30-39), ScopeSectionSchema (offers:30-39) and ScopeSectionSchema (scope-templates:3-11) are the same shape (title/title_cz/content/position) duplicated three times. These line/quote/section structures are the same domain concept reimplemented per file, so a change to e.g. position validation must be made in 3-4 places.
|
||||
- **fix:** Extract a shared `LineItemSchema` and `ScopeSectionSchema` (e.g. in common.ts or a schemas/shared.ts) and import them. Note invoices.schema.ts:6-12 deliberately diverges (throws on quantity<=0), so keep that one specialized or make the shared schema configurable.
|
||||
|
||||
### 80. [LOW/needs-judgment] buildApp and token helpers duplicated instead of reusing helpers.ts
|
||||
- **dimension:** tests part2b
|
||||
- **where:** src/__tests__/helpers.ts:7; src/__tests__/warehouse.test.ts:26; src/__tests__/plan.test.ts:649
|
||||
- **problem:** helpers.ts exports buildApp for auth and totp routes only. warehouse.test.ts and plan.test.ts each redefine their own buildApp, generateToken, and auth header helpers with slightly different setup, since warehouse adds securityHeaders and helpers does not. The token-minting and app-bootstrap logic now lives in three places and will drift, and a token minted wrong in one file is not caught by the others.
|
||||
- **fix:** Extract a shared buildApp that takes routes and options plus one token and auth-header helper into helpers.ts and import everywhere, then re-run the full suite since it changes test bootstrap.
|
||||
|
||||
### 81. [LOW/safe-auto] Test named soft delete actually asserts a hard delete that its own comment flags as buggy
|
||||
- **dimension:** tests part2b
|
||||
- **where:** src/__tests__/warehouse.test.ts:630; src/__tests__/warehouse.test.ts:637
|
||||
- **problem:** The test titled deactivates an item soft delete asserts a 404 after delete. Its own comment at lines 636 to 638 notes that the route hard-deletes the row and calls this inconsistent with the supplier soft-delete pattern, so the misleading name hides the discrepancy from future readers.
|
||||
- **fix:** Rename the test to hard-deletes an item, and if soft-delete is the intended contract convert it to a todo or expected-fail test documenting the desired behaviour. Confirm the decision with the team.
|
||||
|
||||
### 82. [LOW/needs-judgment] `Record<string, any>` / untyped record builders in attendance PDF/HTML construction
|
||||
- **dimension:** ts-safety
|
||||
- **where:** src/admin/hooks/useAttendanceAdmin.ts:350; src/admin/hooks/useAttendanceAdmin.ts:382; src/admin/hooks/useAttendanceAdmin.ts:397; src/admin/hooks/useAttendanceAdmin.ts:598; src/services/offers.service.ts:49; src/services/orders.service.ts:41
|
||||
- **problem:** Several HTML/PDF/total-calculation builders take `Record<string, any>` and iterate with `(log: any)`/`(i: any)` (useAttendanceAdmin buildUserSectionHtml/recordsByDate; offers `enrichQuotation`, orders `enrichOrder`). These produce HTML that is interpolated into PDF/print output, so an `any`-typed field that is unexpectedly an object or undefined can render `[object Object]` or `NaN` totals with no compile-time signal. Lower severity than the auth bug because output is internal documents, but it is the broadest untyped surface after the plan stack.
|
||||
- **fix:** Define narrow input interfaces for the attendance record and quotation/order item shapes (the Prisma row types or the existing schemas can be reused) and replace the `Record<string, any>` parameters. At minimum type the `.map`/`.reduce` callbacks (`i`, `log`) with the item type to catch field-name and numeric-coercion mistakes.
|
||||
|
||||
### 83. [LOW/safe-auto] `category: input.category as any` casts bypass the Prisma category column type
|
||||
- **dimension:** ts-safety
|
||||
- **where:** src/services/plan.service.ts:451; src/services/plan.service.ts:518; src/services/plan.service.ts:639; src/services/plan.service.ts:710
|
||||
- **problem:** Four `create`/`update` calls cast `input.category` (a plain `string`) to `any` to satisfy the Prisma `category` column type. Validity is enforced at runtime via `assertActiveCategory` (a DB lookup), so it's not unsafe in practice, but the `as any` discards the compiler's check and would also silence a future schema type change for this column.
|
||||
- **fix:** If the Prisma column is an enum, cast to that specific enum type (e.g. `Prisma.$Enums.<Name>`) instead of `any`; if it is a `String` column, the cast is unnecessary and can be removed. Either way avoid `as any` so the field stays type-checked.
|
||||
|
||||
### 84. [LOW/manual] `request.authData!` non-null assertions: acceptable post-auth pattern (no action)
|
||||
- **dimension:** ts-safety
|
||||
- **where:** src/routes/admin/attendance.ts:30; src/middleware/auth.ts:44; src/routes/admin/plan.ts:119; src/routes/admin/warehouse.ts:1066; src/routes/admin/quotations.ts:139
|
||||
- **problem:** Non-null assertions are widespread but almost entirely `request.authData!` inside handlers guarded by `requirePermission`/`requireAuth`, plus `result.error!`/`result.status!` after an `"error" in result` narrowing. These are correct given the middleware contract; the Fastify `authData` is declared optional on the request type but is always populated after the auth preHandler. Flagging only to note it was reviewed and is intentional, not a defect.
|
||||
- **fix:** No change required. If you want to eliminate the `authData!` assertions, declare an `AuthenticatedRequest` type (or a module augmentation making `authData` required) for routes mounted behind the auth hook, so the `!` becomes unnecessary. Optional, cosmetic.
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "1.9.0",
|
||||
"version": "1.9.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "app-ts",
|
||||
"version": "1.9.0",
|
||||
"version": "1.9.7",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "1.9.0",
|
||||
"version": "1.9.7",
|
||||
"description": "",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Re-add the projects.create permission (removed in commit 82919d3 when manual
|
||||
-- project creation was deleted). Idempotent: re-running is a no-op.
|
||||
-- Mirrors prisma/seed.ts PERMISSIONS exactly (name, display_name, module, description).
|
||||
|
||||
-- 1. Insert the permission (INSERT IGNORE skips on duplicate name).
|
||||
INSERT IGNORE INTO `permissions` (`name`, `display_name`, `module`, `description`, `created_at`) VALUES
|
||||
('projects.create', 'Vytvořit projekt', 'projects', 'Ručně vytvářet projekty', NOW());
|
||||
|
||||
-- 2. Grant it to the admin role (idempotent via composite PK).
|
||||
INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`)
|
||||
SELECT r.id, p.id
|
||||
FROM `roles` r
|
||||
CROSS JOIN `permissions` p
|
||||
WHERE r.name = 'admin'
|
||||
AND p.name IN ('projects.create');
|
||||
@@ -172,6 +172,12 @@ const PERMISSIONS: {
|
||||
module: "projects",
|
||||
description: "Prohlížet seznam projektů",
|
||||
},
|
||||
{
|
||||
name: "projects.create",
|
||||
display_name: "Vytvořit projekt",
|
||||
module: "projects",
|
||||
description: "Ručně vytvářet projekty",
|
||||
},
|
||||
{
|
||||
name: "projects.edit",
|
||||
display_name: "Upravit projekt",
|
||||
|
||||
@@ -5,18 +5,20 @@ import { config } from "../config/env";
|
||||
|
||||
describe("auth service", () => {
|
||||
describe("verifyAccessToken", () => {
|
||||
it("returns null and logs error for invalid JWT", async () => {
|
||||
it("returns null WITHOUT logging for an invalid JWT (expected condition)", async () => {
|
||||
const consoleSpy = vi
|
||||
.spyOn(console, "error")
|
||||
.mockImplementation(() => {});
|
||||
const result = await verifyAccessToken("invalid-token");
|
||||
expect(result).toBeNull();
|
||||
expect(consoleSpy).toHaveBeenCalled();
|
||||
expect(consoleSpy.mock.calls[0][0]).toMatch(/JWT verification error/);
|
||||
// Invalid/expired access tokens are an expected condition (the client
|
||||
// refreshes on the resulting 401), so verifyAccessToken deliberately
|
||||
// does NOT log them as errors — only genuinely unexpected failures.
|
||||
expect(consoleSpy).not.toHaveBeenCalled();
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("returns null for expired JWT", async () => {
|
||||
it("returns null WITHOUT logging for an expired JWT", async () => {
|
||||
const consoleSpy = vi
|
||||
.spyOn(console, "error")
|
||||
.mockImplementation(() => {});
|
||||
@@ -27,7 +29,7 @@ describe("auth service", () => {
|
||||
);
|
||||
const result = await verifyAccessToken(expiredToken);
|
||||
expect(result).toBeNull();
|
||||
expect(consoleSpy).toHaveBeenCalled();
|
||||
expect(consoleSpy).not.toHaveBeenCalled();
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
142
src/__tests__/manual-create.test.ts
Normal file
142
src/__tests__/manual-create.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { createProject } from "../services/projects.service";
|
||||
import { createOrder } from "../services/orders.service";
|
||||
|
||||
const createdProjectIds: number[] = [];
|
||||
const createdOrderIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of createdProjectIds)
|
||||
await prisma.projects.deleteMany({ where: { id } });
|
||||
for (const id of createdOrderIds)
|
||||
await prisma.orders.deleteMany({ where: { id } });
|
||||
createdProjectIds.length = 0;
|
||||
createdOrderIds.length = 0;
|
||||
await prisma.number_sequences.deleteMany({ where: { type: "shared" } });
|
||||
});
|
||||
|
||||
const baseOrder = {
|
||||
status: "prijata" as const,
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
vat_rate: 21,
|
||||
apply_vat: true,
|
||||
exchange_rate: 1,
|
||||
};
|
||||
|
||||
describe("createOrder (manual, optional linked project)", () => {
|
||||
it("creates an order AND a project sharing one number when create_project=true", async () => {
|
||||
const res = await createOrder({
|
||||
...baseOrder,
|
||||
scope_title: "Ruční zakázka",
|
||||
create_project: true,
|
||||
});
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
expect(res.project_id).toBeTruthy();
|
||||
const project = await prisma.projects.findUnique({
|
||||
where: { id: res.project_id! },
|
||||
});
|
||||
if (project) createdProjectIds.push(project.id);
|
||||
expect(project?.project_number).toBe(res.order_number);
|
||||
expect(project?.order_id).toBe(res.id);
|
||||
});
|
||||
|
||||
it("creates only the order when create_project=false", async () => {
|
||||
const res = await createOrder({ ...baseOrder, create_project: false });
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
expect(res.project_id).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("shared pool coherence (tracking)", () => {
|
||||
it("order → standalone project → order produce three distinct shared numbers", async () => {
|
||||
const o1 = await createOrder({ ...baseOrder, create_project: true });
|
||||
if ("id" in o1) {
|
||||
createdOrderIds.push(o1.id);
|
||||
if (o1.project_id) createdProjectIds.push(o1.project_id);
|
||||
}
|
||||
const p = await createProject({ name: "Mezi-projekt", status: "aktivni" });
|
||||
if ("project_number" in p) createdProjectIds.push(p.id);
|
||||
const o2 = await createOrder({ ...baseOrder, create_project: false });
|
||||
if ("id" in o2) createdOrderIds.push(o2.id);
|
||||
|
||||
const n1 = "id" in o1 ? o1.order_number : null;
|
||||
const np = "project_number" in p ? p.project_number : null;
|
||||
const n2 = "id" in o2 ? o2.order_number : null;
|
||||
expect(new Set([n1, np, n2]).size).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createProject (manual, standalone)", () => {
|
||||
it("assigns a shared number and is not linked to an order", async () => {
|
||||
const result = await createProject({
|
||||
name: "Test projekt",
|
||||
status: "aktivni",
|
||||
});
|
||||
expect("project_number" in result).toBe(true);
|
||||
if (!("project_number" in result)) return;
|
||||
createdProjectIds.push(result.id);
|
||||
expect(typeof result.project_number).toBe("string");
|
||||
expect(result.project_number!.length).toBeGreaterThan(0);
|
||||
expect(result.order_id).toBeNull();
|
||||
});
|
||||
|
||||
it("gives consecutive standalone projects distinct numbers", async () => {
|
||||
const a = await createProject({ name: "Projekt A", status: "aktivni" });
|
||||
const b = await createProject({ name: "Projekt B", status: "aktivni" });
|
||||
if ("project_number" in a) createdProjectIds.push(a.id);
|
||||
if ("project_number" in b) createdProjectIds.push(b.id);
|
||||
expect("project_number" in a && "project_number" in b).toBe(true);
|
||||
if ("project_number" in a && "project_number" in b) {
|
||||
expect(a.project_number).not.toBe(b.project_number);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("createOrder with price line item + attachment", () => {
|
||||
it("stores a single line item with the entered price", async () => {
|
||||
const res = await createOrder({
|
||||
...baseOrder,
|
||||
create_project: false,
|
||||
items: [
|
||||
{
|
||||
description: "Práce",
|
||||
quantity: 1,
|
||||
unit_price: 12345,
|
||||
is_included_in_total: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
const items = await prisma.order_items.findMany({
|
||||
where: { order_id: res.id },
|
||||
});
|
||||
expect(items.length).toBe(1);
|
||||
expect(Number(items[0].unit_price)).toBe(12345);
|
||||
});
|
||||
|
||||
it("stores an uploaded PO attachment", async () => {
|
||||
const buf = Buffer.from("%PDF-1.4 fake");
|
||||
const res = await createOrder(
|
||||
{ ...baseOrder, create_project: false },
|
||||
buf,
|
||||
"po.pdf",
|
||||
);
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
const order = await prisma.orders.findUnique({
|
||||
where: { id: res.id },
|
||||
select: { attachment_name: true, attachment_data: true },
|
||||
});
|
||||
expect(order?.attachment_name).toBe("po.pdf");
|
||||
expect(order?.attachment_data).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -434,3 +434,22 @@
|
||||
color: var(--text-muted);
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
Mobile (responsive)
|
||||
============================================================================ */
|
||||
|
||||
/* The Leaflet map at a fixed 400px dominates a phone viewport — let it scale
|
||||
with the viewport height (with sensible min/max) on small screens. */
|
||||
@media (max-width: 640px) {
|
||||
.attendance-location-map {
|
||||
height: clamp(220px, 45vh, 400px);
|
||||
}
|
||||
}
|
||||
|
||||
/* The clock card's 2rem padding crushes content at ~360px — tighten it. */
|
||||
@media (max-width: 480px) {
|
||||
.attendance-clock-card {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,7 +265,7 @@ img {
|
||||
border-radius: var(--border-radius-sm);
|
||||
background: var(--bg-tertiary);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--danger-color);
|
||||
color: var(--danger);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
|
||||
@@ -221,6 +221,8 @@
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
backdrop-filter: blur(2px);
|
||||
-webkit-backdrop-filter: blur(2px);
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
@@ -247,6 +249,14 @@
|
||||
padding: 18px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.admin-modal-heading {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-modal-title {
|
||||
@@ -255,6 +265,45 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.admin-modal-subtitle {
|
||||
margin: 2px 0 0;
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.admin-modal-close {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
color: var(--text-muted);
|
||||
border-radius: var(--border-radius-sm);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background var(--motion-fast) ease,
|
||||
color var(--motion-fast) ease,
|
||||
border-color var(--motion-fast) ease,
|
||||
transform var(--motion-fast) ease;
|
||||
}
|
||||
|
||||
.admin-modal-close:hover:not(:disabled) {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-color);
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.admin-modal-close:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.admin-modal-body {
|
||||
padding: 18px;
|
||||
overflow-y: auto;
|
||||
@@ -269,10 +318,45 @@
|
||||
border-top: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
justify-content: flex-end;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.admin-modal-footer-left,
|
||||
.admin-modal-footer-right {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.admin-modal-footer-right {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.admin-modal-footer {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.admin-modal-footer-left,
|
||||
.admin-modal-footer-right {
|
||||
width: 100%;
|
||||
}
|
||||
.admin-modal-footer-left .admin-btn,
|
||||
.admin-modal-footer-right .admin-btn {
|
||||
flex: 1;
|
||||
}
|
||||
.admin-modal-footer-left {
|
||||
order: 2;
|
||||
}
|
||||
.admin-modal-footer-right {
|
||||
order: 1;
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.admin-modal-overlay {
|
||||
padding: 0;
|
||||
@@ -526,6 +610,25 @@
|
||||
0 0 0 1px var(--border-color);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.admin-tabs {
|
||||
display: flex;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.admin-tabs::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin-tab {
|
||||
flex: 0 0 auto;
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
Empty State
|
||||
============================================================================ */
|
||||
@@ -761,7 +864,9 @@
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.admin-kpi-grid {
|
||||
.admin-kpi-grid,
|
||||
.admin-kpi-4,
|
||||
.admin-kpi-3 {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -989,37 +1094,44 @@
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
/* Compact 2-up filter grid instead of a tall full-width column:
|
||||
the search box spans the row; the filter selects / date pickers sit
|
||||
two-per-row; the reset button spans the row. Touch sizing (44px height +
|
||||
16px font from forms.css) is unchanged — this just halves the vertical
|
||||
footprint of multi-filter bars on phones. */
|
||||
.admin-search-bar {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.admin-search-bar .admin-form-input,
|
||||
.admin-search-bar .admin-form-select {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.admin-search-bar .react-datepicker-wrapper {
|
||||
max-width: 100%;
|
||||
/* Search box spans the full row (handles both the .admin-search wrapper
|
||||
and a bare text input used directly as the search field). */
|
||||
.admin-search-bar > .admin-search,
|
||||
.admin-search-bar > .admin-form-input:not([type="date"]) {
|
||||
flex: 1 1 100%;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.admin-search {
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* Filters (status/supplier selects, native date inputs, datepicker
|
||||
wrappers): two per row. */
|
||||
.admin-search-bar > .admin-form-select,
|
||||
.admin-search-bar > .admin-form-input[type="date"],
|
||||
.admin-search-bar > .react-datepicker-wrapper {
|
||||
flex: 1 1 calc(50% - 0.25rem);
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* Action buttons (e.g. "Zrušit filtry") span the full row. */
|
||||
.admin-search-bar > .admin-btn {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.admin-search-bar .admin-form-input,
|
||||
.admin-search-bar .admin-form-select {
|
||||
min-width: 100%;
|
||||
}
|
||||
|
||||
.admin-search-bar .react-datepicker-wrapper {
|
||||
min-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
Item Picker (Warehouse)
|
||||
============================================================================ */
|
||||
@@ -1099,3 +1211,14 @@
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.admin-item-picker-list {
|
||||
max-width: calc(100vw - 24px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.admin-item-picker-item {
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import FormModal from "./FormModal";
|
||||
import AdminDatePicker from "./AdminDatePicker";
|
||||
import useModalLock from "../hooks/useModalLock";
|
||||
|
||||
interface BulkAttendanceForm {
|
||||
month: string;
|
||||
@@ -39,182 +38,128 @@ export default function BulkAttendanceModal({
|
||||
toggleUser,
|
||||
toggleAllUsers,
|
||||
}: BulkAttendanceModalProps) {
|
||||
useModalLock(isOpen);
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
onClick={() => !submitting && onClose()}
|
||||
<FormModal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Vyplnit docházku za měsíc"
|
||||
size="lg"
|
||||
loading={submitting}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Vyplnit měsíc"
|
||||
submitDisabled={form.user_ids.length === 0}
|
||||
>
|
||||
<p
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
marginTop: "0.25rem",
|
||||
marginBottom: "1rem",
|
||||
fontSize: "0.875rem",
|
||||
}}
|
||||
>
|
||||
Vytvoří záznamy pro všechny pracovní dny. Svátky se automaticky označí.
|
||||
Existující záznamy se přeskočí.
|
||||
</p>
|
||||
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Měsíc</label>
|
||||
<AdminDatePicker
|
||||
mode="month"
|
||||
value={form.month}
|
||||
onChange={(val) => setForm({ ...form, month: val })}
|
||||
/>
|
||||
<motion.div
|
||||
className="admin-modal admin-modal-lg"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="bulk-attendance-modal-title"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
</div>
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Zaměstnanci
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleAllUsers}
|
||||
style={{
|
||||
marginLeft: "0.75rem",
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "var(--accent-color)",
|
||||
cursor: "pointer",
|
||||
fontSize: "0.8125rem",
|
||||
fontWeight: 500,
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
{form.user_ids.length === users.length
|
||||
? "Odznačit vše"
|
||||
: "Vybrat vše"}
|
||||
</button>
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "0.375rem",
|
||||
maxHeight: "200px",
|
||||
overflowY: "auto",
|
||||
padding: "0.75rem",
|
||||
background: "var(--bg-tertiary)",
|
||||
borderRadius: "var(--border-radius-sm)",
|
||||
border: "1px solid var(--border-color)",
|
||||
}}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2
|
||||
id="bulk-attendance-modal-title"
|
||||
className="admin-modal-title"
|
||||
>
|
||||
Vyplnit docházku za měsíc
|
||||
</h2>
|
||||
<p
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
marginTop: "0.25rem",
|
||||
fontSize: "0.875rem",
|
||||
}}
|
||||
>
|
||||
Vytvoří záznamy pro všechny pracovní dny. Svátky se automaticky
|
||||
označí. Existující záznamy se přeskočí.
|
||||
</p>
|
||||
</div>
|
||||
{users.map((user) => (
|
||||
<label key={user.id} className="admin-form-checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.user_ids.includes(String(user.id))}
|
||||
onChange={() => toggleUser(user.id)}
|
||||
/>
|
||||
<span>{user.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<small className="admin-form-hint">
|
||||
Vybráno: {form.user_ids.length} z {users.length}
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-body">
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Měsíc</label>
|
||||
<AdminDatePicker
|
||||
mode="month"
|
||||
value={form.month}
|
||||
onChange={(val) => setForm({ ...form, month: val })}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Příchod</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.arrival_time}
|
||||
onChange={(val) => setForm({ ...form, arrival_time: val })}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Odchod</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.departure_time}
|
||||
onChange={(val) => setForm({ ...form, departure_time: val })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Zaměstnanci
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleAllUsers}
|
||||
style={{
|
||||
marginLeft: "0.75rem",
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "var(--accent-color)",
|
||||
cursor: "pointer",
|
||||
fontSize: "0.8125rem",
|
||||
fontWeight: 500,
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
{form.user_ids.length === users.length
|
||||
? "Odznačit vše"
|
||||
: "Vybrat vše"}
|
||||
</button>
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "0.375rem",
|
||||
maxHeight: "200px",
|
||||
overflowY: "auto",
|
||||
padding: "0.75rem",
|
||||
background: "var(--bg-tertiary)",
|
||||
borderRadius: "var(--border-radius-sm)",
|
||||
border: "1px solid var(--border-color)",
|
||||
}}
|
||||
>
|
||||
{users.map((user) => (
|
||||
<label key={user.id} className="admin-form-checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.user_ids.includes(String(user.id))}
|
||||
onChange={() => toggleUser(user.id)}
|
||||
/>
|
||||
<span>{user.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<small className="admin-form-hint">
|
||||
Vybráno: {form.user_ids.length} z {users.length}
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Příchod</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.arrival_time}
|
||||
onChange={(val) =>
|
||||
setForm({ ...form, arrival_time: val })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Odchod</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.departure_time}
|
||||
onChange={(val) =>
|
||||
setForm({ ...form, departure_time: val })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Začátek pauzy</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_start_time}
|
||||
onChange={(val) =>
|
||||
setForm({ ...form, break_start_time: val })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Konec pauzy</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_end_time}
|
||||
onChange={(val) =>
|
||||
setForm({ ...form, break_end_time: val })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={submitting}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSubmit}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={submitting || form.user_ids.length === 0}
|
||||
>
|
||||
{submitting ? "Vytvářím záznamy..." : "Vyplnit měsíc"}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Začátek pauzy</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_start_time}
|
||||
onChange={(val) => setForm({ ...form, break_start_time: val })}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Konec pauzy</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_end_time}
|
||||
onChange={(val) => setForm({ ...form, break_end_time: val })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</FormModal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import useReducedMotion from "../hooks/useReducedMotion";
|
||||
import useModalLock from "../hooks/useModalLock";
|
||||
|
||||
interface ConfirmModalProps {
|
||||
isOpen: boolean;
|
||||
@@ -91,6 +93,9 @@ export default function ConfirmModal({
|
||||
confirmVariant,
|
||||
loading,
|
||||
}: ConfirmModalProps) {
|
||||
const reducedMotion = useReducedMotion();
|
||||
// Lock body scroll while open (ref-counted, nesting-safe) — matches FormModal.
|
||||
useModalLock(isOpen);
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
@@ -104,6 +109,9 @@ export default function ConfirmModal({
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [isOpen, loading, onClose]);
|
||||
|
||||
const duration = reducedMotion ? 0 : 0.22;
|
||||
const ease = [0.16, 1, 0.3, 1] as const;
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
@@ -112,18 +120,21 @@ export default function ConfirmModal({
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
transition={{ duration: reducedMotion ? 0 : 0.18 }}
|
||||
>
|
||||
<div className="admin-modal-backdrop" onClick={onClose} />
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
onClick={() => !loading && onClose()}
|
||||
/>
|
||||
<motion.div
|
||||
className="admin-modal admin-confirm-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="confirm-modal-title"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
initial={{ opacity: 0, scale: 0.96, y: 16 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
exit={{ opacity: 0, scale: 0.97, y: 8 }}
|
||||
transition={{ duration, ease }}
|
||||
>
|
||||
<div className="admin-modal-body admin-confirm-content">
|
||||
<div className={`admin-confirm-icon admin-confirm-icon-${type}`}>
|
||||
|
||||
@@ -1,20 +1,38 @@
|
||||
import { useEffect, type ReactNode, type FormEvent } from "react";
|
||||
import {
|
||||
useEffect,
|
||||
type ReactNode,
|
||||
type FormEvent,
|
||||
Children,
|
||||
isValidElement,
|
||||
cloneElement,
|
||||
} from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import useModalLock from "../hooks/useModalLock";
|
||||
import useReducedMotion from "../hooks/useReducedMotion";
|
||||
|
||||
export interface FormModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSubmit?: () => void; // called when user clicks primary button (only if provided)
|
||||
title: string;
|
||||
/** Optional muted line shown under the title in the header. */
|
||||
subtitle?: ReactNode;
|
||||
children: ReactNode; // modal body (form fields)
|
||||
submitLabel?: string; // primary button text
|
||||
cancelLabel?: string; // cancel button text
|
||||
loading?: boolean;
|
||||
/** Disable the primary (submit) button — e.g. until the form is valid.
|
||||
* Keeps the button visibly greyed out instead of clickable-but-inert. */
|
||||
submitDisabled?: boolean;
|
||||
hideFooter?: boolean; // for "view-only" modals
|
||||
size?: "sm" | "md" | "lg"; // optional
|
||||
closeOnBackdrop?: boolean; // default true
|
||||
closeOnEsc?: boolean; // default true
|
||||
/** Slot for footer-left actions (e.g. delete). Rendered to the LEFT of
|
||||
* the standard cancel/submit group in the modal footer. */
|
||||
footerLeft?: ReactNode;
|
||||
/** Hide the close × in the header. Default false. */
|
||||
hideCloseButton?: boolean;
|
||||
}
|
||||
|
||||
export default function FormModal({
|
||||
@@ -22,16 +40,21 @@ export default function FormModal({
|
||||
onClose,
|
||||
onSubmit,
|
||||
title,
|
||||
subtitle,
|
||||
children,
|
||||
submitLabel = "Uložit",
|
||||
cancelLabel = "Zrušit",
|
||||
loading = false,
|
||||
submitDisabled = false,
|
||||
hideFooter = false,
|
||||
size = "md",
|
||||
closeOnBackdrop = true,
|
||||
closeOnEsc = true,
|
||||
footerLeft,
|
||||
hideCloseButton = false,
|
||||
}: FormModalProps) {
|
||||
useModalLock(isOpen);
|
||||
const reducedMotion = useReducedMotion();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !closeOnEsc) return;
|
||||
@@ -59,6 +82,16 @@ export default function FormModal({
|
||||
const modalClassName =
|
||||
size === "lg" ? "admin-modal admin-modal-lg" : "admin-modal";
|
||||
|
||||
// Snappier ease curve for modal entry — matches the "industrial/refined"
|
||||
// tone. Roughly equivalent to the cubic-bezier(0.16, 1, 0.3, 1) used by
|
||||
// a lot of design systems for "expo out" feel.
|
||||
const ease = [0.16, 1, 0.3, 1] as const;
|
||||
const duration = reducedMotion ? 0 : 0.22;
|
||||
// Stagger the body children slightly for a "drawing-in" reveal. We cap
|
||||
// the cascade so long forms don't drag on forever.
|
||||
const childrenArray = Children.toArray(children).filter(isValidElement);
|
||||
const stagger = reducedMotion ? 0 : Math.min(childrenArray.length, 5) * 0.03;
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
@@ -67,7 +100,7 @@ export default function FormModal({
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
transition={{ duration: reducedMotion ? 0 : 0.18 }}
|
||||
>
|
||||
<div className="admin-modal-backdrop" onClick={handleBackdropClick} />
|
||||
<motion.div
|
||||
@@ -75,39 +108,89 @@ export default function FormModal({
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
initial={{ opacity: 0, scale: 0.96, y: 16 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
exit={{ opacity: 0, scale: 0.97, y: 8 }}
|
||||
transition={{ duration, ease }}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2 id={titleId} className="admin-modal-title">
|
||||
{title}
|
||||
</h2>
|
||||
<div className="admin-modal-heading">
|
||||
<h2 id={titleId} className="admin-modal-title">
|
||||
{title}
|
||||
</h2>
|
||||
{subtitle && <p className="admin-modal-subtitle">{subtitle}</p>}
|
||||
</div>
|
||||
{!hideCloseButton && (
|
||||
<button
|
||||
type="button"
|
||||
className="admin-modal-close"
|
||||
onClick={() => !loading && onClose()}
|
||||
aria-label="Zavřít"
|
||||
title="Zavřít (Esc)"
|
||||
disabled={loading}
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<line x1="18" y1="6" x2="6" y2="18" />
|
||||
<line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-body">{children}</div>
|
||||
<div className="admin-modal-body">
|
||||
{reducedMotion || stagger === 0
|
||||
? children
|
||||
: Children.map(children, (child, i) => {
|
||||
if (!isValidElement(child)) return child;
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 6 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
delay: 0.04 + i * 0.03,
|
||||
ease: "easeOut",
|
||||
}}
|
||||
>
|
||||
{cloneElement(child)}
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{!hideFooter && (
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => !loading && onClose()}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={loading}
|
||||
>
|
||||
{cancelLabel}
|
||||
</button>
|
||||
{onSubmit && (
|
||||
<div className="admin-modal-footer-left">{footerLeft}</div>
|
||||
<div className="admin-modal-footer-right">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePrimaryClick}
|
||||
className="admin-btn admin-btn-primary"
|
||||
onClick={() => !loading && onClose()}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Zpracování..." : submitLabel}
|
||||
{cancelLabel}
|
||||
</button>
|
||||
)}
|
||||
{onSubmit && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePrimaryClick}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={loading || submitDisabled}
|
||||
>
|
||||
{loading ? "Zpracování..." : submitLabel}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import FormModal from "./FormModal";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
|
||||
interface ConfirmationItem {
|
||||
@@ -103,294 +103,250 @@ export default function OrderConfirmationModal({
|
||||
}, [defaultVatRate]);
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="admin-modal-backdrop" onClick={onClose} />
|
||||
<motion.div
|
||||
className={
|
||||
step === "edit" ? "admin-modal admin-modal-lg" : "admin-modal"
|
||||
}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="order-confirmation-modal-title"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2
|
||||
id="order-confirmation-modal-title"
|
||||
className="admin-modal-title"
|
||||
<FormModal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title={`Potvrzení objednávky ${orderNumber}`}
|
||||
size={step === "edit" ? "lg" : "md"}
|
||||
loading={loading}
|
||||
hideFooter
|
||||
>
|
||||
{step === "choose" ? (
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Jazyk dokumentu</label>
|
||||
<div className="flex-row gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLang("cs")}
|
||||
className={
|
||||
lang === "cs"
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
Potvrzení objednávky {orderNumber}
|
||||
</h2>
|
||||
Čeština
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLang("en")}
|
||||
className={
|
||||
lang === "en"
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
English
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-body">
|
||||
{step === "choose" ? (
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Jazyk dokumentu</label>
|
||||
<div className="flex-row gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLang("cs")}
|
||||
className={
|
||||
lang === "cs"
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
Čeština
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLang("en")}
|
||||
className={
|
||||
lang === "en"
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
English
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">DPH</label>
|
||||
<div className="flex-row gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setApplyVatState(true)}
|
||||
className={
|
||||
applyVatState
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
S DPH
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setApplyVatState(false)}
|
||||
className={
|
||||
!applyVatState
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
Bez DPH
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Obsah potvrzení</label>
|
||||
<p
|
||||
className="text-secondary"
|
||||
style={{ marginBottom: "0.75rem" }}
|
||||
>
|
||||
Jak chcete připravit potvrzení objednávky?
|
||||
</p>
|
||||
<button
|
||||
onClick={handleUseExisting}
|
||||
disabled={loading}
|
||||
className="admin-btn admin-btn-primary w-full"
|
||||
style={{ marginBottom: "0.5rem" }}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Generuji...
|
||||
</>
|
||||
) : (
|
||||
"Použít položky z objednávky"
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setItems(initialItems.length > 0 ? initialItems : []);
|
||||
setStep("edit");
|
||||
}}
|
||||
disabled={loading}
|
||||
className="admin-btn admin-btn-secondary w-full"
|
||||
>
|
||||
Upravit položky
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-form">
|
||||
<div className="admin-table-responsive">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Popis</th>
|
||||
<th>Mn.</th>
|
||||
<th>Jedn.</th>
|
||||
<th>Cena</th>
|
||||
<th>%DPH</th>
|
||||
<th style={{ width: "40px" }} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((item, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={item.description}
|
||||
onChange={(e) =>
|
||||
updateItem(i, "description", e.target.value)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ minWidth: "200px" }}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
value={item.quantity}
|
||||
onChange={(e) =>
|
||||
updateItem(
|
||||
i,
|
||||
"quantity",
|
||||
Number(e.target.value) || 0,
|
||||
)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ width: "80px" }}
|
||||
step="0.001"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={item.unit}
|
||||
onChange={(e) =>
|
||||
updateItem(i, "unit", e.target.value)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ width: "60px" }}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
value={item.unit_price}
|
||||
onChange={(e) =>
|
||||
updateItem(
|
||||
i,
|
||||
"unit_price",
|
||||
Number(e.target.value) || 0,
|
||||
)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ width: "100px" }}
|
||||
step="0.01"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
value={item.vat_rate}
|
||||
onChange={(e) =>
|
||||
updateItem(
|
||||
i,
|
||||
"vat_rate",
|
||||
Number(e.target.value) || 0,
|
||||
)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ width: "70px" }}
|
||||
step="1"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
onClick={() => removeItem(i)}
|
||||
className="admin-btn-icon danger"
|
||||
title="Odstranit"
|
||||
>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<polyline points="3 6 5 6 21 6" />
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||
</svg>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button
|
||||
onClick={addItem}
|
||||
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||
>
|
||||
+ Přidat položku
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">DPH</label>
|
||||
<div className="flex-row gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setApplyVatState(true)}
|
||||
className={
|
||||
applyVatState
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
S DPH
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setApplyVatState(false)}
|
||||
className={
|
||||
!applyVatState
|
||||
? "admin-btn admin-btn-primary admin-btn-sm"
|
||||
: "admin-btn admin-btn-secondary admin-btn-sm"
|
||||
}
|
||||
>
|
||||
Bez DPH
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-footer">
|
||||
{step === "edit" && (
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Obsah potvrzení</label>
|
||||
<p className="text-secondary" style={{ marginBottom: "0.75rem" }}>
|
||||
Jak chcete připravit potvrzení objednávky?
|
||||
</p>
|
||||
<button
|
||||
onClick={handleUseExisting}
|
||||
disabled={loading}
|
||||
className="admin-btn admin-btn-primary w-full"
|
||||
style={{ marginBottom: "0.5rem" }}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStep("choose")}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={loading}
|
||||
>
|
||||
Zpět
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleEditGenerate}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={loading || items.length === 0}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Generuji...
|
||||
</>
|
||||
) : (
|
||||
"Vygenerovat PDF"
|
||||
)}
|
||||
</button>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Generuji...
|
||||
</>
|
||||
) : (
|
||||
"Použít položky z objednávky"
|
||||
)}
|
||||
{step === "choose" && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={loading}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setItems(initialItems.length > 0 ? initialItems : []);
|
||||
setStep("edit");
|
||||
}}
|
||||
disabled={loading}
|
||||
className="admin-btn admin-btn-secondary w-full"
|
||||
>
|
||||
Upravit položky
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={loading}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-form">
|
||||
<div className="admin-table-responsive">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Popis</th>
|
||||
<th>Mn.</th>
|
||||
<th>Jedn.</th>
|
||||
<th>Cena</th>
|
||||
<th>%DPH</th>
|
||||
<th style={{ width: "40px" }} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((item, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={item.description}
|
||||
onChange={(e) =>
|
||||
updateItem(i, "description", e.target.value)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ minWidth: "200px" }}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
value={item.quantity}
|
||||
onChange={(e) =>
|
||||
updateItem(i, "quantity", Number(e.target.value) || 0)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ width: "80px" }}
|
||||
step="0.001"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={item.unit}
|
||||
onChange={(e) => updateItem(i, "unit", e.target.value)}
|
||||
className="admin-form-input"
|
||||
style={{ width: "60px" }}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
value={item.unit_price}
|
||||
onChange={(e) =>
|
||||
updateItem(
|
||||
i,
|
||||
"unit_price",
|
||||
Number(e.target.value) || 0,
|
||||
)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ width: "100px" }}
|
||||
step="0.01"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
value={item.vat_rate}
|
||||
onChange={(e) =>
|
||||
updateItem(i, "vat_rate", Number(e.target.value) || 0)
|
||||
}
|
||||
className="admin-form-input"
|
||||
style={{ width: "70px" }}
|
||||
step="1"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
onClick={() => removeItem(i)}
|
||||
className="admin-btn-icon danger"
|
||||
title="Odstranit"
|
||||
>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<polyline points="3 6 5 6 21 6" />
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||
</svg>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button
|
||||
onClick={addItem}
|
||||
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||
>
|
||||
+ Přidat položku
|
||||
</button>
|
||||
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStep("choose")}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={loading}
|
||||
>
|
||||
Zpět
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleEditGenerate}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={loading || items.length === 0}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
Generuji...
|
||||
</>
|
||||
) : (
|
||||
"Vygenerovat PDF"
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</FormModal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import AdminDatePicker from "./AdminDatePicker";
|
||||
import useModalLock from "../hooks/useModalLock";
|
||||
import FormModal from "./FormModal";
|
||||
import {
|
||||
calcFormWorkMinutes,
|
||||
calcProjectMinutesTotal,
|
||||
@@ -216,7 +215,6 @@ export default function ShiftFormModal({
|
||||
onShiftDateChange,
|
||||
editingRecord,
|
||||
}: ShiftFormModalProps) {
|
||||
useModalLock(isOpen);
|
||||
const isCreate = mode === "create";
|
||||
const isWorkType = form.leave_type === "work";
|
||||
|
||||
@@ -247,276 +245,209 @@ export default function ShiftFormModal({
|
||||
};
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="admin-modal-backdrop" onClick={onClose} />
|
||||
<motion.div
|
||||
className="admin-modal admin-modal-lg"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="shift-form-modal-title"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2 id="shift-form-modal-title" className="admin-modal-title">
|
||||
{isCreate ? "Přidat záznam docházky" : "Upravit docházku"}
|
||||
</h2>
|
||||
{!isCreate && editingRecord && (
|
||||
<p
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
marginTop: "0.25rem",
|
||||
}}
|
||||
>
|
||||
{editingRecord.user_name} —{" "}
|
||||
{formatDate(editingRecord.shift_date)}
|
||||
</p>
|
||||
)}
|
||||
<FormModal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title={isCreate ? "Přidat záznam docházky" : "Upravit docházku"}
|
||||
subtitle={
|
||||
!isCreate && editingRecord
|
||||
? `${editingRecord.user_name} — ${formatDate(editingRecord.shift_date)}`
|
||||
: undefined
|
||||
}
|
||||
size="lg"
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Uložit"
|
||||
cancelLabel="Zrušit"
|
||||
>
|
||||
<div className="admin-form">
|
||||
{isCreate ? (
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label required">Zaměstnanec</label>
|
||||
<select
|
||||
value={form.user_id}
|
||||
onChange={(e) => updateField("user_id", e.target.value)}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="">Vyberte zaměstnance</option>
|
||||
{users.map((user) => (
|
||||
<option key={user.id} value={user.id}>
|
||||
{user.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label required">Datum směny</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.shift_date}
|
||||
onChange={(val) => onShiftDateChange(val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Datum směny</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.shift_date}
|
||||
onChange={(val) => updateField("shift_date", val)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="admin-modal-body">
|
||||
<div className="admin-form">
|
||||
{isCreate ? (
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label required">
|
||||
Zaměstnanec
|
||||
</label>
|
||||
<select
|
||||
value={form.user_id}
|
||||
onChange={(e) => updateField("user_id", e.target.value)}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="">Vyberte zaměstnance</option>
|
||||
{users.map((user) => (
|
||||
<option key={user.id} value={user.id}>
|
||||
{user.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label required">
|
||||
Datum směny
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.shift_date}
|
||||
onChange={(val) => onShiftDateChange(val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Datum směny</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.shift_date}
|
||||
onChange={(val) => updateField("shift_date", val)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Typ záznamu</label>
|
||||
<select
|
||||
value={form.leave_type}
|
||||
onChange={(e) => updateField("leave_type", e.target.value)}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="work">Práce</option>
|
||||
<option value="vacation">Dovolená</option>
|
||||
<option value="sick">Nemoc</option>
|
||||
<option value="unpaid">Neplacené volno</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Typ záznamu</label>
|
||||
<select
|
||||
value={form.leave_type}
|
||||
onChange={(e) => updateField("leave_type", e.target.value)}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="work">Práce</option>
|
||||
<option value="vacation">Dovolená</option>
|
||||
<option value="sick">Nemoc</option>
|
||||
<option value="unpaid">Neplacené volno</option>
|
||||
</select>
|
||||
</div>
|
||||
{!isWorkType && (
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Počet hodin</label>
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={form.leave_hours}
|
||||
onChange={(e) =>
|
||||
updateField("leave_hours", parseFloat(e.target.value))
|
||||
}
|
||||
min="0.5"
|
||||
max="24"
|
||||
step="0.5"
|
||||
className="admin-form-input"
|
||||
/>
|
||||
{isCreate && (
|
||||
<small className="admin-form-hint">8 hodin = celý den</small>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isWorkType && (
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Počet hodin</label>
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={form.leave_hours}
|
||||
onChange={(e) =>
|
||||
updateField("leave_hours", parseFloat(e.target.value))
|
||||
}
|
||||
min="0.5"
|
||||
max="24"
|
||||
step="0.5"
|
||||
className="admin-form-input"
|
||||
/>
|
||||
{isCreate && (
|
||||
<small className="admin-form-hint">
|
||||
8 hodin = celý den
|
||||
</small>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isWorkType && (
|
||||
<>
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Příchod - datum
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.arrival_date}
|
||||
onChange={(val) => updateField("arrival_date", val)}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Příchod - čas
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.arrival_time}
|
||||
onChange={(val) => updateField("arrival_time", val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Začátek pauzy - datum
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.break_start_date}
|
||||
onChange={(val) =>
|
||||
updateField("break_start_date", val)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Začátek pauzy - čas
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_start_time}
|
||||
onChange={(val) =>
|
||||
updateField("break_start_time", val)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Konec pauzy - datum
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.break_end_date}
|
||||
onChange={(val) => updateField("break_end_date", val)}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Konec pauzy - čas
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_end_time}
|
||||
onChange={(val) => updateField("break_end_time", val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Odchod - datum
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.departure_date}
|
||||
onChange={(val) => updateField("departure_date", val)}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Odchod - čas</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.departure_time}
|
||||
onChange={(val) => updateField("departure_time", val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isWorkType && projectList.length > 0 && (
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Projekty</label>
|
||||
<ProjectTimeStatus form={form} projectLogs={projectLogs} />
|
||||
{projectLogs.map((log, i) => (
|
||||
<ProjectLogRow
|
||||
key={log._key || i}
|
||||
log={log}
|
||||
index={i}
|
||||
projectList={projectList}
|
||||
onUpdate={updateProjectLog}
|
||||
onRemove={removeProjectLog}
|
||||
/>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={addProjectLog}
|
||||
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||
>
|
||||
+ Přidat projekt
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Poznámka</label>
|
||||
<textarea
|
||||
value={form.notes}
|
||||
onChange={(e) => updateField("notes", e.target.value)}
|
||||
className="admin-form-textarea"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
{isWorkType && (
|
||||
<>
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Příchod - datum</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.arrival_date}
|
||||
onChange={(val) => updateField("arrival_date", val)}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Příchod - čas</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.arrival_time}
|
||||
onChange={(val) => updateField("arrival_time", val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSubmit}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
Uložit
|
||||
</button>
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Začátek pauzy - datum
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.break_start_date}
|
||||
onChange={(val) => updateField("break_start_date", val)}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Začátek pauzy - čas</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_start_time}
|
||||
onChange={(val) => updateField("break_start_time", val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Konec pauzy - datum</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.break_end_date}
|
||||
onChange={(val) => updateField("break_end_date", val)}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Konec pauzy - čas</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.break_end_time}
|
||||
onChange={(val) => updateField("break_end_time", val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Odchod - datum</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={form.departure_date}
|
||||
onChange={(val) => updateField("departure_date", val)}
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Odchod - čas</label>
|
||||
<AdminDatePicker
|
||||
mode="time"
|
||||
value={form.departure_time}
|
||||
onChange={(val) => updateField("departure_time", val)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isWorkType && projectList.length > 0 && (
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Projekty</label>
|
||||
<ProjectTimeStatus form={form} projectLogs={projectLogs} />
|
||||
{projectLogs.map((log, i) => (
|
||||
<ProjectLogRow
|
||||
key={log._key || i}
|
||||
log={log}
|
||||
index={i}
|
||||
projectList={projectList}
|
||||
onUpdate={updateProjectLog}
|
||||
onRemove={removeProjectLog}
|
||||
/>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={addProjectLog}
|
||||
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||
>
|
||||
+ Přidat projekt
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Poznámka</label>
|
||||
<textarea
|
||||
value={form.notes}
|
||||
onChange={(e) => updateField("notes", e.target.value)}
|
||||
className="admin-form-textarea"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</FormModal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { motion } from "framer-motion";
|
||||
import { useAuth } from "../../context/AuthContext";
|
||||
import { useAlert } from "../../context/AlertContext";
|
||||
import useModalLock from "../../hooks/useModalLock";
|
||||
import apiFetch from "../../utils/api";
|
||||
import FormModal from "../FormModal";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -71,8 +71,6 @@ export default function DashProfile({
|
||||
last_name: "",
|
||||
});
|
||||
|
||||
useModalLock(showModal);
|
||||
|
||||
const openEditModal = () => {
|
||||
const nameParts = (user?.fullName || "").split(" ");
|
||||
setFormData({
|
||||
@@ -261,482 +259,367 @@ export default function DashProfile({
|
||||
</motion.div>
|
||||
|
||||
{/* Edit Profile Modal */}
|
||||
<AnimatePresence>
|
||||
{showModal && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
onClick={() => setShowModal(false)}
|
||||
/>
|
||||
<motion.div
|
||||
className="admin-modal"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2 className="admin-modal-title">Upravit profil</h2>
|
||||
</div>
|
||||
<div className="admin-modal-body">
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Jméno</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.first_name}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
first_name: e.target.value,
|
||||
})
|
||||
}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Příjmení</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.last_name}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
last_name: e.target.value,
|
||||
})
|
||||
}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Uživatelské jméno
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.username}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, username: e.target.value })
|
||||
}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">E-mail</label>
|
||||
<input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, email: e.target.value })
|
||||
}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Aktuální heslo</label>
|
||||
<input
|
||||
type="password"
|
||||
value={formData.current_password}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
current_password: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="Pro změnu hesla, zadejte aktuální heslo"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Nové heslo
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={formData.new_password}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
new_password: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="Pro změnu hesla, zadejte nové heslo"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowModal(false)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
Uložit změny
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* 2FA Setup Modal */}
|
||||
<AnimatePresence>
|
||||
{show2FASetup && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
onClick={() => {
|
||||
if (!backupCodes) {
|
||||
setShow2FASetup(false);
|
||||
<FormModal
|
||||
isOpen={showModal}
|
||||
onClose={() => setShowModal(false)}
|
||||
title="Upravit profil"
|
||||
size="md"
|
||||
onSubmit={handleSubmit}
|
||||
submitLabel="Uložit změny"
|
||||
>
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-row">
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Jméno</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.first_name}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
first_name: e.target.value,
|
||||
})
|
||||
}
|
||||
}}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Příjmení</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.last_name}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
last_name: e.target.value,
|
||||
})
|
||||
}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Uživatelské jméno</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.username}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, username: e.target.value })
|
||||
}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
<motion.div
|
||||
className="admin-modal"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2 className="admin-modal-title">
|
||||
{backupCodes ? "Záložní kódy" : "Nastavení 2FA"}
|
||||
</h2>
|
||||
</div>
|
||||
<div className="admin-modal-body">
|
||||
{backupCodes ? (
|
||||
<div>
|
||||
<div className="admin-role-locked-notice mb-4">
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
|
||||
<line x1="12" y1="9" x2="12" y2="13" />
|
||||
<line x1="12" y1="17" x2="12.01" y2="17" />
|
||||
</svg>
|
||||
Uložte si tyto kódy na bezpečné místo. Každý kód lze
|
||||
použít pouze jednou. Po zavření tohoto okna je již
|
||||
neuvidíte.
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(2, 1fr)",
|
||||
gap: "0.5rem",
|
||||
padding: "1rem",
|
||||
background: "var(--bg-secondary)",
|
||||
borderRadius: "0.5rem",
|
||||
fontFamily: "monospace",
|
||||
fontSize: "1rem",
|
||||
}}
|
||||
>
|
||||
{backupCodes.map((code) => (
|
||||
<div
|
||||
key={code}
|
||||
style={{
|
||||
padding: "0.25rem 0.5rem",
|
||||
textAlign: "center",
|
||||
color: "var(--text-primary)",
|
||||
}}
|
||||
>
|
||||
{code}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ marginTop: "0.75rem" }}>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard?.writeText(
|
||||
backupCodes.join("\n"),
|
||||
);
|
||||
alert.success("Kódy zkopírovány");
|
||||
}}
|
||||
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect
|
||||
x="9"
|
||||
y="9"
|
||||
width="13"
|
||||
height="13"
|
||||
rx="2"
|
||||
ry="2"
|
||||
/>
|
||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
|
||||
</svg>
|
||||
Kopírovat kódy
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p
|
||||
className="text-secondary"
|
||||
style={{ fontSize: "0.875rem", marginBottom: "1rem" }}
|
||||
>
|
||||
Naskenujte QR kód v autentizační aplikaci (Google
|
||||
Authenticator, Authy, Microsoft Authenticator apod.)
|
||||
</p>
|
||||
{totpQrUri && (
|
||||
<div
|
||||
style={{ textAlign: "center", marginBottom: "1rem" }}
|
||||
>
|
||||
<img
|
||||
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(totpQrUri)}`}
|
||||
alt="TOTP QR Code"
|
||||
style={{
|
||||
width: 200,
|
||||
height: 200,
|
||||
borderRadius: "0.5rem",
|
||||
border: "1px solid var(--border-color)",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{totpSecret && (
|
||||
<div className="mb-4">
|
||||
<label
|
||||
className="admin-form-label"
|
||||
style={{ fontSize: "0.75rem" }}
|
||||
>
|
||||
Nebo zadejte klíč ručně:
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
padding: "0.5rem 0.75rem",
|
||||
background: "var(--bg-secondary)",
|
||||
borderRadius: "0.375rem",
|
||||
fontFamily: "monospace",
|
||||
fontSize: "0.875rem",
|
||||
wordBreak: "break-all",
|
||||
color: "var(--text-primary)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<span>{totpSecret}</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard?.writeText(totpSecret);
|
||||
alert.success("Klíč zkopírován");
|
||||
}}
|
||||
className="admin-btn-icon"
|
||||
title="Kopírovat"
|
||||
aria-label="Kopírovat"
|
||||
style={{ flexShrink: 0 }}
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect
|
||||
x="9"
|
||||
y="9"
|
||||
width="13"
|
||||
height="13"
|
||||
rx="2"
|
||||
ry="2"
|
||||
/>
|
||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Ověřovací kód z aplikace
|
||||
</label>
|
||||
<input
|
||||
ref={totpSetupRef}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]*"
|
||||
maxLength={6}
|
||||
value={totpCode}
|
||||
onChange={(e) =>
|
||||
setTotpCode(e.target.value.replace(/\D/g, ""))
|
||||
}
|
||||
placeholder="000000"
|
||||
className="admin-form-input"
|
||||
style={{
|
||||
textAlign: "center",
|
||||
fontSize: "1.25rem",
|
||||
letterSpacing: "0.4rem",
|
||||
fontFamily: "monospace",
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && totpCode.length === 6) {
|
||||
onConfirm2FA();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-modal-footer">
|
||||
{backupCodes ? (
|
||||
<button
|
||||
onClick={() => {
|
||||
setShow2FASetup(false);
|
||||
setBackupCodes(null);
|
||||
}}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
Rozumím, uložil jsem si kódy
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
onClick={() => setShow2FASetup(false)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={totpSubmitting}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
<button
|
||||
onClick={onConfirm2FA}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={totpSubmitting || totpCode.length !== 6}
|
||||
>
|
||||
{totpSubmitting ? "Ověřuji..." : "Aktivovat 2FA"}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">E-mail</label>
|
||||
<input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, email: e.target.value })
|
||||
}
|
||||
required
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Aktuální heslo</label>
|
||||
<input
|
||||
type="password"
|
||||
value={formData.current_password}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
current_password: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="Pro změnu hesla, zadejte aktuální heslo"
|
||||
/>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Nové heslo</label>
|
||||
<input
|
||||
type="password"
|
||||
value={formData.new_password}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
new_password: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="Pro změnu hesla, zadejte nové heslo"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</FormModal>
|
||||
|
||||
{/* 2FA Disable Modal */}
|
||||
<AnimatePresence>
|
||||
{show2FADisable && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
{/* 2FA Setup Modal — multi-step: setup → backup codes */}
|
||||
<FormModal
|
||||
isOpen={show2FASetup}
|
||||
onClose={() => {
|
||||
// Only reachable on the setup step (backdrop/ESC/× are locked while
|
||||
// backupCodes is set — that branch is unreachable so removed).
|
||||
setShow2FASetup(false);
|
||||
setTotpCode("");
|
||||
}}
|
||||
title={backupCodes ? "Záložní kódy" : "Nastavení 2FA"}
|
||||
size="md"
|
||||
loading={backupCodes ? false : totpSubmitting}
|
||||
onSubmit={
|
||||
backupCodes
|
||||
? () => {
|
||||
setShow2FASetup(false);
|
||||
setBackupCodes(null);
|
||||
}
|
||||
: onConfirm2FA
|
||||
}
|
||||
submitLabel={
|
||||
backupCodes ? "Rozumím, uložil jsem si kódy" : "Aktivovat 2FA"
|
||||
}
|
||||
submitDisabled={backupCodes ? false : totpCode.length !== 6}
|
||||
cancelLabel="Zrušit"
|
||||
// On the backup-codes step the cancel/× would silently dismiss unsaved
|
||||
// codes, so hide the footer + × and lock backdrop/ESC; the explicit
|
||||
// in-body primary is the single deliberate exit.
|
||||
hideFooter={!!backupCodes}
|
||||
hideCloseButton={!!backupCodes}
|
||||
closeOnBackdrop={!backupCodes}
|
||||
closeOnEsc={!backupCodes}
|
||||
>
|
||||
{backupCodes ? (
|
||||
<div>
|
||||
<div className="admin-role-locked-notice mb-4">
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
|
||||
<line x1="12" y1="9" x2="12" y2="13" />
|
||||
<line x1="12" y1="17" x2="12.01" y2="17" />
|
||||
</svg>
|
||||
Uložte si tyto kódy na bezpečné místo. Každý kód lze použít pouze
|
||||
jednou. Po zavření tohoto okna je již neuvidíte.
|
||||
</div>
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
onClick={() => setShow2FADisable(false)}
|
||||
/>
|
||||
<motion.div
|
||||
className="admin-modal"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(2, 1fr)",
|
||||
gap: "0.5rem",
|
||||
padding: "1rem",
|
||||
background: "var(--bg-secondary)",
|
||||
borderRadius: "0.5rem",
|
||||
fontFamily: "monospace",
|
||||
fontSize: "1rem",
|
||||
}}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2 className="admin-modal-title">Deaktivovat 2FA</h2>
|
||||
</div>
|
||||
<div className="admin-modal-body">
|
||||
<p
|
||||
{backupCodes.map((code) => (
|
||||
<div
|
||||
key={code}
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
fontSize: "0.875rem",
|
||||
marginBottom: "1rem",
|
||||
padding: "0.25rem 0.5rem",
|
||||
textAlign: "center",
|
||||
color: "var(--text-primary)",
|
||||
}}
|
||||
>
|
||||
Pro deaktivaci dvoufaktorového ověření zadejte aktuální kód z
|
||||
autentizační aplikace.
|
||||
</p>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Ověřovací kód</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]*"
|
||||
maxLength={6}
|
||||
value={disableCode}
|
||||
onChange={(e) =>
|
||||
setDisableCode(e.target.value.replace(/\D/g, ""))
|
||||
}
|
||||
placeholder="000000"
|
||||
className="admin-form-input"
|
||||
style={{
|
||||
textAlign: "center",
|
||||
fontSize: "1.25rem",
|
||||
letterSpacing: "0.4rem",
|
||||
fontFamily: "monospace",
|
||||
{code}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ marginTop: "0.75rem" }}>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard?.writeText(backupCodes.join("\n"));
|
||||
alert.success("Kódy zkopírovány");
|
||||
}}
|
||||
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
|
||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
|
||||
</svg>
|
||||
Kopírovat kódy
|
||||
</button>
|
||||
</div>
|
||||
{/* Footer is hidden on this step; the single deliberate exit lives
|
||||
in the body and also clears the codes. */}
|
||||
<div style={{ marginTop: "1.25rem", textAlign: "right" }}>
|
||||
<button
|
||||
onClick={() => {
|
||||
setShow2FASetup(false);
|
||||
setBackupCodes(null);
|
||||
}}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
Rozumím, uložil jsem si kódy
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p
|
||||
className="text-secondary"
|
||||
style={{ fontSize: "0.875rem", marginBottom: "1rem" }}
|
||||
>
|
||||
Naskenujte QR kód v autentizační aplikaci (Google Authenticator,
|
||||
Authy, Microsoft Authenticator apod.)
|
||||
</p>
|
||||
{totpQrUri && (
|
||||
<div style={{ textAlign: "center", marginBottom: "1rem" }}>
|
||||
<img
|
||||
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(totpQrUri)}`}
|
||||
alt="TOTP QR Code"
|
||||
style={{
|
||||
width: 200,
|
||||
height: 200,
|
||||
borderRadius: "0.5rem",
|
||||
border: "1px solid var(--border-color)",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{totpSecret && (
|
||||
<div className="mb-4">
|
||||
<label
|
||||
className="admin-form-label"
|
||||
style={{ fontSize: "0.75rem" }}
|
||||
>
|
||||
Nebo zadejte klíč ručně:
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
padding: "0.5rem 0.75rem",
|
||||
background: "var(--bg-secondary)",
|
||||
borderRadius: "0.375rem",
|
||||
fontFamily: "monospace",
|
||||
fontSize: "0.875rem",
|
||||
wordBreak: "break-all",
|
||||
color: "var(--text-primary)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<span>{totpSecret}</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard?.writeText(totpSecret);
|
||||
alert.success("Klíč zkopírován");
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && disableCode.length === 6) {
|
||||
onDisable2FA();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
className="admin-btn-icon"
|
||||
title="Kopírovat"
|
||||
aria-label="Kopírovat"
|
||||
style={{ flexShrink: 0 }}
|
||||
>
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
|
||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
onClick={() => setShow2FADisable(false)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={totpSubmitting}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
<button
|
||||
onClick={onDisable2FA}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={totpSubmitting || disableCode.length !== 6}
|
||||
>
|
||||
{totpSubmitting ? "Deaktivuji..." : "Deaktivovat 2FA"}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">
|
||||
Ověřovací kód z aplikace
|
||||
</label>
|
||||
<input
|
||||
ref={totpSetupRef}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]*"
|
||||
maxLength={6}
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, ""))}
|
||||
placeholder="000000"
|
||||
className="admin-form-input"
|
||||
style={{
|
||||
textAlign: "center",
|
||||
fontSize: "1.25rem",
|
||||
letterSpacing: "0.4rem",
|
||||
fontFamily: "monospace",
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && totpCode.length === 6) {
|
||||
onConfirm2FA();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</FormModal>
|
||||
|
||||
{/* 2FA Disable Modal */}
|
||||
<FormModal
|
||||
isOpen={show2FADisable}
|
||||
onClose={() => setShow2FADisable(false)}
|
||||
title="Deaktivovat 2FA"
|
||||
size="md"
|
||||
loading={totpSubmitting}
|
||||
onSubmit={onDisable2FA}
|
||||
submitDisabled={disableCode.length !== 6}
|
||||
submitLabel="Deaktivovat 2FA"
|
||||
cancelLabel="Zrušit"
|
||||
>
|
||||
<p
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
fontSize: "0.875rem",
|
||||
marginBottom: "1rem",
|
||||
}}
|
||||
>
|
||||
Pro deaktivaci dvoufaktorového ověření zadejte aktuální kód z
|
||||
autentizační aplikace.
|
||||
</p>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Ověřovací kód</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]*"
|
||||
maxLength={6}
|
||||
value={disableCode}
|
||||
onChange={(e) => setDisableCode(e.target.value.replace(/\D/g, ""))}
|
||||
placeholder="000000"
|
||||
className="admin-form-input"
|
||||
style={{
|
||||
textAlign: "center",
|
||||
fontSize: "1.25rem",
|
||||
letterSpacing: "0.4rem",
|
||||
fontFamily: "monospace",
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && disableCode.length === 6) {
|
||||
onDisable2FA();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</FormModal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { motion } from "framer-motion";
|
||||
import { useAuth } from "../../context/AuthContext";
|
||||
import { useAlert } from "../../context/AlertContext";
|
||||
import { formatKm } from "../../utils/formatters";
|
||||
import { formatKm, todayLocalStr } from "../../utils/formatters";
|
||||
import AdminDatePicker from "../AdminDatePicker";
|
||||
import apiFetch from "../../utils/api";
|
||||
import useModalLock from "../../hooks/useModalLock";
|
||||
import FormModal from "../FormModal";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -69,12 +69,10 @@ export default function DashQuickActions({
|
||||
});
|
||||
const [tripErrors, setTripErrors] = useState<TripErrors>({});
|
||||
|
||||
useModalLock(showTripModal);
|
||||
|
||||
const openTripModal = async () => {
|
||||
setTripForm({
|
||||
vehicle_id: "",
|
||||
trip_date: new Date().toISOString().split("T")[0],
|
||||
trip_date: todayLocalStr(),
|
||||
start_km: "",
|
||||
end_km: "",
|
||||
route_from: "",
|
||||
@@ -316,273 +314,222 @@ export default function DashQuickActions({
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
<AnimatePresence>
|
||||
{showTripModal && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<FormModal
|
||||
isOpen={showTripModal}
|
||||
onClose={() => setShowTripModal(false)}
|
||||
title="Přidat jízdu"
|
||||
size="lg"
|
||||
onSubmit={handleTripSubmit}
|
||||
submitLabel="Uložit"
|
||||
loading={tripSubmitting}
|
||||
>
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-row">
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
onClick={() => setShowTripModal(false)}
|
||||
/>
|
||||
<motion.div
|
||||
className="admin-modal admin-modal-lg"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className={`admin-form-group${tripErrors.vehicle_id ? " has-error" : ""}`}
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2 className="admin-modal-title">Přidat jízdu</h2>
|
||||
</div>
|
||||
<div className="admin-modal-body">
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-row">
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.vehicle_id ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Vozidlo
|
||||
</label>
|
||||
<select
|
||||
value={tripForm.vehicle_id}
|
||||
onChange={(e) => {
|
||||
handleTripVehicleChange(e.target.value);
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
vehicle_id: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="">Vyberte vozidlo</option>
|
||||
{tripVehicles.map((v) => (
|
||||
<option key={v.id} value={v.id}>
|
||||
{v.spz} - {v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{tripErrors.vehicle_id && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.vehicle_id}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.trip_date ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Datum jízdy
|
||||
</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={tripForm.trip_date}
|
||||
onChange={(val: string) => {
|
||||
setTripForm((prev) => ({ ...prev, trip_date: val }));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
trip_date: undefined,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
{tripErrors.trip_date && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.trip_date}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<label className="admin-form-label required">Vozidlo</label>
|
||||
<select
|
||||
value={tripForm.vehicle_id}
|
||||
onChange={(e) => {
|
||||
handleTripVehicleChange(e.target.value);
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
vehicle_id: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="">Vyberte vozidlo</option>
|
||||
{tripVehicles.map((v) => (
|
||||
<option key={v.id} value={v.id}>
|
||||
{v.spz} - {v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{tripErrors.vehicle_id && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.vehicle_id}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.trip_date ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">Datum jízdy</label>
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={tripForm.trip_date}
|
||||
onChange={(val: string) => {
|
||||
setTripForm((prev) => ({ ...prev, trip_date: val }));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
trip_date: undefined,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
{tripErrors.trip_date && (
|
||||
<span className="admin-form-error">{tripErrors.trip_date}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row admin-form-row-3">
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.start_km ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Počáteční stav km
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
value={tripForm.start_km}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
start_km: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
start_km: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
min="0"
|
||||
/>
|
||||
{tripErrors.start_km && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.start_km}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.end_km ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Konečný stav km
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
value={tripForm.end_km}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
end_km: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
end_km: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
min="0"
|
||||
/>
|
||||
{tripErrors.end_km && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.end_km}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Vzdálenost</label>
|
||||
<input
|
||||
type="text"
|
||||
value={`${formatKm(tripDistance())} km`}
|
||||
className="admin-form-input"
|
||||
readOnly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-form-row admin-form-row-3">
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.start_km ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Počáteční stav km
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
value={tripForm.start_km}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
start_km: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
start_km: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
min="0"
|
||||
/>
|
||||
{tripErrors.start_km && (
|
||||
<span className="admin-form-error">{tripErrors.start_km}</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.end_km ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Konečný stav km
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
value={tripForm.end_km}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
end_km: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
end_km: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
min="0"
|
||||
/>
|
||||
{tripErrors.end_km && (
|
||||
<span className="admin-form-error">{tripErrors.end_km}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Vzdálenost</label>
|
||||
<input
|
||||
type="text"
|
||||
value={`${formatKm(tripDistance())} km`}
|
||||
className="admin-form-input"
|
||||
readOnly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.route_from ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Místo odjezdu
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={tripForm.route_from}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
route_from: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
route_from: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
placeholder="Např. Praha"
|
||||
/>
|
||||
{tripErrors.route_from && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.route_from}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.route_to ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Místo příjezdu
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={tripForm.route_to}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
route_to: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
route_to: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
placeholder="Např. Brno"
|
||||
/>
|
||||
{tripErrors.route_to && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.route_to}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-form-row">
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.route_from ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">Místo odjezdu</label>
|
||||
<input
|
||||
type="text"
|
||||
value={tripForm.route_from}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
route_from: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
route_from: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
placeholder="Např. Praha"
|
||||
/>
|
||||
{tripErrors.route_from && (
|
||||
<span className="admin-form-error">
|
||||
{tripErrors.route_from}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`admin-form-group${tripErrors.route_to ? " has-error" : ""}`}
|
||||
>
|
||||
<label className="admin-form-label required">
|
||||
Místo příjezdu
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={tripForm.route_to}
|
||||
onChange={(e) => {
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
route_to: e.target.value,
|
||||
}));
|
||||
setTripErrors((prev) => ({
|
||||
...prev,
|
||||
route_to: undefined,
|
||||
}));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
placeholder="Např. Brno"
|
||||
/>
|
||||
{tripErrors.route_to && (
|
||||
<span className="admin-form-error">{tripErrors.route_to}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Typ jízdy</label>
|
||||
<select
|
||||
value={tripForm.is_business}
|
||||
onChange={(e) =>
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
is_business: parseInt(e.target.value),
|
||||
}))
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value={1}>Služební</option>
|
||||
<option value={0}>Soukromá</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Typ jízdy</label>
|
||||
<select
|
||||
value={tripForm.is_business}
|
||||
onChange={(e) =>
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
is_business: parseInt(e.target.value),
|
||||
}))
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value={1}>Služební</option>
|
||||
<option value={0}>Soukromá</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Poznámky</label>
|
||||
<textarea
|
||||
value={tripForm.notes}
|
||||
onChange={(e) =>
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
notes: e.target.value,
|
||||
}))
|
||||
}
|
||||
className="admin-form-textarea"
|
||||
rows={2}
|
||||
placeholder="Volitelné poznámky..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowTripModal(false)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={tripSubmitting}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleTripSubmit}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={tripSubmitting}
|
||||
>
|
||||
{tripSubmitting ? "Ukládám..." : "Uložit"}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div className="admin-form-group">
|
||||
<label className="admin-form-label">Poznámky</label>
|
||||
<textarea
|
||||
value={tripForm.notes}
|
||||
onChange={(e) =>
|
||||
setTripForm((prev) => ({
|
||||
...prev,
|
||||
notes: e.target.value,
|
||||
}))
|
||||
}
|
||||
className="admin-form-textarea"
|
||||
rows={2}
|
||||
placeholder="Volitelné poznámky..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</FormModal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -197,3 +197,15 @@
|
||||
.react-datepicker__close-icon::after {
|
||||
background-color: var(--accent-color) !important;
|
||||
}
|
||||
|
||||
/* Mobile safety net — keep the popper inside the viewport on small phones.
|
||||
(Native date input is used on touch; this guards the rare desktop-style popper.) */
|
||||
@media (max-width: 480px) {
|
||||
.react-datepicker-popper {
|
||||
max-width: calc(100vw - 24px);
|
||||
}
|
||||
|
||||
.react-datepicker {
|
||||
font-size: 0.8rem !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,3 +169,31 @@
|
||||
color: var(--text-tertiary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
File Manager — mobile
|
||||
============================================================================ */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
/* Toolbar wraps so actions drop below the path instead of overflowing */
|
||||
.fm-toolbar {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* New-folder input goes full width (override the 250px desktop cap) */
|
||||
.fm-new-folder .admin-form-input {
|
||||
max-width: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Breadcrumb scrolls horizontally instead of overflowing the container */
|
||||
.fm-breadcrumb {
|
||||
flex-wrap: nowrap;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.fm-breadcrumb-segment {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +310,8 @@
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.admin-form-row,
|
||||
.admin-form-row-3,
|
||||
.admin-form-row-4,
|
||||
.admin-form-row-5 {
|
||||
grid-template-columns: 1fr;
|
||||
@@ -486,3 +488,23 @@
|
||||
color: var(--text-tertiary);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.admin-customer-dropdown {
|
||||
max-width: calc(100vw - 24px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.admin-customer-dropdown-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.admin-customer-selected .admin-btn-icon {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
margin-right: -10px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,9 +127,17 @@
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
/* Month-nav row may wrap so it never forces horizontal page overflow */
|
||||
.invoice-month-nav {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* 44px touch target for the prev/next month buttons */
|
||||
.invoice-month-btn {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.received-upload-row {
|
||||
|
||||
40
src/admin/lib/entityTypeLabels.ts
Normal file
40
src/admin/lib/entityTypeLabels.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// Single source of truth for audit-log entity_type → Czech label, used by
|
||||
// the Audit Log page and the dashboard activity feed.
|
||||
//
|
||||
// IMPORTANT: keys MUST match the `entityType` values the server actually
|
||||
// writes via logAudit() (see src/types/index.ts `EntityType` and the
|
||||
// `entityType:` args in src/routes/**). The previous maps used legacy keys
|
||||
// (e.g. "invoices_invoice", "offers_quotation", "trips") that never matched
|
||||
// what the server writes, and omitted every warehouse_* entity, so those
|
||||
// audit rows rendered the raw English entity_type instead of a Czech label.
|
||||
export const ENTITY_TYPE_LABELS: Record<string, string> = {
|
||||
user: "Uživatel",
|
||||
role: "Role",
|
||||
attendance: "Docházka",
|
||||
leave_request: "Žádost o nepřítomnost",
|
||||
leave_balance: "Saldo nepřítomnosti",
|
||||
invoice: "Faktura",
|
||||
quotation: "Nabídka",
|
||||
order: "Objednávka",
|
||||
project: "Projekt",
|
||||
project_file: "Soubor projektu",
|
||||
customer: "Zákazník",
|
||||
trip: "Jízda",
|
||||
vehicle: "Vozidlo",
|
||||
bank_account: "Bankovní účet",
|
||||
company_settings: "Nastavení firmy",
|
||||
audit_logs: "Audit log",
|
||||
warehouse_item: "Skladová položka",
|
||||
warehouse_receipt: "Příjemka",
|
||||
warehouse_issue: "Výdejka",
|
||||
warehouse_reservation: "Rezervace",
|
||||
warehouse_inventory: "Inventura",
|
||||
warehouse_supplier: "Dodavatel",
|
||||
warehouse_category: "Kategorie skladu",
|
||||
warehouse_location: "Skladová lokace",
|
||||
warehouse_receipt_attachment: "Příloha příjemky",
|
||||
work_plan_entry: "Plán prací – záznam",
|
||||
work_plan_override: "Plán prací – přepsání dne",
|
||||
plan_category: "Plán prací – kategorie",
|
||||
session: "Relace",
|
||||
};
|
||||
@@ -9,12 +9,8 @@ export const dashboardOptions = () =>
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
export const require2FAOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["settings", "2fa"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ require_2fa: boolean }>("/api/admin/totp/required"),
|
||||
});
|
||||
// require2FAOptions lives in ./settings.ts (the single definition consumers
|
||||
// import). The duplicate copy that used to be here was dead.
|
||||
|
||||
export interface Session {
|
||||
id: number | string;
|
||||
|
||||
@@ -82,3 +82,12 @@ export const orderDetailOptions = (id: string | undefined) =>
|
||||
queryFn: () => jsonQuery<OrderData>(`/api/admin/orders/${id}`),
|
||||
enabled: !!id,
|
||||
});
|
||||
|
||||
export const orderNextNumberOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["orders", "next-number"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ next_number?: string; number?: string }>(
|
||||
"/api/admin/orders/next-number",
|
||||
),
|
||||
});
|
||||
|
||||
@@ -109,3 +109,12 @@ export const projectFilesOptions = (projectId: number, path: string) =>
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const projectNextNumberOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["projects", "next-number"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ next_number?: string; number?: string }>(
|
||||
"/api/admin/projects/next-number",
|
||||
),
|
||||
});
|
||||
|
||||
@@ -76,9 +76,6 @@ export const systemInfoOptions = () =>
|
||||
),
|
||||
});
|
||||
|
||||
/** @deprecated Use systemInfoOptions instead — this query fetches system-info, not system settings. */
|
||||
export const systemSettingsOptions = systemInfoOptions;
|
||||
|
||||
export const require2FAOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["settings", "2fa"],
|
||||
|
||||
@@ -464,6 +464,26 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Keep Quill picker dropdowns on-screen on narrow phones.
|
||||
The font picker hard-codes min-width: 11rem and the color picker a fixed
|
||||
176px width — both overflow a ~360px viewport. */
|
||||
@media (max-width: 480px) {
|
||||
.admin-rich-editor .ql-snow .ql-picker-options,
|
||||
.admin-rich-editor .ql-snow .ql-font .ql-picker-options,
|
||||
.admin-rich-editor .ql-snow .ql-size .ql-picker-options {
|
||||
min-width: 0;
|
||||
max-width: calc(100vw - 32px);
|
||||
}
|
||||
|
||||
.admin-rich-editor
|
||||
.ql-snow
|
||||
.ql-color-picker
|
||||
.ql-picker-options[aria-hidden="false"] {
|
||||
width: auto;
|
||||
max-width: calc(100vw - 32px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.offers-items-table .admin-table td .admin-form-input {
|
||||
font-size: 16px;
|
||||
|
||||
@@ -3,10 +3,10 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { Link } from "react-router-dom";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { motion } from "framer-motion";
|
||||
import AdminDatePicker from "../components/AdminDatePicker";
|
||||
import ConfirmModal from "../components/ConfirmModal";
|
||||
import useModalLock from "../hooks/useModalLock";
|
||||
import FormModal from "../components/FormModal";
|
||||
import {
|
||||
formatTime,
|
||||
calculateWorkMinutes,
|
||||
@@ -17,7 +17,7 @@ import Forbidden from "../components/Forbidden";
|
||||
import apiFetch from "../utils/api";
|
||||
import { jsonQuery } from "../lib/apiAdapter";
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import { czechPlural } from "../utils/formatters";
|
||||
import { czechPlural, todayLocalStr } from "../utils/formatters";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -140,8 +140,8 @@ export default function Attendance() {
|
||||
const [isLeaveModalOpen, setIsLeaveModalOpen] = useState(false);
|
||||
const [leaveForm, setLeaveForm] = useState({
|
||||
leave_type: "vacation",
|
||||
date_from: new Date().toISOString().split("T")[0],
|
||||
date_to: new Date().toISOString().split("T")[0],
|
||||
date_from: todayLocalStr(),
|
||||
date_to: todayLocalStr(),
|
||||
notes: "",
|
||||
});
|
||||
const [requestSubmitting, setRequestSubmitting] = useState(false);
|
||||
@@ -172,8 +172,6 @@ export default function Attendance() {
|
||||
}
|
||||
}, [statusQuery.data]);
|
||||
|
||||
useModalLock(isLeaveModalOpen);
|
||||
|
||||
if (!hasPermission("attendance.record")) return <Forbidden />;
|
||||
|
||||
const handlePunch = (action: string) => {
|
||||
@@ -334,8 +332,8 @@ export default function Attendance() {
|
||||
alert.success(result?.message || "Žádost odeslána");
|
||||
setLeaveForm({
|
||||
leave_type: "vacation",
|
||||
date_from: new Date().toISOString().split("T")[0],
|
||||
date_to: new Date().toISOString().split("T")[0],
|
||||
date_from: todayLocalStr(),
|
||||
date_to: todayLocalStr(),
|
||||
notes: "",
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -931,163 +929,127 @@ export default function Attendance() {
|
||||
</div>
|
||||
|
||||
{/* Leave Modal */}
|
||||
<AnimatePresence>
|
||||
{isLeaveModalOpen && (
|
||||
<motion.div
|
||||
className="admin-modal-overlay"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div
|
||||
className="admin-modal-backdrop"
|
||||
onClick={() => setIsLeaveModalOpen(false)}
|
||||
/>
|
||||
<motion.div
|
||||
className="admin-modal"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
<FormModal
|
||||
isOpen={isLeaveModalOpen}
|
||||
onClose={() => setIsLeaveModalOpen(false)}
|
||||
title="Žádost o nepřítomnost"
|
||||
onSubmit={() => {
|
||||
// Preserve original guard: do not submit when there are 0 business days.
|
||||
if (
|
||||
calculateBusinessDays(leaveForm.date_from, leaveForm.date_to) === 0
|
||||
)
|
||||
return;
|
||||
handleRequestSubmit();
|
||||
}}
|
||||
submitLabel="Odeslat žádost"
|
||||
submitDisabled={
|
||||
calculateBusinessDays(leaveForm.date_from, leaveForm.date_to) === 0
|
||||
}
|
||||
loading={requestSubmitting}
|
||||
>
|
||||
<div className="admin-form">
|
||||
<FormField label="Typ nepřítomnosti">
|
||||
<select
|
||||
value={leaveForm.leave_type}
|
||||
onChange={(e) =>
|
||||
setLeaveForm({
|
||||
...leaveForm,
|
||||
leave_type: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<div className="admin-modal-header">
|
||||
<h2 className="admin-modal-title">Žádost o nepřítomnost</h2>
|
||||
</div>
|
||||
<option value="vacation">Dovolená</option>
|
||||
<option value="sick">Nemoc</option>
|
||||
<option value="unpaid">Neplacené volno</option>
|
||||
</select>
|
||||
</FormField>
|
||||
|
||||
<div className="admin-modal-body">
|
||||
<div className="admin-form">
|
||||
<FormField label="Typ nepřítomnosti">
|
||||
<select
|
||||
value={leaveForm.leave_type}
|
||||
onChange={(e) =>
|
||||
setLeaveForm({
|
||||
...leaveForm,
|
||||
leave_type: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="vacation">Dovolená</option>
|
||||
<option value="sick">Nemoc</option>
|
||||
<option value="unpaid">Neplacené volno</option>
|
||||
</select>
|
||||
</FormField>
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<FormField label="Od">
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={leaveForm.date_from}
|
||||
onChange={(val: string) => {
|
||||
setLeaveForm((prev) => ({
|
||||
...prev,
|
||||
date_from: val,
|
||||
date_to: prev.date_to < val ? val : prev.date_to,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Do">
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={leaveForm.date_to}
|
||||
minDate={leaveForm.date_from}
|
||||
onChange={(val: string) =>
|
||||
setLeaveForm({ ...leaveForm, date_to: val })
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<FormField label="Od">
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={leaveForm.date_from}
|
||||
onChange={(val: string) => {
|
||||
setLeaveForm((prev) => ({
|
||||
...prev,
|
||||
date_from: val,
|
||||
date_to: prev.date_to < val ? val : prev.date_to,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Do">
|
||||
<AdminDatePicker
|
||||
mode="date"
|
||||
value={leaveForm.date_to}
|
||||
minDate={leaveForm.date_from}
|
||||
onChange={(val: string) =>
|
||||
setLeaveForm({ ...leaveForm, date_to: val })
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
{leaveForm.date_from && leaveForm.date_to && (
|
||||
<div className="admin-form-group">
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "1.5rem",
|
||||
padding: "0.75rem 1rem",
|
||||
background: "var(--bg-tertiary)",
|
||||
borderRadius: "var(--border-radius)",
|
||||
fontSize: "0.875rem",
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
<strong>
|
||||
{calculateBusinessDays(
|
||||
leaveForm.date_from,
|
||||
leaveForm.date_to,
|
||||
)}
|
||||
</strong>{" "}
|
||||
{czechPlural(
|
||||
calculateBusinessDays(
|
||||
leaveForm.date_from,
|
||||
leaveForm.date_to,
|
||||
),
|
||||
"pracovní den",
|
||||
"pracovní dny",
|
||||
"pracovních dnů",
|
||||
)}
|
||||
</span>
|
||||
<span className="text-muted">
|
||||
{calculateBusinessDays(
|
||||
leaveForm.date_from,
|
||||
leaveForm.date_to,
|
||||
) * 8}{" "}
|
||||
hodin
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField label="Poznámka">
|
||||
<textarea
|
||||
value={leaveForm.notes}
|
||||
onChange={(e) =>
|
||||
setLeaveForm({ ...leaveForm, notes: e.target.value })
|
||||
}
|
||||
placeholder="Volitelná poznámka..."
|
||||
className="admin-form-textarea"
|
||||
rows={2}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsLeaveModalOpen(false)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={requestSubmitting}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRequestSubmit}
|
||||
disabled={
|
||||
requestSubmitting ||
|
||||
{leaveForm.date_from && leaveForm.date_to && (
|
||||
<div className="admin-form-group">
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "1.5rem",
|
||||
padding: "0.75rem 1rem",
|
||||
background: "var(--bg-tertiary)",
|
||||
borderRadius: "var(--border-radius)",
|
||||
fontSize: "0.875rem",
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
<strong>
|
||||
{calculateBusinessDays(
|
||||
leaveForm.date_from,
|
||||
leaveForm.date_to,
|
||||
)}
|
||||
</strong>{" "}
|
||||
{czechPlural(
|
||||
calculateBusinessDays(
|
||||
leaveForm.date_from,
|
||||
leaveForm.date_to,
|
||||
) === 0
|
||||
}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
{requestSubmitting ? "Odesílám..." : "Odeslat žádost"}
|
||||
</button>
|
||||
),
|
||||
"pracovní den",
|
||||
"pracovní dny",
|
||||
"pracovních dnů",
|
||||
)}
|
||||
</span>
|
||||
<span className="text-muted">
|
||||
{calculateBusinessDays(
|
||||
leaveForm.date_from,
|
||||
leaveForm.date_to,
|
||||
) * 8}{" "}
|
||||
hodin
|
||||
</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField label="Poznámka">
|
||||
<textarea
|
||||
value={leaveForm.notes}
|
||||
onChange={(e) =>
|
||||
setLeaveForm({ ...leaveForm, notes: e.target.value })
|
||||
}
|
||||
placeholder="Volitelná poznámka..."
|
||||
className="admin-form-textarea"
|
||||
rows={2}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</FormModal>
|
||||
|
||||
<ConfirmModal
|
||||
isOpen={gpsConfirm.isOpen}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { motion } from "framer-motion";
|
||||
import AdminDatePicker from "../components/AdminDatePicker";
|
||||
import FormField from "../components/FormField";
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import { todayLocalStr } from "../utils/formatters";
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
interface CreateForm {
|
||||
@@ -46,7 +47,7 @@ export default function AttendanceCreate() {
|
||||
});
|
||||
|
||||
const [form, setForm] = useState<CreateForm>(() => {
|
||||
const today = new Date().toISOString().split("T")[0];
|
||||
const today = todayLocalStr();
|
||||
return {
|
||||
user_id: "",
|
||||
shift_date: today,
|
||||
|
||||
@@ -11,6 +11,7 @@ import AdminDatePicker from "../components/AdminDatePicker";
|
||||
import { czechPlural } from "../utils/formatters";
|
||||
import apiFetch from "../utils/api";
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import { ENTITY_TYPE_LABELS } from "../lib/entityTypeLabels";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -44,27 +45,6 @@ const ACTION_BADGE_CLASS: Record<string, string> = {
|
||||
access_denied: "admin-badge-danger",
|
||||
};
|
||||
|
||||
const ENTITY_TYPE_LABELS: Record<string, string> = {
|
||||
user: "Uživatel",
|
||||
attendance: "Docházka",
|
||||
leave_request: "Žádost o nepřítomnost",
|
||||
offers_quotation: "Nabídka",
|
||||
offers_customer: "Zákazník",
|
||||
offers_item_template: "Šablona položky",
|
||||
offers_scope_template: "Šablona rozsahu",
|
||||
offers_settings: "Nastavení nabídek",
|
||||
orders_order: "Objednávka",
|
||||
invoices_invoice: "Faktura",
|
||||
projects_project: "Projekt",
|
||||
role: "Role",
|
||||
trips: "Jízda",
|
||||
vehicles: "Vozidlo",
|
||||
bank_account: "Bankovní účet",
|
||||
work_plan_entry: "Plán prací – záznam",
|
||||
work_plan_override: "Plán prací – přepsání dne",
|
||||
plan_category: "Plán prací – kategorie",
|
||||
};
|
||||
|
||||
const ACTION_OPTIONS = Object.entries(ACTION_LABELS).map(([value, label]) => ({
|
||||
value,
|
||||
label,
|
||||
|
||||
@@ -48,7 +48,7 @@ import {
|
||||
import { offerCustomersOptions, type Customer } from "../lib/queries/offers";
|
||||
import { bankAccountsOptions, type BankAccount } from "../lib/queries/common";
|
||||
import { jsonQuery } from "../lib/apiAdapter";
|
||||
import { formatCurrency, formatDate } from "../utils/formatters";
|
||||
import { formatCurrency, formatDate, todayLocalStr } from "../utils/formatters";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -326,9 +326,9 @@ export default function InvoiceDetail() {
|
||||
customer_id: null,
|
||||
customer_name: "",
|
||||
order_id: fromOrderId ? Number(fromOrderId) : null,
|
||||
issue_date: new Date().toISOString().split("T")[0],
|
||||
issue_date: todayLocalStr(),
|
||||
due_date: new Date(Date.now() + 14 * 86400000).toISOString().split("T")[0],
|
||||
tax_date: new Date().toISOString().split("T")[0],
|
||||
tax_date: todayLocalStr(),
|
||||
currency: "CZK",
|
||||
apply_vat: 1,
|
||||
vat_rate: 21,
|
||||
|
||||
@@ -56,7 +56,7 @@ import AdminDatePicker from "../components/AdminDatePicker";
|
||||
import RichEditor from "../components/RichEditor";
|
||||
import useDebounce from "../hooks/useDebounce";
|
||||
import apiFetch from "../utils/api";
|
||||
import { formatCurrency } from "../utils/formatters";
|
||||
import { formatCurrency, todayLocalStr } from "../utils/formatters";
|
||||
import {
|
||||
companySettingsOptions,
|
||||
type CompanySettingsData,
|
||||
@@ -101,7 +101,7 @@ const emptyForm: OfferForm = {
|
||||
project_code: "",
|
||||
customer_id: null,
|
||||
customer_name: "",
|
||||
created_at: new Date().toISOString().split("T")[0],
|
||||
created_at: todayLocalStr(),
|
||||
valid_until: "",
|
||||
currency: "CZK",
|
||||
language: "EN",
|
||||
@@ -678,7 +678,7 @@ export default function OfferDetail() {
|
||||
}
|
||||
}
|
||||
if (!isEdit && result.data?.id) {
|
||||
queryClient.invalidateQueries({ queryKey: ["offers", "list"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["offers"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||
@@ -690,7 +690,7 @@ export default function OfferDetail() {
|
||||
items,
|
||||
sections,
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ["offers", "list"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["offers"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||
@@ -736,7 +736,7 @@ export default function OfferDetail() {
|
||||
if (result.success) {
|
||||
setShowOrderModal(false);
|
||||
alert.success(result.message || "Objednávka byla vytvořena");
|
||||
await queryClient.invalidateQueries({ queryKey: ["offers", "list"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["offers"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||
@@ -762,7 +762,7 @@ export default function OfferDetail() {
|
||||
setInvalidateConfirm(false);
|
||||
setOfferStatus("invalidated");
|
||||
alert.success(result.message || "Nabídka byla zneplatněna");
|
||||
queryClient.invalidateQueries({ queryKey: ["offers", "list"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["offers"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||
@@ -789,7 +789,7 @@ export default function OfferDetail() {
|
||||
deletingRef.current = true;
|
||||
queryClient.removeQueries({ queryKey: ["offers", id] });
|
||||
alert.success(result.message || "Nabídka byla smazána");
|
||||
await queryClient.invalidateQueries({ queryKey: ["offers", "list"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["offers"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import apiFetch from "../utils/api";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { motion } from "framer-motion";
|
||||
import ConfirmModal from "../components/ConfirmModal";
|
||||
import FormModal from "../components/FormModal";
|
||||
import FormField from "../components/FormField";
|
||||
|
||||
import { formatCurrency, formatDate, czechPlural } from "../utils/formatters";
|
||||
import SortIcon from "../components/SortIcon";
|
||||
import useTableSort from "../hooks/useTableSort";
|
||||
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
|
||||
import { orderListOptions } from "../lib/queries/orders";
|
||||
import {
|
||||
orderListOptions,
|
||||
orderNextNumberOptions,
|
||||
} from "../lib/queries/orders";
|
||||
import { offerCustomersOptions } from "../lib/queries/offers";
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import Pagination from "../components/Pagination";
|
||||
|
||||
@@ -71,6 +79,126 @@ export default function Orders() {
|
||||
},
|
||||
});
|
||||
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [createForm, setCreateForm] = useState({
|
||||
customer_id: "",
|
||||
customer_order_number: "",
|
||||
currency: "CZK",
|
||||
vat_rate: "21",
|
||||
apply_vat: true,
|
||||
scope_title: "",
|
||||
scope_description: "",
|
||||
notes: "",
|
||||
create_project: true,
|
||||
price: "",
|
||||
quantity: "1",
|
||||
});
|
||||
const [creating, setCreating] = useState(false);
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const [orderAttachment, setOrderAttachment] = useState<File | null>(null);
|
||||
|
||||
const customersQuery = useQuery({
|
||||
...offerCustomersOptions(),
|
||||
enabled: showCreate,
|
||||
});
|
||||
const nextNumberQuery = useQuery({
|
||||
...orderNextNumberOptions(),
|
||||
enabled: showCreate,
|
||||
});
|
||||
|
||||
const openCreate = () => {
|
||||
setCreateForm({
|
||||
customer_id: "",
|
||||
customer_order_number: "",
|
||||
currency: "CZK",
|
||||
vat_rate: "21",
|
||||
apply_vat: true,
|
||||
scope_title: "",
|
||||
scope_description: "",
|
||||
notes: "",
|
||||
create_project: true,
|
||||
price: "",
|
||||
quantity: "1",
|
||||
});
|
||||
setOrderAttachment(null);
|
||||
setShowCreate(true);
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
setCreating(true);
|
||||
try {
|
||||
const priceNum = createForm.price ? Number(createForm.price) : 0;
|
||||
const qtyNum = createForm.quantity ? Number(createForm.quantity) : 1;
|
||||
const items =
|
||||
priceNum > 0
|
||||
? [
|
||||
{
|
||||
description: createForm.scope_title || "Položka",
|
||||
quantity: qtyNum,
|
||||
unit_price: priceNum,
|
||||
is_included_in_total: true,
|
||||
},
|
||||
]
|
||||
: undefined;
|
||||
|
||||
let fetchOptions: RequestInit;
|
||||
if (orderAttachment) {
|
||||
const fd = new FormData();
|
||||
if (createForm.customer_id)
|
||||
fd.append("customer_id", createForm.customer_id);
|
||||
fd.append("customer_order_number", createForm.customer_order_number);
|
||||
fd.append("currency", createForm.currency);
|
||||
fd.append("vat_rate", createForm.vat_rate);
|
||||
fd.append("apply_vat", createForm.apply_vat ? "1" : "0");
|
||||
fd.append("scope_title", createForm.scope_title);
|
||||
fd.append("scope_description", createForm.scope_description);
|
||||
fd.append("notes", createForm.notes);
|
||||
fd.append("create_project", createForm.create_project ? "1" : "0");
|
||||
if (items) fd.append("items", JSON.stringify(items));
|
||||
fd.append("attachment", orderAttachment);
|
||||
fetchOptions = { method: "POST", body: fd };
|
||||
} else {
|
||||
fetchOptions = {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
customer_id: createForm.customer_id
|
||||
? Number(createForm.customer_id)
|
||||
: null,
|
||||
customer_order_number: createForm.customer_order_number,
|
||||
currency: createForm.currency,
|
||||
vat_rate: createForm.vat_rate,
|
||||
apply_vat: createForm.apply_vat,
|
||||
scope_title: createForm.scope_title,
|
||||
scope_description: createForm.scope_description,
|
||||
notes: createForm.notes,
|
||||
create_project: createForm.create_project,
|
||||
...(items ? { items } : {}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const response = await apiFetch(`${API_BASE}/orders`, fetchOptions);
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
setShowCreate(false);
|
||||
alert.success(result.message || "Objednávka byla vytvořena");
|
||||
await queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["offers"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||
if (result.data?.id) navigate(`/orders/${result.data.id}`);
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se vytvořit objednávku");
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const {
|
||||
items: orders,
|
||||
pagination,
|
||||
@@ -120,6 +248,27 @@ export default function Orders() {
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{hasPermission("orders.create") && (
|
||||
<div className="admin-page-actions">
|
||||
<button
|
||||
onClick={openCreate}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="12" y1="5" x2="12" y2="19" />
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
Vytvořit objednávku
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
@@ -377,6 +526,230 @@ export default function Orders() {
|
||||
type="danger"
|
||||
loading={deleteMutation.isPending}
|
||||
/>
|
||||
|
||||
<FormModal
|
||||
isOpen={showCreate}
|
||||
onClose={() => setShowCreate(false)}
|
||||
onSubmit={handleCreate}
|
||||
title="Vytvořit objednávku bez nabídky"
|
||||
submitLabel="Vytvořit"
|
||||
loading={creating}
|
||||
>
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Zákazník">
|
||||
<select
|
||||
value={createForm.customer_id}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, customer_id: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
>
|
||||
<option value="">— bez zákazníka —</option>
|
||||
{(customersQuery.data ?? []).map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
<FormField label="Číslo objednávky zákazníka">
|
||||
<input
|
||||
type="text"
|
||||
value={createForm.customer_order_number}
|
||||
onChange={(e) =>
|
||||
setCreateForm({
|
||||
...createForm,
|
||||
customer_order_number: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Měna">
|
||||
<select
|
||||
value={createForm.currency}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, currency: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
>
|
||||
<option value="CZK">CZK</option>
|
||||
<option value="EUR">EUR</option>
|
||||
<option value="USD">USD</option>
|
||||
<option value="GBP">GBP</option>
|
||||
</select>
|
||||
</FormField>
|
||||
<FormField label="Sazba DPH (%)">
|
||||
<input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
value={createForm.vat_rate}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, vat_rate: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
min="0"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Cena za jednotku (bez DPH)">
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={createForm.price}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, price: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
min="0"
|
||||
step="0.01"
|
||||
placeholder="0"
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Množství">
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={createForm.quantity}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, quantity: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
min="0"
|
||||
step="1"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<FormField label="Předmět (scope)">
|
||||
<input
|
||||
type="text"
|
||||
value={createForm.scope_title}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, scope_title: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Popis">
|
||||
<textarea
|
||||
value={createForm.scope_description}
|
||||
onChange={(e) =>
|
||||
setCreateForm({
|
||||
...createForm,
|
||||
scope_description: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-input"
|
||||
rows={3}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Poznámka">
|
||||
<textarea
|
||||
value={createForm.notes}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, notes: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
rows={2}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Příloha (PO zákazníka, PDF)">
|
||||
{orderAttachment ? (
|
||||
<div className="flex-row gap-2">
|
||||
<span className="text-md">
|
||||
{orderAttachment.name}{" "}
|
||||
<span className="text-tertiary">
|
||||
({(orderAttachment.size / 1024).toFixed(0)} KB)
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOrderAttachment(null)}
|
||||
className="admin-btn-icon"
|
||||
title="Odebrat"
|
||||
style={{ marginLeft: "auto" }}
|
||||
>
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M18 6L6 18M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label
|
||||
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||
style={{
|
||||
cursor: "pointer",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: "0.4rem",
|
||||
}}
|
||||
>
|
||||
Vybrat soubor
|
||||
<input
|
||||
type="file"
|
||||
accept="application/pdf"
|
||||
onChange={(e) =>
|
||||
setOrderAttachment(e.target.files?.[0] || null)
|
||||
}
|
||||
style={{ display: "none" }}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</FormField>
|
||||
|
||||
<label className="admin-form-checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={createForm.apply_vat}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, apply_vat: e.target.checked })
|
||||
}
|
||||
/>
|
||||
<span>Účtovat DPH</span>
|
||||
</label>
|
||||
|
||||
<label className="admin-form-checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={createForm.create_project}
|
||||
onChange={(e) =>
|
||||
setCreateForm({
|
||||
...createForm,
|
||||
create_project: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>Vytvořit propojený projekt</span>
|
||||
</label>
|
||||
|
||||
<p className="admin-form-hint">
|
||||
Číslo objednávky:{" "}
|
||||
<strong>
|
||||
{nextNumberQuery.data?.number ??
|
||||
nextNumberQuery.data?.next_number ??
|
||||
"…"}
|
||||
</strong>{" "}
|
||||
(přiděleno automaticky)
|
||||
</p>
|
||||
</div>
|
||||
</FormModal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import PlanCategoriesModal from "../components/PlanCategoriesModal";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { projectListOptions, type Project } from "../lib/queries/projects";
|
||||
import { planCategoriesOptions, type PlanCategory } from "../lib/queries/plan";
|
||||
import "../plan.css";
|
||||
// plan.css is imported once globally in AdminApp.tsx — no per-page re-import.
|
||||
|
||||
const MONTH_NAMES = [
|
||||
"Leden",
|
||||
@@ -576,29 +576,35 @@ export default function PlanWork() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.12 }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
onClick={goToToday}
|
||||
>
|
||||
Dnes
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
onClick={goPrev}
|
||||
aria-label="Předchozí"
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
onClick={goNext}
|
||||
aria-label="Další"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
{/* Nav buttons grouped so they stay on one row when the toolbar
|
||||
stacks on mobile (see .plan-toolbar-nav in plan.css). On desktop
|
||||
the wrapper is an inline-flex with the same 12px gap, so the
|
||||
layout is visually identical. */}
|
||||
<div className="plan-toolbar-nav">
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
onClick={goToToday}
|
||||
>
|
||||
Dnes
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
onClick={goPrev}
|
||||
aria-label="Předchozí"
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
onClick={goNext}
|
||||
aria-label="Další"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
<span className="plan-range-label-slot">
|
||||
<AnimatePresence mode="popLayout" initial={false}>
|
||||
<motion.span
|
||||
@@ -644,7 +650,7 @@ export default function PlanWork() {
|
||||
{canEdit && (
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
className="admin-btn admin-btn-secondary plan-toolbar-cat"
|
||||
onClick={() => setCatModalOpen(true)}
|
||||
>
|
||||
Správa kategorií
|
||||
|
||||
@@ -81,10 +81,18 @@ export default function ProjectDetail() {
|
||||
const notes: ProjectNote[] = project?.project_notes || [];
|
||||
|
||||
const { data: usersData } = useQuery(userListOptions("projects.view"));
|
||||
const users: User[] = (usersData ?? []).map((u: ApiUser) => ({
|
||||
id: u.id,
|
||||
name: `${u.first_name || ""} ${u.last_name || ""}`.trim() || u.username,
|
||||
}));
|
||||
// Only active users with projects.view — but keep the project's CURRENT
|
||||
// assignee in the list even if they're now inactive, so the select still
|
||||
// reflects the saved value (marked "(neaktivní)" so it's clear).
|
||||
const assignedUserId = project?.responsible_user_id || "";
|
||||
const users: User[] = (usersData ?? [])
|
||||
.filter((u: ApiUser) => u.is_active || String(u.id) === assignedUserId)
|
||||
.map((u: ApiUser) => ({
|
||||
id: u.id,
|
||||
name:
|
||||
(`${u.first_name || ""} ${u.last_name || ""}`.trim() || u.username) +
|
||||
(u.is_active ? "" : " (neaktivní)"),
|
||||
}));
|
||||
|
||||
// Reset form sync when navigating to a different project
|
||||
const formInitialized = useRef(false);
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { Link } from "react-router-dom";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { motion } from "framer-motion";
|
||||
import ConfirmModal from "../components/ConfirmModal";
|
||||
import FormModal from "../components/FormModal";
|
||||
import FormField from "../components/FormField";
|
||||
|
||||
import { formatDate, czechPlural } from "../utils/formatters";
|
||||
import SortIcon from "../components/SortIcon";
|
||||
import useTableSort from "../hooks/useTableSort";
|
||||
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
|
||||
import { projectListOptions } from "../lib/queries/projects";
|
||||
import {
|
||||
projectListOptions,
|
||||
projectNextNumberOptions,
|
||||
} from "../lib/queries/projects";
|
||||
import { offerCustomersOptions } from "../lib/queries/offers";
|
||||
import { userListOptions } from "../lib/queries/users";
|
||||
import { useApiMutation } from "../lib/queries/mutations";
|
||||
import Pagination from "../components/Pagination";
|
||||
|
||||
@@ -73,6 +81,74 @@ export default function Projects() {
|
||||
},
|
||||
});
|
||||
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [createForm, setCreateForm] = useState({
|
||||
name: "",
|
||||
customer_id: "",
|
||||
responsible_user_id: "",
|
||||
status: "aktivni",
|
||||
start_date: "",
|
||||
end_date: "",
|
||||
notes: "",
|
||||
});
|
||||
const [createErrors, setCreateErrors] = useState<Record<string, string>>({});
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
const customersQuery = useQuery({
|
||||
...offerCustomersOptions(),
|
||||
enabled: showCreate,
|
||||
});
|
||||
// Responsible-person picker: only users whose role can view projects
|
||||
// (projects.view, filtered server-side) and who are active.
|
||||
const usersQuery = useQuery({
|
||||
...userListOptions("projects.view"),
|
||||
enabled: showCreate,
|
||||
});
|
||||
const nextNumberQuery = useQuery({
|
||||
...projectNextNumberOptions(),
|
||||
enabled: showCreate,
|
||||
});
|
||||
|
||||
const createMutation = useApiMutation<typeof createForm, { id: number }>({
|
||||
url: () => `${API_BASE}/projects`,
|
||||
method: () => "POST",
|
||||
invalidate: ["projects", "orders", "offers", "invoices", "attendance"],
|
||||
onSuccess: () => {
|
||||
setShowCreate(false);
|
||||
alert.success("Projekt byl vytvořen");
|
||||
},
|
||||
});
|
||||
|
||||
const openCreate = () => {
|
||||
setCreateForm({
|
||||
name: "",
|
||||
customer_id: "",
|
||||
responsible_user_id: "",
|
||||
status: "aktivni",
|
||||
start_date: "",
|
||||
end_date: "",
|
||||
notes: "",
|
||||
});
|
||||
setCreateErrors({});
|
||||
setShowCreate(true);
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
const errs: Record<string, string> = {};
|
||||
if (!createForm.name.trim()) errs.name = "Zadejte název projektu";
|
||||
setCreateErrors(errs);
|
||||
if (Object.keys(errs).length > 0) return;
|
||||
|
||||
setCreating(true);
|
||||
try {
|
||||
await createMutation.mutateAsync(createForm);
|
||||
} catch (e) {
|
||||
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const {
|
||||
items: projects,
|
||||
pagination,
|
||||
@@ -126,6 +202,27 @@ export default function Projects() {
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{hasPermission("projects.create") && (
|
||||
<div className="admin-page-actions">
|
||||
<button
|
||||
onClick={openCreate}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="12" y1="5" x2="12" y2="19" />
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
Přidat projekt
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
@@ -172,7 +269,8 @@ export default function Projects() {
|
||||
fontSize: "0.875rem",
|
||||
}}
|
||||
>
|
||||
Projekt se vytvoří automaticky při vytvoření objednávky.
|
||||
Projekty vznikají z objednávek nebo je můžete vytvořit ručně
|
||||
tlačítkem „Přidat projekt".
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
@@ -233,6 +331,7 @@ export default function Projects() {
|
||||
order={order}
|
||||
/>
|
||||
</th>
|
||||
<th>Typ</th>
|
||||
<th>Objednávka</th>
|
||||
<th>Akce</th>
|
||||
</tr>
|
||||
@@ -257,6 +356,11 @@ export default function Projects() {
|
||||
</td>
|
||||
<td className="admin-mono">{formatDate(p.start_date)}</td>
|
||||
<td className="admin-mono">{formatDate(p.end_date)}</td>
|
||||
<td>
|
||||
<span className="admin-badge">
|
||||
{p.order_id ? "Z objednávky" : "Samostatný"}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
{p.order_id ? (
|
||||
<Link
|
||||
@@ -359,6 +463,116 @@ export default function Projects() {
|
||||
type="danger"
|
||||
loading={deleteMutation.isPending}
|
||||
/>
|
||||
|
||||
<FormModal
|
||||
isOpen={showCreate}
|
||||
onClose={() => setShowCreate(false)}
|
||||
onSubmit={handleCreate}
|
||||
title="Přidat projekt"
|
||||
submitLabel="Vytvořit"
|
||||
loading={creating}
|
||||
>
|
||||
<div className="admin-form">
|
||||
<FormField label="Název" error={createErrors.name} required>
|
||||
<input
|
||||
type="text"
|
||||
value={createForm.name}
|
||||
onChange={(e) => {
|
||||
setCreateForm({ ...createForm, name: e.target.value });
|
||||
setCreateErrors((p) => ({ ...p, name: "" }));
|
||||
}}
|
||||
className="admin-form-input"
|
||||
placeholder="Název projektu"
|
||||
aria-invalid={!!createErrors.name}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Zákazník">
|
||||
<select
|
||||
value={createForm.customer_id}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, customer_id: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
>
|
||||
<option value="">— bez zákazníka —</option>
|
||||
{(customersQuery.data ?? []).map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Zodpovědná osoba">
|
||||
<select
|
||||
value={createForm.responsible_user_id}
|
||||
onChange={(e) =>
|
||||
setCreateForm({
|
||||
...createForm,
|
||||
responsible_user_id: e.target.value,
|
||||
})
|
||||
}
|
||||
className="admin-form-input"
|
||||
>
|
||||
<option value="">— nepřiřazeno —</option>
|
||||
{(usersQuery.data ?? [])
|
||||
.filter((u) => u.is_active)
|
||||
.map((u) => (
|
||||
<option key={u.id} value={u.id}>
|
||||
{u.first_name} {u.last_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Začátek">
|
||||
<input
|
||||
type="date"
|
||||
value={createForm.start_date}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, start_date: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Konec">
|
||||
<input
|
||||
type="date"
|
||||
value={createForm.end_date}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, end_date: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<FormField label="Poznámka">
|
||||
<textarea
|
||||
value={createForm.notes}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, notes: e.target.value })
|
||||
}
|
||||
className="admin-form-input"
|
||||
rows={3}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<p className="admin-form-hint">
|
||||
Číslo projektu:{" "}
|
||||
<strong>
|
||||
{nextNumberQuery.data?.number ??
|
||||
nextNumberQuery.data?.next_number ??
|
||||
"…"}
|
||||
</strong>{" "}
|
||||
(přiděleno automaticky)
|
||||
</p>
|
||||
</div>
|
||||
</FormModal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import FormModal from "../components/FormModal";
|
||||
import FormField from "../components/FormField";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { formatDate } from "../utils/attendanceHelpers";
|
||||
import { formatKm } from "../utils/formatters";
|
||||
import { formatKm, todayLocalStr } from "../utils/formatters";
|
||||
import apiFetch from "../utils/api";
|
||||
import {
|
||||
tripListOptions,
|
||||
@@ -53,7 +53,7 @@ export default function Trips() {
|
||||
}>({ show: false, tripId: null });
|
||||
const [form, setForm] = useState<TripForm>({
|
||||
vehicle_id: "",
|
||||
trip_date: new Date().toISOString().split("T")[0],
|
||||
trip_date: todayLocalStr(),
|
||||
start_km: "",
|
||||
end_km: "",
|
||||
route_from: "",
|
||||
@@ -117,10 +117,9 @@ export default function Trips() {
|
||||
|
||||
const openCreateModal = () => {
|
||||
setEditingTrip(null);
|
||||
const today = new Date().toISOString().split("T")[0];
|
||||
setForm({
|
||||
vehicle_id: "",
|
||||
trip_date: today,
|
||||
trip_date: todayLocalStr(),
|
||||
start_km: "",
|
||||
end_km: "",
|
||||
route_from: "",
|
||||
|
||||
@@ -83,11 +83,17 @@
|
||||
.plan-grid-wrap {
|
||||
position: relative;
|
||||
overflow: auto;
|
||||
/* Smooth momentum scroll on touch, and keep scroll chaining contained so a
|
||||
fling inside the grid doesn't bounce the whole page (or trigger
|
||||
pull-to-refresh) on mobile. */
|
||||
-webkit-overflow-scrolling: touch;
|
||||
overscroll-behavior: contain;
|
||||
background: var(--plan-paper);
|
||||
border: 1px solid var(--plan-paper-rule);
|
||||
border-radius: 14px;
|
||||
box-shadow: var(--plan-shadow);
|
||||
max-height: calc(100vh - 240px);
|
||||
max-height: calc(100dvh - 240px);
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
@@ -726,6 +732,16 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Nav button group (Dnes / ← / →). On desktop it's an inline-flex with the
|
||||
same 12px gap the toolbar used between the three loose buttons before, so
|
||||
the layout is unchanged. On mobile it becomes a full-width row (see the
|
||||
≤640px block below). */
|
||||
.plan-toolbar-nav {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.plan-view-toggle {
|
||||
margin-left: auto;
|
||||
display: inline-flex;
|
||||
@@ -956,6 +972,118 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
Mobile toolbar — stack into clean full-width rows.
|
||||
|
||||
The desktop toolbar is one wrap-row with a fixed-width range label and a
|
||||
`margin-left:auto` view toggle; on a phone that collapses into a ragged,
|
||||
gappy mess. Here we lay it out as tidy stacked rows: nav buttons on row 1,
|
||||
the range label centered on its own row, a full-width segmented view toggle,
|
||||
then the category-manager button full-width. Source order already produces
|
||||
this stack once each block is forced to 100% width — no `order` juggling.
|
||||
---------------------------------------------------------------------------- */
|
||||
@media (max-width: 640px) {
|
||||
.plan-toolbar {
|
||||
gap: 8px;
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
/* Row 1: Dnes (grows) + the two arrow buttons (compact). */
|
||||
.plan-toolbar-nav {
|
||||
display: flex;
|
||||
flex: 1 1 100%;
|
||||
gap: 8px;
|
||||
}
|
||||
.plan-toolbar-nav .admin-btn {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
/* The ← / → buttons carry an aria-label; "Dnes" does not — keep the arrows
|
||||
compact and let "Dnes" take the remaining width. */
|
||||
.plan-toolbar-nav .admin-btn[aria-label] {
|
||||
flex: 0 0 auto;
|
||||
min-width: 56px;
|
||||
}
|
||||
|
||||
/* Row 2: range label, full width, centered — drop the desktop min-width. */
|
||||
.plan-range-label-slot {
|
||||
flex: 1 1 100%;
|
||||
min-width: 0;
|
||||
justify-content: center;
|
||||
}
|
||||
.plan-range-label {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
/* Row 3: view toggle as a full-width segmented control, two equal halves. */
|
||||
.plan-view-toggle {
|
||||
flex: 1 1 100%;
|
||||
margin-left: 0;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.plan-view-toggle .admin-btn {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
/* Row 4: category-manager button, full width. */
|
||||
.plan-toolbar-cat {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
|
||||
/* Keep the whole grid inside the viewport so the toolbar stays put and the
|
||||
sticky header / date column do the orienting (rather than the page
|
||||
scrolling the header out of view). */
|
||||
.plan-grid-wrap {
|
||||
max-height: calc(100dvh - 300px);
|
||||
min-height: 280px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
Small phones — tighten columns so ~2 people are comfortably visible at
|
||||
360–390px, and shrink the date "stamp" a touch. The colgroup <col> width is
|
||||
what actually pins the date column (min-width on the cells is only a floor),
|
||||
so it must be set here too, not just on the cells.
|
||||
---------------------------------------------------------------------------- */
|
||||
@media (max-width: 480px) {
|
||||
.plan-grid col.plan-grid-date-col {
|
||||
width: 72px;
|
||||
}
|
||||
.plan-grid thead th.plan-grid-date-col {
|
||||
min-width: 72px;
|
||||
padding-left: 10px;
|
||||
padding-right: 8px;
|
||||
}
|
||||
.plan-grid tbody td.plan-grid-date-col {
|
||||
min-width: 72px;
|
||||
padding: 8px 8px 8px 10px;
|
||||
}
|
||||
.plan-grid tbody td.plan-grid-date-col .plan-date-daynum {
|
||||
font-size: 14px;
|
||||
}
|
||||
.plan-grid tbody td {
|
||||
min-width: 132px;
|
||||
}
|
||||
.plan-cell {
|
||||
min-height: 56px;
|
||||
padding: 8px 9px 9px 14px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
Touch devices — the "+" add-hint and the tape-grow are hover-only, so they
|
||||
never surface on a phone. Show a faint, persistent "+" on empty *editable*
|
||||
cells so tapping-to-add is discoverable. Read-only and past cells already
|
||||
suppress the glyph (content:none / the readonly chain), so they stay inert.
|
||||
---------------------------------------------------------------------------- */
|
||||
@media (hover: none) {
|
||||
.plan-cell--empty:not(.plan-cell--readonly)::after {
|
||||
opacity: 0.26;
|
||||
color: var(--plan-ink-faint);
|
||||
}
|
||||
}
|
||||
|
||||
/* Respect users who don't want a moving target — kill the hover transforms
|
||||
and the rule-line animation. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
@@ -65,6 +65,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* Row actions — enlarge touch targets so icon buttons are tappable */
|
||||
@media (max-width: 768px) {
|
||||
.admin-table-actions a,
|
||||
.admin-table-actions button,
|
||||
.admin-table-actions .admin-btn-icon {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
.admin-table-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -21,11 +21,9 @@ interface AttendanceRecord {
|
||||
}>;
|
||||
}
|
||||
|
||||
export const formatDate = (dateStr: string | null | undefined): string => {
|
||||
if (!dateStr) return "—";
|
||||
const d = new Date(dateStr);
|
||||
return d.toLocaleDateString("cs-CZ");
|
||||
};
|
||||
// formatDate is defined once in ./formatters and re-exported here so existing
|
||||
// importers of attendanceHelpers keep working without a duplicate definition.
|
||||
export { formatDate } from "./formatters";
|
||||
|
||||
/** Extract time as HH:MM from a datetime string without timezone conversion */
|
||||
const extractTime = (datetime: string): string => {
|
||||
|
||||
@@ -18,26 +18,9 @@ export const STATUS_LABELS: Record<string, string> = {
|
||||
leave: "Nepřítomen",
|
||||
};
|
||||
|
||||
export const ENTITY_TYPE_LABELS: Record<string, string> = {
|
||||
user: "Uživatel",
|
||||
attendance: "Docházka",
|
||||
leave_request: "Žádost o nepřítomnost",
|
||||
offers_quotation: "Nabídka",
|
||||
offers_customer: "Zákazník",
|
||||
offers_item_template: "Šablona položky",
|
||||
offers_scope_template: "Šablona rozsahu",
|
||||
offers_settings: "Nastavení nabídek",
|
||||
orders_order: "Objednávka",
|
||||
invoices_invoice: "Faktura",
|
||||
projects_project: "Projekt",
|
||||
role: "Role",
|
||||
trips: "Jízda",
|
||||
vehicles: "Vozidlo",
|
||||
bank_account: "Bankovní účet",
|
||||
work_plan_entry: "Plán prací – záznam",
|
||||
work_plan_override: "Plán prací – přepsání dne",
|
||||
plan_category: "Plán prací – kategorie",
|
||||
};
|
||||
// Re-exported from the single source of truth so the dashboard activity feed
|
||||
// and the Audit Log page can't drift apart. See ../lib/entityTypeLabels.
|
||||
export { ENTITY_TYPE_LABELS } from "../lib/entityTypeLabels";
|
||||
|
||||
export const ACTION_LABELS: Record<string, string> = {
|
||||
create: "Vytvořil",
|
||||
|
||||
@@ -23,6 +23,19 @@ export function formatDate(dateStr: string | null | undefined): string {
|
||||
return d.toLocaleDateString("cs-CZ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Today's date as `YYYY-MM-DD` in LOCAL (Prague) time — use this for
|
||||
* date-input defaults. `new Date().toISOString().slice(0, 10)` gives the UTC
|
||||
* date, which is a day behind the Czech date during the post-midnight window
|
||||
* (Prague is UTC+1/+2), so a "today" default could land on yesterday.
|
||||
*/
|
||||
export function todayLocalStr(): string {
|
||||
const d = new Date();
|
||||
const m = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${m}-${day}`;
|
||||
}
|
||||
|
||||
export function formatKm(km: number | string): string {
|
||||
return new Intl.NumberFormat("cs-CZ").format(Number(km) || 0);
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ export default async function attendanceRoutes(
|
||||
return error(reply, "Nedostatečná oprávnění", 403);
|
||||
}
|
||||
const attendanceId = Number(query.attendance_id);
|
||||
if (!attendanceId) return error(reply, "Missing attendance_id", 400);
|
||||
if (!attendanceId) return error(reply, "Chybí attendance_id", 400);
|
||||
const data = await attendanceService.getProjectLogs(attendanceId);
|
||||
return reply.send({ success: true, data });
|
||||
}
|
||||
@@ -193,7 +193,7 @@ export default async function attendanceRoutes(
|
||||
// --- action=location: single record with GPS data ---
|
||||
if (action === "location") {
|
||||
const id = Number(query.id);
|
||||
if (!id) return error(reply, "Missing id", 400);
|
||||
if (!id) return error(reply, "Chybí id záznamu", 400);
|
||||
const record = await attendanceService.getLocationRecord(id);
|
||||
if (!record) return error(reply, "Záznam nenalezen", 404);
|
||||
const isAdmin = authData.permissions.includes("attendance.manage");
|
||||
|
||||
@@ -12,12 +12,10 @@ import { parseBody } from "../../schemas/common";
|
||||
// forensic history.
|
||||
const DELETE_ALL_CONFIRM = "DELETE_ALL_AUDIT" as const;
|
||||
|
||||
const AuditCleanupSchema = z
|
||||
.object({
|
||||
days: z.number().int().nonnegative().optional(),
|
||||
confirm: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
const AuditCleanupSchema = z.strictObject({
|
||||
days: z.number().int().nonnegative().optional(),
|
||||
confirm: z.string().optional(),
|
||||
});
|
||||
|
||||
export default async function auditLogRoutes(
|
||||
fastify: FastifyInstance,
|
||||
|
||||
@@ -104,7 +104,6 @@ export default async function ordersRoutes(
|
||||
request.headers["content-type"]?.includes("multipart");
|
||||
|
||||
if (isMultipart) {
|
||||
// === Order from quotation flow (multipart) ===
|
||||
const fields: Record<string, string> = {};
|
||||
let attachmentBuffer: Buffer | null = null;
|
||||
let attachmentName: string | null = null;
|
||||
@@ -119,37 +118,82 @@ export default async function ordersRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
const quotationId = parseInt(fields.quotationId, 10);
|
||||
const customerOrderNumber = fields.customerOrderNumber || "";
|
||||
|
||||
if (!quotationId || isNaN(quotationId)) {
|
||||
return error(reply, "Chybí ID nabídky", 400);
|
||||
// From-quotation flow (multipart with attachment)
|
||||
if (fields.quotationId) {
|
||||
const quotationId = parseInt(fields.quotationId, 10);
|
||||
const customerOrderNumber = fields.customerOrderNumber || "";
|
||||
if (!quotationId || isNaN(quotationId)) {
|
||||
return error(reply, "Chybí ID nabídky", 400);
|
||||
}
|
||||
const result = await createOrderFromQuotation({
|
||||
quotationId,
|
||||
customerOrderNumber,
|
||||
attachmentBuffer,
|
||||
attachmentName,
|
||||
});
|
||||
if ("error" in result)
|
||||
return error(reply, result.error!, result.status!);
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "order",
|
||||
entityId: result.data.order_id,
|
||||
description: `Vytvořena objednávka ${result.data.order_number} z nabídky #${result.data.quotationId}`,
|
||||
});
|
||||
return success(
|
||||
reply,
|
||||
{
|
||||
order_id: result.data.order_id,
|
||||
id: result.data.id,
|
||||
order_number: result.data.order_number,
|
||||
},
|
||||
201,
|
||||
"Objednávka byla vytvořena",
|
||||
);
|
||||
}
|
||||
|
||||
const result = await createOrderFromQuotation({
|
||||
quotationId,
|
||||
customerOrderNumber,
|
||||
// Manual order (multipart, with optional PO attachment)
|
||||
const rawManual: Record<string, unknown> = { ...fields };
|
||||
if (typeof fields.items === "string" && fields.items.length > 0) {
|
||||
try {
|
||||
rawManual.items = JSON.parse(fields.items);
|
||||
} catch {
|
||||
return error(reply, "Neplatná data položek", 400);
|
||||
}
|
||||
}
|
||||
const manualParsed = parseBody(CreateOrderSchema, rawManual);
|
||||
if ("error" in manualParsed)
|
||||
return error(reply, manualParsed.error, 400);
|
||||
|
||||
const result = await createOrder(
|
||||
manualParsed.data,
|
||||
attachmentBuffer,
|
||||
attachmentName,
|
||||
});
|
||||
);
|
||||
if ("error" in result)
|
||||
return error(reply, result.error!, result.status!);
|
||||
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "order",
|
||||
entityId: result.data.order_id,
|
||||
description: `Vytvořena objednávka ${result.data.order_number} z nabídky #${result.data.quotationId}`,
|
||||
entityId: result.id,
|
||||
description: `Vytvořena objednávka ${result.order_number}`,
|
||||
});
|
||||
if (result.project_id) {
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "project",
|
||||
entityId: result.project_id,
|
||||
description: `Vytvořen projekt k objednávce ${result.order_number}`,
|
||||
});
|
||||
}
|
||||
return success(
|
||||
reply,
|
||||
{
|
||||
order_id: result.data.order_id,
|
||||
id: result.data.id,
|
||||
order_number: result.data.order_number,
|
||||
},
|
||||
{ id: result.id },
|
||||
201,
|
||||
"Objednávka byla vytvořena",
|
||||
);
|
||||
@@ -216,6 +260,16 @@ export default async function ordersRoutes(
|
||||
entityId: result.id,
|
||||
description: `Vytvořena objednávka ${result.order_number}`,
|
||||
});
|
||||
if (result.project_id) {
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "project",
|
||||
entityId: result.project_id,
|
||||
description: `Vytvořen projekt k objednávce ${result.order_number}`,
|
||||
});
|
||||
}
|
||||
return success(
|
||||
reply,
|
||||
{ id: result.id },
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "../../middleware/auth";
|
||||
import { success, error, parseId } from "../../utils/response";
|
||||
import { parseBody } from "../../schemas/common";
|
||||
import { AuthData } from "../../types";
|
||||
import { logAudit } from "../../services/audit";
|
||||
import {
|
||||
CreatePlanEntrySchema,
|
||||
@@ -40,8 +41,12 @@ import {
|
||||
|
||||
const MAX_RANGE_DAYS = 92;
|
||||
|
||||
function isAdminLike(authData: any): boolean {
|
||||
return authData?.role === "admin";
|
||||
// NOTE: AuthData carries `roleName` (not `role` — that lives on JwtPayload).
|
||||
// The previous `authData.role` read was always undefined, so admins were
|
||||
// wrongly scoped to their own plan rows on the /entries and /overrides
|
||||
// endpoints. Typed (not `any`) so this can't silently regress.
|
||||
function isAdminLike(authData: AuthData | undefined): boolean {
|
||||
return authData?.roleName === "admin";
|
||||
}
|
||||
|
||||
function forceFromQuery(query: unknown): boolean {
|
||||
|
||||
@@ -58,7 +58,7 @@ export default async function projectFilesRoutes(
|
||||
const { project_id: projectIdStr, path: subPath = "" } = parsedQuery.data;
|
||||
const projectId = Number(projectIdStr);
|
||||
const project = await getProjectForFiles(projectId);
|
||||
if (!project) return error(reply, "Projekt nebyl nalezen", 404);
|
||||
if (!project) return error(reply, "Projekt nenalezen", 404);
|
||||
|
||||
if (!fm.isConfigured()) {
|
||||
return error(reply, "Souborový systém není nakonfigurován", 500);
|
||||
@@ -70,7 +70,7 @@ export default async function projectFilesRoutes(
|
||||
return error(reply, "Projekt nemá číslo projektu");
|
||||
|
||||
const result = fm.downloadFile(project.project_number, subPath);
|
||||
if (!result) return error(reply, "Soubor nebyl nalezen", 404);
|
||||
if (!result) return error(reply, "Soubor nenalezen", 404);
|
||||
|
||||
const stream = fs.createReadStream(result.filePath);
|
||||
const encodedName = encodeURIComponent(result.fileName);
|
||||
@@ -89,7 +89,7 @@ export default async function projectFilesRoutes(
|
||||
|
||||
const result = fm.listFiles(project.project_number, subPath);
|
||||
if (result === null) {
|
||||
return error(reply, "Složka nebyla nalezena", 404);
|
||||
return error(reply, "Složka nenalezena", 404);
|
||||
}
|
||||
|
||||
return success(reply, {
|
||||
@@ -109,7 +109,7 @@ export default async function projectFilesRoutes(
|
||||
if ("error" in parsedQuery) return error(reply, parsedQuery.error, 400);
|
||||
const projectId = Number(parsedQuery.data.project_id);
|
||||
const project = await getProjectForFiles(projectId);
|
||||
if (!project) return error(reply, "Projekt nebyl nalezen", 404);
|
||||
if (!project) return error(reply, "Projekt nenalezen", 404);
|
||||
if (!project.project_number)
|
||||
return error(reply, "Projekt nemá číslo projektu");
|
||||
|
||||
@@ -162,7 +162,7 @@ export default async function projectFilesRoutes(
|
||||
if ("error" in parsedQuery) return error(reply, parsedQuery.error, 400);
|
||||
const projectId = Number(parsedQuery.data.project_id);
|
||||
const project = await getProjectForFiles(projectId);
|
||||
if (!project) return error(reply, "Projekt nebyl nalezen", 404);
|
||||
if (!project) return error(reply, "Projekt nenalezen", 404);
|
||||
if (!project.project_number)
|
||||
return error(reply, "Projekt nemá číslo projektu");
|
||||
|
||||
@@ -225,7 +225,7 @@ export default async function projectFilesRoutes(
|
||||
if ("error" in parsedQuery) return error(reply, parsedQuery.error, 400);
|
||||
const projectId = Number(parsedQuery.data.project_id);
|
||||
const project = await getProjectForFiles(projectId);
|
||||
if (!project) return error(reply, "Projekt nebyl nalezen", 404);
|
||||
if (!project) return error(reply, "Projekt nenalezen", 404);
|
||||
if (!project.project_number)
|
||||
return error(reply, "Projekt nemá číslo projektu");
|
||||
|
||||
@@ -267,7 +267,7 @@ export default async function projectFilesRoutes(
|
||||
if ("error" in parsedQuery) return error(reply, parsedQuery.error, 400);
|
||||
const projectId = Number(parsedQuery.data.project_id);
|
||||
const project = await getProjectForFiles(projectId);
|
||||
if (!project) return error(reply, "Projekt nebyl nalezen", 404);
|
||||
if (!project) return error(reply, "Projekt nenalezen", 404);
|
||||
if (!project.project_number)
|
||||
return error(reply, "Projekt nemá číslo projektu");
|
||||
|
||||
|
||||
@@ -6,11 +6,14 @@ import { parsePagination, buildPaginationMeta } from "../../utils/pagination";
|
||||
import { parseBody } from "../../schemas/common";
|
||||
import {
|
||||
UpdateProjectSchema,
|
||||
CreateProjectSchema,
|
||||
CreateProjectNoteSchema,
|
||||
} from "../../schemas/projects.schema";
|
||||
import {
|
||||
listProjects,
|
||||
getProject,
|
||||
createProject,
|
||||
getNextProjectNumber,
|
||||
updateProject,
|
||||
deleteProject,
|
||||
createProjectNote,
|
||||
@@ -46,6 +49,40 @@ export default async function projectsRoutes(
|
||||
},
|
||||
);
|
||||
|
||||
// GET /api/admin/projects/next-number — preview the next shared number
|
||||
fastify.get(
|
||||
"/next-number",
|
||||
{ preHandler: requirePermission("projects.create") },
|
||||
async (_request, reply) => {
|
||||
const number = await getNextProjectNumber();
|
||||
return success(reply, { number, next_number: number });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /api/admin/projects — create a standalone (manual) project
|
||||
fastify.post(
|
||||
"/",
|
||||
{ preHandler: requirePermission("projects.create") },
|
||||
async (request, reply) => {
|
||||
const parsed = parseBody(CreateProjectSchema, request.body);
|
||||
if ("error" in parsed) return error(reply, parsed.error, 400);
|
||||
|
||||
const result = await createProject(parsed.data);
|
||||
if ("error" in result)
|
||||
return error(reply, result.error, (result as any).status ?? 400);
|
||||
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "project",
|
||||
entityId: result.id,
|
||||
description: `Vytvořen projekt ${result.project_number}`,
|
||||
});
|
||||
return success(reply, { id: result.id }, 201, "Projekt byl vytvořen");
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get<{ Params: { id: string } }>(
|
||||
"/:id",
|
||||
{ preHandler: requirePermission("projects.view") },
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { FastifyInstance } from "fastify";
|
||||
import prisma from "../../config/database";
|
||||
import { requireAuth } from "../../middleware/auth";
|
||||
import { success, error } from "../../utils/response";
|
||||
import { success, error, parseId } from "../../utils/response";
|
||||
import { hashToken } from "../../services/auth";
|
||||
import { logAudit } from "../../services/audit";
|
||||
|
||||
/** Parse user-agent string into browser, OS, and device icon */
|
||||
function parseUserAgent(ua: string | null): {
|
||||
@@ -81,8 +82,8 @@ export default async function sessionsRoutes(
|
||||
"/:id",
|
||||
{ preHandler: requireAuth },
|
||||
async (request, reply) => {
|
||||
const id = parseInt(request.params.id, 10);
|
||||
if (Number.isNaN(id)) return error(reply, "Neplatné ID relace", 400);
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
if (id === null) return;
|
||||
const authData = request.authData!;
|
||||
|
||||
const session = await prisma.refresh_tokens.findFirst({
|
||||
@@ -94,6 +95,14 @@ export default async function sessionsRoutes(
|
||||
where: { id },
|
||||
data: { replaced_at: new Date() },
|
||||
});
|
||||
await logAudit({
|
||||
request,
|
||||
authData,
|
||||
action: "delete",
|
||||
entityType: "session",
|
||||
entityId: id,
|
||||
description: `Ukončena relace #${id} (${session.ip_address ?? "?"})`,
|
||||
});
|
||||
return success(reply, null, 200, "Relace ukončena");
|
||||
},
|
||||
);
|
||||
@@ -112,7 +121,7 @@ export default async function sessionsRoutes(
|
||||
return error(reply, "Nelze identifikovat aktuální relaci", 400);
|
||||
}
|
||||
|
||||
await prisma.refresh_tokens.updateMany({
|
||||
const terminated = await prisma.refresh_tokens.updateMany({
|
||||
where: {
|
||||
user_id: authData.userId,
|
||||
replaced_at: null,
|
||||
@@ -120,6 +129,13 @@ export default async function sessionsRoutes(
|
||||
},
|
||||
data: { replaced_at: new Date() },
|
||||
});
|
||||
await logAudit({
|
||||
request,
|
||||
authData,
|
||||
action: "delete",
|
||||
entityType: "session",
|
||||
description: `Ukončeny všechny ostatní relace (${terminated.count})`,
|
||||
});
|
||||
return success(reply, null, 200, "Všechny ostatní relace ukončeny");
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { FastifyInstance } from "fastify";
|
||||
import prisma from "../../config/database";
|
||||
import { requireAuth, requirePermission } from "../../middleware/auth";
|
||||
import { logAudit } from "../../services/audit";
|
||||
import { success, error } from "../../utils/response";
|
||||
import { success, error, parseId } from "../../utils/response";
|
||||
import { parsePagination, buildPaginationMeta } from "../../utils/pagination";
|
||||
import { parseBody } from "../../schemas/common";
|
||||
import { CreateTripSchema, UpdateTripSchema } from "../../schemas/trips.schema";
|
||||
@@ -189,8 +189,8 @@ export default async function tripsRoutes(
|
||||
"/last-km/:vehicleId",
|
||||
{ preHandler: requirePermission("trips.manage") },
|
||||
async (request, reply) => {
|
||||
const vehicleId = parseInt(request.params.vehicleId, 10);
|
||||
if (isNaN(vehicleId)) return error(reply, "Neplatné ID vozidla", 400);
|
||||
const vehicleId = parseId((request.params as any).vehicleId, reply);
|
||||
if (vehicleId === null) return;
|
||||
|
||||
const [lastTrip, vehicle] = await Promise.all([
|
||||
prisma.trips.findFirst({
|
||||
@@ -261,8 +261,8 @@ export default async function tripsRoutes(
|
||||
"/:id",
|
||||
{ preHandler: requireAuth },
|
||||
async (request, reply) => {
|
||||
const id = parseInt(request.params.id, 10);
|
||||
if (isNaN(id)) return error(reply, "Neplatné ID", 400);
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
if (id === null) return;
|
||||
const parsed = parseBody(UpdateTripSchema, request.body);
|
||||
if ("error" in parsed) return error(reply, parsed.error, 400);
|
||||
const body = parsed.data;
|
||||
@@ -335,8 +335,8 @@ export default async function tripsRoutes(
|
||||
"/:id",
|
||||
{ preHandler: requireAuth },
|
||||
async (request, reply) => {
|
||||
const id = parseInt(request.params.id, 10);
|
||||
if (isNaN(id)) return error(reply, "Neplatné ID", 400);
|
||||
const id = parseId((request.params as any).id, reply);
|
||||
if (id === null) return;
|
||||
const authData = request.authData!;
|
||||
const existing = await prisma.trips.findUnique({ where: { id } });
|
||||
if (!existing) return error(reply, "Jízda nenalezena", 404);
|
||||
|
||||
@@ -6,14 +6,14 @@ const QuotationItemSchema = z.object({
|
||||
quantity: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional()
|
||||
.default(1),
|
||||
unit: z.string().nullish(),
|
||||
unit_price: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional()
|
||||
.default(0),
|
||||
is_included_in_total: z
|
||||
@@ -23,7 +23,7 @@ const QuotationItemSchema = z.object({
|
||||
position: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional(),
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ const ScopeSectionSchema = z.object({
|
||||
position: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional(),
|
||||
});
|
||||
|
||||
@@ -53,7 +53,7 @@ export const CreateQuotationSchema = z.object({
|
||||
vat_rate: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional()
|
||||
.default(21.0),
|
||||
apply_vat: z
|
||||
@@ -75,7 +75,7 @@ export const UpdateQuotationSchema = z.object({
|
||||
customer_id: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional(),
|
||||
created_at: z.union([z.string(), z.null()]).optional(),
|
||||
valid_until: z.union([z.string(), z.null()]).optional(),
|
||||
@@ -84,7 +84,7 @@ export const UpdateQuotationSchema = z.object({
|
||||
vat_rate: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional(),
|
||||
apply_vat: z
|
||||
.preprocess((v) => v === true || v === 1 || v === "1", z.boolean())
|
||||
|
||||
@@ -6,14 +6,14 @@ const OrderItemSchema = z.object({
|
||||
quantity: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional()
|
||||
.default(1),
|
||||
unit: z.string().nullish(),
|
||||
unit_price: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional()
|
||||
.default(0),
|
||||
is_included_in_total: z
|
||||
@@ -23,7 +23,7 @@ const OrderItemSchema = z.object({
|
||||
position: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional(),
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ const OrderSectionSchema = z.object({
|
||||
position: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional(),
|
||||
});
|
||||
|
||||
@@ -42,7 +42,7 @@ export const CreateOrderFromQuotationSchema = z.object({
|
||||
quotationId: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" }),
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" }),
|
||||
customerOrderNumber: z.string().optional().default(""),
|
||||
});
|
||||
|
||||
@@ -68,7 +68,7 @@ export const CreateOrderSchema = z.object({
|
||||
vat_rate: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional()
|
||||
.default(21.0),
|
||||
apply_vat: z
|
||||
@@ -78,7 +78,7 @@ export const CreateOrderSchema = z.object({
|
||||
exchange_rate: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional()
|
||||
.default(1.0),
|
||||
scope_title: z.string().nullish(),
|
||||
@@ -86,6 +86,10 @@ export const CreateOrderSchema = z.object({
|
||||
notes: z.string().nullish(),
|
||||
items: z.array(OrderItemSchema).optional(),
|
||||
sections: z.array(OrderSectionSchema).optional(),
|
||||
create_project: z
|
||||
.preprocess((v) => v === true || v === 1 || v === "1", z.boolean())
|
||||
.optional()
|
||||
.default(true),
|
||||
});
|
||||
|
||||
export const UpdateOrderSchema = z.object({
|
||||
@@ -103,7 +107,7 @@ export const UpdateOrderSchema = z.object({
|
||||
vat_rate: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((v) => !Number.isNaN(v), { message: "Must be a valid number" })
|
||||
.refine((v) => !Number.isNaN(v), { message: "Musí být platné číslo" })
|
||||
.optional(),
|
||||
apply_vat: z
|
||||
.preprocess((v) => v === true || v === 1 || v === "1", z.boolean())
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const CreateProjectSchema = z.object({
|
||||
name: z.string().min(1, "Zadejte název projektu"),
|
||||
customer_id: z
|
||||
.union([z.number(), z.string(), z.null()])
|
||||
.transform((v) => (v === null || v === "" ? null : Number(v)))
|
||||
.refine((v) => v === null || !Number.isNaN(v), {
|
||||
message: "Neplatný zákazník",
|
||||
})
|
||||
.optional(),
|
||||
responsible_user_id: z
|
||||
.union([z.number(), z.string(), z.null()])
|
||||
.transform((v) => (v === null || v === "" ? null : Number(v)))
|
||||
.refine((v) => v === null || !Number.isNaN(v), {
|
||||
message: "Neplatná zodpovědná osoba",
|
||||
})
|
||||
.optional(),
|
||||
status: z.string().optional().default("aktivni"),
|
||||
start_date: z.union([z.string(), z.null()]).optional(),
|
||||
end_date: z.union([z.string(), z.null()]).optional(),
|
||||
notes: z.string().nullish(),
|
||||
});
|
||||
|
||||
export const UpdateProjectSchema = z.object({
|
||||
name: z.string().nullish(),
|
||||
status: z.string().optional(),
|
||||
@@ -28,5 +50,6 @@ export const CreateProjectNoteSchema = z.object({
|
||||
content: z.string().nullish(),
|
||||
});
|
||||
|
||||
export type CreateProjectInput = z.infer<typeof CreateProjectSchema>;
|
||||
export type UpdateProjectInput = z.infer<typeof UpdateProjectSchema>;
|
||||
export type CreateProjectNoteInput = z.infer<typeof CreateProjectNoteSchema>;
|
||||
|
||||
@@ -220,7 +220,9 @@ async function start() {
|
||||
}
|
||||
|
||||
// --- Start ---
|
||||
const port = config.isProduction ? config.port : 3000;
|
||||
// Dev listens on a fixed local port (prod uses config.port / the PORT env).
|
||||
// 3050 keeps it clear of other local apps that commonly grab 3000.
|
||||
const port = config.isProduction ? config.port : 3050;
|
||||
try {
|
||||
await app.listen({ port, host: config.host });
|
||||
app.log.info(`Server running on http://${config.host}:${port}`);
|
||||
|
||||
@@ -115,7 +115,12 @@ export class NasFileManager {
|
||||
return (
|
||||
fs.existsSync(this.basePath) && fs.statSync(this.basePath).isDirectory()
|
||||
);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] stat failed for basePath:",
|
||||
this.basePath,
|
||||
err,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -136,7 +141,8 @@ export class NasFileManager {
|
||||
try {
|
||||
fs.mkdirSync(fullPath, { recursive: true, mode: 0o775 });
|
||||
return true;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] mkdir failed for path:", fullPath, err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -150,7 +156,12 @@ export class NasFileManager {
|
||||
try {
|
||||
await fs.promises.rm(folderPath, { recursive: true, force: true });
|
||||
return true;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] delete failed for path:",
|
||||
folderPath,
|
||||
err,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -173,7 +184,14 @@ export class NasFileManager {
|
||||
try {
|
||||
fs.renameSync(currentPath, newPath);
|
||||
return true;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] rename failed:",
|
||||
currentPath,
|
||||
"→",
|
||||
newPath,
|
||||
err,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -188,14 +206,20 @@ export class NasFileManager {
|
||||
try {
|
||||
const stat = fs.lstatSync(dirPath);
|
||||
if (!stat.isDirectory()) return null;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] lstat failed for path:", dirPath, err);
|
||||
return null;
|
||||
}
|
||||
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(dirPath);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] readdir failed for path:",
|
||||
dirPath,
|
||||
err,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -206,7 +230,12 @@ export class NasFileManager {
|
||||
let lstat: fs.Stats;
|
||||
try {
|
||||
lstat = fs.lstatSync(fullPath);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] lstat failed for entry:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -216,7 +245,12 @@ export class NasFileManager {
|
||||
if (isLink) {
|
||||
try {
|
||||
isDir = fs.statSync(fullPath).isDirectory();
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] stat failed for symlink target:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
isDir = false;
|
||||
}
|
||||
} else {
|
||||
@@ -237,8 +271,12 @@ export class NasFileManager {
|
||||
try {
|
||||
const target = fs.readlinkSync(fullPath);
|
||||
item.link_target = target;
|
||||
} catch {
|
||||
// ignore
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] readlink failed for:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +317,12 @@ export class NasFileManager {
|
||||
let realDirPath: string;
|
||||
try {
|
||||
realDirPath = fs.realpathSync(dirPath);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] realpath failed for path:",
|
||||
dirPath,
|
||||
err,
|
||||
);
|
||||
realDirPath = dirPath;
|
||||
}
|
||||
|
||||
@@ -304,14 +347,16 @@ export class NasFileManager {
|
||||
|
||||
try {
|
||||
await fs.promises.mkdir(dirPath, { recursive: true, mode: 0o775 });
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] mkdir failed for path:", dirPath, err);
|
||||
return "Cílová složka neexistuje";
|
||||
}
|
||||
|
||||
let stat: fs.Stats;
|
||||
try {
|
||||
stat = await fs.promises.stat(dirPath);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] stat failed for path:", dirPath, err);
|
||||
return "Cílová složka neexistuje";
|
||||
}
|
||||
if (!stat.isDirectory()) {
|
||||
@@ -376,7 +421,8 @@ export class NasFileManager {
|
||||
try {
|
||||
const stat = fs.lstatSync(fullPath);
|
||||
if (!stat.isFile()) return null;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] lstat failed for path:", fullPath, err);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -413,7 +459,8 @@ export class NasFileManager {
|
||||
try {
|
||||
const stat = await fs.promises.lstat(fullPath);
|
||||
isDir = stat.isDirectory();
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] lstat failed for path:", fullPath, err);
|
||||
return "Soubor nebo složka neexistuje";
|
||||
}
|
||||
|
||||
@@ -423,7 +470,12 @@ export class NasFileManager {
|
||||
} else {
|
||||
await fs.promises.unlink(fullPath);
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] delete failed for path:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
return isDir
|
||||
? "Nepodařilo se smazat složku"
|
||||
: "Nepodařilo se smazat soubor";
|
||||
@@ -455,7 +507,12 @@ export class NasFileManager {
|
||||
|
||||
try {
|
||||
await fs.promises.stat(fullFrom);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] stat failed for source path:",
|
||||
fullFrom,
|
||||
err,
|
||||
);
|
||||
return "Zdrojový soubor neexistuje";
|
||||
}
|
||||
|
||||
@@ -509,7 +566,8 @@ export class NasFileManager {
|
||||
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
||||
return "Nadřazená složka neexistuje";
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] lstat failed for path:", dirPath, err);
|
||||
return "Nadřazená složka neexistuje";
|
||||
}
|
||||
|
||||
@@ -528,7 +586,8 @@ export class NasFileManager {
|
||||
|
||||
try {
|
||||
await fs.promises.mkdir(newPath, { mode: 0o775 });
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[nas-file-manager] mkdir failed for path:", newPath, err);
|
||||
return "Nepodařilo se vytvořit složku";
|
||||
}
|
||||
|
||||
@@ -559,7 +618,12 @@ export class NasFileManager {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(this.basePath);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] readdir failed for basePath:",
|
||||
this.basePath,
|
||||
err,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -571,7 +635,12 @@ export class NasFileManager {
|
||||
if (fs.statSync(fullPath).isDirectory()) {
|
||||
return fullPath;
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] stat failed for entry:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -676,7 +745,12 @@ export class NasFileManager {
|
||||
try {
|
||||
const entries = fs.readdirSync(dirPath);
|
||||
return entries.length;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-file-manager] readdir failed for path:",
|
||||
dirPath,
|
||||
err,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,12 @@ class NasFinancialsManager {
|
||||
try {
|
||||
fs.mkdirSync(this.basePath, { recursive: true });
|
||||
return fs.statSync(this.basePath).isDirectory();
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] mkdir/stat failed for basePath:",
|
||||
this.basePath,
|
||||
err,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -44,7 +49,12 @@ class NasFinancialsManager {
|
||||
const monthPath = path.join(yearPath, monthDir);
|
||||
try {
|
||||
if (!fs.statSync(monthPath).isDirectory()) continue;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] stat failed for monthPath:",
|
||||
monthPath,
|
||||
err,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const filePath = path.join(monthPath, safeName);
|
||||
@@ -53,8 +63,12 @@ class NasFinancialsManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// best effort
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] cleanIssuedInvoice failed for:",
|
||||
invoiceNumber,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +87,12 @@ class NasFinancialsManager {
|
||||
try {
|
||||
fs.writeFileSync(fullPath, pdfBuffer);
|
||||
return `${DIR_ISSUED}/${year}/${this.pad(month)}/${path.basename(fullPath)}`;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] write failed for issued invoice:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -86,7 +105,12 @@ class NasFinancialsManager {
|
||||
try {
|
||||
const data = fs.readFileSync(fullPath);
|
||||
return { data, fileName: path.basename(fullPath) };
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] read failed for issued invoice:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -97,7 +121,12 @@ class NasFinancialsManager {
|
||||
try {
|
||||
fs.unlinkSync(fullPath);
|
||||
return true;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] delete failed for issued invoice:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -148,7 +177,12 @@ class NasFinancialsManager {
|
||||
try {
|
||||
const data = fs.readFileSync(fullPath);
|
||||
return { data, fileName: path.basename(fullPath) };
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] read failed for received invoice:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -160,7 +194,12 @@ class NasFinancialsManager {
|
||||
try {
|
||||
fs.unlinkSync(fullPath);
|
||||
return true;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] delete failed for received invoice:",
|
||||
fullPath,
|
||||
err,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -181,7 +220,12 @@ class NasFinancialsManager {
|
||||
try {
|
||||
fs.mkdirSync(dirPath, { recursive: true });
|
||||
return dirPath;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"[nas-financials-manager] mkdir failed for path:",
|
||||
dirPath,
|
||||
err,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -288,9 +288,14 @@ interface CreateOrderData {
|
||||
notes?: string | null;
|
||||
items?: OrderItemInput[];
|
||||
sections?: OrderSectionInput[];
|
||||
create_project?: boolean;
|
||||
}
|
||||
|
||||
export async function createOrder(body: CreateOrderData) {
|
||||
export async function createOrder(
|
||||
body: CreateOrderData,
|
||||
attachmentBuffer?: Buffer | null,
|
||||
attachmentName?: string | null,
|
||||
) {
|
||||
try {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
const orderNumber =
|
||||
@@ -322,6 +327,10 @@ export async function createOrder(body: CreateOrderData) {
|
||||
scope_title: body.scope_title ?? null,
|
||||
scope_description: body.scope_description ?? null,
|
||||
notes: body.notes ?? null,
|
||||
attachment_data: attachmentBuffer
|
||||
? new Uint8Array(attachmentBuffer)
|
||||
: null,
|
||||
attachment_name: attachmentName || null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -352,7 +361,27 @@ export async function createOrder(body: CreateOrderData) {
|
||||
});
|
||||
}
|
||||
|
||||
return { id: order.id, order_number: order.order_number };
|
||||
let projectId: number | undefined;
|
||||
// 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) {
|
||||
const project = await tx.projects.create({
|
||||
data: {
|
||||
project_number: orderNumber,
|
||||
name: body.scope_title || body.customer_order_number || orderNumber,
|
||||
customer_id: order.customer_id,
|
||||
order_id: order.id,
|
||||
status: "aktivni",
|
||||
},
|
||||
});
|
||||
projectId = project.id;
|
||||
}
|
||||
|
||||
return {
|
||||
id: order.id,
|
||||
order_number: order.order_number,
|
||||
project_id: projectId,
|
||||
};
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Error && "status" in err) {
|
||||
|
||||
@@ -448,7 +448,7 @@ export async function createEntry(
|
||||
date_from: toDateOnly(input.date_from),
|
||||
date_to: toDateOnly(input.date_to),
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category as any,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
created_by: actorUserId,
|
||||
},
|
||||
@@ -515,7 +515,7 @@ export async function updateEntry(
|
||||
date_from: input.date_from ? toDateOnly(input.date_from) : undefined,
|
||||
date_to: input.date_to ? toDateOnly(input.date_to) : undefined,
|
||||
project_id: input.project_id === undefined ? undefined : input.project_id,
|
||||
category: input.category as any,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
},
|
||||
});
|
||||
@@ -636,7 +636,7 @@ export async function createOverride(
|
||||
user_id: input.user_id,
|
||||
shift_date: date,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category as any,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
created_by: actorUserId,
|
||||
},
|
||||
@@ -707,7 +707,7 @@ export async function updateOverride(
|
||||
where: { id },
|
||||
data: {
|
||||
project_id: input.project_id === undefined ? undefined : input.project_id,
|
||||
category: input.category as any,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import prisma from "../config/database";
|
||||
import { releaseSharedNumber } from "./numbering.service";
|
||||
import {
|
||||
generateSharedNumber,
|
||||
previewSharedNumber,
|
||||
releaseSharedNumber,
|
||||
} from "./numbering.service";
|
||||
import { NasFileManager } from "./nas-file-manager";
|
||||
import type { CreateProjectInput } from "../schemas/projects.schema";
|
||||
|
||||
const nasFileManager = new NasFileManager();
|
||||
|
||||
@@ -144,6 +149,60 @@ export async function updateProject(id: number, body: Record<string, any>) {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a standalone (manual) project. Takes the next SHARED number — the
|
||||
* same pool orders/projects draw from — generated atomically inside the
|
||||
* transaction (SELECT … FOR UPDATE via getNextSequence). order_id stays null,
|
||||
* which is what marks it "samostatný" in the UI. NAS folder creation is
|
||||
* best-effort (the manager self-guards isConfigured() and swallows fs errors).
|
||||
*/
|
||||
export async function createProject(data: CreateProjectInput) {
|
||||
if (data.customer_id != null) {
|
||||
const customer = await prisma.customers.findUnique({
|
||||
where: { id: data.customer_id },
|
||||
});
|
||||
if (!customer) return { error: "Zákazník nenalezen", status: 400 };
|
||||
}
|
||||
if (data.responsible_user_id != null) {
|
||||
const user = await prisma.users.findUnique({
|
||||
where: { id: data.responsible_user_id },
|
||||
});
|
||||
if (!user) return { error: "Zodpovědná osoba nenalezena", status: 400 };
|
||||
}
|
||||
|
||||
const project = await prisma.$transaction(async (tx) => {
|
||||
const project_number = await generateSharedNumber(tx);
|
||||
return tx.projects.create({
|
||||
data: {
|
||||
project_number,
|
||||
name: data.name,
|
||||
customer_id: data.customer_id ?? null,
|
||||
responsible_user_id: data.responsible_user_id ?? null,
|
||||
status: data.status || "aktivni",
|
||||
start_date: data.start_date ? new Date(data.start_date) : null,
|
||||
end_date: data.end_date ? new Date(data.end_date) : null,
|
||||
notes: data.notes ?? null,
|
||||
order_id: null,
|
||||
quotation_id: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
if (project.project_number && nasFileManager.isConfigured()) {
|
||||
nasFileManager.createProjectFolder(
|
||||
project.project_number,
|
||||
project.name || "",
|
||||
);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
/** Preview the next shared number for the create form (does NOT consume it). */
|
||||
export async function getNextProjectNumber(): Promise<string> {
|
||||
return previewSharedNumber();
|
||||
}
|
||||
|
||||
export async function deleteProject(id: number, deleteFiles: boolean = false) {
|
||||
const existing = await prisma.projects.findUnique({ where: { id } });
|
||||
if (!existing) return { error: "not_found" as const };
|
||||
|
||||
@@ -146,4 +146,5 @@ export type EntityType =
|
||||
| "warehouse_receipt_attachment"
|
||||
| "work_plan_entry"
|
||||
| "work_plan_override"
|
||||
| "plan_category";
|
||||
| "plan_category"
|
||||
| "session";
|
||||
|
||||
@@ -10,5 +10,11 @@ export default defineConfig({
|
||||
testTimeout: 15000,
|
||||
hookTimeout: 15000,
|
||||
exclude: ["dist/**", "node_modules/**", ".claude/**"],
|
||||
// Tests run against a real shared MySQL test DB. Running test files in
|
||||
// parallel lets two files (e.g. numbering + manual-create) hit the same
|
||||
// `number_sequences` row with SELECT ... FOR UPDATE + deleteMany at once,
|
||||
// which deadlocks (MySQL 1213). Serialise files so DB-touching suites
|
||||
// don't contend. Tests within a file already run sequentially.
|
||||
fileParallelism: false,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user