Compare commits

..

63 Commits

Author SHA1 Message Date
BOHA
b6cd5046d5 chore(release): v2.1.5 — Odin multi-conversation chat (sidebar, invoice import)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:28:43 +02:00
BOHA
25c8c39ba6 feat(odin): scope to invoice processing only (guard general chat)
Odin currently advertises general Q&A via the /chat path, which burns API
credits on open-ended questions. Guard it: a text-only message makes NO AI
call — it gets a canned reply telling the user to attach an invoice. The
invoice path (attachments → extract) is unchanged. Removing the guard
re-enables the general /chat path for a later phase.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:26:54 +02:00
BOHA
4b2770a000 fix(odin): show conversation auto-title immediately (no refresh needed)
ensureActive() created the conversation and invalidated the list before the
server-side auto-title was applied (that happens on the message append), so
the sidebar showed "Nová konverzace" until a refresh. Move the
["ai","conversations"] invalidation to persist()'s success path — after the
append (and thus the auto-title) lands.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:22:31 +02:00
BOHA
434a12b4a8 feat(odin): mobile composer + responsive sidebar + message-entrance animation
- Composer rebuilt claude-style: a rounded pill with a multiline auto-growing
  textarea and attach/send ICON buttons (vertically centered), so there's room
  to type on mobile (was squeezed between two text buttons).
- Conversation list collapses into a slide-in Drawer below md, with a menu
  button in the chat header; chat is full-width on mobile.
- Each new message bubble animates in (fade + slide-up; fade-only under
  prefers-reduced-motion) via framer-motion, so sent messages and Odin's
  replies appear smoothly.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:19:54 +02:00
BOHA
28fb399217 feat(odin): refine hero — Newsreader serif, red name, staggered entrance
- Swap Fraunces → Newsreader (literary serif, full Czech, optical sizing).
- Split the greeting so the user's first name renders in brand-red italic.
- Add a subtle staggered fade-in (framer-motion), skipped under
  prefers-reduced-motion.
- New description that names Odin and covers chat + invoice import.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:03:16 +02:00
BOHA
c0ff7b4549 feat(odin): editorial serif hero — Fraunces greeting + italic subtitle
Drop the gradient "Odin" wordmark from the new-conversation hero and make the
personalized greeting the centerpiece in Fraunces (optical-sized serif), with
an italic Fraunces description — a refined, literary, claude-like treatment.
Loads Fraunces (upright + italic) via the existing Google Fonts link.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:57:15 +02:00
BOHA
1e21c12f33 feat(odin): personalized greeting hero on the new-conversation screen
Time-based Czech greeting + the user's first name (e.g. "Dobrý večer, Admin")
above the big gradient "Odin" wordmark, with a stylish description line. Drop
the redundant mark from the hero (it lives on the nav item + thinking state).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:51:00 +02:00
BOHA
ab12f9d791 feat(odin): sidebar brand is a big gradient "Odin" wordmark (drop the icon)
The mark already lives on the nav menu item; the conversation sidebar's brand
no longer duplicates it — just a larger gradient "Odin" wordmark above the new
chat button.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:47:39 +02:00
BOHA
cf442b9a99 feat(odin): big claude.ai-style hero on the new-conversation screen
Replace the small empty-state with a large centred hero — the animated Odin
mark + a big gradient "Odin" wordmark (responsive clamp font) and the helper
line beneath.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:44:38 +02:00
BOHA
2e7caea5a6 feat(odin): use the Odin mark as the sidebar nav icon
Replace the chat-bubble glyph on the "Odin" nav item with the OdinMark, and
make the mark's SVG sizing !important so the nav's `& svg { width:18 }` rule
can't shrink it (its `size` prop stays authoritative everywhere).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:41:20 +02:00
BOHA
702a4984ee feat(odin): animated Odin brand mark (AI core orbiting business data)
A self-contained animated SVG mark in BOHA red: a 4-point AI spark (Odin) that
slow-rotates and breathes, a data node orbiting a faint ring (the assistant at
the centre of the business system). An "idle" and a "thinking" state (faster
orbit + red glow); honours prefers-reduced-motion. Used as the sidebar brand,
the empty-state hero, and the busy/thinking indicator.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:31:48 +02:00
BOHA
769767c33d feat(odin): left sidebar + lazy conversation creation (claude.ai-style)
- Replace top tabs with a left sidebar (New chat + scrollable conversation
  list, per-row rename/delete menu, active highlight), chat on the right.
- Fix duplicate-empty-conversations bug: "Nová konverzace" now just opens an
  empty composer; a DB row is created only on the first successful message
  (and a failed AI call no longer leaves an orphan conversation). Repeated
  clicks never spawn empties, and nothing empty survives a refresh.
- Land on a fresh new chat on mount; deleting the open conversation returns
  to new chat.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 20:07:07 +02:00
BOHA
f18e2e0f2c docs(odin): forward-looking notes for a Phase 2 general assistant
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 19:52:30 +02:00
BOHA
d62abe81fd feat(odin): use the full page (full width + taller shell)
Drop the 1100px max-width cap and size the chat shell to fill the content
area (100dvh - 100px = top bar + main bottom padding), so Odin uses the whole
page now that it owns the route.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 19:51:23 +02:00
BOHA
ac7c220bb1 fix(odin): gate Uložit on invoices.create + correct invoice invalidation key
Final review caught two minor issues:
- saveInvoice invalidated ["received-invoices"], which matches no query (the
  received list/stats are keyed ["invoices","received",…]); use ["invoices"]
  so the list/stats actually refresh after an import.
- The Save button hit /received-invoices (requires invoices.create) while Odin
  is gated only on ai.use; disable Uložit (with a hint) when the user lacks
  invoices.create so the UI never offers a 403 action. Dormant today (ai.use is
  admin-only and admin bypasses checks) but correct going forward.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 19:46:49 +02:00
BOHA
b7ebf04001 feat(odin): OdinChat orchestrator; render on /odin; remove DashAssistant
Wire OdinTabs/OdinThread/InvoiceReviewCard/OdinComposer into a single
OdinChat orchestrator; mount it on /odin (maxWidth 1100); delete the
old DashAssistant and its aiHistoryOptions query helper.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 19:39:15 +02:00
BOHA
441f46a471 feat(odin): tabs, thread, review-card, composer components
Add four presentational components + shared types under
src/admin/components/odin/ as props-driven building blocks for the
multi-conversation Odin page (Task 6 wires state/queries).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 19:34:22 +02:00
BOHA
f011a67ff3 feat(odin): conversation query options 2026-06-08 19:28:04 +02:00
BOHA
92594f89c3 test(odin): conversation CRUD, isolation, auto-title, cascade
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 19:27:31 +02:00
BOHA
6664e3bc4d feat(odin): conversation-scoped service + routes (replace /history)
Remove single-thread getChatHistory/appendChatMessages/clearChatHistory and the
three /history routes; add listConversations, createConversation, getConversation-
Messages, appendConversationMessages, renameConversation, deleteConversation with
ownership checks and auto-title; wire six /conversations[/:id] routes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 19:21:13 +02:00
BOHA
c5cfd855ba feat(odin): ai_conversations table + conversation_id on messages 2026-06-08 19:14:01 +02:00
BOHA
2565e0de21 docs(odin): implementation plan for multi-conversation chat
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 19:11:54 +02:00
BOHA
817f0b2f00 docs(odin): design spec for multi-conversation chat
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 19:01:50 +02:00
BOHA
e4ec08a5ef feat(ai): move the assistant to its own "Odin" sidebar page
Promote the AI chat from a dashboard widget to a dedicated page:
- new sidebar item "Odin" under the Přehled section, gated on ai.use, → /odin
- new /odin route + Odin page (reuses the assistant component, with a light
  ai.use guard)
- remove the widget from the dashboard
- rebrand the assistant header "Asistent" → "Odin" and give the thread more
  height now that it owns the page

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 18:38:35 +02:00
BOHA
049ee492c0 chore(release): v2.1.0 — AI assistant (chat, PDF invoice import, budget)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:33:19 +02:00
BOHA
f4bc038f8b fix(received-invoices): treat amount as gross (VAT-inclusive), back-calc VAT
The amount on a received invoice is the GROSS total the user pays (VAT
included), and VAT is the portion contained within it — not a net base with
VAT added on top. Switch the formula from amount*rate/100 to the
VAT-inclusive amount*rate/(100+rate) via a shared, tested vatFromGross()
helper used by both the create (manual upload + AI import share this
endpoint) and edit paths. Rate 0 → no VAT.

