Compare commits

...

24 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
24 changed files with 2971 additions and 779 deletions

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,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" />

View File

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

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

@@ -89,14 +89,27 @@ model ai_usage {
@@index([created_at], map: "idx_ai_usage_created")
}
model ai_chat_messages {
id Int @id @default(autoincrement())
model ai_conversations {
id Int @id @default(autoincrement())
user_id Int
role String @db.VarChar(20)
content String @db.Text
created_at DateTime @default(now()) @db.Timestamp(0)
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_chat_user")
@@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 {

View File

@@ -14,27 +14,29 @@ import {
getBudgetUsd,
assertBudgetAvailable,
isConfigured,
getChatHistory,
appendChatMessages,
clearChatHistory,
listConversations,
createConversation,
getConversationMessages,
appendConversationMessages,
renameConversation,
deleteConversation,
} from "../services/ai.service";
const KIND = "test_ai"; // marker so we only clean our own rows
// Synthetic, FK-free user ids for chat-history service tests (no users row needed).
const HIST_UID_A = 999999991;
const HIST_UID_B = 999999992;
const HIST_MARKER = "「test-hist」"; // marker for HTTP-test rows on real users
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_chat_messages.deleteMany({
where: { user_id: { in: [HIST_UID_A, HIST_UID_B] } },
await prisma.ai_conversations.deleteMany({
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
});
await prisma.ai_chat_messages.deleteMany({
where: { content: { contains: HIST_MARKER } },
await prisma.ai_conversations.deleteMany({
where: { title: { contains: HIST_MARKER } },
});
});
@@ -112,43 +114,90 @@ describe("ai.service cost + budget", () => {
});
});
describe("ai.service chat history", () => {
describe("ai.service conversations", () => {
beforeEach(async () => {
await prisma.ai_chat_messages.deleteMany({
where: { user_id: { in: [HIST_UID_A, HIST_UID_B] } },
await prisma.ai_conversations.deleteMany({
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
});
});
it("appends and returns a user's thread oldest → newest", async () => {
await appendChatMessages(HIST_UID_A, [
{ role: "user", content: "ahoj" },
{ role: "assistant", content: "Dobrý den" },
// 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…" },
]);
await appendChatMessages(HIST_UID_A, [
{ role: "user", content: "jak se máš" },
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…",
]);
const hist = await getChatHistory(HIST_UID_A);
expect(hist.map((m) => m.content)).toEqual([
"ahoj",
"Dobrý den",
"jak se máš",
]);
expect(hist[0].role).toBe("user");
});
it("isolates history per user", async () => {
await appendChatMessages(HIST_UID_A, [{ role: "user", content: "A1" }]);
await appendChatMessages(HIST_UID_B, [{ role: "user", content: "B1" }]);
const a = await getChatHistory(HIST_UID_A);
const b = await getChatHistory(HIST_UID_B);
expect(a.map((m) => m.content)).toEqual(["A1"]);
expect(b.map((m) => m.content)).toEqual(["B1"]);
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("clears a user's thread", async () => {
await appendChatMessages(HIST_UID_A, [{ role: "user", content: "x" }]);
await clearChatHistory(HIST_UID_A);
expect(await getChatHistory(HIST_UID_A)).toEqual([]);
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);
});
});
@@ -266,82 +315,134 @@ describe("HTTP /api/admin/ai", () => {
(appConfig.anthropic as { apiKey: string }).apiKey = savedKey;
});
it("GET /history requires ai.use", async () => {
it("GET /conversations requires ai.use", async () => {
const res = await app.inject({
method: "GET",
url: "/api/admin/ai/history",
url: "/api/admin/ai/conversations",
headers: { Authorization: `Bearer ${noPermToken}` },
});
expect(res.statusCode).toBe(403);
});
it("POST /history appends and GET /history returns the thread", async () => {
const post = await app.inject({
it("conversation lifecycle over HTTP (create → append → list → rename → delete)", async () => {
const created = await app.inject({
method: "POST",
url: "/api/admin/ai/history",
url: "/api/admin/ai/conversations",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: {
messages: [
{ role: "user", content: `${HIST_MARKER} dotaz` },
{ role: "assistant", content: `${HIST_MARKER} odpoved` },
],
},
payload: { title: `${HIST_MARKER} t` },
});
expect(post.statusCode).toBe(200);
expect(created.statusCode).toBe(200);
const id = created.json().data.conversation.id as number;
const get = await app.inject({
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/history",
url: `/api/admin/ai/conversations/${id}/messages`,
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(get.statusCode).toBe(200);
const contents = get
.json()
.data.messages.map((m: { content: string }) => m.content);
expect(contents).toContain(`${HIST_MARKER} dotaz`);
expect(contents).toContain(`${HIST_MARKER} odpoved`);
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("POST /history rejects an empty messages array", async () => {
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/history",
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(res.statusCode).toBe(400);
});
it("DELETE /history clears the thread", async () => {
await app.inject({
method: "POST",
url: "/api/admin/ai/history",
headers: {
Authorization: `Bearer ${adminToken}`,
"Content-Type": "application/json",
},
payload: { messages: [{ role: "user", content: `${HIST_MARKER} x` }] },
});
const del = await app.inject({
method: "DELETE",
url: "/api/admin/ai/history",
headers: { Authorization: `Bearer ${adminToken}` },
});
expect(del.statusCode).toBe(200);
const get = await app.inject({
method: "GET",
url: "/api/admin/ai/history",
headers: { Authorization: `Bearer ${adminToken}` },
});
const contents = get
.json()
.data.messages.map((m: { content: string }) => m.content);
expect(contents).not.toContain(`${HIST_MARKER} x`);
expect(append.statusCode).toBe(400);
});
});

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

@@ -1,631 +0,0 @@
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 Chip from "@mui/material/Chip";
import CircularProgress from "@mui/material/CircularProgress";
import { Card, Button, TextField } from "../../ui";
import apiFetch from "../../utils/api";
import { useAlert } from "../../context/AlertContext";
import {
aiUsageOptions,
aiHistoryOptions,
type ExtractedInvoice,
} from "../../lib/queries/ai";
interface ChatTurn {
role: "user" | "assistant";
content: string;
}
// The review card is a *form* model: every editable field is a string (what the
// inputs hold), distinct from the API's ExtractedInvoice. We convert numbers at
// save time. This keeps the type honest — no `number` field holding a string.
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;
}
type EditableField =
| "supplier_name"
| "invoice_number"
| "amount"
| "currency"
| "vat_rate"
| "issue_date"
| "due_date"
| "description";
// A staged file carries a stable id so chip keys survive mid-list removal.
interface StagedFile {
id: string;
file: File;
}
// Stable, monotonic id. NOT crypto.randomUUID() — that only exists in a secure
// context (HTTPS/localhost) and throws over plain HTTP on a LAN. A counter is
// unique within the session and context-independent.
let uidSeq = 0;
const nextUid = () => `ai-${(uidSeq += 1)}`;
// How many recent turns to send the model as context (bounds tokens/cost).
const MODEL_CONTEXT = 20;
// Server schema caps a stored message at 8000 chars.
const MAX_STORE = 8000;
const plural = (n: number) =>
n === 1 ? "fakturu" : n >= 2 && n <= 4 ? "faktury" : "faktur";
/** A human, Czech summary of an extraction so the assistant "reports back". */
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 DashAssistant() {
const alert = useAlert();
const qc = useQueryClient();
const { data: usage } = useQuery(aiUsageOptions());
const { data: historyData, isPending: historyPending } =
useQuery(aiHistoryOptions());
const [turns, setTurns] = useState<ChatTurn[]>([]);
const [input, setInput] = useState("");
const [busy, setBusy] = useState(false);
const [review, setReview] = useState<ReviewInvoice[]>([]);
const [attachments, setAttachments] = useState<StagedFile[]>([]);
const fileRef = useRef<HTMLInputElement>(null);
const threadRef = useRef<HTMLDivElement>(null);
const seeded = useRef(false);
// Seed the thread from server history exactly once (first time it arrives).
useEffect(() => {
if (!seeded.current && historyData) {
seeded.current = true;
setTurns(
historyData.messages.map((m) => ({ role: m.role, content: m.content })),
);
}
}, [historyData]);
// Keep the thread scrolled to the latest message. Deliberately NOT keyed on
// `review` — editing a review-card field must not yank the thread to bottom.
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;
// Best-effort: persist the given turns to the server thread. A persistence
// blip must not fail the user's interaction, but must not be swallowed.
const persist = (msgs: ChatTurn[]) => {
apiFetch("/api/admin/ai/history", {
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));
})
.catch((e) => console.error("[ai] history persist failed", e));
};
// Attaching only *stages* files — nothing is sent until the user presses
// Odeslat. We append (multiple picks accumulate) and clear the input element.
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));
// Disabled until history has settled, so the user can't send a turn before
// the seed runs (which would otherwise let a late history load clobber it).
const canSubmit =
!historyPending && !busy && (!!input.trim() || attachments.length > 0);
// Single submit (Odeslat). With staged attachments → extract invoices for
// review (the typed message is shown as a caption; the assistant's summary is
// the reply to it). Otherwise → a normal chat turn.
const submit = async () => {
if (busy) return;
const text = input.trim();
const files = attachments.map((a) => a.file);
if (!text && files.length === 0) return;
// Any interaction means the thread is "live"; a late-arriving history load
// must not overwrite it (belt-and-suspenders alongside the canSubmit gate).
seeded.current = true;
const prevTurns = turns; // snapshot for rollback on failure
setBusy(true);
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");
// The server iterates parts serially and pushes one result per file in
// submission order (truncating only if budget runs out mid-batch), so
// files[i] is reliably this result's File — more robust than matching by
// name, which would collide on duplicate filenames.
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([]);
persist([
{ role: "user", content: userContent },
{ role: "assistant", content: note },
]);
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
} else {
// Send only recent context, and ensure it starts on a user turn (the
// Anthropic API requires the first message to be from the user).
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("");
persist([
{ role: "user", content: userContent },
{ role: "assistant", content: reply },
]);
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
}
} catch (e) {
// Roll back the optimistic user turn and KEEP input + attachments so the
// user can retry without losing their typed text or staged PDFs.
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: ["received-invoices"] });
} catch (e) {
alert.error(e instanceof Error ? e.message : "Uložení selhalo");
} finally {
setBusy(false);
}
};
const clearHistory = async () => {
if (busy) return;
setBusy(true);
try {
const res = await apiFetch("/api/admin/ai/history", { method: "DELETE" });
if (!res.ok) throw new Error("Nepodařilo se vymazat historii");
setTurns([]);
setReview([]);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba");
} finally {
setBusy(false);
}
};
const patch = (uid: string, field: EditableField, value: string) =>
setReview((r) =>
r.map((inv) => (inv.uid === uid ? { ...inv, [field]: value } : inv)),
);
const fieldCols = { xs: "1fr", sm: "1fr 1fr" };
return (
<Card sx={{ mb: 3 }}>
{/* Header */}
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
mb: 1.5,
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
<Box
sx={{
px: 0.75,
py: 0.25,
borderRadius: 1,
fontSize: 11,
fontWeight: 700,
letterSpacing: 0.5,
color: "common.white",
bgcolor: "primary.main",
}}
>
AI
</Box>
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
Asistent
</Typography>
</Box>
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
{usage && (
<Typography variant="caption" color="text.secondary">
Utraceno: ${usage.month_spend_usd.toFixed(2)} / $
{usage.budget_usd.toFixed(2)}
</Typography>
)}
{turns.length > 0 && (
<Button
variant="text"
color="inherit"
size="small"
onClick={clearHistory}
disabled={busy}
sx={{ minWidth: 0, color: "text.secondary" }}
>
Vymazat
</Button>
)}
</Box>
</Box>
{/* Thread */}
<Box
ref={threadRef}
sx={{
display: "flex",
flexDirection: "column",
gap: 1,
minHeight: 120,
maxHeight: 360,
overflowY: "auto",
mb: 1.5,
p: 1,
borderRadius: 2,
bgcolor: "action.hover",
}}
>
{turns.length === 0 && !busy && (
<Box
sx={{
flex: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
textAlign: "center",
color: "text.secondary",
px: 2,
}}
>
<Typography variant="body2" sx={{ color: "inherit" }}>
{historyPending
? "Načítám…"
: "Zeptejte se, nebo přiložte fakturu (PDF) k automatickému importu."}
</Typography>
</Box>
)}
{turns.map((t, i) => (
<Box
key={i}
sx={{
alignSelf: t.role === "user" ? "flex-end" : "flex-start",
maxWidth: "85%",
px: 1.5,
py: 1,
borderRadius: 2,
boxShadow: 1,
bgcolor: t.role === "user" ? "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: t.role === "user" ? "common.white" : "text.primary",
}}
>
{t.content}
</Typography>
</Box>
))}
{busy && (
<Box
sx={{
alignSelf: "flex-start",
display: "flex",
alignItems: "center",
gap: 1,
px: 1.5,
py: 1,
color: "text.secondary",
}}
>
<CircularProgress size={14} />
<Typography variant="caption">Pracuji</Typography>
</Box>
)}
</Box>
{/* Pending invoices to confirm — rendered OUTSIDE the scrollable thread so
the Uložit button is always reachable (the page scrolls if there are
many), and editing a field never yanks the chat scroll. */}
{review.length > 0 && (
<Box sx={{ mb: 1.5 }}>
<Typography
variant="subtitle2"
sx={{ fontWeight: 600, color: "text.secondary", mb: 1 }}
>
Faktury k potvrzení ({review.length})
</Typography>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
{review.map((inv) => (
<Card key={inv.uid} variant="outlined" sx={{ p: 1.5 }}>
<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>
<Box
sx={{
display: "grid",
gridTemplateColumns: fieldCols,
gap: 1,
}}
>
<TextField
label="Dodavatel"
value={inv.supplier_name}
onChange={(e) =>
patch(inv.uid, "supplier_name", e.target.value)
}
/>
<TextField
label="Číslo faktury"
value={inv.invoice_number}
onChange={(e) =>
patch(inv.uid, "invoice_number", e.target.value)
}
/>
<TextField
label="Částka s DPH"
value={inv.amount}
onChange={(e) => patch(inv.uid, "amount", e.target.value)}
/>
<TextField
label="Měna"
value={inv.currency}
onChange={(e) => patch(inv.uid, "currency", e.target.value)}
/>
<TextField
label="Sazba DPH %"
value={inv.vat_rate}
onChange={(e) => patch(inv.uid, "vat_rate", e.target.value)}
/>
<TextField
label="Datum vystavení"
value={inv.issue_date}
onChange={(e) =>
patch(inv.uid, "issue_date", e.target.value)
}
/>
<TextField
label="Datum splatnosti"
value={inv.due_date}
onChange={(e) => patch(inv.uid, "due_date", e.target.value)}
/>
<TextField
label="Popis"
value={inv.description}
onChange={(e) =>
patch(inv.uid, "description", e.target.value)
}
/>
</Box>
<Box sx={{ display: "flex", gap: 1, mt: 1.5 }}>
<Button onClick={() => saveInvoice(inv)} disabled={busy}>
Uložit
</Button>
<Button
variant="outlined"
color="inherit"
onClick={() =>
setReview((r) => r.filter((x) => x.uid !== inv.uid))
}
disabled={busy}
>
Zahodit
</Button>
</Box>
</Card>
))}
</Box>
</Box>
)}
{/* Staged attachments */}
{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 : () => removeAttachment(s.id)}
/>
))}
</Box>
)}
{/* Composer */}
<Box sx={{ display: "flex", gap: 1, alignItems: "center" }}>
<input
ref={fileRef}
type="file"
accept="application/pdf,image/*"
multiple
hidden
onChange={(e) => onFiles(e.target.files)}
/>
<Button
variant="outlined"
color="inherit"
onClick={() => fileRef.current?.click()}
disabled={busy}
>
Přiložit
</Button>
<TextField
fullWidth
placeholder="Napište zprávu…"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submit();
}
}}
/>
<Button onClick={submit} disabled={!canSubmit}>
Odeslat
</Button>
</Box>
</Card>
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -32,15 +32,30 @@ export const aiUsageOptions = () =>
staleTime: 30_000,
});
export const aiHistoryOptions = () =>
export interface Conversation {
id: number;
title: string;
updated_at: string;
}
export const aiConversationsOptions = () =>
queryOptions({
queryKey: ["ai", "history"],
queryKey: ["ai", "conversations"],
queryFn: () =>
jsonQuery<{ messages: StoredChatMessage[] }>("/api/admin/ai/history"),
// Within a mount the thread is seeded once and mutated locally, so don't
// refetch on focus (staleTime Infinity). But gcTime 0 drops the cache on
// unmount, so every remount re-reads the DB (the source of truth) — this
// is what keeps a cleared/appended thread from resurrecting stale messages.
jsonQuery<{ conversations: Conversation[] }>(
"/api/admin/ai/conversations",
),
staleTime: 30_000,
});
export const aiConversationMessagesOptions = (id: number) =>
queryOptions({
queryKey: ["ai", "conversation", id, "messages"],
queryFn: () =>
jsonQuery<{ messages: StoredChatMessage[] }>(
`/api/admin/ai/conversations/${id}/messages`,
),
// Re-read the DB on each mount/selection (no stale-cache resurrection).
staleTime: Infinity,
gcTime: 0,
});

