Compare commits

...

9 Commits

Author SHA1 Message Date
BOHA
1a262508d4 chore(release): v2.0.5 — multi-record plan cells
A plan cell now holds up to 3 records: additive assignments + day
exceptions, via the layered entries/overrides model (no migration).
resolveCell/resolveGrid return arrays; cap enforced per layer on create;
grid renders up to 3 stacked; cell editor is a day panel (list/add/edit,
layer-aware add); dashboard "today" card shows up to 3.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:37:40 +02:00
BOHA
23ac924472 fix(plan): edit/add the clicked record + layer-aware add in exception mode
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:29:52 +02:00
BOHA
9370423fb0 feat(plan): day panel — list/add/edit up to 3 records per cell
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:16:52 +02:00
BOHA
a146fc26a3 feat(plan): grid renders up to 3 stacked records per cell
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 11:08:48 +02:00
BOHA
72888bf9cd feat(plan): resolveCell/resolveGrid return arrays; dashboard shows up to 3
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:53:26 +02:00
BOHA
80dc8a5c69 feat(plan): per-cell record cap (3) + additive overrides
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 10:46:40 +02:00
BOHA
2cfa28dc47 docs(plan): implementation plan for multi-record plan cells (v2.0.5)
Five tasks: (1) backend cap + additive overrides, (2) resolve->arrays +
coordinated frontend shape change + dashboard, (3) grid stacked render,
(4) day-panel cell editor, (5) v2.0.5 release. Backend tasks are TDD
against the real test DB; frontend tasks gate on tsc/build/Chrome (no
component-test harness).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:33:40 +02:00
BOHA
628cd54a81 docs(plan): spec for multi-record plan cells (max 3 per cell)
Feature A of 2: lets a plan cell hold up to 3 records (additive
assignments + day exceptions) via the layered entries/overrides model,
no migration. resolveCell/resolveGrid return arrays; cap enforced per
layer on create; grid shows up to 3 stacked; cell editor becomes a
day panel; dashboard today-card shows up to 3. Feature B (bulk create)
decisions captured as deferred.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 10:22:15 +02:00
BOHA
9ae69e09a3 fix(orders): delete NAS folder when order delete modal's checkbox is ticked
The order delete modal sends { delete_files }, but the route ignored the
body and deleteOrder never touched the NAS — so the project folder of an
order-spawned project always stayed on the share (the only way to delete
such a project is via its order, since deleteProject blocks order-linked
projects). Project delete (standalone projects) already worked.

- orders route: read delete_files from the body, pass to deleteOrder.
- orders.service deleteOrder(id, deleteFiles): select project_number and,
  after the DB transaction commits, best-effort deleteProjectFolder for
  each linked project when the flag is set. Non-fatal; idempotent.
- tests: NasFileManager.deleteProjectFolder coverage — removes by number
  prefix, no-op when absent, false when not mounted (158 -> 161 tests).

Bump version to 2.0.4.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 08:51:57 +02:00
18 changed files with 2635 additions and 458 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -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 03 `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[]` (03) 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 23 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 (fromto), 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 = MonFri 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).

View File

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

View File

@@ -68,3 +68,39 @@ describe("NasFileManager.createProjectFolder", () => {
);
});
});
/**
* Folder deletion primitive used by the "delete folder" checkbox on both the
* order delete (orders.service deleteOrder) and project delete (projects.service
* deleteProject) paths. Matches the project by number prefix.
*/
describe("NasFileManager.deleteProjectFolder", () => {
let tmpBase: string;
let nas: NasFileManager;
beforeEach(() => {
tmpBase = fs.mkdtempSync(path.join(os.tmpdir(), "nas-del-"));
nas = new NasFileManager(tmpBase);
});
afterEach(() => {
fs.rmSync(tmpBase, { recursive: true, force: true });
});
it("removes an existing project folder (matched by number prefix)", async () => {
nas.createProjectFolder("26710010", "Hala");
expect(fs.existsSync(path.join(tmpBase, "26710010_Hala"))).toBe(true);
const ok = await nas.deleteProjectFolder("26710010");
expect(ok).toBe(true);
expect(fs.existsSync(path.join(tmpBase, "26710010_Hala"))).toBe(false);
});
it("is a no-op (returns true) when no folder exists for the number", async () => {
expect(await nas.deleteProjectFolder("26710011")).toBe(true);
});
it("returns false when the NAS base is not mounted", async () => {
const missing = new NasFileManager(path.join(tmpBase, "nope"));
expect(await missing.deleteProjectFolder("26710012")).toBe(false);
});
});

View File