- AI extraction now asks Claude for the total INCLUDING VAT (was "základ bez
  DPH"), reinforced in the structured-output schema description.
- Label the amount field "Částka s DPH" in the AI review card and the manual
  upload/edit forms so the gross convention is explicit.
- Add unit tests with the user-confirmed figures (22 542,91 @ 21% → 3 912,41,
  base 18 630,50) plus other rates and the no-VAT case.

Existing rows keep their stored (gross) amounts; their vat_amount recomputes
on next edit. A one-shot backfill can correct historical vat_amount if wanted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:27:56 +02:00
BOHA
58e5fd2b1d feat(ai): server-side chat history + assistant UX fixes
Server-side, per-user chat history (the thread now survives reload):
- new ai_chat_messages table + migration; getChatHistory/appendChatMessages/
  clearChatHistory; GET/POST/DELETE /api/admin/ai/history (ai.use-guarded);
  service + HTTP tests (isolation, ordering, clear, perm, validation).
- DashAssistant loads the thread on mount and persists each turn; "Vymazat"
  clears it. gcTime:0 so each mount re-reads the DB (no stale-cache resurrection);
  composer gated until history settles + seed flag flipped on submit (no
  seed/submit race clobbering a freshly-sent turn).

UX + correctness fixes from review/feedback:
- review cards moved OUT of the scrollable thread into a "Faktury k potvrzení"
  section so Uložit is always reachable; chat auto-scroll no longer fires on
  field edits.
- chat bubble text colour set on the Typography (GlobalStyles pins `p` to
  text.secondary, which was overriding the inherited bubble colour → unreadable).
- never clear input/staged PDFs on a failed submit (rollback + keep), so a
  budget error can't wipe staged invoices; roll back the optimistic user turn.
- stable attachment ids (no crypto.randomUUID — undefined over plain HTTP).
- editable Datum splatnosti + Popis fields; client-side extraction summary.

Security: DashProfile clipboard copy now uses an execCommand fallback (works
over plain HTTP) and only shows the success toast when the copy actually
succeeded — previously it falsely claimed to copy 2FA codes / the TOTP secret.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:02:26 +02:00
BOHA
0226cdd52b fix(ai): cap extract-invoices batch at 20 files
Final review flagged that the multipart limits set only fileSize, so a
single /extract-invoices request could carry unbounded PDF parts. The
per-batch budget re-check already bounds total spend, but this bounds the
work (one vision call per file) of any single request.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:05:16 +02:00
BOHA
b665ea1d9b feat(ai): dashboard chat widget with invoice import + budget indicator 2026-06-08 15:01:52 +02:00
BOHA
ec74ded953 feat(ai): chat / extract-invoices / usage / budget routes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 14:50:23 +02:00
BOHA
bcf63d00d1 feat(ai): spend tracker + AI service (chat, extractInvoice)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 14:41:03 +02:00
BOHA
096784768f feat(ai): add @anthropic-ai/sdk, ai_usage table, ai.use permission
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 14:23:06 +02:00
BOHA
3623b441ce docs(ai): implementation plan for AI assistant Phase 1 (v2.1.0)
Five tasks: (1) foundation — SDK dep, env, ai_usage table + ai.use
permission migration; (2) spend tracker + ai.service (chat,
extractInvoice) with cost/budget tests; (3) /ai routes (usage, budget,
chat, extract) with guard tests; (4) DashAssistant dashboard widget;
(5) v2.1.0 release. Anthropic call stubbed in tests; migration apply is
controller-coordinated (dev server stopped).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 14:19:06 +02:00
BOHA
4bf7bf4ed6 docs(ai): spec for AI assistant Phase 1 (chat + invoice import + budget)
Admin-only Claude (Sonnet 4.6) chat embedded on the dashboard under the
welcome text. Attach received-invoice PDFs → extract (vision + structured
output) → confirm/edit → save via the existing received-invoices endpoint.
$50/month admin-editable budget enforced via an ai_usage table + pre-call
guard. New @anthropic-ai/sdk dep, ANTHROPIC_API_KEY, ai.use permission;
one migration. No system-data tools (Phase 2). Ships as v2.1.0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 14:09:47 +02:00
BOHA
92252382ac chore(release): v2.0.8 — show all employees in dashboard attendance
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:07:59 +02:00
BOHA
8bed920de1 feat(dashboard): show every active employee in "Docházka dnes"
The attendance card listed only employees with a record today (present /
break / clocked-out / on-leave). Now every active employee appears;
those with no record today show as "absent" (Nepřítomen), so the card
reflects the whole team. Loads active users (was a bare count) and
appends the unrecorded ones.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:00:09 +02:00
BOHA
9d2992b722 chore(release): v2.0.7 — always show notes in multi-record plan cells
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:54:47 +02:00
BOHA
1ddc0feccd fix(plan): always show notes for every record in a multi-record cell
Previously notes were hidden when a cell held 2-3 records (a density
choice). Show each record's note regardless of count — drop the
now-unused showNote prop on PlanRangeChips.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:53:45 +02:00
BOHA
cce2c9cfaa chore(release): v2.0.6 — bulk plan creation
Assign one project/category to many employees over a date range in one
action. "Hromadné přiřazení" on /plan-work: employee checklist +
include-weekends toggle, mirrors the single-create form. Creates range
entries grouped by contiguous eligible days per employee (weekends-off →
per-work-week chunks); per-day cap skips days already at 3; 92-day range
cap. Reuses createEntry; summary audit + result counts. No migration.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:48:09 +02:00
BOHA
2610301258 harden(plan): 92-day range cap + dedup user_ids on bulk create 2026-06-08 12:17:51 +02:00
BOHA
13d1fc2be3 feat(plan): bulk assignment modal on /plan-work
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 12:11:20 +02:00
BOHA
95ca258718 feat(plan): bulk entry creation endpoint + service 2026-06-08 12:03:47 +02:00
BOHA
6db87bf4ae docs(plan): implementation plan for bulk plan creation (v2.0.6)
Three tasks: (1) backend bulk endpoint + bulkCreateEntries service
(reuses createEntry; weekday filter + contiguous-run segmentation +
per-day cap skip) with TDD tests, (2) BulkPlanModal + PlanWork wiring
+ usePlanWork bulkCreate mutation, (3) v2.0.6 release. No migration.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:54:44 +02:00
BOHA
c6a146d57a docs(plan): spec for bulk plan creation (Feature B)
Assign one project/category to many employees over a date range in one
action. Modal mirrors single-create + employee checklist + "include
weekends" toggle. Stores range entries grouped by contiguous eligible
days per employee (weekends-off → per-work-week chunks); per-day cap
skips days already at 3. POST /plan/entries/bulk + bulkCreateEntries
(reuses createEntry); summary audit + result counts. No migration.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:49:55 +02:00
BOHA
1a262508d4 chore(release): v2.0.5 — multi-record plan cells
A plan cell now holds up to 3 records: additive assignments + day
exceptions, via the layered entries/overrides model (no migration).
resolveCell/resolveGrid return arrays; cap enforced per layer on create;
grid renders up to 3 stacked; cell editor is a day panel (list/add/edit,
layer-aware add); dashboard "today" card shows up to 3.

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

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

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

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

Bump version to 2.0.4.

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

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

Bump version to 2.0.3.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,891 @@
# Bulk Plan Creation Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Assign one project/category to many employees over a date range in a single action ("Hromadné přiřazení" on /plan-work).
**Architecture:** A new `POST /api/admin/plan/entries/bulk` endpoint drives a `bulkCreateEntries` service that, per employee, computes the eligible days in the range (weekday filter + Feature A's under-cap rule), groups contiguous eligible days into runs, and creates one range `work_plan_entries` row per run by **reusing `createEntry`**. The frontend adds a presentational `BulkPlanModal` (mirroring the single-create form + the existing bulk-attendance employee picker) wired from `PlanWork`, with a summary alert and `["plan"]` invalidation. No DB migration.
**Tech Stack:** Fastify 5 + Prisma (MySQL), Zod 4, React 18 + MUI v7, TanStack Query, Vitest (server-side, real test DB). Spec: `docs/superpowers/specs/2026-06-08-bulk-plan-creation-design.md`. Builds on Feature A (multi-record plan cells, v2.0.5).
**Gates:** `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`. The frontend has no component-test harness (server-side tests only), so Task 2 gates on `tsc -b` + `build`.
---
## File Structure
**Backend**
- `src/schemas/plan.schema.ts` — add `BulkPlanEntrySchema`.
- `src/services/plan.service.ts` — add `bulkCreateEntries(...)` (reuses `createEntry`, `assertNotPastDate`, `assertActiveCategory`, `toDateOnly`, `MAX_RECORDS_PER_CELL`).
- `src/routes/admin/plan.ts` — add `POST /entries/bulk`.
**Frontend**
- `src/admin/components/BulkPlanModal.tsx` — new presentational modal.
- `src/admin/hooks/usePlanWork.ts` — add a `bulkCreate` mutation.
- `src/admin/pages/PlanWork.tsx` — toolbar button + bulk form state + toggles + submit wiring.
**Tests**
- `src/__tests__/plan.test.ts``bulkCreateEntries` service tests.
---
## Task 1: Backend — bulk endpoint + service
**Files:**
- Modify: `src/schemas/plan.schema.ts`
- Modify: `src/services/plan.service.ts`
- Modify: `src/routes/admin/plan.ts`
- Test: `src/__tests__/plan.test.ts`
- [ ] **Step 1: Write the failing service tests**
Add this block to the end of `src/__tests__/plan.test.ts` (before the final HTTP describe block is fine; anywhere at top level). It imports `bulkCreateEntries` — add it to the existing `import { ... } from "../services/plan.service"` list at the top of the file.
```ts
// ---------------------------------------------------------------------------
// bulkCreateEntries
// ---------------------------------------------------------------------------
describe("plan.service.bulkCreateEntries", () => {
it("creates one continuous range per employee when weekends are included", async () => {
// 2096-06-01 is a Friday; 2096-06-03 is a Sunday. include_weekends → one
// range 06-01..06-03 covering all 3 days.
const res = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-01",
date_to: "2096-06-03",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}bulk-wknd`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.created_entries).toBe(1);
expect(res.data.created_days).toBe(3);
expect(res.data.skipped_days).toBe(0);
expect(res.data.users).toBe(1);
});
it("splits into per-work-week ranges and skips weekends when excluded", async () => {
// 2096-06-01 (Fri) .. 2096-06-05 (Tue): Fri | Sat Sun excluded | Mon Tue.
// Two runs: [06-01] and [06-04..06-05] → 2 entries, 3 days, 0 skipped.
const res = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-01",
date_to: "2096-06-05",
include_weekends: false,
project_id: null,
category: "work",
note: `${N}bulk-week`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.created_entries).toBe(2);
expect(res.data.created_days).toBe(3);
expect(res.data.skipped_days).toBe(0);
});
it("skips days already at the cap and splits the range around them", async () => {
// Pre-fill 2096-07-02 to the cap (3 entries) for the user. A weekends-on
// bulk over 07-01..07-03 then creates 07-01 and 07-03 (two ranges), skips
// 07-02. 2096-07-01..03 are Sun/Mon/Tue — all included with weekends on.
for (let i = 0; i < 3; i++) {
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2096-07-02"),
date_to: new Date("2096-07-02"),
category: "work",
note: `${N}cap${i}`,
created_by: adminUserId,
},
});
}
const res = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-07-01",
date_to: "2096-07-03",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}bulk-cap`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.created_entries).toBe(2);
expect(res.data.created_days).toBe(2);
expect(res.data.skipped_days).toBe(1);
});
it("aggregates across multiple employees", async () => {
const res = await bulkCreateEntries(
{
user_ids: [adminUserId, noPermUserId],
date_from: "2096-08-03", // Friday
date_to: "2096-08-03",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}bulk-multi`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.users).toBe(2);
expect(res.data.created_entries).toBe(2);
expect(res.data.created_days).toBe(2);
});
it("rejects empty user_ids, past dates, bad range, and inactive category", async () => {
const empty = await bulkCreateEntries(
{
user_ids: [],
date_from: "2096-06-01",
date_to: "2096-06-01",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}x`,
},
adminUserId,
);
expect("error" in empty && empty.status).toBe(400);
const past = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2000-01-01",
date_to: "2000-01-02",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}x`,
},
adminUserId,
);
expect("error" in past && past.status).toBe(403);
const badRange = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-10",
date_to: "2096-06-01",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}x`,
},
adminUserId,
);
expect("error" in badRange && badRange.status).toBe(400);
const badCat = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-01",
date_to: "2096-06-01",
include_weekends: true,
project_id: null,
category: "__nope__",
note: `${N}x`,
},
adminUserId,
);
expect("error" in badCat && badCat.status).toBe(400);
});
});
```
- [ ] **Step 2: Run the tests to verify they fail**
Run: `npx vitest run src/__tests__/plan.test.ts`
Expected: FAIL — `bulkCreateEntries` is not exported / not a function.
- [ ] **Step 3: Implement `bulkCreateEntries` in `plan.service.ts`**
Add at the end of `src/services/plan.service.ts` (after `listOverrides`):
```ts
// ---------------------------------------------------------------------------
// Bulk entry creation
// ---------------------------------------------------------------------------
/**
* Bulk-assign a project/category to many employees over a date range. For each
* employee, walk the range, keep the days that pass the weekday filter
* (weekends excluded unless include_weekends) AND are under the per-cell cap,
* group contiguous kept days into runs, and create one range entry per run by
* reusing createEntry (so cap / past-date / category validation stays DRY).
*
* Days that pass the weekday filter but are already at the cap are counted in
* skipped_days (and split the range). Weekend days, when excluded, are out of
* scope and are NOT counted as skipped.
*/
export async function bulkCreateEntries(
input: {
user_ids: number[];
date_from: string;
date_to: string;
include_weekends: boolean;
project_id?: number | null;
category: string;
note: string;
},
actorUserId: number,
): Promise<
Result<{
created_entries: number;
created_days: number;
skipped_days: number;
users: number;
}>
> {
if (input.user_ids.length === 0) {
return { error: "Vyberte alespoň jednoho zaměstnance", status: 400 };
}
if (input.date_to < input.date_from) {
return { error: "Datum do musí být stejné nebo po datumu od", status: 400 };
}
const lockFrom = assertNotPastDate(input.date_from, false);
if (lockFrom) return lockFrom;
const lockTo = assertNotPastDate(input.date_to, false);
if (lockTo) return lockTo;
const catErr = await assertActiveCategory(input.category);
if (catErr) return catErr;
const from = toDateOnly(input.date_from);
const to = toDateOnly(input.date_to);
// The day list for the whole range (UTC midnights), built once.
const days: Date[] = [];
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
days.push(new Date(d));
}
let createdEntries = 0;
let createdDays = 0;
let skippedDays = 0;
for (const userId of input.user_ids) {
// Per-day cap counts from this user's existing active entries.
const existing = await prisma.work_plan_entries.findMany({
where: {
user_id: userId,
is_deleted: false,
date_from: { lte: to },
date_to: { gte: from },
},
select: { date_from: true, date_to: true },
});
const countFor = (day: Date): number =>
existing.filter((e) => e.date_from <= day && e.date_to >= day).length;
// Eligibility per day (weekday filter + under-cap). Tally cap skips.
const eligible: boolean[] = [];
for (const day of days) {
const dow = day.getUTCDay(); // 0 = Sun, 6 = Sat
const isWeekend = dow === 0 || dow === 6;
if (isWeekend && !input.include_weekends) {
eligible.push(false);
continue;
}
if (countFor(day) >= MAX_RECORDS_PER_CELL) {
skippedDays++;
eligible.push(false);
continue;
}
eligible.push(true);
}
// Group contiguous eligible days into runs; create one range per run.
let runStart = -1;
for (let i = 0; i <= days.length; i++) {
const ok = i < days.length && eligible[i];
if (ok && runStart === -1) {
runStart = i;
} else if (!ok && runStart !== -1) {
const segFrom = days[runStart].toISOString().slice(0, 10);
const segTo = days[i - 1].toISOString().slice(0, 10);
const runDays = i - runStart;
const res = await createEntry(
{
user_id: userId,
date_from: segFrom,
date_to: segTo,
project_id: input.project_id ?? null,
category: input.category,
note: input.note,
},
actorUserId,
false,
);
if ("data" in res) {
createdEntries++;
createdDays += runDays;
} else {
// Rare race (e.g. the cap filled concurrently). Treat as skipped.
skippedDays += runDays;
}
runStart = -1;
}
}
}
return {
data: {
created_entries: createdEntries,
created_days: createdDays,
skipped_days: skippedDays,
users: input.user_ids.length,
},
oldData: null,
};
}
```
- [ ] **Step 4: Run the service tests to verify they pass**
Run: `npx vitest run src/__tests__/plan.test.ts`
Expected: PASS (including the 5 new bulk tests).
- [ ] **Step 5: Add `BulkPlanEntrySchema` to `plan.schema.ts`**
Append to `src/schemas/plan.schema.ts`:
```ts
export const BulkPlanEntrySchema = z
.object({
user_ids: z
.array(intFromForm)
.min(1, "Vyberte alespoň jednoho zaměstnance"),
date_from: isoDate,
date_to: isoDate,
include_weekends: z
.union([z.boolean(), z.string()])
.transform((v) => v === true || v === "true" || v === "1")
.default(false),
project_id: z
.union([z.number(), z.string(), z.null()])
.transform((v) => (v === null ? null : Number(v)))
.nullish(),
category: planCategoryEnum.default("work"),
note: z.string().max(500, "Maximálně 500 znaků").default(""),
})
.refine((v) => v.date_to >= v.date_from, {
message: "Datum do musí být stejné nebo po datumu od",
path: ["date_to"],
});
```
- [ ] **Step 6: Add the `POST /entries/bulk` route**
In `src/routes/admin/plan.ts`: add `bulkCreateEntries` to the existing import from `../../services/plan.service` and `BulkPlanEntrySchema` to the import from `../../schemas/plan.schema`. Then add this route immediately after the `POST /entries` handler (after its closing `);`, before `PATCH /entries/:id`):
```ts
// --- POST /plan/entries/bulk ---
app.post(
"/entries/bulk",
{ preHandler: requirePermission("attendance.manage") },
async (request: FastifyRequest, reply: FastifyReply) => {
const body = parseBody(BulkPlanEntrySchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const result = await bulkCreateEntries(
body.data!,
request.authData!.userId,
);
if ("error" in result) return error(reply, result.error, result.status);
await logAudit({
request,
authData: request.authData,
action: "create",
entityType: "work_plan_entry",
description: `Hromadné přiřazení: ${body.data!.category}${result.data.users} zaměstnanců, ${body.data!.date_from}${body.data!.date_to} (${result.data.created_days} dní)`,
});
return success(reply, result.data, 201, "Hromadné přiřazení dokončeno");
},
);
```
- [ ] **Step 7: Add an HTTP route test**
Add to the `describe("HTTP /api/admin/plan", ...)` block in `src/__tests__/plan.test.ts`:
```ts
it("POST /entries/bulk requires attendance.manage", async () => {
const res = await authPost("/api/admin/plan/entries/bulk", noPermToken, {
user_ids: [adminUserId],
date_from: "2095-06-01",
date_to: "2095-06-01",
include_weekends: true,
category: "work",
note: `${N}bulk-forbidden`,
});
expect(res.statusCode).toBe(403);
});
it("POST /entries/bulk creates entries for an admin and returns a summary", async () => {
const res = await authPost("/api/admin/plan/entries/bulk", adminToken, {
user_ids: [adminUserId],
date_from: "2095-06-05", // Sunday; weekends on → 1 day
date_to: "2095-06-05",
include_weekends: true,
category: "work",
note: `${N}bulk-http`,
});
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body.success).toBe(true);
expect(body.data.created_days).toBe(1);
expect(body.data.users).toBe(1);
});
```
- [ ] **Step 8: Gate**
Run: `npx tsc -b --noEmit` (exit 0), then `npx vitest run` (all pass).
- [ ] **Step 9: Commit**
```bash
git add src/schemas/plan.schema.ts src/services/plan.service.ts src/routes/admin/plan.ts src/__tests__/plan.test.ts
git commit -m "feat(plan): bulk entry creation endpoint + service"
```
---
## Task 2: Frontend — bulk modal + wiring
**Files:**
- Create: `src/admin/components/BulkPlanModal.tsx`
- Modify: `src/admin/hooks/usePlanWork.ts`
- Modify: `src/admin/pages/PlanWork.tsx`
Frontend-only; gate on `tsc -b` + `build` (no component-test harness). Mirrors `BulkAttendanceModal.tsx` (presentational; parent owns state + toggles + submit).
- [ ] **Step 1: Create `BulkPlanModal.tsx`**
```tsx
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import {
Modal,
Field,
DateField,
Select,
TextField,
CheckboxField,
} from "../ui";
import type { PlanUser, PlanCategory } from "../lib/queries/plan";
import type { Project } from "../lib/queries/projects";
export interface BulkPlanForm {
date_from: string;
date_to: string;
is_range: boolean;
user_ids: string[];
include_weekends: boolean;
project_id: string;
category: string;
note: string;
}
interface Props {
isOpen: boolean;
onClose: () => void;
form: BulkPlanForm;
setForm: (form: BulkPlanForm) => void;
users: PlanUser[];
projects: Project[];
categories: PlanCategory[];
onSubmit: () => void;
submitting: boolean;
toggleUser: (userId: number) => void;
toggleAllUsers: () => void;
}
export default function BulkPlanModal({
isOpen,
onClose,
form,
setForm,
users,
projects,
categories,
onSubmit,
submitting,
toggleUser,
toggleAllUsers,
}: Props) {
const activeCategories = categories.filter((c) => c.is_active);
return (
<Modal
isOpen={isOpen}
onClose={onClose}
title="Hromadné přiřazení"
maxWidth="lg"
loading={submitting}
onSubmit={onSubmit}
submitText="Vytvořit"
submitDisabled={form.user_ids.length === 0}
>
<Typography
variant="body2"
color="text.secondary"
sx={{ mt: 0.25, mb: 2 }}
>
Vytvoří záznamy pro vybrané dny u zvolených zaměstnanců. Dny, které
mají 3 záznamy, se přeskočí.
</Typography>
<Field label="Datum od">
<DateField
value={form.date_from}
onChange={(val) => setForm({ ...form, date_from: val })}
/>
</Field>
<Field label="Rozsah dnů">
<CheckboxField
label="Více dní"
checked={form.is_range}
onChange={(checked) => setForm({ ...form, is_range: checked })}
/>
</Field>
{form.is_range && (
<Field label="Datum do">
<DateField
value={form.date_to}
onChange={(val) => setForm({ ...form, date_to: val })}
/>
</Field>
)}
<Field label="Víkendy">
<CheckboxField
label="Zahrnout víkendy"
checked={form.include_weekends}
onChange={(checked) =>
setForm({ ...form, include_weekends: checked })
}
/>
</Field>
<Box sx={{ mb: 2 }}>
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, mb: 0.5 }}>
<Typography
component="span"
variant="body2"
sx={{ fontWeight: 600, color: "text.secondary" }}
>
Zaměstnanci
</Typography>
<Typography
component="button"
type="button"
onClick={toggleAllUsers}
variant="caption"
sx={{
background: "none",
border: "none",
p: 0,
cursor: "pointer",
fontWeight: 500,
color: "primary.main",
}}
>
{form.user_ids.length === users.length
? "Odznačit vše"
: "Vybrat vše"}
</Typography>
</Box>
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: 0.25,
maxHeight: 200,
overflowY: "auto",
p: 1.5,
bgcolor: "action.hover",
borderRadius: 2,
border: 1,
borderColor: "divider",
}}
>
{users.map((u) => (
<CheckboxField
key={u.id}
label={u.full_name}
checked={form.user_ids.includes(String(u.id))}
onChange={() => toggleUser(u.id)}
/>
))}
</Box>
<Typography variant="caption" color="text.secondary">
Vybráno: {form.user_ids.length} z {users.length}
</Typography>
</Box>
<Field label="Projekt">
<Select
value={form.project_id}
onChange={(val) => setForm({ ...form, project_id: val })}
options={[
{ value: "", label: "— bez projektu —" },
...projects.map((p) => ({ value: String(p.id), label: p.name })),
]}
/>
</Field>
<Field label="Kategorie">
<Select
value={form.category}
onChange={(val) => setForm({ ...form, category: val })}
options={activeCategories.map((c) => ({
value: c.key,
label: c.label,
}))}
/>
</Field>
<Field label="Text poznámky (volitelný)">
<TextField
multiline
minRows={2}
value={form.note}
onChange={(e) => setForm({ ...form, note: e.target.value })}
inputProps={{ maxLength: 500 }}
/>
</Field>
</Modal>
);
}
```
- [ ] **Step 2: Add a `bulkCreate` mutation to `usePlanWork.ts`**
After the `deleteOverride` mutation definition (before the `rollbackMutation` function), add:
```ts
const bulkCreate = useMutation({
mutationFn: (body: any) =>
apiCall("/api/admin/plan/entries/bulk", {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
}),
onSuccess: () => {
// No optimistic patch — bulk can touch many cells; just invalidate and
// let the grid refetch the authoritative state.
invalidate();
},
});
```
Add `bulkCreate` to the hook's return object (next to `createEntry`, etc.).
- [ ] **Step 3: Wire the bulk modal into `PlanWork.tsx`**
(a) Add imports near the other component imports:
```ts
import BulkPlanModal, { type BulkPlanForm } from "../components/BulkPlanModal";
```
(b) Pull `bulkCreate` out of the `usePlanWork(...)` destructure (alongside `createEntry`, etc.).
(c) Add bulk state + a default form (place near the other `useState` declarations, after `catModalOpen`):
```ts
const [bulkOpen, setBulkOpen] = useState(false);
const [bulkSubmitting, setBulkSubmitting] = useState(false);
const [bulkForm, setBulkForm] = useState<BulkPlanForm>(() => {
const today = todayIsoLocal();
return {
date_from: today,
date_to: today,
is_range: false,
user_ids: [],
include_weekends: false,
project_id: "",
category: "work",
note: "",
};
});
const planUsers = grid?.users ?? [];
const toggleBulkUser = useCallback((userId: number) => {
setBulkForm((prev) => ({
...prev,
user_ids: prev.user_ids.includes(String(userId))
? prev.user_ids.filter((u) => u !== String(userId))
: [...prev.user_ids, String(userId)],
}));
}, []);
const toggleAllBulkUsers = useCallback(() => {
const allIds = (grid?.users ?? []).map((u) => String(u.id));
setBulkForm((prev) => ({
...prev,
user_ids: prev.user_ids.length === allIds.length ? [] : allIds,
}));
}, [grid]);
const submitBulk = useCallback(async () => {
if (bulkForm.user_ids.length === 0) return;
setBulkSubmitting(true);
try {
const data: any = await bulkCreate.mutateAsync({
user_ids: bulkForm.user_ids.map(Number),
date_from: bulkForm.date_from,
date_to: bulkForm.is_range ? bulkForm.date_to : bulkForm.date_from,
include_weekends: bulkForm.include_weekends,
project_id: bulkForm.project_id ? Number(bulkForm.project_id) : null,
category: bulkForm.category,
note: bulkForm.note,
});
const skipped =
data?.skipped_days > 0
? ` ${data.skipped_days} dní přeskočeno (limit 3 na den).`
: "";
alert.success(
`Vytvořeno ${data?.created_days ?? 0} záznamů pro ${data?.users ?? 0} zaměstnanců.${skipped}`,
);
setBulkOpen(false);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba při ukládání");
} finally {
setBulkSubmitting(false);
}
}, [bulkForm, bulkCreate, alert]);
```
(d) Add the toolbar button next to "Správa kategorií" (inside the same `canEdit` region of the toolbar `<Box>`):
```tsx
{
canEdit && (
<Button
variant="outlined"
color="inherit"
onClick={() => setBulkOpen(true)}
>
Hromadné přiřazení
</Button>
);
}
```
(e) Render the modal alongside `<PlanCategoriesModal ... />`:
```tsx
<BulkPlanModal
isOpen={bulkOpen}
onClose={() => setBulkOpen(false)}
form={bulkForm}
setForm={setBulkForm}
users={planUsers}
projects={projects}
categories={categories}
onSubmit={submitBulk}
submitting={bulkSubmitting}
toggleUser={toggleBulkUser}
toggleAllUsers={toggleAllBulkUsers}
/>
```
- [ ] **Step 4: Gate + Chrome check**
```bash
npx tsc -b --noEmit
npm run build
```
Then in Chrome on `/plan-work` (dev server already running — do not start it): click "Hromadné přiřazení", select 2 employees, a date range with "Více dní", leave weekends off, pick a project + category, submit; confirm the grid fills only MonFri across the selected people, the summary alert shows counts, and re-running on a day already at 3 records skips it.
- [ ] **Step 5: Commit**
```bash
git add src/admin/components/BulkPlanModal.tsx src/admin/hooks/usePlanWork.ts src/admin/pages/PlanWork.tsx
git commit -m "feat(plan): bulk assignment modal on /plan-work"
```
---
## Task 3: Release v2.0.6
**Files:**
- Modify: `package.json`
- [ ] **Step 1: Bump version** to `"version": "2.0.6"` in `package.json`.
- [ ] **Step 2: Full gate**
```bash
npx tsc -b --noEmit
npx vitest run
npm run build
```
Expected: tsc exit 0, vitest all pass, build success.
- [ ] **Step 3: Merge to master + commit + tag**
```bash
git checkout master
git merge --ff-only feat/bulk-plan-creation
git add package.json
git commit -m "chore(release): v2.0.6 — bulk plan creation"
git tag -a v2.0.6 -m "v2.0.6 — bulk plan creation"
```
(If implementation happened directly on master, skip the checkout/merge.)
- [ ] **Step 4: Push to Gitea**
```bash
git push origin master
git push origin v2.0.6
```
- [ ] **Step 5: Build tarball + deploy to production (REQUIRES explicit user confirmation)**
```bash
tar -czf app-ts-2.0.6.tar.gz dist dist-client prisma package.json package-lock.json scripts
scp app-ts-2.0.6.tar.gz boha_admin@192.168.50.100:/tmp/
ssh boha_admin@192.168.50.100 'set -e; cd /var/www/app-ts && rm -rf dist dist-client prisma scripts package.json package-lock.json && tar -xzf /tmp/app-ts-2.0.6.tar.gz && npm install --omit=dev && npx prisma migrate deploy && pm2 restart app-ts --update-env'
```
No migration ships in this release → `prisma migrate deploy` reports "No pending migrations".
- [ ] **Step 6: Health check**
```bash
ssh boha_admin@192.168.50.100 'curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3001/; curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3001/api/admin/session'
```
Expected: `200` then `401`. Confirm pm2 shows `app-ts` v2.0.6 online.
---
## Notes for the implementer
- **Reuse, don't re-validate:** `bulkCreateEntries` calls `createEntry`, which already enforces the cap, past-date, category, and range checks. Don't duplicate those.
- **`skipped_days` semantics:** only weekday-eligible days blocked by the cap count as skipped. Weekend days (when excluded) are out of scope, not skipped.
- **No DB migration.** Don't run any prisma migrate command.
- **Do not start the dev server** — the user runs it. Use the running instance for the Chrome check.
- **Do not deploy to production without explicit confirmation** (Task 3, Steps 56).

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,792 @@
# Odin Multi-Conversation Chat — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Turn the single-thread Odin assistant into a multi-conversation chat (top-tabs, rename/delete, auto-title) on the `/odin` page.
**Architecture:** New `ai_conversations` table; `ai_chat_messages` gains `conversation_id` (FK, cascade). Conversation-scoped service + routes replace the single `/history` endpoints. A new `OdinChat` component (+ focused sub-components) replaces `DashAssistant`, keeping all proven chat/extract/save logic but scoped to the active conversation.
**Tech Stack:** Fastify 5, Prisma 6 (MySQL), Zod 4, React 18 + MUI v7, TanStack Query, Vitest (real DB).
**Spec:** `docs/superpowers/specs/2026-06-08-odin-conversations-design.md`.
---
## File map
| File | Responsibility |
| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `prisma/schema.prisma` | + `ai_conversations`; `ai_chat_messages.conversation_id` + relation + index swap |
| `prisma/migrations/20260608140000_add_ai_conversations/migration.sql` | create table, add column, backfill, enforce FK |
| `src/services/ai.service.ts` | replace `getChatHistory/appendChatMessages/clearChatHistory` with conversation-scoped fns |
| `src/schemas/ai.schema.ts` | + `AiCreateConversationSchema`, `AiRenameConversationSchema`; keep `AiHistoryAppendSchema` (reused for append) |
| `src/routes/admin/ai.ts` | replace `/history` routes with `/conversations*` routes |
| `src/__tests__/ai.test.ts` | replace history tests with conversation tests |
| `src/admin/lib/queries/ai.ts` | + conversation query options/types; remove `aiHistoryOptions` |
| `src/admin/components/odin/OdinTabs.tsx` | conversation tabs + new + rename/delete menu |
| `src/admin/components/odin/OdinThread.tsx` | message list + avatar + empty/busy states |
| `src/admin/components/odin/InvoiceReviewCard.tsx` | editable extracted-invoice card |
| `src/admin/components/odin/OdinComposer.tsx` | staged chips + attach + input + send |
| `src/admin/components/odin/OdinChat.tsx` | orchestrator: queries, state, the ported logic |
| `src/admin/pages/Odin.tsx` | render `OdinChat` (was `DashAssistant`) |
| `src/admin/components/dashboard/DashAssistant.tsx` | **deleted** |
**Controller note (migration):** Tasks that touch the DB require the dev server stopped. After Task 1's files are written, the **controller** runs: ask user to stop dev server → `npx prisma generate``npx prisma migrate deploy` (applies to dev `app` DB) → resume. Backend tsc is red between Task 1 and Task 2 (data model changes before the service is updated) — that is expected; Task 2 restores green.
---
## Task 1: Data model + migration
**Files:**
- Modify: `prisma/schema.prisma`
- Create: `prisma/migrations/20260608140000_add_ai_conversations/migration.sql`
- [ ] **Step 1: Edit `prisma/schema.prisma`** — replace the existing `ai_chat_messages` model and add `ai_conversations` above it:
```prisma
model ai_conversations {
id Int @id @default(autoincrement())
user_id Int
title String @db.VarChar(255)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @updatedAt @db.Timestamp(0)
messages ai_chat_messages[]
@@index([user_id, id], map: "idx_ai_conv_user")
}
model ai_chat_messages {
id Int @id @default(autoincrement())
user_id Int
conversation_id Int
role String @db.VarChar(20)
content String @db.Text
created_at DateTime @default(now()) @db.Timestamp(0)
conversation ai_conversations @relation(fields: [conversation_id], references: [id], onDelete: Cascade)
@@index([conversation_id, id], map: "idx_ai_chat_conv")
}
```
- [ ] **Step 2: Write the migration SQL** at `prisma/migrations/20260608140000_add_ai_conversations/migration.sql`:
```sql
-- Multi-conversation Odin: conversations table + conversation_id on messages.
CREATE TABLE `ai_conversations` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`user_id` INTEGER NOT NULL,
`title` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`),
INDEX `idx_ai_conv_user` (`user_id`, `id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `ai_chat_messages`
ADD COLUMN `conversation_id` INTEGER NULL AFTER `user_id`;
-- Backfill: one conversation per user who has messages ("keep as first conversation").
INSERT INTO `ai_conversations` (`user_id`, `title`, `created_at`, `updated_at`)
SELECT `user_id`, 'Konverzace', NOW(), NOW()
FROM `ai_chat_messages`
GROUP BY `user_id`;
UPDATE `ai_chat_messages` m
JOIN `ai_conversations` c ON c.`user_id` = m.`user_id`
SET m.`conversation_id` = c.`id`;
-- Enforce: drop old per-user index, NOT NULL, FK (cascade), per-conversation index.
ALTER TABLE `ai_chat_messages`
DROP INDEX `idx_ai_chat_user`,
MODIFY `conversation_id` INTEGER NOT NULL,
ADD CONSTRAINT `fk_ai_chat_conv` FOREIGN KEY (`conversation_id`)
REFERENCES `ai_conversations`(`id`) ON DELETE CASCADE,
ADD INDEX `idx_ai_chat_conv` (`conversation_id`, `id`);
```
- [ ] **Step 3: Controller applies the migration** (not the implementer):
- Ask user to stop the dev server (Prisma engine DLL is locked on Windows otherwise).
- `npx prisma generate` — expect "Generated Prisma Client".
- `npx prisma migrate deploy` — expect "Applying migration `20260608140000_add_ai_conversations`" → "successfully applied".
- [ ] **Step 4: Commit**
```bash
git add prisma/schema.prisma prisma/migrations/20260608140000_add_ai_conversations
git commit -m "feat(odin): ai_conversations table + conversation_id on messages"
```
---
## Task 2: Backend — conversation service, schemas, routes
**Files:**
- Modify: `src/services/ai.service.ts`
- Modify: `src/schemas/ai.schema.ts`
- Modify: `src/routes/admin/ai.ts`
- [ ] **Step 1: Replace the chat-history block in `ai.service.ts`.** Delete `getChatHistory`, `appendChatMessages`, `clearChatHistory` and the `HISTORY_LIMIT` const, and put this in their place (keep the `StoredChatMessage` interface):
```ts
// ── Conversations (server-side, per user) ─────────────────────────────────
export interface StoredChatMessage {
role: string;
content: string;
created_at: Date;
}
export interface ConversationSummary {
id: number;
title: string;
updated_at: Date;
}
const DEFAULT_CONVERSATION_TITLE = "Nová konverzace";
const MESSAGE_LIMIT = 200; // cap a single thread read
export async function listConversations(
userId: number,
): Promise<ConversationSummary[]> {
return prisma.ai_conversations.findMany({
where: { user_id: userId },
orderBy: { id: "asc" }, // stable tab order
select: { id: true, title: true, updated_at: true },
});
}
export async function createConversation(
userId: number,
title?: string,
): Promise<ConversationSummary> {
return prisma.ai_conversations.create({
data: {
user_id: userId,
title: title?.trim() || DEFAULT_CONVERSATION_TITLE,
},
select: { id: true, title: true, updated_at: true },
});
}
/** Ownership-checked fetch; null when not found / not owned. */
async function ownConversation(userId: number, convId: number) {
return prisma.ai_conversations.findFirst({
where: { id: convId, user_id: userId },
select: { id: true, title: true },
});
}
export async function getConversationMessages(
userId: number,
convId: number,
): Promise<{ data: StoredChatMessage[] } | { error: string; status: number }> {
if (!(await ownConversation(userId, convId)))
return { error: "Konverzace nenalezena", status: 404 };
const rows = await prisma.ai_chat_messages.findMany({
where: { conversation_id: convId },
orderBy: { id: "desc" },
take: MESSAGE_LIMIT,
select: { role: true, content: true, created_at: true },
});
return { data: rows.reverse() };
}
export async function appendConversationMessages(
userId: number,
convId: number,
messages: { role: string; content: string }[],
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
const conv = await ownConversation(userId, convId);
if (!conv) return { error: "Konverzace nenalezena", status: 404 };
if (messages.length > 0) {
await prisma.ai_chat_messages.createMany({
data: messages.map((m) => ({
user_id: userId,
conversation_id: convId,
role: m.role,
content: m.content,
})),
});
}
// Auto-title from the first user message (only while still the default), and
// always bump updated_at.
const firstUser = messages.find((m) => m.role === "user");
const data: { updated_at: Date; title?: string } = { updated_at: new Date() };
if (conv.title === DEFAULT_CONVERSATION_TITLE && firstUser) {
const t = firstUser.content.replace(/\s+/g, " ").trim().slice(0, 60);
if (t) data.title = t;
}
await prisma.ai_conversations.update({ where: { id: convId }, data });
return { data: { ok: true } };
}
export async function renameConversation(
userId: number,
convId: number,
title: string,
): Promise<{ data: ConversationSummary } | { error: string; status: number }> {
if (!(await ownConversation(userId, convId)))
return { error: "Konverzace nenalezena", status: 404 };
const updated = await prisma.ai_conversations.update({
where: { id: convId },
data: { title: title.trim() || DEFAULT_CONVERSATION_TITLE },
select: { id: true, title: true, updated_at: true },
});
return { data: updated };
}
export async function deleteConversation(
userId: number,
convId: number,
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
if (!(await ownConversation(userId, convId)))
return { error: "Konverzace nenalezena", status: 404 };
await prisma.ai_conversations.delete({ where: { id: convId } }); // cascade
return { data: { ok: true } };
}
```
- [ ] **Step 2: Schemas** — in `src/schemas/ai.schema.ts`, keep `AiHistoryAppendSchema` (reused for append) and add:
```ts
export const AiCreateConversationSchema = z.object({
title: z.string().max(255).optional(),
});
export const AiRenameConversationSchema = z.object({
title: z.string().min(1, "Název je povinný").max(255),
});
```
- [ ] **Step 3: Routes** — in `src/routes/admin/ai.ts`: update imports (drop `getChatHistory/appendChatMessages/clearChatHistory`, add the new fns; add `AiCreateConversationSchema, AiRenameConversationSchema`; import `parseId` from `"../../schemas/common"`). Delete the three `/history` route blocks and append these (all `requirePermission("ai.use")`):
```ts
// GET /conversations — this user's conversations (stable order)
app.get(
"/conversations",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const conversations = await listConversations(request.authData!.userId);
return success(reply, { conversations });
},
);
// POST /conversations — create
app.post(
"/conversations",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const body = parseBody(AiCreateConversationSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const conversation = await createConversation(
request.authData!.userId,
body.data.title,
);
return success(reply, { conversation });
},
);
// GET /conversations/:id/messages
app.get(
"/conversations/:id/messages",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const result = await getConversationMessages(request.authData!.userId, id);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, { messages: result.data });
},
);
// POST /conversations/:id/messages — append turns
app.post(
"/conversations/:id/messages",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const body = parseBody(AiHistoryAppendSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const result = await appendConversationMessages(
request.authData!.userId,
id,
body.data.messages,
);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, result.data);
},
);
// PATCH /conversations/:id — rename
app.patch(
"/conversations/:id",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const body = parseBody(AiRenameConversationSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const result = await renameConversation(
request.authData!.userId,
id,
body.data.title,
);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, { conversation: result.data });
},
);
// DELETE /conversations/:id
app.delete(
"/conversations/:id",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const result = await deleteConversation(request.authData!.userId, id);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, result.data);
},
);
```
- [ ] **Step 4: Gate**
Run: `npx tsc -b --noEmit` — expect exit 0. Run: `npm run build` — expect success.
- [ ] **Step 5: Commit**
```bash
git add src/services/ai.service.ts src/schemas/ai.schema.ts src/routes/admin/ai.ts
git commit -m "feat(odin): conversation-scoped service + routes (replace /history)"
```
---
## Task 3: Backend tests
**Files:**
- Modify: `src/__tests__/ai.test.ts`
- [ ] **Step 1: Replace the imports + cleanup markers.** Swap the history-fn imports for the conversation fns, and update the top-of-file constants/cleanup:
```ts
import {
computeCostUsd,
recordUsage,
getMonthSpendUsd,
getBudgetUsd,
assertBudgetAvailable,
isConfigured,
listConversations,
createConversation,
getConversationMessages,
appendConversationMessages,
renameConversation,
deleteConversation,
} from "../services/ai.service";
const KIND = "test_ai";
const CONV_UID_A = 999999991; // synthetic, FK-free owner ids
const CONV_UID_B = 999999992;
const HIST_MARKER = "「test-conv」"; // marks HTTP-test conversations on real users
```
Update the top-level cleanup (`afterAll` and the conversation `beforeEach`) to delete by these. Deleting a conversation cascades its messages:
```ts
afterAll(async () => {
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
await prisma.ai_conversations.deleteMany({
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
});
await prisma.ai_conversations.deleteMany({
where: { title: { contains: HIST_MARKER } },
});
});
```
- [ ] **Step 2: Replace the `describe("ai.service chat history", …)` block** with conversation service tests:
```ts
describe("ai.service conversations", () => {
beforeEach(async () => {
await prisma.ai_conversations.deleteMany({
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
});
});
it("creates, lists, appends (auto-title), and reads oldest→newest", async () => {
const conv = await createConversation(CONV_UID_A);
expect(conv.title).toBe("Nová konverzace");
await appendConversationMessages(CONV_UID_A, conv.id, [
{ role: "user", content: "Kolik je hodin v Praze?" },
{ role: "assistant", content: "Nevím, ale…" },
]);
const list = await listConversations(CONV_UID_A);
expect(list).toHaveLength(1);
expect(list[0].title).toBe("Kolik je hodin v Praze?"); // auto-titled
const msgs = await getConversationMessages(CONV_UID_A, conv.id);
expect("data" in msgs && msgs.data.map((m) => m.content)).toEqual([
"Kolik je hodin v Praze?",
"Nevím, ale…",
]);
});
it("does not overwrite a renamed title on later appends", async () => {
const conv = await createConversation(CONV_UID_A);
await renameConversation(CONV_UID_A, conv.id, "Moje téma");
await appendConversationMessages(CONV_UID_A, conv.id, [
{ role: "user", content: "tohle by nemělo přepsat název" },
]);
const list = await listConversations(CONV_UID_A);
expect(list[0].title).toBe("Moje téma");
});
it("isolates conversations per user (404 across owners)", async () => {
const a = await createConversation(CONV_UID_A);
expect(await listConversations(CONV_UID_B)).toHaveLength(0);
const read = await getConversationMessages(CONV_UID_B, a.id);
expect("error" in read && read.status).toBe(404);
const ren = await renameConversation(CONV_UID_B, a.id, "hack");
expect("error" in ren && ren.status).toBe(404);
const del = await deleteConversation(CONV_UID_B, a.id);
expect("error" in del && del.status).toBe(404);
});
it("cascade-deletes messages with the conversation", async () => {
const conv = await createConversation(CONV_UID_A);
await appendConversationMessages(CONV_UID_A, conv.id, [
{ role: "user", content: "x" },
]);
await deleteConversation(CONV_UID_A, conv.id);
const remaining = await prisma.ai_chat_messages.count({
where: { conversation_id: conv.id },
});
expect(remaining).toBe(0);
});
});
```
- [ ] **Step 3: Replace the HTTP history tests** (the `/history` `it(...)` blocks) with conversation HTTP tests inside the existing `describe("HTTP /api/admin/ai", …)`:
```ts
it("GET /conversations requires ai.use", async () => {
const res = await app.inject({
method: "GET",
url: "/api/admin/ai/conversations",
headers: { Authorization: `Bearer ${noPermToken}` },
});
expect(res.statusCode).toBe(403);
});
it("conversation lifecycle over HTTP (create → append → list → rename → delete)", async () => {
const created = await app.inject({
method: "POST",
url: "/api/admin/ai/conversations",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { title: `${HIST_MARKER} t` },
});
expect(created.statusCode).toBe(200);
const id = created.json().data.conversation.id as number;
const app2 = await app.inject({
method: "POST",
url: `/api/admin/ai/conversations/${id}/messages`,
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { messages: [{ role: "user", content: "ahoj" }] },
});
expect(app2.statusCode).toBe(200);
const msgs = await app.inject({
method: "GET",
url: `/api/admin/ai/conversations/${id}/messages`,
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(
msgs.json().data.messages.map((m: { content: string }) => m.content),
).toContain("ahoj");
const renamed = await app.inject({
method: "PATCH",
url: `/api/admin/ai/conversations/${id}`,
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { title: `${HIST_MARKER} renamed` },
});
expect(renamed.json().data.conversation.title).toBe(`${HIST_MARKER} renamed`);
const del = await app.inject({
method: "DELETE",
url: `/api/admin/ai/conversations/${id}`,
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(del.statusCode).toBe(200);
});
it("GET messages of a non-existent conversation → 404", async () => {
const res = await app.inject({
method: "GET",
url: "/api/admin/ai/conversations/999999000/messages",
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(res.statusCode).toBe(404);
});
```
- [ ] **Step 4: Gate**
Run: `npx vitest run src/__tests__/ai.test.ts` — expect all passing. Then `npx vitest run` — expect the whole suite green.
- [ ] **Step 5: Commit**
```bash
git add src/__tests__/ai.test.ts
git commit -m "test(odin): conversation CRUD, isolation, auto-title, cascade"
```
---
## Task 4: Frontend queries + types
**Files:**
- Modify: `src/admin/lib/queries/ai.ts`
- [ ] **Step 1: Add conversation options.** Keep everything (incl. `aiHistoryOptions` for now — it's removed in Task 6 alongside its only consumer `DashAssistant.tsx`, so every task stays green). Add:
```ts
export interface Conversation {
id: number;
title: string;
updated_at: string;
}
export const aiConversationsOptions = () =>
queryOptions({
queryKey: ["ai", "conversations"],
queryFn: () =>
jsonQuery<{ conversations: Conversation[] }>(
"/api/admin/ai/conversations",
),
staleTime: 30_000,
});
export const aiConversationMessagesOptions = (id: number) =>
queryOptions({
queryKey: ["ai", "conversation", id, "messages"],
queryFn: () =>
jsonQuery<{ messages: StoredChatMessage[] }>(
`/api/admin/ai/conversations/${id}/messages`,
),
// Re-read the DB on each mount/selection (no stale-cache resurrection).
staleTime: Infinity,
gcTime: 0,
});
```
- [ ] **Step 2: Gate**
Run: `npx tsc -p tsconfig.app.json --noEmit` — expect exit 0 (we kept `aiHistoryOptions`, so `DashAssistant.tsx` still compiles).
- [ ] **Step 3: Commit**
```bash
git add src/admin/lib/queries/ai.ts
git commit -m "feat(odin): conversation query options"
```
---
## Task 5: Frontend presentational components
**Files:**
- Create: `src/admin/components/odin/OdinTabs.tsx`
- Create: `src/admin/components/odin/OdinThread.tsx`
- Create: `src/admin/components/odin/InvoiceReviewCard.tsx`
- Create: `src/admin/components/odin/OdinComposer.tsx`
These are **props-driven** (no data fetching). Port presentational details (bubble styling, the `Typography`-color fix, review-card fields, staged chips) from the current `src/admin/components/dashboard/DashAssistant.tsx`, which the implementer should read first.
- [ ] **Step 1: Shared types** — define at the top of `OdinChat.tsx` (Task 6) and import where needed, OR duplicate the tiny `ChatTurn` shape. Use these exact shapes across files:
```ts
export interface ChatTurn {
role: "user" | "assistant";
content: string;
}
export interface ReviewInvoice {
uid: string;
supplier_name: string;
invoice_number: string;
amount: string;
currency: string;
vat_rate: string;
issue_date: string;
due_date: string;
description: string;
file_name: string;
file: File;
}
export type EditableField =
| "supplier_name"
| "invoice_number"
| "amount"
| "currency"
| "vat_rate"
| "issue_date"
| "due_date"
| "description";
export interface StagedFile {
id: string;
file: File;
}
```
Put these in a new `src/admin/components/odin/types.ts` and import from there in every odin file.
- [ ] **Step 2: `OdinTabs.tsx`** — props and behavior:
```tsx
interface OdinTabsProps {
conversations: { id: number; title: string }[];
activeId: number | null;
busy: boolean;
onSelect: (id: number) => void;
onNew: () => void;
onRename: (id: number, title: string) => void;
onDelete: (id: number) => void;
}
```
Render a horizontally-scrollable row (`Box` with `overflowX: "auto"`, `display: flex`, `gap`). Each conversation is a clickable pill (`Button` size small; active = `contained`, else `outlined color="inherit"`). After the pills, a `+` `Button` calls `onNew`. The **active** pill shows a small `⋮` `IconButton` opening an `@mui/material` `Menu` with "Přejmenovat" and "Smazat". "Přejmenovat" opens the kit `Modal` containing a `TextField` (prefilled with current title) → on submit calls `onRename`. "Smazat" opens the kit `ConfirmDialog` → on confirm calls `onDelete`. All actions disabled while `busy`.
- [ ] **Step 3: `OdinThread.tsx`** — props:
```tsx
interface OdinThreadProps {
turns: ChatTurn[];
busy: boolean;
loading: boolean;
threadRef: React.RefObject<HTMLDivElement>;
}
```
Render the scrolling message area (`flex: 1, minHeight: 0, overflowY: "auto"`). Assistant turns left with a small circular Odin avatar (`Box` 28px, `borderRadius: "50%"`, `bgcolor: "primary.main"`, white "O"); user turns right-aligned `primary.main` bubble. **Message colour MUST be on the `Typography`** (`color: user ? "common.white" : "text.primary"`) — GlobalStyles pins `p` to text.secondary. Empty state (no turns, not busy, not loading): centered Odin avatar + "Dobrý den, jsem Odin. Zeptejte se, nebo přiložte fakturu (PDF) k importu." When `loading`: "Načítám…". When `busy`: a `CircularProgress size={14}` + "Pracuji…" row.
- [ ] **Step 4: `InvoiceReviewCard.tsx`** — props:
```tsx
interface InvoiceReviewCardProps {
inv: ReviewInvoice;
busy: boolean;
onChange: (uid: string, field: EditableField, value: string) => void;
onSave: (inv: ReviewInvoice) => void;
onDiscard: (uid: string) => void;
}
```
Port the card body from `DashAssistant.tsx` verbatim (the `Chip "Faktura"` + filename header, the 2-col grid of `TextField`s including **"Částka s DPH"**, "Datum splatnosti", "Popis", and the Uložit / Zahodit buttons). Replace `patch(...)``onChange(...)`, `saveInvoice``onSave`, the discard filter→`onDiscard(inv.uid)`.
- [ ] **Step 5: `OdinComposer.tsx`** — props:
```tsx
interface OdinComposerProps {
input: string;
attachments: StagedFile[];
busy: boolean;
canSubmit: boolean;
fileRef: React.RefObject<HTMLInputElement>;
onInput: (v: string) => void;
onFiles: (files: FileList | null) => void;
onRemoveAttachment: (id: string) => void;
onSubmit: () => void;
}
```
Port the staged-attachment chips + the composer row (hidden file `input`, "Přiložit" button, `TextField` with Enter-to-submit, "Odeslat" button) from `DashAssistant.tsx`. Disable per `busy` / `!canSubmit`.
- [ ] **Step 6: Gate**
Run: `npx tsc -p tsconfig.app.json --noEmit` — expect exit 0 (these compile independently of the orchestrator). If a component is unused at this point, that is fine — Task 6 wires them.
- [ ] **Step 7: Commit**
```bash
git add src/admin/components/odin
git commit -m "feat(odin): tabs, thread, review-card, composer components"
```
---
## Task 6: OdinChat orchestrator + page + delete DashAssistant
**Files:**
- Create: `src/admin/components/odin/OdinChat.tsx`
- Modify: `src/admin/pages/Odin.tsx`
- Modify: `src/admin/lib/queries/ai.ts` (remove `aiHistoryOptions`)
- Delete: `src/admin/components/dashboard/DashAssistant.tsx`
- [ ] **Step 1: Write `OdinChat.tsx`.** It owns all state + queries + the ported submit/extract/save logic, scoped to the active conversation. Port the helper fns (`summaryNote`, `nextUid`, `plural`, `MODEL_CONTEXT`, `MAX_STORE`) and the **submit / saveInvoice / onFiles / persist** logic from `DashAssistant.tsx` with these adaptations:
- **Queries:** `usage` (unchanged), `aiConversationsOptions()`, and `aiConversationMessagesOptions(activeId)` (enabled when `activeId != null`).
- **State:** `activeId: number | null`, plus `input`, `busy`, `turns`, `review`, `attachments`, `fileRef`, `threadRef`.
- **Ensure a conversation exists:** when the conversations query resolves: if empty, `POST /conversations` to create a default and `setActiveId(new.id)` + invalidate `["ai","conversations"]`; else if `activeId == null`, `setActiveId(list[0].id)`.
- **Seed per conversation:** a `seededId = useRef<number|null>(null)`. Effect keyed on `[activeId, messagesData]`: when `messagesData` for the active id arrives and `seededId.current !== activeId`, set `seededId.current = activeId`, `setTurns(messagesData.messages.map(m => ({role:m.role, content:m.content})))`, `setReview([])`.
- **Switch tab (`onSelect`):** `setActiveId(id); setTurns([]); setReview([]); seededId.current = null;` (force re-seed; the messages query for the new id loads and seeds).
- **`persist(msgs)`** posts to `/api/admin/ai/conversations/${activeId}/messages` (was `/history`); best-effort + `console.error` on failure.
- **`submit`:** identical to `DashAssistant.submit` EXCEPT it first ensures `activeId` (if null, await-create one and use it); marks `seededId.current = activeId`; on success persists via the conversation endpoint; on error rolls back + keeps input/attachments. Gate `canSubmit` on `!conversationsPending && activeId != null && !busy && (input.trim() || attachments.length)`.
- **`onNew`:** `POST /conversations` → select it (`setActiveId`, clear turns/review, `seededId.current=null`) + invalidate `["ai","conversations"]`.
- **`onRename(id, title)`:** `PATCH /conversations/:id` → invalidate `["ai","conversations"]`.
- **`onDelete(id)`:** `DELETE /conversations/:id` → invalidate `["ai","conversations"]`; if `id === activeId`, pick another conversation from the (refetched) list or null.
- **Layout:** a full-height shell — `Box sx={{ height: "calc(100dvh - 140px)", display: "flex", flexDirection: "column" }}` containing: header (`Odin` + budget `Utraceno: $x / $y`), `<OdinTabs … />`, `<OdinThread … />` (flex 1), the review list (`review.map(inv => <InvoiceReviewCard … />)` in a bounded `maxHeight: "35vh", overflowY: "auto"` box), and `<OdinComposer … />`.
- **Self-hide:** keep `if (usage && usage.configured === false) return null;`.
Reference the exact bodies of `submit`, `saveInvoice`, `onFiles`, `summaryNote`, `nextUid` in the current `DashAssistant.tsx` (lines ~52333) — copy them, applying only the adaptations above.
- [ ] **Step 2: Update `src/admin/pages/Odin.tsx`** — swap the import and render:
```tsx
import OdinChat from "../components/odin/OdinChat";
// …
<Box sx={{ maxWidth: 1100, mx: "auto" }}>
<OdinChat />
</Box>;
```
- [ ] **Step 3: Delete `src/admin/components/dashboard/DashAssistant.tsx`** and remove the now-orphaned `aiHistoryOptions` from `src/admin/lib/queries/ai.ts` (DashAssistant was its only consumer).
```bash
git rm src/admin/components/dashboard/DashAssistant.tsx
```
- [ ] **Step 4: Gate**
Run: `npx tsc -b --noEmit` — expect exit 0. Run: `npm run build` — expect success. Run: `npx vitest run` — expect the full suite green.
- [ ] **Step 5: Commit**
```bash
git add src/admin/components/odin/OdinChat.tsx src/admin/pages/Odin.tsx src/admin/lib/queries/ai.ts
git commit -m "feat(odin): OdinChat orchestrator; render on /odin; remove DashAssistant"
```
---
## Final verification (controller)
- `npx tsc -b --noEmit` = 0, `npm run build` = success, `npx vitest run` = all green.
- Manual (user/controller): create a conversation, send a chat, attach a PDF → review → save, rename a tab, delete a tab, reload (history persists per conversation), switch tabs (each keeps its own thread).
- Adversarial review pass (workflow) before merge/release.

View File

@@ -0,0 +1,190 @@
# Design — AI assistant, Phase 1 (chat + invoice import + budget cap)
**Date:** 2026-06-08
**Status:** Approved (brainstorming) — ready for implementation plan
**Phase 1 of 2.** Phase 2 (the AI querying system data via read-tools) is a separate later cycle — see "Deferred: Phase 2" at the end.
---
## Goal
Add the app's first AI capability: an **admin-only chat assistant embedded on the
dashboard** where you can talk to Claude and, crucially, **attach received-invoice
PDFs that the AI reads and imports into Přijaté faktury** (extract → you confirm →
save). All AI usage is bounded by an **admin-editable monthly budget (default
$50)** that hard-stops calls when exhausted.
## Decisions (locked in brainstorming)
- **Scope (Phase 1):** chat + invoice import + budget cap. **No system-data
access** (the AI cannot query your invoices/projects/attendance — that's Phase 2).
- **Placement:** a `DashAssistant` widget on the **dashboard, at the top under the
welcome text** — not a separate page, not a floating bubble.
- **Access:** **admins only**, via a new `ai.use` permission.
- **Model:** **Claude Sonnet 4.6** (strong vision, low cost).
- **Save flow:** extract → **you confirm/edit → save** (never silent auto-save).
- **Budget:** **$50/month**, resets each calendar month, **admin-editable in
Settings**; AI calls are **blocked** once the month's spend reaches the budget.
- **Chat:** **non-streaming** (request → full reply) and **in-browser history
only** (not persisted server-side) for v1 — both are easy later upgrades.
## Non-goals / out of scope (Phase 1)
- No system-data query tools / function-calling (Phase 2).
- No server-side conversation persistence, no streaming.
- No new invoice storage path — reuses `POST /received-invoices` verbatim.
---
## Architecture
Greenfield AI integration; the rest of the app is unaffected and works unchanged
if `ANTHROPIC_API_KEY` is absent (the assistant widget simply doesn't render and
the AI routes return a clear "not configured" error).
- **Dependency:** `@anthropic-ai/sdk`.
- **Env:** `ANTHROPIC_API_KEY` (required for the feature). Optional
`AI_MONTHLY_BUDGET_USD` default seed (the live value lives in the DB, below).
- **`src/services/ai.service.ts`** — wraps the SDK, owns the model choice + system
prompt + cost accounting. Two operations:
- `chat(messages)``client.messages.create({ model: "claude-sonnet-4-6", … })`,
non-streaming, returns `{ reply: string, usage }`.
- `extractInvoice(pdfBuffer, fileName)``client.messages.create` with the PDF as
a `document` content block + `output_config.format` JSON-schema for the
received-invoice fields, returns `{ fields, usage }`.
- Both call the spend tracker to record usage **and** are gated by the budget
guard (below) BEFORE the API call.
- Isolated so tests can stub the Anthropic call (no real API in CI).
## Spend cap (the $50/month budget)
- **New table `ai_usage`** (migration): `id`, `user_id?`, `kind` ("chat" |
"extract"), `model`, `input_tokens`, `output_tokens`, `cost_usd`
`@db.Decimal(10,6)`, `created_at @db.Timestamp(0)`, with an index on
`created_at`.
- **Cost map** (in `ai.service.ts`): model → `{ inputPerToken, outputPerToken }`.
Sonnet 4.6 = $3 / $15 per 1M → `0.000003` / `0.000015` per token. `cost_usd =
in*inP + out*outP`.
- **Budget value:** a new `ai_monthly_budget_usd Decimal @default(50)` column on
`company_settings` (the existing app-config singleton). Admin-editable in
Settings.
- **Budget guard `assertBudgetAvailable()`:** sum `cost_usd` for rows where
`created_at >= startOfMonth(now)`; if `>= ai_monthly_budget_usd`, return
`{ error: "Měsíční rozpočet AI byl vyčerpán", status: 402 }`. Called at the top
of every AI route BEFORE the Claude call.
- **Usage read:** `GET /api/admin/ai/usage` → `{ month_spend_usd, budget_usd,
remaining_usd }` for the chat's budget indicator and the Settings page.
## Backend routes — `src/routes/admin/ai.ts`
All guarded by `requirePermission("ai.use")`.
- `POST /api/admin/ai/chat` — body `{ messages: {role, content}[] }`. Budget guard →
`ai.service.chat` → log usage → `success(reply: string, remaining_usd)`.
- `POST /api/admin/ai/extract-invoices` — multipart PDF files (≤ `MAX_UPLOAD_SIZE`,
PDF/image only). Budget guard → `extractInvoice` per file → returns the extracted
fields per file (NOT saved) + usage. The files are **not** persisted here.
- `GET /api/admin/ai/usage` — current-month spend + budget + remaining.
If `ANTHROPIC_API_KEY` is unset, the POST routes return
`{ error: "AI není nakonfigurováno", status: 503 }`.
## Invoice import flow (extract → confirm → save)
1. Admin attaches one or more invoice PDFs in the dashboard chat (optionally with a
text note).
2. Frontend posts the files to `POST /ai/extract-invoices`; the AI returns the
extracted fields for each.
3. The chat renders an **editable review card per invoice** (dodavatel, číslo
faktury, částka, měna, sazba DPH, datum vystavení/splatnosti, poznámka),
pre-filled with the AI's values, plus a duplicate hint if `invoice_number` +
`supplier_name` already exists.
4. Admin glances/edits → **"Uložit"** (per card) or **"Uložit vše"**.
5. The frontend submits **the original File + the confirmed metadata** to the
**existing `POST /api/admin/received-invoices`** (multipart) — same NAS storage,
same server-side VAT recompute, same audit. The AI never writes invoices
directly. (The PDF is uploaded twice — once to extract, once to save — which is
fine for invoice-sized files and avoids any server-side temp-file handling.)
## Frontend
- **`src/admin/components/dashboard/DashAssistant.tsx`** — the chat widget:
message list, input box, attach-file button, and a small budget indicator
("Rozpočet: $X.XX / $50"). Non-streaming; conversation in component state only.
Renders the invoice review cards inline (reusing the received-invoice field
inputs / kit components).
- **`src/admin/pages/Dashboard.tsx`** — render `<DashAssistant />` at the top,
directly under the welcome text, **only when** the user is admin / has `ai.use`
(and only when AI is configured — a `GET /ai/usage` 503 hides it gracefully).
- **`src/admin/lib/queries/ai.ts`** — React Query options/mutations for chat,
extract, and usage. On a successful invoice save, invalidate `["received-invoices"]`.
- **Settings** — an admin field to set the monthly budget (writes
`company_settings.ai_monthly_budget_usd`).
## Permissions & migration
One Prisma migration:
- Create `ai_usage` table.
- Add `ai_monthly_budget_usd` to `company_settings` (default 50).
- Insert the `ai.use` permission and grant it to the **admin** role (explicit
`INSERT`s in `migration.sql`, per the project's migration policy).
(The admin role bypasses permission checks via `roleName === "admin"`, but the
explicit `ai.use` permission lets the access be widened later without code changes
and documents intent.)
## Security / privacy
- **Phase 1 has no tools**, so the AI cannot take actions on your data — its only
effect is the human-confirmed invoice save. A malicious/auto-generated invoice
PDF therefore can't trigger anything (the injection-to-action surface arrives in
Phase 2 and is designed there).
- Attached PDFs are sent to the Anthropic API to be read. The API key lives in
`.env` (server-side only), never exposed to the browser.
- Standard sanitization already applies on the received-invoice render/PDF paths;
AI-extracted text flows through the same validated `received_invoices` create.
## Testing
Server-side, real test DB, **Anthropic call stubbed** (no real API in CI):
- **Spend tracker:** `cost_usd` computed correctly from tokens for Sonnet 4.6;
monthly sum only counts the current month.
- **Budget guard:** under budget → allowed; at/over budget → `402` with the Czech
message; the guard reads the DB budget value.
- **Permissions:** all `/ai/*` routes return `403` without `ai.use`.
- **Not-configured:** with no `ANTHROPIC_API_KEY`, POST routes return `503`.
- **extract field-mapping:** given a stubbed AI response, the route returns the
expected `received_invoices` field shape (and computes nothing that the existing
create doesn't already).
Frontend has no component-test harness → gated by `tsc -b` + `build` + a manual
check (the dashboard widget renders for admins, hidden otherwise).
Gates: `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`.
## Rollout
Ships as **v2.1.0** (notable new capability) via the standard process. **Requires a
migration**, so the dev server must be stopped for `prisma migrate dev` (ask first),
and the release runs `prisma migrate deploy` on prod. `ANTHROPIC_API_KEY` must be
set in the production `.env` before the feature works.
---
## Deferred: Phase 2 (system-data access) — captured
A later, separate spec + cycle. The AI gains **read-only tools** (function calling)
to answer questions about your data — e.g. "co je po splatnosti?", "kolik jsme
fakturovali v květnu?". Key design work for Phase 2:
- A curated set of **read tools** (search invoices, overdue list, project lookup,
attendance summary, …), each **scoped to the calling user's permissions** so the
AI never returns data the user can't see.
- The **agentic tool-loop** (Claude requests a tool → app executes against Prisma →
returns results → Claude continues), with a per-conversation tool-call cap to
bound cost (within the same monthly budget).
- **Prompt-injection hardening:** because the AI will both read untrusted invoice
content _and_ hold tools, tools stay **read-only**, results are treated as data,
and any state-changing action remains human-confirmed.

View File

@@ -0,0 +1,188 @@
# Design — Bulk plan creation (Feature B)
**Date:** 2026-06-08
**Status:** Approved (brainstorming) — ready for implementation plan
**Builds on:** Feature A (multi-record plan cells, max 3 per cell), shipped in v2.0.5. Spec: `docs/superpowers/specs/2026-06-08-multi-record-plan-cells-design.md`.
---
## Goal
Let a planner assign one project/category to **many employees over a date range
in a single action**, instead of creating each person's plan record one by one.
A "Hromadné přiřazení" button on **/plan-work** opens a modal that mirrors the
existing single-record create form, plus an employee checklist and an "include
weekends" toggle.
## Decisions (locked in brainstorming)
- **Modal mirrors single-create** (`Datum od` + "Více dní" → `Datum do`, Projekt,
Kategorie, Text poznámky) **plus** a multi-select employee checklist and a
**"Zahrnout víkendy"** checkbox.
- **Storage = range entries** (`work_plan_entries`), one per contiguous run of
eligible days per employee — the same row shape the single-create form produces.
- **Weekends:** default off (MonFri only). Only Sat/Sun are excluded — **no
separate holiday handling**.
- **Cap:** governed by Feature A's `MAX_RECORDS_PER_CELL = 3`. A day already at
the cap for an employee is **skipped** (never overwritten), which also splits
that employee's range around the skipped day.
- **Past dates blocked** (no `force` exposed in the bulk UI).
- **Category** picker defaults to **Práce**; **Project** is optional ("bez
projektu"); **note** optional, applied to all created entries.
## Non-goals / out of scope
- No DB migration (reuses `work_plan_entries` and Feature A's cap logic).
- No overwrite/replace of existing records (purely additive under the cap).
- No holiday/`svátky` exclusion (only weekends).
- No bulk creation of **overrides** — bulk always creates **entries** (the normal
layer); single-day exceptions remain the per-cell day-panel's job.
---
## Storage & weekend behaviour
For each selected employee, the service computes the **eligible days** in
`[date_from, date_to]` and groups **contiguous** eligible days into range
entries.
A day `D` is **eligible** for employee `U` when all hold:
1. `D` is within `[date_from, date_to]` (inclusive).
2. `include_weekends` is true, **or** `D` is a weekday (MonFri).
3. `U` has fewer than `MAX_RECORDS_PER_CELL` active entries covering `D` (under
the cap).
Contiguous runs of eligible days become one range entry each
(`date_from = run start`, `date_to = run end`). Consequences:
- **Víkendy ON, no cap conflicts:** one continuous range per employee — identical
to creating a single multi-day record for everyone.
- **Víkendy OFF:** one range per work-week (MonFri chunks), because a weekend day
breaks the run.
- **A cap-full day** breaks the run too, so the range splits around it (and that
`(employee, day)` is counted as skipped).
In the grid these are ordinary range entries — they show the "součást rozsahu"
badge and open the range-vs-this-day chooser on click, exactly like
manually-created ranges.
---
## Backend
### Route — `POST /api/admin/plan/entries/bulk`
- Guard: `requirePermission("attendance.manage")` (same as single entry create).
- Body (validated by a new Zod schema `BulkPlanEntrySchema` in
`src/schemas/plan.schema.ts`):
```
{
user_ids: number[] // ≥1
date_from: string // YYYY-MM-DD
date_to: string // YYYY-MM-DD (≥ date_from)
include_weekends: boolean
project_id?: number | null
category: string // default applied client-side; validated server-side
note?: string // default ""
}
```
- On success: one **summary audit** row (`logAudit`, action `create`, entityType
`work_plan_entry`, description e.g. `Hromadné přiřazení: <kategorie> <projekt> —
N zaměstnanců, <from><to> (<created_days> dní)`), then `success(reply,
summary, 201, "Hromadné přiřazení dokončeno")`.
### Service — `bulkCreateEntries(input, actorUserId)` in `src/services/plan.service.ts`
Up-front validation (fail fast, nothing created):
- `user_ids.length >= 1` (else `{ error, status: 400 }`).
- `date_to >= date_from` (else 400).
- `assertNotPastDate(date_from, false)` and `assertNotPastDate(date_to, false)`
(bulk blocks past dates; 403).
- `assertActiveCategory(category)` (400 if inactive/unknown).
Then, per employee:
- Load the employee's active entries overlapping `[date_from, date_to]` once;
compute per-day coverage counts.
- Walk the days, mark eligible ones (weekday filter + under-cap), group contiguous
runs.
- For each run, create the range by **reusing `createEntry`**
(`{ user_id, date_from: runStart, date_to: runEnd, project_id, category, note }`,
`actorUserId`, `force: false`). Reusing `createEntry` keeps cap / past-date /
category validation DRY; its cap re-check passes because every day in the run is
already under the cap. A `createEntry` that nonetheless returns `{ error }` (rare
race) is counted as skipped, not fatal.
Aggregate and return:
```
{
created_entries: number // range rows created
created_days: number // (employee, day) records created
skipped_days: number // weekday-eligible (employee, day) slots skipped at the cap
users: number // employees processed
}
```
`skipped_days` counts only days that passed the weekday filter but were at the
cap — weekend days (when excluded) are out of scope, not "skipped".
Best-effort across employees/segments (no cross-entry transaction): up-front
validation already rejects bad input, and the cap-skip is by design. Partial
results are reported in the summary.
---
## Frontend
### Modal — `src/admin/components/BulkPlanModal.tsx`
Mirrors the single-create `EditForm` fields + bulk-attendance's employee picker
(`BulkAttendanceModal.tsx` is the pattern to follow):
- `Datum od` (DateField) + "Více dní" CheckboxField → `Datum do` (DateField).
- **Zaměstnanci** — scrollable `CheckboxField` list (source: the plan users
already loaded for the grid, `/plan/users`), with a "Vybrat vše" / "Odznačit
vše" toggle and a "Vybráno X z Y" caption; submit disabled when none selected.
- **Zahrnout víkendy** CheckboxField (default off).
- **Projekt** Select (optional — "— bez projektu —"), **Kategorie** Select
(active categories, default `work`/Práce), **Text poznámky** TextField (optional).
- A short helper line, e.g. _"Vytvoří záznamy pro vybrané dny u zvolených
zaměstnanců. Dny nad limit 3 záznamů se přeskočí."_
### Wiring — `src/admin/pages/PlanWork.tsx`
- A "Hromadné přiřazení" Button in the toolbar (next to "Správa kategorií"),
rendered only when `canEdit` (`attendance.manage`).
- A `bulkCreate` mutation (React Query) → `POST /api/admin/plan/entries/bulk`;
on success show an alert summarising the returned counts (e.g. _"Vytvořeno 18
záznamů pro 5 zaměstnanců; 4 dny přeskočeny (limit 3 na den)."_), close the
modal, and `invalidate: ["plan"]` so the grid refreshes.
---
## Testing (`src/__tests__/plan.test.ts` or a new `bulkPlan.test.ts`)
Backend service tests against the real test DB:
- **Weekday filter:** weekends-off over a MonSun span creates only MonFri days
(and as the expected number of per-work-week ranges); weekends-on creates one
continuous range.
- **Segmentation:** a cap-full day in the middle splits the range into two; the
skipped day is counted in `skipped_days`.
- **Cap skip:** an employee already at 3 entries on some days gets those days
skipped; the summary reflects `created_days` vs `skipped_days`.
- **Multi-employee aggregation:** `users`, `created_entries`, `created_days` sum
correctly across the selected employees.
- **Validation:** empty `user_ids` → 400; past `date_from` → 403; inactive
category → 400; `date_to < date_from` → 400.
Gates: `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`.
## Rollout
Ships as **v2.0.6** via the standard process (commit → tag → Gitea → tarball →
prod deploy → health check). No migration step. The grid refreshes via
`["plan"]` invalidation.

View File

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

View File

@@ -0,0 +1,218 @@
# Odin — Multi-Conversation AI Chat — Design
**Date:** 2026-06-08
**Status:** Approved (design), pending spec review
## Goal
Replace the single-thread Odin assistant with a multi-conversation chat: a
purpose-built UI on the `/odin` page where the user keeps several named
conversations (like topics), switches between them via top tabs, and can
rename or delete them. All existing assistant capabilities (chat, PDF invoice
extraction → review → save, monthly budget) carry over unchanged.
## Background (current state)
- `ai_chat_messages` is a single rolling thread per user (`user_id, role,
content, created_at`). Endpoints `GET/POST/DELETE /api/admin/ai/history`
read/append/clear that one thread.
- The chat lives in `DashAssistant.tsx`, rendered on the `/odin` page (moved
off the dashboard in the prior change, branch `feat/odin-page`).
- Stateless AI endpoints (`/chat`, `/extract-invoices`, `/usage`, `/budget`)
are unaffected by conversations — they don't persist anything themselves.
## Decisions (from brainstorming)
- **Titling:** new conversation auto-titles from its first user message; user
can rename.
- **Per-conversation actions:** rename + delete.
- **Existing history:** migrate the current single thread into one conversation
per user ("keep as first conversation"); nothing is lost.
- **Layout:** top tabs + chat (not a left sidebar).
## Data model
### `ai_conversations` (new)
| column | type | notes |
| ---------- | --------------------- | ----------------------------------- |
| id | INT PK AUTO_INCREMENT | |
| user_id | INT NOT NULL | owner; isolation key |
| title | VARCHAR(255) NOT NULL | default "Nová konverzace" |
| created_at | TIMESTAMP(0) NOT NULL | default CURRENT_TIMESTAMP |
| updated_at | TIMESTAMP(0) NOT NULL | bumped on each append; sort/recency |
Index: `idx_ai_conv_user (user_id, id)`.
### `ai_chat_messages` (modified)
- Add `conversation_id INT NOT NULL` (FK → `ai_conversations(id)` `ON DELETE
CASCADE`). Keep `user_id` (denormalized, harmless; simplifies cleanup).
- Replace index `idx_ai_chat_user (user_id, id)` with
`idx_ai_chat_conv (conversation_id, id)` (messages are read per conversation).
### Prisma
```prisma
model ai_conversations {
id Int @id @default(autoincrement())
user_id Int
title String @db.VarChar(255)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @updatedAt @db.Timestamp(0)
messages ai_chat_messages[]
@@index([user_id, id], map: "idx_ai_conv_user")
}
model ai_chat_messages {
id Int @id @default(autoincrement())
user_id Int
conversation_id Int
role String @db.VarChar(20)
content String @db.Text
created_at DateTime @default(now()) @db.Timestamp(0)
conversation ai_conversations @relation(fields: [conversation_id], references: [id], onDelete: Cascade)
@@index([conversation_id, id], map: "idx_ai_chat_conv")
}
```
### Migration (hand-written SQL; one tracked migration)
1. `CREATE TABLE ai_conversations (...)`.
2. `ALTER TABLE ai_chat_messages ADD COLUMN conversation_id INT NULL AFTER user_id`.
3. Backfill one conversation per user who has messages:
`INSERT INTO ai_conversations (user_id, title, created_at, updated_at)
SELECT user_id, 'Konverzace', NOW(), NOW() FROM ai_chat_messages GROUP BY user_id;`
4. Point messages at it:
`UPDATE ai_chat_messages m JOIN ai_conversations c ON c.user_id = m.user_id
SET m.conversation_id = c.id;`
5. Drop the old index, enforce NOT NULL, add the FK + new index:
`ALTER TABLE ai_chat_messages DROP INDEX idx_ai_chat_user,
MODIFY conversation_id INT NOT NULL,
ADD CONSTRAINT fk_ai_chat_conv FOREIGN KEY (conversation_id)
REFERENCES ai_conversations(id) ON DELETE CASCADE,
ADD INDEX idx_ai_chat_conv (conversation_id, id);`
The backfill is a no-op when `ai_chat_messages` is empty (prod today), and
preserves the dev thread.
## Service layer (`ai.service.ts`)
Replace the single-thread helpers (`getChatHistory` / `appendChatMessages` /
`clearChatHistory`) with conversation-scoped ones. Every function takes
`userId` and verifies the conversation belongs to the user.
- `listConversations(userId)` → `{id, title, updated_at}[]`, ordered by `id` asc
(stable tab order).
- `createConversation(userId, title?)` → the new conversation (default title
"Nová konverzace").
- `getConversation(userId, id)` → conversation or null (ownership check helper).
- `getConversationMessages(userId, id)` → `StoredChatMessage[]` oldest→newest,
or `{ error, status }` if not owned/found.
- `appendConversationMessages(userId, id, msgs)` → append; **bump `updated_at`**;
**auto-title**: if the conversation's title is still the default and this batch
has a user message, set `title` = first ~60 chars of that user message.
- `renameConversation(userId, id, title)` / `deleteConversation(userId, id)` —
ownership-checked; delete cascades messages.
Auto-title keeps titling server-side and robust (no client title logic).
## Routes (`routes/admin/ai.ts`, all `requirePermission("ai.use")`)
| Method | Path | Body / result |
| ------ | ----------------------------- | ------------------------------------------ |
| GET | `/conversations` | → `{ conversations: [...] }` |
| POST | `/conversations` | `{ title? }` → `{ conversation }` |
| GET | `/conversations/:id/messages` | → `{ messages: [...] }` (404 if not owned) |
| POST | `/conversations/:id/messages` | `{ messages:[{role,content}] }` (1..20) |
| PATCH | `/conversations/:id` | `{ title }` (1..255) |
| DELETE | `/conversations/:id` | → `{ ok: true }` |
`:id` parsed via `parseId`; bodies via `parseBody`; ownership 404 from the
service surfaced with `error(reply, ...)`. The old `/history` routes are removed.
`/chat`, `/extract-invoices`, `/usage`, `/budget` are unchanged.
## Frontend
### Queries (`lib/queries/ai.ts`)
- `aiConversationsOptions()` → `["ai","conversations"]`, `GET /conversations`.
- `aiConversationMessagesOptions(id)` → `["ai","conversation",id,"messages"]`,
`GET /conversations/:id/messages`, `gcTime: 0` (each mount re-reads the DB,
same rationale as today: no stale-cache resurrection).
- Types: `Conversation { id, title, updated_at }`, reuse `StoredChatMessage`.
### Components (`src/admin/components/odin/`)
- **`OdinChat.tsx`** — orchestrator. Owns: active conversation id, input, busy,
staged attachments, review list. Loads the conversation list; ensures one
exists (creates a default if the user has none); loads the active thread;
routes send/extract/save through the active conversation. Full-height flex
layout: header → tabs → thread (flex-grow, scroll) → review → composer.
- **`OdinTabs.tsx`** — horizontally-scrollable tabs (one per conversation) +
a "+" new-chat button + a ⋮ menu on the active tab (Přejmenovat / Smazat).
Rename uses a small Modal with a text field; delete uses ConfirmDialog.
- **`OdinThread.tsx`** — message list with an Odin avatar on assistant turns,
user turns right-aligned; the "Pracuji…" indicator; empty-state greeting.
(Message text colour set on the `Typography` — GlobalStyles pins `p` to
text.secondary.)
- **`InvoiceReviewCard.tsx`** — the editable extract card (supplier, number,
Částka s DPH, měna, sazba, dates, popis) + Uložit / Zahodit.
- **`OdinComposer.tsx`** — staged-attachment chips + attach button + message
field (Enter to send) + send button; disabled until the active thread loads.
`DashAssistant.tsx` is deleted; `pages/Odin.tsx` renders `OdinChat`.
### Data flow
1. Mount → load `aiConversationsOptions`. If empty, `POST /conversations` to
create a default and select it; else select the first (or last-active).
2. Selecting a tab sets the active id → `aiConversationMessagesOptions(id)`
loads that thread into the displayed turns (seed-once per id; submit marks
the thread live so a late load can't clobber — same guard as today).
3. **Send (chat):** optimistic user turn → `POST /chat` → append assistant
reply → `POST /conversations/:id/messages` persists both → bump usage. On
error: roll back, keep input.
4. **Send (attachments):** `POST /extract-invoices` → review cards →
client-side summary turn → persist the user+summary turns. Save a card →
`POST /received-invoices` (gross/VAT-inclusive, unchanged).
5. **New / rename / delete** → mutations that invalidate `["ai","conversations"]`
(and reset the active id appropriately on delete).
### Reuse
All proven logic carries over verbatim: staged-attach (no auto-send), the three
bug fixes (no clear-on-error, rollback dangling turn, stable ids — `nextUid`,
NOT `crypto.randomUUID`), the model-context trimming (last 20, leading-user),
budget indicator, gross/VAT save. The only structural change is "one thread" →
"active conversation thread", plus the tab/CRUD shell.
## Error handling
- Ownership: service returns `{ error: "Konverzace nenalezena", status: 404 }`
for a conversation the user doesn't own; routes surface it. No cross-user read
or write is possible (every query filters by `user_id`).
- Persistence is best-effort and logged (never swallowed), as today.
- Auto-create-default and create/rename/delete failures surface a Czech toast.
## Testing
Backend (Vitest, real DB):
- Conversation CRUD: create → list → rename → delete (cascade removes messages).
- **Isolation:** user A cannot read/append/rename/delete user B's conversation
(404), and `listConversations(A)` excludes B's.
- Append: ordering oldest→newest; `updated_at` bumps; **auto-title** sets the
title from the first user message and does not overwrite a renamed title.
- HTTP: routes 403 without `ai.use`; 404 for a foreign/:id; 400 on bad body.
Frontend: no component tests (consistent with the codebase); gated by
`tsc -b` + `npm run build`. Live verification by the user/controller.
## Out of scope (Phase 2+)
- Querying system data inside chat (the original deferred Phase-2 scope).
- Conversation search, pinning, folders, sharing.
- Streaming responses.

View File

@@ -0,0 +1,49 @@
# Odin → General Assistant (Phase 2+) — Forward-Looking Notes
**Date:** 2026-06-08 · **Status:** NOT scheduled — design notes only, recorded so Phase 1 choices don't box us in.
The vision: Odin grows from "chat + invoice import" into a **general assistant** that can **query system data** (invoices, projects, attendance, vehicles…) and **take actions** (create an order, mark paid, draft a quote…). This note assesses whether the Phase-1 architecture supports that, and what to carry forward deliberately.
## Bottom line
Phase 1 sets us up well; it does **not** box us in. Two things to carry forward on purpose:
1. **Structured message storage** (content blocks, not a plain string) — cheap to plan now, costly to retrofit later.
2. **The assistant acts strictly as the authenticated user** — every tool runs through the existing permission/ownership layer.
Everything else (conversations, budget/usage, thin services) is already pointing the right way.
## What Phase 1 already gets right
- **Conversations** — multi-turn, persisted, per-user, isolated. Exactly the context substrate an agent needs.
- **Budget + usage tracking + `ai.use` gate** — the cost/access spine. Tool loops spend more, so this matters _more_, not less.
- **Thin service layer** (`{ data } | { error, status }`, ownership-checked) — ideal to wrap as tools without rewriting business logic.
- **The extract → review → save flow** — a perfect template for "propose action → human confirms → execute." The `canSave`/`invoices.create` gate added in Phase 1 is the one-tool version of per-action authorization.
## The one schema thing to note now
`ai_chat_messages.content` is a **plain string**. Tool use requires persisting **content blocks** (`text` + `tool_use` + `tool_result`), because the model must see the full tool-call history to continue. When Phase 2 lands, store the **raw content-block array** (JSON column, e.g. `content_json`/`blocks`) and keep a derived plain-text for display/search. Don't change it now — just design Phase 2 persistence as "store the blocks," treating the current string as a lossy projection.
## The core shift (Phase 2)
1. **Tool use over the existing services.** Define tools (`list_invoices`, `get_project`, `create_order`, …) whose handlers call the **same service functions the routes use**. The SDK tool-runner loops; we execute. Reuses all validation/business logic and — critically — permissions.
2. **Authorization is the hard part.** Every tool MUST run **as the user**, through `requirePermission` / service ownership checks. The assistant must never do what the user can't. It is the user's _delegate_, not a privileged actor.
3. **Read vs write.** Read/query tools may run autonomously. Write/destructive tools **propose → confirm → execute** (generalize the invoice review card into a generic "action card"). Aligns with the assistant safety rules (confirm side-effecting actions).
4. **Audit.** Every action the assistant takes should `logAudit` like a manual action, attributed to the user with a marker (e.g. `via: "odin"`), for a real trail.
5. **Cost.** Tool loops are multi-round-trip → 310× the tokens of a chat turn. The $50 cap bites faster; consider per-conversation cost display and per-action budget re-checks (the inter-file budget re-check in `extract-invoices` is the pattern).
## Data access: tools-over-services, NOT RAG
Recommendation: **function-calling against the real services**, not embeddings/RAG. The data is structured, live, and permissioned — tools give correct, current, authorized answers. RAG over a snapshot would be stale, would leak across permission boundaries, and would duplicate logic. Reserve embeddings for genuinely unstructured document search if it ever comes up.
## Other forward notes
- **Model / effort:** a true agentic assistant wants a stronger model and possibly `effort` tuning; Phase-1 Sonnet single-shot is right for now.
- **Streaming:** multi-step tool use feels slow without it — add SSE when Phase 2 lands.
- **System prompt:** describe the user's role + available tools + the confirm-before-write rule.
- **Managed Agents vs self-hosted loop:** Anthropic's Managed Agents host the loop, but for a self-hosted business app with our own services + permissions, **Claude API + tool use with a self-hosted loop** is the better fit — authorization stays in our stack.
## What NOT to do prematurely
- Don't add a tool framework, embeddings, or streaming now — Phase 1 is plain chat + a fixed-prompt extractor, and that's the right scope.
- Don't widen `ai.use` to non-admins until the per-action authorization story (point 2) is in place.

View File

@@ -13,7 +13,7 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Urbanist:wght@300;400;500;600;700;800&display=swap"
href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;0,6..72,600;1,6..72,400;1,6..72,500&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Urbanist:wght@300;400;500;600;700;800&display=swap"
rel="stylesheet"
/>
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />

67
package-lock.json generated
View File

@@ -1,14 +1,15 @@
{
"name": "app-ts",
"version": "2.0.0",
"version": "2.0.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "app-ts",
"version": "2.0.0",
"version": "2.0.8",
"license": "ISC",
"dependencies": {
"@anthropic-ai/sdk": "^0.102.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
@@ -71,6 +72,27 @@
"vitest": "^4.1.0"
}
},
"node_modules/@anthropic-ai/sdk": {
"version": "0.102.0",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.102.0.tgz",
"integrity": "sha512-cThh3KcPW3lzkFyTz1cjyhJvOVw45NkLMoowO2ZJ/76CBz44ADUon+NsjEc/PypAkARs72Xu8qxTnx6PAOTQUQ==",
"license": "MIT",
"dependencies": {
"json-schema-to-ts": "^3.1.1",
"standardwebhooks": "^1.0.0"
},
"bin": {
"anthropic-ai-sdk": "bin/cli"
},
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
},
"peerDependenciesMeta": {
"zod": {
"optional": true
}
}
},
"node_modules/@asamuzakjp/css-color": {
"version": "5.1.11",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",
@@ -2249,6 +2271,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@stablelib/base64": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
"license": "MIT"
},
"node_modules/@standard-schema/spec": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
@@ -4073,6 +4101,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/fast-sha256": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
"license": "Unlicense"
},
"node_modules/fast-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
@@ -4801,6 +4835,19 @@
"dequal": "^2.0.3"
}
},
"node_modules/json-schema-to-ts": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.18.3",
"ts-algebra": "^2.0.0"
},
"engines": {
"node": ">=16"
}
},
"node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -6751,6 +6798,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/standardwebhooks": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz",
"integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==",
"license": "MIT",
"dependencies": {
"@stablelib/base64": "^1.0.0",
"fast-sha256": "^1.3.0"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@@ -7139,6 +7196,12 @@
"tree-kill": "cli.js"
}
},
"node_modules/ts-algebra": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
"license": "MIT"
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "app-ts",
"version": "2.0.0",
"version": "2.1.5",
"description": "",
"main": "dist/server.js",
"scripts": {
@@ -28,6 +28,7 @@
"license": "ISC",
"type": "commonjs",
"dependencies": {
"@anthropic-ai/sdk": "^0.102.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",

View File

@@ -0,0 +1,29 @@
-- AI assistant (Phase 1): usage-tracking table, monthly budget column, ai.use permission.
CREATE TABLE `ai_usage` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`user_id` INTEGER NULL,
`kind` VARCHAR(20) NOT NULL,
`model` VARCHAR(50) NOT NULL,
`input_tokens` INTEGER NOT NULL DEFAULT 0,
`output_tokens` INTEGER NOT NULL DEFAULT 0,
`cost_usd` DECIMAL(10, 6) NOT NULL DEFAULT 0,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`),
INDEX `idx_ai_usage_created` (`created_at`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `company_settings`
ADD COLUMN `ai_monthly_budget_usd` DECIMAL(10, 2) NULL DEFAULT 50.00;
-- ai.use permission + grant to admin (INSERT IGNORE → idempotent), mirroring
-- the warehouse-permissions migration.
INSERT IGNORE INTO `permissions` (`name`, `display_name`, `module`, `description`, `created_at`) VALUES
('ai.use', 'AI asistent', 'ai', 'Používat AI asistenta (chat a import faktur)', NOW());
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 = 'ai.use';

View File

@@ -0,0 +1,11 @@
-- AI assistant (Phase 1): per-user chat history (server-side, permanent).
CREATE TABLE `ai_chat_messages` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`user_id` INTEGER NOT NULL,
`role` VARCHAR(20) NOT NULL,
`content` TEXT NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`),
INDEX `idx_ai_chat_user` (`user_id`, `id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

View File

@@ -0,0 +1,32 @@
-- Multi-conversation Odin: conversations table + conversation_id on messages.
CREATE TABLE `ai_conversations` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`user_id` INTEGER NOT NULL,
`title` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`),
INDEX `idx_ai_conv_user` (`user_id`, `id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `ai_chat_messages`
ADD COLUMN `conversation_id` INTEGER NULL AFTER `user_id`;
-- Backfill: one conversation per user who has messages ("keep as first conversation").
INSERT INTO `ai_conversations` (`user_id`, `title`, `created_at`, `updated_at`)
SELECT `user_id`, 'Konverzace', NOW(), NOW()
FROM `ai_chat_messages`
GROUP BY `user_id`;
UPDATE `ai_chat_messages` m
JOIN `ai_conversations` c ON c.`user_id` = m.`user_id`
SET m.`conversation_id` = c.`id`;
-- Enforce: drop old per-user index, NOT NULL, FK (cascade), per-conversation index.
ALTER TABLE `ai_chat_messages`
DROP INDEX `idx_ai_chat_user`,
MODIFY `conversation_id` INTEGER NOT NULL,
ADD CONSTRAINT `fk_ai_chat_conv` FOREIGN KEY (`conversation_id`)
REFERENCES `ai_conversations`(`id`) ON DELETE CASCADE,
ADD INDEX `idx_ai_chat_conv` (`conversation_id`, `id`);

View File

@@ -76,6 +76,42 @@ model audit_logs {
@@fulltext([description], map: "idx_audit_search")
}
model ai_usage {
id Int @id @default(autoincrement())
user_id Int?
kind String @db.VarChar(20)
model String @db.VarChar(50)
input_tokens Int @default(0)
output_tokens Int @default(0)
cost_usd Decimal @default(0) @db.Decimal(10, 6)
created_at DateTime @default(now()) @db.Timestamp(0)
@@index([created_at], map: "idx_ai_usage_created")
}
model ai_conversations {
id Int @id @default(autoincrement())
user_id Int
title String @db.VarChar(255)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @updatedAt @db.Timestamp(0)
messages ai_chat_messages[]
@@index([user_id, id], map: "idx_ai_conv_user")
}
model ai_chat_messages {
id Int @id @default(autoincrement())
user_id Int
conversation_id Int
role String @db.VarChar(20)
content String @db.Text
created_at DateTime @default(now()) @db.Timestamp(0)
conversation ai_conversations @relation(fields: [conversation_id], references: [id], onDelete: Cascade)
@@index([conversation_id, id], map: "idx_ai_chat_conv")
}
model bank_accounts {
id Int @id @default(autoincrement())
account_name String? @db.VarChar(255)
@@ -134,6 +170,7 @@ model company_settings {
warehouse_issue_number_pattern String? @db.VarChar(100)
warehouse_inventory_prefix String? @db.VarChar(20)
warehouse_inventory_number_pattern String? @db.VarChar(100)
ai_monthly_budget_usd Decimal? @default(50.00) @db.Decimal(10, 2)
}
model customers {

448
src/__tests__/ai.test.ts Normal file
View File

@@ -0,0 +1,448 @@
import { describe, it, expect, beforeEach, beforeAll, afterAll } from "vitest";
import Fastify from "fastify";
import cookie from "@fastify/cookie";
import rateLimit from "@fastify/rate-limit";
import jwt from "jsonwebtoken";
import prisma from "../config/database";
import { config as appConfig } from "../config/env";
import { securityHeaders } from "../middleware/security";
import aiRoutes from "../routes/admin/ai";
import {
computeCostUsd,
recordUsage,
getMonthSpendUsd,
getBudgetUsd,
assertBudgetAvailable,
isConfigured,
listConversations,
createConversation,
getConversationMessages,
appendConversationMessages,
renameConversation,
deleteConversation,
} from "../services/ai.service";
const KIND = "test_ai"; // marker so we only clean our own rows
const CONV_UID_A = 999999991; // synthetic, FK-free owner ids
const CONV_UID_B = 999999992;
const HIST_MARKER = "「test-conv」"; // marks HTTP-test conversations on real users
beforeEach(async () => {
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
});
afterAll(async () => {
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
await prisma.ai_conversations.deleteMany({
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
});
await prisma.ai_conversations.deleteMany({
where: { title: { contains: HIST_MARKER } },
});
});
describe("ai.service cost + budget", () => {
it("computes Sonnet 4.6 cost from tokens", () => {
// 1,000,000 input @ $3 + 1,000,000 output @ $15 = $18
expect(
computeCostUsd("claude-sonnet-4-6", 1_000_000, 1_000_000),
).toBeCloseTo(18, 6);
expect(computeCostUsd("claude-sonnet-4-6", 4000, 500)).toBeCloseTo(
0.0195,
6,
);
});
it("records usage with the computed cost", async () => {
await recordUsage({
userId: null,
kind: KIND,
model: "claude-sonnet-4-6",
inputTokens: 4000,
outputTokens: 500,
});
const rows = await prisma.ai_usage.findMany({ where: { kind: KIND } });
expect(rows.length).toBe(1);
expect(Number(rows[0].cost_usd)).toBeCloseTo(0.0195, 6);
});
it("sums only the current month's spend", async () => {
await recordUsage({
userId: null,
kind: KIND,
model: "claude-sonnet-4-6",
inputTokens: 1_000_000,
outputTokens: 0,
}); // $3 this month
// An old row (last year) must NOT count.
await prisma.ai_usage.create({
data: {
kind: KIND,
model: "claude-sonnet-4-6",
input_tokens: 1_000_000,
output_tokens: 0,
cost_usd: 3,
created_at: new Date("2000-01-01T00:00:00Z"),
},
});
const spend = await getMonthSpendUsd();
expect(spend).toBeGreaterThanOrEqual(3);
expect(spend).toBeLessThan(6); // the year-2000 $3 is excluded
});
it("assertBudgetAvailable blocks at/over budget, allows under", async () => {
const budget = await getBudgetUsd();
// Under budget → null (allowed)
expect(await assertBudgetAvailable()).toBeNull();
// Push spend over budget for this month, then it must block with 402.
await prisma.ai_usage.create({
data: {
kind: KIND,
model: "claude-sonnet-4-6",
input_tokens: 0,
output_tokens: 0,
cost_usd: budget + 1,
created_at: new Date(),
},
});
const blocked = await assertBudgetAvailable();
expect(blocked).not.toBeNull();
expect(blocked?.status).toBe(402);
});
it("isConfigured reflects the API key presence", () => {
expect(typeof isConfigured()).toBe("boolean");
});
});
describe("ai.service conversations", () => {
beforeEach(async () => {
await prisma.ai_conversations.deleteMany({
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
});
});
// Narrow a service result to its error branch with a clear failure message.
const expectError = (
r: { error: string; status: number } | { data: unknown },
status: number,
) => {
if (!("error" in r))
throw new Error(`expected an error result, got ${JSON.stringify(r)}`);
expect(r.status).toBe(status);
};
it("creates, lists, appends (auto-title), and reads oldest→newest", async () => {
const conv = await createConversation(CONV_UID_A);
expect(conv.title).toBe("Nová konverzace");
await appendConversationMessages(CONV_UID_A, conv.id, [
{ role: "user", content: "Kolik je hodin v Praze?" },
{ role: "assistant", content: "Nevím, ale…" },
]);
const list = await listConversations(CONV_UID_A);
expect(list).toHaveLength(1);
expect(list[0].title).toBe("Kolik je hodin v Praze?"); // auto-titled
const msgs = await getConversationMessages(CONV_UID_A, conv.id);
if (!("data" in msgs)) throw new Error("expected messages, got an error");
expect(msgs.data.map((m) => m.content)).toEqual([
"Kolik je hodin v Praze?",
"Nevím, ale…",
]);
});
it("does not overwrite a renamed title on later appends", async () => {
const conv = await createConversation(CONV_UID_A);
await renameConversation(CONV_UID_A, conv.id, "Moje téma");
await appendConversationMessages(CONV_UID_A, conv.id, [
{ role: "user", content: "tohle by nemělo přepsat název" },
]);
const list = await listConversations(CONV_UID_A);
expect(list[0].title).toBe("Moje téma");
});
it("bumps updated_at on append", async () => {
const conv = await createConversation(CONV_UID_A);
// Force an old timestamp, then prove append refreshes it (TIMESTAMP(0) is
// second-precision, so compare against a year rather than ms deltas).
await prisma.ai_conversations.update({
where: { id: conv.id },
data: { updated_at: new Date("2000-01-01T00:00:00Z") },
});
await appendConversationMessages(CONV_UID_A, conv.id, [
{ role: "user", content: "ping" },
]);
const after = (await listConversations(CONV_UID_A))[0].updated_at;
expect(after.getFullYear()).toBeGreaterThan(2000);
});
it("isolates conversations per user (404 on every op across owners)", async () => {
const a = await createConversation(CONV_UID_A);
expect(await listConversations(CONV_UID_B)).toHaveLength(0);
expectError(await getConversationMessages(CONV_UID_B, a.id), 404);
expectError(
await appendConversationMessages(CONV_UID_B, a.id, [
{ role: "user", content: "x" },
]),
404,
);
expectError(await renameConversation(CONV_UID_B, a.id, "hack"), 404);
expectError(await deleteConversation(CONV_UID_B, a.id), 404);
});
it("cascade-deletes messages with the conversation", async () => {
const conv = await createConversation(CONV_UID_A);
await appendConversationMessages(CONV_UID_A, conv.id, [
{ role: "user", content: "x" },
]);
await deleteConversation(CONV_UID_A, conv.id);
const remaining = await prisma.ai_chat_messages.count({
where: { conversation_id: conv.id },
});
expect(remaining).toBe(0);
});
});
describe("HTTP /api/admin/ai", () => {
let app: Awaited<ReturnType<typeof buildAiApp>>;
let adminToken: string;
let noPermToken: string;
let noPermRoleId: number;
let noPermUserId: number;
let savedKey: string;
async function buildAiApp() {
const a = Fastify({ logger: false });
await a.register(cookie);
await a.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
a.addHook("onRequest", securityHeaders);
await a.register(aiRoutes, { prefix: "/api/admin/ai" });
return a;
}
function token(user: {
id: number;
username: string;
roleName: string | null;
}) {
return jwt.sign(
{ sub: user.id, username: user.username, role: user.roleName },
appConfig.jwt.secret,
{ expiresIn: "15m" },
);
}
beforeAll(async () => {
savedKey = appConfig.anthropic.apiKey;
app = await buildAiApp();
const admin = await prisma.users.findFirst({
where: { roles: { name: "admin" } },
include: { roles: true },
});
if (!admin) throw new Error("admin not found");
adminToken = token({
id: admin.id,
username: admin.username,
roleName: admin.roles?.name ?? null,
});
const stamp = Date.now();
const role = await prisma.roles.create({
data: { name: `noperm_ai_${stamp}`, display_name: "No Perm AI" },
});
noPermRoleId = role.id;
const u = await prisma.users.create({
data: {
username: `noperm_ai_${stamp}`,
first_name: "No",
last_name: "Perm",
email: `noperm_ai_${stamp}@test.local`,
password_hash:
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
role_id: role.id,
is_active: true,
},
});
noPermUserId = u.id;
noPermToken = token({
id: u.id,
username: u.username,
roleName: role.name,
});
});
afterAll(async () => {
if (app) await app.close();
(appConfig.anthropic as { apiKey: string }).apiKey = savedKey;
if (noPermUserId)
await prisma.users
.deleteMany({ where: { id: noPermUserId } })
.catch(() => {});
if (noPermRoleId)
await prisma.roles
.deleteMany({ where: { id: noPermRoleId } })
.catch(() => {});
});
it("GET /usage requires ai.use", async () => {
const res = await app.inject({
method: "GET",
url: "/api/admin/ai/usage",
headers: { Authorization: `Bearer ${noPermToken}` },
});
expect(res.statusCode).toBe(403);
});
it("GET /usage returns spend + budget for an admin", async () => {
const res = await app.inject({
method: "GET",
url: "/api/admin/ai/usage",
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(typeof body.data.budget_usd).toBe("number");
expect(typeof body.data.month_spend_usd).toBe("number");
});
it("POST /chat returns 503 when AI is not configured", async () => {
(appConfig.anthropic as { apiKey: string }).apiKey = "";
const res = await app.inject({
method: "POST",
url: "/api/admin/ai/chat",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { messages: [{ role: "user", content: "ahoj" }] },
});
expect(res.statusCode).toBe(503);
(appConfig.anthropic as { apiKey: string }).apiKey = savedKey;
});
it("GET /conversations requires ai.use", async () => {
const res = await app.inject({
method: "GET",
url: "/api/admin/ai/conversations",
headers: { Authorization: `Bearer ${noPermToken}` },
});
expect(res.statusCode).toBe(403);
});
it("conversation lifecycle over HTTP (create → append → list → rename → delete)", async () => {
const created = await app.inject({
method: "POST",
url: "/api/admin/ai/conversations",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { title: `${HIST_MARKER} t` },
});
expect(created.statusCode).toBe(200);
const id = created.json().data.conversation.id as number;
const appended = await app.inject({
method: "POST",
url: `/api/admin/ai/conversations/${id}/messages`,
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { messages: [{ role: "user", content: "ahoj" }] },
});
expect(appended.statusCode).toBe(200);
const msgs = await app.inject({
method: "GET",
url: `/api/admin/ai/conversations/${id}/messages`,
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(
msgs.json().data.messages.map((m: { content: string }) => m.content),
).toContain("ahoj");
const renamed = await app.inject({
method: "PATCH",
url: `/api/admin/ai/conversations/${id}`,
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { title: `${HIST_MARKER} renamed` },
});
expect(renamed.json().data.conversation.title).toBe(
`${HIST_MARKER} renamed`,
);
const del = await app.inject({
method: "DELETE",
url: `/api/admin/ai/conversations/${id}`,
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(del.statusCode).toBe(200);
});
it("GET messages of a non-existent conversation → 404", async () => {
const res = await app.inject({
method: "GET",
url: "/api/admin/ai/conversations/999999000/messages",
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(res.statusCode).toBe(404);
});
it("POST /conversations requires ai.use", async () => {
const res = await app.inject({
method: "POST",
url: "/api/admin/ai/conversations",
headers: {
Authorization: `Bearer ${noPermToken}`,
"Content-Type": "application/json",
},
payload: { title: "x" },
});
expect(res.statusCode).toBe(403);
});
it("GET /conversations lists the user's conversations", async () => {
const created = await app.inject({
method: "POST",
url: "/api/admin/ai/conversations",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { title: `${HIST_MARKER} listed` },
});
const id = created.json().data.conversation.id as number;
const list = await app.inject({
method: "GET",
url: "/api/admin/ai/conversations",
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(list.statusCode).toBe(200);
expect(
list.json().data.conversations.map((c: { id: number }) => c.id),
).toContain(id);
});
it("rejects an empty title (PATCH) and empty messages (POST) with 400", async () => {
const patch = await app.inject({
method: "PATCH",
url: "/api/admin/ai/conversations/999999000",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { title: "" },
});
expect(patch.statusCode).toBe(400);
const append = await app.inject({
method: "POST",
url: "/api/admin/ai/conversations/999999000/messages",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { messages: [] },
});
expect(append.statusCode).toBe(400);
});
});

View File

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

View File

@@ -20,6 +20,7 @@ import {
deleteOverride,
listEntries,
listOverrides,
bulkCreateEntries,
} from "../services/plan.service";
// ---------------------------------------------------------------------------
@@ -58,6 +59,20 @@ beforeEach(async () => {
await prisma.work_plan_overrides.deleteMany({
where: { note: { contains: N } },
});
// Also clean up empty-note rows on the specific test dates used by the
// "allows an empty note" tests. These rows are not caught by the prefix
// filter above, and would cause the per-cell cap check to reject them
// once three accumulate across runs.
await prisma.work_plan_entries.deleteMany({
where: {
date_from: {
in: [
new Date("2099-07-15T00:00:00.000Z"),
new Date("2097-08-05T00:00:00.000Z"),
],
},
},
});
});
afterAll(async () => {
@@ -75,10 +90,9 @@ afterAll(async () => {
// ---------------------------------------------------------------------------
describe("plan.service.resolveCell", () => {
it("returns null when nothing covers the date", async () => {
// No entry, no override for (adminUserId, "2099-01-01")
it("returns [] when nothing covers the date", async () => {
const result = await resolveCell(adminUserId, "2099-01-01");
expect(result).toBeNull();
expect(result).toEqual([]);
});
it("returns the entry that covers the date", async () => {
@@ -93,17 +107,14 @@ describe("plan.service.resolveCell", () => {
},
});
const result = await resolveCell(adminUserId, "2099-06-05");
expect(result).not.toBeNull();
expect(result?.source).toBe("entry");
expect(result?.note).toBe(`${N}PLC upgrade`);
expect(result?.category).toBe("work");
expect(result?.rangeFrom).toBe("2099-06-01");
expect(result?.rangeTo).toBe("2099-06-10");
expect(result.length).toBe(1);
expect(result[0].source).toBe("entry");
expect(result[0].note).toBe(`${N}PLC upgrade`);
expect(result[0].rangeFrom).toBe("2099-06-01");
expect(result[0].rangeTo).toBe("2099-06-10");
});
it("returns the override for that day, not the entry", async () => {
// An entry covers 2099-06-01..2099-06-10, but an override on 2099-06-05
// takes precedence.
it("returns overrides (entries hidden) when an override exists", async () => {
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
@@ -124,10 +135,51 @@ describe("plan.service.resolveCell", () => {
},
});
const result = await resolveCell(adminUserId, "2099-06-05");
expect(result).not.toBeNull();
expect(result?.source).toBe("override");
expect(result?.note).toBe(`${N}Volno po noční`);
expect(result?.category).toBe("leave");
expect(result.length).toBe(1);
expect(result[0].source).toBe("override");
expect(result[0].note).toBe(`${N}Volno po noční`);
});
it("returns multiple additive entries newest-first", async () => {
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-01"),
date_to: new Date("2099-06-10"),
category: "work",
note: `${N}first`,
created_by: adminUserId,
},
});
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-05"),
date_to: new Date("2099-06-05"),
category: "work",
note: `${N}second`,
created_by: adminUserId,
},
});
const result = await resolveCell(adminUserId, "2099-06-05");
expect(result.length).toBe(2);
expect(result[0].note).toBe(`${N}second`); // newest first
});
it("caps the returned records at MAX_RECORDS_PER_CELL", async () => {
for (let i = 0; i < 4; i++) {
await prisma.work_plan_overrides.create({
data: {
user_id: adminUserId,
shift_date: new Date("2099-06-06"),
category: "leave",
note: `${N}cap${i}`,
created_by: adminUserId,
},
});
}
const result = await resolveCell(adminUserId, "2099-06-06");
expect(result.length).toBe(3);
});
it("ignores soft-deleted entries and overrides", async () => {
@@ -143,7 +195,7 @@ describe("plan.service.resolveCell", () => {
},
});
const result = await resolveCell(adminUserId, "2099-06-05");
expect(result).toBeNull();
expect(result).toEqual([]);
});
});
@@ -164,11 +216,11 @@ describe("plan.service.resolveGrid", () => {
},
});
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-05");
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-04"]).toBeNull();
expect(cells[adminUserId]["2099-06-05"]).toBeNull();
expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-04"]).toEqual([]);
expect(cells[adminUserId]["2099-06-05"]).toEqual([]);
});
it("applies override on a covered day", async () => {
@@ -192,9 +244,78 @@ describe("plan.service.resolveGrid", () => {
},
});
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-03");
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}B`);
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}B`);
expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
});
it("stacks additive entries newest-first and caps the day at MAX_RECORDS_PER_CELL", async () => {
// Two entries cover 2099-06-12 → both appear, newest-first. A 3rd entry
// covering the same day and a 4th overlapping one push past the cap, so the
// day must still return exactly 3 (mirrors resolveCell's cap behaviour).
//
// created_at is @db.Timestamp(0) (second precision, MySQL TIMESTAMP range
// tops out at 2038), so rows created in the same second tie on the
// `created_at desc` sort. We set explicit, distinct in-range created_at
// values so the newest-first assertion is deterministic.
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-11"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g1`,
created_by: adminUserId,
created_at: new Date("2037-06-01T08:00:00.000Z"),
},
});
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-12"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g2`,
created_by: adminUserId,
created_at: new Date("2037-06-01T09:00:00.000Z"), // newer than g1
},
});
// Two-entry day: assert length 2 and newest-first ordering.
const twoDay = await resolveGrid([adminUserId], "2099-06-11", "2099-06-12");
expect(twoDay[adminUserId]["2099-06-12"].length).toBe(2);
expect(twoDay[adminUserId]["2099-06-12"][0].note).toBe(`${N}g2`); // newest first
// Day with no second entry stays single.
expect(twoDay[adminUserId]["2099-06-11"].length).toBe(1);
// Add a 3rd and a 4th overlapping entry on 2099-06-12 to exceed the cap.
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-12"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g3`,
created_by: adminUserId,
created_at: new Date("2037-06-01T10:00:00.000Z"),
},
});
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2099-06-12"),
date_to: new Date("2099-06-12"),
category: "work",
note: `${N}g4`,
created_by: adminUserId,
created_at: new Date("2037-06-01T11:00:00.000Z"),
},
});
const cappedDay = await resolveGrid(
[adminUserId],
"2099-06-12",
"2099-06-12",
);
expect(cappedDay[adminUserId]["2099-06-12"].length).toBe(3);
});
});
@@ -341,6 +462,36 @@ describe("plan.service.createEntry", () => {
expect("error" in result).toBe(true);
if ("error" in result) expect(result.status).toBe(403);
});
it("rejects a 4th entry covering a day already at the cap", async () => {
for (let i = 0; i < 3; i++) {
const r = await createEntry(
{
user_id: adminUserId,
date_from: "2099-07-20",
date_to: "2099-07-20",
category: "work",
note: `${N}e${i}`,
},
adminUserId,
false,
);
expect("data" in r).toBe(true);
}
const fourth = await createEntry(
{
user_id: adminUserId,
date_from: "2099-07-20",
date_to: "2099-07-20",
category: "work",
note: `${N}e3`,
},
adminUserId,
false,
);
expect("error" in fourth).toBe(true);
if ("error" in fourth) expect(fourth.status).toBe(400);
});
});
// ---------------------------------------------------------------------------
@@ -439,7 +590,7 @@ describe("plan.service.deleteEntry", () => {
// ---------------------------------------------------------------------------
describe("plan.service.createOverride", () => {
it("creates an override and returns { data, oldData: null, replacedData: null }", async () => {
it("creates an override and returns { data, oldData: null }", async () => {
const result = await createOverride(
{
user_id: adminUserId,
@@ -454,42 +605,45 @@ describe("plan.service.createOverride", () => {
if ("data" in result) {
expect(result.data.note).toBe(`${N}day off`);
expect(result.oldData).toBeNull();
expect(result.replacedData).toBeNull();
}
});
it("soft-deletes the existing override and reports it in replacedData", async () => {
await createOverride(
it("stacks additive overrides and caps at MAX_RECORDS_PER_CELL", async () => {
for (let i = 0; i < 3; i++) {
const r = await createOverride(
{
user_id: adminUserId,
shift_date: "2099-10-02",
category: "leave",
note: `${N}o${i}`,
},
adminUserId,
false,
);
expect("data" in r).toBe(true);
}
// A 4th record on the same day is rejected by the cap.
const fourth = await createOverride(
{
user_id: adminUserId,
shift_date: "2099-10-02",
category: "leave",
note: `${N}first`,
note: `${N}o3`,
},
adminUserId,
false,
);
const second = await createOverride(
{
expect("error" in fourth).toBe(true);
if ("error" in fourth) expect(fourth.status).toBe(400);
// All three earlier overrides remain active — no replace happened.
const active = await prisma.work_plan_overrides.findMany({
where: {
user_id: adminUserId,
shift_date: "2099-10-02",
category: "sick",
note: `${N}second`,
shift_date: new Date("2099-10-02"),
is_deleted: false,
},
adminUserId,
false,
);
expect("data" in second).toBe(true);
if ("data" in second) {
expect((second.replacedData as any)?.note).toBe(`${N}first`);
}
const all = await prisma.work_plan_overrides.findMany({
where: { user_id: adminUserId, shift_date: new Date("2099-10-02") },
});
// The first should be soft-deleted, the second active
expect(all.find((o) => o.note === `${N}first`)?.is_deleted).toBe(true);
expect(all.find((o) => o.note === `${N}second`)?.is_deleted).toBe(false);
expect(active.length).toBe(3);
});
it("rejects a past date without force", async () => {
@@ -635,6 +789,184 @@ describe("plan.service.listOverrides (employee scoping)", () => {
});
});
// ---------------------------------------------------------------------------
// bulkCreateEntries
// ---------------------------------------------------------------------------
describe("plan.service.bulkCreateEntries", () => {
it("creates one continuous range per employee when weekends are included", async () => {
// 2096-06-01 is a Friday; 2096-06-03 is a Sunday. include_weekends → one
// range 06-01..06-03 covering all 3 days.
const res = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-01",
date_to: "2096-06-03",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}bulk-wknd`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.created_entries).toBe(1);
expect(res.data.created_days).toBe(3);
expect(res.data.skipped_days).toBe(0);
expect(res.data.users).toBe(1);
});
it("splits into per-work-week ranges and skips weekends when excluded", async () => {
// 2096-06-01 (Fri) .. 2096-06-05 (Tue): Fri | Sat Sun excluded | Mon Tue.
// Two runs: [06-01] and [06-04..06-05] → 2 entries, 3 days, 0 skipped.
const res = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-01",
date_to: "2096-06-05",
include_weekends: false,
project_id: null,
category: "work",
note: `${N}bulk-week`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.created_entries).toBe(2);
expect(res.data.created_days).toBe(3);
expect(res.data.skipped_days).toBe(0);
});
it("skips days already at the cap and splits the range around them", async () => {
// Pre-fill 2096-07-02 to the cap (3 entries) for the user. A weekends-on
// bulk over 07-01..07-03 then creates 07-01 and 07-03 (two ranges), skips
// 07-02. 2096-07-01..03 are Sun/Mon/Tue — all included with weekends on.
for (let i = 0; i < 3; i++) {
await prisma.work_plan_entries.create({
data: {
user_id: adminUserId,
date_from: new Date("2096-07-02"),
date_to: new Date("2096-07-02"),
category: "work",
note: `${N}cap${i}`,
created_by: adminUserId,
},
});
}
const res = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-07-01",
date_to: "2096-07-03",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}bulk-cap`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.created_entries).toBe(2);
expect(res.data.created_days).toBe(2);
expect(res.data.skipped_days).toBe(1);
});
it("aggregates across multiple employees", async () => {
const res = await bulkCreateEntries(
{
user_ids: [adminUserId, noPermUserId],
date_from: "2096-08-03", // Friday
date_to: "2096-08-03",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}bulk-multi`,
},
adminUserId,
);
expect("data" in res).toBe(true);
if (!("data" in res)) return;
expect(res.data.users).toBe(2);
expect(res.data.created_entries).toBe(2);
expect(res.data.created_days).toBe(2);
});
it("rejects empty user_ids, past dates, bad range, and inactive category", async () => {
const empty = await bulkCreateEntries(
{
user_ids: [],
date_from: "2096-06-01",
date_to: "2096-06-01",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}x`,
},
adminUserId,
);
expect("error" in empty && empty.status).toBe(400);
const tooLong = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-01-01",
date_to: "2096-12-31", // > 92 days
include_weekends: true,
project_id: null,
category: "work",
note: `${N}x`,
},
adminUserId,
);
expect("error" in tooLong && tooLong.status).toBe(400);
const past = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2000-01-01",
date_to: "2000-01-02",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}x`,
},
adminUserId,
);
expect("error" in past && past.status).toBe(403);
const badRange = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-10",
date_to: "2096-06-01",
include_weekends: true,
project_id: null,
category: "work",
note: `${N}x`,
},
adminUserId,
);
expect("error" in badRange && badRange.status).toBe(400);
const badCat = await bulkCreateEntries(
{
user_ids: [adminUserId],
date_from: "2096-06-01",
date_to: "2096-06-01",
include_weekends: true,
project_id: null,
category: "__nope__",
note: `${N}x`,
},
adminUserId,
);
expect("error" in badCat && badCat.status).toBe(400);
});
});
// ---------------------------------------------------------------------------
// HTTP route tests (Fastify inject)
// ---------------------------------------------------------------------------
@@ -810,7 +1142,7 @@ describe("HTTP /api/admin/plan", () => {
const body = res.json();
expect(body.data.users).toBeDefined();
expect(body.data.cells[adminUserId]).toBeDefined();
expect(body.data.cells[adminUserId]["2097-06-01"].note).toBe(
expect(body.data.cells[adminUserId]["2097-06-01"][0].note).toBe(
`${N}grid test`,
);
});
@@ -883,4 +1215,32 @@ describe("HTTP /api/admin/plan", () => {
);
expect(res.statusCode).toBe(201);
});
it("POST /entries/bulk requires attendance.manage", async () => {
const res = await authPost("/api/admin/plan/entries/bulk", noPermToken, {
user_ids: [adminUserId],
date_from: "2095-06-01",
date_to: "2095-06-01",
include_weekends: true,
category: "work",
note: `${N}bulk-forbidden`,
});
expect(res.statusCode).toBe(403);
});
it("POST /entries/bulk creates entries for an admin and returns a summary", async () => {
const res = await authPost("/api/admin/plan/entries/bulk", adminToken, {
user_ids: [adminUserId],
date_from: "2095-06-05", // Sunday; weekends on → 1 day
date_to: "2095-06-05",
include_weekends: true,
category: "work",
note: `${N}bulk-http`,
});
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body.success).toBe(true);
expect(body.data.created_days).toBe(1);
expect(body.data.users).toBe(1);
});
});

View File

@@ -0,0 +1,26 @@
import { describe, it, expect } from "vitest";
import { vatFromGross } from "../routes/admin/received-invoices";
// `amount` on a received invoice is the GROSS total (VAT included). The VAT is
// the portion contained within it: gross * rate / (100 + rate).
describe("vatFromGross (VAT contained in a gross total)", () => {
it("derives VAT from a real gross total at 21%", () => {
// 22 542,91 @ 21% → 3 912,41 (base 18 630,50). User-confirmed figures.
expect(vatFromGross(22542.91, 21)).toBeCloseTo(3912.41, 2);
expect(22542.91 - vatFromGross(22542.91, 21)).toBeCloseTo(18630.5, 2);
});
it("derives VAT at other rates", () => {
expect(vatFromGross(1210, 21)).toBeCloseTo(210, 2); // base 1000
expect(vatFromGross(1100, 10)).toBeCloseTo(100, 2); // base 1000
expect(vatFromGross(1150, 15)).toBeCloseTo(150, 2); // base 1000
});
it("returns 0 when there is no VAT", () => {
expect(vatFromGross(5000, 0)).toBe(0);
});
it("returns 0 for a zero amount", () => {
expect(vatFromGross(0, 21)).toBe(0);
});
});

View File

@@ -12,6 +12,7 @@ import { LoadingState } from "./ui";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
const Odin = lazy(() => import("./pages/Odin"));
const Users = lazy(() => import("./pages/Users"));
const Attendance = lazy(() => import("./pages/Attendance"));
const AttendanceHistory = lazy(() => import("./pages/AttendanceHistory"));
@@ -82,6 +83,7 @@ export default function AdminApp() {
)}
<Route element={<AppShell />}>
<Route index element={<Dashboard />} />
<Route path="odin" element={<Odin />} />
<Route path="users" element={<Users />} />
<Route path="attendance" element={<Attendance />} />
<Route

View File

@@ -0,0 +1,191 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import {
Modal,
Field,
DateField,
Select,
TextField,
CheckboxField,
} from "../ui";
import type { PlanUser, PlanCategory } from "../lib/queries/plan";
import type { Project } from "../lib/queries/projects";
export interface BulkPlanForm {
date_from: string;
date_to: string;
is_range: boolean;
user_ids: string[];
include_weekends: boolean;
project_id: string;
category: string;
note: string;
}
interface Props {
isOpen: boolean;
onClose: () => void;
form: BulkPlanForm;
setForm: (form: BulkPlanForm) => void;
users: PlanUser[];
projects: Project[];
categories: PlanCategory[];
onSubmit: () => void;
submitting: boolean;
toggleUser: (userId: number) => void;
toggleAllUsers: () => void;
}
export default function BulkPlanModal({
isOpen,
onClose,
form,
setForm,
users,
projects,
categories,
onSubmit,
submitting,
toggleUser,
toggleAllUsers,
}: Props) {
const activeCategories = categories.filter((c) => c.is_active);
return (
<Modal
isOpen={isOpen}
onClose={onClose}
title="Hromadné přiřazení"
maxWidth="lg"
loading={submitting}
onSubmit={onSubmit}
submitText="Vytvořit"
submitDisabled={form.user_ids.length === 0}
>
<Typography
variant="body2"
color="text.secondary"
sx={{ mt: 0.25, mb: 2 }}
>
Vytvoří záznamy pro vybrané dny u zvolených zaměstnanců. Dny, které
mají 3 záznamy, se přeskočí.
</Typography>
<Field label="Datum od">
<DateField
value={form.date_from}
onChange={(val) => setForm({ ...form, date_from: val })}
/>
</Field>
<Field label="Rozsah dnů">
<CheckboxField
label="Více dní"
checked={form.is_range}
onChange={(checked) => setForm({ ...form, is_range: checked })}
/>
</Field>
{form.is_range && (
<Field label="Datum do">
<DateField
value={form.date_to}
onChange={(val) => setForm({ ...form, date_to: val })}
/>
</Field>
)}
<Field label="Víkendy">
<CheckboxField
label="Zahrnout víkendy"
checked={form.include_weekends}
onChange={(checked) =>
setForm({ ...form, include_weekends: checked })
}
/>
</Field>
<Box sx={{ mb: 2 }}>
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, mb: 0.5 }}>
<Typography
component="span"
variant="body2"
sx={{ fontWeight: 600, color: "text.secondary" }}
>
Zaměstnanci
</Typography>
<Typography
component="button"
type="button"
onClick={toggleAllUsers}
variant="caption"
sx={{
background: "none",
border: "none",
p: 0,
cursor: "pointer",
fontWeight: 500,
color: "primary.main",
}}
>
{users.length > 0 && form.user_ids.length === users.length
? "Odznačit vše"
: "Vybrat vše"}
</Typography>
</Box>
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: 0.25,
maxHeight: 200,
overflowY: "auto",
p: 1.5,
bgcolor: "action.hover",
borderRadius: 2,
border: 1,
borderColor: "divider",
}}
>
{users.map((u) => (
<CheckboxField
key={u.id}
label={u.full_name}
checked={form.user_ids.includes(String(u.id))}
onChange={() => toggleUser(u.id)}
/>
))}
</Box>
<Typography variant="caption" color="text.secondary">
Vybráno: {form.user_ids.length} z {users.length}
</Typography>
</Box>
<Field label="Projekt">
<Select
value={form.project_id}
onChange={(val) => setForm({ ...form, project_id: val })}
options={[
{ value: "", label: "— bez projektu —" },
...projects.map((p) => ({ value: String(p.id), label: p.name })),
]}
/>
</Field>
<Field label="Kategorie">
<Select
value={form.category}
onChange={(val) => setForm({ ...form, category: val })}
options={activeCategories.map((c) => ({
value: c.key,
label: c.label,
}))}
/>
</Field>
<Field label="Text poznámky (volitelný)">
<TextField
multiline
minRows={2}
value={form.note}
onChange={(e) => setForm({ ...form, note: e.target.value })}
inputProps={{ maxLength: 500 }}
/>
</Field>
</Modal>
);
}

View File

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

View File

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

View File

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

View File

@@ -10,11 +10,41 @@ import DialogActions from "@mui/material/DialogActions";
import { useAuth } from "../../context/AuthContext";
import { useAlert } from "../../context/AlertContext";
import apiFetch from "../../utils/api";
import { iconBadgeSx } from "../../theme";
import { Card, Button, Modal, Field, TextField } from "../../ui";
import useDialogScrollLock from "../../ui/useDialogScrollLock";
const API_BASE = "/api/admin";
// Copy helper. navigator.clipboard is SECURE-CONTEXT ONLY (undefined over plain
// HTTP on a LAN), so we fall back to the legacy execCommand path — which works
// in insecure contexts — and report whether the copy actually succeeded. The
// caller MUST gate its success toast on the returned boolean (otherwise it lies
// to the user about copying 2FA codes / the TOTP secret).
async function copyToClipboard(text: string): Promise<boolean> {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return true;
}
} catch {
// fall through to the legacy path
}
try {
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand("copy");
document.body.removeChild(ta);
return ok;
} catch {
return false;
}
}
interface DashProfileProps {
totpEnabled: boolean;
totpLoading: boolean;
@@ -251,17 +281,18 @@ export default function DashProfile({
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<Box
sx={{
width: 36,
height: 36,
borderRadius: "50%",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
bgcolor: totpEnabled ? "success.main" : "grey.600",
color: "common.white",
}}
sx={[
{
width: 36,
height: 36,
borderRadius: "50%",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
iconBadgeSx(totpEnabled ? "success" : "default"),
]}
>
<svg
width="18"
@@ -425,7 +456,8 @@ export default function DashProfile({
p: 1.5,
mb: 2,
borderRadius: 2,
bgcolor: "warning.light",
bgcolor:
"rgba(var(--mui-palette-warning-mainChannel) / 0.12)",
color: "warning.main",
fontSize: "0.875rem",
}}
@@ -477,9 +509,10 @@ export default function DashProfile({
</Box>
<Box sx={{ mt: 1.5 }}>
<Button
onClick={() => {
navigator.clipboard?.writeText(backupCodes.join("\n"));
alert.success("Kódy zkopírovány");
onClick={async () => {
const ok = await copyToClipboard(backupCodes.join("\n"));
if (ok) alert.success("Kódy zkopírovány");
else alert.error("Kopírování selhalo zkopírujte ručně");
}}
variant="outlined"
color="inherit"
@@ -540,9 +573,11 @@ export default function DashProfile({
>
<span>{totpSecret}</span>
<IconButton
onClick={() => {
navigator.clipboard?.writeText(totpSecret);
alert.success("Klíč zkopírován");
onClick={async () => {
const ok = await copyToClipboard(totpSecret);
if (ok) alert.success("Klíč zkopírován");
else
alert.error("Kopírování selhalo zkopírujte ručně");
}}
size="small"
title="Kopírovat"

View File

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

View File

@@ -0,0 +1,121 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Chip from "@mui/material/Chip";
import { Card, Button, TextField } from "../../ui";
import type { ReviewInvoice, EditableField } from "./types";
interface InvoiceReviewCardProps {
inv: ReviewInvoice;
busy: boolean;
canSave: boolean;
onChange: (uid: string, field: EditableField, value: string) => void;
onSave: (inv: ReviewInvoice) => void;
onDiscard: (uid: string) => void;
}
const fieldCols = { xs: "1fr", sm: "1fr 1fr" };
export default function InvoiceReviewCard({
inv,
busy,
canSave,
onChange,
onSave,
onDiscard,
}: InvoiceReviewCardProps) {
return (
<Card variant="outlined" sx={{ p: 1.5 }}>
{/* Header: chip + filename */}
<Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1 }}>
<Chip label="Faktura" size="small" color="primary" />
<Typography
variant="caption"
color="text.secondary"
noWrap
title={inv.file_name}
>
{inv.file_name}
</Typography>
</Box>
{/* 2-column field grid */}
<Box
sx={{
display: "grid",
gridTemplateColumns: fieldCols,
gap: 1,
}}
>
<TextField
label="Dodavatel"
value={inv.supplier_name}
disabled={busy}
onChange={(e) => onChange(inv.uid, "supplier_name", e.target.value)}
/>
<TextField
label="Číslo faktury"
value={inv.invoice_number}
disabled={busy}
onChange={(e) => onChange(inv.uid, "invoice_number", e.target.value)}
/>
<TextField
label="Částka s DPH"
value={inv.amount}
disabled={busy}
onChange={(e) => onChange(inv.uid, "amount", e.target.value)}
/>
<TextField
label="Měna"
value={inv.currency}
disabled={busy}
onChange={(e) => onChange(inv.uid, "currency", e.target.value)}
/>
<TextField
label="Sazba DPH %"
value={inv.vat_rate}
disabled={busy}
onChange={(e) => onChange(inv.uid, "vat_rate", e.target.value)}
/>
<TextField
label="Datum vystavení"
value={inv.issue_date}
disabled={busy}
onChange={(e) => onChange(inv.uid, "issue_date", e.target.value)}
/>
<TextField
label="Datum splatnosti"
value={inv.due_date}
disabled={busy}
onChange={(e) => onChange(inv.uid, "due_date", e.target.value)}
/>
<TextField
label="Popis"
value={inv.description}
disabled={busy}
onChange={(e) => onChange(inv.uid, "description", e.target.value)}
/>
</Box>
{/* Actions */}
<Box sx={{ display: "flex", gap: 1, mt: 1.5 }}>
<Button
onClick={() => onSave(inv)}
disabled={busy || !canSave}
title={
!canSave ? "Nemáte oprávnění k uložení přijatých faktur" : undefined
}
>
Uložit
</Button>
<Button
variant="outlined"
color="inherit"
onClick={() => onDiscard(inv.uid)}
disabled={busy}
>
Zahodit
</Button>
</Box>
</Card>
);
}

View File

@@ -0,0 +1,548 @@
import { useState, useRef, useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Drawer from "@mui/material/Drawer";
import IconButton from "@mui/material/IconButton";
import useMediaQuery from "@mui/material/useMediaQuery";
import apiFetch from "../../utils/api";
import { useAlert } from "../../context/AlertContext";
import { useAuth } from "../../context/AuthContext";
import {
aiUsageOptions,
aiConversationsOptions,
aiConversationMessagesOptions,
type ExtractedInvoice,
} from "../../lib/queries/ai";
import type {
ChatTurn,
ReviewInvoice,
EditableField,
StagedFile,
} from "./types";
import OdinSidebar from "./OdinSidebar";
import OdinThread from "./OdinThread";
import InvoiceReviewCard from "./InvoiceReviewCard";
import OdinComposer from "./OdinComposer";
// Stable, monotonic id (NOT crypto.randomUUID — undefined over plain HTTP).
let uidSeq = 0;
const nextUid = () => `ai-${(uidSeq += 1)}`;
const MODEL_CONTEXT = 20; // recent turns sent to the model
const MAX_STORE = 8000; // server caps a stored message at 8000 chars
const plural = (n: number) =>
n === 1 ? "fakturu" : n >= 2 && n <= 4 ? "faktury" : "faktur";
function summaryNote(reviews: ReviewInvoice[]): string {
if (reviews.length === 0) return "V přílohách jsem nenašel žádnou fakturu.";
const suppliers = [
...new Set(reviews.map((r) => r.supplier_name).filter(Boolean)),
];
const supTxt =
suppliers.length === 1
? ` od ${suppliers[0]}`
: suppliers.length > 1
? ` od ${suppliers[0]} a dalších`
: "";
const totals: Record<string, number> = {};
for (const r of reviews) {
const cur = r.currency || "CZK";
totals[cur] = (totals[cur] || 0) + (Number(r.amount) || 0);
}
const totalsTxt = Object.entries(totals)
.map(
([cur, sum]) =>
`${sum.toLocaleString("cs-CZ", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})} ${cur}`,
)
.join(" + ");
return `Načetl jsem ${reviews.length} ${plural(reviews.length)}${supTxt}, celkem ${totalsTxt}. Zkontrolujte údaje a uložte.`;
}
export default function OdinChat() {
const alert = useAlert();
const qc = useQueryClient();
const { user, hasPermission } = useAuth();
// Saving an extracted invoice hits /received-invoices (needs invoices.create);
// Odin itself only needs ai.use, so the Save affordance is gated separately.
const canSave = hasPermission("invoices.create");
// Time-based Czech greeting + the user's first name (client-local time).
const greetingHour = new Date().getHours();
const greetingPhrase =
greetingHour < 9
? "Dobré ráno"
: greetingHour < 12
? "Dobrý den"
: greetingHour < 18
? "Dobré odpoledne"
: "Dobrý večer";
const userName = (user?.fullName || user?.username || "")
.trim()
.split(/\s+/)[0];
const { data: usage } = useQuery(aiUsageOptions());
const { data: convData, isPending: convPending } = useQuery(
aiConversationsOptions(),
);
const conversations = convData?.conversations ?? [];
const [activeId, setActiveId] = useState<number | null>(null);
const { data: messagesData } = useQuery({
...aiConversationMessagesOptions(activeId ?? 0),
enabled: activeId != null,
});
const [input, setInput] = useState("");
const [busy, setBusy] = useState(false);
const [turns, setTurns] = useState<ChatTurn[]>([]);
const [review, setReview] = useState<ReviewInvoice[]>([]);
const [attachments, setAttachments] = useState<StagedFile[]>([]);
const fileRef = useRef<HTMLInputElement>(null);
const threadRef = useRef<HTMLDivElement>(null);
const seededId = useRef<number | null>(null);
// Below md the conversation list collapses into a slide-in drawer.
const isMobile = useMediaQuery((t) => t.breakpoints.down("md"), {
noSsr: true,
});
const [sidebarOpen, setSidebarOpen] = useState(false);
// No auto-select: like claude.ai, we land on a fresh "new chat" (activeId
// null) and the sidebar lists existing conversations to open. A conversation
// row in the DB is created lazily on the first message (see submit), so
// pressing "Nová konverzace" repeatedly never spawns empty conversations.
// Seed the thread from the active conversation's messages, once per id.
useEffect(() => {
if (activeId != null && messagesData && seededId.current !== activeId) {
seededId.current = activeId;
setTurns(
messagesData.messages.map((m) => ({
role: m.role as "user" | "assistant",
content: m.content,
})),
);
setReview([]);
}
}, [activeId, messagesData]);
// Keep the thread scrolled to the latest message.
useEffect(() => {
const el = threadRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [turns, busy]);
// AI is hidden entirely when the backend isn't configured.
if (usage && usage.configured === false) return null;
const messagesLoading =
activeId != null && !messagesData && seededId.current !== activeId;
const persist = (convId: number, msgs: ChatTurn[]) => {
apiFetch(`/api/admin/ai/conversations/${convId}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: msgs.map((m) => ({
role: m.role,
content: m.content.slice(0, MAX_STORE),
})),
}),
})
.then((r) => {
if (!r.ok) return r.json().then((b) => Promise.reject(b?.error));
// The append applies the server-side auto-title and bumps updated_at,
// so refresh the list now (a new conversation gets its real title here).
qc.invalidateQueries({ queryKey: ["ai", "conversations"] });
})
.catch((e) => console.error("[odin] history persist failed", e));
};
// Attaching only stages files; nothing is sent until Odeslat.
const onFiles = (files: FileList | null) => {
if (!files || files.length === 0) return;
setAttachments((a) => [
...a,
...Array.from(files).map((file) => ({ id: nextUid(), file })),
]);
if (fileRef.current) fileRef.current.value = "";
};
const removeAttachment = (id: string) =>
setAttachments((a) => a.filter((s) => s.id !== id));
const onSelect = (id: number) => {
setSidebarOpen(false);
if (id === activeId || busy) return;
setActiveId(id);
setTurns([]);
setReview([]);
seededId.current = null;
};
// Returns the active conversation id, creating one if none is selected yet.
const ensureActive = async (): Promise<number | null> => {
if (activeId != null) return activeId;
const res = await apiFetch("/api/admin/ai/conversations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const b = await res.json();
if (!res.ok || !b?.data?.conversation) return null;
const id = b.data.conversation.id as number;
seededId.current = id;
setActiveId(id);
// Don't refresh the list yet — the conversation is still the default
// "Nová konverzace" here; persist() invalidates after the auto-title lands.
return id;
};
const canSubmit =
!convPending && !busy && (!!input.trim() || attachments.length > 0);
const submit = async () => {
if (busy) return;
const text = input.trim();
const files = attachments.map((a) => a.file);
if (!text && files.length === 0) return;
// Guard: Odin is scoped to invoice processing only (for now). A text-only
// message makes NO AI call — it gets a canned reply locally, so open-ended
// chat can't burn API credits. The invoice path (attachments) runs normally.
// (Removing this guard re-enables the general /chat path below for Phase 2.)
if (files.length === 0) {
setTurns((t) => [
...t,
{ role: "user", content: text },
{
role: "assistant",
content:
"Momentálně umím zpracovat pouze přijaté faktury. Přiložte prosím fakturu (PDF) a já z ní načtu údaje k uložení.",
},
]);
setInput("");
return;
}
setBusy(true);
const prevTurns = turns;
const userContent = [
text,
files.length > 0 ? `📎 ${files.map((f) => f.name).join(", ")}` : "",
]
.filter(Boolean)
.join("\n");
const optimistic: ChatTurn[] = [
...turns,
{ role: "user", content: userContent },
];
setTurns(optimistic);
try {
if (files.length > 0) {
const fd = new FormData();
files.forEach((f) => fd.append("files", f));
const res = await apiFetch("/api/admin/ai/extract-invoices", {
method: "POST",
body: fd,
});
const body = await res.json();
if (!res.ok) throw new Error(body?.error || "Chyba čtení faktur");
const reviews: ReviewInvoice[] = (
body.data.invoices as Array<{
file_name: string;
fields?: ExtractedInvoice;
error?: string;
}>
)
.map((r, i): ReviewInvoice | null => {
const f = r.fields;
return f
? {
uid: nextUid(),
supplier_name: f.supplier_name ?? "",
invoice_number: f.invoice_number ?? "",
amount: f.amount != null ? String(f.amount) : "",
currency: f.currency ?? "",
vat_rate: f.vat_rate != null ? String(f.vat_rate) : "",
issue_date: f.issue_date ?? "",
due_date: f.due_date ?? "",
description: f.description ?? "",
file_name: r.file_name,
file: files[i],
}
: null;
})
.filter((x): x is ReviewInvoice => x !== null);
setReview((prev) => [...prev, ...reviews]);
const note = summaryNote(reviews);
setTurns((t) => [...t, { role: "assistant", content: note }]);
setInput("");
setAttachments([]);
// Create the conversation now (first successful message) and persist.
const convId = await ensureActive();
if (convId != null)
persist(convId, [
{ role: "user", content: userContent },
{ role: "assistant", content: note },
]);
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
} else {
let ctx = optimistic.slice(-MODEL_CONTEXT);
while (ctx.length && ctx[0].role !== "user") ctx = ctx.slice(1);
const res = await apiFetch("/api/admin/ai/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: ctx }),
});
const body = await res.json();
if (!res.ok) throw new Error(body?.error || "Chyba AI");
const reply: string = body.data.reply;
setTurns((t) => [...t, { role: "assistant", content: reply }]);
setInput("");
// Create the conversation now (first successful message) and persist.
const convId = await ensureActive();
if (convId != null)
persist(convId, [
{ role: "user", content: userContent },
{ role: "assistant", content: reply },
]);
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
}
} catch (e) {
setTurns(prevTurns);
const fallback = files.length > 0 ? "Chyba čtení faktur" : "Chyba AI";
alert.error(e instanceof Error ? e.message : fallback);
} finally {
setBusy(false);
}
};
const saveInvoice = async (inv: ReviewInvoice) => {
if (busy) return;
setBusy(true);
try {
const fd = new FormData();
fd.append("files", inv.file, inv.file_name);
fd.append(
"invoices",
JSON.stringify([
{
supplier_name: inv.supplier_name,
invoice_number: inv.invoice_number || undefined,
description: inv.description || undefined,
amount: inv.amount === "" ? undefined : Number(inv.amount),
currency: inv.currency,
vat_rate: inv.vat_rate === "" ? undefined : Number(inv.vat_rate),
issue_date: inv.issue_date || undefined,
due_date: inv.due_date || undefined,
},
]),
);
const res = await apiFetch("/api/admin/received-invoices", {
method: "POST",
body: fd,
});
const body = await res.json();
if (!res.ok) throw new Error(body?.error || "Uložení selhalo");
alert.success("Faktura uložena");
setReview((r) => r.filter((x) => x.uid !== inv.uid));
qc.invalidateQueries({ queryKey: ["invoices"] });
} catch (e) {
alert.error(e instanceof Error ? e.message : "Uložení selhalo");
} finally {
setBusy(false);
}
};
// "Nová konverzace" just opens a fresh, empty composer — no DB row is created
// until the first message, so repeated clicks never spawn empty conversations.
const onNew = () => {
setSidebarOpen(false);
if (busy) return;
setActiveId(null);
setTurns([]);
setReview([]);
setInput("");
setAttachments([]);
seededId.current = null;
};
const onRename = async (id: number, title: string) => {
const res = await apiFetch(`/api/admin/ai/conversations/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
if (res.ok) qc.invalidateQueries({ queryKey: ["ai", "conversations"] });
else alert.error("Přejmenování selhalo");
};
const onDelete = async (id: number) => {
const res = await apiFetch(`/api/admin/ai/conversations/${id}`, {
method: "DELETE",
});
if (!res.ok) {
alert.error("Smazání selhalo");
return;
}
if (id === activeId) {
// Deleting the open conversation returns to a fresh new chat.
setActiveId(null);
setTurns([]);
setReview([]);
seededId.current = null;
}
qc.invalidateQueries({ queryKey: ["ai", "conversations"] });
};
const patch = (uid: string, field: EditableField, value: string) =>
setReview((r) =>
r.map((inv) => (inv.uid === uid ? { ...inv, [field]: value } : inv)),
);
const activeTitle =
conversations.find((c) => c.id === activeId)?.title ?? "Nová konverzace";
const sidebar = (
<OdinSidebar
conversations={conversations}
activeId={activeId}
busy={busy}
onSelect={onSelect}
onNew={onNew}
onRename={onRename}
onDelete={onDelete}
/>
);
return (
<Box
sx={{
height: "calc(100dvh - 100px)",
display: "flex",
border: 1,
borderColor: "divider",
borderRadius: 3,
bgcolor: "background.paper",
overflow: "hidden",
}}
>
{isMobile ? (
<Drawer
open={sidebarOpen}
onClose={() => setSidebarOpen(false)}
ModalProps={{ keepMounted: true }}
>
{sidebar}
</Drawer>
) : (
sidebar
)}
{/* Chat column */}
<Box
sx={{
flex: 1,
minWidth: 0,
display: "flex",
flexDirection: "column",
gap: 1.5,
p: 2,
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
{isMobile && (
<IconButton
onClick={() => setSidebarOpen(true)}
aria-label="Konverzace"
size="small"
sx={{ ml: -0.5, flexShrink: 0 }}
>
<Box
component="svg"
viewBox="0 0 24 24"
sx={{ width: 22, height: 22 }}
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
>
<line x1="3" y1="6" x2="21" y2="6" />
<line x1="3" y1="12" x2="21" y2="12" />
<line x1="3" y1="18" x2="21" y2="18" />
</Box>
</IconButton>
)}
<Typography
variant="subtitle1"
noWrap
sx={{ fontWeight: 600, minWidth: 0, flex: 1 }}
>
{activeTitle}
</Typography>
{usage && (
<Typography
variant="caption"
color="text.secondary"
sx={{ flexShrink: 0, display: { xs: "none", sm: "block" } }}
>
Utraceno: ${usage.month_spend_usd.toFixed(2)} / $
{usage.budget_usd.toFixed(2)}
</Typography>
)}
</Box>
<OdinThread
turns={turns}
busy={busy}
loading={messagesLoading}
greetingPhrase={greetingPhrase}
userName={userName}
threadRef={threadRef}
/>
{review.length > 0 && (
<Box
sx={{
maxHeight: "35vh",
overflowY: "auto",
display: "flex",
flexDirection: "column",
gap: 1,
}}
>
{review.map((inv) => (
<InvoiceReviewCard
key={inv.uid}
inv={inv}
busy={busy}
canSave={canSave}
onChange={patch}
onSave={saveInvoice}
onDiscard={(uid) =>
setReview((r) => r.filter((x) => x.uid !== uid))
}
/>
))}
</Box>
)}
<OdinComposer
input={input}
attachments={attachments}
busy={busy}
canSubmit={canSubmit}
fileRef={fileRef}
onInput={setInput}
onFiles={onFiles}
onRemoveAttachment={removeAttachment}
onSubmit={submit}
/>
</Box>
</Box>
);
}

View File

@@ -0,0 +1,147 @@
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import IconButton from "@mui/material/IconButton";
import TextField from "@mui/material/TextField";
import type { StagedFile } from "./types";
interface OdinComposerProps {
input: string;
attachments: StagedFile[];
busy: boolean;
canSubmit: boolean;
fileRef: React.RefObject<HTMLInputElement | null>;
onInput: (v: string) => void;
onFiles: (files: FileList | null) => void;
onRemoveAttachment: (id: string) => void;
onSubmit: () => void;
}
export default function OdinComposer({
input,
attachments,
busy,
canSubmit,
fileRef,
onInput,
onFiles,
onRemoveAttachment,
onSubmit,
}: OdinComposerProps) {
return (
<Box>
{/* Staged attachment chips */}
{attachments.length > 0 && (
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5, mb: 1 }}>
{attachments.map((s) => (
<Chip
key={s.id}
label={s.file.name}
size="small"
variant="outlined"
onDelete={busy ? undefined : () => onRemoveAttachment(s.id)}
/>
))}
</Box>
)}
<input
ref={fileRef as React.RefObject<HTMLInputElement>}
type="file"
accept="application/pdf,image/*"
multiple
hidden
onChange={(e) => onFiles(e.target.files)}
/>
{/* Composer pill — full-width growing input with attach + send icons */}
<Box
sx={{
display: "flex",
alignItems: "center",
gap: 0.5,
border: 1,
borderColor: "divider",
borderRadius: 3.5,
bgcolor: "background.default",
pl: 0.75,
pr: 0.75,
py: 0.5,
transition: "border-color 0.15s ease",
"&:focus-within": { borderColor: "primary.main" },
}}
>
<IconButton
onClick={() => fileRef.current?.click()}
disabled={busy}
aria-label="Přiložit fakturu"
title="Přiložit fakturu (PDF)"
sx={{ flexShrink: 0, color: "text.secondary" }}
>
<Box
component="svg"
viewBox="0 0 24 24"
sx={{ width: 21, height: 21 }}
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
</Box>
</IconButton>
<TextField
multiline
maxRows={8}
variant="standard"
placeholder="Napište zprávu…"
value={input}
onChange={(e) => onInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
onSubmit();
}
}}
fullWidth
slotProps={{ input: { disableUnderline: true } }}
sx={{ flex: 1, "& textarea": { py: 0.75, lineHeight: 1.5 } }}
/>
<IconButton
onClick={onSubmit}
disabled={!canSubmit}
aria-label="Odeslat"
title="Odeslat (Enter)"
sx={{
flexShrink: 0,
width: 36,
height: 36,
color: "common.white",
bgcolor: "primary.main",
"&:hover": { bgcolor: "primary.dark" },
"&.Mui-disabled": {
bgcolor: "action.disabledBackground",
color: "action.disabled",
},
}}
>
<Box
component="svg"
viewBox="0 0 24 24"
sx={{ width: 18, height: 18 }}
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="12" y1="19" x2="12" y2="5" />
<polyline points="5 12 12 5 19 12" />
</Box>
</IconButton>
</Box>
</Box>
);
}

View File

@@ -0,0 +1,119 @@
import { keyframes, styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import { useReducedMotion } from "framer-motion";
/**
* Odin's animated brand mark: an AI "spark" (Odin) with a data node orbiting a
* ring — the assistant at the centre of the business system, in BOHA red. The
* spark slow-rotates and breathes; the node orbits. In the "thinking" state
* everything speeds up and the tile glows. Honours prefers-reduced-motion.
*
* The animations live in a `styled("svg")` (not inline style): Emotion only
* injects the @keyframes rule when the keyframes object is used inside
* sx/css/styled, and the child selectors keep the SVG elements plain/typed.
*/
const breathe = keyframes`
0%, 100% { transform: scale(0.9); opacity: 0.9; }
50% { transform: scale(1.08); opacity: 1; }
`;
const spin = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
// Reduce-motion safe: opacity only (no transforms / no travel).
const glow = keyframes`
0%, 100% { opacity: 0.55; }
50% { opacity: 1; }
`;
const Glyph = styled("svg", {
shouldForwardProp: (p) => p !== "thinking" && p !== "reduce",
})<{ thinking: boolean; reduce: boolean }>(({ thinking, reduce }) => ({
// !important so an ancestor `& svg { width }` rule (e.g. SidebarNav forces
// 18px) can't override the mark's own sizing — `size` stays authoritative.
width: "70% !important",
height: "70% !important",
overflow: "visible",
display: "block",
...(reduce
? {
// Reduce-motion: keep a calm opacity glow (no spin/orbit/travel). The
// `!important` + class specificity intentionally overrides the app-wide
// reduced-motion reset in GlobalStyles for this one small mark, since an
// opacity pulse is accessibility-safe (it isn't vestibular motion).
"& .odin-spark": {
animation: `${glow} ${thinking ? "1.1s" : "3s"} ease-in-out infinite !important`,
},
}
: {
"& .odin-orbit": {
transformBox: "view-box",
transformOrigin: "12px 12px",
animation: `${spin} ${thinking ? "1.6s" : "5.5s"} linear infinite`,
},
"& .odin-spin": {
transformBox: "view-box",
transformOrigin: "12px 12px",
animation: `${spin} ${thinking ? "4s" : "11s"} linear infinite`,
},
"& .odin-spark": {
transformBox: "fill-box",
transformOrigin: "center",
animation: `${breathe} ${thinking ? "1s" : "2.8s"} ease-in-out infinite`,
},
}),
}));
export interface OdinMarkProps {
size?: number;
state?: "idle" | "thinking";
}
export default function OdinMark({ size = 28, state = "idle" }: OdinMarkProps) {
const reduce = !!useReducedMotion();
const thinking = state === "thinking";
return (
<Box
sx={(t) => ({
width: size,
height: size,
borderRadius: "32%",
flexShrink: 0,
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
background: `linear-gradient(135deg, ${t.vars!.palette.primary.main}, ${t.vars!.palette.primary.dark})`,
boxShadow: thinking
? `0 0 ${Math.round(size * 0.5)}px 0 rgba(${t.vars!.palette.primary.mainChannel} / 0.55)`
: "none",
transition: "box-shadow 0.3s ease",
})}
>
<Glyph viewBox="0 0 24 24" thinking={thinking} reduce={reduce}>
{/* orbit ring */}
<circle
cx="12"
cy="12"
r="9.2"
fill="none"
stroke="#fff"
strokeOpacity="0.28"
strokeWidth="1"
/>
{/* orbiting data node */}
<g className="odin-orbit">
<circle cx="12" cy="2.8" r="1.4" fill="#fff" />
</g>
{/* spark — group slow-rotates, the star breathes about its own centre */}
<g className="odin-spin">
<path
className="odin-spark"
d="M12 4.5 C12.5 9, 13 9.5, 17.5 12 C13 14.5, 12.5 15, 12 19.5 C11.5 15, 11 14.5, 6.5 12 C11 9.5, 11.5 9, 12 4.5 Z"
fill="#fff"
/>
</g>
</Glyph>
</Box>
);
}

View File

@@ -0,0 +1,221 @@
import { useState } from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import IconButton from "@mui/material/IconButton";
import { Button, TextField, Modal, ConfirmDialog } from "../../ui";
interface OdinSidebarProps {
conversations: { id: number; title: string }[];
activeId: number | null;
busy: boolean;
onSelect: (id: number) => void;
onNew: () => void;
onRename: (id: number, title: string) => void;
onDelete: (id: number) => void;
}
export default function OdinSidebar({
conversations,
activeId,
busy,
onSelect,
onNew,
onRename,
onDelete,
}: OdinSidebarProps) {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const [menuConv, setMenuConv] = useState<{
id: number;
title: string;
} | null>(null);
const [renameOpen, setRenameOpen] = useState(false);
const [renameDraft, setRenameDraft] = useState("");
const [deleteOpen, setDeleteOpen] = useState(false);
const openMenu = (
e: React.MouseEvent<HTMLElement>,
conv: { id: number; title: string },
) => {
e.stopPropagation();
setMenuConv(conv);
setAnchorEl(e.currentTarget);
};
const closeMenu = () => setAnchorEl(null);
const handleRenameOpen = () => {
closeMenu();
setRenameDraft(menuConv?.title ?? "");
setRenameOpen(true);
};
const handleRenameSubmit = () => {
if (menuConv) onRename(menuConv.id, renameDraft.trim() || menuConv.title);
setRenameOpen(false);
};
const handleDeleteOpen = () => {
closeMenu();
setDeleteOpen(true);
};
const handleDeleteConfirm = () => {
if (menuConv) onDelete(menuConv.id);
setDeleteOpen(false);
};
return (
<Box
sx={{
width: { xs: 280, md: 264 },
flexShrink: 0,
height: "100%",
display: "flex",
flexDirection: "column",
borderRight: 1,
borderColor: "divider",
bgcolor: "action.hover",
}}
>
{/* Brand + New chat */}
<Box sx={{ p: 1.5, display: "flex", flexDirection: "column", gap: 1 }}>
<Box
component="span"
sx={(t) => ({
px: 0.5,
fontSize: "1.7rem",
fontWeight: 700,
lineHeight: 1.2,
letterSpacing: "-0.02em",
backgroundImage: `linear-gradient(120deg, ${t.vars!.palette.primary.light}, ${t.vars!.palette.primary.main})`,
WebkitBackgroundClip: "text",
backgroundClip: "text",
WebkitTextFillColor: "transparent",
})}
>
Odin
</Box>
<Button fullWidth disabled={busy} onClick={onNew}>
+ Nová konverzace
</Button>
</Box>
{/* Conversation list */}
<Box
sx={{
flex: 1,
minHeight: 0,
overflowY: "auto",
px: 1,
pb: 1,
display: "flex",
flexDirection: "column",
gap: 0.25,
}}
>
{conversations.length === 0 && (
<Typography
variant="caption"
color="text.secondary"
sx={{ px: 1, py: 1 }}
>
Zatím žádné konverzace.
</Typography>
)}
{conversations.map((conv) => {
const isActive = conv.id === activeId;
return (
<Box
key={conv.id}
onClick={() => !busy && onSelect(conv.id)}
sx={{
display: "flex",
alignItems: "center",
gap: 0.5,
px: 1,
py: 0.75,
borderRadius: 1.5,
cursor: busy ? "default" : "pointer",
bgcolor: isActive ? "action.selected" : "transparent",
"&:hover": {
bgcolor: isActive ? "action.selected" : "action.hover",
},
"&:hover .odin-conv-menu": { opacity: 1 },
}}
>
<Typography
variant="body2"
noWrap
title={conv.title}
sx={{
flex: 1,
minWidth: 0,
color: "text.primary",
fontWeight: isActive ? 600 : 400,
}}
>
{conv.title}
</Typography>
<IconButton
className="odin-conv-menu"
size="small"
disabled={busy}
onClick={(e) => openMenu(e, conv)}
aria-label="Možnosti konverzace"
title="Možnosti konverzace"
sx={{
flexShrink: 0,
opacity: { xs: 1, md: 0 },
transition: "opacity 0.15s",
}}
>
</IconButton>
</Box>
);
})}
</Box>
{/* Per-conversation menu */}
<Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={closeMenu}>
<MenuItem onClick={handleRenameOpen}>Přejmenovat</MenuItem>
<MenuItem onClick={handleDeleteOpen}>Smazat</MenuItem>
</Menu>
{/* Rename modal */}
<Modal
isOpen={renameOpen}
onClose={() => setRenameOpen(false)}
onSubmit={handleRenameSubmit}
title="Přejmenovat konverzaci"
submitText="Přejmenovat"
maxWidth="xs"
>
<Box sx={{ pt: 1 }}>
<TextField
label="Název"
fullWidth
value={renameDraft}
onChange={(e) => setRenameDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleRenameSubmit();
}
}}
autoFocus
/>
</Box>
</Modal>
{/* Delete confirm */}
<ConfirmDialog
isOpen={deleteOpen}
onClose={() => setDeleteOpen(false)}
onConfirm={handleDeleteConfirm}
title="Smazat konverzaci"
message={`Opravdu chcete smazat konverzaci „${menuConv?.title ?? ""}"? Tuto akci nelze vrátit.`}
confirmText="Smazat"
confirmVariant="danger"
/>
</Box>
);
}

View File

@@ -0,0 +1,238 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { motion, useReducedMotion, type Variants } from "framer-motion";
import type { ChatTurn } from "./types";
import OdinMark from "./OdinMark";
const MotionBox = motion.create(Box);
// Staggered hero entrance (skipped under prefers-reduced-motion).
const heroContainer: Variants = {
hidden: {},
show: { transition: { staggerChildren: 0.12, delayChildren: 0.06 } },
};
const heroItem: Variants = {
hidden: { opacity: 0, y: 14 },
show: {
opacity: 1,
y: 0,
transition: { duration: 0.55, ease: [0.16, 1, 0.3, 1] },
},
};
interface OdinThreadProps {
turns: ChatTurn[];
busy: boolean;
loading: boolean;
greetingPhrase?: string;
userName?: string;
threadRef: React.RefObject<HTMLDivElement | null>;
}
/** Small Odin avatar shown to the left of assistant bubbles. */
function OdinAvatar({ size = 28 }: { size?: number }) {
return (
<Box
sx={{
width: size,
height: size,
borderRadius: "50%",
bgcolor: "primary.main",
color: "common.white",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontWeight: 700,
fontSize: size * 0.5,
flexShrink: 0,
}}
>
O
</Box>
);
}
export default function OdinThread({
turns,
busy,
loading,
greetingPhrase,
userName,
threadRef,
}: OdinThreadProps) {
const reduce = useReducedMotion();
const containerMotion = reduce
? {}
: { variants: heroContainer, initial: "hidden", animate: "show" };
const itemMotion = reduce ? {} : { variants: heroItem };
return (
<Box
ref={threadRef}
sx={{
flex: 1,
minHeight: 0,
overflowY: "auto",
display: "flex",
flexDirection: "column",
gap: 1.5,
p: 2,
bgcolor: "action.hover",
borderRadius: 2,
}}
>
{/* Loading state — history is being fetched */}
{loading && (
<Box
sx={{
flex: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Typography variant="body2" sx={{ color: "text.secondary" }}>
Načítám
</Typography>
</Box>
)}
{/* Empty state */}
{turns.length === 0 && !busy && !loading && (
<MotionBox
{...containerMotion}
sx={{
flex: 1,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 1.75,
textAlign: "center",
px: 3,
}}
>
<MotionBox {...itemMotion}>
<Typography
component="h1"
sx={{
fontFamily: "'Newsreader', Georgia, 'Times New Roman', serif",
fontOpticalSizing: "auto",
fontWeight: 500,
fontSize: "clamp(2.2rem, 1.3rem + 2.6vw, 3.3rem)",
lineHeight: 1.05,
letterSpacing: "-0.01em",
color: "text.primary",
m: 0,
}}
>
{greetingPhrase || "Dobrý den"}
{userName && (
<>
,{" "}
<Box
component="span"
sx={(t) => ({
fontStyle: "italic",
backgroundImage: `linear-gradient(120deg, ${t.vars!.palette.primary.light}, ${t.vars!.palette.primary.main})`,
WebkitBackgroundClip: "text",
backgroundClip: "text",
WebkitTextFillColor: "transparent",
})}
>
{userName}
</Box>
</>
)}
</Typography>
</MotionBox>
<MotionBox {...itemMotion}>
<Typography
component="p"
sx={{
fontFamily: "'Newsreader', Georgia, serif",
fontStyle: "italic",
fontWeight: 400,
fontSize: "clamp(1.05rem, 0.95rem + 0.45vw, 1.3rem)",
lineHeight: 1.55,
color: "text.secondary",
maxWidth: 540,
m: 0,
}}
>
Zeptejte se na cokoli, nebo přiložte fakturu Odin ji přečte a
připraví k uložení.
</Typography>
</MotionBox>
</MotionBox>
)}
{/* Message bubbles */}
{turns.map((t, i) => {
const isUser = t.role === "user";
return (
<MotionBox
key={i}
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{
duration: reduce ? 0.3 : 0.34,
ease: [0.16, 1, 0.3, 1],
}}
sx={{
display: "flex",
flexDirection: "row",
alignItems: "flex-end",
gap: 1,
alignSelf: isUser ? "flex-end" : "flex-start",
maxWidth: "80%",
}}
>
{!isUser && <OdinAvatar size={28} />}
<Box
sx={{
px: 1.5,
py: 1,
borderRadius: 2,
boxShadow: 1,
bgcolor: isUser ? "primary.main" : "background.paper",
}}
>
{/* Color MUST sit on the Typography: GlobalStyles pins `p` to
text.secondary, which beats a color merely inherited from the
Box. An sx class on the element wins over that element rule. */}
<Typography
variant="body2"
sx={{
whiteSpace: "pre-wrap",
color: isUser ? "common.white" : "text.primary",
}}
>
{t.content}
</Typography>
</Box>
</MotionBox>
);
})}
{/* Busy indicator */}
{busy && (
<Box
sx={{
alignSelf: "flex-start",
display: "flex",
alignItems: "center",
gap: 1,
px: 1.5,
py: 1,
color: "text.secondary",
}}
>
<OdinMark size={22} state="thinking" />
<Typography variant="caption" sx={{ color: "inherit" }}>
Pracuji
</Typography>
</Box>
)}
</Box>
);
}

View File

@@ -0,0 +1,33 @@
export interface ChatTurn {
role: "user" | "assistant";
content: string;
}
export interface ReviewInvoice {
uid: string;
supplier_name: string;
invoice_number: string;
amount: string;
currency: string;
vat_rate: string;
issue_date: string;
due_date: string;
description: string;
file_name: string;
file: File;
}
export type EditableField =
| "supplier_name"
| "invoice_number"
| "amount"
| "currency"
| "vat_rate"
| "issue_date"
| "due_date"
| "description";
export interface StagedFile {
id: string;
file: File;
}

View File

@@ -12,9 +12,11 @@ export type ViewMode = "week" | "month";
export type ModalMode =
| { kind: "closed" }
| { kind: "create"; userId: number; date: string }
| { kind: "create-override"; userId: number; date: string }
| { kind: "edit-range"; entryId: number; userId: number; date: string }
| { kind: "edit-override"; overrideId: number; userId: number; date: string }
| { kind: "day-in-range"; userId: number; date: string; entryId: number }
| { kind: "day"; userId: number; date: string }
| { kind: "view"; userId: number; date: string };
function isoDate(d: Date): string {
@@ -150,16 +152,16 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
key: readonly unknown[],
userId: number,
dates: string[],
mutator: (prev: ResolvedCell | null) => ResolvedCell | null,
): Record<string, ResolvedCell | null> | null {
mutator: (prev: ResolvedCell[]) => ResolvedCell[],
): Record<string, ResolvedCell[]> | null {
const prev = snapshotGrid(key);
if (!prev) return null;
const userPrev = prev.cells[userId] ?? {};
const rolled: Record<string, ResolvedCell | null> = {};
const userNext: Record<string, ResolvedCell | null> = { ...userPrev };
const rolled: Record<string, ResolvedCell[]> = {};
const userNext: Record<string, ResolvedCell[]> = { ...userPrev };
for (const date of dates) {
rolled[date] = userPrev[date] ?? null;
userNext[date] = mutator(rolled[date]);
rolled[date] = userPrev[date] ?? [];
userNext[date] = mutator(rolled[date]).slice(0, 3);
}
qc.setQueryData(key, {
...prev,
@@ -244,7 +246,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
// the ResolvedCell mirrors the request body.
const days = eachDay(body.date_from, body.date_to);
const id = data && typeof data.id === "number" ? data.id : null;
const rolled = patchCells(currentGridKey, body.user_id, days, () =>
const rolled = patchCells(currentGridKey, body.user_id, days, (prev) => [
makeEntryCell({
userId: body.user_id,
date: days[0],
@@ -255,7 +257,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
rangeTo: body.date_to,
entryId: id,
}),
);
...prev,
]);
// Stash the rollback on the mutation object so PlanWork can call
// it from onError.
(createEntry as any)._rolled = rolled;
@@ -294,8 +297,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
let ownerUserId: number | null = null;
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const cell of Object.values(byDate)) {
if (cell && cell.entryId === id) {
for (const cells of Object.values(byDate)) {
if (cells.some((c) => c.entryId === id)) {
ownerUserId = Number(uidStr);
break;
}
@@ -304,20 +307,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
}
}
if (ownerUserId !== null) {
const rolled = patchCells(currentGridKey, ownerUserId, days, (prev) =>
makeEntryCell({
userId: ownerUserId!,
date: days[0],
projectId:
body.project_id === undefined
? (prev?.project_id ?? null)
: body.project_id,
category: body.category ?? prev?.category ?? "work",
note: body.note ?? prev?.note ?? "",
rangeFrom: body.date_from,
rangeTo: body.date_to,
entryId: id,
}),
const rolled = patchCells(
currentGridKey,
ownerUserId,
days,
(prev) => {
const existing = prev.find((c) => c.entryId === id) ?? null;
const updated = makeEntryCell({
userId: ownerUserId!,
date: days[0],
projectId:
body.project_id === undefined
? (existing?.project_id ?? null)
: body.project_id,
category: body.category ?? existing?.category ?? "work",
note: body.note ?? existing?.note ?? "",
rangeFrom: body.date_from,
rangeTo: body.date_to,
entryId: id,
});
return [updated, ...prev.filter((c) => c.entryId !== id)];
},
);
(updateEntry as any)._rolled = rolled;
}
@@ -338,24 +348,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
const grid = qc.getQueryData<GridData>(currentGridKey as any);
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [, cell] of Object.entries(byDate)) {
if (
cell &&
cell.entryId === vars.id &&
cell.rangeFrom &&
cell.rangeTo
) {
const days = eachDay(cell.rangeFrom, cell.rangeTo);
const rolled = patchCells(
currentGridKey,
Number(uidStr),
days,
() => null,
);
(deleteEntry as any)._rolled = rolled;
let range: { from: string; to: string } | null = null;
for (const cells of Object.values(byDate)) {
const hit = cells.find(
(c) => c.entryId === vars.id && c.rangeFrom && c.rangeTo,
);
if (hit) {
range = { from: hit.rangeFrom!, to: hit.rangeTo! };
break;
}
}
if (range) {
const days = eachDay(range.from, range.to);
const rolled = patchCells(
currentGridKey,
Number(uidStr),
days,
(prev) => prev.filter((c) => c.entryId !== vars.id),
);
(deleteEntry as any)._rolled = rolled;
break;
}
}
}
invalidate();
@@ -375,7 +388,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
currentGridKey,
vars.user_id,
[vars.shift_date],
() =>
(prev) => [
makeOverrideCell({
userId: vars.user_id,
date: vars.shift_date,
@@ -384,6 +397,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
note: vars.note,
overrideId: id,
}),
...prev,
],
);
(createOverride as any)._rolled = rolled;
invalidate();
@@ -411,21 +426,30 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
const grid = qc.getQueryData<GridData>(currentGridKey as any);
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) {
if (cell && cell.overrideId === vars.id) {
for (const [date, cells] of Object.entries(byDate)) {
if (cells.some((c) => c.overrideId === vars.id)) {
const rolled = patchCells(
currentGridKey,
Number(uidStr),
[date],
(prev) =>
makeOverrideCell({
(prev) => {
const existing =
prev.find((c) => c.overrideId === vars.id) ?? null;
const updated = makeOverrideCell({
userId: Number(uidStr),
date,
projectId: vars.body.project_id ?? prev?.project_id ?? null,
category: vars.body.category ?? prev?.category ?? "work",
note: vars.body.note ?? prev?.note ?? "",
projectId:
vars.body.project_id ?? existing?.project_id ?? null,
category:
vars.body.category ?? existing?.category ?? "work",
note: vars.body.note ?? existing?.note ?? "",
overrideId: vars.id,
}),
});
return [
updated,
...prev.filter((c) => c.overrideId !== vars.id),
];
},
);
(updateOverride as any)._rolled = rolled;
break;
@@ -446,13 +470,13 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
const grid = qc.getQueryData<GridData>(currentGridKey as any);
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) {
if (cell && cell.overrideId === vars.id) {
for (const [date, cells] of Object.entries(byDate)) {
if (cells.some((c) => c.overrideId === vars.id)) {
const rolled = patchCells(
currentGridKey,
Number(uidStr),
[date],
() => null,
(prev) => prev.filter((c) => c.overrideId !== vars.id),
);
(deleteOverride as any)._rolled = rolled;
break;
@@ -464,6 +488,20 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
},
});
const bulkCreate = useMutation({
mutationFn: (body: any) =>
apiCall("/api/admin/plan/entries/bulk", {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
}),
onSuccess: () => {
// No optimistic patch — bulk can touch many cells; just invalidate and
// let the grid refetch the authoritative state.
invalidate();
},
});
// Roll back an optimistic patch on mutation error. Called from
// PlanWork's mutation wrappers via `rollbackMutation(mutation, key)`.
// `mutation` is a TanStack mutation result with a `_rolled` snapshot stashed
@@ -472,15 +510,15 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
// directly without the "weak type" mismatch a `{ _rolled? }` param causes.
function rollbackMutation(mutation: unknown, userId: number) {
const stash = mutation as {
_rolled?: Record<string, ResolvedCell | null> | null;
_rolled?: Record<string, ResolvedCell[]> | null;
};
if (!stash._rolled) return;
const prev = qc.getQueryData<GridData>(currentGridKey as any);
if (!prev) return;
const userPrev = prev.cells[userId] ?? {};
const userNext = { ...userPrev };
for (const [date, cell] of Object.entries(stash._rolled)) {
userNext[date] = cell;
for (const [date, cells] of Object.entries(stash._rolled)) {
userNext[date] = cells;
}
qc.setQueryData(currentGridKey, {
...prev,
@@ -510,6 +548,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
createOverride,
updateOverride,
deleteOverride,
bulkCreate,
invalidate,
// Exposed so PlanWork can roll back an optimistic patch when a
// mutation throws. Pass the failed mutation and the userId it
@@ -518,10 +557,18 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
};
}
export function getCells(
grid: GridData | undefined,
userId: number,
date: string,
): ResolvedCell[] {
return grid?.cells?.[userId]?.[date] ?? [];
}
export function getCell(
grid: GridData | undefined,
userId: number,
date: string,
): ResolvedCell | null {
return grid?.cells?.[userId]?.[date] ?? null;
return getCells(grid, userId, date)[0] ?? null;
}

View File

@@ -0,0 +1,61 @@
import { queryOptions } from "@tanstack/react-query";
import { jsonQuery } from "../apiAdapter";
export interface AiUsage {
configured: boolean;
month_spend_usd: number;
budget_usd: number;
remaining_usd: number;
}
export interface ExtractedInvoice {
supplier_name: string;
invoice_number: string | null;
amount: number;
currency: string;
vat_rate: number;
issue_date: string | null;
due_date: string | null;
description: string | null;
}
export interface StoredChatMessage {
role: "user" | "assistant";
content: string;
created_at: string;
}
export const aiUsageOptions = () =>
queryOptions({
queryKey: ["ai", "usage"],
queryFn: () => jsonQuery<AiUsage>("/api/admin/ai/usage"),
staleTime: 30_000,
});
export interface Conversation {
id: number;
title: string;
updated_at: string;
}
export const aiConversationsOptions = () =>
queryOptions({
queryKey: ["ai", "conversations"],
queryFn: () =>
jsonQuery<{ conversations: Conversation[] }>(
"/api/admin/ai/conversations",
),
staleTime: 30_000,
});
export const aiConversationMessagesOptions = (id: number) =>
queryOptions({
queryKey: ["ai", "conversation", id, "messages"],
queryFn: () =>
jsonQuery<{ messages: StoredChatMessage[] }>(
`/api/admin/ai/conversations/${id}/messages`,
),
// Re-read the DB on each mount/selection (no stale-cache resurrection).
staleTime: Infinity,
gcTime: 0,
});

View File

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

View File

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

View File

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

View File

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

24
src/admin/pages/Odin.tsx Normal file
View File

@@ -0,0 +1,24 @@
import Typography from "@mui/material/Typography";
import { PageEnter } from "../ui";
import { useAuth } from "../context/AuthContext";
import OdinChat from "../components/odin/OdinChat";
export default function Odin() {
const { hasPermission } = useAuth();
if (!hasPermission("ai.use")) {
return (
<PageEnter>
<Typography variant="body1" color="text.secondary">
Nemáte oprávnění pro AI asistenta.
</Typography>
</PageEnter>
);
}
return (
<PageEnter>
<OdinChat />
</PageEnter>
);
}

View File

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

View File

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

View File

@@ -8,16 +8,22 @@ import { useAlert } from "../context/AlertContext";
import {
usePlanWork,
getCell,
getCells,
type ModalMode as HookModalMode,
} from "../hooks/usePlanWork";
import type { PlanCellModalMode } from "../components/PlanCellModal";
import PlanGrid from "../components/PlanGrid";
import PlanCellModal from "../components/PlanCellModal";
import PlanCategoriesModal from "../components/PlanCategoriesModal";
import BulkPlanModal, { type BulkPlanForm } from "../components/BulkPlanModal";
import Forbidden from "../components/Forbidden";
import { Button, Alert, LoadingState, PageEnter } from "../ui";
import { projectListOptions, type Project } from "../lib/queries/projects";
import { planCategoriesOptions, type PlanCategory } from "../lib/queries/plan";
import {
planCategoriesOptions,
type PlanCategory,
type ResolvedCell,
} from "../lib/queries/plan";
// plan.css is imported once globally in AdminApp.tsx — no per-page re-import.
const MONTH_NAMES = [
@@ -123,6 +129,7 @@ export default function PlanWork() {
createOverride,
updateOverride,
deleteOverride,
bulkCreate,
rollbackMutation,
} = usePlanWork({ canEdit });
@@ -135,6 +142,84 @@ export default function PlanWork() {
const [catModalOpen, setCatModalOpen] = useState(false);
const [bulkOpen, setBulkOpen] = useState(false);
const [bulkSubmitting, setBulkSubmitting] = useState(false);
const [bulkForm, setBulkForm] = useState<BulkPlanForm>(() => {
const today = todayIsoLocal();
return {
date_from: today,
date_to: today,
is_range: false,
user_ids: [],
include_weekends: false,
project_id: "",
category: "work",
note: "",
};
});
const planUsers = useMemo(() => grid?.users ?? [], [grid]);
const toggleBulkUser = useCallback((userId: number) => {
setBulkForm((prev) => ({
...prev,
user_ids: prev.user_ids.includes(String(userId))
? prev.user_ids.filter((u) => u !== String(userId))
: [...prev.user_ids, String(userId)],
}));
}, []);
const toggleAllBulkUsers = useCallback(() => {
const allIds = (grid?.users ?? []).map((u) => String(u.id));
if (allIds.length === 0) return; // grid not yet loaded — no-op
setBulkForm((prev) => ({
...prev,
user_ids: prev.user_ids.length === allIds.length ? [] : allIds,
}));
}, [grid]);
const submitBulk = useCallback(async () => {
if (bulkForm.user_ids.length === 0) return;
setBulkSubmitting(true);
try {
const data: any = await bulkCreate.mutateAsync({
user_ids: bulkForm.user_ids.map(Number),
date_from: bulkForm.date_from,
date_to: bulkForm.is_range ? bulkForm.date_to : bulkForm.date_from,
include_weekends: bulkForm.include_weekends,
project_id: bulkForm.project_id ? Number(bulkForm.project_id) : null,
category: bulkForm.category,
note: bulkForm.note,
});
// apiCall returns the full envelope { success, data, message };
// the summary counts are under .data
const summary = data?.data ?? data;
const skipped =
summary?.skipped_days > 0
? ` ${summary.skipped_days} dní přeskočeno (limit 3 na den).`
: "";
alert.success(
`Vytvořeno ${summary?.created_days ?? 0} záznamů pro ${summary?.users ?? 0} zaměstnanců.${skipped}`,
);
setBulkOpen(false);
// Reset the volatile parts so reopening starts clean (project /
// category / weekends stay sticky — users often repeat those).
const today = todayIsoLocal();
setBulkForm((prev) => ({
...prev,
date_from: today,
date_to: today,
is_range: false,
user_ids: [],
note: "",
}));
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba při ukládání");
} finally {
setBulkSubmitting(false);
}
}, [bulkForm, bulkCreate, alert]);
// `lastMutated` is the (userId, date) of the most recent successful
// mutation. We pass it to PlanGrid as `pulseKey`; the matching cell
// gets a one-shot CSS pulse animation. We clear it after 700ms (the
@@ -193,84 +278,86 @@ export default function PlanWork() {
// Null when the modal is closed or in a "create" state with no source cell.
const [modalCell, setModalCell] = useState<ReturnType<typeof getCell>>(null);
// Open the create form for a brand-new record. `source` picks the layer:
// "entry" (default) opens the normal create form; "override" opens the
// single-day create-override form. The day panel passes "override" when the
// day is in exception mode so the new record lands in the same layer that's
// showing (otherwise resolveCell would hide a new entry behind the override).
const openCreate = useCallback(
(userId: number, date: string) => {
(userId: number, date: string, source: "entry" | "override" = "entry") => {
setModalCell(null);
setHookModal({ kind: "create", userId, date });
if (source === "override") {
setHookModal({ kind: "create-override", userId, date });
} else {
setHookModal({ kind: "create", userId, date });
}
},
[setHookModal],
);
const openCell = useCallback(
(userId: number, date: string) => {
const cell = getCell(grid, userId, date);
(userId: number, date: string, cells: ResolvedCell[]) => {
const primary = cells[0] ?? null;
// Past-date guard: the server rejects create/edit on past dates with
// a 403 (see assertNotPastDate in plan.service.ts). To keep the user
// out of the "click → modal opens → error toast" state, route any
// past-day click to view mode (or to no-op if there's no record).
if (isPastDate(date, todayIsoLocal())) {
if (!cell) {
// Empty past cell — nothing to show or edit.
return;
}
setModalCell(cell);
if (!primary) return;
setModalCell(primary);
setHookModal({ kind: "view", userId, date });
return;
}
if (!cell) {
// Empty cell — open the create modal if the user can edit, otherwise
// there's nothing to view.
if (cells.length === 0) {
if (canEdit) openCreate(userId, date);
return;
}
if (!canEdit) {
setModalCell(primary);
setHookModal({ kind: "view", userId, date });
return;
}
setHookModal({ kind: "day", userId, date });
},
[canEdit, openCreate, setHookModal],
);
// Open the correct editor for one record from the day panel. This is the
// per-record version of the old openCell branch logic: a multi-day entry
// routes through the day-in-range chooser; a single-day entry → edit-range;
// an override → edit-override.
const editRecord = useCallback(
(cell: ReturnType<typeof getCell>, userId: number, date: string) => {
if (!cell) return;
setModalCell(cell);
if (cell.source === "entry" && cell.entryId !== null) {
if (canEdit) {
// A multi-day entry clicked on a single day → "day-in-range" so the
// user can decide between editing the range or creating a one-day
// override.
if (
cell.rangeFrom &&
cell.rangeTo &&
cell.rangeFrom !== cell.rangeTo
) {
setHookModal({
kind: "day-in-range",
entryId: cell.entryId,
userId,
date,
});
return;
}
if (cell.rangeFrom && cell.rangeTo && cell.rangeFrom !== cell.rangeTo) {
setHookModal({
kind: "day-in-range",
entryId: cell.entryId,
userId,
date,
});
} else {
setHookModal({
kind: "edit-range",
entryId: cell.entryId,
userId,
date,
});
return;
}
// Read-only view
setHookModal({ kind: "view", userId, date });
return;
}
if (cell.source === "override" && cell.overrideId !== null) {
if (canEdit) {
setHookModal({
kind: "edit-override",
overrideId: cell.overrideId,
userId,
date,
});
} else {
setHookModal({ kind: "view", userId, date });
}
return;
setHookModal({
kind: "edit-override",
overrideId: cell.overrideId,
userId,
date,
});
}
// No source — treat as empty
if (canEdit) openCreate(userId, date);
},
[grid, canEdit, openCreate, setHookModal],
[setHookModal],
);
const closeModal = useCallback(() => {
@@ -280,11 +367,14 @@ export default function PlanWork() {
// Switch the modal from "day-in-range" to "edit-range" mode, keeping the
// same cell context so the EditForm opens with the range's values.
// Uses `modalCell` — the record the user actually clicked in the day panel
// (captured by editRecord) — NOT getCell (which returns the PRIMARY record).
// On a day with 2+ records these differ; using the primary would edit the
// wrong range. modalCell is already set to the clicked record at this point
// (editRecord → day-in-range → here).
const switchToEditRange = useCallback(
(entryId: number, userId: number, date: string) => {
const cell = getCell(grid, userId, date);
if (!cell) return;
setModalCell(cell);
if (!modalCell) return;
setHookModal({
kind: "edit-range",
entryId,
@@ -292,7 +382,7 @@ export default function PlanWork() {
date,
});
},
[grid, setHookModal],
[modalCell, setHookModal],
);
// --- Mutation wrappers -----------------------------------------------------
@@ -327,8 +417,9 @@ export default function PlanWork() {
let firstDate: string | null = null;
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) {
if (cell && cell.entryId === id) {
for (const [date, cells] of Object.entries(byDate)) {
const hit = cells.find((c) => c.entryId === id);
if (hit) {
userId = Number(uidStr);
firstDate = body.date_from ?? date;
break;
@@ -357,10 +448,11 @@ export default function PlanWork() {
let firstDate: string | null = null;
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [date, cell] of Object.entries(byDate)) {
if (cell && cell.entryId === id) {
for (const [date, cells] of Object.entries(byDate)) {
const hit = cells.find((c) => c.entryId === id);
if (hit) {
userId = Number(uidStr);
firstDate = cell.rangeFrom ?? date;
firstDate = hit.rangeFrom ?? date;
break;
}
}
@@ -402,8 +494,9 @@ export default function PlanWork() {
let date: string | null = null;
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [d, cell] of Object.entries(byDate)) {
if (cell && cell.overrideId === id) {
for (const [d, cells] of Object.entries(byDate)) {
const hit = cells.find((c) => c.overrideId === id);
if (hit) {
userId = Number(uidStr);
date = d;
break;
@@ -431,8 +524,9 @@ export default function PlanWork() {
let date: string | null = null;
if (grid) {
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
for (const [d, cell] of Object.entries(byDate)) {
if (cell && cell.overrideId === id) {
for (const [d, cells] of Object.entries(byDate)) {
const hit = cells.find((c) => c.overrideId === id);
if (hit) {
userId = Number(uidStr);
date = d;
break;
@@ -455,11 +549,14 @@ export default function PlanWork() {
);
// "Create override from range" — turn a multi-day entry into a one-day
// override for the clicked date. We look up the cell's source entry and
// create a new override mirroring its fields, locked to a single date.
// override for the clicked date. We mirror the CLICKED record's fields
// (modalCell, captured by editRecord) — NOT getCell, which returns the
// PRIMARY record. On a day with 2+ records the clicked entry can differ
// from the primary; carving from the primary would copy the wrong
// project/category/note into the override.
const createOverrideFromRange = useCallback(
async (entryId: number, userId: number, date: string) => {
const cell = getCell(grid, userId, date);
const cell = modalCell;
if (!cell) {
alert.error("Nepodařilo se najít zdrojový záznam");
return;
@@ -483,7 +580,7 @@ export default function PlanWork() {
// symmetry with the modal contract.
void entryId;
},
[grid, createOverride, alert, firePulse, rollbackMutation],
[modalCell, createOverride, alert, firePulse, rollbackMutation],
);
// --- Modal key for remount-on-mode-change ----------------------------------
@@ -504,6 +601,9 @@ export default function PlanWork() {
const modalMode: PlanCellModalMode = useMemo(() => {
if (hookModal.kind === "closed") return { kind: "closed" };
if (hookModal.kind === "create") return hookModal;
// create-override carries the same userId/date payload as create and needs
// no merged cell/range — pass it straight through (EditForm handles it).
if (hookModal.kind === "create-override") return hookModal;
if (hookModal.kind === "view") {
if (!modalCell) return { kind: "closed" };
return {
@@ -536,8 +636,16 @@ export default function PlanWork() {
},
} as PlanCellModalMode;
}
if (hookModal.kind === "day") {
return {
kind: "day",
userId: hookModal.userId,
date: hookModal.date,
cells: getCells(grid, hookModal.userId, hookModal.date),
};
}
return { kind: "closed" };
}, [hookModal, modalCell]);
}, [hookModal, modalCell, grid]);
if (!canEdit && !hasPermission("attendance.record")) {
// Hard block for users who have neither manage nor record permission.
@@ -645,6 +753,15 @@ export default function PlanWork() {
Správa kategorií
</Button>
)}
{canEdit && (
<Button
variant="outlined"
color="inherit"
onClick={() => setBulkOpen(true)}
>
Hromadné přiřazení
</Button>
)}
</Box>
{gridLoading && <LoadingState />}
@@ -691,12 +808,27 @@ export default function PlanWork() {
onDeleteOverride={deleteOverrideFn}
onCreateOverrideFromRange={createOverrideFromRange}
onSwitchToEditRange={switchToEditRange}
onAddRecord={openCreate}
onEditRecord={editRecord}
/>
<PlanCategoriesModal
isOpen={catModalOpen}
onClose={() => setCatModalOpen(false)}
categories={categories}
/>
<BulkPlanModal
isOpen={bulkOpen}
onClose={() => setBulkOpen(false)}
form={bulkForm}
setForm={setBulkForm}
users={planUsers}
projects={projects}
categories={categories}
onSubmit={submitBulk}
submitting={bulkSubmitting}
toggleUser={toggleBulkUser}
toggleAllUsers={toggleAllBulkUsers}
/>
</PageEnter>
);
}

View File

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

View File

@@ -932,7 +932,7 @@ export default function ReceivedInvoices({
<Box sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}>
<Box sx={{ flex: 1 }}>
<Field
label="Částka"
label="Částka s DPH"
required
error={uploadErrors[idx]?.amount}
>
@@ -1096,7 +1096,7 @@ export default function ReceivedInvoices({
sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}
>
<Box sx={{ flex: 1 }}>
<Field label="Částka" required>
<Field label="Částka s DPH" required>
<TextField
type="number"
slotProps={{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
import { type ReactNode } from "react";
import OdinMark from "../components/odin/OdinMark";
export interface MenuItem {
path: string;
@@ -38,6 +39,13 @@ export const menuSections: MenuSection[] = [
</svg>
),
},
{
path: "/odin",
label: "Odin",
permission: "ai.use",
end: true,
icon: <OdinMark size={22} />,
},
],
},
{

View File

@@ -16,6 +16,7 @@ export const STATUS_LABELS: Record<string, string> = {
away: "Přestávka",
out: "Nepřihlášen",
leave: "Nepřítomen",
absent: "Nepřítomen",
};
// Re-exported from the single source of truth so the dashboard activity feed

View File

@@ -61,6 +61,10 @@ export const config = {
),
},
anthropic: {
apiKey: process.env.ANTHROPIC_API_KEY || "",
},
nas: {
path: process.env.NAS_PATH || "Z:/02_PROJEKTY",
financialsPath: process.env.NAS_FINANCIALS_PATH || "",

230
src/routes/admin/ai.ts Normal file
View File

@@ -0,0 +1,230 @@
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
import multipart from "@fastify/multipart";
import { requirePermission } from "../../middleware/auth";
import { success, error, parseId } from "../../utils/response";
import { parseBody } from "../../schemas/common";
import {
AiChatSchema,
AiBudgetSchema,
AiHistoryAppendSchema,
AiCreateConversationSchema,
AiRenameConversationSchema,
} from "../../schemas/ai.schema";
import { logAudit } from "../../services/audit";
import { config } from "../../config/env";
import {
isConfigured,
assertBudgetAvailable,
getMonthSpendUsd,
getBudgetUsd,
setBudgetUsd,
chat,
extractInvoice,
listConversations,
createConversation,
getConversationMessages,
appendConversationMessages,
renameConversation,
deleteConversation,
type ExtractedInvoice,
} from "../../services/ai.service";
export default async function aiRoutes(app: FastifyInstance): Promise<void> {
await app.register(multipart, {
// Cap files per request: the budget re-check already bounds *spend* mid-batch,
// but this bounds the work (one vision call per file) of a single request.
limits: { fileSize: config.nas.maxUploadSize, files: 20 },
});
// GET /api/admin/ai/usage — current-month spend + budget
app.get(
"/usage",
{ preHandler: requirePermission("ai.use") },
async (_request: FastifyRequest, reply: FastifyReply) => {
const [month_spend_usd, budget_usd] = await Promise.all([
getMonthSpendUsd(),
getBudgetUsd(),
]);
return success(reply, {
configured: isConfigured(),
month_spend_usd: Math.round(month_spend_usd * 1_000_000) / 1_000_000,
budget_usd,
remaining_usd: Math.max(0, budget_usd - month_spend_usd),
});
},
);
// PUT /api/admin/ai/budget — set the monthly budget (admins have ai.use)
app.put(
"/budget",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const body = parseBody(AiBudgetSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const { budget_usd } = body.data;
await setBudgetUsd(budget_usd);
await logAudit({
request,
authData: request.authData,
action: "update",
entityType: "company_settings",
description: `Změněn měsíční rozpočet AI na $${budget_usd}`,
newValues: { ai_monthly_budget_usd: budget_usd },
});
return success(reply, { budget_usd }, 200, "Rozpočet uložen");
},
);
// POST /api/admin/ai/chat
app.post(
"/chat",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
if (!isConfigured()) return error(reply, "AI není nakonfigurováno", 503);
const body = parseBody(AiChatSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const budgetErr = await assertBudgetAvailable();
if (budgetErr) return error(reply, budgetErr.error, budgetErr.status);
const { reply: text } = await chat(
body.data.messages,
request.authData!.userId,
);
const [budgetAfter, spendAfter] = await Promise.all([
getBudgetUsd(),
getMonthSpendUsd(),
]);
const remaining_usd = Math.max(0, budgetAfter - spendAfter);
return success(reply, { reply: text, remaining_usd });
},
);
// POST /api/admin/ai/extract-invoices — multipart PDF files
app.post(
"/extract-invoices",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
if (!isConfigured()) return error(reply, "AI není nakonfigurováno", 503);
const budgetErr = await assertBudgetAvailable();
if (budgetErr) return error(reply, budgetErr.error, budgetErr.status);
const parts = request.parts();
const results: Array<{
file_name: string;
fields?: ExtractedInvoice;
error?: string;
}> = [];
for await (const part of parts) {
if (part.type !== "file") continue;
const buf = await part.toBuffer();
try {
const fields = await extractInvoice(buf, request.authData!.userId);
results.push({ file_name: part.filename || "faktura.pdf", fields });
} catch (e) {
request.log.error(e, "extractInvoice failed");
results.push({
file_name: part.filename || "faktura.pdf",
error: "Nepodařilo se přečíst fakturu",
});
}
// Re-check the budget between files so one batch can't blow far past it.
const over = await assertBudgetAvailable();
if (over) break;
}
if (results.length === 0)
return error(reply, "Nebyl nahrán žádný soubor", 400);
return success(reply, { invoices: results });
},
);
// GET /conversations — this user's conversations (stable order)
app.get(
"/conversations",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const conversations = await listConversations(request.authData!.userId);
return success(reply, { conversations });
},
);
// POST /conversations — create
app.post(
"/conversations",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const body = parseBody(AiCreateConversationSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const conversation = await createConversation(
request.authData!.userId,
body.data.title,
);
return success(reply, { conversation });
},
);
// GET /conversations/:id/messages
app.get(
"/conversations/:id/messages",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const result = await getConversationMessages(
request.authData!.userId,
id,
);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, { messages: result.data });
},
);
// POST /conversations/:id/messages — append turns
app.post(
"/conversations/:id/messages",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const body = parseBody(AiHistoryAppendSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const result = await appendConversationMessages(
request.authData!.userId,
id,
body.data.messages,
);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, result.data);
},
);
// PATCH /conversations/:id — rename
app.patch(
"/conversations/:id",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const body = parseBody(AiRenameConversationSchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const result = await renameConversation(
request.authData!.userId,
id,
body.data.title,
);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, { conversation: result.data });
},
);
// DELETE /conversations/:id
app.delete(
"/conversations/:id",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const id = parseId((request.params as { id: string }).id, reply);
if (id === null) return;
const result = await deleteConversation(request.authData!.userId, id);
if ("error" in result) return error(reply, result.error, result.status);
return success(reply, result.data);
},
);
}

View File

@@ -4,6 +4,7 @@ import { requireAuth } from "../../middleware/auth";
import { success } from "../../utils/response";
import { localTimeStr } from "../../utils/date";
import { toCzk } from "../../services/exchange-rates";
import { resolveCell } from "../../services/plan.service";
export default async function dashboardRoutes(
fastify: FastifyInstance,
@@ -42,9 +43,33 @@ export default async function dashboardRoutes(
result.my_shift = { has_ongoing: myShift !== null };
}
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
// resolveCell returns 03 records (override-beats-range layering); an empty
// array means the user has plan access but nothing is scheduled today. Each
// record's category key is enriched with its label + colour so the widget
// needs no extra query. todayStr uses local (Europe/Prague) calendar date —
// the plan's @db.Date day.
if (has("attendance.record") || has("attendance.manage")) {
const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
const cells = await resolveCell(userId, todayStr);
result.today_plan = await Promise.all(
cells.map(async (cell) => {
const cat = await prisma.plan_categories.findUnique({
where: { key: cell.category },
select: { label: true, color: true },
});
return {
...cell,
category_label: cat?.label ?? cell.category,
category_color: cat?.color ?? null,
};
}),
);
}
// Attendance admin — only for attendance.manage
if (has("attendance.manage")) {
const [todayAttendance, onLeaveToday, usersCount] = await Promise.all([
const [todayAttendance, onLeaveToday, activeUsers] = await Promise.all([
prisma.attendance.findMany({
where: {
shift_date: { gte: todayStart, lt: todayEnd },
@@ -64,8 +89,13 @@ export default async function dashboardRoutes(
users: { select: { id: true, first_name: true, last_name: true } },
},
}),
prisma.users.count({ where: { is_active: true } }),
prisma.users.findMany({
where: { is_active: true },
select: { id: true, first_name: true, last_name: true },
orderBy: [{ last_name: "asc" }, { first_name: "asc" }],
}),
]);
const usersCount = activeUsers.length;
const userAttendanceMap = new Map<number, (typeof todayAttendance)[0]>();
for (const a of todayAttendance) {
@@ -128,6 +158,25 @@ export default async function dashboardRoutes(
});
}
// Show every active employee — those with no attendance record today
// appear as "absent" so the card reflects the whole team, not just those
// who clocked in or are on leave.
const recordedUserIds = new Set<number>([
...userAttendanceMap.keys(),
...leaveUserIds,
]);
for (const user of activeUsers) {
if (recordedUserIds.has(user.id)) continue;
attendanceUsers.push({
user_id: user.id,
name: `${user.first_name} ${user.last_name}`,
initials:
`${user.first_name?.charAt(0) ?? ""}${user.last_name?.charAt(0) ?? ""}`.toUpperCase(),
status: "absent",
arrived_at: null,
});
}
result.attendance = {
present_today: presentCount,
total_active: usersCount,

View File

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

View File

@@ -15,6 +15,7 @@ import {
UpdatePlanOverrideSchema,
PlanRangeQuerySchema,
PlanGridQuerySchema,
BulkPlanEntrySchema,
} from "../../schemas/plan.schema";
import {
resolveGrid,
@@ -27,6 +28,7 @@ import {
deleteOverride,
listEntries,
listOverrides,
bulkCreateEntries,
} from "../../services/plan.service";
import {
CreatePlanCategorySchema,
@@ -259,6 +261,29 @@ export default async function planRoutes(app: FastifyInstance) {
},
);
// --- POST /plan/entries/bulk ---
app.post(
"/entries/bulk",
{ preHandler: requirePermission("attendance.manage") },
async (request: FastifyRequest, reply: FastifyReply) => {
const body = parseBody(BulkPlanEntrySchema, request.body);
if ("error" in body) return error(reply, body.error, 400);
const result = await bulkCreateEntries(
body.data!,
request.authData!.userId,
);
if ("error" in result) return error(reply, result.error, result.status);
await logAudit({
request,
authData: request.authData,
action: "create",
entityType: "work_plan_entry",
description: `Hromadné přiřazení: ${body.data!.category}${result.data.users} zaměstnanců, ${body.data!.date_from}${body.data!.date_to} (${result.data.created_days} dní)`,
});
return success(reply, result.data, 201, "Hromadné přiřazení dokončeno");
},
);
// --- PATCH /plan/entries/:id ---
app.patch(
"/entries/:id",
@@ -328,18 +353,6 @@ export default async function planRoutes(app: FastifyInstance) {
);
if ("error" in result) return error(reply, result.error, result.status);
// If the create replaced an existing active override, log the soft-delete first.
if (result.replacedData) {
await logAudit({
request,
authData: request.authData,
action: "delete",
entityType: "work_plan_override",
entityId: (result.replacedData as any).id,
oldValues: result.replacedData as Record<string, unknown>,
description: result.replacedDescription,
});
}
await logAudit({
request,
authData: request.authData,

View File

@@ -22,6 +22,15 @@ const VALID_STATUSES = ["unpaid", "paid"] as const;
function roundMoney(n: number): number {
return Math.round(n * 100) / 100;
}
/**
* VAT contained WITHIN a gross (VAT-inclusive) amount. `amount` is the total to
* pay including tax, so the tax portion is gross * rate / (100 + rate) — e.g.
* 22542.91 @ 21% → 3912.41 (base 18630.50). Returns 0 when there is no VAT.
*/
export function vatFromGross(gross: number, rate: number): number {
return rate > 0 ? roundMoney((gross * rate) / (100 + rate)) : 0;
}
const ALLOWED_SORT_FIELDS = [
"id",
"supplier_name",
@@ -284,11 +293,8 @@ export default async function receivedInvoicesRoutes(
const meta = invoicesMeta[i] || {};
const amount = Number(meta.amount ?? 0);
const vatRate = Number(meta.vat_rate ?? 21);
// Amount is net — VAT = amount * rate / 100
const vatAmount =
vatRate > 0
? Math.round(((amount * vatRate) / 100) * 100) / 100
: 0;
// `amount` is the GROSS total (VAT included); VAT is the portion within it.
const vatAmount = vatFromGross(amount, vatRate);
const issueDate = meta.issue_date
? new Date(String(meta.issue_date))
@@ -448,7 +454,7 @@ export default async function receivedInvoicesRoutes(
}
}
// Recalculate vat_amount when amount or vat_rate changes (matching PHP)
// Recalculate vat_amount when amount (gross) or vat_rate changes.
const finalAmount =
body.amount !== undefined
? Number(body.amount)
@@ -457,9 +463,8 @@ export default async function receivedInvoicesRoutes(
body.vat_rate !== undefined
? Number(body.vat_rate)
: Number(existing.vat_rate);
// Amount is net — VAT = amount * rate / 100
const computedVat =
finalVatRate > 0 ? roundMoney((finalAmount * finalVatRate) / 100) : 0;
// `amount` is the GROSS total (VAT included); VAT is the portion within it.
const computedVat = vatFromGross(finalAmount, finalVatRate);
// Auto-set paid_date when status transitions to paid (matching PHP)
const newStatus =

40
src/schemas/ai.schema.ts Normal file
View File

@@ -0,0 +1,40 @@
import { z } from "zod";
export const AiChatSchema = z.object({
messages: z
.array(
z.object({
role: z.enum(["user", "assistant"]),
content: z.string().min(1).max(8000),
}),
)
.min(1, "Zpráva je povinná")
.max(100, "Příliš mnoho zpráv"),
});
export const AiHistoryAppendSchema = z.object({
messages: z
.array(
z.object({
role: z.enum(["user", "assistant"]),
content: z.string().min(1).max(8000),
}),
)
.min(1, "Žádné zprávy")
.max(20, "Příliš mnoho zpráv"),
});
export const AiCreateConversationSchema = z.object({
title: z.string().max(255).optional(),
});
export const AiRenameConversationSchema = z.object({
title: z.string().min(1, "Název je povinný").max(255),
});
export const AiBudgetSchema = z.object({
budget_usd: z
.union([z.number(), z.string()])
.transform((v) => Number(v))
.refine((n) => Number.isFinite(n) && n >= 0, "Neplatný rozpočet"),
});

View File

@@ -83,3 +83,27 @@ export const PlanGridQuerySchema = z.object({
date_to: isoDate,
view: z.enum(["week", "month"]).default("week"),
});
export const BulkPlanEntrySchema = z
.object({
user_ids: z
.array(intFromForm)
.min(1, "Vyberte alespoň jednoho zaměstnance")
.transform((ids) => [...new Set(ids)]),
date_from: isoDate,
date_to: isoDate,
include_weekends: z
.union([z.boolean(), z.string()])
.transform((v) => v === true || v === "true" || v === "1")
.default(false),
project_id: z
.union([z.number(), z.string(), z.null()])
.transform((v) => (v === null ? null : Number(v)))
.nullish(),
category: planCategoryEnum.default("work"),
note: z.string().max(500, "Maximálně 500 znaků").default(""),
})
.refine((v) => v.date_to >= v.date_from, {
message: "Datum do musí být stejné nebo po datumu od",
path: ["date_to"],
});

View File

@@ -35,6 +35,7 @@ import ordersPdfRoutes from "./routes/admin/orders-pdf";
import projectFilesRoutes from "./routes/admin/project-files";
import warehouseRoutes from "./routes/admin/warehouse";
import planRoutes from "./routes/admin/plan";
import aiRoutes from "./routes/admin/ai";
const app = Fastify({
logger: {
@@ -152,6 +153,7 @@ async function start() {
});
await app.register(warehouseRoutes, { prefix: "/api/admin/warehouse" });
await app.register(planRoutes, { prefix: "/api/admin/plan" });
await app.register(aiRoutes, { prefix: "/api/admin/ai" });
// --- Frontend: Vite dev middleware (dev only) ---
if (!config.isProduction) {

352
src/services/ai.service.ts Normal file
View File

@@ -0,0 +1,352 @@
import Anthropic from "@anthropic-ai/sdk";
import prisma from "../config/database";
import { config } from "../config/env";
/** The single model this assistant uses (Phase 1). */
export const AI_MODEL = "claude-sonnet-4-6";
/** Per-token USD pricing. Sonnet 4.6 = $3 / $15 per 1M (input / output). */
const PRICING: Record<string, { input: number; output: number }> = {
"claude-sonnet-4-6": { input: 3 / 1_000_000, output: 15 / 1_000_000 },
};
const DEFAULT_BUDGET_USD = 50;
export function isConfigured(): boolean {
return !!config.anthropic.apiKey;
}
/** Lazily build the SDK client; throws a typed result upstream if unconfigured. */
function client(): Anthropic {
return new Anthropic({ apiKey: config.anthropic.apiKey });
}
export function computeCostUsd(
model: string,
inputTokens: number,
outputTokens: number,
): number {
const p = PRICING[model] ?? PRICING[AI_MODEL];
return inputTokens * p.input + outputTokens * p.output;
}
export async function recordUsage(args: {
userId: number | null;
kind: string;
model: string;
inputTokens: number;
outputTokens: number;
}): Promise<void> {
await prisma.ai_usage.create({
data: {
user_id: args.userId,
kind: args.kind,
model: args.model,
input_tokens: args.inputTokens,
output_tokens: args.outputTokens,
cost_usd: computeCostUsd(args.model, args.inputTokens, args.outputTokens),
},
});
}
// Budget window edge uses the UTC month boundary (ai_usage.created_at is a UTC
// @db.Timestamp). At month turnover this is offset from Prague local time by the
// UTC offset for ~1-2h — acceptable for a soft monthly budget, and stable.
function startOfMonthUtc(): Date {
const d = new Date();
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
}
export async function getMonthSpendUsd(): Promise<number> {
const agg = await prisma.ai_usage.aggregate({
_sum: { cost_usd: true },
where: { created_at: { gte: startOfMonthUtc() } },
});
return Number(agg._sum.cost_usd ?? 0);
}
export async function getBudgetUsd(): Promise<number> {
const settings = await prisma.company_settings.findFirst({
select: { ai_monthly_budget_usd: true },
});
const v = settings?.ai_monthly_budget_usd;
return v == null ? DEFAULT_BUDGET_USD : Number(v);
}
export async function setBudgetUsd(value: number): Promise<void> {
const existing = await prisma.company_settings.findFirst({
select: { id: true },
});
if (existing) {
await prisma.company_settings.update({
where: { id: existing.id },
data: { ai_monthly_budget_usd: value },
});
} else {
await prisma.company_settings.create({
data: { company_name: "", ai_monthly_budget_usd: value },
});
}
}
/** Returns { error, status: 402 } when this month's spend has reached the budget. */
export async function assertBudgetAvailable(): Promise<{
error: string;
status: number;
} | null> {
const [spend, budget] = await Promise.all([
getMonthSpendUsd(),
getBudgetUsd(),
]);
if (spend >= budget) {
return { error: "Měsíční rozpočet AI byl vyčerpán", status: 402 };
}
return null;
}
// ── Conversations (server-side, per user) ─────────────────────────────────
export interface StoredChatMessage {
role: string;
content: string;
created_at: Date;
}
export interface ConversationSummary {
id: number;
title: string;
updated_at: Date;
}
const DEFAULT_CONVERSATION_TITLE = "Nová konverzace";
const MESSAGE_LIMIT = 200; // cap a single thread read
export async function listConversations(
userId: number,
): Promise<ConversationSummary[]> {
return prisma.ai_conversations.findMany({
where: { user_id: userId },
orderBy: { id: "asc" }, // stable tab order
select: { id: true, title: true, updated_at: true },
});
}
export async function createConversation(
userId: number,
title?: string,
): Promise<ConversationSummary> {
return prisma.ai_conversations.create({
data: {
user_id: userId,
title: title?.trim() || DEFAULT_CONVERSATION_TITLE,
},
select: { id: true, title: true, updated_at: true },
});
}
/** Ownership-checked fetch; null when not found / not owned. */
async function ownConversation(userId: number, convId: number) {
return prisma.ai_conversations.findFirst({
where: { id: convId, user_id: userId },
select: { id: true, title: true },
});
}
export async function getConversationMessages(
userId: number,
convId: number,
): Promise<{ data: StoredChatMessage[] } | { error: string; status: number }> {
if (!(await ownConversation(userId, convId)))
return { error: "Konverzace nenalezena", status: 404 };
const rows = await prisma.ai_chat_messages.findMany({
where: { conversation_id: convId },
orderBy: { id: "desc" },
take: MESSAGE_LIMIT,
select: { role: true, content: true, created_at: true },
});
return { data: rows.reverse() };
}
export async function appendConversationMessages(
userId: number,
convId: number,
messages: { role: string; content: string }[],
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
const conv = await ownConversation(userId, convId);
if (!conv) return { error: "Konverzace nenalezena", status: 404 };
// The route validates messages with min(1), so this is normally non-empty;
// the guard is defensive (and still bumps updated_at below for an empty call).
if (messages.length > 0) {
await prisma.ai_chat_messages.createMany({
data: messages.map((m) => ({
user_id: userId,
conversation_id: convId,
role: m.role,
content: m.content,
})),
});
}
// Auto-title from the first user message (only while still the default), and
// always bump updated_at.
const firstUser = messages.find((m) => m.role === "user");
const data: { updated_at: Date; title?: string } = { updated_at: new Date() };
if (conv.title === DEFAULT_CONVERSATION_TITLE && firstUser) {
const t = firstUser.content.replace(/\s+/g, " ").trim().slice(0, 60);
if (t) data.title = t;
}
await prisma.ai_conversations.update({ where: { id: convId }, data });
return { data: { ok: true } };
}
export async function renameConversation(
userId: number,
convId: number,
title: string,
): Promise<{ data: ConversationSummary } | { error: string; status: number }> {
if (!(await ownConversation(userId, convId)))
return { error: "Konverzace nenalezena", status: 404 };
const updated = await prisma.ai_conversations.update({
where: { id: convId },
data: { title: title.trim() || DEFAULT_CONVERSATION_TITLE },
select: { id: true, title: true, updated_at: true },
});
return { data: updated };
}
export async function deleteConversation(
userId: number,
convId: number,
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
if (!(await ownConversation(userId, convId)))
return { error: "Konverzace nenalezena", status: 404 };
await prisma.ai_conversations.delete({ where: { id: convId } }); // cascade
return { data: { ok: true } };
}
export interface ChatMessage {
role: "user" | "assistant";
content: string;
}
const SYSTEM_PROMPT =
"Jsi asistent v interním firemním systému (česká firma). Odpovídej česky, stručně a věcně. " +
"Nemáš přístup k datům systému; pomáháš s obecnými dotazy a se čtením přiložených faktur.";
/** Plain chat turn. Records usage. Caller must check the budget first. */
export async function chat(
messages: ChatMessage[],
userId: number | null,
): Promise<{ reply: string }> {
const res = await client().messages.create({
model: AI_MODEL,
max_tokens: 2048,
system: SYSTEM_PROMPT,
messages: messages.map((m) => ({ role: m.role, content: m.content })),
});
// Best-effort usage logging — a ledger-write blip must not fail the user's
// call or vanish silently (CLAUDE.md: never swallow non-fatal failures).
try {
await recordUsage({
userId,
kind: "chat",
model: AI_MODEL,
inputTokens: res.usage.input_tokens,
outputTokens: res.usage.output_tokens,
});
} catch (e) {
console.error("[ai.service] recordUsage failed (chat)", e);
}
const reply = res.content
.filter((b): b is Anthropic.TextBlock => b.type === "text")
.map((b) => b.text)
.join("\n");
return { reply };
}
export interface ExtractedInvoice {
supplier_name: string;
invoice_number: string | null;
amount: number;
currency: string;
vat_rate: number;
issue_date: string | null;
due_date: string | null;
description: string | null;
}
// JSON schema for the structured extraction. Typed as the SDK's mutable
// index-signature shape (`Record<string, unknown>` leaves), NOT `as const` —
// a deeply-readonly literal won't assign to JSONOutputFormat.schema.
const INVOICE_SCHEMA: Record<string, unknown> = {
type: "object",
properties: {
supplier_name: { type: "string" },
invoice_number: { type: ["string", "null"] },
amount: {
type: "number",
description:
"Celková částka k úhradě VČETNĚ DPH (gross total), NE základ bez DPH.",
},
currency: { type: "string" },
vat_rate: {
type: "number",
description: "Sazba DPH v procentech; 0 pokud faktura nemá DPH.",
},
issue_date: { type: ["string", "null"] },
due_date: { type: ["string", "null"] },
description: { type: ["string", "null"] },
},
required: ["supplier_name", "amount", "currency", "vat_rate"],
additionalProperties: false,
};
/** Vision-extract the received-invoice fields from a PDF. Records usage. */
export async function extractInvoice(
pdfBuffer: Buffer,
userId: number | null,
): Promise<ExtractedInvoice> {
const res = await client().messages.create({
model: AI_MODEL,
max_tokens: 1024,
output_config: {
format: { type: "json_schema", schema: INVOICE_SCHEMA },
},
messages: [
{
role: "user",
content: [
{
type: "document",
source: {
type: "base64",
media_type: "application/pdf",
data: pdfBuffer.toString("base64"),
},
},
{
type: "text",
text:
"Vyčti z této přijaté faktury tato pole: dodavatele, číslo faktury, " +
"celkovou částku k úhradě VČETNĚ DPH (tj. konečný součet, NE základ bez DPH), " +
"měnu (ISO kód), sazbu DPH v procentech, datum vystavení a splatnosti (YYYY-MM-DD) a krátký popis. " +
"Pokud faktura nemá DPH, vrať sazbu 0. Pokud pole chybí, vrať null.",
},
],
},
],
});
try {
await recordUsage({
userId,
kind: "extract",
model: AI_MODEL,
inputTokens: res.usage.input_tokens,
outputTokens: res.usage.output_tokens,
});
} catch (e) {
console.error("[ai.service] recordUsage failed (extract)", e);
}
const text = res.content
.filter((b): b is Anthropic.TextBlock => b.type === "text")
.map((b) => b.text)
.join("");
return JSON.parse(text) as ExtractedInvoice;
}

View File

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

View File

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

View File

@@ -108,12 +108,14 @@ export interface ResolvedCell {
}
/**
* Compute the effective plan cell for (userId, dateStr).
* Compute the effective plan records for (userId, dateStr) as an array of
* 0MAX_RECORDS_PER_CELL records.
*
* Precedence: override > entry > null.
* Soft-deleted rows are ignored (is_deleted = false filter).
* If multiple entries cover the same day, the latest by created_at wins
* and a warning is logged.
* Layering: if any override exists for the day, the overrides are returned
* (newest-first) and the range entries are hidden; otherwise the range
* entries covering the day are returned (newest-first). Soft-deleted rows
* are ignored (is_deleted = false filter). The result is capped at
* MAX_RECORDS_PER_CELL.
*
* dateStr must be a YYYY-MM-DD string. The function builds a JS Date
* from it and Prisma handles timezone conversion against the MySQL
@@ -122,31 +124,31 @@ export interface ResolvedCell {
export async function resolveCell(
userId: number,
dateStr: string,
): Promise<ResolvedCell | null> {
): Promise<ResolvedCell[]> {
const date = new Date(dateStr);
// 1. Single-day override for this exact date
const override = await prisma.work_plan_overrides.findFirst({
const overrides = await prisma.work_plan_overrides.findMany({
where: { user_id: userId, shift_date: date, is_deleted: false },
orderBy: { created_at: "desc" },
take: MAX_RECORDS_PER_CELL,
include: { projects: projectSelect },
});
if (override) {
return {
source: "override",
if (overrides.length > 0) {
return overrides.map((o) => ({
source: "override" as const,
entryId: null,
overrideId: override.id,
user_id: override.user_id,
overrideId: o.id,
user_id: o.user_id,
shift_date: dateStr,
project_id: override.project_id,
...projectFields(override.projects),
category: override.category,
note: override.note,
project_id: o.project_id,
...projectFields(o.projects),
category: o.category,
note: o.note,
rangeFrom: null,
rangeTo: null,
};
}));
}
// 2. Range entry that covers the day
const entries = await prisma.work_plan_entries.findMany({
where: {
user_id: userId,
@@ -155,24 +157,11 @@ export async function resolveCell(
is_deleted: false,
},
orderBy: { created_at: "desc" },
take: MAX_RECORDS_PER_CELL,
include: { projects: projectSelect },
});
if (entries.length === 0) return null;
if (entries.length > 1) {
// Multiple entries overlap. Use the latest. A persistent audit-log
// entry would be ideal here, but logAudit() currently requires a
// FastifyRequest — services have no request. Use console.warn as a
// stand-in until a service-context audit logger is introduced.
console.warn(
`[plan.service] multiple entries cover user ${userId} on ${dateStr}; using the latest (entry id ${entries[0].id})`,
);
}
const entry = entries[0];
return {
source: "entry",
return entries.map((entry) => ({
source: "entry" as const,
entryId: entry.id,
overrideId: null,
user_id: entry.user_id,
@@ -183,12 +172,14 @@ export async function resolveCell(
note: entry.note,
rangeFrom: entry.date_from.toISOString().slice(0, 10),
rangeTo: entry.date_to.toISOString().slice(0, 10),
};
}));
}
/**
* Compute the effective plan cell for every (userId, date) in the
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell | null.
* Compute the effective plan records for every (userId, date) in the
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell[]
* (0MAX_RECORDS_PER_CELL records, same layering as resolveCell; empty
* days are []).
*
* Implementation: load all entries and overrides for the range in two
* queries, then iterate the dates and resolve each cell in O(1) per
@@ -198,7 +189,7 @@ export async function resolveGrid(
userIds: number[],
dateFromStr: string,
dateToStr: string,
): Promise<Record<number, Record<string, ResolvedCell | null>>> {
): Promise<Record<number, Record<string, ResolvedCell[]>>> {
const dateFrom = new Date(dateFromStr);
const dateTo = new Date(dateToStr);
@@ -219,11 +210,11 @@ export async function resolveGrid(
is_deleted: false,
shift_date: { gte: dateFrom, lte: dateTo },
},
orderBy: { created_at: "desc" },
include: { projects: projectSelect },
}),
]);
// Build a date list (inclusive)
const dates: string[] = [];
for (
let d = new Date(dateFrom);
@@ -233,56 +224,52 @@ export async function resolveGrid(
dates.push(d.toISOString().slice(0, 10));
}
const result: Record<number, Record<string, ResolvedCell | null>> = {};
const result: Record<number, Record<string, ResolvedCell[]>> = {};
for (const uid of userIds) {
result[uid] = {};
for (const dateStr of dates) {
// Override first
const override = overrides.find(
(o) =>
o.user_id === uid &&
o.shift_date.toISOString().slice(0, 10) === dateStr,
);
if (override) {
result[uid][dateStr] = {
source: "override",
const day = new Date(dateStr);
const dayOverrides = overrides
.filter(
(o) =>
o.user_id === uid &&
o.shift_date.toISOString().slice(0, 10) === dateStr,
)
.slice(0, MAX_RECORDS_PER_CELL);
if (dayOverrides.length > 0) {
result[uid][dateStr] = dayOverrides.map((o) => ({
source: "override" as const,
entryId: null,
overrideId: override.id,
user_id: override.user_id,
overrideId: o.id,
user_id: o.user_id,
shift_date: dateStr,
project_id: override.project_id,
...projectFields(override.projects),
category: override.category,
note: override.note,
project_id: o.project_id,
...projectFields(o.projects),
category: o.category,
note: o.note,
rangeFrom: null,
rangeTo: null,
};
}));
continue;
}
// First (latest by created_at) matching entry
const entry = entries.find(
(e) =>
e.user_id === uid &&
e.date_from <= new Date(dateStr) &&
e.date_to >= new Date(dateStr),
);
if (entry) {
result[uid][dateStr] = {
source: "entry",
entryId: entry.id,
overrideId: null,
user_id: entry.user_id,
shift_date: dateStr,
project_id: entry.project_id,
...projectFields(entry.projects),
category: entry.category,
note: entry.note,
rangeFrom: entry.date_from.toISOString().slice(0, 10),
rangeTo: entry.date_to.toISOString().slice(0, 10),
};
} else {
result[uid][dateStr] = null;
}
const dayEntries = entries
.filter(
(e) => e.user_id === uid && e.date_from <= day && e.date_to >= day,
)
.slice(0, MAX_RECORDS_PER_CELL);
result[uid][dateStr] = dayEntries.map((e) => ({
source: "entry" as const,
entryId: e.id,
overrideId: null,
user_id: e.user_id,
shift_date: dateStr,
project_id: e.project_id,
...projectFields(e.projects),
category: e.category,
note: e.note,
rangeFrom: e.date_from.toISOString().slice(0, 10),
rangeTo: e.date_to.toISOString().slice(0, 10),
}));
}
}
@@ -377,22 +364,14 @@ export function assertNotPastDate(
* where `oldData` is null for creates and the pre-update snapshot for
* updates / deletes (so the route handler can call `logAudit` with it).
*
* The optional `replacedData` field is set only by `createOverride` when
* an existing active override for the same (user, date) was soft-deleted
* before creating the new one. The route handler uses it to emit a
* second audit-log entry for the deletion of the replaced row.
*
* On failure returns `{ error, status }`.
*/
export type Result<T> =
| {
data: T;
oldData: unknown | null;
replacedData?: unknown | null;
/** Human-readable Czech subject for the audit-log row. */
description?: string;
/** Audit description for the `replacedData` soft-delete row, if any. */
replacedDescription?: string;
}
| { error: string; status: number };
@@ -401,6 +380,46 @@ function toDateOnly(dateStr: string): Date {
return new Date(dateStr + "T00:00:00.000Z");
}
/** Maximum number of records (entries OR overrides) shown per cell per day. */
export const MAX_RECORDS_PER_CELL = 3;
/**
* Returns { error, status } if creating an entry over [dateFromStr, dateToStr]
* would push any single day past MAX_RECORDS_PER_CELL active entries for the
* user. Names the first offending date. Counts entries regardless of whether an
* override currently hides them (simpler and predictable).
*/
async function assertEntryCapAvailable(
userId: number,
dateFromStr: string,
dateToStr: string,
): Promise<{ error: string; status: number } | null> {
const from = toDateOnly(dateFromStr);
const to = toDateOnly(dateToStr);
const existing = await prisma.work_plan_entries.findMany({
where: {
user_id: userId,
is_deleted: false,
date_from: { lte: to },
date_to: { gte: from },
},
select: { date_from: true, date_to: true },
});
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
const day = new Date(d);
const count = existing.filter(
(e) => e.date_from <= day && e.date_to >= day,
).length;
if (count >= MAX_RECORDS_PER_CELL) {
return {
error: `Na den ${day.toISOString().slice(0, 10)} jsou již ${MAX_RECORDS_PER_CELL} záznamy (maximum).`,
status: 400,
};
}
}
return null;
}
/** Create a work_plan_entries row. Past dates require force=true. */
export async function createEntry(
input: {
@@ -442,6 +461,13 @@ export async function createEntry(
const catErr = await assertActiveCategory(input.category);
if (catErr) return catErr;
const capErr = await assertEntryCapAvailable(
input.user_id,
input.date_from,
input.date_to,
);
if (capErr) return capErr;
const created = await prisma.work_plan_entries.create({
data: {
user_id: input.user_id,
@@ -576,13 +602,10 @@ export async function deleteEntry(
// ---------------------------------------------------------------------------
/**
* Create a work_plan_overrides row. Replaces any active override for the
* same (user_id, shift_date) — soft-deletes the old one. Past dates
* require force=true.
*
* Returns { data, oldData: null, replacedData: existing_or_null } so the
* route handler can emit two audit log rows: one for the soft-deleted
* previous override, and one for the new one.
* Create a work_plan_overrides row. Additive: stacks up to
* MAX_RECORDS_PER_CELL active overrides per (user_id, shift_date); a create
* past the cap returns { error, status: 400 }. Past dates require force=true.
* Returns { data, oldData: null, description }.
*/
export async function createOverride(
input: {
@@ -601,49 +624,41 @@ export async function createOverride(
const catErr = await assertActiveCategory(input.category);
if (catErr) return catErr;
// Application-level enforcement of "at most one active override per
// (user_id, shift_date)". The previous DB unique constraint was dropped
// (see migration 20260605122718_drop_wpo_unique_constraint) because
// MySQL unique indexes don't ignore soft-deleted rows, which would have
// blocked legitimate soft-delete-then-create replacement.
//
// Race protection: wrap the soft-delete + create in a transaction with
// SELECT ... FOR UPDATE on the colliding row so two concurrent requests
// can't both create active overrides for the same user-day.
const date = toDateOnly(input.shift_date);
const { created, replaced } = await prisma.$transaction(async (tx) => {
const existing = await tx.work_plan_overrides.findFirst({
where: {
user_id: input.user_id,
shift_date: date,
is_deleted: false,
},
});
if (existing) {
// Lock the row before update so a concurrent createOverride for the
// same (user, date) waits and sees the soft-deleted state.
await tx.$executeRaw`SELECT id FROM work_plan_overrides WHERE id = ${existing.id} FOR UPDATE`;
await tx.work_plan_overrides.update({
where: { id: existing.id },
data: { is_deleted: true },
// Additive up to MAX_RECORDS_PER_CELL. (This previously REPLACED the existing
// override; multi-record cells stack instead.) count+create runs in one
// transaction; a concurrent create could in theory add one extra row, but
// resolve display caps at MAX_RECORDS_PER_CELL so that is benign.
let created;
try {
created = await prisma.$transaction(async (tx) => {
const count = await tx.work_plan_overrides.count({
where: { user_id: input.user_id, shift_date: date, is_deleted: false },
});
if (count >= MAX_RECORDS_PER_CELL) {
throw Object.assign(new Error("cap"), { __cap: true });
}
return tx.work_plan_overrides.create({
data: {
user_id: input.user_id,
shift_date: date,
project_id: input.project_id ?? null,
category: input.category,
note: input.note,
created_by: actorUserId,
},
});
}
const createdRow = await tx.work_plan_overrides.create({
data: {
user_id: input.user_id,
shift_date: date,
project_id: input.project_id ?? null,
category: input.category,
note: input.note,
created_by: actorUserId,
},
});
return { created: createdRow, replaced: existing };
});
} catch (e) {
if (e && typeof e === "object" && "__cap" in e) {
return {
error: `Na tento den jsou již ${MAX_RECORDS_PER_CELL} záznamy (maximum).`,
status: 400,
};
}
throw e;
}
const { userName, projectName } = await resolvePlanLabels(
created.user_id,
@@ -658,26 +673,7 @@ export async function createOverride(
force,
});
let replacedDescription: string | undefined;
if (replaced) {
const r = await resolvePlanLabels(replaced.user_id, replaced.project_id);
replacedDescription = buildPlanAuditDescription({
userName: r.userName,
categoryLabel: await resolveCategoryLabel(replaced.category),
projectName: r.projectName,
dateFrom: isoDay(replaced.shift_date),
dateTo: isoDay(replaced.shift_date),
suffix: "nahrazeno novým záznamem",
});
}
return {
data: created,
oldData: null,
replacedData: replaced,
description,
replacedDescription,
};
return { data: created, oldData: null, description };
}
/** Update a work_plan_overrides row. */
@@ -765,6 +761,157 @@ export async function deleteOverride(
return { data: { ok: true }, oldData: existing, description };
}
// ---------------------------------------------------------------------------
// Bulk entry creation
// ---------------------------------------------------------------------------
/**
* Bulk-assign a project/category to many employees over a date range. For each
* employee, walk the range, keep the days that pass the weekday filter
* (weekends excluded unless include_weekends) AND are under the per-cell cap,
* group contiguous kept days into runs, and create one range entry per run by
* reusing createEntry (so cap / past-date / category validation stays DRY).
*
* Days that pass the weekday filter but are already at the cap are counted in
* skipped_days (and split the range). Weekend days, when excluded, are out of
* scope and are NOT counted as skipped.
*/
export async function bulkCreateEntries(
input: {
user_ids: number[];
date_from: string;
date_to: string;
include_weekends: boolean;
project_id?: number | null;
category: string;
note: string;
},
actorUserId: number,
): Promise<
Result<{
created_entries: number;
created_days: number;
skipped_days: number;
users: number;
}>
> {
if (input.user_ids.length === 0) {
return { error: "Vyberte alespoň jednoho zaměstnance", status: 400 };
}
if (input.date_to < input.date_from) {
return { error: "Datum do musí být stejné nebo po datumu od", status: 400 };
}
const lockFrom = assertNotPastDate(input.date_from, false);
if (lockFrom) return lockFrom;
const lockTo = assertNotPastDate(input.date_to, false);
if (lockTo) return lockTo;
const catErr = await assertActiveCategory(input.category);
if (catErr) return catErr;
const from = toDateOnly(input.date_from);
const to = toDateOnly(input.date_to);
// Bound the work (users × days). Mirror the 92-day cap on GET /plan/grid so
// one bulk call can't fan out into thousands of inserts.
const rangeDays = Math.round((to.getTime() - from.getTime()) / 86400000) + 1;
if (rangeDays > 92) {
return { error: "Maximální rozsah je 92 dní", status: 400 };
}
// The day list for the whole range (UTC midnights), built once.
const days: Date[] = [];
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
days.push(new Date(d));
}
let createdEntries = 0;
let createdDays = 0;
let skippedDays = 0;
for (const userId of input.user_ids) {
// Per-day cap counts from this user's existing active entries.
const existing = await prisma.work_plan_entries.findMany({
where: {
user_id: userId,
is_deleted: false,
date_from: { lte: to },
date_to: { gte: from },
},
select: { date_from: true, date_to: true },
});
const countFor = (day: Date): number =>
existing.filter((e) => e.date_from <= day && e.date_to >= day).length;
// Eligibility per day (weekday filter + under-cap). Tally cap skips.
const eligible: boolean[] = [];
for (const day of days) {
const dow = day.getUTCDay(); // 0 = Sun, 6 = Sat
const isWeekend = dow === 0 || dow === 6;
if (isWeekend && !input.include_weekends) {
eligible.push(false);
continue;
}
if (countFor(day) >= MAX_RECORDS_PER_CELL) {
skippedDays++;
eligible.push(false);
continue;
}
eligible.push(true);
}
// Group contiguous eligible days into runs; create one range per run.
let runStart = -1;
for (let i = 0; i <= days.length; i++) {
const ok = i < days.length && eligible[i];
if (ok && runStart === -1) {
runStart = i;
} else if (!ok && runStart !== -1) {
const segFrom = days[runStart].toISOString().slice(0, 10);
const segTo = days[i - 1].toISOString().slice(0, 10);
const runDays = i - runStart;
const res = await createEntry(
{
user_id: userId,
date_from: segFrom,
date_to: segTo,
project_id: input.project_id ?? null,
category: input.category,
note: input.note,
},
actorUserId,
false,
);
if ("data" in res) {
createdEntries++;
createdDays += runDays;
} else {
// Rare race (e.g. the cap filled concurrently between the count and
// the create). Treat the run's days as skipped, but log — services
// must not swallow non-fatal failures (CLAUDE.md known-issue #4).
console.warn("[plan.service] bulkCreateEntries: segment skipped", {
userId,
segFrom,
segTo,
error: res.error,
});
skippedDays += runDays;
}
runStart = -1;
}
}
}
return {
data: {
created_entries: createdEntries,
created_days: createdDays,
skipped_days: skippedDays,
users: input.user_ids.length,
},
oldData: null,
};
}
// ---------------------------------------------------------------------------
// Raw-row list endpoints
// ---------------------------------------------------------------------------

View File

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