Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
049ee492c0 | ||
|
|
f4bc038f8b | ||
|
|
58e5fd2b1d | ||
|
|
0226cdd52b | ||
|
|
b665ea1d9b | ||
|
|
ec74ded953 | ||
|
|
bcf63d00d1 | ||
|
|
096784768f | ||
|
|
3623b441ce | ||
|
|
4bf7bf4ed6 |
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
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.
|
||||
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.8",
|
||||
"version": "2.1.0",
|
||||
"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;
|
||||
@@ -76,6 +76,29 @@ 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_chat_messages {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
role String @db.VarChar(20)
|
||||
content String @db.Text
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
|
||||
@@index([user_id, id], map: "idx_ai_chat_user")
|
||||
}
|
||||
|
||||
model bank_accounts {
|
||||
id Int @id @default(autoincrement())
|
||||
account_name String? @db.VarChar(255)
|
||||
@@ -134,6 +157,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 {
|
||||
|
||||
347
src/__tests__/ai.test.ts
Normal file
347
src/__tests__/ai.test.ts
Normal file
@@ -0,0 +1,347 @@
|
||||
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,
|
||||
getChatHistory,
|
||||
appendChatMessages,
|
||||
clearChatHistory,
|
||||
} from "../services/ai.service";
|
||||
|
||||
const KIND = "test_ai"; // marker so we only clean our own rows
|
||||
// Synthetic, FK-free user ids for chat-history service tests (no users row needed).
|
||||
const HIST_UID_A = 999999991;
|
||||
const HIST_UID_B = 999999992;
|
||||
const HIST_MARKER = "「test-hist」"; // marker for HTTP-test rows on real users
|
||||
|
||||
beforeEach(async () => {
|
||||
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
|
||||
await prisma.ai_chat_messages.deleteMany({
|
||||
where: { user_id: { in: [HIST_UID_A, HIST_UID_B] } },
|
||||
});
|
||||
await prisma.ai_chat_messages.deleteMany({
|
||||
where: { content: { 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 chat history", () => {
|
||||
beforeEach(async () => {
|
||||
await prisma.ai_chat_messages.deleteMany({
|
||||
where: { user_id: { in: [HIST_UID_A, HIST_UID_B] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("appends and returns a user's thread oldest → newest", async () => {
|
||||
await appendChatMessages(HIST_UID_A, [
|
||||
{ role: "user", content: "ahoj" },
|
||||
{ role: "assistant", content: "Dobrý den" },
|
||||
]);
|
||||
await appendChatMessages(HIST_UID_A, [
|
||||
{ role: "user", content: "jak se máš" },
|
||||
]);
|
||||
const hist = await getChatHistory(HIST_UID_A);
|
||||
expect(hist.map((m) => m.content)).toEqual([
|
||||
"ahoj",
|
||||
"Dobrý den",
|
||||
"jak se máš",
|
||||
]);
|
||||
expect(hist[0].role).toBe("user");
|
||||
});
|
||||
|
||||
it("isolates history per user", async () => {
|
||||
await appendChatMessages(HIST_UID_A, [{ role: "user", content: "A1" }]);
|
||||
await appendChatMessages(HIST_UID_B, [{ role: "user", content: "B1" }]);
|
||||
const a = await getChatHistory(HIST_UID_A);
|
||||
const b = await getChatHistory(HIST_UID_B);
|
||||
expect(a.map((m) => m.content)).toEqual(["A1"]);
|
||||
expect(b.map((m) => m.content)).toEqual(["B1"]);
|
||||
});
|
||||
|
||||
it("clears a user's thread", async () => {
|
||||
await appendChatMessages(HIST_UID_A, [{ role: "user", content: "x" }]);
|
||||
await clearChatHistory(HIST_UID_A);
|
||||
expect(await getChatHistory(HIST_UID_A)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
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 /history requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/history",
|
||||
headers: { Authorization: `Bearer ${noPermToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("POST /history appends and GET /history returns the thread", async () => {
|
||||
const post = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/history",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
messages: [
|
||||
{ role: "user", content: `${HIST_MARKER} dotaz` },
|
||||
{ role: "assistant", content: `${HIST_MARKER} odpoved` },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(post.statusCode).toBe(200);
|
||||
|
||||
const get = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/history",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(get.statusCode).toBe(200);
|
||||
const contents = get
|
||||
.json()
|
||||
.data.messages.map((m: { content: string }) => m.content);
|
||||
expect(contents).toContain(`${HIST_MARKER} dotaz`);
|
||||
expect(contents).toContain(`${HIST_MARKER} odpoved`);
|
||||
});
|
||||
|
||||
it("POST /history rejects an empty messages array", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/history",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("DELETE /history clears the thread", async () => {
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/history",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [{ role: "user", content: `${HIST_MARKER} x` }] },
|
||||
});
|
||||
const del = await app.inject({
|
||||
method: "DELETE",
|
||||
url: "/api/admin/ai/history",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(del.statusCode).toBe(200);
|
||||
const get = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/history",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const contents = get
|
||||
.json()
|
||||
.data.messages.map((m: { content: string }) => m.content);
|
||||
expect(contents).not.toContain(`${HIST_MARKER} x`);
|
||||
});
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
631
src/admin/components/dashboard/DashAssistant.tsx
Normal file
631
src/admin/components/dashboard/DashAssistant.tsx
Normal file
@@ -0,0 +1,631 @@
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Chip from "@mui/material/Chip";
|
||||
import CircularProgress from "@mui/material/CircularProgress";
|
||||
import { Card, Button, TextField } from "../../ui";
|
||||
import apiFetch from "../../utils/api";
|
||||
import { useAlert } from "../../context/AlertContext";
|
||||
import {
|
||||
aiUsageOptions,
|
||||
aiHistoryOptions,
|
||||
type ExtractedInvoice,
|
||||
} from "../../lib/queries/ai";
|
||||
|
||||
interface ChatTurn {
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
}
|
||||
// The review card is a *form* model: every editable field is a string (what the
|
||||
// inputs hold), distinct from the API's ExtractedInvoice. We convert numbers at
|
||||
// save time. This keeps the type honest — no `number` field holding a string.
|
||||
interface ReviewInvoice {
|
||||
uid: string;
|
||||
supplier_name: string;
|
||||
invoice_number: string;
|
||||
amount: string;
|
||||
currency: string;
|
||||
vat_rate: string;
|
||||
issue_date: string;
|
||||
due_date: string;
|
||||
description: string;
|
||||
file_name: string;
|
||||
file: File;
|
||||
}
|
||||
type EditableField =
|
||||
| "supplier_name"
|
||||
| "invoice_number"
|
||||
| "amount"
|
||||
| "currency"
|
||||
| "vat_rate"
|
||||
| "issue_date"
|
||||
| "due_date"
|
||||
| "description";
|
||||
|
||||
// A staged file carries a stable id so chip keys survive mid-list removal.
|
||||
interface StagedFile {
|
||||
id: string;
|
||||
file: File;
|
||||
}
|
||||
|
||||
// Stable, monotonic id. NOT crypto.randomUUID() — that only exists in a secure
|
||||
// context (HTTPS/localhost) and throws over plain HTTP on a LAN. A counter is
|
||||
// unique within the session and context-independent.
|
||||
let uidSeq = 0;
|
||||
const nextUid = () => `ai-${(uidSeq += 1)}`;
|
||||
|
||||
// How many recent turns to send the model as context (bounds tokens/cost).
|
||||
const MODEL_CONTEXT = 20;
|
||||
// Server schema caps a stored message at 8000 chars.
|
||||
const MAX_STORE = 8000;
|
||||
|
||||
const plural = (n: number) =>
|
||||
n === 1 ? "fakturu" : n >= 2 && n <= 4 ? "faktury" : "faktur";
|
||||
|
||||
/** A human, Czech summary of an extraction so the assistant "reports back". */
|
||||
function summaryNote(reviews: ReviewInvoice[]): string {
|
||||
if (reviews.length === 0) return "V přílohách jsem nenašel žádnou fakturu.";
|
||||
const suppliers = [
|
||||
...new Set(reviews.map((r) => r.supplier_name).filter(Boolean)),
|
||||
];
|
||||
const supTxt =
|
||||
suppliers.length === 1
|
||||
? ` od ${suppliers[0]}`
|
||||
: suppliers.length > 1
|
||||
? ` od ${suppliers[0]} a dalších`
|
||||
: "";
|
||||
const totals: Record<string, number> = {};
|
||||
for (const r of reviews) {
|
||||
const cur = r.currency || "CZK";
|
||||
totals[cur] = (totals[cur] || 0) + (Number(r.amount) || 0);
|
||||
}
|
||||
const totalsTxt = Object.entries(totals)
|
||||
.map(
|
||||
([cur, sum]) =>
|
||||
`${sum.toLocaleString("cs-CZ", {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})} ${cur}`,
|
||||
)
|
||||
.join(" + ");
|
||||
return `Načetl jsem ${reviews.length} ${plural(reviews.length)}${supTxt}, celkem ${totalsTxt}. Zkontrolujte údaje a uložte.`;
|
||||
}
|
||||
|
||||
export default function DashAssistant() {
|
||||
const alert = useAlert();
|
||||
const qc = useQueryClient();
|
||||
const { data: usage } = useQuery(aiUsageOptions());
|
||||
const { data: historyData, isPending: historyPending } =
|
||||
useQuery(aiHistoryOptions());
|
||||
|
||||
const [turns, setTurns] = useState<ChatTurn[]>([]);
|
||||
const [input, setInput] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [review, setReview] = useState<ReviewInvoice[]>([]);
|
||||
const [attachments, setAttachments] = useState<StagedFile[]>([]);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const threadRef = useRef<HTMLDivElement>(null);
|
||||
const seeded = useRef(false);
|
||||
|
||||
// Seed the thread from server history exactly once (first time it arrives).
|
||||
useEffect(() => {
|
||||
if (!seeded.current && historyData) {
|
||||
seeded.current = true;
|
||||
setTurns(
|
||||
historyData.messages.map((m) => ({ role: m.role, content: m.content })),
|
||||
);
|
||||
}
|
||||
}, [historyData]);
|
||||
|
||||
// Keep the thread scrolled to the latest message. Deliberately NOT keyed on
|
||||
// `review` — editing a review-card field must not yank the thread to bottom.
|
||||
useEffect(() => {
|
||||
const el = threadRef.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, [turns, busy]);
|
||||
|
||||
// AI is hidden entirely when the backend isn't configured.
|
||||
if (usage && usage.configured === false) return null;
|
||||
|
||||
// Best-effort: persist the given turns to the server thread. A persistence
|
||||
// blip must not fail the user's interaction, but must not be swallowed.
|
||||
const persist = (msgs: ChatTurn[]) => {
|
||||
apiFetch("/api/admin/ai/history", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
messages: msgs.map((m) => ({
|
||||
role: m.role,
|
||||
content: m.content.slice(0, MAX_STORE),
|
||||
})),
|
||||
}),
|
||||
})
|
||||
.then((r) => {
|
||||
if (!r.ok) return r.json().then((b) => Promise.reject(b?.error));
|
||||
})
|
||||
.catch((e) => console.error("[ai] history persist failed", e));
|
||||
};
|
||||
|
||||
// Attaching only *stages* files — nothing is sent until the user presses
|
||||
// Odeslat. We append (multiple picks accumulate) and clear the input element.
|
||||
const onFiles = (files: FileList | null) => {
|
||||
if (!files || files.length === 0) return;
|
||||
setAttachments((a) => [
|
||||
...a,
|
||||
...Array.from(files).map((file) => ({ id: nextUid(), file })),
|
||||
]);
|
||||
if (fileRef.current) fileRef.current.value = "";
|
||||
};
|
||||
|
||||
const removeAttachment = (id: string) =>
|
||||
setAttachments((a) => a.filter((s) => s.id !== id));
|
||||
|
||||
// Disabled until history has settled, so the user can't send a turn before
|
||||
// the seed runs (which would otherwise let a late history load clobber it).
|
||||
const canSubmit =
|
||||
!historyPending && !busy && (!!input.trim() || attachments.length > 0);
|
||||
|
||||
// Single submit (Odeslat). With staged attachments → extract invoices for
|
||||
// review (the typed message is shown as a caption; the assistant's summary is
|
||||
// the reply to it). Otherwise → a normal chat turn.
|
||||
const submit = async () => {
|
||||
if (busy) return;
|
||||
const text = input.trim();
|
||||
const files = attachments.map((a) => a.file);
|
||||
if (!text && files.length === 0) return;
|
||||
|
||||
// Any interaction means the thread is "live"; a late-arriving history load
|
||||
// must not overwrite it (belt-and-suspenders alongside the canSubmit gate).
|
||||
seeded.current = true;
|
||||
const prevTurns = turns; // snapshot for rollback on failure
|
||||
setBusy(true);
|
||||
|
||||
const userContent = [
|
||||
text,
|
||||
files.length > 0 ? `📎 ${files.map((f) => f.name).join(", ")}` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
const optimistic: ChatTurn[] = [
|
||||
...turns,
|
||||
{ role: "user", content: userContent },
|
||||
];
|
||||
setTurns(optimistic);
|
||||
|
||||
try {
|
||||
if (files.length > 0) {
|
||||
const fd = new FormData();
|
||||
files.forEach((f) => fd.append("files", f));
|
||||
const res = await apiFetch("/api/admin/ai/extract-invoices", {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) throw new Error(body?.error || "Chyba čtení faktur");
|
||||
// The server iterates parts serially and pushes one result per file in
|
||||
// submission order (truncating only if budget runs out mid-batch), so
|
||||
// files[i] is reliably this result's File — more robust than matching by
|
||||
// name, which would collide on duplicate filenames.
|
||||
const reviews: ReviewInvoice[] = (
|
||||
body.data.invoices as Array<{
|
||||
file_name: string;
|
||||
fields?: ExtractedInvoice;
|
||||
error?: string;
|
||||
}>
|
||||
)
|
||||
.map((r, i): ReviewInvoice | null => {
|
||||
const f = r.fields;
|
||||
return f
|
||||
? {
|
||||
uid: nextUid(),
|
||||
supplier_name: f.supplier_name ?? "",
|
||||
invoice_number: f.invoice_number ?? "",
|
||||
amount: f.amount != null ? String(f.amount) : "",
|
||||
currency: f.currency ?? "",
|
||||
vat_rate: f.vat_rate != null ? String(f.vat_rate) : "",
|
||||
issue_date: f.issue_date ?? "",
|
||||
due_date: f.due_date ?? "",
|
||||
description: f.description ?? "",
|
||||
file_name: r.file_name,
|
||||
file: files[i],
|
||||
}
|
||||
: null;
|
||||
})
|
||||
.filter((x): x is ReviewInvoice => x !== null);
|
||||
setReview((prev) => [...prev, ...reviews]);
|
||||
const note = summaryNote(reviews);
|
||||
setTurns((t) => [...t, { role: "assistant", content: note }]);
|
||||
setInput("");
|
||||
setAttachments([]);
|
||||
persist([
|
||||
{ role: "user", content: userContent },
|
||||
{ role: "assistant", content: note },
|
||||
]);
|
||||
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
|
||||
} else {
|
||||
// Send only recent context, and ensure it starts on a user turn (the
|
||||
// Anthropic API requires the first message to be from the user).
|
||||
let ctx = optimistic.slice(-MODEL_CONTEXT);
|
||||
while (ctx.length && ctx[0].role !== "user") ctx = ctx.slice(1);
|
||||
const res = await apiFetch("/api/admin/ai/chat", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ messages: ctx }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) throw new Error(body?.error || "Chyba AI");
|
||||
const reply: string = body.data.reply;
|
||||
setTurns((t) => [...t, { role: "assistant", content: reply }]);
|
||||
setInput("");
|
||||
persist([
|
||||
{ role: "user", content: userContent },
|
||||
{ role: "assistant", content: reply },
|
||||
]);
|
||||
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
|
||||
}
|
||||
} catch (e) {
|
||||
// Roll back the optimistic user turn and KEEP input + attachments so the
|
||||
// user can retry without losing their typed text or staged PDFs.
|
||||
setTurns(prevTurns);
|
||||
const fallback = files.length > 0 ? "Chyba čtení faktur" : "Chyba AI";
|
||||
alert.error(e instanceof Error ? e.message : fallback);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const saveInvoice = async (inv: ReviewInvoice) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("files", inv.file, inv.file_name);
|
||||
fd.append(
|
||||
"invoices",
|
||||
JSON.stringify([
|
||||
{
|
||||
supplier_name: inv.supplier_name,
|
||||
invoice_number: inv.invoice_number || undefined,
|
||||
description: inv.description || undefined,
|
||||
amount: inv.amount === "" ? undefined : Number(inv.amount),
|
||||
currency: inv.currency,
|
||||
vat_rate: inv.vat_rate === "" ? undefined : Number(inv.vat_rate),
|
||||
issue_date: inv.issue_date || undefined,
|
||||
due_date: inv.due_date || undefined,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const res = await apiFetch("/api/admin/received-invoices", {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) throw new Error(body?.error || "Uložení selhalo");
|
||||
alert.success("Faktura uložena");
|
||||
setReview((r) => r.filter((x) => x.uid !== inv.uid));
|
||||
qc.invalidateQueries({ queryKey: ["received-invoices"] });
|
||||
} catch (e) {
|
||||
alert.error(e instanceof Error ? e.message : "Uložení selhalo");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const clearHistory = async () => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await apiFetch("/api/admin/ai/history", { method: "DELETE" });
|
||||
if (!res.ok) throw new Error("Nepodařilo se vymazat historii");
|
||||
setTurns([]);
|
||||
setReview([]);
|
||||
} catch (e) {
|
||||
alert.error(e instanceof Error ? e.message : "Chyba");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const patch = (uid: string, field: EditableField, value: string) =>
|
||||
setReview((r) =>
|
||||
r.map((inv) => (inv.uid === uid ? { ...inv, [field]: value } : inv)),
|
||||
);
|
||||
|
||||
const fieldCols = { xs: "1fr", sm: "1fr 1fr" };
|
||||
|
||||
return (
|
||||
<Card sx={{ mb: 3 }}>
|
||||
{/* Header */}
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
mb: 1.5,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<Box
|
||||
sx={{
|
||||
px: 0.75,
|
||||
py: 0.25,
|
||||
borderRadius: 1,
|
||||
fontSize: 11,
|
||||
fontWeight: 700,
|
||||
letterSpacing: 0.5,
|
||||
color: "common.white",
|
||||
bgcolor: "primary.main",
|
||||
}}
|
||||
>
|
||||
AI
|
||||
</Box>
|
||||
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
|
||||
Asistent
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
{usage && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
Utraceno: ${usage.month_spend_usd.toFixed(2)} / $
|
||||
{usage.budget_usd.toFixed(2)}
|
||||
</Typography>
|
||||
)}
|
||||
{turns.length > 0 && (
|
||||
<Button
|
||||
variant="text"
|
||||
color="inherit"
|
||||
size="small"
|
||||
onClick={clearHistory}
|
||||
disabled={busy}
|
||||
sx={{ minWidth: 0, color: "text.secondary" }}
|
||||
>
|
||||
Vymazat
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Thread */}
|
||||
<Box
|
||||
ref={threadRef}
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 1,
|
||||
minHeight: 120,
|
||||
maxHeight: 360,
|
||||
overflowY: "auto",
|
||||
mb: 1.5,
|
||||
p: 1,
|
||||
borderRadius: 2,
|
||||
bgcolor: "action.hover",
|
||||
}}
|
||||
>
|
||||
{turns.length === 0 && !busy && (
|
||||
<Box
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
textAlign: "center",
|
||||
color: "text.secondary",
|
||||
px: 2,
|
||||
}}
|
||||
>
|
||||
<Typography variant="body2" sx={{ color: "inherit" }}>
|
||||
{historyPending
|
||||
? "Načítám…"
|
||||
: "Zeptejte se, nebo přiložte fakturu (PDF) k automatickému importu."}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{turns.map((t, i) => (
|
||||
<Box
|
||||
key={i}
|
||||
sx={{
|
||||
alignSelf: t.role === "user" ? "flex-end" : "flex-start",
|
||||
maxWidth: "85%",
|
||||
px: 1.5,
|
||||
py: 1,
|
||||
borderRadius: 2,
|
||||
boxShadow: 1,
|
||||
bgcolor: t.role === "user" ? "primary.main" : "background.paper",
|
||||
}}
|
||||
>
|
||||
{/* Color MUST sit on the Typography: GlobalStyles pins `p` to
|
||||
text.secondary, which beats a color merely inherited from the
|
||||
Box. An sx class on the element wins over that element rule. */}
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{
|
||||
whiteSpace: "pre-wrap",
|
||||
color: t.role === "user" ? "common.white" : "text.primary",
|
||||
}}
|
||||
>
|
||||
{t.content}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
|
||||
{busy && (
|
||||
<Box
|
||||
sx={{
|
||||
alignSelf: "flex-start",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
px: 1.5,
|
||||
py: 1,
|
||||
color: "text.secondary",
|
||||
}}
|
||||
>
|
||||
<CircularProgress size={14} />
|
||||
<Typography variant="caption">Pracuji…</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Pending invoices to confirm — rendered OUTSIDE the scrollable thread so
|
||||
the Uložit button is always reachable (the page scrolls if there are
|
||||
many), and editing a field never yanks the chat scroll. */}
|
||||
{review.length > 0 && (
|
||||
<Box sx={{ mb: 1.5 }}>
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
sx={{ fontWeight: 600, color: "text.secondary", mb: 1 }}
|
||||
>
|
||||
Faktury k potvrzení ({review.length})
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
{review.map((inv) => (
|
||||
<Card key={inv.uid} variant="outlined" sx={{ p: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
mb: 1,
|
||||
}}
|
||||
>
|
||||
<Chip label="Faktura" size="small" color="primary" />
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="text.secondary"
|
||||
noWrap
|
||||
title={inv.file_name}
|
||||
>
|
||||
{inv.file_name}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: fieldCols,
|
||||
gap: 1,
|
||||
}}
|
||||
>
|
||||
<TextField
|
||||
label="Dodavatel"
|
||||
value={inv.supplier_name}
|
||||
onChange={(e) =>
|
||||
patch(inv.uid, "supplier_name", e.target.value)
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
label="Číslo faktury"
|
||||
value={inv.invoice_number}
|
||||
onChange={(e) =>
|
||||
patch(inv.uid, "invoice_number", e.target.value)
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
label="Částka s DPH"
|
||||
value={inv.amount}
|
||||
onChange={(e) => patch(inv.uid, "amount", e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Měna"
|
||||
value={inv.currency}
|
||||
onChange={(e) => patch(inv.uid, "currency", e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Sazba DPH %"
|
||||
value={inv.vat_rate}
|
||||
onChange={(e) => patch(inv.uid, "vat_rate", e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Datum vystavení"
|
||||
value={inv.issue_date}
|
||||
onChange={(e) =>
|
||||
patch(inv.uid, "issue_date", e.target.value)
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
label="Datum splatnosti"
|
||||
value={inv.due_date}
|
||||
onChange={(e) => patch(inv.uid, "due_date", e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Popis"
|
||||
value={inv.description}
|
||||
onChange={(e) =>
|
||||
patch(inv.uid, "description", e.target.value)
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ display: "flex", gap: 1, mt: 1.5 }}>
|
||||
<Button onClick={() => saveInvoice(inv)} disabled={busy}>
|
||||
Uložit
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
onClick={() =>
|
||||
setReview((r) => r.filter((x) => x.uid !== inv.uid))
|
||||
}
|
||||
disabled={busy}
|
||||
>
|
||||
Zahodit
|
||||
</Button>
|
||||
</Box>
|
||||
</Card>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Staged attachments */}
|
||||
{attachments.length > 0 && (
|
||||
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5, mb: 1 }}>
|
||||
{attachments.map((s) => (
|
||||
<Chip
|
||||
key={s.id}
|
||||
label={s.file.name}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
onDelete={busy ? undefined : () => removeAttachment(s.id)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Composer */}
|
||||
<Box sx={{ display: "flex", gap: 1, alignItems: "center" }}>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="application/pdf,image/*"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(e) => onFiles(e.target.files)}
|
||||
/>
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={busy}
|
||||
>
|
||||
Přiložit
|
||||
</Button>
|
||||
<TextField
|
||||
fullWidth
|
||||
placeholder="Napište zprávu…"
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button onClick={submit} disabled={!canSubmit}>
|
||||
Odeslat
|
||||
</Button>
|
||||
</Box>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
46
src/admin/lib/queries/ai.ts
Normal file
46
src/admin/lib/queries/ai.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
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 const aiHistoryOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["ai", "history"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ messages: StoredChatMessage[] }>("/api/admin/ai/history"),
|
||||
// Within a mount the thread is seeded once and mutated locally, so don't
|
||||
// refetch on focus (staleTime Infinity). But gcTime 0 drops the cache on
|
||||
// unmount, so every remount re-reads the DB (the source of truth) — this
|
||||
// is what keeps a cleared/appended thread from resurrecting stale messages.
|
||||
staleTime: Infinity,
|
||||
gcTime: 0,
|
||||
});
|
||||
@@ -22,6 +22,7 @@ import DashSessions from "../components/dashboard/DashSessions";
|
||||
import DashTodayPlan, {
|
||||
type TodayPlan,
|
||||
} from "../components/dashboard/DashTodayPlan";
|
||||
import DashAssistant from "../components/dashboard/DashAssistant";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -236,6 +237,9 @@ export default function Dashboard() {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* AI Assistant widget */}
|
||||
{hasPermission("ai.use") && <DashAssistant />}
|
||||
|
||||
{/* 2FA Required Banner */}
|
||||
{user?.require2FA && !user?.totpEnabled && (
|
||||
<Card
|
||||
|
||||
@@ -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={{
|
||||
|
||||
@@ -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 || "",
|
||||
|
||||
165
src/routes/admin/ai.ts
Normal file
165
src/routes/admin/ai.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
|
||||
import multipart from "@fastify/multipart";
|
||||
import { requirePermission } from "../../middleware/auth";
|
||||
import { success, error } from "../../utils/response";
|
||||
import { parseBody } from "../../schemas/common";
|
||||
import {
|
||||
AiChatSchema,
|
||||
AiBudgetSchema,
|
||||
AiHistoryAppendSchema,
|
||||
} from "../../schemas/ai.schema";
|
||||
import { logAudit } from "../../services/audit";
|
||||
import { config } from "../../config/env";
|
||||
import {
|
||||
isConfigured,
|
||||
assertBudgetAvailable,
|
||||
getMonthSpendUsd,
|
||||
getBudgetUsd,
|
||||
setBudgetUsd,
|
||||
chat,
|
||||
extractInvoice,
|
||||
getChatHistory,
|
||||
appendChatMessages,
|
||||
clearChatHistory,
|
||||
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 /api/admin/ai/history — this user's stored chat thread
|
||||
app.get(
|
||||
"/history",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const messages = await getChatHistory(request.authData!.userId);
|
||||
return success(reply, { messages });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /api/admin/ai/history — append turns to this user's thread
|
||||
app.post(
|
||||
"/history",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(AiHistoryAppendSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
await appendChatMessages(request.authData!.userId, body.data.messages);
|
||||
return success(reply, { ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /api/admin/ai/history — clear this user's thread
|
||||
app.delete(
|
||||
"/history",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
await clearChatHistory(request.authData!.userId);
|
||||
return success(reply, { ok: true });
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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 =
|
||||
|
||||
32
src/schemas/ai.schema.ts
Normal file
32
src/schemas/ai.schema.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
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 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"),
|
||||
});
|
||||
@@ -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) {
|
||||
|
||||
279
src/services/ai.service.ts
Normal file
279
src/services/ai.service.ts
Normal file
@@ -0,0 +1,279 @@
|
||||
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;
|
||||
}
|
||||
|
||||
// ── Chat history (server-side, permanent, per user) ───────────────────────
|
||||
export interface StoredChatMessage {
|
||||
role: string;
|
||||
content: string;
|
||||
created_at: Date;
|
||||
}
|
||||
|
||||
// Cap how many turns we read back / display. The full thread stays in the DB;
|
||||
// this only bounds a single GET payload (and, on the client, the model context).
|
||||
const HISTORY_LIMIT = 200;
|
||||
|
||||
/** This user's chat thread, oldest → newest, capped at HISTORY_LIMIT. */
|
||||
export async function getChatHistory(
|
||||
userId: number,
|
||||
): Promise<StoredChatMessage[]> {
|
||||
const rows = await prisma.ai_chat_messages.findMany({
|
||||
where: { user_id: userId },
|
||||
orderBy: { id: "desc" },
|
||||
take: HISTORY_LIMIT,
|
||||
select: { role: true, content: true, created_at: true },
|
||||
});
|
||||
return rows.reverse();
|
||||
}
|
||||
|
||||
/** Append turns to this user's thread (best-effort caller). */
|
||||
export async function appendChatMessages(
|
||||
userId: number,
|
||||
messages: { role: string; content: string }[],
|
||||
): Promise<void> {
|
||||
if (messages.length === 0) return;
|
||||
await prisma.ai_chat_messages.createMany({
|
||||
data: messages.map((m) => ({
|
||||
user_id: userId,
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
/** Wipe this user's thread. */
|
||||
export async function clearChatHistory(userId: number): Promise<void> {
|
||||
await prisma.ai_chat_messages.deleteMany({ where: { user_id: userId } });
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user