Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
049ee492c0 | ||
|
|
f4bc038f8b | ||
|
|
58e5fd2b1d | ||
|
|
0226cdd52b | ||
|
|
b665ea1d9b | ||
|
|
ec74ded953 | ||
|
|
bcf63d00d1 | ||
|
|
096784768f | ||
|
|
3623b441ce | ||
|
|
4bf7bf4ed6 | ||
|
|
92252382ac | ||
|
|
8bed920de1 | ||
|
|
9d2992b722 | ||
|
|
1ddc0feccd | ||
|
|
cce2c9cfaa | ||
|
|
2610301258 | ||
|
|
13d1fc2be3 | ||
|
|
95ca258718 | ||
|
|
6db87bf4ae | ||
|
|
c6a146d57a | ||
|
|
1a262508d4 | ||
|
|
23ac924472 | ||
|
|
9370423fb0 | ||
|
|
a146fc26a3 | ||
|
|
72888bf9cd | ||
|
|
80dc8a5c69 | ||
|
|
2cfa28dc47 | ||
|
|
628cd54a81 | ||
|
|
9ae69e09a3 |
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).
|
||||
1524
docs/superpowers/plans/2026-06-08-multi-record-plan-cells.md
Normal file
1524
docs/superpowers/plans/2026-06-08-multi-record-plan-cells.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.
|
||||
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.
|
||||
@@ -0,0 +1,208 @@
|
||||
# Design — Multi-record plan cells (max 3 per cell)
|
||||
|
||||
**Date:** 2026-06-08
|
||||
**Status:** Approved (brainstorming) — ready for implementation plan
|
||||
**Feature A of 2.** Feature B (bulk plan creation) is a separate later cycle — see "Deferred: Feature B" at the end.
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Today a plan cell (one person, one day) resolves to **exactly one** record: an
|
||||
override hides the planned range, and overlapping range entries collapse to
|
||||
"newest wins". The work plan should instead let a cell hold **up to 3 records**,
|
||||
so a person can have several assignments on the same day (additive) _and_ still
|
||||
get one-day exceptions to a planned range.
|
||||
|
||||
This is the enabling model change. The eventual "bulk assign a project to many
|
||||
employees over a date range" form (Feature B) will create records under this
|
||||
model and respect the 3-per-cell cap.
|
||||
|
||||
## Use cases (both required)
|
||||
|
||||
1. **Additive** — several projects/tasks the same day (e.g. morning project A,
|
||||
afternoon project B). Both records show in the cell.
|
||||
2. **Day exception** — assigned to a multi-day range, but one day differs;
|
||||
replace just that day without splitting the range.
|
||||
|
||||
## Non-goals / out of scope
|
||||
|
||||
- No bulk-create UI (Feature B).
|
||||
- No database migration — the tables already allow multiple rows per
|
||||
(user, day) (the old `work_plan_overrides` uniqueness constraint was dropped in
|
||||
migration `20260605122718_drop_wpo_unique_constraint`).
|
||||
- The max is a fixed constant (3), not user-configurable.
|
||||
|
||||
---
|
||||
|
||||
## Model — "layered" (approved)
|
||||
|
||||
Keep the two existing tables and their meaning; stop collapsing them to one
|
||||
record.
|
||||
|
||||
- **`work_plan_entries` (ranges) = the normal-plan layer.** Multiple active
|
||||
ranges may cover the same day → the **additive** case.
|
||||
- **`work_plan_overrides` (single-day) = the exception layer.** When a day has
|
||||
≥1 active override, the overrides **replace** the range entries for that day
|
||||
(today's "override beats entry" rule, kept) → the **day-exception** case.
|
||||
|
||||
### Resolution rule
|
||||
|
||||
For a given `(user, day)`:
|
||||
|
||||
1. Active overrides for that exact day (`is_deleted = false`). If any →
|
||||
the cell is the overrides, **newest-first, capped at 3**.
|
||||
2. Otherwise → active entries covering that day
|
||||
(`date_from ≤ day ≤ date_to`, `is_deleted = false`), **newest-first, capped at 3**.
|
||||
3. Otherwise → empty.
|
||||
|
||||
The cell is therefore an array of 0–3 `ResolvedCell` items, all from a single
|
||||
layer (overrides **or** entries, never mixed). This preserves the "exception
|
||||
replaces the day" semantic while allowing additive stacking within each layer.
|
||||
|
||||
**Known limitation (accepted):** a range entry and an exception override cannot
|
||||
show together on the same day — an override is all-or-nothing for that day. This
|
||||
matches what "exception" means.
|
||||
|
||||
### Cap (max 3 per cell)
|
||||
|
||||
`MAX_RECORDS_PER_CELL = 3` (single constant in `plan.service.ts`).
|
||||
|
||||
Enforced on create, per layer, per day:
|
||||
|
||||
- **`createOverride`** — reject if the `(user, day)` already has 3 active
|
||||
overrides.
|
||||
- **`createEntry`** — reject if **any** day in the new `[date_from, date_to]`
|
||||
range is already covered by 3 active entries for that user. The error names the
|
||||
first offending date (Czech message). Cap counts entries regardless of whether
|
||||
they are currently hidden by an override (simpler and predictable).
|
||||
|
||||
`createOverride` **changes from replace-semantics to additive-with-cap**: it no
|
||||
longer soft-deletes the existing override for that day. The transaction +
|
||||
row-lock that protected the old "at most one active override" invariant is
|
||||
repurposed to enforce "at most 3" under concurrency. The `replacedData` /
|
||||
`replacedDescription` plumbing (and the route branch that logged the replaced
|
||||
row's soft-delete) is removed.
|
||||
|
||||
---
|
||||
|
||||
## Backend changes
|
||||
|
||||
### `src/services/plan.service.ts`
|
||||
|
||||
- `ResolvedCell` interface unchanged (still one record).
|
||||
- `resolveCell(userId, dateStr)` → returns `ResolvedCell[]` (0–3) using the
|
||||
resolution rule above. Replaces the current single-result + "newest wins"
|
||||
`console.warn`.
|
||||
- `resolveGrid(userIds, from, to)` → `cells[userId][dateStr]` becomes
|
||||
`ResolvedCell[]` (empty array, not `null`, for no records). Same two-query
|
||||
load; per (user, day) build the capped array from the right layer.
|
||||
- `createEntry` → add the per-day entry-cap check before insert.
|
||||
- `createOverride` → drop the soft-delete-replace; add the override-cap check;
|
||||
keep the transaction/lock for race safety; drop `replacedData`.
|
||||
- Add `export const MAX_RECORDS_PER_CELL = 3;`.
|
||||
|
||||
### `src/routes/admin/plan.ts`
|
||||
|
||||
- `POST /plan/overrides` — remove the `result.replacedData` audit branch (no
|
||||
longer produced). Everything else unchanged (cap errors surface via the normal
|
||||
`{ error, status }` path).
|
||||
|
||||
### `src/routes/admin/dashboard.ts`
|
||||
|
||||
- `today_plan` is built from `resolveCell` → now an **array**. Map each record
|
||||
with its category label + colour (the existing enrichment, applied per item).
|
||||
`result.today_plan` becomes `TodayPlan[]` (possibly empty).
|
||||
|
||||
---
|
||||
|
||||
## Frontend changes
|
||||
|
||||
### Types — `src/admin/lib/queries/plan.ts`
|
||||
|
||||
- `GridData.cells: Record<number, Record<string, ResolvedCell[]>>` (was
|
||||
`ResolvedCell | null`).
|
||||
|
||||
### Grid — `src/admin/components/PlanGrid.tsx` + `PlanRangeChips.tsx`
|
||||
|
||||
- A cell renders **up to 3 stacked records**, each a compact row: category
|
||||
colour bar + category label + project (mono). When the cell has **exactly one**
|
||||
record, also show its note (2-line clamp), as today. With 2–3 records, notes
|
||||
are omitted for density.
|
||||
- `--cat-color` is set per record row (not per cell).
|
||||
- `onCellClick(userId, date, cells)` passes the **array**. Empty cell → still a
|
||||
one-click create. Occupied cell → opens the day panel (below).
|
||||
- Past-day / read-only / weekend / today styling unchanged.
|
||||
|
||||
```
|
||||
┌─ Jan N. · Čt 12 ───────┐
|
||||
│▌ PRÁCE · 26710001 │
|
||||
│▌ DOVOLENÁ │
|
||||
│▌ ŠKOLENÍ · 26710044 │
|
||||
└────────────────────────┘ ▌ = category colour bar
|
||||
```
|
||||
|
||||
### Cell editor — `src/admin/components/PlanCellModal.tsx`
|
||||
|
||||
New top-level **day-panel** mode shown when a cell has ≥1 record:
|
||||
|
||||
- Lists the day's records (each: colour bar, category, project, optional note)
|
||||
with **edit (✎)** and **delete (🗑)** per record.
|
||||
- **"+ Přidat záznam"** button, disabled at 3 with a hint
|
||||
("Maximum 3 záznamy na den"). Add targets the **showing layer**: an entry in
|
||||
normal mode, an override in exception mode — so the panel reads simply as
|
||||
"records for this day" and the entry/override distinction stays invisible.
|
||||
- Editing a record reuses the existing `EditForm`. Editing a record that belongs
|
||||
to a **multi-day range** still routes through the existing `day-in-range`
|
||||
chooser ("edit whole range" vs "carve out this day" = create override).
|
||||
- Empty cell skips the panel and opens the create form directly (current
|
||||
behaviour).
|
||||
|
||||
`PlanWork.tsx` wires the new panel: cell-click opens it with the array; the
|
||||
panel's per-record actions reuse the existing entry/override create/update/delete
|
||||
mutations and `invalidate: ["plan"]`.
|
||||
|
||||
### Dashboard — `DashTodayPlan.tsx` + `Dashboard.tsx`
|
||||
|
||||
- `today_plan` prop becomes `TodayPlan[]`. Render up to 3 records stacked
|
||||
(reuse the existing single-record card layout per item). Empty array → the
|
||||
existing "Pro dnešek nemáte naplánováno." state.
|
||||
|
||||
---
|
||||
|
||||
## Testing (`src/__tests__/plan.test.ts`)
|
||||
|
||||
Update existing assertions for the array shape, and add:
|
||||
|
||||
- `resolveCell` returns `[]` for an empty day; one item for a single entry; the
|
||||
override layer (entries hidden) when an override exists.
|
||||
- **Additive:** two entries covering the same day → both returned (newest first).
|
||||
- **Cap display:** 4 overlapping entries on a day → only 3 returned.
|
||||
- **Cap enforcement:** `createEntry` rejects when a day in range already has 3
|
||||
entries (error names the date); `createOverride` rejects at 3 overrides.
|
||||
- **Additive overrides:** `createOverride` no longer soft-deletes the prior
|
||||
override; two overrides on a day coexist.
|
||||
- `resolveGrid` cell arrays match `resolveCell` for the same (user, day).
|
||||
|
||||
Gates: `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`.
|
||||
|
||||
## Rollout
|
||||
|
||||
Ships as its own release (**v2.0.5**) via the standard process (commit → tag →
|
||||
Gitea → tarball → prod deploy → health check). No migration step.
|
||||
|
||||
---
|
||||
|
||||
## Deferred: Feature B (bulk plan creation) — decisions captured
|
||||
|
||||
A later, separate spec + cycle. Locked decisions from this brainstorming:
|
||||
|
||||
- **Form:** select one project, a date range (from–to), and multiple employees;
|
||||
create the assignment for all of them at once.
|
||||
- **Category:** a category picker in the bulk form, **default Práce**.
|
||||
- **Weekends:** an **"include weekends" checkbox** (off = Mon–Fri only, which
|
||||
requires splitting each person into per-work-week entries; on = one continuous
|
||||
range).
|
||||
- **Conflict handling:** governed by this feature's **max-3-per-cell** rule — for
|
||||
each employee/day, create the record only if the cell is under the cap;
|
||||
otherwise **skip** that day (no error).
|
||||
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.3",
|
||||
"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`);
|
||||
});
|
||||
});
|
||||
@@ -68,3 +68,39 @@ describe("NasFileManager.createProjectFolder", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Folder deletion primitive used by the "delete folder" checkbox on both the
|
||||
* order delete (orders.service deleteOrder) and project delete (projects.service
|
||||
* deleteProject) paths. Matches the project by number prefix.
|
||||
*/
|
||||
describe("NasFileManager.deleteProjectFolder", () => {
|
||||
let tmpBase: string;
|
||||
let nas: NasFileManager;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpBase = fs.mkdtempSync(path.join(os.tmpdir(), "nas-del-"));
|
||||
nas = new NasFileManager(tmpBase);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpBase, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("removes an existing project folder (matched by number prefix)", async () => {
|
||||
nas.createProjectFolder("26710010", "Hala");
|
||||
expect(fs.existsSync(path.join(tmpBase, "26710010_Hala"))).toBe(true);
|
||||
const ok = await nas.deleteProjectFolder("26710010");
|
||||
expect(ok).toBe(true);
|
||||
expect(fs.existsSync(path.join(tmpBase, "26710010_Hala"))).toBe(false);
|
||||
});
|
||||
|
||||
it("is a no-op (returns true) when no folder exists for the number", async () => {
|
||||
expect(await nas.deleteProjectFolder("26710011")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the NAS base is not mounted", async () => {
|
||||
const missing = new NasFileManager(path.join(tmpBase, "nope"));
|
||||
expect(await missing.deleteProjectFolder("26710012")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
deleteOverride,
|
||||
listEntries,
|
||||
listOverrides,
|
||||
bulkCreateEntries,
|
||||
} from "../services/plan.service";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -58,6 +59,20 @@ beforeEach(async () => {
|
||||
await prisma.work_plan_overrides.deleteMany({
|
||||
where: { note: { contains: N } },
|
||||
});
|
||||
// Also clean up empty-note rows on the specific test dates used by the
|
||||
// "allows an empty note" tests. These rows are not caught by the prefix
|
||||
// filter above, and would cause the per-cell cap check to reject them
|
||||
// once three accumulate across runs.
|
||||
await prisma.work_plan_entries.deleteMany({
|
||||
where: {
|
||||
date_from: {
|
||||
in: [
|
||||
new Date("2099-07-15T00:00:00.000Z"),
|
||||
new Date("2097-08-05T00:00:00.000Z"),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -75,10 +90,9 @@ afterAll(async () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("plan.service.resolveCell", () => {
|
||||
it("returns null when nothing covers the date", async () => {
|
||||
// No entry, no override for (adminUserId, "2099-01-01")
|
||||
it("returns [] when nothing covers the date", async () => {
|
||||
const result = await resolveCell(adminUserId, "2099-01-01");
|
||||
expect(result).toBeNull();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns the entry that covers the date", async () => {
|
||||
@@ -93,17 +107,14 @@ describe("plan.service.resolveCell", () => {
|
||||
},
|
||||
});
|
||||
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.source).toBe("entry");
|
||||
expect(result?.note).toBe(`${N}PLC upgrade`);
|
||||
expect(result?.category).toBe("work");
|
||||
expect(result?.rangeFrom).toBe("2099-06-01");
|
||||
expect(result?.rangeTo).toBe("2099-06-10");
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].source).toBe("entry");
|
||||
expect(result[0].note).toBe(`${N}PLC upgrade`);
|
||||
expect(result[0].rangeFrom).toBe("2099-06-01");
|
||||
expect(result[0].rangeTo).toBe("2099-06-10");
|
||||
});
|
||||
|
||||
it("returns the override for that day, not the entry", async () => {
|
||||
// An entry covers 2099-06-01..2099-06-10, but an override on 2099-06-05
|
||||
// takes precedence.
|
||||
it("returns overrides (entries hidden) when an override exists", async () => {
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
@@ -124,10 +135,51 @@ describe("plan.service.resolveCell", () => {
|
||||
},
|
||||
});
|
||||
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.source).toBe("override");
|
||||
expect(result?.note).toBe(`${N}Volno po noční`);
|
||||
expect(result?.category).toBe("leave");
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].source).toBe("override");
|
||||
expect(result[0].note).toBe(`${N}Volno po noční`);
|
||||
});
|
||||
|
||||
it("returns multiple additive entries newest-first", async () => {
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2099-06-01"),
|
||||
date_to: new Date("2099-06-10"),
|
||||
category: "work",
|
||||
note: `${N}first`,
|
||||
created_by: adminUserId,
|
||||
},
|
||||
});
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2099-06-05"),
|
||||
date_to: new Date("2099-06-05"),
|
||||
category: "work",
|
||||
note: `${N}second`,
|
||||
created_by: adminUserId,
|
||||
},
|
||||
});
|
||||
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||
expect(result.length).toBe(2);
|
||||
expect(result[0].note).toBe(`${N}second`); // newest first
|
||||
});
|
||||
|
||||
it("caps the returned records at MAX_RECORDS_PER_CELL", async () => {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
await prisma.work_plan_overrides.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
shift_date: new Date("2099-06-06"),
|
||||
category: "leave",
|
||||
note: `${N}cap${i}`,
|
||||
created_by: adminUserId,
|
||||
},
|
||||
});
|
||||
}
|
||||
const result = await resolveCell(adminUserId, "2099-06-06");
|
||||
expect(result.length).toBe(3);
|
||||
});
|
||||
|
||||
it("ignores soft-deleted entries and overrides", async () => {
|
||||
@@ -143,7 +195,7 @@ describe("plan.service.resolveCell", () => {
|
||||
},
|
||||
});
|
||||
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||
expect(result).toBeNull();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -164,11 +216,11 @@ describe("plan.service.resolveGrid", () => {
|
||||
},
|
||||
});
|
||||
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-05");
|
||||
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-04"]).toBeNull();
|
||||
expect(cells[adminUserId]["2099-06-05"]).toBeNull();
|
||||
expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-04"]).toEqual([]);
|
||||
expect(cells[adminUserId]["2099-06-05"]).toEqual([]);
|
||||
});
|
||||
|
||||
it("applies override on a covered day", async () => {
|
||||
@@ -192,9 +244,78 @@ describe("plan.service.resolveGrid", () => {
|
||||
},
|
||||
});
|
||||
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-03");
|
||||
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}B`);
|
||||
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-01"][0]?.note).toBe(`${N}A`);
|
||||
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}B`);
|
||||
expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
|
||||
});
|
||||
|
||||
it("stacks additive entries newest-first and caps the day at MAX_RECORDS_PER_CELL", async () => {
|
||||
// Two entries cover 2099-06-12 → both appear, newest-first. A 3rd entry
|
||||
// covering the same day and a 4th overlapping one push past the cap, so the
|
||||
// day must still return exactly 3 (mirrors resolveCell's cap behaviour).
|
||||
//
|
||||
// created_at is @db.Timestamp(0) (second precision, MySQL TIMESTAMP range
|
||||
// tops out at 2038), so rows created in the same second tie on the
|
||||
// `created_at desc` sort. We set explicit, distinct in-range created_at
|
||||
// values so the newest-first assertion is deterministic.
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2099-06-11"),
|
||||
date_to: new Date("2099-06-12"),
|
||||
category: "work",
|
||||
note: `${N}g1`,
|
||||
created_by: adminUserId,
|
||||
created_at: new Date("2037-06-01T08:00:00.000Z"),
|
||||
},
|
||||
});
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2099-06-12"),
|
||||
date_to: new Date("2099-06-12"),
|
||||
category: "work",
|
||||
note: `${N}g2`,
|
||||
created_by: adminUserId,
|
||||
created_at: new Date("2037-06-01T09:00:00.000Z"), // newer than g1
|
||||
},
|
||||
});
|
||||
// Two-entry day: assert length 2 and newest-first ordering.
|
||||
const twoDay = await resolveGrid([adminUserId], "2099-06-11", "2099-06-12");
|
||||
expect(twoDay[adminUserId]["2099-06-12"].length).toBe(2);
|
||||
expect(twoDay[adminUserId]["2099-06-12"][0].note).toBe(`${N}g2`); // newest first
|
||||
// Day with no second entry stays single.
|
||||
expect(twoDay[adminUserId]["2099-06-11"].length).toBe(1);
|
||||
|
||||
// Add a 3rd and a 4th overlapping entry on 2099-06-12 to exceed the cap.
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2099-06-12"),
|
||||
date_to: new Date("2099-06-12"),
|
||||
category: "work",
|
||||
note: `${N}g3`,
|
||||
created_by: adminUserId,
|
||||
created_at: new Date("2037-06-01T10:00:00.000Z"),
|
||||
},
|
||||
});
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2099-06-12"),
|
||||
date_to: new Date("2099-06-12"),
|
||||
category: "work",
|
||||
note: `${N}g4`,
|
||||
created_by: adminUserId,
|
||||
created_at: new Date("2037-06-01T11:00:00.000Z"),
|
||||
},
|
||||
});
|
||||
const cappedDay = await resolveGrid(
|
||||
[adminUserId],
|
||||
"2099-06-12",
|
||||
"2099-06-12",
|
||||
);
|
||||
expect(cappedDay[adminUserId]["2099-06-12"].length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -341,6 +462,36 @@ describe("plan.service.createEntry", () => {
|
||||
expect("error" in result).toBe(true);
|
||||
if ("error" in result) expect(result.status).toBe(403);
|
||||
});
|
||||
|
||||
it("rejects a 4th entry covering a day already at the cap", async () => {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const r = await createEntry(
|
||||
{
|
||||
user_id: adminUserId,
|
||||
date_from: "2099-07-20",
|
||||
date_to: "2099-07-20",
|
||||
category: "work",
|
||||
note: `${N}e${i}`,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
expect("data" in r).toBe(true);
|
||||
}
|
||||
const fourth = await createEntry(
|
||||
{
|
||||
user_id: adminUserId,
|
||||
date_from: "2099-07-20",
|
||||
date_to: "2099-07-20",
|
||||
category: "work",
|
||||
note: `${N}e3`,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
expect("error" in fourth).toBe(true);
|
||||
if ("error" in fourth) expect(fourth.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -439,7 +590,7 @@ describe("plan.service.deleteEntry", () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("plan.service.createOverride", () => {
|
||||
it("creates an override and returns { data, oldData: null, replacedData: null }", async () => {
|
||||
it("creates an override and returns { data, oldData: null }", async () => {
|
||||
const result = await createOverride(
|
||||
{
|
||||
user_id: adminUserId,
|
||||
@@ -454,42 +605,45 @@ describe("plan.service.createOverride", () => {
|
||||
if ("data" in result) {
|
||||
expect(result.data.note).toBe(`${N}day off`);
|
||||
expect(result.oldData).toBeNull();
|
||||
expect(result.replacedData).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("soft-deletes the existing override and reports it in replacedData", async () => {
|
||||
await createOverride(
|
||||
it("stacks additive overrides and caps at MAX_RECORDS_PER_CELL", async () => {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const r = await createOverride(
|
||||
{
|
||||
user_id: adminUserId,
|
||||
shift_date: "2099-10-02",
|
||||
category: "leave",
|
||||
note: `${N}o${i}`,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
expect("data" in r).toBe(true);
|
||||
}
|
||||
// A 4th record on the same day is rejected by the cap.
|
||||
const fourth = await createOverride(
|
||||
{
|
||||
user_id: adminUserId,
|
||||
shift_date: "2099-10-02",
|
||||
category: "leave",
|
||||
note: `${N}first`,
|
||||
note: `${N}o3`,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
const second = await createOverride(
|
||||
{
|
||||
expect("error" in fourth).toBe(true);
|
||||
if ("error" in fourth) expect(fourth.status).toBe(400);
|
||||
// All three earlier overrides remain active — no replace happened.
|
||||
const active = await prisma.work_plan_overrides.findMany({
|
||||
where: {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2099-10-02",
|
||||
category: "sick",
|
||||
note: `${N}second`,
|
||||
shift_date: new Date("2099-10-02"),
|
||||
is_deleted: false,
|
||||
},
|
||||
adminUserId,
|
||||
false,
|
||||
);
|
||||
expect("data" in second).toBe(true);
|
||||
if ("data" in second) {
|
||||
expect((second.replacedData as any)?.note).toBe(`${N}first`);
|
||||
}
|
||||
|
||||
const all = await prisma.work_plan_overrides.findMany({
|
||||
where: { user_id: adminUserId, shift_date: new Date("2099-10-02") },
|
||||
});
|
||||
// The first should be soft-deleted, the second active
|
||||
expect(all.find((o) => o.note === `${N}first`)?.is_deleted).toBe(true);
|
||||
expect(all.find((o) => o.note === `${N}second`)?.is_deleted).toBe(false);
|
||||
expect(active.length).toBe(3);
|
||||
});
|
||||
|
||||
it("rejects a past date without force", async () => {
|
||||
@@ -635,6 +789,184 @@ describe("plan.service.listOverrides (employee scoping)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// bulkCreateEntries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("plan.service.bulkCreateEntries", () => {
|
||||
it("creates one continuous range per employee when weekends are included", async () => {
|
||||
// 2096-06-01 is a Friday; 2096-06-03 is a Sunday. include_weekends → one
|
||||
// range 06-01..06-03 covering all 3 days.
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-wknd`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(1);
|
||||
expect(res.data.created_days).toBe(3);
|
||||
expect(res.data.skipped_days).toBe(0);
|
||||
expect(res.data.users).toBe(1);
|
||||
});
|
||||
|
||||
it("splits into per-work-week ranges and skips weekends when excluded", async () => {
|
||||
// 2096-06-01 (Fri) .. 2096-06-05 (Tue): Fri | Sat Sun excluded | Mon Tue.
|
||||
// Two runs: [06-01] and [06-04..06-05] → 2 entries, 3 days, 0 skipped.
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-05",
|
||||
include_weekends: false,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-week`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(3);
|
||||
expect(res.data.skipped_days).toBe(0);
|
||||
});
|
||||
|
||||
it("skips days already at the cap and splits the range around them", async () => {
|
||||
// Pre-fill 2096-07-02 to the cap (3 entries) for the user. A weekends-on
|
||||
// bulk over 07-01..07-03 then creates 07-01 and 07-03 (two ranges), skips
|
||||
// 07-02. 2096-07-01..03 are Sun/Mon/Tue — all included with weekends on.
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
date_from: new Date("2096-07-02"),
|
||||
date_to: new Date("2096-07-02"),
|
||||
category: "work",
|
||||
note: `${N}cap${i}`,
|
||||
created_by: adminUserId,
|
||||
},
|
||||
});
|
||||
}
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-07-01",
|
||||
date_to: "2096-07-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-cap`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(2);
|
||||
expect(res.data.skipped_days).toBe(1);
|
||||
});
|
||||
|
||||
it("aggregates across multiple employees", async () => {
|
||||
const res = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId, noPermUserId],
|
||||
date_from: "2096-08-03", // Friday
|
||||
date_to: "2096-08-03",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}bulk-multi`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("data" in res).toBe(true);
|
||||
if (!("data" in res)) return;
|
||||
expect(res.data.users).toBe(2);
|
||||
expect(res.data.created_entries).toBe(2);
|
||||
expect(res.data.created_days).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects empty user_ids, past dates, bad range, and inactive category", async () => {
|
||||
const empty = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in empty && empty.status).toBe(400);
|
||||
|
||||
const tooLong = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-01-01",
|
||||
date_to: "2096-12-31", // > 92 days
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in tooLong && tooLong.status).toBe(400);
|
||||
|
||||
const past = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2000-01-01",
|
||||
date_to: "2000-01-02",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in past && past.status).toBe(403);
|
||||
|
||||
const badRange = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-10",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "work",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in badRange && badRange.status).toBe(400);
|
||||
|
||||
const badCat = await bulkCreateEntries(
|
||||
{
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2096-06-01",
|
||||
date_to: "2096-06-01",
|
||||
include_weekends: true,
|
||||
project_id: null,
|
||||
category: "__nope__",
|
||||
note: `${N}x`,
|
||||
},
|
||||
adminUserId,
|
||||
);
|
||||
expect("error" in badCat && badCat.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HTTP route tests (Fastify inject)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -810,7 +1142,7 @@ describe("HTTP /api/admin/plan", () => {
|
||||
const body = res.json();
|
||||
expect(body.data.users).toBeDefined();
|
||||
expect(body.data.cells[adminUserId]).toBeDefined();
|
||||
expect(body.data.cells[adminUserId]["2097-06-01"].note).toBe(
|
||||
expect(body.data.cells[adminUserId]["2097-06-01"][0].note).toBe(
|
||||
`${N}grid test`,
|
||||
);
|
||||
});
|
||||
@@ -883,4 +1215,32 @@ describe("HTTP /api/admin/plan", () => {
|
||||
);
|
||||
expect(res.statusCode).toBe(201);
|
||||
});
|
||||
|
||||
it("POST /entries/bulk requires attendance.manage", async () => {
|
||||
const res = await authPost("/api/admin/plan/entries/bulk", noPermToken, {
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2095-06-01",
|
||||
date_to: "2095-06-01",
|
||||
include_weekends: true,
|
||||
category: "work",
|
||||
note: `${N}bulk-forbidden`,
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("POST /entries/bulk creates entries for an admin and returns a summary", async () => {
|
||||
const res = await authPost("/api/admin/plan/entries/bulk", adminToken, {
|
||||
user_ids: [adminUserId],
|
||||
date_from: "2095-06-05", // Sunday; weekends on → 1 day
|
||||
date_to: "2095-06-05",
|
||||
include_weekends: true,
|
||||
category: "work",
|
||||
note: `${N}bulk-http`,
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.created_days).toBe(1);
|
||||
expect(body.data.users).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -31,6 +31,7 @@ interface Project {
|
||||
export type PlanCellModalMode =
|
||||
| { kind: "closed" }
|
||||
| { kind: "create"; userId: number; date: string }
|
||||
| { kind: "create-override"; userId: number; date: string }
|
||||
| {
|
||||
kind: "edit-range";
|
||||
entryId: number;
|
||||
@@ -64,7 +65,8 @@ export type PlanCellModalMode =
|
||||
note: string;
|
||||
};
|
||||
}
|
||||
| { kind: "view"; userId: number; date: string; cell: ResolvedCell };
|
||||
| { kind: "view"; userId: number; date: string; cell: ResolvedCell }
|
||||
| { kind: "day"; userId: number; date: string; cells: ResolvedCell[] };
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
@@ -84,6 +86,16 @@ interface Props {
|
||||
date: string,
|
||||
) => Promise<void>;
|
||||
onSwitchToEditRange: (entryId: number, userId: number, date: string) => void;
|
||||
/** Open the create form for a brand-new record on (userId, date). The
|
||||
* `source` picks the layer the new record lands in: "entry" in normal mode,
|
||||
* "override" in exception mode (a day whose shown records are overrides). */
|
||||
onAddRecord: (
|
||||
userId: number,
|
||||
date: string,
|
||||
source: "entry" | "override",
|
||||
) => void;
|
||||
/** Open the right editor for one of the day's existing records. */
|
||||
onEditRecord: (cell: ResolvedCell, userId: number, date: string) => void;
|
||||
}
|
||||
|
||||
const TrashIcon = (
|
||||
@@ -112,6 +124,7 @@ export default function PlanCellModal(props: Props) {
|
||||
if (mode.kind === "view") return <ViewModal {...props} />;
|
||||
if (mode.kind === "day-in-range")
|
||||
return <DayInRangeModal {...props} mode={mode} />;
|
||||
if (mode.kind === "day") return <DayPanel {...props} mode={mode} />;
|
||||
return <EditForm {...props} />;
|
||||
}
|
||||
|
||||
@@ -131,21 +144,26 @@ function EditForm(props: Props) {
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
// Narrow mode to the kinds EditForm actually handles. The call site in
|
||||
// PlanCellModal only passes "create" | "edit-range" | "edit-override" but
|
||||
// the parameter type is the full union, so we narrow explicitly here.
|
||||
// PlanCellModal only passes "create" | "create-override" | "edit-range" |
|
||||
// "edit-override" but the parameter type is the full union, so we narrow
|
||||
// explicitly here.
|
||||
if (
|
||||
mode.kind !== "create" &&
|
||||
mode.kind !== "create-override" &&
|
||||
mode.kind !== "edit-range" &&
|
||||
mode.kind !== "edit-override"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isOverride = mode.kind === "edit-override";
|
||||
// An override is a single-day record — both editing one ("edit-override")
|
||||
// and creating one ("create-override") lock the date and hide the range UI.
|
||||
const isOverride =
|
||||
mode.kind === "edit-override" || mode.kind === "create-override";
|
||||
const activeCategories = props.categories.filter((c) => c.is_active);
|
||||
|
||||
const initial = (() => {
|
||||
if (mode.kind === "create") {
|
||||
if (mode.kind === "create" || mode.kind === "create-override") {
|
||||
return {
|
||||
date_from: mode.date,
|
||||
date_to: mode.date,
|
||||
@@ -190,9 +208,11 @@ function EditForm(props: Props) {
|
||||
const title =
|
||||
mode.kind === "create"
|
||||
? "Nový záznam plánu"
|
||||
: mode.kind === "edit-range"
|
||||
? "Upravit rozsah"
|
||||
: "Upravit přepsání dne";
|
||||
: mode.kind === "create-override"
|
||||
? "Nové přepsání dne"
|
||||
: mode.kind === "edit-range"
|
||||
? "Upravit rozsah"
|
||||
: "Upravit přepsání dne";
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setSubmitting(true);
|
||||
@@ -207,6 +227,17 @@ function EditForm(props: Props) {
|
||||
category,
|
||||
note,
|
||||
});
|
||||
} else if (mode.kind === "create-override") {
|
||||
// An override is a single day — lock it to mode.date regardless of
|
||||
// any local dateFrom/isRange state (the date field is disabled for
|
||||
// overrides, but be explicit).
|
||||
await onSaveOverride({
|
||||
user_id: mode.userId,
|
||||
shift_date: mode.date,
|
||||
project_id: projectId,
|
||||
category,
|
||||
note,
|
||||
});
|
||||
} else if (mode.kind === "edit-range") {
|
||||
await onUpdateEntry(mode.entryId, {
|
||||
date_from: dateFrom,
|
||||
@@ -249,6 +280,10 @@ function EditForm(props: Props) {
|
||||
const showRetiredCategory =
|
||||
category && !activeCategories.some((c) => c.key === category);
|
||||
|
||||
// Both create flows ("create" entry, "create-override") show "Vytvořit" and
|
||||
// have no Smazat button (there is no existing row to delete yet).
|
||||
const isCreate = mode.kind === "create" || mode.kind === "create-override";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
@@ -256,10 +291,10 @@ function EditForm(props: Props) {
|
||||
title={title}
|
||||
onClose={onClose}
|
||||
onSubmit={handleSubmit}
|
||||
submitText={mode.kind === "create" ? "Vytvořit" : "Uložit"}
|
||||
submitText={isCreate ? "Vytvořit" : "Uložit"}
|
||||
loading={submitting}
|
||||
>
|
||||
{mode.kind !== "create" && (
|
||||
{!isCreate && (
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
@@ -506,3 +541,117 @@ function ViewModal(props: Props) {
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const EditIcon = (
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
|
||||
<path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
function DayPanel(
|
||||
props: Props & { mode: Extract<PlanCellModalMode, { kind: "day" }> },
|
||||
) {
|
||||
const { mode, onClose, onAddRecord, onEditRecord, categories } = props;
|
||||
const catMap = Object.fromEntries(categories.map((x) => [x.key, x]));
|
||||
const atCap = mode.cells.length >= 3;
|
||||
const free = 3 - mode.cells.length;
|
||||
// A day is in "exception mode" when its shown records are overrides. Cells
|
||||
// are single-layer (all overrides OR all entries), so cells[0] is enough.
|
||||
// "+ Přidat záznam" must add to the layer that's showing — an override here,
|
||||
// otherwise resolveCell would hide a freshly-created entry behind the
|
||||
// existing override after refetch.
|
||||
const isOverrideMode = mode.cells[0]?.source === "override";
|
||||
return (
|
||||
<Modal
|
||||
isOpen
|
||||
title={`Plán — ${formatDate(mode.date)}`}
|
||||
onClose={onClose}
|
||||
onSubmit={onClose}
|
||||
submitText="Zavřít"
|
||||
hideCancel
|
||||
>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.25, mb: 2 }}>
|
||||
{mode.cells.map((c, i) => {
|
||||
const color =
|
||||
catMap[c.category]?.color || "var(--mui-palette-divider)";
|
||||
const projectLabel = cellProjectLabel(c);
|
||||
return (
|
||||
<Card
|
||||
key={
|
||||
c.entryId != null
|
||||
? c.entryId
|
||||
: c.overrideId != null
|
||||
? `o${c.overrideId}`
|
||||
: i
|
||||
}
|
||||
variant="outlined"
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 4,
|
||||
alignSelf: "stretch",
|
||||
minHeight: 28,
|
||||
borderRadius: 2,
|
||||
bgcolor: color,
|
||||
}}
|
||||
/>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography sx={{ fontWeight: 600, fontSize: "0.85rem" }}>
|
||||
{planCategoryLabel(c.category, catMap)}
|
||||
{projectLabel ? ` · ${projectLabel}` : ""}
|
||||
</Typography>
|
||||
{c.note && (
|
||||
<Typography variant="body2" color="text.secondary" noWrap>
|
||||
{c.note}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
startIcon={EditIcon}
|
||||
onClick={() => onEditRecord(c, mode.userId, mode.date)}
|
||||
>
|
||||
Upravit
|
||||
</Button>
|
||||
</Box>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
disabled={atCap}
|
||||
onClick={() =>
|
||||
onAddRecord(
|
||||
mode.userId,
|
||||
mode.date,
|
||||
isOverrideMode ? "override" : "entry",
|
||||
)
|
||||
}
|
||||
>
|
||||
+ Přidat záznam
|
||||
</Button>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{atCap
|
||||
? "Maximum 3 záznamy na den"
|
||||
: `${free} ${free === 1 ? "volné místo" : "volná místa"}`}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -290,6 +290,17 @@ const PlanGridRoot = styled(Box)(({ theme }) => ({
|
||||
},
|
||||
"& .plan-cell--pulse": { animation: "plan-cell-pulse 600ms ease-out" },
|
||||
|
||||
"& .plan-cell-record": {
|
||||
display: "block",
|
||||
width: "100%",
|
||||
minWidth: 0,
|
||||
},
|
||||
"& .plan-cell-record + .plan-cell-record": {
|
||||
marginTop: 5,
|
||||
paddingTop: 5,
|
||||
borderTop: `1px dashed ${theme.vars!.palette.divider}`,
|
||||
},
|
||||
|
||||
// Chips inside a cell
|
||||
"& .plan-chip-block": {
|
||||
display: "flex",
|
||||
@@ -373,11 +384,7 @@ interface Props {
|
||||
// the value so back-to-back mutations on the same cell re-trigger
|
||||
// the animation (React needs a new key to re-mount the class).
|
||||
pulseKey?: { userId: number; date: string; nonce: number } | null;
|
||||
onCellClick: (
|
||||
userId: number,
|
||||
date: string,
|
||||
cell: ResolvedCell | null,
|
||||
) => void;
|
||||
onCellClick: (userId: number, date: string, cells: ResolvedCell[]) => void;
|
||||
}
|
||||
|
||||
// Full Czech weekday names, indexed by Date.getUTCDay() (0 = Sunday).
|
||||
@@ -529,7 +536,8 @@ export default function PlanGrid({
|
||||
</span>
|
||||
</td>
|
||||
{users.map((u) => {
|
||||
const cell = data.cells[u.id]?.[date] ?? null;
|
||||
const cellArr = data.cells[u.id]?.[date] ?? [];
|
||||
const cell = cellArr[0] ?? null;
|
||||
const past = isPastDate(date, today);
|
||||
// Past-day cells are read-only in the UI: an empty past
|
||||
// cell is non-interactive (no create modal, no "+" hint),
|
||||
@@ -571,29 +579,50 @@ export default function PlanGrid({
|
||||
} as CSSProperties)
|
||||
: undefined
|
||||
}
|
||||
onClick={() => onCellClick(u.id, date, cell)}
|
||||
onClick={() => onCellClick(u.id, date, cellArr)}
|
||||
aria-label={
|
||||
cell
|
||||
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
|
||||
? cellArr.length === 1
|
||||
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
|
||||
: `${u.full_name}, ${date}, ${cellArr.length} záznamy`
|
||||
: isLocked
|
||||
? `${u.full_name}, ${date}, ${past ? "uplynulý den" : "prázdné"} — bez záznamu`
|
||||
: `${u.full_name}, ${date}, prázdné — přidat záznam`
|
||||
}
|
||||
>
|
||||
<PlanRangeChips
|
||||
cell={cell}
|
||||
project={
|
||||
cell?.project_id
|
||||
? (projects.find(
|
||||
(p) => p.id === cell.project_id,
|
||||
) ?? null)
|
||||
: null
|
||||
}
|
||||
readonly={!canEdit}
|
||||
categoryLabel={
|
||||
cell ? planCategoryLabel(cell.category, catMap) : ""
|
||||
}
|
||||
/>
|
||||
{cellArr.map((c, i) => (
|
||||
<Box
|
||||
key={
|
||||
c.entryId != null
|
||||
? c.entryId
|
||||
: c.overrideId != null
|
||||
? `o${c.overrideId}`
|
||||
: i
|
||||
}
|
||||
className="plan-cell-record"
|
||||
style={
|
||||
{
|
||||
"--cat-color": catMap[c.category]?.color,
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
<PlanRangeChips
|
||||
cell={c}
|
||||
project={
|
||||
c.project_id
|
||||
? (projects.find(
|
||||
(p) => p.id === c.project_id,
|
||||
) ?? null)
|
||||
: null
|
||||
}
|
||||
readonly={!canEdit}
|
||||
categoryLabel={planCategoryLabel(
|
||||
c.category,
|
||||
catMap,
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
))}
|
||||
</button>
|
||||
</td>
|
||||
);
|
||||
|
||||
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"
|
||||
|
||||
@@ -3,7 +3,7 @@ import Typography from "@mui/material/Typography";
|
||||
import { Card } from "../../ui";
|
||||
import { formatDate } from "../../utils/formatters";
|
||||
|
||||
/** The logged-in user's resolved work plan for today (see GET /api/admin/dashboard). */
|
||||
/** One resolved plan record for today (see GET /api/admin/dashboard). */
|
||||
export interface TodayPlan {
|
||||
shift_date: string;
|
||||
category: string;
|
||||
@@ -23,15 +23,64 @@ function projectLabel(p: TodayPlan): string {
|
||||
return parts.length > 0 ? parts.join(" — ") : "Bez projektu";
|
||||
}
|
||||
|
||||
/**
|
||||
* "Vaše dnešní zařazení" — shows the logged-in user's work-plan entry for today
|
||||
* (category + project/site + note, with a range badge when the day is part of a
|
||||
* multi-day range). `plan === null` = the user has plan access but nothing is
|
||||
* scheduled today (muted empty state). Rendered near the clock-in on the
|
||||
* dashboard; the caller gates it on the plan permission.
|
||||
*/
|
||||
export default function DashTodayPlan({ plan }: { plan: TodayPlan | null }) {
|
||||
const color = plan?.category_color || "var(--mui-palette-primary-main)";
|
||||
function PlanRow({ plan }: { plan: TodayPlan }) {
|
||||
const color = plan.category_color || "var(--mui-palette-primary-main)";
|
||||
return (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
<Box
|
||||
sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: 0.75,
|
||||
px: 1.25,
|
||||
py: 0.5,
|
||||
borderRadius: 999,
|
||||
border: 1,
|
||||
borderColor: "divider",
|
||||
bgcolor: `color-mix(in srgb, ${color} 12%, transparent)`,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: "50%",
|
||||
bgcolor: color,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<Typography
|
||||
component="span"
|
||||
sx={{ fontWeight: 700, fontSize: "0.8rem" }}
|
||||
>
|
||||
{plan.category_label}
|
||||
</Typography>
|
||||
</Box>
|
||||
{plan.rangeFrom && plan.rangeTo && plan.rangeFrom !== plan.rangeTo && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
součást rozsahu {formatDate(plan.rangeFrom)} –{" "}
|
||||
{formatDate(plan.rangeTo)}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<Typography variant="h6" sx={{ lineHeight: 1.25 }}>
|
||||
{projectLabel(plan)}
|
||||
</Typography>
|
||||
{plan.note && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{plan.note}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Vaše dnešní zařazení" — the logged-in user's resolved plan record(s) for
|
||||
* today (up to 3). Empty array = nothing scheduled. */
|
||||
export default function DashTodayPlan({ plans }: { plans: TodayPlan[] }) {
|
||||
return (
|
||||
<Card sx={{ mb: 3 }}>
|
||||
<Typography
|
||||
@@ -40,65 +89,20 @@ export default function DashTodayPlan({ plan }: { plan: TodayPlan | null }) {
|
||||
>
|
||||
Vaše dnešní zařazení
|
||||
</Typography>
|
||||
|
||||
{plan ? (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
{plans.length > 0 ? (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
{plans.map((p, i) => (
|
||||
<Box
|
||||
key={i}
|
||||
sx={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: 0.75,
|
||||
px: 1.25,
|
||||
py: 0.5,
|
||||
borderRadius: 999,
|
||||
border: 1,
|
||||
pt: i === 0 ? 0 : 2,
|
||||
borderTop: i === 0 ? 0 : 1,
|
||||
borderColor: "divider",
|
||||
bgcolor: `color-mix(in srgb, ${color} 12%, transparent)`,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: "50%",
|
||||
bgcolor: color,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<Typography
|
||||
component="span"
|
||||
sx={{ fontWeight: 700, fontSize: "0.8rem" }}
|
||||
>
|
||||
{plan.category_label}
|
||||
</Typography>
|
||||
<PlanRow plan={p} />
|
||||
</Box>
|
||||
{plan.rangeFrom &&
|
||||
plan.rangeTo &&
|
||||
plan.rangeFrom !== plan.rangeTo && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
součást rozsahu {formatDate(plan.rangeFrom)} –{" "}
|
||||
{formatDate(plan.rangeTo)}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Typography variant="h6" sx={{ lineHeight: 1.25 }}>
|
||||
{projectLabel(plan)}
|
||||
</Typography>
|
||||
|
||||
{plan.note && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{plan.note}
|
||||
</Typography>
|
||||
)}
|
||||
))}
|
||||
</Box>
|
||||
) : (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
|
||||
@@ -12,9 +12,11 @@ export type ViewMode = "week" | "month";
|
||||
export type ModalMode =
|
||||
| { kind: "closed" }
|
||||
| { kind: "create"; userId: number; date: string }
|
||||
| { kind: "create-override"; userId: number; date: string }
|
||||
| { kind: "edit-range"; entryId: number; userId: number; date: string }
|
||||
| { kind: "edit-override"; overrideId: number; userId: number; date: string }
|
||||
| { kind: "day-in-range"; userId: number; date: string; entryId: number }
|
||||
| { kind: "day"; userId: number; date: string }
|
||||
| { kind: "view"; userId: number; date: string };
|
||||
|
||||
function isoDate(d: Date): string {
|
||||
@@ -150,16 +152,16 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
key: readonly unknown[],
|
||||
userId: number,
|
||||
dates: string[],
|
||||
mutator: (prev: ResolvedCell | null) => ResolvedCell | null,
|
||||
): Record<string, ResolvedCell | null> | null {
|
||||
mutator: (prev: ResolvedCell[]) => ResolvedCell[],
|
||||
): Record<string, ResolvedCell[]> | null {
|
||||
const prev = snapshotGrid(key);
|
||||
if (!prev) return null;
|
||||
const userPrev = prev.cells[userId] ?? {};
|
||||
const rolled: Record<string, ResolvedCell | null> = {};
|
||||
const userNext: Record<string, ResolvedCell | null> = { ...userPrev };
|
||||
const rolled: Record<string, ResolvedCell[]> = {};
|
||||
const userNext: Record<string, ResolvedCell[]> = { ...userPrev };
|
||||
for (const date of dates) {
|
||||
rolled[date] = userPrev[date] ?? null;
|
||||
userNext[date] = mutator(rolled[date]);
|
||||
rolled[date] = userPrev[date] ?? [];
|
||||
userNext[date] = mutator(rolled[date]).slice(0, 3);
|
||||
}
|
||||
qc.setQueryData(key, {
|
||||
...prev,
|
||||
@@ -244,7 +246,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// the ResolvedCell mirrors the request body.
|
||||
const days = eachDay(body.date_from, body.date_to);
|
||||
const id = data && typeof data.id === "number" ? data.id : null;
|
||||
const rolled = patchCells(currentGridKey, body.user_id, days, () =>
|
||||
const rolled = patchCells(currentGridKey, body.user_id, days, (prev) => [
|
||||
makeEntryCell({
|
||||
userId: body.user_id,
|
||||
date: days[0],
|
||||
@@ -255,7 +257,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
rangeTo: body.date_to,
|
||||
entryId: id,
|
||||
}),
|
||||
);
|
||||
...prev,
|
||||
]);
|
||||
// Stash the rollback on the mutation object so PlanWork can call
|
||||
// it from onError.
|
||||
(createEntry as any)._rolled = rolled;
|
||||
@@ -294,8 +297,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
let ownerUserId: number | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const cell of Object.values(byDate)) {
|
||||
if (cell && cell.entryId === id) {
|
||||
for (const cells of Object.values(byDate)) {
|
||||
if (cells.some((c) => c.entryId === id)) {
|
||||
ownerUserId = Number(uidStr);
|
||||
break;
|
||||
}
|
||||
@@ -304,20 +307,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
}
|
||||
}
|
||||
if (ownerUserId !== null) {
|
||||
const rolled = patchCells(currentGridKey, ownerUserId, days, (prev) =>
|
||||
makeEntryCell({
|
||||
userId: ownerUserId!,
|
||||
date: days[0],
|
||||
projectId:
|
||||
body.project_id === undefined
|
||||
? (prev?.project_id ?? null)
|
||||
: body.project_id,
|
||||
category: body.category ?? prev?.category ?? "work",
|
||||
note: body.note ?? prev?.note ?? "",
|
||||
rangeFrom: body.date_from,
|
||||
rangeTo: body.date_to,
|
||||
entryId: id,
|
||||
}),
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
ownerUserId,
|
||||
days,
|
||||
(prev) => {
|
||||
const existing = prev.find((c) => c.entryId === id) ?? null;
|
||||
const updated = makeEntryCell({
|
||||
userId: ownerUserId!,
|
||||
date: days[0],
|
||||
projectId:
|
||||
body.project_id === undefined
|
||||
? (existing?.project_id ?? null)
|
||||
: body.project_id,
|
||||
category: body.category ?? existing?.category ?? "work",
|
||||
note: body.note ?? existing?.note ?? "",
|
||||
rangeFrom: body.date_from,
|
||||
rangeTo: body.date_to,
|
||||
entryId: id,
|
||||
});
|
||||
return [updated, ...prev.filter((c) => c.entryId !== id)];
|
||||
},
|
||||
);
|
||||
(updateEntry as any)._rolled = rolled;
|
||||
}
|
||||
@@ -338,24 +348,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [, cell] of Object.entries(byDate)) {
|
||||
if (
|
||||
cell &&
|
||||
cell.entryId === vars.id &&
|
||||
cell.rangeFrom &&
|
||||
cell.rangeTo
|
||||
) {
|
||||
const days = eachDay(cell.rangeFrom, cell.rangeTo);
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
days,
|
||||
() => null,
|
||||
);
|
||||
(deleteEntry as any)._rolled = rolled;
|
||||
let range: { from: string; to: string } | null = null;
|
||||
for (const cells of Object.values(byDate)) {
|
||||
const hit = cells.find(
|
||||
(c) => c.entryId === vars.id && c.rangeFrom && c.rangeTo,
|
||||
);
|
||||
if (hit) {
|
||||
range = { from: hit.rangeFrom!, to: hit.rangeTo! };
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (range) {
|
||||
const days = eachDay(range.from, range.to);
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
days,
|
||||
(prev) => prev.filter((c) => c.entryId !== vars.id),
|
||||
);
|
||||
(deleteEntry as any)._rolled = rolled;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
invalidate();
|
||||
@@ -375,7 +388,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
currentGridKey,
|
||||
vars.user_id,
|
||||
[vars.shift_date],
|
||||
() =>
|
||||
(prev) => [
|
||||
makeOverrideCell({
|
||||
userId: vars.user_id,
|
||||
date: vars.shift_date,
|
||||
@@ -384,6 +397,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
note: vars.note,
|
||||
overrideId: id,
|
||||
}),
|
||||
...prev,
|
||||
],
|
||||
);
|
||||
(createOverride as any)._rolled = rolled;
|
||||
invalidate();
|
||||
@@ -411,21 +426,30 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === vars.id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
if (cells.some((c) => c.overrideId === vars.id)) {
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
[date],
|
||||
(prev) =>
|
||||
makeOverrideCell({
|
||||
(prev) => {
|
||||
const existing =
|
||||
prev.find((c) => c.overrideId === vars.id) ?? null;
|
||||
const updated = makeOverrideCell({
|
||||
userId: Number(uidStr),
|
||||
date,
|
||||
projectId: vars.body.project_id ?? prev?.project_id ?? null,
|
||||
category: vars.body.category ?? prev?.category ?? "work",
|
||||
note: vars.body.note ?? prev?.note ?? "",
|
||||
projectId:
|
||||
vars.body.project_id ?? existing?.project_id ?? null,
|
||||
category:
|
||||
vars.body.category ?? existing?.category ?? "work",
|
||||
note: vars.body.note ?? existing?.note ?? "",
|
||||
overrideId: vars.id,
|
||||
}),
|
||||
});
|
||||
return [
|
||||
updated,
|
||||
...prev.filter((c) => c.overrideId !== vars.id),
|
||||
];
|
||||
},
|
||||
);
|
||||
(updateOverride as any)._rolled = rolled;
|
||||
break;
|
||||
@@ -446,13 +470,13 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === vars.id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
if (cells.some((c) => c.overrideId === vars.id)) {
|
||||
const rolled = patchCells(
|
||||
currentGridKey,
|
||||
Number(uidStr),
|
||||
[date],
|
||||
() => null,
|
||||
(prev) => prev.filter((c) => c.overrideId !== vars.id),
|
||||
);
|
||||
(deleteOverride as any)._rolled = rolled;
|
||||
break;
|
||||
@@ -464,6 +488,20 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
},
|
||||
});
|
||||
|
||||
const bulkCreate = useMutation({
|
||||
mutationFn: (body: any) =>
|
||||
apiCall("/api/admin/plan/entries/bulk", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
onSuccess: () => {
|
||||
// No optimistic patch — bulk can touch many cells; just invalidate and
|
||||
// let the grid refetch the authoritative state.
|
||||
invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
// Roll back an optimistic patch on mutation error. Called from
|
||||
// PlanWork's mutation wrappers via `rollbackMutation(mutation, key)`.
|
||||
// `mutation` is a TanStack mutation result with a `_rolled` snapshot stashed
|
||||
@@ -472,15 +510,15 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
// directly without the "weak type" mismatch a `{ _rolled? }` param causes.
|
||||
function rollbackMutation(mutation: unknown, userId: number) {
|
||||
const stash = mutation as {
|
||||
_rolled?: Record<string, ResolvedCell | null> | null;
|
||||
_rolled?: Record<string, ResolvedCell[]> | null;
|
||||
};
|
||||
if (!stash._rolled) return;
|
||||
const prev = qc.getQueryData<GridData>(currentGridKey as any);
|
||||
if (!prev) return;
|
||||
const userPrev = prev.cells[userId] ?? {};
|
||||
const userNext = { ...userPrev };
|
||||
for (const [date, cell] of Object.entries(stash._rolled)) {
|
||||
userNext[date] = cell;
|
||||
for (const [date, cells] of Object.entries(stash._rolled)) {
|
||||
userNext[date] = cells;
|
||||
}
|
||||
qc.setQueryData(currentGridKey, {
|
||||
...prev,
|
||||
@@ -510,6 +548,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
createOverride,
|
||||
updateOverride,
|
||||
deleteOverride,
|
||||
bulkCreate,
|
||||
invalidate,
|
||||
// Exposed so PlanWork can roll back an optimistic patch when a
|
||||
// mutation throws. Pass the failed mutation and the userId it
|
||||
@@ -518,10 +557,18 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||
};
|
||||
}
|
||||
|
||||
export function getCells(
|
||||
grid: GridData | undefined,
|
||||
userId: number,
|
||||
date: string,
|
||||
): ResolvedCell[] {
|
||||
return grid?.cells?.[userId]?.[date] ?? [];
|
||||
}
|
||||
|
||||
export function getCell(
|
||||
grid: GridData | undefined,
|
||||
userId: number,
|
||||
date: string,
|
||||
): ResolvedCell | null {
|
||||
return grid?.cells?.[userId]?.[date] ?? null;
|
||||
return getCells(grid, userId, date)[0] ?? null;
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
@@ -81,7 +81,7 @@ export interface GridData {
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
users: PlanUser[];
|
||||
cells: Record<number, Record<string, ResolvedCell | null>>;
|
||||
cells: Record<number, Record<string, ResolvedCell[]>>;
|
||||
}
|
||||
|
||||
export const planKeys = {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -72,7 +73,7 @@ interface DashData {
|
||||
pending_orders?: number;
|
||||
unpaid_invoices?: number;
|
||||
pending_leave_requests?: number;
|
||||
today_plan?: TodayPlan | null;
|
||||
today_plan?: TodayPlan[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -325,7 +329,7 @@ export default function Dashboard() {
|
||||
{!dashLoading &&
|
||||
(hasPermission("attendance.record") ||
|
||||
hasPermission("attendance.manage")) && (
|
||||
<DashTodayPlan plan={dashData?.today_plan ?? null} />
|
||||
<DashTodayPlan plans={dashData?.today_plan ?? []} />
|
||||
)}
|
||||
|
||||
{/* Quick actions */}
|
||||
|
||||
@@ -8,16 +8,22 @@ import { useAlert } from "../context/AlertContext";
|
||||
import {
|
||||
usePlanWork,
|
||||
getCell,
|
||||
getCells,
|
||||
type ModalMode as HookModalMode,
|
||||
} from "../hooks/usePlanWork";
|
||||
import type { PlanCellModalMode } from "../components/PlanCellModal";
|
||||
import PlanGrid from "../components/PlanGrid";
|
||||
import PlanCellModal from "../components/PlanCellModal";
|
||||
import PlanCategoriesModal from "../components/PlanCategoriesModal";
|
||||
import BulkPlanModal, { type BulkPlanForm } from "../components/BulkPlanModal";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { Button, Alert, LoadingState, PageEnter } from "../ui";
|
||||
import { projectListOptions, type Project } from "../lib/queries/projects";
|
||||
import { planCategoriesOptions, type PlanCategory } from "../lib/queries/plan";
|
||||
import {
|
||||
planCategoriesOptions,
|
||||
type PlanCategory,
|
||||
type ResolvedCell,
|
||||
} from "../lib/queries/plan";
|
||||
// plan.css is imported once globally in AdminApp.tsx — no per-page re-import.
|
||||
|
||||
const MONTH_NAMES = [
|
||||
@@ -123,6 +129,7 @@ export default function PlanWork() {
|
||||
createOverride,
|
||||
updateOverride,
|
||||
deleteOverride,
|
||||
bulkCreate,
|
||||
rollbackMutation,
|
||||
} = usePlanWork({ canEdit });
|
||||
|
||||
@@ -135,6 +142,84 @@ export default function PlanWork() {
|
||||
|
||||
const [catModalOpen, setCatModalOpen] = useState(false);
|
||||
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
const [bulkSubmitting, setBulkSubmitting] = useState(false);
|
||||
const [bulkForm, setBulkForm] = useState<BulkPlanForm>(() => {
|
||||
const today = todayIsoLocal();
|
||||
return {
|
||||
date_from: today,
|
||||
date_to: today,
|
||||
is_range: false,
|
||||
user_ids: [],
|
||||
include_weekends: false,
|
||||
project_id: "",
|
||||
category: "work",
|
||||
note: "",
|
||||
};
|
||||
});
|
||||
|
||||
const planUsers = useMemo(() => grid?.users ?? [], [grid]);
|
||||
|
||||
const toggleBulkUser = useCallback((userId: number) => {
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
user_ids: prev.user_ids.includes(String(userId))
|
||||
? prev.user_ids.filter((u) => u !== String(userId))
|
||||
: [...prev.user_ids, String(userId)],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const toggleAllBulkUsers = useCallback(() => {
|
||||
const allIds = (grid?.users ?? []).map((u) => String(u.id));
|
||||
if (allIds.length === 0) return; // grid not yet loaded — no-op
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
user_ids: prev.user_ids.length === allIds.length ? [] : allIds,
|
||||
}));
|
||||
}, [grid]);
|
||||
|
||||
const submitBulk = useCallback(async () => {
|
||||
if (bulkForm.user_ids.length === 0) return;
|
||||
setBulkSubmitting(true);
|
||||
try {
|
||||
const data: any = await bulkCreate.mutateAsync({
|
||||
user_ids: bulkForm.user_ids.map(Number),
|
||||
date_from: bulkForm.date_from,
|
||||
date_to: bulkForm.is_range ? bulkForm.date_to : bulkForm.date_from,
|
||||
include_weekends: bulkForm.include_weekends,
|
||||
project_id: bulkForm.project_id ? Number(bulkForm.project_id) : null,
|
||||
category: bulkForm.category,
|
||||
note: bulkForm.note,
|
||||
});
|
||||
// apiCall returns the full envelope { success, data, message };
|
||||
// the summary counts are under .data
|
||||
const summary = data?.data ?? data;
|
||||
const skipped =
|
||||
summary?.skipped_days > 0
|
||||
? ` ${summary.skipped_days} dní přeskočeno (limit 3 na den).`
|
||||
: "";
|
||||
alert.success(
|
||||
`Vytvořeno ${summary?.created_days ?? 0} záznamů pro ${summary?.users ?? 0} zaměstnanců.${skipped}`,
|
||||
);
|
||||
setBulkOpen(false);
|
||||
// Reset the volatile parts so reopening starts clean (project /
|
||||
// category / weekends stay sticky — users often repeat those).
|
||||
const today = todayIsoLocal();
|
||||
setBulkForm((prev) => ({
|
||||
...prev,
|
||||
date_from: today,
|
||||
date_to: today,
|
||||
is_range: false,
|
||||
user_ids: [],
|
||||
note: "",
|
||||
}));
|
||||
} catch (e) {
|
||||
alert.error(e instanceof Error ? e.message : "Chyba při ukládání");
|
||||
} finally {
|
||||
setBulkSubmitting(false);
|
||||
}
|
||||
}, [bulkForm, bulkCreate, alert]);
|
||||
|
||||
// `lastMutated` is the (userId, date) of the most recent successful
|
||||
// mutation. We pass it to PlanGrid as `pulseKey`; the matching cell
|
||||
// gets a one-shot CSS pulse animation. We clear it after 700ms (the
|
||||
@@ -193,84 +278,86 @@ export default function PlanWork() {
|
||||
// Null when the modal is closed or in a "create" state with no source cell.
|
||||
const [modalCell, setModalCell] = useState<ReturnType<typeof getCell>>(null);
|
||||
|
||||
// Open the create form for a brand-new record. `source` picks the layer:
|
||||
// "entry" (default) opens the normal create form; "override" opens the
|
||||
// single-day create-override form. The day panel passes "override" when the
|
||||
// day is in exception mode so the new record lands in the same layer that's
|
||||
// showing (otherwise resolveCell would hide a new entry behind the override).
|
||||
const openCreate = useCallback(
|
||||
(userId: number, date: string) => {
|
||||
(userId: number, date: string, source: "entry" | "override" = "entry") => {
|
||||
setModalCell(null);
|
||||
setHookModal({ kind: "create", userId, date });
|
||||
if (source === "override") {
|
||||
setHookModal({ kind: "create-override", userId, date });
|
||||
} else {
|
||||
setHookModal({ kind: "create", userId, date });
|
||||
}
|
||||
},
|
||||
[setHookModal],
|
||||
);
|
||||
|
||||
const openCell = useCallback(
|
||||
(userId: number, date: string) => {
|
||||
const cell = getCell(grid, userId, date);
|
||||
(userId: number, date: string, cells: ResolvedCell[]) => {
|
||||
const primary = cells[0] ?? null;
|
||||
// Past-date guard: the server rejects create/edit on past dates with
|
||||
// a 403 (see assertNotPastDate in plan.service.ts). To keep the user
|
||||
// out of the "click → modal opens → error toast" state, route any
|
||||
// past-day click to view mode (or to no-op if there's no record).
|
||||
if (isPastDate(date, todayIsoLocal())) {
|
||||
if (!cell) {
|
||||
// Empty past cell — nothing to show or edit.
|
||||
return;
|
||||
}
|
||||
setModalCell(cell);
|
||||
if (!primary) return;
|
||||
setModalCell(primary);
|
||||
setHookModal({ kind: "view", userId, date });
|
||||
return;
|
||||
}
|
||||
if (!cell) {
|
||||
// Empty cell — open the create modal if the user can edit, otherwise
|
||||
// there's nothing to view.
|
||||
if (cells.length === 0) {
|
||||
if (canEdit) openCreate(userId, date);
|
||||
return;
|
||||
}
|
||||
if (!canEdit) {
|
||||
setModalCell(primary);
|
||||
setHookModal({ kind: "view", userId, date });
|
||||
return;
|
||||
}
|
||||
setHookModal({ kind: "day", userId, date });
|
||||
},
|
||||
[canEdit, openCreate, setHookModal],
|
||||
);
|
||||
|
||||
// Open the correct editor for one record from the day panel. This is the
|
||||
// per-record version of the old openCell branch logic: a multi-day entry
|
||||
// routes through the day-in-range chooser; a single-day entry → edit-range;
|
||||
// an override → edit-override.
|
||||
const editRecord = useCallback(
|
||||
(cell: ReturnType<typeof getCell>, userId: number, date: string) => {
|
||||
if (!cell) return;
|
||||
setModalCell(cell);
|
||||
if (cell.source === "entry" && cell.entryId !== null) {
|
||||
if (canEdit) {
|
||||
// A multi-day entry clicked on a single day → "day-in-range" so the
|
||||
// user can decide between editing the range or creating a one-day
|
||||
// override.
|
||||
if (
|
||||
cell.rangeFrom &&
|
||||
cell.rangeTo &&
|
||||
cell.rangeFrom !== cell.rangeTo
|
||||
) {
|
||||
setHookModal({
|
||||
kind: "day-in-range",
|
||||
entryId: cell.entryId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (cell.rangeFrom && cell.rangeTo && cell.rangeFrom !== cell.rangeTo) {
|
||||
setHookModal({
|
||||
kind: "day-in-range",
|
||||
entryId: cell.entryId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
} else {
|
||||
setHookModal({
|
||||
kind: "edit-range",
|
||||
entryId: cell.entryId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Read-only view
|
||||
setHookModal({ kind: "view", userId, date });
|
||||
return;
|
||||
}
|
||||
if (cell.source === "override" && cell.overrideId !== null) {
|
||||
if (canEdit) {
|
||||
setHookModal({
|
||||
kind: "edit-override",
|
||||
overrideId: cell.overrideId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
} else {
|
||||
setHookModal({ kind: "view", userId, date });
|
||||
}
|
||||
return;
|
||||
setHookModal({
|
||||
kind: "edit-override",
|
||||
overrideId: cell.overrideId,
|
||||
userId,
|
||||
date,
|
||||
});
|
||||
}
|
||||
// No source — treat as empty
|
||||
if (canEdit) openCreate(userId, date);
|
||||
},
|
||||
[grid, canEdit, openCreate, setHookModal],
|
||||
[setHookModal],
|
||||
);
|
||||
|
||||
const closeModal = useCallback(() => {
|
||||
@@ -280,11 +367,14 @@ export default function PlanWork() {
|
||||
|
||||
// Switch the modal from "day-in-range" to "edit-range" mode, keeping the
|
||||
// same cell context so the EditForm opens with the range's values.
|
||||
// Uses `modalCell` — the record the user actually clicked in the day panel
|
||||
// (captured by editRecord) — NOT getCell (which returns the PRIMARY record).
|
||||
// On a day with 2+ records these differ; using the primary would edit the
|
||||
// wrong range. modalCell is already set to the clicked record at this point
|
||||
// (editRecord → day-in-range → here).
|
||||
const switchToEditRange = useCallback(
|
||||
(entryId: number, userId: number, date: string) => {
|
||||
const cell = getCell(grid, userId, date);
|
||||
if (!cell) return;
|
||||
setModalCell(cell);
|
||||
if (!modalCell) return;
|
||||
setHookModal({
|
||||
kind: "edit-range",
|
||||
entryId,
|
||||
@@ -292,7 +382,7 @@ export default function PlanWork() {
|
||||
date,
|
||||
});
|
||||
},
|
||||
[grid, setHookModal],
|
||||
[modalCell, setHookModal],
|
||||
);
|
||||
|
||||
// --- Mutation wrappers -----------------------------------------------------
|
||||
@@ -327,8 +417,9 @@ export default function PlanWork() {
|
||||
let firstDate: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.entryId === id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.entryId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
firstDate = body.date_from ?? date;
|
||||
break;
|
||||
@@ -357,10 +448,11 @@ export default function PlanWork() {
|
||||
let firstDate: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [date, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.entryId === id) {
|
||||
for (const [date, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.entryId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
firstDate = cell.rangeFrom ?? date;
|
||||
firstDate = hit.rangeFrom ?? date;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -402,8 +494,9 @@ export default function PlanWork() {
|
||||
let date: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [d, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === id) {
|
||||
for (const [d, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.overrideId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
date = d;
|
||||
break;
|
||||
@@ -431,8 +524,9 @@ export default function PlanWork() {
|
||||
let date: string | null = null;
|
||||
if (grid) {
|
||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||
for (const [d, cell] of Object.entries(byDate)) {
|
||||
if (cell && cell.overrideId === id) {
|
||||
for (const [d, cells] of Object.entries(byDate)) {
|
||||
const hit = cells.find((c) => c.overrideId === id);
|
||||
if (hit) {
|
||||
userId = Number(uidStr);
|
||||
date = d;
|
||||
break;
|
||||
@@ -455,11 +549,14 @@ export default function PlanWork() {
|
||||
);
|
||||
|
||||
// "Create override from range" — turn a multi-day entry into a one-day
|
||||
// override for the clicked date. We look up the cell's source entry and
|
||||
// create a new override mirroring its fields, locked to a single date.
|
||||
// override for the clicked date. We mirror the CLICKED record's fields
|
||||
// (modalCell, captured by editRecord) — NOT getCell, which returns the
|
||||
// PRIMARY record. On a day with 2+ records the clicked entry can differ
|
||||
// from the primary; carving from the primary would copy the wrong
|
||||
// project/category/note into the override.
|
||||
const createOverrideFromRange = useCallback(
|
||||
async (entryId: number, userId: number, date: string) => {
|
||||
const cell = getCell(grid, userId, date);
|
||||
const cell = modalCell;
|
||||
if (!cell) {
|
||||
alert.error("Nepodařilo se najít zdrojový záznam");
|
||||
return;
|
||||
@@ -483,7 +580,7 @@ export default function PlanWork() {
|
||||
// symmetry with the modal contract.
|
||||
void entryId;
|
||||
},
|
||||
[grid, createOverride, alert, firePulse, rollbackMutation],
|
||||
[modalCell, createOverride, alert, firePulse, rollbackMutation],
|
||||
);
|
||||
|
||||
// --- Modal key for remount-on-mode-change ----------------------------------
|
||||
@@ -504,6 +601,9 @@ export default function PlanWork() {
|
||||
const modalMode: PlanCellModalMode = useMemo(() => {
|
||||
if (hookModal.kind === "closed") return { kind: "closed" };
|
||||
if (hookModal.kind === "create") return hookModal;
|
||||
// create-override carries the same userId/date payload as create and needs
|
||||
// no merged cell/range — pass it straight through (EditForm handles it).
|
||||
if (hookModal.kind === "create-override") return hookModal;
|
||||
if (hookModal.kind === "view") {
|
||||
if (!modalCell) return { kind: "closed" };
|
||||
return {
|
||||
@@ -536,8 +636,16 @@ export default function PlanWork() {
|
||||
},
|
||||
} as PlanCellModalMode;
|
||||
}
|
||||
if (hookModal.kind === "day") {
|
||||
return {
|
||||
kind: "day",
|
||||
userId: hookModal.userId,
|
||||
date: hookModal.date,
|
||||
cells: getCells(grid, hookModal.userId, hookModal.date),
|
||||
};
|
||||
}
|
||||
return { kind: "closed" };
|
||||
}, [hookModal, modalCell]);
|
||||
}, [hookModal, modalCell, grid]);
|
||||
|
||||
if (!canEdit && !hasPermission("attendance.record")) {
|
||||
// Hard block for users who have neither manage nor record permission.
|
||||
@@ -645,6 +753,15 @@ export default function PlanWork() {
|
||||
Správa kategorií
|
||||
</Button>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="inherit"
|
||||
onClick={() => setBulkOpen(true)}
|
||||
>
|
||||
Hromadné přiřazení
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{gridLoading && <LoadingState />}
|
||||
@@ -691,12 +808,27 @@ export default function PlanWork() {
|
||||
onDeleteOverride={deleteOverrideFn}
|
||||
onCreateOverrideFromRange={createOverrideFromRange}
|
||||
onSwitchToEditRange={switchToEditRange}
|
||||
onAddRecord={openCreate}
|
||||
onEditRecord={editRecord}
|
||||
/>
|
||||
<PlanCategoriesModal
|
||||
isOpen={catModalOpen}
|
||||
onClose={() => setCatModalOpen(false)}
|
||||
categories={categories}
|
||||
/>
|
||||
<BulkPlanModal
|
||||
isOpen={bulkOpen}
|
||||
onClose={() => setBulkOpen(false)}
|
||||
form={bulkForm}
|
||||
setForm={setBulkForm}
|
||||
users={planUsers}
|
||||
projects={projects}
|
||||
categories={categories}
|
||||
onSubmit={submitBulk}
|
||||
submitting={bulkSubmitting}
|
||||
toggleUser={toggleBulkUser}
|
||||
toggleAllUsers={toggleAllBulkUsers}
|
||||
/>
|
||||
</PageEnter>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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={{
|
||||
|
||||
@@ -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 || "",
|
||||
|
||||
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 });
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -44,31 +44,32 @@ export default async function dashboardRoutes(
|
||||
}
|
||||
|
||||
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
|
||||
// resolveCell applies override-beats-range precedence; null = the user has
|
||||
// plan access but nothing is scheduled today. The category key is enriched
|
||||
// with its label + colour so the widget needs no extra query. todayStr uses
|
||||
// local (Europe/Prague) calendar date — the plan's @db.Date day.
|
||||
// resolveCell returns 0–3 records (override-beats-range layering); an empty
|
||||
// array means the user has plan access but nothing is scheduled today. Each
|
||||
// record's category key is enriched with its label + colour so the widget
|
||||
// needs no extra query. todayStr uses local (Europe/Prague) calendar date —
|
||||
// the plan's @db.Date day.
|
||||
if (has("attendance.record") || has("attendance.manage")) {
|
||||
const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
||||
const cell = await resolveCell(userId, todayStr);
|
||||
if (cell) {
|
||||
const cat = await prisma.plan_categories.findUnique({
|
||||
where: { key: cell.category },
|
||||
select: { label: true, color: true },
|
||||
});
|
||||
result.today_plan = {
|
||||
...cell,
|
||||
category_label: cat?.label ?? cell.category,
|
||||
category_color: cat?.color ?? null,
|
||||
};
|
||||
} else {
|
||||
result.today_plan = null;
|
||||
}
|
||||
const cells = await resolveCell(userId, todayStr);
|
||||
result.today_plan = await Promise.all(
|
||||
cells.map(async (cell) => {
|
||||
const cat = await prisma.plan_categories.findUnique({
|
||||
where: { key: cell.category },
|
||||
select: { label: true, color: true },
|
||||
});
|
||||
return {
|
||||
...cell,
|
||||
category_label: cat?.label ?? cell.category,
|
||||
category_color: cat?.color ?? null,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Attendance admin — only for attendance.manage
|
||||
if (has("attendance.manage")) {
|
||||
const [todayAttendance, onLeaveToday, usersCount] = await Promise.all([
|
||||
const [todayAttendance, onLeaveToday, activeUsers] = await Promise.all([
|
||||
prisma.attendance.findMany({
|
||||
where: {
|
||||
shift_date: { gte: todayStart, lt: todayEnd },
|
||||
@@ -88,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) {
|
||||
@@ -152,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,
|
||||
|
||||
@@ -310,7 +310,9 @@ export default async function ordersRoutes(
|
||||
const id = parseId(request.params.id, reply);
|
||||
if (id === null) return;
|
||||
|
||||
const result = await deleteOrder(id);
|
||||
const body = request.body as Record<string, unknown> | undefined;
|
||||
const deleteFiles = !!body?.delete_files;
|
||||
const result = await deleteOrder(id, deleteFiles);
|
||||
if ("error" in result) return error(reply, result.error!, result.status!);
|
||||
|
||||
await logAudit({
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
UpdatePlanOverrideSchema,
|
||||
PlanRangeQuerySchema,
|
||||
PlanGridQuerySchema,
|
||||
BulkPlanEntrySchema,
|
||||
} from "../../schemas/plan.schema";
|
||||
import {
|
||||
resolveGrid,
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
deleteOverride,
|
||||
listEntries,
|
||||
listOverrides,
|
||||
bulkCreateEntries,
|
||||
} from "../../services/plan.service";
|
||||
import {
|
||||
CreatePlanCategorySchema,
|
||||
@@ -259,6 +261,29 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
},
|
||||
);
|
||||
|
||||
// --- POST /plan/entries/bulk ---
|
||||
app.post(
|
||||
"/entries/bulk",
|
||||
{ preHandler: requirePermission("attendance.manage") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(BulkPlanEntrySchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const result = await bulkCreateEntries(
|
||||
body.data!,
|
||||
request.authData!.userId,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "create",
|
||||
entityType: "work_plan_entry",
|
||||
description: `Hromadné přiřazení: ${body.data!.category} — ${result.data.users} zaměstnanců, ${body.data!.date_from}–${body.data!.date_to} (${result.data.created_days} dní)`,
|
||||
});
|
||||
return success(reply, result.data, 201, "Hromadné přiřazení dokončeno");
|
||||
},
|
||||
);
|
||||
|
||||
// --- PATCH /plan/entries/:id ---
|
||||
app.patch(
|
||||
"/entries/:id",
|
||||
@@ -328,18 +353,6 @@ export default async function planRoutes(app: FastifyInstance) {
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
|
||||
// If the create replaced an existing active override, log the soft-delete first.
|
||||
if (result.replacedData) {
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
action: "delete",
|
||||
entityType: "work_plan_override",
|
||||
entityId: (result.replacedData as any).id,
|
||||
oldValues: result.replacedData as Record<string, unknown>,
|
||||
description: result.replacedDescription,
|
||||
});
|
||||
}
|
||||
await logAudit({
|
||||
request,
|
||||
authData: request.authData,
|
||||
|
||||
@@ -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"),
|
||||
});
|
||||
@@ -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) {
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -588,15 +588,17 @@ export async function updateOrder(id: number, body: UpdateOrderData) {
|
||||
return { data: { id, order_number: existing.order_number } };
|
||||
}
|
||||
|
||||
export async function deleteOrder(id: number) {
|
||||
export async function deleteOrder(id: number, deleteFiles = false) {
|
||||
const existing = await prisma.orders.findUnique({ where: { id } });
|
||||
if (!existing)
|
||||
return { error: "Objednávka nenalezena", status: 404 } as const;
|
||||
|
||||
// Fetch linked projects before the transaction for number release later
|
||||
// Fetch linked projects before the transaction for number release and
|
||||
// (optional) NAS folder cleanup later. project_number is needed to locate
|
||||
// the folder on the share.
|
||||
const linkedProjects = await prisma.projects.findMany({
|
||||
where: { order_id: id },
|
||||
select: { id: true, created_at: true },
|
||||
select: { id: true, created_at: true, project_number: true },
|
||||
});
|
||||
|
||||
// Guard: projects may have non-cascaded warehouse refs (sklad_issues,
|
||||
@@ -662,6 +664,24 @@ export async function deleteOrder(id: number) {
|
||||
await tx.orders.delete({ where: { id } });
|
||||
});
|
||||
|
||||
// Best-effort NAS folder cleanup for the order's project(s), outside the
|
||||
// transaction and only when the user ticked the "delete folder" checkbox in
|
||||
// the order delete modal. Non-fatal: a NAS error must not undo the
|
||||
// already-committed DB delete. deleteProjectFolder is idempotent — it returns
|
||||
// true (no-op) when the folder is already absent.
|
||||
if (deleteFiles && nasFileManager.isConfigured()) {
|
||||
for (const p of linkedProjects) {
|
||||
if (!p.project_number) continue;
|
||||
const ok = await nasFileManager.deleteProjectFolder(p.project_number);
|
||||
if (!ok) {
|
||||
console.error(
|
||||
"[orders.service] NAS folder not deleted for project",
|
||||
p.project_number,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const year = existing.created_at
|
||||
? new Date(existing.created_at).getFullYear()
|
||||
: new Date().getFullYear();
|
||||
|
||||
@@ -108,12 +108,14 @@ export interface ResolvedCell {
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the effective plan cell for (userId, dateStr).
|
||||
* Compute the effective plan records for (userId, dateStr) as an array of
|
||||
* 0–MAX_RECORDS_PER_CELL records.
|
||||
*
|
||||
* Precedence: override > entry > null.
|
||||
* Soft-deleted rows are ignored (is_deleted = false filter).
|
||||
* If multiple entries cover the same day, the latest by created_at wins
|
||||
* and a warning is logged.
|
||||
* Layering: if any override exists for the day, the overrides are returned
|
||||
* (newest-first) and the range entries are hidden; otherwise the range
|
||||
* entries covering the day are returned (newest-first). Soft-deleted rows
|
||||
* are ignored (is_deleted = false filter). The result is capped at
|
||||
* MAX_RECORDS_PER_CELL.
|
||||
*
|
||||
* dateStr must be a YYYY-MM-DD string. The function builds a JS Date
|
||||
* from it and Prisma handles timezone conversion against the MySQL
|
||||
@@ -122,31 +124,31 @@ export interface ResolvedCell {
|
||||
export async function resolveCell(
|
||||
userId: number,
|
||||
dateStr: string,
|
||||
): Promise<ResolvedCell | null> {
|
||||
): Promise<ResolvedCell[]> {
|
||||
const date = new Date(dateStr);
|
||||
|
||||
// 1. Single-day override for this exact date
|
||||
const override = await prisma.work_plan_overrides.findFirst({
|
||||
const overrides = await prisma.work_plan_overrides.findMany({
|
||||
where: { user_id: userId, shift_date: date, is_deleted: false },
|
||||
orderBy: { created_at: "desc" },
|
||||
take: MAX_RECORDS_PER_CELL,
|
||||
include: { projects: projectSelect },
|
||||
});
|
||||
if (override) {
|
||||
return {
|
||||
source: "override",
|
||||
if (overrides.length > 0) {
|
||||
return overrides.map((o) => ({
|
||||
source: "override" as const,
|
||||
entryId: null,
|
||||
overrideId: override.id,
|
||||
user_id: override.user_id,
|
||||
overrideId: o.id,
|
||||
user_id: o.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: override.project_id,
|
||||
...projectFields(override.projects),
|
||||
category: override.category,
|
||||
note: override.note,
|
||||
project_id: o.project_id,
|
||||
...projectFields(o.projects),
|
||||
category: o.category,
|
||||
note: o.note,
|
||||
rangeFrom: null,
|
||||
rangeTo: null,
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
// 2. Range entry that covers the day
|
||||
const entries = await prisma.work_plan_entries.findMany({
|
||||
where: {
|
||||
user_id: userId,
|
||||
@@ -155,24 +157,11 @@ export async function resolveCell(
|
||||
is_deleted: false,
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
take: MAX_RECORDS_PER_CELL,
|
||||
include: { projects: projectSelect },
|
||||
});
|
||||
|
||||
if (entries.length === 0) return null;
|
||||
|
||||
if (entries.length > 1) {
|
||||
// Multiple entries overlap. Use the latest. A persistent audit-log
|
||||
// entry would be ideal here, but logAudit() currently requires a
|
||||
// FastifyRequest — services have no request. Use console.warn as a
|
||||
// stand-in until a service-context audit logger is introduced.
|
||||
console.warn(
|
||||
`[plan.service] multiple entries cover user ${userId} on ${dateStr}; using the latest (entry id ${entries[0].id})`,
|
||||
);
|
||||
}
|
||||
|
||||
const entry = entries[0];
|
||||
return {
|
||||
source: "entry",
|
||||
return entries.map((entry) => ({
|
||||
source: "entry" as const,
|
||||
entryId: entry.id,
|
||||
overrideId: null,
|
||||
user_id: entry.user_id,
|
||||
@@ -183,12 +172,14 @@ export async function resolveCell(
|
||||
note: entry.note,
|
||||
rangeFrom: entry.date_from.toISOString().slice(0, 10),
|
||||
rangeTo: entry.date_to.toISOString().slice(0, 10),
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the effective plan cell for every (userId, date) in the
|
||||
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell | null.
|
||||
* Compute the effective plan records for every (userId, date) in the
|
||||
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell[]
|
||||
* (0–MAX_RECORDS_PER_CELL records, same layering as resolveCell; empty
|
||||
* days are []).
|
||||
*
|
||||
* Implementation: load all entries and overrides for the range in two
|
||||
* queries, then iterate the dates and resolve each cell in O(1) per
|
||||
@@ -198,7 +189,7 @@ export async function resolveGrid(
|
||||
userIds: number[],
|
||||
dateFromStr: string,
|
||||
dateToStr: string,
|
||||
): Promise<Record<number, Record<string, ResolvedCell | null>>> {
|
||||
): Promise<Record<number, Record<string, ResolvedCell[]>>> {
|
||||
const dateFrom = new Date(dateFromStr);
|
||||
const dateTo = new Date(dateToStr);
|
||||
|
||||
@@ -219,11 +210,11 @@ export async function resolveGrid(
|
||||
is_deleted: false,
|
||||
shift_date: { gte: dateFrom, lte: dateTo },
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
include: { projects: projectSelect },
|
||||
}),
|
||||
]);
|
||||
|
||||
// Build a date list (inclusive)
|
||||
const dates: string[] = [];
|
||||
for (
|
||||
let d = new Date(dateFrom);
|
||||
@@ -233,56 +224,52 @@ export async function resolveGrid(
|
||||
dates.push(d.toISOString().slice(0, 10));
|
||||
}
|
||||
|
||||
const result: Record<number, Record<string, ResolvedCell | null>> = {};
|
||||
const result: Record<number, Record<string, ResolvedCell[]>> = {};
|
||||
for (const uid of userIds) {
|
||||
result[uid] = {};
|
||||
for (const dateStr of dates) {
|
||||
// Override first
|
||||
const override = overrides.find(
|
||||
(o) =>
|
||||
o.user_id === uid &&
|
||||
o.shift_date.toISOString().slice(0, 10) === dateStr,
|
||||
);
|
||||
if (override) {
|
||||
result[uid][dateStr] = {
|
||||
source: "override",
|
||||
const day = new Date(dateStr);
|
||||
const dayOverrides = overrides
|
||||
.filter(
|
||||
(o) =>
|
||||
o.user_id === uid &&
|
||||
o.shift_date.toISOString().slice(0, 10) === dateStr,
|
||||
)
|
||||
.slice(0, MAX_RECORDS_PER_CELL);
|
||||
if (dayOverrides.length > 0) {
|
||||
result[uid][dateStr] = dayOverrides.map((o) => ({
|
||||
source: "override" as const,
|
||||
entryId: null,
|
||||
overrideId: override.id,
|
||||
user_id: override.user_id,
|
||||
overrideId: o.id,
|
||||
user_id: o.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: override.project_id,
|
||||
...projectFields(override.projects),
|
||||
category: override.category,
|
||||
note: override.note,
|
||||
project_id: o.project_id,
|
||||
...projectFields(o.projects),
|
||||
category: o.category,
|
||||
note: o.note,
|
||||
rangeFrom: null,
|
||||
rangeTo: null,
|
||||
};
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
// First (latest by created_at) matching entry
|
||||
const entry = entries.find(
|
||||
(e) =>
|
||||
e.user_id === uid &&
|
||||
e.date_from <= new Date(dateStr) &&
|
||||
e.date_to >= new Date(dateStr),
|
||||
);
|
||||
if (entry) {
|
||||
result[uid][dateStr] = {
|
||||
source: "entry",
|
||||
entryId: entry.id,
|
||||
overrideId: null,
|
||||
user_id: entry.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: entry.project_id,
|
||||
...projectFields(entry.projects),
|
||||
category: entry.category,
|
||||
note: entry.note,
|
||||
rangeFrom: entry.date_from.toISOString().slice(0, 10),
|
||||
rangeTo: entry.date_to.toISOString().slice(0, 10),
|
||||
};
|
||||
} else {
|
||||
result[uid][dateStr] = null;
|
||||
}
|
||||
const dayEntries = entries
|
||||
.filter(
|
||||
(e) => e.user_id === uid && e.date_from <= day && e.date_to >= day,
|
||||
)
|
||||
.slice(0, MAX_RECORDS_PER_CELL);
|
||||
result[uid][dateStr] = dayEntries.map((e) => ({
|
||||
source: "entry" as const,
|
||||
entryId: e.id,
|
||||
overrideId: null,
|
||||
user_id: e.user_id,
|
||||
shift_date: dateStr,
|
||||
project_id: e.project_id,
|
||||
...projectFields(e.projects),
|
||||
category: e.category,
|
||||
note: e.note,
|
||||
rangeFrom: e.date_from.toISOString().slice(0, 10),
|
||||
rangeTo: e.date_to.toISOString().slice(0, 10),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,22 +364,14 @@ export function assertNotPastDate(
|
||||
* where `oldData` is null for creates and the pre-update snapshot for
|
||||
* updates / deletes (so the route handler can call `logAudit` with it).
|
||||
*
|
||||
* The optional `replacedData` field is set only by `createOverride` when
|
||||
* an existing active override for the same (user, date) was soft-deleted
|
||||
* before creating the new one. The route handler uses it to emit a
|
||||
* second audit-log entry for the deletion of the replaced row.
|
||||
*
|
||||
* On failure returns `{ error, status }`.
|
||||
*/
|
||||
export type Result<T> =
|
||||
| {
|
||||
data: T;
|
||||
oldData: unknown | null;
|
||||
replacedData?: unknown | null;
|
||||
/** Human-readable Czech subject for the audit-log row. */
|
||||
description?: string;
|
||||
/** Audit description for the `replacedData` soft-delete row, if any. */
|
||||
replacedDescription?: string;
|
||||
}
|
||||
| { error: string; status: number };
|
||||
|
||||
@@ -401,6 +380,46 @@ function toDateOnly(dateStr: string): Date {
|
||||
return new Date(dateStr + "T00:00:00.000Z");
|
||||
}
|
||||
|
||||
/** Maximum number of records (entries OR overrides) shown per cell per day. */
|
||||
export const MAX_RECORDS_PER_CELL = 3;
|
||||
|
||||
/**
|
||||
* Returns { error, status } if creating an entry over [dateFromStr, dateToStr]
|
||||
* would push any single day past MAX_RECORDS_PER_CELL active entries for the
|
||||
* user. Names the first offending date. Counts entries regardless of whether an
|
||||
* override currently hides them (simpler and predictable).
|
||||
*/
|
||||
async function assertEntryCapAvailable(
|
||||
userId: number,
|
||||
dateFromStr: string,
|
||||
dateToStr: string,
|
||||
): Promise<{ error: string; status: number } | null> {
|
||||
const from = toDateOnly(dateFromStr);
|
||||
const to = toDateOnly(dateToStr);
|
||||
const existing = await prisma.work_plan_entries.findMany({
|
||||
where: {
|
||||
user_id: userId,
|
||||
is_deleted: false,
|
||||
date_from: { lte: to },
|
||||
date_to: { gte: from },
|
||||
},
|
||||
select: { date_from: true, date_to: true },
|
||||
});
|
||||
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
|
||||
const day = new Date(d);
|
||||
const count = existing.filter(
|
||||
(e) => e.date_from <= day && e.date_to >= day,
|
||||
).length;
|
||||
if (count >= MAX_RECORDS_PER_CELL) {
|
||||
return {
|
||||
error: `Na den ${day.toISOString().slice(0, 10)} jsou již ${MAX_RECORDS_PER_CELL} záznamy (maximum).`,
|
||||
status: 400,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Create a work_plan_entries row. Past dates require force=true. */
|
||||
export async function createEntry(
|
||||
input: {
|
||||
@@ -442,6 +461,13 @@ export async function createEntry(
|
||||
const catErr = await assertActiveCategory(input.category);
|
||||
if (catErr) return catErr;
|
||||
|
||||
const capErr = await assertEntryCapAvailable(
|
||||
input.user_id,
|
||||
input.date_from,
|
||||
input.date_to,
|
||||
);
|
||||
if (capErr) return capErr;
|
||||
|
||||
const created = await prisma.work_plan_entries.create({
|
||||
data: {
|
||||
user_id: input.user_id,
|
||||
@@ -576,13 +602,10 @@ export async function deleteEntry(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a work_plan_overrides row. Replaces any active override for the
|
||||
* same (user_id, shift_date) — soft-deletes the old one. Past dates
|
||||
* require force=true.
|
||||
*
|
||||
* Returns { data, oldData: null, replacedData: existing_or_null } so the
|
||||
* route handler can emit two audit log rows: one for the soft-deleted
|
||||
* previous override, and one for the new one.
|
||||
* Create a work_plan_overrides row. Additive: stacks up to
|
||||
* MAX_RECORDS_PER_CELL active overrides per (user_id, shift_date); a create
|
||||
* past the cap returns { error, status: 400 }. Past dates require force=true.
|
||||
* Returns { data, oldData: null, description }.
|
||||
*/
|
||||
export async function createOverride(
|
||||
input: {
|
||||
@@ -601,49 +624,41 @@ export async function createOverride(
|
||||
const catErr = await assertActiveCategory(input.category);
|
||||
if (catErr) return catErr;
|
||||
|
||||
// Application-level enforcement of "at most one active override per
|
||||
// (user_id, shift_date)". The previous DB unique constraint was dropped
|
||||
// (see migration 20260605122718_drop_wpo_unique_constraint) because
|
||||
// MySQL unique indexes don't ignore soft-deleted rows, which would have
|
||||
// blocked legitimate soft-delete-then-create replacement.
|
||||
//
|
||||
// Race protection: wrap the soft-delete + create in a transaction with
|
||||
// SELECT ... FOR UPDATE on the colliding row so two concurrent requests
|
||||
// can't both create active overrides for the same user-day.
|
||||
const date = toDateOnly(input.shift_date);
|
||||
|
||||
const { created, replaced } = await prisma.$transaction(async (tx) => {
|
||||
const existing = await tx.work_plan_overrides.findFirst({
|
||||
where: {
|
||||
user_id: input.user_id,
|
||||
shift_date: date,
|
||||
is_deleted: false,
|
||||
},
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
// Lock the row before update so a concurrent createOverride for the
|
||||
// same (user, date) waits and sees the soft-deleted state.
|
||||
await tx.$executeRaw`SELECT id FROM work_plan_overrides WHERE id = ${existing.id} FOR UPDATE`;
|
||||
await tx.work_plan_overrides.update({
|
||||
where: { id: existing.id },
|
||||
data: { is_deleted: true },
|
||||
// Additive up to MAX_RECORDS_PER_CELL. (This previously REPLACED the existing
|
||||
// override; multi-record cells stack instead.) count+create runs in one
|
||||
// transaction; a concurrent create could in theory add one extra row, but
|
||||
// resolve display caps at MAX_RECORDS_PER_CELL so that is benign.
|
||||
let created;
|
||||
try {
|
||||
created = await prisma.$transaction(async (tx) => {
|
||||
const count = await tx.work_plan_overrides.count({
|
||||
where: { user_id: input.user_id, shift_date: date, is_deleted: false },
|
||||
});
|
||||
if (count >= MAX_RECORDS_PER_CELL) {
|
||||
throw Object.assign(new Error("cap"), { __cap: true });
|
||||
}
|
||||
return tx.work_plan_overrides.create({
|
||||
data: {
|
||||
user_id: input.user_id,
|
||||
shift_date: date,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
created_by: actorUserId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const createdRow = await tx.work_plan_overrides.create({
|
||||
data: {
|
||||
user_id: input.user_id,
|
||||
shift_date: date,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
created_by: actorUserId,
|
||||
},
|
||||
});
|
||||
|
||||
return { created: createdRow, replaced: existing };
|
||||
});
|
||||
} catch (e) {
|
||||
if (e && typeof e === "object" && "__cap" in e) {
|
||||
return {
|
||||
error: `Na tento den jsou již ${MAX_RECORDS_PER_CELL} záznamy (maximum).`,
|
||||
status: 400,
|
||||
};
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
const { userName, projectName } = await resolvePlanLabels(
|
||||
created.user_id,
|
||||
@@ -658,26 +673,7 @@ export async function createOverride(
|
||||
force,
|
||||
});
|
||||
|
||||
let replacedDescription: string | undefined;
|
||||
if (replaced) {
|
||||
const r = await resolvePlanLabels(replaced.user_id, replaced.project_id);
|
||||
replacedDescription = buildPlanAuditDescription({
|
||||
userName: r.userName,
|
||||
categoryLabel: await resolveCategoryLabel(replaced.category),
|
||||
projectName: r.projectName,
|
||||
dateFrom: isoDay(replaced.shift_date),
|
||||
dateTo: isoDay(replaced.shift_date),
|
||||
suffix: "nahrazeno novým záznamem",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
data: created,
|
||||
oldData: null,
|
||||
replacedData: replaced,
|
||||
description,
|
||||
replacedDescription,
|
||||
};
|
||||
return { data: created, oldData: null, description };
|
||||
}
|
||||
|
||||
/** Update a work_plan_overrides row. */
|
||||
@@ -765,6 +761,157 @@ export async function deleteOverride(
|
||||
return { data: { ok: true }, oldData: existing, description };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bulk entry creation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Bulk-assign a project/category to many employees over a date range. For each
|
||||
* employee, walk the range, keep the days that pass the weekday filter
|
||||
* (weekends excluded unless include_weekends) AND are under the per-cell cap,
|
||||
* group contiguous kept days into runs, and create one range entry per run by
|
||||
* reusing createEntry (so cap / past-date / category validation stays DRY).
|
||||
*
|
||||
* Days that pass the weekday filter but are already at the cap are counted in
|
||||
* skipped_days (and split the range). Weekend days, when excluded, are out of
|
||||
* scope and are NOT counted as skipped.
|
||||
*/
|
||||
export async function bulkCreateEntries(
|
||||
input: {
|
||||
user_ids: number[];
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
include_weekends: boolean;
|
||||
project_id?: number | null;
|
||||
category: string;
|
||||
note: string;
|
||||
},
|
||||
actorUserId: number,
|
||||
): Promise<
|
||||
Result<{
|
||||
created_entries: number;
|
||||
created_days: number;
|
||||
skipped_days: number;
|
||||
users: number;
|
||||
}>
|
||||
> {
|
||||
if (input.user_ids.length === 0) {
|
||||
return { error: "Vyberte alespoň jednoho zaměstnance", status: 400 };
|
||||
}
|
||||
if (input.date_to < input.date_from) {
|
||||
return { error: "Datum do musí být stejné nebo po datumu od", status: 400 };
|
||||
}
|
||||
const lockFrom = assertNotPastDate(input.date_from, false);
|
||||
if (lockFrom) return lockFrom;
|
||||
const lockTo = assertNotPastDate(input.date_to, false);
|
||||
if (lockTo) return lockTo;
|
||||
const catErr = await assertActiveCategory(input.category);
|
||||
if (catErr) return catErr;
|
||||
|
||||
const from = toDateOnly(input.date_from);
|
||||
const to = toDateOnly(input.date_to);
|
||||
|
||||
// Bound the work (users × days). Mirror the 92-day cap on GET /plan/grid so
|
||||
// one bulk call can't fan out into thousands of inserts.
|
||||
const rangeDays = Math.round((to.getTime() - from.getTime()) / 86400000) + 1;
|
||||
if (rangeDays > 92) {
|
||||
return { error: "Maximální rozsah je 92 dní", status: 400 };
|
||||
}
|
||||
|
||||
// The day list for the whole range (UTC midnights), built once.
|
||||
const days: Date[] = [];
|
||||
for (let d = new Date(from); d <= to; d.setUTCDate(d.getUTCDate() + 1)) {
|
||||
days.push(new Date(d));
|
||||
}
|
||||
|
||||
let createdEntries = 0;
|
||||
let createdDays = 0;
|
||||
let skippedDays = 0;
|
||||
|
||||
for (const userId of input.user_ids) {
|
||||
// Per-day cap counts from this user's existing active entries.
|
||||
const existing = await prisma.work_plan_entries.findMany({
|
||||
where: {
|
||||
user_id: userId,
|
||||
is_deleted: false,
|
||||
date_from: { lte: to },
|
||||
date_to: { gte: from },
|
||||
},
|
||||
select: { date_from: true, date_to: true },
|
||||
});
|
||||
const countFor = (day: Date): number =>
|
||||
existing.filter((e) => e.date_from <= day && e.date_to >= day).length;
|
||||
|
||||
// Eligibility per day (weekday filter + under-cap). Tally cap skips.
|
||||
const eligible: boolean[] = [];
|
||||
for (const day of days) {
|
||||
const dow = day.getUTCDay(); // 0 = Sun, 6 = Sat
|
||||
const isWeekend = dow === 0 || dow === 6;
|
||||
if (isWeekend && !input.include_weekends) {
|
||||
eligible.push(false);
|
||||
continue;
|
||||
}
|
||||
if (countFor(day) >= MAX_RECORDS_PER_CELL) {
|
||||
skippedDays++;
|
||||
eligible.push(false);
|
||||
continue;
|
||||
}
|
||||
eligible.push(true);
|
||||
}
|
||||
|
||||
// Group contiguous eligible days into runs; create one range per run.
|
||||
let runStart = -1;
|
||||
for (let i = 0; i <= days.length; i++) {
|
||||
const ok = i < days.length && eligible[i];
|
||||
if (ok && runStart === -1) {
|
||||
runStart = i;
|
||||
} else if (!ok && runStart !== -1) {
|
||||
const segFrom = days[runStart].toISOString().slice(0, 10);
|
||||
const segTo = days[i - 1].toISOString().slice(0, 10);
|
||||
const runDays = i - runStart;
|
||||
const res = await createEntry(
|
||||
{
|
||||
user_id: userId,
|
||||
date_from: segFrom,
|
||||
date_to: segTo,
|
||||
project_id: input.project_id ?? null,
|
||||
category: input.category,
|
||||
note: input.note,
|
||||
},
|
||||
actorUserId,
|
||||
false,
|
||||
);
|
||||
if ("data" in res) {
|
||||
createdEntries++;
|
||||
createdDays += runDays;
|
||||
} else {
|
||||
// Rare race (e.g. the cap filled concurrently between the count and
|
||||
// the create). Treat the run's days as skipped, but log — services
|
||||
// must not swallow non-fatal failures (CLAUDE.md known-issue #4).
|
||||
console.warn("[plan.service] bulkCreateEntries: segment skipped", {
|
||||
userId,
|
||||
segFrom,
|
||||
segTo,
|
||||
error: res.error,
|
||||
});
|
||||
skippedDays += runDays;
|
||||
}
|
||||
runStart = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
created_entries: createdEntries,
|
||||
created_days: createdDays,
|
||||
skipped_days: skippedDays,
|
||||
users: input.user_ids.length,
|
||||
},
|
||||
oldData: null,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Raw-row list endpoints
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user