Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92252382ac | ||
|
|
8bed920de1 | ||
|
|
9d2992b722 | ||
|
|
1ddc0feccd | ||
|
|
cce2c9cfaa | ||
|
|
2610301258 | ||
|
|
13d1fc2be3 | ||
|
|
95ca258718 | ||
|
|
6db87bf4ae | ||
|
|
c6a146d57a | ||
|
|
1a262508d4 | ||
|
|
23ac924472 | ||
|
|
9370423fb0 | ||
|
|
a146fc26a3 | ||
|
|
72888bf9cd | ||
|
|
80dc8a5c69 | ||
|
|
2cfa28dc47 | ||
|
|
628cd54a81 | ||
|
|
9ae69e09a3 | ||
|
|
df83eb2091 | ||
|
|
9c862034ca | ||
|
|
67d62a6df0 | ||
|
|
512f1fd92b |
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
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).
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.0.1",
|
||||
"version": "2.0.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "app-ts",
|
||||
"version": "2.0.1",
|
||||
"version": "2.0.2",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.0.1",
|
||||
"version": "2.0.8",
|
||||
"description": "",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
|
||||
106
src/__tests__/nas-project-folder.test.ts
Normal file
106
src/__tests__/nas-project-folder.test.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { NasFileManager } from "../services/nas-file-manager";
|
||||
|
||||
/**
|
||||
* Folder auto-creation primitive used by both the manual project-create path
|
||||
* (projects.service createProject) and the order→project paths (orders.service
|
||||
* createOrder / createOrderFromQuotation). Uses an isolated temp dir via the
|
||||
* constructor seam so it is deterministic and passes even where the real NAS
|
||||
* (Z:) is not mounted.
|
||||
*/
|
||||
describe("NasFileManager.createProjectFolder", () => {
|
||||
let tmpBase: string;
|
||||
let nas: NasFileManager;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpBase = fs.mkdtempSync(path.join(os.tmpdir(), "nas-proj-"));
|
||||
nas = new NasFileManager(tmpBase);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpBase, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("creates a <number>_<name> folder for a new project", () => {
|
||||
const ok = nas.createProjectFolder("26710001", "Rekonstrukce haly");
|
||||
expect(ok).toBe(true);
|
||||
expect(
|
||||
fs.existsSync(path.join(tmpBase, "26710001_Rekonstrukce_haly")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("is idempotent — a second call does not create a duplicate", () => {
|
||||
expect(nas.createProjectFolder("26710002", "Hala")).toBe(true);
|
||||
expect(nas.createProjectFolder("26710002", "Hala")).toBe(true);
|
||||
const matches = fs
|
||||
.readdirSync(tmpBase)
|
||||
.filter((e) => e.startsWith("26710002_"));
|
||||
expect(matches).toEqual(["26710002_Hala"]);
|
||||
});
|
||||
|
||||
it("preserves Czech diacritics (no transliteration)", () => {
|
||||
expect(nas.createProjectFolder("26710003", "Měření haly")).toBe(true);
|
||||
expect(fs.existsSync(path.join(tmpBase, "26710003_Měření_haly"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("strips illegal characters and collapses spaces", () => {
|
||||
expect(nas.createProjectFolder("26710004", "A / B: C")).toBe(true);
|
||||
expect(fs.existsSync(path.join(tmpBase, "26710004_A_B_C"))).toBe(true);
|
||||
});
|
||||
|
||||
it("handles an empty name without crashing (trailing underscore)", () => {
|
||||
expect(nas.createProjectFolder("26710005", "")).toBe(true);
|
||||
expect(fs.existsSync(path.join(tmpBase, "26710005_"))).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false and creates nothing when the NAS base is not mounted", () => {
|
||||
const missing = new NasFileManager(
|
||||
path.join(tmpBase, "does-not-exist-subdir"),
|
||||
);
|
||||
expect(missing.createProjectFolder("26710006", "X")).toBe(false);
|
||||
expect(fs.existsSync(path.join(tmpBase, "does-not-exist-subdir"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
|
||||
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>
|
||||
);
|
||||
|
||||
114
src/admin/components/dashboard/DashTodayPlan.tsx
Normal file
114
src/admin/components/dashboard/DashTodayPlan.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { Card } from "../../ui";
|
||||
import { formatDate } from "../../utils/formatters";
|
||||
|
||||
/** One resolved plan record for today (see GET /api/admin/dashboard). */
|
||||
export interface TodayPlan {
|
||||
shift_date: string;
|
||||
category: string;
|
||||
category_label: string;
|
||||
category_color: string | null;
|
||||
project_id: number | null;
|
||||
project_number: string | null;
|
||||
project_name: string | null;
|
||||
note: string;
|
||||
source: "entry" | "override";
|
||||
rangeFrom: string | null;
|
||||
rangeTo: string | null;
|
||||
}
|
||||
|
||||
function projectLabel(p: TodayPlan): string {
|
||||
const parts = [p.project_number, p.project_name].filter(Boolean);
|
||||
return parts.length > 0 ? parts.join(" — ") : "Bez projektu";
|
||||
}
|
||||
|
||||
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
|
||||
variant="subtitle2"
|
||||
sx={{ mb: 1.5, fontWeight: 600, color: "text.secondary" }}
|
||||
>
|
||||
Vaše dnešní zařazení
|
||||
</Typography>
|
||||
{plans.length > 0 ? (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
{plans.map((p, i) => (
|
||||
<Box
|
||||
key={i}
|
||||
sx={{
|
||||
pt: i === 0 ? 0 : 2,
|
||||
borderTop: i === 0 ? 0 : 1,
|
||||
borderColor: "divider",
|
||||
}}
|
||||
>
|
||||
<PlanRow plan={p} />
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
) : (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Pro dnešek nemáte naplánováno.
|
||||
</Typography>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -19,6 +19,9 @@ import DashActivityFeed from "../components/dashboard/DashActivityFeed";
|
||||
import DashAttendanceToday from "../components/dashboard/DashAttendanceToday";
|
||||
import DashProfile from "../components/dashboard/DashProfile";
|
||||
import DashSessions from "../components/dashboard/DashSessions";
|
||||
import DashTodayPlan, {
|
||||
type TodayPlan,
|
||||
} from "../components/dashboard/DashTodayPlan";
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
@@ -69,6 +72,7 @@ interface DashData {
|
||||
pending_orders?: number;
|
||||
unpaid_invoices?: number;
|
||||
pending_leave_requests?: number;
|
||||
today_plan?: TodayPlan[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -317,6 +321,13 @@ export default function Dashboard() {
|
||||
<DashKpiCards dashData={dashData ?? null} />
|
||||
)}
|
||||
|
||||
{/* My work plan for today — paired with the clock-in below */}
|
||||
{!dashLoading &&
|
||||
(hasPermission("attendance.record") ||
|
||||
hasPermission("attendance.manage")) && (
|
||||
<DashTodayPlan plans={dashData?.today_plan ?? []} />
|
||||
)}
|
||||
|
||||
{/* Quick actions */}
|
||||
{!dashLoading && (
|
||||
<DashQuickActions
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -4,6 +4,7 @@ import { requireAuth } from "../../middleware/auth";
|
||||
import { success } from "../../utils/response";
|
||||
import { localTimeStr } from "../../utils/date";
|
||||
import { toCzk } from "../../services/exchange-rates";
|
||||
import { resolveCell } from "../../services/plan.service";
|
||||
|
||||
export default async function dashboardRoutes(
|
||||
fastify: FastifyInstance,
|
||||
@@ -42,9 +43,33 @@ export default async function dashboardRoutes(
|
||||
result.my_shift = { has_ongoing: myShift !== null };
|
||||
}
|
||||
|
||||
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
|
||||
// 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 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 },
|
||||
@@ -64,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) {
|
||||
@@ -128,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,
|
||||
|
||||
@@ -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"],
|
||||
});
|
||||
|
||||
@@ -105,8 +105,12 @@ interface DownloadResult {
|
||||
export class NasFileManager {
|
||||
private readonly basePath: string;
|
||||
|
||||
constructor() {
|
||||
this.basePath = path.resolve(config.nas.path).replace(/\\/g, "/");
|
||||
constructor(basePath?: string) {
|
||||
// basePath is an injection seam for tests; production callers pass nothing
|
||||
// and get the configured NAS_PATH.
|
||||
this.basePath = path
|
||||
.resolve(basePath ?? config.nas.path)
|
||||
.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
public isConfigured(): boolean {
|
||||
|
||||
@@ -5,6 +5,11 @@ import {
|
||||
releaseSharedNumber,
|
||||
isOrderNumberTaken,
|
||||
} from "./numbering.service";
|
||||
import { NasFileManager } from "./nas-file-manager";
|
||||
|
||||
// Best-effort NAS folder creation for order-spawned projects, mirroring
|
||||
// projects.service. Stateless singleton; reads NAS_PATH at construction.
|
||||
const nasFileManager = new NasFileManager();
|
||||
|
||||
interface OrderItemInput {
|
||||
description?: string | null;
|
||||
@@ -262,6 +267,23 @@ export async function createOrderFromQuotation(
|
||||
return { order, project, orderNumber };
|
||||
});
|
||||
|
||||
// Best-effort NAS project folder, outside the transaction (mirrors
|
||||
// createProject). A project created from an accepted offer must get the same
|
||||
// 02_PROJEKTY/<number>_<name> folder as a manually-created one. Non-fatal: a
|
||||
// NAS outage must never roll back the order.
|
||||
if (result.project.project_number && nasFileManager.isConfigured()) {
|
||||
const created = nasFileManager.createProjectFolder(
|
||||
result.project.project_number,
|
||||
result.project.name || "",
|
||||
);
|
||||
if (!created) {
|
||||
console.error(
|
||||
"[orders.service] NAS folder not created for project",
|
||||
result.project.project_number,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
order_id: result.order.id,
|
||||
@@ -297,7 +319,7 @@ export async function createOrder(
|
||||
attachmentName?: string | null,
|
||||
) {
|
||||
try {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const orderNumber =
|
||||
body.order_number !== undefined && body.order_number !== null
|
||||
? String(body.order_number)
|
||||
@@ -362,6 +384,8 @@ export async function createOrder(
|
||||
}
|
||||
|
||||
let projectId: number | undefined;
|
||||
let createdProject: { project_number: string; name: string } | null =
|
||||
null;
|
||||
// Only auto-create a project for genuine offer-less orders; share the
|
||||
// order's number (same shared pool) exactly like the from-quotation flow.
|
||||
if (body.create_project !== false && body.quotation_id == null) {
|
||||
@@ -375,14 +399,42 @@ export async function createOrder(
|
||||
},
|
||||
});
|
||||
projectId = project.id;
|
||||
if (project.project_number) {
|
||||
createdProject = {
|
||||
project_number: project.project_number,
|
||||
name: project.name || "",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: order.id,
|
||||
order_number: order.order_number,
|
||||
project_id: projectId,
|
||||
createdProject,
|
||||
};
|
||||
});
|
||||
|
||||
// Best-effort NAS project folder, outside the transaction (mirrors
|
||||
// createProject). Non-fatal so a NAS outage can't roll back the order.
|
||||
if (result.createdProject && nasFileManager.isConfigured()) {
|
||||
const created = nasFileManager.createProjectFolder(
|
||||
result.createdProject.project_number,
|
||||
result.createdProject.name,
|
||||
);
|
||||
if (!created) {
|
||||
console.error(
|
||||
"[orders.service] NAS folder not created for project",
|
||||
result.createdProject.project_number,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: result.id,
|
||||
order_number: result.order_number,
|
||||
project_id: result.project_id,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof Error && "status" in err) {
|
||||
return {
|
||||
@@ -536,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,
|
||||
@@ -610,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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -189,10 +189,16 @@ export async function createProject(data: CreateProjectInput) {
|
||||
});
|
||||
|
||||
if (project.project_number && nasFileManager.isConfigured()) {
|
||||
nasFileManager.createProjectFolder(
|
||||
const created = nasFileManager.createProjectFolder(
|
||||
project.project_number,
|
||||
project.name || "",
|
||||
);
|
||||
if (!created) {
|
||||
console.error(
|
||||
"[projects.service] NAS folder not created for project",
|
||||
project.project_number,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return project;
|
||||
|
||||
Reference in New Issue
Block a user