View File

@@ -22,7 +22,6 @@ import DashSessions from "../components/dashboard/DashSessions";
import DashTodayPlan, {
type TodayPlan,
} from "../components/dashboard/DashTodayPlan";
import DashAssistant from "../components/dashboard/DashAssistant";
const API_BASE = "/api/admin";
@@ -237,9 +236,6 @@ export default function Dashboard() {
</Typography>
</Box>
{/* AI Assistant widget */}
{hasPermission("ai.use") && <DashAssistant />}
{/* 2FA Required Banner */}
{user?.require2FA && !user?.totpEnabled && (
<Card

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

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

@@ -1,12 +1,14 @@
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
import multipart from "@fastify/multipart";
import { requirePermission } from "../../middleware/auth";
import { success, error } from "../../utils/response";
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";
@@ -18,9 +20,12 @@ import {
setBudgetUsd,
chat,
extractInvoice,
getChatHistory,
appendChatMessages,
clearChatHistory,
listConversations,
createConversation,
getConversationMessages,
appendConversationMessages,
renameConversation,
deleteConversation,
type ExtractedInvoice,
} from "../../services/ai.service";
@@ -131,35 +136,95 @@ export default async function aiRoutes(app: FastifyInstance): Promise<void> {
},
);
// GET /api/admin/ai/history — this user's stored chat thread
// GET /conversations — this user's conversations (stable order)
app.get(
"/history",
"/conversations",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
const messages = await getChatHistory(request.authData!.userId);
return success(reply, { messages });
const conversations = await listConversations(request.authData!.userId);
return success(reply, { conversations });
},
);
// POST /api/admin/ai/history — append turns to this user's thread
// POST /conversations — create
app.post(
"/history",
"/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);
await appendChatMessages(request.authData!.userId, body.data.messages);
return success(reply, { ok: true });
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);
},
);
// DELETE /api/admin/ai/history — clear this user's thread
app.delete(
"/history",
// PATCH /conversations/:id — rename
app.patch(
"/conversations/:id",
{ preHandler: requirePermission("ai.use") },
async (request: FastifyRequest, reply: FastifyReply) => {
await clearChatHistory(request.authData!.userId);
return success(reply, { ok: true });
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

@@ -24,6 +24,14 @@ export const AiHistoryAppendSchema = z.object({
.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()])

View File

@@ -104,48 +104,121 @@ export async function assertBudgetAvailable(): Promise<{
return null;
}
// ── Chat history (server-side, permanent, per user) ───────────────────────
// ── 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;
}
// Cap how many turns we read back / display. The full thread stays in the DB;
// this only bounds a single GET payload (and, on the client, the model context).
const HISTORY_LIMIT = 200;
const DEFAULT_CONVERSATION_TITLE = "Nová konverzace";
const MESSAGE_LIMIT = 200; // cap a single thread read
/** This user's chat thread, oldest → newest, capped at HISTORY_LIMIT. */
export async function getChatHistory(
export async function listConversations(
userId: number,
): Promise<StoredChatMessage[]> {
const rows = await prisma.ai_chat_messages.findMany({
): 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: HISTORY_LIMIT,
take: MESSAGE_LIMIT,
select: { role: true, content: true, created_at: true },
});
return rows.reverse();
return { data: rows.reverse() };
}
/** Append turns to this user's thread (best-effort caller). */
export async function appendChatMessages(
export async function appendConversationMessages(
userId: number,
convId: number,
messages: { role: string; content: string }[],
): Promise<void> {
if (messages.length === 0) return;
await prisma.ai_chat_messages.createMany({
data: messages.map((m) => ({
user_id: userId,
role: m.role,
content: m.content,
})),
});
): 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 } };
}
/** Wipe this user's thread. */
export async function clearChatHistory(userId: number): Promise<void> {
await prisma.ai_chat_messages.deleteMany({ where: { user_id: userId } });
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 {