Compare commits

..

36 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
35 changed files with 5405 additions and 23 deletions

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,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.2",
"version": "2.0.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "app-ts",
"version": "2.0.2",
"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.7",
"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,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

@@ -16,6 +16,35 @@ 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;
@@ -480,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"
@@ -543,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,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

@@ -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,
});

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

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

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

@@ -69,7 +69,7 @@ export default async function dashboardRoutes(
// 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 },
@@ -89,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) {
@@ -153,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

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

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