Compare commits
45 Commits
v2.0.5
...
b1f21a1f48
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1f21a1f48 | ||
|
|
b6cd5046d5 | ||
|
|
25c8c39ba6 | ||
|
|
4b2770a000 | ||
|
|
434a12b4a8 | ||
|
|
28fb399217 | ||
|
|
c0ff7b4549 | ||
|
|
1e21c12f33 | ||
|
|
ab12f9d791 | ||
|
|
cf442b9a99 | ||
|
|
2e7caea5a6 | ||
|
|
702a4984ee | ||
|
|
769767c33d | ||
|
|
f18e2e0f2c | ||
|
|
d62abe81fd | ||
|
|
ac7c220bb1 | ||
|
|
b7ebf04001 | ||
|
|
441f46a471 | ||
|
|
f011a67ff3 | ||
|
|
92594f89c3 | ||
|
|
6664e3bc4d | ||
|
|
c5cfd855ba | ||
|
|
2565e0de21 | ||
|
|
817f0b2f00 | ||
|
|
e4ec08a5ef | ||
|
|
049ee492c0 | ||
|
|
f4bc038f8b | ||
|
|
58e5fd2b1d | ||
|
|
0226cdd52b | ||
|
|
b665ea1d9b | ||
|
|
ec74ded953 | ||
|
|
bcf63d00d1 | ||
|
|
096784768f | ||
|
|
3623b441ce | ||
|
|
4bf7bf4ed6 | ||
|
|
92252382ac | ||
|
|
8bed920de1 | ||
|
|
9d2992b722 | ||
|
|
1ddc0feccd | ||
|
|
cce2c9cfaa | ||
|
|
2610301258 | ||
|
|
13d1fc2be3 | ||
|
|
95ca258718 | ||
|
|
6db87bf4ae | ||
|
|
c6a146d57a |
48
CLAUDE.md
48
CLAUDE.md
@@ -7,18 +7,19 @@ Handles attendance, invoicing, leave/trips, projects, vehicles, and HR operation
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
| -------------- | ------------------------------------------------------------- |
|
||||
| Runtime | Node.js, TypeScript 5.9.3 (strict) |
|
||||
| HTTP Framework | Fastify 5.8.2 |
|
||||
| ORM | Prisma 6.19.2 → MySQL |
|
||||
| Auth | JWT (HS256, 15 min) + TOTP 2FA (RFC 6238, otpauth) + bcryptjs |
|
||||
| Validation | Zod 4.3.6 |
|
||||
| Frontend | React 18.3.1 + Vite 8.0.0 + Material UI v7 (Emotion) |
|
||||
| Testing | Vitest 4.1.0 + Supertest |
|
||||
| PDF | Puppeteer 24.x |
|
||||
| Email | nodemailer 8.x |
|
||||
| Cron | node-cron 4.x |
|
||||
| Layer | Technology |
|
||||
| -------------- | -------------------------------------------------------------- |
|
||||
| Runtime | Node.js, TypeScript 5.9.3 (strict) |
|
||||
| HTTP Framework | Fastify 5.8.2 |
|
||||
| ORM | Prisma 6.19.2 → MySQL |
|
||||
| Auth | JWT (HS256, 15 min) + TOTP 2FA (RFC 6238, otpauth) + bcryptjs |
|
||||
| Validation | Zod 4.3.6 |
|
||||
| Frontend | React 18.3.1 + Vite 8.0.0 + Material UI v7 (Emotion) |
|
||||
| Testing | Vitest 4.1.0 + Supertest |
|
||||
| PDF | Puppeteer 24.x |
|
||||
| Email | nodemailer 8.x |
|
||||
| Cron | node-cron 4.x |
|
||||
| AI | @anthropic-ai/sdk 0.102 — Claude Sonnet 4.6 ("Odin" assistant) |
|
||||
|
||||
---
|
||||
|
||||
@@ -35,21 +36,21 @@ src/
|
||||
├── utils/ # totp.ts, pdf.ts, email.ts, audit.ts, formatters, etc.
|
||||
├── config/ # env.ts (config singleton, Date.toJSON override)
|
||||
├── types/ # index.ts (AuthData, JwtPayload, ApiResponse, re-exports from Prisma)
|
||||
├── admin/ # React 18 + Material UI frontend (~105 .tsx files)
|
||||
├── admin/ # React 18 + Material UI frontend (~114 .tsx files)
|
||||
│ ├── AdminApp.tsx # Router + lazy-loaded pages
|
||||
│ ├── theme.ts # MUI theme — light/dark color schemes, tokens, component defaults
|
||||
│ ├── GlobalStyles.tsx # App-wide global styles via MUI <GlobalStyles> (reset, typography, utilities)
|
||||
│ ├── ui/ # MUI component kit (AppShell, Button, DataTable, Modal, …) — pages import from here
|
||||
│ ├── context/ # AuthContext, AlertContext (ThemeContext lives in src/context/)
|
||||
│ ├── components/ # Non-page components: RichEditor (Quill), PlanGrid, file manager, dashboard/ + warehouse/ widgets
|
||||
│ ├── components/ # Non-page components: RichEditor (Quill), PlanGrid, file manager, dashboard/ + warehouse/ widgets, odin/ (AI chat)
|
||||
│ ├── pages/ # One file per page/feature
|
||||
│ ├── lib/ # React Query options & mutations (queries/) + shared label maps
|
||||
│ ├── hooks/ # usePaginatedQuery, useTableSort, useDebounce, useReducedMotion, …
|
||||
│ └── utils/ # api.ts (fetch wrapper with token refresh), formatters, helpers
|
||||
└── __tests__/ # Vitest tests (~14 files: auth, numbering, warehouse, plan, invoices, …)
|
||||
└── __tests__/ # Vitest tests (17 files: auth, numbering, warehouse, plan, invoices, ai/Odin, received-invoices VAT, …)
|
||||
|
||||
prisma/
|
||||
├── schema.prisma # 49 models, MySQL, snake_case columns
|
||||
├── schema.prisma # 52 models, MySQL, snake_case columns
|
||||
└── migrations/ # Applied migrations
|
||||
|
||||
dist/ # Compiled server (CommonJS, ES2022)
|
||||
@@ -240,7 +241,7 @@ if ("error" in body) return error(reply, body.error, 400);
|
||||
|
||||
Tests live in `src/__tests__/`. They use Vitest + Supertest against a real test database (`.env.test`).
|
||||
|
||||
- The suite spans ~14 files / 152 tests — auth, numbering, warehouse, plan, invoices, exchange-rates, schema coercion, NAS file manager, env, manual-create. Server-side only (no component tests yet).
|
||||
- The suite spans 17 files / 195 tests — auth, numbering, warehouse, plan, invoices, exchange-rates, schema coercion, NAS file manager, env, manual-create, AI/Odin (conversation CRUD, isolation, auto-title, cascade, budget), received-invoices VAT. Server-side only (no component tests yet).
|
||||
- Use `buildApp()` helper to spin up the Fastify instance for tests.
|
||||
- Tests use `vitest.config.ts` with `environment: 'node'` and 15s timeout.
|
||||
- **Do not mock Prisma** — tests hit a real database to catch schema/query bugs.
|
||||
@@ -305,6 +306,19 @@ The admin frontend is **fully on Material UI v7** (Emotion). The old ~7,100 line
|
||||
|
||||
---
|
||||
|
||||
## AI Assistant — "Odin" (shipped v2.1.5)
|
||||
|
||||
Admins-only Claude assistant on the `/odin` page (sidebar nav item "Odin"). **Phase-1 scope is invoice import ONLY** — general chat is guarded off in `OdinChat.submit` to avoid spending API credits: a text-only message gets a canned reply and makes NO AI call. Removing that one guard re-enables the `/chat` path for a later "general assistant" phase.
|
||||
|
||||
- **SDK / model:** `@anthropic-ai/sdk` → `claude-sonnet-4-6`. Server-side only — `ANTHROPIC_API_KEY` in `.env` (already set on prod; **don't touch env, the user manages it**). The whole feature self-hides when the key is absent (`/ai/usage` returns `configured:false`).
|
||||
- **Backend:** `src/services/ai.service.ts` (chat, `extractInvoice` [PDF→structured-output JSON], cost/budget tracking, conversation CRUD with server-side auto-title), `src/routes/admin/ai.ts` (`/api/admin/ai/*`: usage, budget, chat, extract-invoices, conversations[/:id/messages]), `src/schemas/ai.schema.ts`. Every route `requirePermission("ai.use")` (granted to **admin only** via migration).
|
||||
- **Data:** `ai_usage` (per-call token-cost ledger), `ai_conversations` + `ai_chat_messages` (per-user, FK cascade, auto-title from first message), `company_settings.ai_monthly_budget_usd` (default $50; `assertBudgetAvailable` → 402 at the cap).
|
||||
- **Frontend:** `src/admin/pages/Odin.tsx` → `src/admin/components/odin/`: `OdinChat` (orchestrator + state + the proven submit/extract/save logic), `OdinSidebar` (conversation list; inline ≥md, slide-in Drawer below md), `OdinThread` (messages, framer-motion entrance, Newsreader serif greeting hero), `OdinComposer` (claude-style rounded multiline pill, attach/send icons), `InvoiceReviewCard`, `OdinMark` (animated brand mark — CSS keyframes via `styled`, not inline style; opacity-glow fallback under reduced-motion), `types.ts`. Queries in `src/admin/lib/queries/ai.ts`. `Fraunces`→`Newsreader` font added to `index.html`.
|
||||
- **Invoice flow:** attach PDF(s) → `extract-invoices` → editable review cards → save to the EXISTING `POST /received-invoices`. **`received_invoices.amount` is GROSS (VAT-inclusive)** — VAT is back-calculated via `vatFromGross` in `received-invoices.ts` (`amount * rate/(100+rate)`), used by both the manual form and the AI import. The save button is gated on `invoices.create`.
|
||||
- **Phase 2 (general assistant — NOT built):** forward-looking design notes in `docs/superpowers/specs/2026-06-08-odin-phase2-general-assistant-notes.md` (tool-use over services, structured message-block storage, per-action authorization). Phase-1 spec/plan also under `docs/superpowers/`.
|
||||
|
||||
---
|
||||
|
||||
## Database Conventions
|
||||
|
||||
- All models use `snake_case` column names; Prisma maps to camelCase in TypeScript.
|
||||
|
||||
1274
docs/superpowers/plans/2026-06-08-ai-assistant-phase1.md
Normal file
1274
docs/superpowers/plans/2026-06-08-ai-assistant-phase1.md
Normal file
File diff suppressed because it is too large
Load Diff
891
docs/superpowers/plans/2026-06-08-bulk-plan-creation.md
Normal file
891
docs/superpowers/plans/2026-06-08-bulk-plan-creation.md
Normal file
@@ -0,0 +1,891 @@
|
||||
# Bulk Plan Creation Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Assign one project/category to many employees over a date range in a single action ("Hromadné přiřazení" on /plan-work).
|
||||
|
||||
**Architecture:** A new `POST /api/admin/plan/entries/bulk` endpoint drives a `bulkCreateEntries` service that, per employee, computes the eligible days in the range (weekday filter + Feature A's under-cap rule), groups contiguous eligible days into runs, and creates one range `work_plan_entries` row per run by **reusing `createEntry`**. The frontend adds a presentational `BulkPlanModal` (mirroring the single-create form + the existing bulk-attendance employee picker) wired from `PlanWork`, with a summary alert and `["plan"]` invalidation. No DB migration.
|
||||
|
||||
**Tech Stack:** Fastify 5 + Prisma (MySQL), Zod 4, React 18 + MUI v7, TanStack Query, Vitest (server-side, real test DB). Spec: `docs/superpowers/specs/2026-06-08-bulk-plan-creation-design.md`. Builds on Feature A (multi-record plan cells, v2.0.5).
|
||||
|
||||
**Gates:** `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`. The frontend has no component-test harness (server-side tests only), so Task 2 gates on `tsc -b` + `build`.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
**Backend**
|
||||
|
||||
- `src/schemas/plan.schema.ts` — add `BulkPlanEntrySchema`.
|
||||
- `src/services/plan.service.ts` — add `bulkCreateEntries(...)` (reuses `createEntry`, `assertNotPastDate`, `assertActiveCategory`, `toDateOnly`, `MAX_RECORDS_PER_CELL`).
|
||||
- `src/routes/admin/plan.ts` — add `POST /entries/bulk`.
|
||||
|
||||
**Frontend**
|
||||
|
||||
- `src/admin/components/BulkPlanModal.tsx` — new presentational modal.
|
||||
- `src/admin/hooks/usePlanWork.ts` — add a `bulkCreate` mutation.
|
||||
- `src/admin/pages/PlanWork.tsx` — toolbar button + bulk form state + toggles + submit wiring.
|
||||
|
||||
**Tests**
|
||||
|
||||
- `src/__tests__/plan.test.ts` — `bulkCreateEntries` service tests.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Backend — bulk endpoint + service
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/schemas/plan.schema.ts`
|
||||
- Modify: `src/services/plan.service.ts`
|
||||
- Modify: `src/routes/admin/plan.ts`
|
||||
- Test: `src/__tests__/plan.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing service tests**
|
||||
|
||||
Add this block to the end of `src/__tests__/plan.test.ts` (before the final HTTP describe block is fine; anywhere at top level). It imports `bulkCreateEntries` — add it to the existing `import { ... } from "../services/plan.service"` list at the top of the file.
|
||||
|
||||
```ts
|
||||
// ---------------------------------------------------------------------------
|
||||
// bulkCreateEntries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("plan.service.bulkCreateEntries", () => {
|
||||
it("creates one continuous range per employee when weekends are included", async () => {
|
||||
// 2096-06-01 is a Friday; 2096-06-03 is a Sunday. include_weekends → one
|
||||
// range 06-01..06-03 covering all 3 days.
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-wknd`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(1);
|
||||
expect(res.data.created_days).toBe(3);
|
||||
expect(res.data.skipped_days).toBe(0);
|
||||
expect(res.data.users).toBe(1);
|
||||
});
|
||||
|
||||
it("splits into per-work-week ranges and skips weekends when excluded", async () => {
|
||||
// 2096-06-01 (Fri) .. 2096-06-05 (Tue): Fri | Sat Sun excluded | Mon Tue.
|
||||
// Two runs: [06-01] and [06-04..06-05] → 2 entries, 3 days, 0 skipped.
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-05",
|
||||
include_weekends: false,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-week`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(3);
|
||||
expect(res.data.skipped_days).toBe(0);
|
||||
});
|
||||
|
||||
it("skips days already at the cap and splits the range around them", async () => {
|
||||
// Pre-fill 2096-07-02 to the cap (3 entries) for the user. A weekends-on
|
||||
// bulk over 07-01..07-03 then creates 07-01 and 07-03 (two ranges), skips
|
||||
// 07-02. 2096-07-01..03 are Sun/Mon/Tue — all included with weekends on.
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2096-07-02"),
|
||||
date_to: new Date("2096-07-02"),
|
||||
category: "work",
|
||||
note: `${N}cap${i}`,
|
||||
created_by: adminUserId,
|
||||
},
|
||||
});
|
||||
}
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-07-01",
|
||||
date_to: "2096-07-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-cap`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(2);
|
||||
expect(res.data.skipped_days).toBe(1);
|
||||
});
|
||||
|
||||
it("aggregates across multiple employees", async () => {
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId, noPermUserId],
|
||||
date_from: "2096-08-03", // Friday
|
||||
date_to: "2096-08-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-multi`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.users).toBe(2);
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects empty user_ids, past dates, bad range, and inactive category", async () => {
|
||||
const empty = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in empty && empty.status).toBe(400);
|
||||
|
||||
const past = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2000-01-01",
|
||||
date_to: "2000-01-02",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in past && past.status).toBe(403);
|
||||
|
||||
const badRange = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-10",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in badRange && badRange.status).toBe(400);
|
||||
|
||||
const badCat = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "__nope__",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in badCat && badCat.status).toBe(400);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the tests to verify they fail**
|
||||
|
||||
Run: `npx vitest run src/__tests__/plan.test.ts`
|
||||
Expected: FAIL — `bulkCreateEntries` is not exported / not a function.
|
||||
|
||||
- [ ] **Step 3: Implement `bulkCreateEntries` in `plan.service.ts`**
|
||||
|
||||
Add at the end of `src/services/plan.service.ts` (after `listOverrides`):
|
||||
|
||||
```ts
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bulk entry creation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Bulk-assign a project/category to many employees over a date range. For each
|
||||
* employee, walk the range, keep the days that pass the weekday filter
|
||||
* (weekends excluded unless include_weekends) AND are under the per-cell cap,
|
||||
* group contiguous kept days into runs, and create one range entry per run by
|
||||
* reusing createEntry (so cap / past-date / category validation stays DRY).
|
||||
*
|
||||
* Days that pass the weekday filter but are already at the cap are counted in
|
||||
* skipped_days (and split the range). Weekend days, when excluded, are out of
|
||||
* scope and are NOT counted as skipped.
|
||||
*/
|
||||
export async function bulkCreateEntries(
|
||||
input: {
|
||||
user_ids: number[];
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
include_weekends: boolean;
|
||||
project_id?: number | null;
|
||||
category: string;
|
||||
note: string;
|
||||
},
|
||||
actorUserId: number,
|
||||
): Promise<
|
||||
Result<{
|
||||
created_entries: number;
|
||||
created_days: number;
|
||||
skipped_days: number;
|
||||
users: number;
|
||||
}>
|
||||
> {
|
||||
if (input.user_ids.length === 0) {
|
||||
return { error: "Vyberte alespoň jednoho zaměstnance", status: 400 };
|
||||
}
|
||||
if (input.date_to < input.date_from) {
|
||||
return { error: "Datum do musí být stejné nebo po datumu od", status: 400 };
|
||||
}
|
||||
const lockFrom = assertNotPastDate(input.date_from, false);
|
||||
if (lockFrom) return lockFrom;
|
||||
const lockTo = assertNotPastDate(input.date_to, false);
|
||||
if (lockTo) return lockTo;
|
||||
const catErr = await assertActiveCategory(input.category);
|
||||
if (catErr) return catErr;
|
||||
|
||||
const from = toDateOnly(input.date_from);
|
||||
const to = toDateOnly(input.date_to);
|
||||
|
||||
// The day list for the whole range (UTC midnights), built once.
|
||||
const days: Date[] = [];
|
||||
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
|
||||
days.push(new Date(d));
|
||||
}
|
||||
|
||||
let createdEntries = 0;
|
||||
let createdDays = 0;
|
||||
let skippedDays = 0;
|
||||
|
||||
for (const userId of input.user_ids) {
|
||||
// Per-day cap counts from this user's existing active entries.
|
||||
const existing = await prisma.work_plan_entries.findMany({
|
||||
where: {
|
||||
user_id: userId,
|
||||
is_deleted: false,
|
||||
date_from: { lte: to },
|
||||
date_to: { gte: from },
|
||||
},
|
||||
select: { date_from: true, date_to: true },
|
||||
});
|
||||
const countFor = (day: Date): number =>
|
||||
existing.filter((e) => e.date_from <= day && e.date_to >= day).length;
|
||||
|
||||
// Eligibility per day (weekday filter + under-cap). Tally cap skips.
|
||||
const eligible: boolean[] = [];
|
||||
for (const day of days) {
|
||||
const dow = day.getUTCDay(); // 0 = Sun, 6 = Sat
|
||||
const isWeekend = dow === 0 || dow === 6;
|
||||
if (isWeekend && !input.include_weekends) {
|
||||
eligible.push(false);
|
||||
continue;
|
||||
}
|
||||
if (countFor(day) >= MAX_RECORDS_PER_CELL) {
|
||||
skippedDays++;
|
||||
eligible.push(false);
|
||||
continue;
|
||||
}
|
||||
eligible.push(true);
|
||||
}
|
||||
|
||||
// Group contiguous eligible days into runs; create one range per run.
|
||||
let runStart = -1;
|
||||
for (let i = 0; i <= days.length; i++) {
|
||||
const ok = i < days.length && eligible[i];
|
||||
if (ok && runStart === -1) {
|
||||
runStart = i;
|
||||
} else if (!ok && runStart !== -1) {
|
||||
const segFrom = days[runStart].toISOString().slice(0, 10);
|
||||
const segTo = days[i - 1].toISOString().slice(0, 10);
|
||||
const runDays = i - runStart;
|
||||
const res = await createEntry(
|
||||
{
|
||||
user_id: userId,
|
||||
date_from: segFrom,
|
||||
date_to: segTo,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
},
|
||||
actorUserId,
|
||||
false,
|
||||
);
|
||||
if ("data" in res) {
|
||||
createdEntries++;
|
||||
createdDays += runDays;
|
||||
} else {
|
||||
// Rare race (e.g. the cap filled concurrently). Treat as skipped.
|
||||
skippedDays += runDays;
|
||||
}
|
||||
runStart = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
created_entries: createdEntries,
|
||||
created_days: createdDays,
|
||||
skipped_days: skippedDays,
|
||||
users: input.user_ids.length,
|
||||
},
|
||||
oldData: null,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the service tests to verify they pass**
|
||||
|
||||
Run: `npx vitest run src/__tests__/plan.test.ts`
|
||||
Expected: PASS (including the 5 new bulk tests).
|
||||
|
||||
- [ ] **Step 5: Add `BulkPlanEntrySchema` to `plan.schema.ts`**
|
||||
|
||||
Append to `src/schemas/plan.schema.ts`:
|
||||
|
||||
```ts
|
||||
export const BulkPlanEntrySchema = z
|
||||
.object({
|
||||
user_ids: z
|
||||
.array(intFromForm)
|
||||
.min(1, "Vyberte alespoň jednoho zaměstnance"),
|
||||
date_from: isoDate,
|
||||
date_to: isoDate,
|
||||
include_weekends: z
|
||||
.union([z.boolean(), z.string()])
|
||||
.transform((v) => v === true || v === "true" || v === "1")
|
||||
.default(false),
|
||||
project_id: z
|
||||
.union([z.number(), z.string(), z.null()])
|
||||
.transform((v) => (v === null ? null : Number(v)))
|
||||
.nullish(),
|
||||
category: planCategoryEnum.default("work"),
|
||||
note: z.string().max(500, "Maximálně 500 znaků").default(""),
|
||||
})
|
||||
.refine((v) => v.date_to >= v.date_from, {
|
||||
message: "Datum do musí být stejné nebo po datumu od",
|
||||
path: ["date_to"],
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Add the `POST /entries/bulk` route**
|
||||
|
||||
In `src/routes/admin/plan.ts`: add `bulkCreateEntries` to the existing import from `../../services/plan.service` and `BulkPlanEntrySchema` to the import from `../../schemas/plan.schema`. Then add this route immediately after the `POST /entries` handler (after its closing `);`, before `PATCH /entries/:id`):
|
||||
|
||||
```ts
|
||||
// --- POST /plan/entries/bulk ---
|
||||
app.post(
|
||||
"/entries/bulk",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(BulkPlanEntrySchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const result = await bulkCreateEntries(
|
||||
body.data!,
|
||||
request.authData!.userId,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "work_plan_entry",
|
||||
description: `Hromadné přiřazení: ${body.data!.category} — ${result.data.users} zaměstnanců, ${body.data!.date_from}–${body.data!.date_to} (${result.data.created_days} dní)`,
|
||||
});
|
||||
return success(reply, result.data, 201, "Hromadné přiřazení dokončeno");
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
- [ ] **Step 7: Add an HTTP route test**
|
||||
|
||||
Add to the `describe("HTTP /api/admin/plan", ...)` block in `src/__tests__/plan.test.ts`:
|
||||
|
||||
```ts
|
||||
it("POST /entries/bulk requires attendance.manage", async () => {
|
||||
const res = await authPost("/api/admin/plan/entries/bulk", noPermToken, {
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2095-06-01",
|
||||
date_to: "2095-06-01",
|
||||
include_weekends: true,
|
||||
category: "work",
|
||||
note: `${N}bulk-forbidden`,
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("POST /entries/bulk creates entries for an admin and returns a summary", async () => {
|
||||
const res = await authPost("/api/admin/plan/entries/bulk", adminToken, {
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2095-06-05", // Sunday; weekends on → 1 day
|
||||
date_to: "2095-06-05",
|
||||
include_weekends: true,
|
||||
category: "work",
|
||||
note: `${N}bulk-http`,
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.created_days).toBe(1);
|
||||
expect(body.data.users).toBe(1);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 8: Gate**
|
||||
|
||||
Run: `npx tsc -b --noEmit` (exit 0), then `npx vitest run` (all pass).
|
||||
|
||||
- [ ] **Step 9: Commit**
|
||||
|
||||
```bash
|
||||
git add src/schemas/plan.schema.ts src/services/plan.service.ts src/routes/admin/plan.ts src/__tests__/plan.test.ts
|
||||
git commit -m "feat(plan): bulk entry creation endpoint + service"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Frontend — bulk modal + wiring
|
||||
|
||||
**Files:**
|
||||
|
||||
- Create: `src/admin/components/BulkPlanModal.tsx`
|
||||
- Modify: `src/admin/hooks/usePlanWork.ts`
|
||||
- Modify: `src/admin/pages/PlanWork.tsx`
|
||||
|
||||
Frontend-only; gate on `tsc -b` + `build` (no component-test harness). Mirrors `BulkAttendanceModal.tsx` (presentational; parent owns state + toggles + submit).
|
||||
|
||||
- [ ] **Step 1: Create `BulkPlanModal.tsx`**
|
||||
|
||||
```tsx
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import {
|
||||
Modal,
|
||||
Field,
|
||||
DateField,
|
||||
Select,
|
||||
TextField,
|
||||
CheckboxField,
|
||||
} from "../ui";
|
||||
import type { PlanUser, PlanCategory } from "../lib/queries/plan";
|
||||
import type { Project } from "../lib/queries/projects";
|
||||
|
||||
export interface BulkPlanForm {
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
is_range: boolean;
|
||||
user_ids: string[];
|
||||
include_weekends: boolean;
|
||||
project_id: string;
|
||||
category: string;
|
||||
note: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
form: BulkPlanForm;
|
||||
setForm: (form: BulkPlanForm) => void;
|
||||
users: PlanUser[];
|
||||
projects: Project[];
|
||||
categories: PlanCategory[];
|
||||
onSubmit: () => void;
|
||||
submitting: boolean;
|
||||
toggleUser: (userId: number) => void;
|
||||
toggleAllUsers: () => void;
|
||||
}
|
||||
|
||||
export default function BulkPlanModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
form,
|
||||
setForm,
|
||||
users,
|
||||
projects,
|
||||
categories,
|
||||
onSubmit,
|
||||
submitting,
|
||||
toggleUser,
|
||||
toggleAllUsers,
|
||||
}: Props) {
|
||||
const activeCategories = categories.filter((c) => c.is_active);
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Hromadné přiřazení"
|
||||
maxWidth="lg"
|
||||
loading={submitting}
|
||||
onSubmit={onSubmit}
|
||||
submitText="Vytvořit"
|
||||
submitDisabled={form.user_ids.length === 0}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{ mt: 0.25, mb: 2 }}
|
||||
>
|
||||
Vytvoří záznamy pro vybrané dny u zvolených zaměstnanců. Dny, které už
|
||||
mají 3 záznamy, se přeskočí.
|
||||
</Typography>
|
||||
|
||||
<Field label="Datum od">
|
||||
<DateField
|
||||
value={form.date_from}
|
||||
onChange={(val) => setForm({ ...form, date_from: val })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Rozsah dnů">
|
||||
<CheckboxField
|
||||
label="Více dní"
|
||||
checked={form.is_range}
|
||||
onChange={(checked) => setForm({ ...form, is_range: checked })}
|
||||
/>
|
||||
</Field>
|
||||
{form.is_range && (
|
||||
<Field label="Datum do">
|
||||
<DateField
|
||||
value={form.date_to}
|
||||
onChange={(val) => setForm({ ...form, date_to: val })}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Víkendy">
|
||||
<CheckboxField
|
||||
label="Zahrnout víkendy"
|
||||
checked={form.include_weekends}
|
||||
onChange={(checked) =>
|
||||
setForm({ ...form, include_weekends: checked })
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, mb: 0.5 }}>
|
||||
<Typography
|
||||
component="span"
|
||||
variant="body2"
|
||||
sx={{ fontWeight: 600, color: "text.secondary" }}
|
||||
>
|
||||
Zaměstnanci
|
||||
</Typography>
|
||||
<Typography
|
||||
component="button"
|
||||
type="button"
|
||||
onClick={toggleAllUsers}
|
||||
variant="caption"
|
||||
sx={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
p: 0,
|
||||
cursor: "pointer",
|
||||
fontWeight: 500,
|
||||
color: "primary.main",
|
||||
}}
|
||||
>
|
||||
{form.user_ids.length === users.length
|
||||
? "Odznačit vše"
|
||||
: "Vybrat vše"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 0.25,
|
||||
maxHeight: 200,
|
||||
overflowY: "auto",
|
||||
p: 1.5,
|
||||
bgcolor: "action.hover",
|
||||
borderRadius: 2,
|
||||
border: 1,
|
||||
borderColor: "divider",
|
||||
}}
|
||||
>
|
||||
{users.map((u) => (
|
||||
<CheckboxField
|
||||
key={u.id}
|
||||
label={u.full_name}
|
||||
checked={form.user_ids.includes(String(u.id))}
|
||||
onChange={() => toggleUser(u.id)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
Vybráno: {form.user_ids.length} z {users.length}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Field label="Projekt">
|
||||
<Select
|
||||
value={form.project_id}
|
||||
onChange={(val) => setForm({ ...form, project_id: val })}
|
||||
options={[
|
||||
{ value: "", label: "— bez projektu —" },
|
||||
...projects.map((p) => ({ value: String(p.id), label: p.name })),
|
||||
]}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Kategorie">
|
||||
<Select
|
||||
value={form.category}
|
||||
onChange={(val) => setForm({ ...form, category: val })}
|
||||
options={activeCategories.map((c) => ({
|
||||
value: c.key,
|
||||
label: c.label,
|
||||
}))}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Text poznámky (volitelný)">
|
||||
<TextField
|
||||
multiline
|
||||
minRows={2}
|
||||
value={form.note}
|
||||
onChange={(e) => setForm({ ...form, note: e.target.value })}
|
||||
inputProps={{ maxLength: 500 }}
|
||||
/>
|
||||
</Field>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add a `bulkCreate` mutation to `usePlanWork.ts`**
|
||||
|
||||
After the `deleteOverride` mutation definition (before the `rollbackMutation` function), add:
|
||||
|
||||
```ts
|
||||
const bulkCreate = useMutation({
|
||||
mutationFn: (body: any) =>
|
||||
apiCall("/api/admin/plan/entries/bulk", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
onSuccess: () => {
|
||||
// No optimistic patch — bulk can touch many cells; just invalidate and
|
||||
// let the grid refetch the authoritative state.
|
||||
invalidate();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Add `bulkCreate` to the hook's return object (next to `createEntry`, etc.).
|
||||
|
||||
- [ ] **Step 3: Wire the bulk modal into `PlanWork.tsx`**
|
||||
|
||||
(a) Add imports near the other component imports:
|
||||
|
||||
```ts
|
||||
import BulkPlanModal, { type BulkPlanForm } from "../components/BulkPlanModal";
|
||||
```
|
||||
|
||||
(b) Pull `bulkCreate` out of the `usePlanWork(...)` destructure (alongside `createEntry`, etc.).
|
||||
|
||||
(c) Add bulk state + a default form (place near the other `useState` declarations, after `catModalOpen`):
|
||||
|
||||
```ts
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
const [bulkSubmitting, setBulkSubmitting] = useState(false);
|
||||
const [bulkForm, setBulkForm] = useState<BulkPlanForm>(() => {
|
||||
const today = todayIsoLocal();
|
||||
return {
|
||||
date_from: today,
|
||||
date_to: today,
|
||||
is_range: false,
|
||||
user_ids: [],
|
||||
include_weekends: false,
|
||||
project_id: "",
|
||||
category: "work",
|
||||
note: "",
|
||||
};
|
||||
});
|
||||
|
||||
const planUsers = grid?.users ?? [];
|
||||
|
||||
const toggleBulkUser = useCallback((userId: number) => {
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
user_ids: prev.user_ids.includes(String(userId))
|
||||
? prev.user_ids.filter((u) => u !== String(userId))
|
||||
: [...prev.user_ids, String(userId)],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const toggleAllBulkUsers = useCallback(() => {
|
||||
const allIds = (grid?.users ?? []).map((u) => String(u.id));
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
user_ids: prev.user_ids.length === allIds.length ? [] : allIds,
|
||||
}));
|
||||
}, [grid]);
|
||||
|
||||
const submitBulk = useCallback(async () => {
|
||||
if (bulkForm.user_ids.length === 0) return;
|
||||
setBulkSubmitting(true);
|
||||
try {
|
||||
const data: any = await bulkCreate.mutateAsync({
|
||||
user_ids: bulkForm.user_ids.map(Number),
|
||||
date_from: bulkForm.date_from,
|
||||
date_to: bulkForm.is_range ? bulkForm.date_to : bulkForm.date_from,
|
||||
include_weekends: bulkForm.include_weekends,
|
||||
project_id: bulkForm.project_id ? Number(bulkForm.project_id) : null,
|
||||
category: bulkForm.category,
|
||||
note: bulkForm.note,
|
||||
});
|
||||
const skipped =
|
||||
data?.skipped_days > 0
|
||||
? ` ${data.skipped_days} dní přeskočeno (limit 3 na den).`
|
||||
: "";
|
||||
alert.success(
|
||||
`Vytvořeno ${data?.created_days ?? 0} záznamů pro ${data?.users ?? 0} zaměstnanců.${skipped}`,
|
||||
);
|
||||
setBulkOpen(false);
|
||||
} catch (e) {
|
||||
alert.error(e instanceof Error ? e.message : "Chyba při ukládání");
|
||||
} finally {
|
||||
setBulkSubmitting(false);
|
||||
}
|
||||
}, [bulkForm, bulkCreate, alert]);
|
||||
```
|
||||
|
||||
(d) Add the toolbar button next to "Správa kategorií" (inside the same `canEdit` region of the toolbar `<Box>`):
|
||||
|
||||
```tsx
|
||||
{
|
||||
canEdit && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
onClick={() => setBulkOpen(true)}
|
||||
>
|
||||
Hromadné přiřazení
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
(e) Render the modal alongside `<PlanCategoriesModal ... />`:
|
||||
|
||||
```tsx
|
||||
<BulkPlanModal
|
||||
isOpen={bulkOpen}
|
||||
onClose={() => setBulkOpen(false)}
|
||||
form={bulkForm}
|
||||
setForm={setBulkForm}
|
||||
users={planUsers}
|
||||
projects={projects}
|
||||
categories={categories}
|
||||
onSubmit={submitBulk}
|
||||
submitting={bulkSubmitting}
|
||||
toggleUser={toggleBulkUser}
|
||||
toggleAllUsers={toggleAllBulkUsers}
|
||||
/>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Gate + Chrome check**
|
||||
|
||||
```bash
|
||||
npx tsc -b --noEmit
|
||||
npm run build
|
||||
```
|
||||
|
||||
Then in Chrome on `/plan-work` (dev server already running — do not start it): click "Hromadné přiřazení", select 2 employees, a date range with "Více dní", leave weekends off, pick a project + category, submit; confirm the grid fills only Mon–Fri across the selected people, the summary alert shows counts, and re-running on a day already at 3 records skips it.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/admin/components/BulkPlanModal.tsx src/admin/hooks/usePlanWork.ts src/admin/pages/PlanWork.tsx
|
||||
git commit -m "feat(plan): bulk assignment modal on /plan-work"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Release v2.0.6
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `package.json`
|
||||
|
||||
- [ ] **Step 1: Bump version** to `"version": "2.0.6"` in `package.json`.
|
||||
|
||||
- [ ] **Step 2: Full gate**
|
||||
|
||||
```bash
|
||||
npx tsc -b --noEmit
|
||||
npx vitest run
|
||||
npm run build
|
||||
```
|
||||
|
||||
Expected: tsc exit 0, vitest all pass, build success.
|
||||
|
||||
- [ ] **Step 3: Merge to master + commit + tag**
|
||||
|
||||
```bash
|
||||
git checkout master
|
||||
git merge --ff-only feat/bulk-plan-creation
|
||||
git add package.json
|
||||
git commit -m "chore(release): v2.0.6 — bulk plan creation"
|
||||
git tag -a v2.0.6 -m "v2.0.6 — bulk plan creation"
|
||||
```
|
||||
|
||||
(If implementation happened directly on master, skip the checkout/merge.)
|
||||
|
||||
- [ ] **Step 4: Push to Gitea**
|
||||
|
||||
```bash
|
||||
git push origin master
|
||||
git push origin v2.0.6
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Build tarball + deploy to production (REQUIRES explicit user confirmation)**
|
||||
|
||||
```bash
|
||||
tar -czf app-ts-2.0.6.tar.gz dist dist-client prisma package.json package-lock.json scripts
|
||||
scp app-ts-2.0.6.tar.gz boha_admin@192.168.50.100:/tmp/
|
||||
ssh boha_admin@192.168.50.100 'set -e; cd /var/www/app-ts && rm -rf dist dist-client prisma scripts package.json package-lock.json && tar -xzf /tmp/app-ts-2.0.6.tar.gz && npm install --omit=dev && npx prisma migrate deploy && pm2 restart app-ts --update-env'
|
||||
```
|
||||
|
||||
No migration ships in this release → `prisma migrate deploy` reports "No pending migrations".
|
||||
|
||||
- [ ] **Step 6: Health check**
|
||||
|
||||
```bash
|
||||
ssh boha_admin@192.168.50.100 'curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3001/; curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3001/api/admin/session'
|
||||
```
|
||||
|
||||
Expected: `200` then `401`. Confirm pm2 shows `app-ts` v2.0.6 online.
|
||||
|
||||
---
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- **Reuse, don't re-validate:** `bulkCreateEntries` calls `createEntry`, which already enforces the cap, past-date, category, and range checks. Don't duplicate those.
|
||||
- **`skipped_days` semantics:** only weekday-eligible days blocked by the cap count as skipped. Weekend days (when excluded) are out of scope, not skipped.
|
||||
- **No DB migration.** Don't run any prisma migrate command.
|
||||
- **Do not start the dev server** — the user runs it. Use the running instance for the Chrome check.
|
||||
- **Do not deploy to production without explicit confirmation** (Task 3, Steps 5–6).
|
||||
792
docs/superpowers/plans/2026-06-08-odin-conversations.md
Normal file
792
docs/superpowers/plans/2026-06-08-odin-conversations.md
Normal 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 ~52–333) — 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.
|
||||
190
docs/superpowers/specs/2026-06-08-ai-assistant-phase1-design.md
Normal file
190
docs/superpowers/specs/2026-06-08-ai-assistant-phase1-design.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# Design — AI assistant, Phase 1 (chat + invoice import + budget cap)
|
||||
|
||||
**Date:** 2026-06-08
|
||||
**Status:** Approved (brainstorming) — ready for implementation plan
|
||||
**Phase 1 of 2.** Phase 2 (the AI querying system data via read-tools) is a separate later cycle — see "Deferred: Phase 2" at the end.
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Add the app's first AI capability: an **admin-only chat assistant embedded on the
|
||||
dashboard** where you can talk to Claude and, crucially, **attach received-invoice
|
||||
PDFs that the AI reads and imports into Přijaté faktury** (extract → you confirm →
|
||||
save). All AI usage is bounded by an **admin-editable monthly budget (default
|
||||
$50)** that hard-stops calls when exhausted.
|
||||
|
||||
## Decisions (locked in brainstorming)
|
||||
|
||||
- **Scope (Phase 1):** chat + invoice import + budget cap. **No system-data
|
||||
access** (the AI cannot query your invoices/projects/attendance — that's Phase 2).
|
||||
- **Placement:** a `DashAssistant` widget on the **dashboard, at the top under the
|
||||
welcome text** — not a separate page, not a floating bubble.
|
||||
- **Access:** **admins only**, via a new `ai.use` permission.
|
||||
- **Model:** **Claude Sonnet 4.6** (strong vision, low cost).
|
||||
- **Save flow:** extract → **you confirm/edit → save** (never silent auto-save).
|
||||
- **Budget:** **$50/month**, resets each calendar month, **admin-editable in
|
||||
Settings**; AI calls are **blocked** once the month's spend reaches the budget.
|
||||
- **Chat:** **non-streaming** (request → full reply) and **in-browser history
|
||||
only** (not persisted server-side) for v1 — both are easy later upgrades.
|
||||
|
||||
## Non-goals / out of scope (Phase 1)
|
||||
|
||||
- No system-data query tools / function-calling (Phase 2).
|
||||
- No server-side conversation persistence, no streaming.
|
||||
- No new invoice storage path — reuses `POST /received-invoices` verbatim.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
Greenfield AI integration; the rest of the app is unaffected and works unchanged
|
||||
if `ANTHROPIC_API_KEY` is absent (the assistant widget simply doesn't render and
|
||||
the AI routes return a clear "not configured" error).
|
||||
|
||||
- **Dependency:** `@anthropic-ai/sdk`.
|
||||
- **Env:** `ANTHROPIC_API_KEY` (required for the feature). Optional
|
||||
`AI_MONTHLY_BUDGET_USD` default seed (the live value lives in the DB, below).
|
||||
- **`src/services/ai.service.ts`** — wraps the SDK, owns the model choice + system
|
||||
prompt + cost accounting. Two operations:
|
||||
- `chat(messages)` → `client.messages.create({ model: "claude-sonnet-4-6", … })`,
|
||||
non-streaming, returns `{ reply: string, usage }`.
|
||||
- `extractInvoice(pdfBuffer, fileName)` → `client.messages.create` with the PDF as
|
||||
a `document` content block + `output_config.format` JSON-schema for the
|
||||
received-invoice fields, returns `{ fields, usage }`.
|
||||
- Both call the spend tracker to record usage **and** are gated by the budget
|
||||
guard (below) BEFORE the API call.
|
||||
- Isolated so tests can stub the Anthropic call (no real API in CI).
|
||||
|
||||
## Spend cap (the $50/month budget)
|
||||
|
||||
- **New table `ai_usage`** (migration): `id`, `user_id?`, `kind` ("chat" |
|
||||
"extract"), `model`, `input_tokens`, `output_tokens`, `cost_usd`
|
||||
`@db.Decimal(10,6)`, `created_at @db.Timestamp(0)`, with an index on
|
||||
`created_at`.
|
||||
- **Cost map** (in `ai.service.ts`): model → `{ inputPerToken, outputPerToken }`.
|
||||
Sonnet 4.6 = $3 / $15 per 1M → `0.000003` / `0.000015` per token. `cost_usd =
|
||||
in*inP + out*outP`.
|
||||
- **Budget value:** a new `ai_monthly_budget_usd Decimal @default(50)` column on
|
||||
`company_settings` (the existing app-config singleton). Admin-editable in
|
||||
Settings.
|
||||
- **Budget guard `assertBudgetAvailable()`:** sum `cost_usd` for rows where
|
||||
`created_at >= startOfMonth(now)`; if `>= ai_monthly_budget_usd`, return
|
||||
`{ error: "Měsíční rozpočet AI byl vyčerpán", status: 402 }`. Called at the top
|
||||
of every AI route BEFORE the Claude call.
|
||||
- **Usage read:** `GET /api/admin/ai/usage` → `{ month_spend_usd, budget_usd,
|
||||
remaining_usd }` for the chat's budget indicator and the Settings page.
|
||||
|
||||
## Backend routes — `src/routes/admin/ai.ts`
|
||||
|
||||
All guarded by `requirePermission("ai.use")`.
|
||||
|
||||
- `POST /api/admin/ai/chat` — body `{ messages: {role, content}[] }`. Budget guard →
|
||||
`ai.service.chat` → log usage → `success(reply: string, remaining_usd)`.
|
||||
- `POST /api/admin/ai/extract-invoices` — multipart PDF files (≤ `MAX_UPLOAD_SIZE`,
|
||||
PDF/image only). Budget guard → `extractInvoice` per file → returns the extracted
|
||||
fields per file (NOT saved) + usage. The files are **not** persisted here.
|
||||
- `GET /api/admin/ai/usage` — current-month spend + budget + remaining.
|
||||
|
||||
If `ANTHROPIC_API_KEY` is unset, the POST routes return
|
||||
`{ error: "AI není nakonfigurováno", status: 503 }`.
|
||||
|
||||
## Invoice import flow (extract → confirm → save)
|
||||
|
||||
1. Admin attaches one or more invoice PDFs in the dashboard chat (optionally with a
|
||||
text note).
|
||||
2. Frontend posts the files to `POST /ai/extract-invoices`; the AI returns the
|
||||
extracted fields for each.
|
||||
3. The chat renders an **editable review card per invoice** (dodavatel, číslo
|
||||
faktury, částka, měna, sazba DPH, datum vystavení/splatnosti, poznámka),
|
||||
pre-filled with the AI's values, plus a duplicate hint if `invoice_number` +
|
||||
`supplier_name` already exists.
|
||||
4. Admin glances/edits → **"Uložit"** (per card) or **"Uložit vše"**.
|
||||
5. The frontend submits **the original File + the confirmed metadata** to the
|
||||
**existing `POST /api/admin/received-invoices`** (multipart) — same NAS storage,
|
||||
same server-side VAT recompute, same audit. The AI never writes invoices
|
||||
directly. (The PDF is uploaded twice — once to extract, once to save — which is
|
||||
fine for invoice-sized files and avoids any server-side temp-file handling.)
|
||||
|
||||
## Frontend
|
||||
|
||||
- **`src/admin/components/dashboard/DashAssistant.tsx`** — the chat widget:
|
||||
message list, input box, attach-file button, and a small budget indicator
|
||||
("Rozpočet: $X.XX / $50"). Non-streaming; conversation in component state only.
|
||||
Renders the invoice review cards inline (reusing the received-invoice field
|
||||
inputs / kit components).
|
||||
- **`src/admin/pages/Dashboard.tsx`** — render `<DashAssistant />` at the top,
|
||||
directly under the welcome text, **only when** the user is admin / has `ai.use`
|
||||
(and only when AI is configured — a `GET /ai/usage` 503 hides it gracefully).
|
||||
- **`src/admin/lib/queries/ai.ts`** — React Query options/mutations for chat,
|
||||
extract, and usage. On a successful invoice save, invalidate `["received-invoices"]`.
|
||||
- **Settings** — an admin field to set the monthly budget (writes
|
||||
`company_settings.ai_monthly_budget_usd`).
|
||||
|
||||
## Permissions & migration
|
||||
|
||||
One Prisma migration:
|
||||
|
||||
- Create `ai_usage` table.
|
||||
- Add `ai_monthly_budget_usd` to `company_settings` (default 50).
|
||||
- Insert the `ai.use` permission and grant it to the **admin** role (explicit
|
||||
`INSERT`s in `migration.sql`, per the project's migration policy).
|
||||
|
||||
(The admin role bypasses permission checks via `roleName === "admin"`, but the
|
||||
explicit `ai.use` permission lets the access be widened later without code changes
|
||||
and documents intent.)
|
||||
|
||||
## Security / privacy
|
||||
|
||||
- **Phase 1 has no tools**, so the AI cannot take actions on your data — its only
|
||||
effect is the human-confirmed invoice save. A malicious/auto-generated invoice
|
||||
PDF therefore can't trigger anything (the injection-to-action surface arrives in
|
||||
Phase 2 and is designed there).
|
||||
- Attached PDFs are sent to the Anthropic API to be read. The API key lives in
|
||||
`.env` (server-side only), never exposed to the browser.
|
||||
- Standard sanitization already applies on the received-invoice render/PDF paths;
|
||||
AI-extracted text flows through the same validated `received_invoices` create.
|
||||
|
||||
## Testing
|
||||
|
||||
Server-side, real test DB, **Anthropic call stubbed** (no real API in CI):
|
||||
|
||||
- **Spend tracker:** `cost_usd` computed correctly from tokens for Sonnet 4.6;
|
||||
monthly sum only counts the current month.
|
||||
- **Budget guard:** under budget → allowed; at/over budget → `402` with the Czech
|
||||
message; the guard reads the DB budget value.
|
||||
- **Permissions:** all `/ai/*` routes return `403` without `ai.use`.
|
||||
- **Not-configured:** with no `ANTHROPIC_API_KEY`, POST routes return `503`.
|
||||
- **extract field-mapping:** given a stubbed AI response, the route returns the
|
||||
expected `received_invoices` field shape (and computes nothing that the existing
|
||||
create doesn't already).
|
||||
|
||||
Frontend has no component-test harness → gated by `tsc -b` + `build` + a manual
|
||||
check (the dashboard widget renders for admins, hidden otherwise).
|
||||
|
||||
Gates: `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`.
|
||||
|
||||
## Rollout
|
||||
|
||||
Ships as **v2.1.0** (notable new capability) via the standard process. **Requires a
|
||||
migration**, so the dev server must be stopped for `prisma migrate dev` (ask first),
|
||||
and the release runs `prisma migrate deploy` on prod. `ANTHROPIC_API_KEY` must be
|
||||
set in the production `.env` before the feature works.
|
||||
|
||||
---
|
||||
|
||||
## Deferred: Phase 2 (system-data access) — captured
|
||||
|
||||
A later, separate spec + cycle. The AI gains **read-only tools** (function calling)
|
||||
to answer questions about your data — e.g. "co je po splatnosti?", "kolik jsme
|
||||
fakturovali v květnu?". Key design work for Phase 2:
|
||||
|
||||
- A curated set of **read tools** (search invoices, overdue list, project lookup,
|
||||
attendance summary, …), each **scoped to the calling user's permissions** so the
|
||||
AI never returns data the user can't see.
|
||||
- The **agentic tool-loop** (Claude requests a tool → app executes against Prisma →
|
||||
returns results → Claude continues), with a per-conversation tool-call cap to
|
||||
bound cost (within the same monthly budget).
|
||||
- **Prompt-injection hardening:** because the AI will both read untrusted invoice
|
||||
content _and_ hold tools, tools stay **read-only**, results are treated as data,
|
||||
and any state-changing action remains human-confirmed.
|
||||
188
docs/superpowers/specs/2026-06-08-bulk-plan-creation-design.md
Normal file
188
docs/superpowers/specs/2026-06-08-bulk-plan-creation-design.md
Normal file
@@ -0,0 +1,188 @@
|
||||
# Design — Bulk plan creation (Feature B)
|
||||
|
||||
**Date:** 2026-06-08
|
||||
**Status:** Approved (brainstorming) — ready for implementation plan
|
||||
**Builds on:** Feature A (multi-record plan cells, max 3 per cell), shipped in v2.0.5. Spec: `docs/superpowers/specs/2026-06-08-multi-record-plan-cells-design.md`.
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Let a planner assign one project/category to **many employees over a date range
|
||||
in a single action**, instead of creating each person's plan record one by one.
|
||||
A "Hromadné přiřazení" button on **/plan-work** opens a modal that mirrors the
|
||||
existing single-record create form, plus an employee checklist and an "include
|
||||
weekends" toggle.
|
||||
|
||||
## Decisions (locked in brainstorming)
|
||||
|
||||
- **Modal mirrors single-create** (`Datum od` + "Více dní" → `Datum do`, Projekt,
|
||||
Kategorie, Text poznámky) **plus** a multi-select employee checklist and a
|
||||
**"Zahrnout víkendy"** checkbox.
|
||||
- **Storage = range entries** (`work_plan_entries`), one per contiguous run of
|
||||
eligible days per employee — the same row shape the single-create form produces.
|
||||
- **Weekends:** default off (Mon–Fri only). Only Sat/Sun are excluded — **no
|
||||
separate holiday handling**.
|
||||
- **Cap:** governed by Feature A's `MAX_RECORDS_PER_CELL = 3`. A day already at
|
||||
the cap for an employee is **skipped** (never overwritten), which also splits
|
||||
that employee's range around the skipped day.
|
||||
- **Past dates blocked** (no `force` exposed in the bulk UI).
|
||||
- **Category** picker defaults to **Práce**; **Project** is optional ("bez
|
||||
projektu"); **note** optional, applied to all created entries.
|
||||
|
||||
## Non-goals / out of scope
|
||||
|
||||
- No DB migration (reuses `work_plan_entries` and Feature A's cap logic).
|
||||
- No overwrite/replace of existing records (purely additive under the cap).
|
||||
- No holiday/`svátky` exclusion (only weekends).
|
||||
- No bulk creation of **overrides** — bulk always creates **entries** (the normal
|
||||
layer); single-day exceptions remain the per-cell day-panel's job.
|
||||
|
||||
---
|
||||
|
||||
## Storage & weekend behaviour
|
||||
|
||||
For each selected employee, the service computes the **eligible days** in
|
||||
`[date_from, date_to]` and groups **contiguous** eligible days into range
|
||||
entries.
|
||||
|
||||
A day `D` is **eligible** for employee `U` when all hold:
|
||||
|
||||
1. `D` is within `[date_from, date_to]` (inclusive).
|
||||
2. `include_weekends` is true, **or** `D` is a weekday (Mon–Fri).
|
||||
3. `U` has fewer than `MAX_RECORDS_PER_CELL` active entries covering `D` (under
|
||||
the cap).
|
||||
|
||||
Contiguous runs of eligible days become one range entry each
|
||||
(`date_from = run start`, `date_to = run end`). Consequences:
|
||||
|
||||
- **Víkendy ON, no cap conflicts:** one continuous range per employee — identical
|
||||
to creating a single multi-day record for everyone.
|
||||
- **Víkendy OFF:** one range per work-week (Mon–Fri chunks), because a weekend day
|
||||
breaks the run.
|
||||
- **A cap-full day** breaks the run too, so the range splits around it (and that
|
||||
`(employee, day)` is counted as skipped).
|
||||
|
||||
In the grid these are ordinary range entries — they show the "součást rozsahu"
|
||||
badge and open the range-vs-this-day chooser on click, exactly like
|
||||
manually-created ranges.
|
||||
|
||||
---
|
||||
|
||||
## Backend
|
||||
|
||||
### Route — `POST /api/admin/plan/entries/bulk`
|
||||
|
||||
- Guard: `requirePermission("attendance.manage")` (same as single entry create).
|
||||
- Body (validated by a new Zod schema `BulkPlanEntrySchema` in
|
||||
`src/schemas/plan.schema.ts`):
|
||||
```
|
||||
{
|
||||
user_ids: number[] // ≥1
|
||||
date_from: string // YYYY-MM-DD
|
||||
date_to: string // YYYY-MM-DD (≥ date_from)
|
||||
include_weekends: boolean
|
||||
project_id?: number | null
|
||||
category: string // default applied client-side; validated server-side
|
||||
note?: string // default ""
|
||||
}
|
||||
```
|
||||
- On success: one **summary audit** row (`logAudit`, action `create`, entityType
|
||||
`work_plan_entry`, description e.g. `Hromadné přiřazení: <kategorie> <projekt> —
|
||||
N zaměstnanců, <from>–<to> (<created_days> dní)`), then `success(reply,
|
||||
summary, 201, "Hromadné přiřazení dokončeno")`.
|
||||
|
||||
### Service — `bulkCreateEntries(input, actorUserId)` in `src/services/plan.service.ts`
|
||||
|
||||
Up-front validation (fail fast, nothing created):
|
||||
|
||||
- `user_ids.length >= 1` (else `{ error, status: 400 }`).
|
||||
- `date_to >= date_from` (else 400).
|
||||
- `assertNotPastDate(date_from, false)` and `assertNotPastDate(date_to, false)`
|
||||
(bulk blocks past dates; 403).
|
||||
- `assertActiveCategory(category)` (400 if inactive/unknown).
|
||||
|
||||
Then, per employee:
|
||||
|
||||
- Load the employee's active entries overlapping `[date_from, date_to]` once;
|
||||
compute per-day coverage counts.
|
||||
- Walk the days, mark eligible ones (weekday filter + under-cap), group contiguous
|
||||
runs.
|
||||
- For each run, create the range by **reusing `createEntry`**
|
||||
(`{ user_id, date_from: runStart, date_to: runEnd, project_id, category, note }`,
|
||||
`actorUserId`, `force: false`). Reusing `createEntry` keeps cap / past-date /
|
||||
category validation DRY; its cap re-check passes because every day in the run is
|
||||
already under the cap. A `createEntry` that nonetheless returns `{ error }` (rare
|
||||
race) is counted as skipped, not fatal.
|
||||
|
||||
Aggregate and return:
|
||||
|
||||
```
|
||||
{
|
||||
created_entries: number // range rows created
|
||||
created_days: number // (employee, day) records created
|
||||
skipped_days: number // weekday-eligible (employee, day) slots skipped at the cap
|
||||
users: number // employees processed
|
||||
}
|
||||
```
|
||||
|
||||
`skipped_days` counts only days that passed the weekday filter but were at the
|
||||
cap — weekend days (when excluded) are out of scope, not "skipped".
|
||||
|
||||
Best-effort across employees/segments (no cross-entry transaction): up-front
|
||||
validation already rejects bad input, and the cap-skip is by design. Partial
|
||||
results are reported in the summary.
|
||||
|
||||
---
|
||||
|
||||
## Frontend
|
||||
|
||||
### Modal — `src/admin/components/BulkPlanModal.tsx`
|
||||
|
||||
Mirrors the single-create `EditForm` fields + bulk-attendance's employee picker
|
||||
(`BulkAttendanceModal.tsx` is the pattern to follow):
|
||||
|
||||
- `Datum od` (DateField) + "Více dní" CheckboxField → `Datum do` (DateField).
|
||||
- **Zaměstnanci** — scrollable `CheckboxField` list (source: the plan users
|
||||
already loaded for the grid, `/plan/users`), with a "Vybrat vše" / "Odznačit
|
||||
vše" toggle and a "Vybráno X z Y" caption; submit disabled when none selected.
|
||||
- **Zahrnout víkendy** CheckboxField (default off).
|
||||
- **Projekt** Select (optional — "— bez projektu —"), **Kategorie** Select
|
||||
(active categories, default `work`/Práce), **Text poznámky** TextField (optional).
|
||||
- A short helper line, e.g. _"Vytvoří záznamy pro vybrané dny u zvolených
|
||||
zaměstnanců. Dny nad limit 3 záznamů se přeskočí."_
|
||||
|
||||
### Wiring — `src/admin/pages/PlanWork.tsx`
|
||||
|
||||
- A "Hromadné přiřazení" Button in the toolbar (next to "Správa kategorií"),
|
||||
rendered only when `canEdit` (`attendance.manage`).
|
||||
- A `bulkCreate` mutation (React Query) → `POST /api/admin/plan/entries/bulk`;
|
||||
on success show an alert summarising the returned counts (e.g. _"Vytvořeno 18
|
||||
záznamů pro 5 zaměstnanců; 4 dny přeskočeny (limit 3 na den)."_), close the
|
||||
modal, and `invalidate: ["plan"]` so the grid refreshes.
|
||||
|
||||
---
|
||||
|
||||
## Testing (`src/__tests__/plan.test.ts` or a new `bulkPlan.test.ts`)
|
||||
|
||||
Backend service tests against the real test DB:
|
||||
|
||||
- **Weekday filter:** weekends-off over a Mon–Sun span creates only Mon–Fri days
|
||||
(and as the expected number of per-work-week ranges); weekends-on creates one
|
||||
continuous range.
|
||||
- **Segmentation:** a cap-full day in the middle splits the range into two; the
|
||||
skipped day is counted in `skipped_days`.
|
||||
- **Cap skip:** an employee already at 3 entries on some days gets those days
|
||||
skipped; the summary reflects `created_days` vs `skipped_days`.
|
||||
- **Multi-employee aggregation:** `users`, `created_entries`, `created_days` sum
|
||||
correctly across the selected employees.
|
||||
- **Validation:** empty `user_ids` → 400; past `date_from` → 403; inactive
|
||||
category → 400; `date_to < date_from` → 400.
|
||||
|
||||
Gates: `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`.
|
||||
|
||||
## Rollout
|
||||
|
||||
Ships as **v2.0.6** via the standard process (commit → tag → Gitea → tarball →
|
||||
prod deploy → health check). No migration step. The grid refreshes via
|
||||
`["plan"]` invalidation.
|
||||
218
docs/superpowers/specs/2026-06-08-odin-conversations-design.md
Normal file
218
docs/superpowers/specs/2026-06-08-odin-conversations-design.md
Normal 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.
|
||||
@@ -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 → 3–10× 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.
|
||||
@@ -13,7 +13,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Urbanist:wght@300;400;500;600;700;800&display=swap"
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;0,6..72,600;1,6..72,400;1,6..72,500&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Urbanist:wght@300;400;500;600;700;800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
|
||||
|
||||
67
package-lock.json
generated
67
package-lock.json
generated
@@ -1,14 +1,15 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "app-ts",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.8",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.102.0",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
@@ -71,6 +72,27 @@
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/sdk": {
|
||||
"version": "0.102.0",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.102.0.tgz",
|
||||
"integrity": "sha512-cThh3KcPW3lzkFyTz1cjyhJvOVw45NkLMoowO2ZJ/76CBz44ADUon+NsjEc/PypAkARs72Xu8qxTnx6PAOTQUQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"json-schema-to-ts": "^3.1.1",
|
||||
"standardwebhooks": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"anthropic-ai-sdk": "bin/cli"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.25.0 || ^4.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"zod": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@asamuzakjp/css-color": {
|
||||
"version": "5.1.11",
|
||||
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",
|
||||
@@ -2249,6 +2271,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@stablelib/base64": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
|
||||
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@standard-schema/spec": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||
@@ -4073,6 +4101,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-sha256": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
|
||||
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
|
||||
@@ -4801,6 +4835,19 @@
|
||||
"dequal": "^2.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-to-ts": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
|
||||
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"ts-algebra": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||
@@ -6751,6 +6798,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/standardwebhooks": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz",
|
||||
"integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@stablelib/base64": "^1.0.0",
|
||||
"fast-sha256": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
@@ -7139,6 +7196,12 @@
|
||||
"tree-kill": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-algebra": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
|
||||
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.0.5",
|
||||
"version": "2.1.5",
|
||||
"description": "",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
@@ -28,6 +28,7 @@
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.102.0",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
-- AI assistant (Phase 1): usage-tracking table, monthly budget column, ai.use permission.
|
||||
|
||||
CREATE TABLE `ai_usage` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`user_id` INTEGER NULL,
|
||||
`kind` VARCHAR(20) NOT NULL,
|
||||
`model` VARCHAR(50) NOT NULL,
|
||||
`input_tokens` INTEGER NOT NULL DEFAULT 0,
|
||||
`output_tokens` INTEGER NOT NULL DEFAULT 0,
|
||||
`cost_usd` DECIMAL(10, 6) NOT NULL DEFAULT 0,
|
||||
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
PRIMARY KEY (`id`),
|
||||
INDEX `idx_ai_usage_created` (`created_at`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `company_settings`
|
||||
ADD COLUMN `ai_monthly_budget_usd` DECIMAL(10, 2) NULL DEFAULT 50.00;
|
||||
|
||||
-- ai.use permission + grant to admin (INSERT IGNORE → idempotent), mirroring
|
||||
-- the warehouse-permissions migration.
|
||||
INSERT IGNORE INTO `permissions` (`name`, `display_name`, `module`, `description`, `created_at`) VALUES
|
||||
('ai.use', 'AI asistent', 'ai', 'Používat AI asistenta (chat a import faktur)', NOW());
|
||||
|
||||
INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`)
|
||||
SELECT r.id, p.id
|
||||
FROM `roles` r
|
||||
CROSS JOIN `permissions` p
|
||||
WHERE r.name = 'admin'
|
||||
AND p.name = 'ai.use';
|
||||
@@ -0,0 +1,11 @@
|
||||
-- AI assistant (Phase 1): per-user chat history (server-side, permanent).
|
||||
|
||||
CREATE TABLE `ai_chat_messages` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`user_id` INTEGER NOT NULL,
|
||||
`role` VARCHAR(20) NOT NULL,
|
||||
`content` TEXT NOT NULL,
|
||||
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
PRIMARY KEY (`id`),
|
||||
INDEX `idx_ai_chat_user` (`user_id`, `id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
@@ -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`);
|
||||
@@ -76,6 +76,42 @@ model audit_logs {
|
||||
@@fulltext([description], map: "idx_audit_search")
|
||||
}
|
||||
|
||||
model ai_usage {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int?
|
||||
kind String @db.VarChar(20)
|
||||
model String @db.VarChar(50)
|
||||
input_tokens Int @default(0)
|
||||
output_tokens Int @default(0)
|
||||
cost_usd Decimal @default(0) @db.Decimal(10, 6)
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
|
||||
@@index([created_at], map: "idx_ai_usage_created")
|
||||
}
|
||||
|
||||
model ai_conversations {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
title String @db.VarChar(255)
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime @default(now()) @updatedAt @db.Timestamp(0)
|
||||
messages ai_chat_messages[]
|
||||
|
||||
@@index([user_id, id], map: "idx_ai_conv_user")
|
||||
}
|
||||
|
||||
model ai_chat_messages {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
conversation_id Int
|
||||
role String @db.VarChar(20)
|
||||
content String @db.Text
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
conversation ai_conversations @relation(fields: [conversation_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([conversation_id, id], map: "idx_ai_chat_conv")
|
||||
}
|
||||
|
||||
model bank_accounts {
|
||||
id Int @id @default(autoincrement())
|
||||
account_name String? @db.VarChar(255)
|
||||
@@ -134,6 +170,7 @@ model company_settings {
|
||||
warehouse_issue_number_pattern String? @db.VarChar(100)
|
||||
warehouse_inventory_prefix String? @db.VarChar(20)
|
||||
warehouse_inventory_number_pattern String? @db.VarChar(100)
|
||||
ai_monthly_budget_usd Decimal? @default(50.00) @db.Decimal(10, 2)
|
||||
}
|
||||
|
||||
model customers {
|
||||
|
||||
448
src/__tests__/ai.test.ts
Normal file
448
src/__tests__/ai.test.ts
Normal file
@@ -0,0 +1,448 @@
|
||||
import { describe, it, expect, beforeEach, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config as appConfig } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import aiRoutes from "../routes/admin/ai";
|
||||
import {
|
||||
computeCostUsd,
|
||||
recordUsage,
|
||||
getMonthSpendUsd,
|
||||
getBudgetUsd,
|
||||
assertBudgetAvailable,
|
||||
isConfigured,
|
||||
listConversations,
|
||||
createConversation,
|
||||
getConversationMessages,
|
||||
appendConversationMessages,
|
||||
renameConversation,
|
||||
deleteConversation,
|
||||
} from "../services/ai.service";
|
||||
|
||||
const KIND = "test_ai"; // marker so we only clean our own rows
|
||||
const CONV_UID_A = 999999991; // synthetic, FK-free owner ids
|
||||
const CONV_UID_B = 999999992;
|
||||
const HIST_MARKER = "「test-conv」"; // marks HTTP-test conversations on real users
|
||||
|
||||
beforeEach(async () => {
|
||||
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
|
||||
});
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { title: { contains: HIST_MARKER } },
|
||||
});
|
||||
});
|
||||
|
||||
describe("ai.service cost + budget", () => {
|
||||
it("computes Sonnet 4.6 cost from tokens", () => {
|
||||
// 1,000,000 input @ $3 + 1,000,000 output @ $15 = $18
|
||||
expect(
|
||||
computeCostUsd("claude-sonnet-4-6", 1_000_000, 1_000_000),
|
||||
).toBeCloseTo(18, 6);
|
||||
expect(computeCostUsd("claude-sonnet-4-6", 4000, 500)).toBeCloseTo(
|
||||
0.0195,
|
||||
6,
|
||||
);
|
||||
});
|
||||
|
||||
it("records usage with the computed cost", async () => {
|
||||
await recordUsage({
|
||||
userId: null,
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
inputTokens: 4000,
|
||||
outputTokens: 500,
|
||||
});
|
||||
const rows = await prisma.ai_usage.findMany({ where: { kind: KIND } });
|
||||
expect(rows.length).toBe(1);
|
||||
expect(Number(rows[0].cost_usd)).toBeCloseTo(0.0195, 6);
|
||||
});
|
||||
|
||||
it("sums only the current month's spend", async () => {
|
||||
await recordUsage({
|
||||
userId: null,
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
inputTokens: 1_000_000,
|
||||
outputTokens: 0,
|
||||
}); // $3 this month
|
||||
// An old row (last year) must NOT count.
|
||||
await prisma.ai_usage.create({
|
||||
data: {
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
input_tokens: 1_000_000,
|
||||
output_tokens: 0,
|
||||
cost_usd: 3,
|
||||
created_at: new Date("2000-01-01T00:00:00Z"),
|
||||
},
|
||||
});
|
||||
const spend = await getMonthSpendUsd();
|
||||
expect(spend).toBeGreaterThanOrEqual(3);
|
||||
expect(spend).toBeLessThan(6); // the year-2000 $3 is excluded
|
||||
});
|
||||
|
||||
it("assertBudgetAvailable blocks at/over budget, allows under", async () => {
|
||||
const budget = await getBudgetUsd();
|
||||
// Under budget → null (allowed)
|
||||
expect(await assertBudgetAvailable()).toBeNull();
|
||||
// Push spend over budget for this month, then it must block with 402.
|
||||
await prisma.ai_usage.create({
|
||||
data: {
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cost_usd: budget + 1,
|
||||
created_at: new Date(),
|
||||
},
|
||||
});
|
||||
const blocked = await assertBudgetAvailable();
|
||||
expect(blocked).not.toBeNull();
|
||||
expect(blocked?.status).toBe(402);
|
||||
});
|
||||
|
||||
it("isConfigured reflects the API key presence", () => {
|
||||
expect(typeof isConfigured()).toBe("boolean");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ai.service conversations", () => {
|
||||
beforeEach(async () => {
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
|
||||
});
|
||||
});
|
||||
|
||||
// Narrow a service result to its error branch with a clear failure message.
|
||||
const expectError = (
|
||||
r: { error: string; status: number } | { data: unknown },
|
||||
status: number,
|
||||
) => {
|
||||
if (!("error" in r))
|
||||
throw new Error(`expected an error result, got ${JSON.stringify(r)}`);
|
||||
expect(r.status).toBe(status);
|
||||
};
|
||||
|
||||
it("creates, lists, appends (auto-title), and reads oldest→newest", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
expect(conv.title).toBe("Nová konverzace");
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "Kolik je hodin v Praze?" },
|
||||
{ role: "assistant", content: "Nevím, ale…" },
|
||||
]);
|
||||
const list = await listConversations(CONV_UID_A);
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].title).toBe("Kolik je hodin v Praze?"); // auto-titled
|
||||
const msgs = await getConversationMessages(CONV_UID_A, conv.id);
|
||||
if (!("data" in msgs)) throw new Error("expected messages, got an error");
|
||||
expect(msgs.data.map((m) => m.content)).toEqual([
|
||||
"Kolik je hodin v Praze?",
|
||||
"Nevím, ale…",
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not overwrite a renamed title on later appends", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
await renameConversation(CONV_UID_A, conv.id, "Moje téma");
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "tohle by nemělo přepsat název" },
|
||||
]);
|
||||
const list = await listConversations(CONV_UID_A);
|
||||
expect(list[0].title).toBe("Moje téma");
|
||||
});
|
||||
|
||||
it("bumps updated_at on append", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
// Force an old timestamp, then prove append refreshes it (TIMESTAMP(0) is
|
||||
// second-precision, so compare against a year rather than ms deltas).
|
||||
await prisma.ai_conversations.update({
|
||||
where: { id: conv.id },
|
||||
data: { updated_at: new Date("2000-01-01T00:00:00Z") },
|
||||
});
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "ping" },
|
||||
]);
|
||||
const after = (await listConversations(CONV_UID_A))[0].updated_at;
|
||||
expect(after.getFullYear()).toBeGreaterThan(2000);
|
||||
});
|
||||
|
||||
it("isolates conversations per user (404 on every op across owners)", async () => {
|
||||
const a = await createConversation(CONV_UID_A);
|
||||
expect(await listConversations(CONV_UID_B)).toHaveLength(0);
|
||||
expectError(await getConversationMessages(CONV_UID_B, a.id), 404);
|
||||
expectError(
|
||||
await appendConversationMessages(CONV_UID_B, a.id, [
|
||||
{ role: "user", content: "x" },
|
||||
]),
|
||||
404,
|
||||
);
|
||||
expectError(await renameConversation(CONV_UID_B, a.id, "hack"), 404);
|
||||
expectError(await deleteConversation(CONV_UID_B, a.id), 404);
|
||||
});
|
||||
|
||||
it("cascade-deletes messages with the conversation", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "x" },
|
||||
]);
|
||||
await deleteConversation(CONV_UID_A, conv.id);
|
||||
const remaining = await prisma.ai_chat_messages.count({
|
||||
where: { conversation_id: conv.id },
|
||||
});
|
||||
expect(remaining).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTTP /api/admin/ai", () => {
|
||||
let app: Awaited<ReturnType<typeof buildAiApp>>;
|
||||
let adminToken: string;
|
||||
let noPermToken: string;
|
||||
let noPermRoleId: number;
|
||||
let noPermUserId: number;
|
||||
let savedKey: string;
|
||||
|
||||
async function buildAiApp() {
|
||||
const a = Fastify({ logger: false });
|
||||
await a.register(cookie);
|
||||
await a.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
a.addHook("onRequest", securityHeaders);
|
||||
await a.register(aiRoutes, { prefix: "/api/admin/ai" });
|
||||
return a;
|
||||
}
|
||||
function token(user: {
|
||||
id: number;
|
||||
username: string;
|
||||
roleName: string | null;
|
||||
}) {
|
||||
return jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: user.roleName },
|
||||
appConfig.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
savedKey = appConfig.anthropic.apiKey;
|
||||
app = await buildAiApp();
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
include: { roles: true },
|
||||
});
|
||||
if (!admin) throw new Error("admin not found");
|
||||
adminToken = token({
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
roleName: admin.roles?.name ?? null,
|
||||
});
|
||||
const stamp = Date.now();
|
||||
const role = await prisma.roles.create({
|
||||
data: { name: `noperm_ai_${stamp}`, display_name: "No Perm AI" },
|
||||
});
|
||||
noPermRoleId = role.id;
|
||||
const u = await prisma.users.create({
|
||||
data: {
|
||||
username: `noperm_ai_${stamp}`,
|
||||
first_name: "No",
|
||||
last_name: "Perm",
|
||||
email: `noperm_ai_${stamp}@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
role_id: role.id,
|
||||
is_active: true,
|
||||
},
|
||||
});
|
||||
noPermUserId = u.id;
|
||||
noPermToken = token({
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
roleName: role.name,
|
||||
});
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
(appConfig.anthropic as { apiKey: string }).apiKey = savedKey;
|
||||
if (noPermUserId)
|
||||
await prisma.users
|
||||
.deleteMany({ where: { id: noPermUserId } })
|
||||
.catch(() => {});
|
||||
if (noPermRoleId)
|
||||
await prisma.roles
|
||||
.deleteMany({ where: { id: noPermRoleId } })
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
it("GET /usage requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/usage",
|
||||
headers: { Authorization: `Bearer ${noPermToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /usage returns spend + budget for an admin", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/usage",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(typeof body.data.budget_usd).toBe("number");
|
||||
expect(typeof body.data.month_spend_usd).toBe("number");
|
||||
});
|
||||
|
||||
it("POST /chat returns 503 when AI is not configured", async () => {
|
||||
(appConfig.anthropic as { apiKey: string }).apiKey = "";
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/chat",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [{ role: "user", content: "ahoj" }] },
|
||||
});
|
||||
expect(res.statusCode).toBe(503);
|
||||
(appConfig.anthropic as { apiKey: string }).apiKey = savedKey;
|
||||
});
|
||||
|
||||
it("GET /conversations requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: { Authorization: `Bearer ${noPermToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("conversation lifecycle over HTTP (create → append → list → rename → delete)", async () => {
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} t` },
|
||||
});
|
||||
expect(created.statusCode).toBe(200);
|
||||
const id = created.json().data.conversation.id as number;
|
||||
|
||||
const appended = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/admin/ai/conversations/${id}/messages`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [{ role: "user", content: "ahoj" }] },
|
||||
});
|
||||
expect(appended.statusCode).toBe(200);
|
||||
|
||||
const msgs = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/ai/conversations/${id}/messages`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(
|
||||
msgs.json().data.messages.map((m: { content: string }) => m.content),
|
||||
).toContain("ahoj");
|
||||
|
||||
const renamed = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/admin/ai/conversations/${id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} renamed` },
|
||||
});
|
||||
expect(renamed.json().data.conversation.title).toBe(
|
||||
`${HIST_MARKER} renamed`,
|
||||
);
|
||||
|
||||
const del = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/admin/ai/conversations/${id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(del.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("GET messages of a non-existent conversation → 404", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations/999999000/messages",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("POST /conversations requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: {
|
||||
Authorization: `Bearer ${noPermToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: "x" },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /conversations lists the user's conversations", async () => {
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} listed` },
|
||||
});
|
||||
const id = created.json().data.conversation.id as number;
|
||||
const list = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(list.statusCode).toBe(200);
|
||||
expect(
|
||||
list.json().data.conversations.map((c: { id: number }) => c.id),
|
||||
).toContain(id);
|
||||
});
|
||||
|
||||
it("rejects an empty title (PATCH) and empty messages (POST) with 400", async () => {
|
||||
const patch = await app.inject({
|
||||
method: "PATCH",
|
||||
url: "/api/admin/ai/conversations/999999000",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: "" },
|
||||
});
|
||||
expect(patch.statusCode).toBe(400);
|
||||
|
||||
const append = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations/999999000/messages",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [] },
|
||||
});
|
||||
expect(append.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
deleteOverride,
|
||||
listEntries,
|
||||
listOverrides,
|
||||
bulkCreateEntries,
|
||||
} from "../services/plan.service";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -788,6 +789,184 @@ describe("plan.service.listOverrides (employee scoping)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// bulkCreateEntries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("plan.service.bulkCreateEntries", () => {
|
||||
it("creates one continuous range per employee when weekends are included", async () => {
|
||||
// 2096-06-01 is a Friday; 2096-06-03 is a Sunday. include_weekends → one
|
||||
// range 06-01..06-03 covering all 3 days.
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-wknd`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(1);
|
||||
expect(res.data.created_days).toBe(3);
|
||||
expect(res.data.skipped_days).toBe(0);
|
||||
expect(res.data.users).toBe(1);
|
||||
});
|
||||
|
||||
it("splits into per-work-week ranges and skips weekends when excluded", async () => {
|
||||
// 2096-06-01 (Fri) .. 2096-06-05 (Tue): Fri | Sat Sun excluded | Mon Tue.
|
||||
// Two runs: [06-01] and [06-04..06-05] → 2 entries, 3 days, 0 skipped.
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-05",
|
||||
include_weekends: false,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-week`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(3);
|
||||
expect(res.data.skipped_days).toBe(0);
|
||||
});
|
||||
|
||||
it("skips days already at the cap and splits the range around them", async () => {
|
||||
// Pre-fill 2096-07-02 to the cap (3 entries) for the user. A weekends-on
|
||||
// bulk over 07-01..07-03 then creates 07-01 and 07-03 (two ranges), skips
|
||||
// 07-02. 2096-07-01..03 are Sun/Mon/Tue — all included with weekends on.
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2096-07-02"),
|
||||
date_to: new Date("2096-07-02"),
|
||||
category: "work",
|
||||
note: `${N}cap${i}`,
|
||||
created_by: adminUserId,
|
||||
},
|
||||
});
|
||||
}
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-07-01",
|
||||
date_to: "2096-07-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-cap`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(2);
|
||||
expect(res.data.skipped_days).toBe(1);
|
||||
});
|
||||
|
||||
it("aggregates across multiple employees", async () => {
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId, noPermUserId],
|
||||
date_from: "2096-08-03", // Friday
|
||||
date_to: "2096-08-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-multi`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.users).toBe(2);
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects empty user_ids, past dates, bad range, and inactive category", async () => {
|
||||
const empty = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in empty && empty.status).toBe(400);
|
||||
|
||||
const tooLong = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-01-01",
|
||||
date_to: "2096-12-31", // > 92 days
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in tooLong && tooLong.status).toBe(400);
|
||||
|
||||
const past = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2000-01-01",
|
||||
date_to: "2000-01-02",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in past && past.status).toBe(403);
|
||||
|
||||
const badRange = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-10",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in badRange && badRange.status).toBe(400);
|
||||
|
||||
const badCat = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "__nope__",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in badCat && badCat.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HTTP route tests (Fastify inject)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1036,4 +1215,32 @@ describe("HTTP /api/admin/plan", () => {
|
||||
);
|
||||
expect(res.statusCode).toBe(201);
|
||||
});
|
||||
|
||||
it("POST /entries/bulk requires attendance.manage", async () => {
|
||||
const res = await authPost("/api/admin/plan/entries/bulk", noPermToken, {
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2095-06-01",
|
||||
date_to: "2095-06-01",
|
||||
include_weekends: true,
|
||||
category: "work",
|
||||
note: `${N}bulk-forbidden`,
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("POST /entries/bulk creates entries for an admin and returns a summary", async () => {
|
||||
const res = await authPost("/api/admin/plan/entries/bulk", adminToken, {
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2095-06-05", // Sunday; weekends on → 1 day
|
||||
date_to: "2095-06-05",
|
||||
include_weekends: true,
|
||||
category: "work",
|
||||
note: `${N}bulk-http`,
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.created_days).toBe(1);
|
||||
expect(body.data.users).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
26
src/__tests__/received-invoices-vat.test.ts
Normal file
26
src/__tests__/received-invoices-vat.test.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { vatFromGross } from "../routes/admin/received-invoices";
|
||||
|
||||
// `amount` on a received invoice is the GROSS total (VAT included). The VAT is
|
||||
// the portion contained within it: gross * rate / (100 + rate).
|
||||
describe("vatFromGross (VAT contained in a gross total)", () => {
|
||||
it("derives VAT from a real gross total at 21%", () => {
|
||||
// 22 542,91 @ 21% → 3 912,41 (base 18 630,50). User-confirmed figures.
|
||||
expect(vatFromGross(22542.91, 21)).toBeCloseTo(3912.41, 2);
|
||||
expect(22542.91 - vatFromGross(22542.91, 21)).toBeCloseTo(18630.5, 2);
|
||||
});
|
||||
|
||||
it("derives VAT at other rates", () => {
|
||||
expect(vatFromGross(1210, 21)).toBeCloseTo(210, 2); // base 1000
|
||||
expect(vatFromGross(1100, 10)).toBeCloseTo(100, 2); // base 1000
|
||||
expect(vatFromGross(1150, 15)).toBeCloseTo(150, 2); // base 1000
|
||||
});
|
||||
|
||||
it("returns 0 when there is no VAT", () => {
|
||||
expect(vatFromGross(5000, 0)).toBe(0);
|
||||
});
|
||||
|
||||
it("returns 0 for a zero amount", () => {
|
||||
expect(vatFromGross(0, 21)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
|
||||
191
src/admin/components/BulkPlanModal.tsx
Normal file
191
src/admin/components/BulkPlanModal.tsx
Normal file
@@ -0,0 +1,191 @@
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import {
|
||||
Modal,
|
||||
Field,
|
||||
DateField,
|
||||
Select,
|
||||
TextField,
|
||||
CheckboxField,
|
||||
} from "../ui";
|
||||
import type { PlanUser, PlanCategory } from "../lib/queries/plan";
|
||||
import type { Project } from "../lib/queries/projects";
|
||||
|
||||
export interface BulkPlanForm {
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
is_range: boolean;
|
||||
user_ids: string[];
|
||||
include_weekends: boolean;
|
||||
project_id: string;
|
||||
category: string;
|
||||
note: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
form: BulkPlanForm;
|
||||
setForm: (form: BulkPlanForm) => void;
|
||||
users: PlanUser[];
|
||||
projects: Project[];
|
||||
categories: PlanCategory[];
|
||||
onSubmit: () => void;
|
||||
submitting: boolean;
|
||||
toggleUser: (userId: number) => void;
|
||||
toggleAllUsers: () => void;
|
||||
}
|
||||
|
||||
export default function BulkPlanModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
form,
|
||||
setForm,
|
||||
users,
|
||||
projects,
|
||||
categories,
|
||||
onSubmit,
|
||||
submitting,
|
||||
toggleUser,
|
||||
toggleAllUsers,
|
||||
}: Props) {
|
||||
const activeCategories = categories.filter((c) => c.is_active);
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Hromadné přiřazení"
|
||||
maxWidth="lg"
|
||||
loading={submitting}
|
||||
onSubmit={onSubmit}
|
||||
submitText="Vytvořit"
|
||||
submitDisabled={form.user_ids.length === 0}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{ mt: 0.25, mb: 2 }}
|
||||
>
|
||||
Vytvoří záznamy pro vybrané dny u zvolených zaměstnanců. Dny, které už
|
||||
mají 3 záznamy, se přeskočí.
|
||||
</Typography>
|
||||
|
||||
<Field label="Datum od">
|
||||
<DateField
|
||||
value={form.date_from}
|
||||
onChange={(val) => setForm({ ...form, date_from: val })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Rozsah dnů">
|
||||
<CheckboxField
|
||||
label="Více dní"
|
||||
checked={form.is_range}
|
||||
onChange={(checked) => setForm({ ...form, is_range: checked })}
|
||||
/>
|
||||
</Field>
|
||||
{form.is_range && (
|
||||
<Field label="Datum do">
|
||||
<DateField
|
||||
value={form.date_to}
|
||||
onChange={(val) => setForm({ ...form, date_to: val })}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Víkendy">
|
||||
<CheckboxField
|
||||
label="Zahrnout víkendy"
|
||||
checked={form.include_weekends}
|
||||
onChange={(checked) =>
|
||||
setForm({ ...form, include_weekends: checked })
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, mb: 0.5 }}>
|
||||
<Typography
|
||||
component="span"
|
||||
variant="body2"
|
||||
sx={{ fontWeight: 600, color: "text.secondary" }}
|
||||
>
|
||||
Zaměstnanci
|
||||
</Typography>
|
||||
<Typography
|
||||
component="button"
|
||||
type="button"
|
||||
onClick={toggleAllUsers}
|
||||
variant="caption"
|
||||
sx={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
p: 0,
|
||||
cursor: "pointer",
|
||||
fontWeight: 500,
|
||||
color: "primary.main",
|
||||
}}
|
||||
>
|
||||
{users.length > 0 && form.user_ids.length === users.length
|
||||
? "Odznačit vše"
|
||||
: "Vybrat vše"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 0.25,
|
||||
maxHeight: 200,
|
||||
overflowY: "auto",
|
||||
p: 1.5,
|
||||
bgcolor: "action.hover",
|
||||
borderRadius: 2,
|
||||
border: 1,
|
||||
borderColor: "divider",
|
||||
}}
|
||||
>
|
||||
{users.map((u) => (
|
||||
<CheckboxField
|
||||
key={u.id}
|
||||
label={u.full_name}
|
||||
checked={form.user_ids.includes(String(u.id))}
|
||||
onChange={() => toggleUser(u.id)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
Vybráno: {form.user_ids.length} z {users.length}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Field label="Projekt">
|
||||
<Select
|
||||
value={form.project_id}
|
||||
onChange={(val) => setForm({ ...form, project_id: val })}
|
||||
options={[
|
||||
{ value: "", label: "— bez projektu —" },
|
||||
...projects.map((p) => ({ value: String(p.id), label: p.name })),
|
||||
]}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Kategorie">
|
||||
<Select
|
||||
value={form.category}
|
||||
onChange={(val) => setForm({ ...form, category: val })}
|
||||
options={activeCategories.map((c) => ({
|
||||
value: c.key,
|
||||
label: c.label,
|
||||
}))}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Text poznámky (volitelný)">
|
||||
<TextField
|
||||
multiline
|
||||
minRows={2}
|
||||
value={form.note}
|
||||
onChange={(e) => setForm({ ...form, note: e.target.value })}
|
||||
inputProps={{ maxLength: 500 }}
|
||||
/>
|
||||
</Field>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -620,7 +620,6 @@ export default function PlanGrid({
|
||||
c.category,
|
||||
catMap,
|
||||
)}
|
||||
showNote={cellArr.length === 1}
|
||||
/>
|
||||
</Box>
|
||||
))}
|
||||
|
||||
@@ -6,7 +6,6 @@ interface Props {
|
||||
project: Project | null;
|
||||
readonly?: boolean;
|
||||
categoryLabel: string;
|
||||
showNote?: boolean;
|
||||
}
|
||||
|
||||
export default function PlanRangeChips({
|
||||
@@ -14,7 +13,6 @@ export default function PlanRangeChips({
|
||||
project,
|
||||
readonly,
|
||||
categoryLabel,
|
||||
showNote = true,
|
||||
}: Props) {
|
||||
void readonly;
|
||||
if (!cell) return null;
|
||||
@@ -38,9 +36,7 @@ export default function PlanRangeChips({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{showNote && cell.note && (
|
||||
<div className="plan-cell-note">{cell.note}</div>
|
||||
)}
|
||||
{cell.note && <div className="plan-cell-note">{cell.note}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,35 @@ import useDialogScrollLock from "../../ui/useDialogScrollLock";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
// Copy helper. navigator.clipboard is SECURE-CONTEXT ONLY (undefined over plain
|
||||
// HTTP on a LAN), so we fall back to the legacy execCommand path — which works
|
||||
// in insecure contexts — and report whether the copy actually succeeded. The
|
||||
// caller MUST gate its success toast on the returned boolean (otherwise it lies
|
||||
// to the user about copying 2FA codes / the TOTP secret).
|
||||
async function copyToClipboard(text: string): Promise<boolean> {
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// fall through to the legacy path
|
||||
}
|
||||
try {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
ta.style.position = "fixed";
|
||||
ta.style.opacity = "0";
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
const ok = document.execCommand("copy");
|
||||
document.body.removeChild(ta);
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface DashProfileProps {
|
||||
totpEnabled: boolean;
|
||||
totpLoading: boolean;
|
||||
@@ -480,9 +509,10 @@ export default function DashProfile({
|
||||
</Box>
|
||||
<Box sx={{ mt: 1.5 }}>
|
||||
<Button
|
||||
onClick={() => {
|
||||
navigator.clipboard?.writeText(backupCodes.join("\n"));
|
||||
alert.success("Kódy zkopírovány");
|
||||
onClick={async () => {
|
||||
const ok = await copyToClipboard(backupCodes.join("\n"));
|
||||
if (ok) alert.success("Kódy zkopírovány");
|
||||
else alert.error("Kopírování selhalo – zkopírujte ručně");
|
||||
}}
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
@@ -543,9 +573,11 @@ export default function DashProfile({
|
||||
>
|
||||
<span>{totpSecret}</span>
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
navigator.clipboard?.writeText(totpSecret);
|
||||
alert.success("Klíč zkopírován");
|
||||
onClick={async () => {
|
||||
const ok = await copyToClipboard(totpSecret);
|
||||
if (ok) alert.success("Klíč zkopírován");
|
||||
else
|
||||
alert.error("Kopírování selhalo – zkopírujte ručně");
|
||||
}}
|
||||
size="small"
|
||||
title="Kopírovat"
|
||||
|
||||
121
src/admin/components/odin/InvoiceReviewCard.tsx
Normal file
121
src/admin/components/odin/InvoiceReviewCard.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
548
src/admin/components/odin/OdinChat.tsx
Normal file
548
src/admin/components/odin/OdinChat.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
147
src/admin/components/odin/OdinComposer.tsx
Normal file
147
src/admin/components/odin/OdinComposer.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
119
src/admin/components/odin/OdinMark.tsx
Normal file
119
src/admin/components/odin/OdinMark.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
221
src/admin/components/odin/OdinSidebar.tsx
Normal file
221
src/admin/components/odin/OdinSidebar.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
238
src/admin/components/odin/OdinThread.tsx
Normal file
238
src/admin/components/odin/OdinThread.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
33
src/admin/components/odin/types.ts
Normal file
33
src/admin/components/odin/types.ts
Normal 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;
|
||||
}
|
||||
@@ -488,6 +488,20 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
},
|
||||
});
|
||||
|
||||
const bulkCreate = useMutation({
|
||||
mutationFn: (body: any) =>
|
||||
apiCall("/api/admin/plan/entries/bulk", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
onSuccess: () => {
|
||||
// No optimistic patch — bulk can touch many cells; just invalidate and
|
||||
// let the grid refetch the authoritative state.
|
||||
invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
// Roll back an optimistic patch on mutation error. Called from
|
||||
// PlanWork's mutation wrappers via `rollbackMutation(mutation, key)`.
|
||||
// `mutation` is a TanStack mutation result with a `_rolled` snapshot stashed
|
||||
@@ -534,6 +548,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
createOverride,
|
||||
updateOverride,
|
||||
deleteOverride,
|
||||
bulkCreate,
|
||||
invalidate,
|
||||
// Exposed so PlanWork can roll back an optimistic patch when a
|
||||
// mutation throws. Pass the failed mutation and the userId it
|
||||
|
||||
61
src/admin/lib/queries/ai.ts
Normal file
61
src/admin/lib/queries/ai.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
import { jsonQuery } from "../apiAdapter";
|
||||
|
||||
export interface AiUsage {
|
||||
configured: boolean;
|
||||
month_spend_usd: number;
|
||||
budget_usd: number;
|
||||
remaining_usd: number;
|
||||
}
|
||||
|
||||
export interface ExtractedInvoice {
|
||||
supplier_name: string;
|
||||
invoice_number: string | null;
|
||||
amount: number;
|
||||
currency: string;
|
||||
vat_rate: number;
|
||||
issue_date: string | null;
|
||||
due_date: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
export interface StoredChatMessage {
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export const aiUsageOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["ai", "usage"],
|
||||
queryFn: () => jsonQuery<AiUsage>("/api/admin/ai/usage"),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
export interface Conversation {
|
||||
id: number;
|
||||
title: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export const aiConversationsOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["ai", "conversations"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ conversations: Conversation[] }>(
|
||||
"/api/admin/ai/conversations",
|
||||
),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
export const aiConversationMessagesOptions = (id: number) =>
|
||||
queryOptions({
|
||||
queryKey: ["ai", "conversation", id, "messages"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ messages: StoredChatMessage[] }>(
|
||||
`/api/admin/ai/conversations/${id}/messages`,
|
||||
),
|
||||
// Re-read the DB on each mount/selection (no stale-cache resurrection).
|
||||
staleTime: Infinity,
|
||||
gcTime: 0,
|
||||
});
|
||||
24
src/admin/pages/Odin.tsx
Normal file
24
src/admin/pages/Odin.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import type { PlanCellModalMode } from "../components/PlanCellModal";
|
||||
import PlanGrid from "../components/PlanGrid";
|
||||
import PlanCellModal from "../components/PlanCellModal";
|
||||
import PlanCategoriesModal from "../components/PlanCategoriesModal";
|
||||
import BulkPlanModal, { type BulkPlanForm } from "../components/BulkPlanModal";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { Button, Alert, LoadingState, PageEnter } from "../ui";
|
||||
import { projectListOptions, type Project } from "../lib/queries/projects";
|
||||
@@ -128,6 +129,7 @@ export default function PlanWork() {
|
||||
createOverride,
|
||||
updateOverride,
|
||||
deleteOverride,
|
||||
bulkCreate,
|
||||
rollbackMutation,
|
||||
} = usePlanWork({ canEdit });
|
||||
|
||||
@@ -140,6 +142,84 @@ export default function PlanWork() {
|
||||
|
||||
const [catModalOpen, setCatModalOpen] = useState(false);
|
||||
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
const [bulkSubmitting, setBulkSubmitting] = useState(false);
|
||||
const [bulkForm, setBulkForm] = useState<BulkPlanForm>(() => {
|
||||
const today = todayIsoLocal();
|
||||
return {
|
||||
date_from: today,
|
||||
date_to: today,
|
||||
is_range: false,
|
||||
user_ids: [],
|
||||
include_weekends: false,
|
||||
project_id: "",
|
||||
category: "work",
|
||||
note: "",
|
||||
};
|
||||
});
|
||||
|
||||
const planUsers = useMemo(() => grid?.users ?? [], [grid]);
|
||||
|
||||
const toggleBulkUser = useCallback((userId: number) => {
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
user_ids: prev.user_ids.includes(String(userId))
|
||||
? prev.user_ids.filter((u) => u !== String(userId))
|
||||
: [...prev.user_ids, String(userId)],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const toggleAllBulkUsers = useCallback(() => {
|
||||
const allIds = (grid?.users ?? []).map((u) => String(u.id));
|
||||
if (allIds.length === 0) return; // grid not yet loaded — no-op
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
user_ids: prev.user_ids.length === allIds.length ? [] : allIds,
|
||||
}));
|
||||
}, [grid]);
|
||||
|
||||
const submitBulk = useCallback(async () => {
|
||||
if (bulkForm.user_ids.length === 0) return;
|
||||
setBulkSubmitting(true);
|
||||
try {
|
||||
const data: any = await bulkCreate.mutateAsync({
|
||||
user_ids: bulkForm.user_ids.map(Number),
|
||||
date_from: bulkForm.date_from,
|
||||
date_to: bulkForm.is_range ? bulkForm.date_to : bulkForm.date_from,
|
||||
include_weekends: bulkForm.include_weekends,
|
||||
project_id: bulkForm.project_id ? Number(bulkForm.project_id) : null,
|
||||
category: bulkForm.category,
|
||||
note: bulkForm.note,
|
||||
});
|
||||
// apiCall returns the full envelope { success, data, message };
|
||||
// the summary counts are under .data
|
||||
const summary = data?.data ?? data;
|
||||
const skipped =
|
||||
summary?.skipped_days > 0
|
||||
? ` ${summary.skipped_days} dní přeskočeno (limit 3 na den).`
|
||||
: "";
|
||||
alert.success(
|
||||
`Vytvořeno ${summary?.created_days ?? 0} záznamů pro ${summary?.users ?? 0} zaměstnanců.${skipped}`,
|
||||
);
|
||||
setBulkOpen(false);
|
||||
// Reset the volatile parts so reopening starts clean (project /
|
||||
// category / weekends stay sticky — users often repeat those).
|
||||
const today = todayIsoLocal();
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
date_from: today,
|
||||
date_to: today,
|
||||
is_range: false,
|
||||
user_ids: [],
|
||||
note: "",
|
||||
}));
|
||||
} catch (e) {
|
||||
alert.error(e instanceof Error ? e.message : "Chyba při ukládání");
|
||||
} finally {
|
||||
setBulkSubmitting(false);
|
||||
}
|
||||
}, [bulkForm, bulkCreate, alert]);
|
||||
|
||||
// `lastMutated` is the (userId, date) of the most recent successful
|
||||
// mutation. We pass it to PlanGrid as `pulseKey`; the matching cell
|
||||
// gets a one-shot CSS pulse animation. We clear it after 700ms (the
|
||||
@@ -673,6 +753,15 @@ export default function PlanWork() {
|
||||
Správa kategorií
|
||||
</Button>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
onClick={() => setBulkOpen(true)}
|
||||
>
|
||||
Hromadné přiřazení
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{gridLoading && <LoadingState />}
|
||||
@@ -727,6 +816,19 @@ export default function PlanWork() {
|
||||
onClose={() => setCatModalOpen(false)}
|
||||
categories={categories}
|
||||
/>
|
||||
<BulkPlanModal
|
||||
isOpen={bulkOpen}
|
||||
onClose={() => setBulkOpen(false)}
|
||||
form={bulkForm}
|
||||
setForm={setBulkForm}
|
||||
users={planUsers}
|
||||
projects={projects}
|
||||
categories={categories}
|
||||
onSubmit={submitBulk}
|
||||
submitting={bulkSubmitting}
|
||||
toggleUser={toggleBulkUser}
|
||||
toggleAllUsers={toggleAllBulkUsers}
|
||||
/>
|
||||
</PageEnter>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -932,7 +932,7 @@ export default function ReceivedInvoices({
|
||||
<Box sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Field
|
||||
label="Částka"
|
||||
label="Částka s DPH"
|
||||
required
|
||||
error={uploadErrors[idx]?.amount}
|
||||
>
|
||||
@@ -1096,7 +1096,7 @@ export default function ReceivedInvoices({
|
||||
sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}
|
||||
>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Field label="Částka" required>
|
||||
<Field label="Částka s DPH" required>
|
||||
<TextField
|
||||
type="number"
|
||||
slotProps={{
|
||||
|
||||
@@ -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} />,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -16,6 +16,7 @@ export const STATUS_LABELS: Record<string, string> = {
|
||||
away: "Přestávka",
|
||||
out: "Nepřihlášen",
|
||||
leave: "Nepřítomen",
|
||||
absent: "Nepřítomen",
|
||||
};
|
||||
|
||||
// Re-exported from the single source of truth so the dashboard activity feed
|
||||
|
||||
@@ -61,6 +61,10 @@ export const config = {
|
||||
),
|
||||
},
|
||||
|
||||
anthropic: {
|
||||
apiKey: process.env.ANTHROPIC_API_KEY || "",
|
||||
},
|
||||
|
||||
nas: {
|
||||
path: process.env.NAS_PATH || "Z:/02_PROJEKTY",
|
||||
financialsPath: process.env.NAS_FINANCIALS_PATH || "",
|
||||
|
||||
230
src/routes/admin/ai.ts
Normal file
230
src/routes/admin/ai.ts
Normal file
@@ -0,0 +1,230 @@
|
||||
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
|
||||
import multipart from "@fastify/multipart";
|
||||
import { requirePermission } from "../../middleware/auth";
|
||||
import { success, error, parseId } from "../../utils/response";
|
||||
import { parseBody } from "../../schemas/common";
|
||||
import {
|
||||
AiChatSchema,
|
||||
AiBudgetSchema,
|
||||
AiHistoryAppendSchema,
|
||||
AiCreateConversationSchema,
|
||||
AiRenameConversationSchema,
|
||||
} from "../../schemas/ai.schema";
|
||||
import { logAudit } from "../../services/audit";
|
||||
import { config } from "../../config/env";
|
||||
import {
|
||||
isConfigured,
|
||||
assertBudgetAvailable,
|
||||
getMonthSpendUsd,
|
||||
getBudgetUsd,
|
||||
setBudgetUsd,
|
||||
chat,
|
||||
extractInvoice,
|
||||
listConversations,
|
||||
createConversation,
|
||||
getConversationMessages,
|
||||
appendConversationMessages,
|
||||
renameConversation,
|
||||
deleteConversation,
|
||||
type ExtractedInvoice,
|
||||
} from "../../services/ai.service";
|
||||
|
||||
export default async function aiRoutes(app: FastifyInstance): Promise<void> {
|
||||
await app.register(multipart, {
|
||||
// Cap files per request: the budget re-check already bounds *spend* mid-batch,
|
||||
// but this bounds the work (one vision call per file) of a single request.
|
||||
limits: { fileSize: config.nas.maxUploadSize, files: 20 },
|
||||
});
|
||||
|
||||
// GET /api/admin/ai/usage — current-month spend + budget
|
||||
app.get(
|
||||
"/usage",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (_request: FastifyRequest, reply: FastifyReply) => {
|
||||
const [month_spend_usd, budget_usd] = await Promise.all([
|
||||
getMonthSpendUsd(),
|
||||
getBudgetUsd(),
|
||||
]);
|
||||
return success(reply, {
|
||||
configured: isConfigured(),
|
||||
month_spend_usd: Math.round(month_spend_usd * 1_000_000) / 1_000_000,
|
||||
budget_usd,
|
||||
remaining_usd: Math.max(0, budget_usd - month_spend_usd),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// PUT /api/admin/ai/budget — set the monthly budget (admins have ai.use)
|
||||
app.put(
|
||||
"/budget",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(AiBudgetSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const { budget_usd } = body.data;
|
||||
await setBudgetUsd(budget_usd);
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "update",
|
||||
entityType: "company_settings",
|
||||
description: `Změněn měsíční rozpočet AI na $${budget_usd}`,
|
||||
newValues: { ai_monthly_budget_usd: budget_usd },
|
||||
});
|
||||
return success(reply, { budget_usd }, 200, "Rozpočet uložen");
|
||||
},
|
||||
);
|
||||
|
||||
// POST /api/admin/ai/chat
|
||||
app.post(
|
||||
"/chat",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
if (!isConfigured()) return error(reply, "AI není nakonfigurováno", 503);
|
||||
const body = parseBody(AiChatSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const budgetErr = await assertBudgetAvailable();
|
||||
if (budgetErr) return error(reply, budgetErr.error, budgetErr.status);
|
||||
const { reply: text } = await chat(
|
||||
body.data.messages,
|
||||
request.authData!.userId,
|
||||
);
|
||||
const [budgetAfter, spendAfter] = await Promise.all([
|
||||
getBudgetUsd(),
|
||||
getMonthSpendUsd(),
|
||||
]);
|
||||
const remaining_usd = Math.max(0, budgetAfter - spendAfter);
|
||||
return success(reply, { reply: text, remaining_usd });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /api/admin/ai/extract-invoices — multipart PDF files
|
||||
app.post(
|
||||
"/extract-invoices",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
if (!isConfigured()) return error(reply, "AI není nakonfigurováno", 503);
|
||||
const budgetErr = await assertBudgetAvailable();
|
||||
if (budgetErr) return error(reply, budgetErr.error, budgetErr.status);
|
||||
|
||||
const parts = request.parts();
|
||||
const results: Array<{
|
||||
file_name: string;
|
||||
fields?: ExtractedInvoice;
|
||||
error?: string;
|
||||
}> = [];
|
||||
for await (const part of parts) {
|
||||
if (part.type !== "file") continue;
|
||||
const buf = await part.toBuffer();
|
||||
try {
|
||||
const fields = await extractInvoice(buf, request.authData!.userId);
|
||||
results.push({ file_name: part.filename || "faktura.pdf", fields });
|
||||
} catch (e) {
|
||||
request.log.error(e, "extractInvoice failed");
|
||||
results.push({
|
||||
file_name: part.filename || "faktura.pdf",
|
||||
error: "Nepodařilo se přečíst fakturu",
|
||||
});
|
||||
}
|
||||
// Re-check the budget between files so one batch can't blow far past it.
|
||||
const over = await assertBudgetAvailable();
|
||||
if (over) break;
|
||||
}
|
||||
if (results.length === 0)
|
||||
return error(reply, "Nebyl nahrán žádný soubor", 400);
|
||||
return success(reply, { invoices: results });
|
||||
},
|
||||
);
|
||||
|
||||
// GET /conversations — this user's conversations (stable order)
|
||||
app.get(
|
||||
"/conversations",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const conversations = await listConversations(request.authData!.userId);
|
||||
return success(reply, { conversations });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /conversations — create
|
||||
app.post(
|
||||
"/conversations",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(AiCreateConversationSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const conversation = await createConversation(
|
||||
request.authData!.userId,
|
||||
body.data.title,
|
||||
);
|
||||
return success(reply, { conversation });
|
||||
},
|
||||
);
|
||||
|
||||
// GET /conversations/:id/messages
|
||||
app.get(
|
||||
"/conversations/:id/messages",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const result = await getConversationMessages(
|
||||
request.authData!.userId,
|
||||
id,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, { messages: result.data });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /conversations/:id/messages — append turns
|
||||
app.post(
|
||||
"/conversations/:id/messages",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const body = parseBody(AiHistoryAppendSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const result = await appendConversationMessages(
|
||||
request.authData!.userId,
|
||||
id,
|
||||
body.data.messages,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, result.data);
|
||||
},
|
||||
);
|
||||
|
||||
// PATCH /conversations/:id — rename
|
||||
app.patch(
|
||||
"/conversations/:id",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const body = parseBody(AiRenameConversationSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const result = await renameConversation(
|
||||
request.authData!.userId,
|
||||
id,
|
||||
body.data.title,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, { conversation: result.data });
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /conversations/:id
|
||||
app.delete(
|
||||
"/conversations/:id",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const result = await deleteConversation(request.authData!.userId, id);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, result.data);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -69,7 +69,7 @@ export default async function dashboardRoutes(
|
||||
|
||||
// Attendance admin — only for attendance.manage
|
||||
if (has("attendance.manage")) {
|
||||
const [todayAttendance, onLeaveToday, usersCount] = await Promise.all([
|
||||
const [todayAttendance, onLeaveToday, activeUsers] = await Promise.all([
|
||||
prisma.attendance.findMany({
|
||||
where: {
|
||||
shift_date: { gte: todayStart, lt: todayEnd },
|
||||
@@ -89,8 +89,13 @@ export default async function dashboardRoutes(
|
||||
users: { select: { id: true, first_name: true, last_name: true } },
|
||||
},
|
||||
}),
|
||||
prisma.users.count({ where: { is_active: true } }),
|
||||
prisma.users.findMany({
|
||||
where: { is_active: true },
|
||||
select: { id: true, first_name: true, last_name: true },
|
||||
orderBy: [{ last_name: "asc" }, { first_name: "asc" }],
|
||||
}),
|
||||
]);
|
||||
const usersCount = activeUsers.length;
|
||||
|
||||
const userAttendanceMap = new Map<number, (typeof todayAttendance)[0]>();
|
||||
for (const a of todayAttendance) {
|
||||
@@ -153,6 +158,25 @@ export default async function dashboardRoutes(
|
||||
});
|
||||
}
|
||||
|
||||
// Show every active employee — those with no attendance record today
|
||||
// appear as "absent" so the card reflects the whole team, not just those
|
||||
// who clocked in or are on leave.
|
||||
const recordedUserIds = new Set<number>([
|
||||
...userAttendanceMap.keys(),
|
||||
...leaveUserIds,
|
||||
]);
|
||||
for (const user of activeUsers) {
|
||||
if (recordedUserIds.has(user.id)) continue;
|
||||
attendanceUsers.push({
|
||||
user_id: user.id,
|
||||
name: `${user.first_name} ${user.last_name}`,
|
||||
initials:
|
||||
`${user.first_name?.charAt(0) ?? ""}${user.last_name?.charAt(0) ?? ""}`.toUpperCase(),
|
||||
status: "absent",
|
||||
arrived_at: null,
|
||||
});
|
||||
}
|
||||
|
||||
result.attendance = {
|
||||
present_today: presentCount,
|
||||
total_active: usersCount,
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
UpdatePlanOverrideSchema,
|
||||
PlanRangeQuerySchema,
|
||||
PlanGridQuerySchema,
|
||||
BulkPlanEntrySchema,
|
||||
} from "../../schemas/plan.schema";
|
||||
import {
|
||||
resolveGrid,
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
deleteOverride,
|
||||
listEntries,
|
||||
listOverrides,
|
||||
bulkCreateEntries,
|
||||
} from "../../services/plan.service";
|
||||
import {
|
||||
CreatePlanCategorySchema,
|
||||
@@ -259,6 +261,29 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
},
|
||||
);
|
||||
|
||||
// --- POST /plan/entries/bulk ---
|
||||
app.post(
|
||||
"/entries/bulk",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(BulkPlanEntrySchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const result = await bulkCreateEntries(
|
||||
body.data!,
|
||||
request.authData!.userId,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "work_plan_entry",
|
||||
description: `Hromadné přiřazení: ${body.data!.category} — ${result.data.users} zaměstnanců, ${body.data!.date_from}–${body.data!.date_to} (${result.data.created_days} dní)`,
|
||||
});
|
||||
return success(reply, result.data, 201, "Hromadné přiřazení dokončeno");
|
||||
},
|
||||
);
|
||||
|
||||
// --- PATCH /plan/entries/:id ---
|
||||
app.patch(
|
||||
"/entries/:id",
|
||||
|
||||
@@ -22,6 +22,15 @@ const VALID_STATUSES = ["unpaid", "paid"] as const;
|
||||
function roundMoney(n: number): number {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* VAT contained WITHIN a gross (VAT-inclusive) amount. `amount` is the total to
|
||||
* pay including tax, so the tax portion is gross * rate / (100 + rate) — e.g.
|
||||
* 22542.91 @ 21% → 3912.41 (base 18630.50). Returns 0 when there is no VAT.
|
||||
*/
|
||||
export function vatFromGross(gross: number, rate: number): number {
|
||||
return rate > 0 ? roundMoney((gross * rate) / (100 + rate)) : 0;
|
||||
}
|
||||
const ALLOWED_SORT_FIELDS = [
|
||||
"id",
|
||||
"supplier_name",
|
||||
@@ -284,11 +293,8 @@ export default async function receivedInvoicesRoutes(
|
||||
const meta = invoicesMeta[i] || {};
|
||||
const amount = Number(meta.amount ?? 0);
|
||||
const vatRate = Number(meta.vat_rate ?? 21);
|
||||
// Amount is net — VAT = amount * rate / 100
|
||||
const vatAmount =
|
||||
vatRate > 0
|
||||
? Math.round(((amount * vatRate) / 100) * 100) / 100
|
||||
: 0;
|
||||
// `amount` is the GROSS total (VAT included); VAT is the portion within it.
|
||||
const vatAmount = vatFromGross(amount, vatRate);
|
||||
|
||||
const issueDate = meta.issue_date
|
||||
? new Date(String(meta.issue_date))
|
||||
@@ -448,7 +454,7 @@ export default async function receivedInvoicesRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
// Recalculate vat_amount when amount or vat_rate changes (matching PHP)
|
||||
// Recalculate vat_amount when amount (gross) or vat_rate changes.
|
||||
const finalAmount =
|
||||
body.amount !== undefined
|
||||
? Number(body.amount)
|
||||
@@ -457,9 +463,8 @@ export default async function receivedInvoicesRoutes(
|
||||
body.vat_rate !== undefined
|
||||
? Number(body.vat_rate)
|
||||
: Number(existing.vat_rate);
|
||||
// Amount is net — VAT = amount * rate / 100
|
||||
const computedVat =
|
||||
finalVatRate > 0 ? roundMoney((finalAmount * finalVatRate) / 100) : 0;
|
||||
// `amount` is the GROSS total (VAT included); VAT is the portion within it.
|
||||
const computedVat = vatFromGross(finalAmount, finalVatRate);
|
||||
|
||||
// Auto-set paid_date when status transitions to paid (matching PHP)
|
||||
const newStatus =
|
||||
|
||||
40
src/schemas/ai.schema.ts
Normal file
40
src/schemas/ai.schema.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const AiChatSchema = z.object({
|
||||
messages: z
|
||||
.array(
|
||||
z.object({
|
||||
role: z.enum(["user", "assistant"]),
|
||||
content: z.string().min(1).max(8000),
|
||||
}),
|
||||
)
|
||||
.min(1, "Zpráva je povinná")
|
||||
.max(100, "Příliš mnoho zpráv"),
|
||||
});
|
||||
|
||||
export const AiHistoryAppendSchema = z.object({
|
||||
messages: z
|
||||
.array(
|
||||
z.object({
|
||||
role: z.enum(["user", "assistant"]),
|
||||
content: z.string().min(1).max(8000),
|
||||
}),
|
||||
)
|
||||
.min(1, "Žádné zprávy")
|
||||
.max(20, "Příliš mnoho zpráv"),
|
||||
});
|
||||
|
||||
export const AiCreateConversationSchema = z.object({
|
||||
title: z.string().max(255).optional(),
|
||||
});
|
||||
|
||||
export const AiRenameConversationSchema = z.object({
|
||||
title: z.string().min(1, "Název je povinný").max(255),
|
||||
});
|
||||
|
||||
export const AiBudgetSchema = z.object({
|
||||
budget_usd: z
|
||||
.union([z.number(), z.string()])
|
||||
.transform((v) => Number(v))
|
||||
.refine((n) => Number.isFinite(n) && n >= 0, "Neplatný rozpočet"),
|
||||
});
|
||||
@@ -83,3 +83,27 @@ export const PlanGridQuerySchema = z.object({
|
||||
date_to: isoDate,
|
||||
view: z.enum(["week", "month"]).default("week"),
|
||||
});
|
||||
|
||||
export const BulkPlanEntrySchema = z
|
||||
.object({
|
||||
user_ids: z
|
||||
.array(intFromForm)
|
||||
.min(1, "Vyberte alespoň jednoho zaměstnance")
|
||||
.transform((ids) => [...new Set(ids)]),
|
||||
date_from: isoDate,
|
||||
date_to: isoDate,
|
||||
include_weekends: z
|
||||
.union([z.boolean(), z.string()])
|
||||
.transform((v) => v === true || v === "true" || v === "1")
|
||||
.default(false),
|
||||
project_id: z
|
||||
.union([z.number(), z.string(), z.null()])
|
||||
.transform((v) => (v === null ? null : Number(v)))
|
||||
.nullish(),
|
||||
category: planCategoryEnum.default("work"),
|
||||
note: z.string().max(500, "Maximálně 500 znaků").default(""),
|
||||
})
|
||||
.refine((v) => v.date_to >= v.date_from, {
|
||||
message: "Datum do musí být stejné nebo po datumu od",
|
||||
path: ["date_to"],
|
||||
});
|
||||
|
||||
@@ -35,6 +35,7 @@ import ordersPdfRoutes from "./routes/admin/orders-pdf";
|
||||
import projectFilesRoutes from "./routes/admin/project-files";
|
||||
import warehouseRoutes from "./routes/admin/warehouse";
|
||||
import planRoutes from "./routes/admin/plan";
|
||||
import aiRoutes from "./routes/admin/ai";
|
||||
|
||||
const app = Fastify({
|
||||
logger: {
|
||||
@@ -152,6 +153,7 @@ async function start() {
|
||||
});
|
||||
await app.register(warehouseRoutes, { prefix: "/api/admin/warehouse" });
|
||||
await app.register(planRoutes, { prefix: "/api/admin/plan" });
|
||||
await app.register(aiRoutes, { prefix: "/api/admin/ai" });
|
||||
|
||||
// --- Frontend: Vite dev middleware (dev only) ---
|
||||
if (!config.isProduction) {
|
||||
|
||||
352
src/services/ai.service.ts
Normal file
352
src/services/ai.service.ts
Normal file
@@ -0,0 +1,352 @@
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
|
||||
/** The single model this assistant uses (Phase 1). */
|
||||
export const AI_MODEL = "claude-sonnet-4-6";
|
||||
|
||||
/** Per-token USD pricing. Sonnet 4.6 = $3 / $15 per 1M (input / output). */
|
||||
const PRICING: Record<string, { input: number; output: number }> = {
|
||||
"claude-sonnet-4-6": { input: 3 / 1_000_000, output: 15 / 1_000_000 },
|
||||
};
|
||||
|
||||
const DEFAULT_BUDGET_USD = 50;
|
||||
|
||||
export function isConfigured(): boolean {
|
||||
return !!config.anthropic.apiKey;
|
||||
}
|
||||
|
||||
/** Lazily build the SDK client; throws a typed result upstream if unconfigured. */
|
||||
function client(): Anthropic {
|
||||
return new Anthropic({ apiKey: config.anthropic.apiKey });
|
||||
}
|
||||
|
||||
export function computeCostUsd(
|
||||
model: string,
|
||||
inputTokens: number,
|
||||
outputTokens: number,
|
||||
): number {
|
||||
const p = PRICING[model] ?? PRICING[AI_MODEL];
|
||||
return inputTokens * p.input + outputTokens * p.output;
|
||||
}
|
||||
|
||||
export async function recordUsage(args: {
|
||||
userId: number | null;
|
||||
kind: string;
|
||||
model: string;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
}): Promise<void> {
|
||||
await prisma.ai_usage.create({
|
||||
data: {
|
||||
user_id: args.userId,
|
||||
kind: args.kind,
|
||||
model: args.model,
|
||||
input_tokens: args.inputTokens,
|
||||
output_tokens: args.outputTokens,
|
||||
cost_usd: computeCostUsd(args.model, args.inputTokens, args.outputTokens),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Budget window edge uses the UTC month boundary (ai_usage.created_at is a UTC
|
||||
// @db.Timestamp). At month turnover this is offset from Prague local time by the
|
||||
// UTC offset for ~1-2h — acceptable for a soft monthly budget, and stable.
|
||||
function startOfMonthUtc(): Date {
|
||||
const d = new Date();
|
||||
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
|
||||
}
|
||||
|
||||
export async function getMonthSpendUsd(): Promise<number> {
|
||||
const agg = await prisma.ai_usage.aggregate({
|
||||
_sum: { cost_usd: true },
|
||||
where: { created_at: { gte: startOfMonthUtc() } },
|
||||
});
|
||||
return Number(agg._sum.cost_usd ?? 0);
|
||||
}
|
||||
|
||||
export async function getBudgetUsd(): Promise<number> {
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { ai_monthly_budget_usd: true },
|
||||
});
|
||||
const v = settings?.ai_monthly_budget_usd;
|
||||
return v == null ? DEFAULT_BUDGET_USD : Number(v);
|
||||
}
|
||||
|
||||
export async function setBudgetUsd(value: number): Promise<void> {
|
||||
const existing = await prisma.company_settings.findFirst({
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) {
|
||||
await prisma.company_settings.update({
|
||||
where: { id: existing.id },
|
||||
data: { ai_monthly_budget_usd: value },
|
||||
});
|
||||
} else {
|
||||
await prisma.company_settings.create({
|
||||
data: { company_name: "", ai_monthly_budget_usd: value },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns { error, status: 402 } when this month's spend has reached the budget. */
|
||||
export async function assertBudgetAvailable(): Promise<{
|
||||
error: string;
|
||||
status: number;
|
||||
} | null> {
|
||||
const [spend, budget] = await Promise.all([
|
||||
getMonthSpendUsd(),
|
||||
getBudgetUsd(),
|
||||
]);
|
||||
if (spend >= budget) {
|
||||
return { error: "Měsíční rozpočet AI byl vyčerpán", status: 402 };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Conversations (server-side, per user) ─────────────────────────────────
|
||||
export interface StoredChatMessage {
|
||||
role: string;
|
||||
content: string;
|
||||
created_at: Date;
|
||||
}
|
||||
export interface ConversationSummary {
|
||||
id: number;
|
||||
title: string;
|
||||
updated_at: Date;
|
||||
}
|
||||
|
||||
const DEFAULT_CONVERSATION_TITLE = "Nová konverzace";
|
||||
const MESSAGE_LIMIT = 200; // cap a single thread read
|
||||
|
||||
export async function listConversations(
|
||||
userId: number,
|
||||
): Promise<ConversationSummary[]> {
|
||||
return prisma.ai_conversations.findMany({
|
||||
where: { user_id: userId },
|
||||
orderBy: { id: "asc" }, // stable tab order
|
||||
select: { id: true, title: true, updated_at: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createConversation(
|
||||
userId: number,
|
||||
title?: string,
|
||||
): Promise<ConversationSummary> {
|
||||
return prisma.ai_conversations.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
title: title?.trim() || DEFAULT_CONVERSATION_TITLE,
|
||||
},
|
||||
select: { id: true, title: true, updated_at: true },
|
||||
});
|
||||
}
|
||||
|
||||
/** Ownership-checked fetch; null when not found / not owned. */
|
||||
async function ownConversation(userId: number, convId: number) {
|
||||
return prisma.ai_conversations.findFirst({
|
||||
where: { id: convId, user_id: userId },
|
||||
select: { id: true, title: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getConversationMessages(
|
||||
userId: number,
|
||||
convId: number,
|
||||
): Promise<{ data: StoredChatMessage[] } | { error: string; status: number }> {
|
||||
if (!(await ownConversation(userId, convId)))
|
||||
return { error: "Konverzace nenalezena", status: 404 };
|
||||
const rows = await prisma.ai_chat_messages.findMany({
|
||||
where: { conversation_id: convId },
|
||||
orderBy: { id: "desc" },
|
||||
take: MESSAGE_LIMIT,
|
||||
select: { role: true, content: true, created_at: true },
|
||||
});
|
||||
return { data: rows.reverse() };
|
||||
}
|
||||
|
||||
export async function appendConversationMessages(
|
||||
userId: number,
|
||||
convId: number,
|
||||
messages: { role: string; content: string }[],
|
||||
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
|
||||
const conv = await ownConversation(userId, convId);
|
||||
if (!conv) return { error: "Konverzace nenalezena", status: 404 };
|
||||
// The route validates messages with min(1), so this is normally non-empty;
|
||||
// the guard is defensive (and still bumps updated_at below for an empty call).
|
||||
if (messages.length > 0) {
|
||||
await prisma.ai_chat_messages.createMany({
|
||||
data: messages.map((m) => ({
|
||||
user_id: userId,
|
||||
conversation_id: convId,
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
})),
|
||||
});
|
||||
}
|
||||
// Auto-title from the first user message (only while still the default), and
|
||||
// always bump updated_at.
|
||||
const firstUser = messages.find((m) => m.role === "user");
|
||||
const data: { updated_at: Date; title?: string } = { updated_at: new Date() };
|
||||
if (conv.title === DEFAULT_CONVERSATION_TITLE && firstUser) {
|
||||
const t = firstUser.content.replace(/\s+/g, " ").trim().slice(0, 60);
|
||||
if (t) data.title = t;
|
||||
}
|
||||
await prisma.ai_conversations.update({ where: { id: convId }, data });
|
||||
return { data: { ok: true } };
|
||||
}
|
||||
|
||||
export async function renameConversation(
|
||||
userId: number,
|
||||
convId: number,
|
||||
title: string,
|
||||
): Promise<{ data: ConversationSummary } | { error: string; status: number }> {
|
||||
if (!(await ownConversation(userId, convId)))
|
||||
return { error: "Konverzace nenalezena", status: 404 };
|
||||
const updated = await prisma.ai_conversations.update({
|
||||
where: { id: convId },
|
||||
data: { title: title.trim() || DEFAULT_CONVERSATION_TITLE },
|
||||
select: { id: true, title: true, updated_at: true },
|
||||
});
|
||||
return { data: updated };
|
||||
}
|
||||
|
||||
export async function deleteConversation(
|
||||
userId: number,
|
||||
convId: number,
|
||||
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
|
||||
if (!(await ownConversation(userId, convId)))
|
||||
return { error: "Konverzace nenalezena", status: 404 };
|
||||
await prisma.ai_conversations.delete({ where: { id: convId } }); // cascade
|
||||
return { data: { ok: true } };
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT =
|
||||
"Jsi asistent v interním firemním systému (česká firma). Odpovídej česky, stručně a věcně. " +
|
||||
"Nemáš přístup k datům systému; pomáháš s obecnými dotazy a se čtením přiložených faktur.";
|
||||
|
||||
/** Plain chat turn. Records usage. Caller must check the budget first. */
|
||||
export async function chat(
|
||||
messages: ChatMessage[],
|
||||
userId: number | null,
|
||||
): Promise<{ reply: string }> {
|
||||
const res = await client().messages.create({
|
||||
model: AI_MODEL,
|
||||
max_tokens: 2048,
|
||||
system: SYSTEM_PROMPT,
|
||||
messages: messages.map((m) => ({ role: m.role, content: m.content })),
|
||||
});
|
||||
// Best-effort usage logging — a ledger-write blip must not fail the user's
|
||||
// call or vanish silently (CLAUDE.md: never swallow non-fatal failures).
|
||||
try {
|
||||
await recordUsage({
|
||||
userId,
|
||||
kind: "chat",
|
||||
model: AI_MODEL,
|
||||
inputTokens: res.usage.input_tokens,
|
||||
outputTokens: res.usage.output_tokens,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[ai.service] recordUsage failed (chat)", e);
|
||||
}
|
||||
const reply = res.content
|
||||
.filter((b): b is Anthropic.TextBlock => b.type === "text")
|
||||
.map((b) => b.text)
|
||||
.join("\n");
|
||||
return { reply };
|
||||
}
|
||||
|
||||
export interface ExtractedInvoice {
|
||||
supplier_name: string;
|
||||
invoice_number: string | null;
|
||||
amount: number;
|
||||
currency: string;
|
||||
vat_rate: number;
|
||||
issue_date: string | null;
|
||||
due_date: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
// JSON schema for the structured extraction. Typed as the SDK's mutable
|
||||
// index-signature shape (`Record<string, unknown>` leaves), NOT `as const` —
|
||||
// a deeply-readonly literal won't assign to JSONOutputFormat.schema.
|
||||
const INVOICE_SCHEMA: Record<string, unknown> = {
|
||||
type: "object",
|
||||
properties: {
|
||||
supplier_name: { type: "string" },
|
||||
invoice_number: { type: ["string", "null"] },
|
||||
amount: {
|
||||
type: "number",
|
||||
description:
|
||||
"Celková částka k úhradě VČETNĚ DPH (gross total), NE základ bez DPH.",
|
||||
},
|
||||
currency: { type: "string" },
|
||||
vat_rate: {
|
||||
type: "number",
|
||||
description: "Sazba DPH v procentech; 0 pokud faktura nemá DPH.",
|
||||
},
|
||||
issue_date: { type: ["string", "null"] },
|
||||
due_date: { type: ["string", "null"] },
|
||||
description: { type: ["string", "null"] },
|
||||
},
|
||||
required: ["supplier_name", "amount", "currency", "vat_rate"],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
/** Vision-extract the received-invoice fields from a PDF. Records usage. */
|
||||
export async function extractInvoice(
|
||||
pdfBuffer: Buffer,
|
||||
userId: number | null,
|
||||
): Promise<ExtractedInvoice> {
|
||||
const res = await client().messages.create({
|
||||
model: AI_MODEL,
|
||||
max_tokens: 1024,
|
||||
output_config: {
|
||||
format: { type: "json_schema", schema: INVOICE_SCHEMA },
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "document",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "application/pdf",
|
||||
data: pdfBuffer.toString("base64"),
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
"Vyčti z této přijaté faktury tato pole: dodavatele, číslo faktury, " +
|
||||
"celkovou částku k úhradě VČETNĚ DPH (tj. konečný součet, NE základ bez DPH), " +
|
||||
"měnu (ISO kód), sazbu DPH v procentech, datum vystavení a splatnosti (YYYY-MM-DD) a krátký popis. " +
|
||||
"Pokud faktura nemá DPH, vrať sazbu 0. Pokud pole chybí, vrať null.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
try {
|
||||
await recordUsage({
|
||||
userId,
|
||||
kind: "extract",
|
||||
model: AI_MODEL,
|
||||
inputTokens: res.usage.input_tokens,
|
||||
outputTokens: res.usage.output_tokens,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[ai.service] recordUsage failed (extract)", e);
|
||||
}
|
||||
const text = res.content
|
||||
.filter((b): b is Anthropic.TextBlock => b.type === "text")
|
||||
.map((b) => b.text)
|
||||
.join("");
|
||||
return JSON.parse(text) as ExtractedInvoice;
|
||||
}
|
||||
@@ -761,6 +761,157 @@ export async function deleteOverride(
|
||||
return { data: { ok: true }, oldData: existing, description };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bulk entry creation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Bulk-assign a project/category to many employees over a date range. For each
|
||||
* employee, walk the range, keep the days that pass the weekday filter
|
||||
* (weekends excluded unless include_weekends) AND are under the per-cell cap,
|
||||
* group contiguous kept days into runs, and create one range entry per run by
|
||||
* reusing createEntry (so cap / past-date / category validation stays DRY).
|
||||
*
|
||||
* Days that pass the weekday filter but are already at the cap are counted in
|
||||
* skipped_days (and split the range). Weekend days, when excluded, are out of
|
||||
* scope and are NOT counted as skipped.
|
||||
*/
|
||||
export async function bulkCreateEntries(
|
||||
input: {
|
||||
user_ids: number[];
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
include_weekends: boolean;
|
||||
project_id?: number | null;
|
||||
category: string;
|
||||
note: string;
|
||||
},
|
||||
actorUserId: number,
|
||||
): Promise<
|
||||
Result<{
|
||||
created_entries: number;
|
||||
created_days: number;
|
||||
skipped_days: number;
|
||||
users: number;
|
||||
}>
|
||||
> {
|
||||
if (input.user_ids.length === 0) {
|
||||
return { error: "Vyberte alespoň jednoho zaměstnance", status: 400 };
|
||||
}
|
||||
if (input.date_to < input.date_from) {
|
||||
return { error: "Datum do musí být stejné nebo po datumu od", status: 400 };
|
||||
}
|
||||
const lockFrom = assertNotPastDate(input.date_from, false);
|
||||
if (lockFrom) return lockFrom;
|
||||
const lockTo = assertNotPastDate(input.date_to, false);
|
||||
if (lockTo) return lockTo;
|
||||
const catErr = await assertActiveCategory(input.category);
|
||||
if (catErr) return catErr;
|
||||
|
||||
const from = toDateOnly(input.date_from);
|
||||
const to = toDateOnly(input.date_to);
|
||||
|
||||
// Bound the work (users × days). Mirror the 92-day cap on GET /plan/grid so
|
||||
// one bulk call can't fan out into thousands of inserts.
|
||||
const rangeDays = Math.round((to.getTime() - from.getTime()) / 86400000) + 1;
|
||||
if (rangeDays > 92) {
|
||||
return { error: "Maximální rozsah je 92 dní", status: 400 };
|
||||
}
|
||||
|
||||
// The day list for the whole range (UTC midnights), built once.
|
||||
const days: Date[] = [];
|
||||
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
|
||||
days.push(new Date(d));
|
||||
}
|
||||
|
||||
let createdEntries = 0;
|
||||
let createdDays = 0;
|
||||
let skippedDays = 0;
|
||||
|
||||
for (const userId of input.user_ids) {
|
||||
// Per-day cap counts from this user's existing active entries.
|
||||
const existing = await prisma.work_plan_entries.findMany({
|
||||
where: {
|
||||
user_id: userId,
|
||||
is_deleted: false,
|
||||
date_from: { lte: to },
|
||||
date_to: { gte: from },
|
||||
},
|
||||
select: { date_from: true, date_to: true },
|
||||
});
|
||||
const countFor = (day: Date): number =>
|
||||
existing.filter((e) => e.date_from <= day && e.date_to >= day).length;
|
||||
|
||||
// Eligibility per day (weekday filter + under-cap). Tally cap skips.
|
||||
const eligible: boolean[] = [];
|
||||
for (const day of days) {
|
||||
const dow = day.getUTCDay(); // 0 = Sun, 6 = Sat
|
||||
const isWeekend = dow === 0 || dow === 6;
|
||||
if (isWeekend && !input.include_weekends) {
|
||||
eligible.push(false);
|
||||
continue;
|
||||
}
|
||||
if (countFor(day) >= MAX_RECORDS_PER_CELL) {
|
||||
skippedDays++;
|
||||
eligible.push(false);
|
||||
continue;
|
||||
}
|
||||
eligible.push(true);
|
||||
}
|
||||
|
||||
// Group contiguous eligible days into runs; create one range per run.
|
||||
let runStart = -1;
|
||||
for (let i = 0; i <= days.length; i++) {
|
||||
const ok = i < days.length && eligible[i];
|
||||
if (ok && runStart === -1) {
|
||||
runStart = i;
|
||||
} else if (!ok && runStart !== -1) {
|
||||
const segFrom = days[runStart].toISOString().slice(0, 10);
|
||||
const segTo = days[i - 1].toISOString().slice(0, 10);
|
||||
const runDays = i - runStart;
|
||||
const res = await createEntry(
|
||||
{
|
||||
user_id: userId,
|
||||
date_from: segFrom,
|
||||
date_to: segTo,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
},
|
||||
actorUserId,
|
||||
false,
|
||||
);
|
||||
if ("data" in res) {
|
||||
createdEntries++;
|
||||
createdDays += runDays;
|
||||
} else {
|
||||
// Rare race (e.g. the cap filled concurrently between the count and
|
||||
// the create). Treat the run's days as skipped, but log — services
|
||||
// must not swallow non-fatal failures (CLAUDE.md known-issue #4).
|
||||
console.warn("[plan.service] bulkCreateEntries: segment skipped", {
|
||||
userId,
|
||||
segFrom,
|
||||
segTo,
|
||||
error: res.error,
|
||||
});
|
||||
skippedDays += runDays;
|
||||
}
|
||||
runStart = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
created_entries: createdEntries,
|
||||
created_days: createdDays,
|
||||
skipped_days: skippedDays,
|
||||
users: input.user_ids.length,
|
||||
},
|
||||
oldData: null,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Raw-row list endpoints
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user