@@ -58,6 +58,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 +89,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 +106,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 +134,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 +194,7 @@ describe("plan.service.resolveCell", () => {
},
});
const result = await resolveCell(adminUserId, "2099-06-05");
expect(result).toBeNull();
expect(result).toEqual([]);
});
});
@@ -164,11 +215,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 +243,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 +461,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 +589,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 +604,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 () => {
@@ -810,7 +963,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`,
);
});

View File

@@ -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>
);
}

View File

@@ -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,51 @@ 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,
)}
showNote={cellArr.length === 1}
/>
</Box>
))}
</button>
</td>
);

View File

@@ -6,6 +6,7 @@ interface Props {
project: Project | null;
readonly?: boolean;
categoryLabel: string;
showNote?: boolean;
}
export default function PlanRangeChips({
@@ -13,6 +14,7 @@ export default function PlanRangeChips({
project,
readonly,
categoryLabel,
showNote = true,
}: Props) {
void readonly;
if (!cell) return null;
@@ -36,7 +38,9 @@ export default function PlanRangeChips({
</span>
)}
</div>
{cell.note && <div className="plan-cell-note">{cell.note}</div>}
{showNote && cell.note && (
<div className="plan-cell-note">{cell.note}</div>
)}
</div>
);
}

View File

@@ -3,7 +3,7 @@ import Typography from "@mui/material/Typography";
import { Card } from "../../ui";
import { formatDate } from "../../utils/formatters";
/** The logged-in user's resolved work plan for today (see GET /api/admin/dashboard). */
/** One resolved plan record for today (see GET /api/admin/dashboard). */
export interface TodayPlan {
shift_date: string;
category: string;
@@ -23,15 +23,64 @@ function projectLabel(p: TodayPlan): string {
return parts.length > 0 ? parts.join(" — ") : "Bez projektu";
}
/**
* "Vaše dnešní zařazení" — shows the logged-in user's work-plan entry for today
* (category + project/site + note, with a range badge when the day is part of a
* multi-day range). `plan === null` = the user has plan access but nothing is
* scheduled today (muted empty state). Rendered near the clock-in on the
* dashboard; the caller gates it on the plan permission.
*/
export default function DashTodayPlan({ plan }: { plan: TodayPlan | null }) {
const color = plan?.category_color || "var(--mui-palette-primary-main)";
function PlanRow({ plan }: { plan: TodayPlan }) {
const color = plan.category_color || "var(--mui-palette-primary-main)";
return (
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
<Box
sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}
>
<Box
sx={{
display: "inline-flex",
alignItems: "center",
gap: 0.75,
px: 1.25,
py: 0.5,
borderRadius: 999,
border: 1,
borderColor: "divider",
bgcolor: `color-mix(in srgb, ${color} 12%, transparent)`,
}}
>
<Box
sx={{
width: 10,
height: 10,
borderRadius: "50%",
bgcolor: color,
flexShrink: 0,
}}
/>
<Typography
component="span"
sx={{ fontWeight: 700, fontSize: "0.8rem" }}
>
{plan.category_label}
</Typography>
</Box>
{plan.rangeFrom && plan.rangeTo && plan.rangeFrom !== plan.rangeTo && (
<Typography variant="caption" color="text.secondary">
součást rozsahu {formatDate(plan.rangeFrom)} {" "}
{formatDate(plan.rangeTo)}
</Typography>
)}
</Box>
<Typography variant="h6" sx={{ lineHeight: 1.25 }}>
{projectLabel(plan)}
</Typography>
{plan.note && (
<Typography variant="body2" color="text.secondary">
{plan.note}
</Typography>
)}
</Box>
);
}
/** "Vaše dnešní zařazení" — the logged-in user's resolved plan record(s) for
* today (up to 3). Empty array = nothing scheduled. */
export default function DashTodayPlan({ plans }: { plans: TodayPlan[] }) {
return (
<Card sx={{ mb: 3 }}>
<Typography
@@ -40,65 +89,20 @@ export default function DashTodayPlan({ plan }: { plan: TodayPlan | null }) {
>
Vaše dnešní zařazení
</Typography>
{plan ? (
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: 1,
flexWrap: "wrap",
}}
>
{plans.length > 0 ? (
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
{plans.map((p, i) => (
<Box
key={i}
sx={{
display: "inline-flex",
alignItems: "center",
gap: 0.75,
px: 1.25,
py: 0.5,
borderRadius: 999,
border: 1,
pt: i === 0 ? 0 : 2,
borderTop: i === 0 ? 0 : 1,
borderColor: "divider",
bgcolor: `color-mix(in srgb, ${color} 12%, transparent)`,
}}
>
<Box
sx={{
width: 10,
height: 10,
borderRadius: "50%",
bgcolor: color,
flexShrink: 0,
}}
/>
<Typography
component="span"
sx={{ fontWeight: 700, fontSize: "0.8rem" }}
>
{plan.category_label}
</Typography>
<PlanRow plan={p} />
</Box>
{plan.rangeFrom &&
plan.rangeTo &&
plan.rangeFrom !== plan.rangeTo && (
<Typography variant="caption" color="text.secondary">
součást rozsahu {formatDate(plan.rangeFrom)} {" "}
{formatDate(plan.rangeTo)}
</Typography>
)}
</Box>
<Typography variant="h6" sx={{ lineHeight: 1.25 }}>
{projectLabel(plan)}
</Typography>
{plan.note && (
<Typography variant="body2" color="text.secondary">
{plan.note}
</Typography>
)}
))}
</Box>
) : (
<Typography variant="body2" color="text.secondary">

View File

@@ -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;
@@ -472,15 +496,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,
@@ -518,10 +542,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;
}

View File

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

View File

@@ -72,7 +72,7 @@ interface DashData {
pending_orders?: number;
unpaid_invoices?: number;
pending_leave_requests?: number;
today_plan?: TodayPlan | null;
today_plan?: TodayPlan[];
[key: string]: unknown;
}
@@ -325,7 +325,7 @@ export default function Dashboard() {
{!dashLoading &&
(hasPermission("attendance.record") ||
hasPermission("attendance.manage")) && (
<DashTodayPlan plan={dashData?.today_plan ?? null} />
<DashTodayPlan plans={dashData?.today_plan ?? []} />
)}
{/* Quick actions */}

View File

@@ -8,6 +8,7 @@ import { useAlert } from "../context/AlertContext";
import {
usePlanWork,
getCell,
getCells,
type ModalMode as HookModalMode,
} from "../hooks/usePlanWork";
import type { PlanCellModalMode } from "../components/PlanCellModal";
@@ -17,7 +18,11 @@ import PlanCategoriesModal from "../components/PlanCategoriesModal";
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 = [
@@ -193,84 +198,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 +287,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 +302,7 @@ export default function PlanWork() {
date,
});
},
[grid, setHookModal],
[modalCell, setHookModal],
);
// --- Mutation wrappers -----------------------------------------------------
@@ -327,8 +337,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 +368,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 +414,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 +444,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 +469,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 +500,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 +521,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 +556,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.
@@ -691,6 +719,8 @@ export default function PlanWork() {
onDeleteOverride={deleteOverrideFn}
onCreateOverrideFromRange={createOverrideFromRange}
onSwitchToEditRange={switchToEditRange}
onAddRecord={openCreate}
onEditRecord={editRecord}
/>
<PlanCategoriesModal
isOpen={catModalOpen}

View File

@@ -44,26 +44,27 @@ export default async function dashboardRoutes(
}
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
// resolveCell applies override-beats-range precedence; null = the user has
// plan access but nothing is scheduled today. The category key is enriched
// with its label + colour so the widget needs no extra query. todayStr uses
// local (Europe/Prague) calendar date — the plan's @db.Date day.
// resolveCell returns 03 records (override-beats-range layering); an empty
// array means the user has plan access but nothing is scheduled today. Each
// record's category key is enriched with its label + colour so the widget
// needs no extra query. todayStr uses local (Europe/Prague) calendar date —
// the plan's @db.Date day.
if (has("attendance.record") || has("attendance.manage")) {
const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
const cell = await resolveCell(userId, todayStr);
if (cell) {
const cat = await prisma.plan_categories.findUnique({
where: { key: cell.category },
select: { label: true, color: true },
});
result.today_plan = {
...cell,
category_label: cat?.label ?? cell.category,
category_color: cat?.color ?? null,
};
} else {
result.today_plan = null;
}
const cells = await resolveCell(userId, todayStr);
result.today_plan = await Promise.all(
cells.map(async (cell) => {
const cat = await prisma.plan_categories.findUnique({
where: { key: cell.category },
select: { label: true, color: true },
});
return {
...cell,
category_label: cat?.label ?? cell.category,
category_color: cat?.color ?? null,
};
}),
);
}
// Attendance admin — only for attendance.manage

View File

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

View File

@@ -328,18 +328,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,

View File

@@ -588,15 +588,17 @@ export async function updateOrder(id: number, body: UpdateOrderData) {
return { data: { id, order_number: existing.order_number } };
}
export async function deleteOrder(id: number) {
export async function deleteOrder(id: number, deleteFiles = false) {
const existing = await prisma.orders.findUnique({ where: { id } });
if (!existing)
return { error: "Objednávka nenalezena", status: 404 } as const;
// Fetch linked projects before the transaction for number release later
// Fetch linked projects before the transaction for number release and
// (optional) NAS folder cleanup later. project_number is needed to locate
// the folder on the share.
const linkedProjects = await prisma.projects.findMany({
where: { order_id: id },
select: { id: true, created_at: true },
select: { id: true, created_at: true, project_number: true },
});
// Guard: projects may have non-cascaded warehouse refs (sklad_issues,
@@ -662,6 +664,24 @@ export async function deleteOrder(id: number) {
await tx.orders.delete({ where: { id } });
});
// Best-effort NAS folder cleanup for the order's project(s), outside the
// transaction and only when the user ticked the "delete folder" checkbox in
// the order delete modal. Non-fatal: a NAS error must not undo the
// already-committed DB delete. deleteProjectFolder is idempotent — it returns
// true (no-op) when the folder is already absent.
if (deleteFiles && nasFileManager.isConfigured()) {
for (const p of linkedProjects) {
if (!p.project_number) continue;
const ok = await nasFileManager.deleteProjectFolder(p.project_number);
if (!ok) {
console.error(
"[orders.service] NAS folder not deleted for project",
p.project_number,
);
}
}
}
const year = existing.created_at
? new Date(existing.created_at).getFullYear()
: new Date().getFullYear();

View File

@@ -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
* 0MAX_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[]
* (0MAX_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. */