Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a262508d4 | ||
|
|
23ac924472 | ||
|
|
9370423fb0 | ||
|
|
a146fc26a3 | ||
|
|
72888bf9cd | ||
|
|
80dc8a5c69 | ||
|
|
2cfa28dc47 | ||
|
|
628cd54a81 |
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
@@ -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).
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "app-ts",
|
"name": "app-ts",
|
||||||
"version": "2.0.4",
|
"version": "2.0.5",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "dist/server.js",
|
"main": "dist/server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -58,6 +58,20 @@ beforeEach(async () => {
|
|||||||
await prisma.work_plan_overrides.deleteMany({
|
await prisma.work_plan_overrides.deleteMany({
|
||||||
where: { note: { contains: N } },
|
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 () => {
|
afterAll(async () => {
|
||||||
@@ -75,10 +89,9 @@ afterAll(async () => {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
describe("plan.service.resolveCell", () => {
|
describe("plan.service.resolveCell", () => {
|
||||||
it("returns null when nothing covers the date", async () => {
|
it("returns [] when nothing covers the date", async () => {
|
||||||
// No entry, no override for (adminUserId, "2099-01-01")
|
|
||||||
const result = await resolveCell(adminUserId, "2099-01-01");
|
const result = await resolveCell(adminUserId, "2099-01-01");
|
||||||
expect(result).toBeNull();
|
expect(result).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns the entry that covers the date", async () => {
|
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");
|
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||||
expect(result).not.toBeNull();
|
expect(result.length).toBe(1);
|
||||||
expect(result?.source).toBe("entry");
|
expect(result[0].source).toBe("entry");
|
||||||
expect(result?.note).toBe(`${N}PLC upgrade`);
|
expect(result[0].note).toBe(`${N}PLC upgrade`);
|
||||||
expect(result?.category).toBe("work");
|
expect(result[0].rangeFrom).toBe("2099-06-01");
|
||||||
expect(result?.rangeFrom).toBe("2099-06-01");
|
expect(result[0].rangeTo).toBe("2099-06-10");
|
||||||
expect(result?.rangeTo).toBe("2099-06-10");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns the override for that day, not the entry", async () => {
|
it("returns overrides (entries hidden) when an override exists", async () => {
|
||||||
// An entry covers 2099-06-01..2099-06-10, but an override on 2099-06-05
|
|
||||||
// takes precedence.
|
|
||||||
await prisma.work_plan_entries.create({
|
await prisma.work_plan_entries.create({
|
||||||
data: {
|
data: {
|
||||||
user_id: adminUserId,
|
user_id: adminUserId,
|
||||||
@@ -124,10 +134,51 @@ describe("plan.service.resolveCell", () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const result = await resolveCell(adminUserId, "2099-06-05");
|
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||||
expect(result).not.toBeNull();
|
expect(result.length).toBe(1);
|
||||||
expect(result?.source).toBe("override");
|
expect(result[0].source).toBe("override");
|
||||||
expect(result?.note).toBe(`${N}Volno po noční`);
|
expect(result[0].note).toBe(`${N}Volno po noční`);
|
||||||
expect(result?.category).toBe("leave");
|
});
|
||||||
|
|
||||||
|
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 () => {
|
it("ignores soft-deleted entries and overrides", async () => {
|
||||||
@@ -143,7 +194,7 @@ describe("plan.service.resolveCell", () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const result = await resolveCell(adminUserId, "2099-06-05");
|
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");
|
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-01"][0]?.note).toBe(`${N}A`);
|
||||||
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}A`);
|
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}A`);
|
||||||
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
expect(cells[adminUserId]["2099-06-03"][0]?.note).toBe(`${N}A`);
|
||||||
expect(cells[adminUserId]["2099-06-04"]).toBeNull();
|
expect(cells[adminUserId]["2099-06-04"]).toEqual([]);
|
||||||
expect(cells[adminUserId]["2099-06-05"]).toBeNull();
|
expect(cells[adminUserId]["2099-06-05"]).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("applies override on a covered day", async () => {
|
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");
|
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-01"][0]?.note).toBe(`${N}A`);
|
||||||
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}B`);
|
expect(cells[adminUserId]["2099-06-02"][0]?.note).toBe(`${N}B`);
|
||||||
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
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);
|
expect("error" in result).toBe(true);
|
||||||
if ("error" in result) expect(result.status).toBe(403);
|
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", () => {
|
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(
|
const result = await createOverride(
|
||||||
{
|
{
|
||||||
user_id: adminUserId,
|
user_id: adminUserId,
|
||||||
@@ -454,42 +604,45 @@ describe("plan.service.createOverride", () => {
|
|||||||
if ("data" in result) {
|
if ("data" in result) {
|
||||||
expect(result.data.note).toBe(`${N}day off`);
|
expect(result.data.note).toBe(`${N}day off`);
|
||||||
expect(result.oldData).toBeNull();
|
expect(result.oldData).toBeNull();
|
||||||
expect(result.replacedData).toBeNull();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("soft-deletes the existing override and reports it in replacedData", async () => {
|
it("stacks additive overrides and caps at MAX_RECORDS_PER_CELL", async () => {
|
||||||
await createOverride(
|
for (let i = 0; i < 3; i++) {
|
||||||
|
const r = await createOverride(
|
||||||
{
|
{
|
||||||
user_id: adminUserId,
|
user_id: adminUserId,
|
||||||
shift_date: "2099-10-02",
|
shift_date: "2099-10-02",
|
||||||
category: "leave",
|
category: "leave",
|
||||||
note: `${N}first`,
|
note: `${N}o${i}`,
|
||||||
},
|
},
|
||||||
adminUserId,
|
adminUserId,
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
const second = await createOverride(
|
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,
|
user_id: adminUserId,
|
||||||
shift_date: "2099-10-02",
|
shift_date: "2099-10-02",
|
||||||
category: "sick",
|
category: "leave",
|
||||||
note: `${N}second`,
|
note: `${N}o3`,
|
||||||
},
|
},
|
||||||
adminUserId,
|
adminUserId,
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
expect("data" in second).toBe(true);
|
expect("error" in fourth).toBe(true);
|
||||||
if ("data" in second) {
|
if ("error" in fourth) expect(fourth.status).toBe(400);
|
||||||
expect((second.replacedData as any)?.note).toBe(`${N}first`);
|
// All three earlier overrides remain active — no replace happened.
|
||||||
}
|
const active = await prisma.work_plan_overrides.findMany({
|
||||||
|
where: {
|
||||||
const all = await prisma.work_plan_overrides.findMany({
|
user_id: adminUserId,
|
||||||
where: { user_id: adminUserId, shift_date: new Date("2099-10-02") },
|
shift_date: new Date("2099-10-02"),
|
||||||
|
is_deleted: false,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
// The first should be soft-deleted, the second active
|
expect(active.length).toBe(3);
|
||||||
expect(all.find((o) => o.note === `${N}first`)?.is_deleted).toBe(true);
|
|
||||||
expect(all.find((o) => o.note === `${N}second`)?.is_deleted).toBe(false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rejects a past date without force", async () => {
|
it("rejects a past date without force", async () => {
|
||||||
@@ -810,7 +963,7 @@ describe("HTTP /api/admin/plan", () => {
|
|||||||
const body = res.json();
|
const body = res.json();
|
||||||
expect(body.data.users).toBeDefined();
|
expect(body.data.users).toBeDefined();
|
||||||
expect(body.data.cells[adminUserId]).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`,
|
`${N}grid test`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ interface Project {
|
|||||||
export type PlanCellModalMode =
|
export type PlanCellModalMode =
|
||||||
| { kind: "closed" }
|
| { kind: "closed" }
|
||||||
| { kind: "create"; userId: number; date: string }
|
| { kind: "create"; userId: number; date: string }
|
||||||
|
| { kind: "create-override"; userId: number; date: string }
|
||||||
| {
|
| {
|
||||||
kind: "edit-range";
|
kind: "edit-range";
|
||||||
entryId: number;
|
entryId: number;
|
||||||
@@ -64,7 +65,8 @@ export type PlanCellModalMode =
|
|||||||
note: string;
|
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 {
|
interface Props {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -84,6 +86,16 @@ interface Props {
|
|||||||
date: string,
|
date: string,
|
||||||
) => Promise<void>;
|
) => Promise<void>;
|
||||||
onSwitchToEditRange: (entryId: number, userId: number, date: string) => 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 = (
|
const TrashIcon = (
|
||||||
@@ -112,6 +124,7 @@ export default function PlanCellModal(props: Props) {
|
|||||||
if (mode.kind === "view") return <ViewModal {...props} />;
|
if (mode.kind === "view") return <ViewModal {...props} />;
|
||||||
if (mode.kind === "day-in-range")
|
if (mode.kind === "day-in-range")
|
||||||
return <DayInRangeModal {...props} mode={mode} />;
|
return <DayInRangeModal {...props} mode={mode} />;
|
||||||
|
if (mode.kind === "day") return <DayPanel {...props} mode={mode} />;
|
||||||
return <EditForm {...props} />;
|
return <EditForm {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,21 +144,26 @@ function EditForm(props: Props) {
|
|||||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||||
|
|
||||||
// Narrow mode to the kinds EditForm actually handles. The call site in
|
// Narrow mode to the kinds EditForm actually handles. The call site in
|
||||||
// PlanCellModal only passes "create" | "edit-range" | "edit-override" but
|
// PlanCellModal only passes "create" | "create-override" | "edit-range" |
|
||||||
// the parameter type is the full union, so we narrow explicitly here.
|
// "edit-override" but the parameter type is the full union, so we narrow
|
||||||
|
// explicitly here.
|
||||||
if (
|
if (
|
||||||
mode.kind !== "create" &&
|
mode.kind !== "create" &&
|
||||||
|
mode.kind !== "create-override" &&
|
||||||
mode.kind !== "edit-range" &&
|
mode.kind !== "edit-range" &&
|
||||||
mode.kind !== "edit-override"
|
mode.kind !== "edit-override"
|
||||||
) {
|
) {
|
||||||
return null;
|
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 activeCategories = props.categories.filter((c) => c.is_active);
|
||||||
|
|
||||||
const initial = (() => {
|
const initial = (() => {
|
||||||
if (mode.kind === "create") {
|
if (mode.kind === "create" || mode.kind === "create-override") {
|
||||||
return {
|
return {
|
||||||
date_from: mode.date,
|
date_from: mode.date,
|
||||||
date_to: mode.date,
|
date_to: mode.date,
|
||||||
@@ -190,6 +208,8 @@ function EditForm(props: Props) {
|
|||||||
const title =
|
const title =
|
||||||
mode.kind === "create"
|
mode.kind === "create"
|
||||||
? "Nový záznam plánu"
|
? "Nový záznam plánu"
|
||||||
|
: mode.kind === "create-override"
|
||||||
|
? "Nové přepsání dne"
|
||||||
: mode.kind === "edit-range"
|
: mode.kind === "edit-range"
|
||||||
? "Upravit rozsah"
|
? "Upravit rozsah"
|
||||||
: "Upravit přepsání dne";
|
: "Upravit přepsání dne";
|
||||||
@@ -207,6 +227,17 @@ function EditForm(props: Props) {
|
|||||||
category,
|
category,
|
||||||
note,
|
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") {
|
} else if (mode.kind === "edit-range") {
|
||||||
await onUpdateEntry(mode.entryId, {
|
await onUpdateEntry(mode.entryId, {
|
||||||
date_from: dateFrom,
|
date_from: dateFrom,
|
||||||
@@ -249,6 +280,10 @@ function EditForm(props: Props) {
|
|||||||
const showRetiredCategory =
|
const showRetiredCategory =
|
||||||
category && !activeCategories.some((c) => c.key === category);
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<Modal
|
<Modal
|
||||||
@@ -256,10 +291,10 @@ function EditForm(props: Props) {
|
|||||||
title={title}
|
title={title}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
submitText={mode.kind === "create" ? "Vytvořit" : "Uložit"}
|
submitText={isCreate ? "Vytvořit" : "Uložit"}
|
||||||
loading={submitting}
|
loading={submitting}
|
||||||
>
|
>
|
||||||
{mode.kind !== "create" && (
|
{!isCreate && (
|
||||||
<Box sx={{ mb: 2 }}>
|
<Box sx={{ mb: 2 }}>
|
||||||
<Button
|
<Button
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
@@ -506,3 +541,117 @@ function ViewModal(props: Props) {
|
|||||||
</Modal>
|
</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--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
|
// Chips inside a cell
|
||||||
"& .plan-chip-block": {
|
"& .plan-chip-block": {
|
||||||
display: "flex",
|
display: "flex",
|
||||||
@@ -373,11 +384,7 @@ interface Props {
|
|||||||
// the value so back-to-back mutations on the same cell re-trigger
|
// 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).
|
// the animation (React needs a new key to re-mount the class).
|
||||||
pulseKey?: { userId: number; date: string; nonce: number } | null;
|
pulseKey?: { userId: number; date: string; nonce: number } | null;
|
||||||
onCellClick: (
|
onCellClick: (userId: number, date: string, cells: ResolvedCell[]) => void;
|
||||||
userId: number,
|
|
||||||
date: string,
|
|
||||||
cell: ResolvedCell | null,
|
|
||||||
) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Full Czech weekday names, indexed by Date.getUTCDay() (0 = Sunday).
|
// Full Czech weekday names, indexed by Date.getUTCDay() (0 = Sunday).
|
||||||
@@ -529,7 +536,8 @@ export default function PlanGrid({
|
|||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
{users.map((u) => {
|
{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);
|
const past = isPastDate(date, today);
|
||||||
// Past-day cells are read-only in the UI: an empty past
|
// Past-day cells are read-only in the UI: an empty past
|
||||||
// cell is non-interactive (no create modal, no "+" hint),
|
// cell is non-interactive (no create modal, no "+" hint),
|
||||||
@@ -571,29 +579,51 @@ export default function PlanGrid({
|
|||||||
} as CSSProperties)
|
} as CSSProperties)
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onClick={() => onCellClick(u.id, date, cell)}
|
onClick={() => onCellClick(u.id, date, cellArr)}
|
||||||
aria-label={
|
aria-label={
|
||||||
cell
|
cell
|
||||||
|
? cellArr.length === 1
|
||||||
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
|
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
|
||||||
|
: `${u.full_name}, ${date}, ${cellArr.length} záznamy`
|
||||||
: isLocked
|
: isLocked
|
||||||
? `${u.full_name}, ${date}, ${past ? "uplynulý den" : "prázdné"} — bez záznamu`
|
? `${u.full_name}, ${date}, ${past ? "uplynulý den" : "prázdné"} — bez záznamu`
|
||||||
: `${u.full_name}, ${date}, prázdné — přidat záznam`
|
: `${u.full_name}, ${date}, prázdné — přidat záznam`
|
||||||
}
|
}
|
||||||
|
>
|
||||||
|
{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
|
<PlanRangeChips
|
||||||
cell={cell}
|
cell={c}
|
||||||
project={
|
project={
|
||||||
cell?.project_id
|
c.project_id
|
||||||
? (projects.find(
|
? (projects.find(
|
||||||
(p) => p.id === cell.project_id,
|
(p) => p.id === c.project_id,
|
||||||
) ?? null)
|
) ?? null)
|
||||||
: null
|
: null
|
||||||
}
|
}
|
||||||
readonly={!canEdit}
|
readonly={!canEdit}
|
||||||
categoryLabel={
|
categoryLabel={planCategoryLabel(
|
||||||
cell ? planCategoryLabel(cell.category, catMap) : ""
|
c.category,
|
||||||
}
|
catMap,
|
||||||
|
)}
|
||||||
|
showNote={cellArr.length === 1}
|
||||||
/>
|
/>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ interface Props {
|
|||||||
project: Project | null;
|
project: Project | null;
|
||||||
readonly?: boolean;
|
readonly?: boolean;
|
||||||
categoryLabel: string;
|
categoryLabel: string;
|
||||||
|
showNote?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PlanRangeChips({
|
export default function PlanRangeChips({
|
||||||
@@ -13,6 +14,7 @@ export default function PlanRangeChips({
|
|||||||
project,
|
project,
|
||||||
readonly,
|
readonly,
|
||||||
categoryLabel,
|
categoryLabel,
|
||||||
|
showNote = true,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
void readonly;
|
void readonly;
|
||||||
if (!cell) return null;
|
if (!cell) return null;
|
||||||
@@ -36,7 +38,9 @@ export default function PlanRangeChips({
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{cell.note && <div className="plan-cell-note">{cell.note}</div>}
|
{showNote && cell.note && (
|
||||||
|
<div className="plan-cell-note">{cell.note}</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import Typography from "@mui/material/Typography";
|
|||||||
import { Card } from "../../ui";
|
import { Card } from "../../ui";
|
||||||
import { formatDate } from "../../utils/formatters";
|
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 {
|
export interface TodayPlan {
|
||||||
shift_date: string;
|
shift_date: string;
|
||||||
category: string;
|
category: string;
|
||||||
@@ -23,33 +23,12 @@ function projectLabel(p: TodayPlan): string {
|
|||||||
return parts.length > 0 ? parts.join(" — ") : "Bez projektu";
|
return parts.length > 0 ? parts.join(" — ") : "Bez projektu";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function PlanRow({ plan }: { plan: TodayPlan }) {
|
||||||
* "Vaše dnešní zařazení" — shows the logged-in user's work-plan entry for today
|
const color = plan.category_color || "var(--mui-palette-primary-main)";
|
||||||
* (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)";
|
|
||||||
return (
|
return (
|
||||||
<Card sx={{ mb: 3 }}>
|
|
||||||
<Typography
|
|
||||||
variant="subtitle2"
|
|
||||||
sx={{ mb: 1.5, fontWeight: 600, color: "text.secondary" }}
|
|
||||||
>
|
|
||||||
Vaše dnešní zařazení
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
{plan ? (
|
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: 1,
|
|
||||||
flexWrap: "wrap",
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
@@ -80,26 +59,51 @@ export default function DashTodayPlan({ plan }: { plan: TodayPlan | null }) {
|
|||||||
{plan.category_label}
|
{plan.category_label}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
{plan.rangeFrom &&
|
{plan.rangeFrom && plan.rangeTo && plan.rangeFrom !== plan.rangeTo && (
|
||||||
plan.rangeTo &&
|
|
||||||
plan.rangeFrom !== plan.rangeTo && (
|
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
součást rozsahu {formatDate(plan.rangeFrom)} –{" "}
|
součást rozsahu {formatDate(plan.rangeFrom)} –{" "}
|
||||||
{formatDate(plan.rangeTo)}
|
{formatDate(plan.rangeTo)}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Typography variant="h6" sx={{ lineHeight: 1.25 }}>
|
<Typography variant="h6" sx={{ lineHeight: 1.25 }}>
|
||||||
{projectLabel(plan)}
|
{projectLabel(plan)}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
{plan.note && (
|
{plan.note && (
|
||||||
<Typography variant="body2" color="text.secondary">
|
<Typography variant="body2" color="text.secondary">
|
||||||
{plan.note}
|
{plan.note}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</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">
|
<Typography variant="body2" color="text.secondary">
|
||||||
Pro dnešek nemáte naplánováno.
|
Pro dnešek nemáte naplánováno.
|
||||||
|
|||||||
@@ -12,9 +12,11 @@ export type ViewMode = "week" | "month";
|
|||||||
export type ModalMode =
|
export type ModalMode =
|
||||||
| { kind: "closed" }
|
| { kind: "closed" }
|
||||||
| { kind: "create"; userId: number; date: string }
|
| { kind: "create"; userId: number; date: string }
|
||||||
|
| { kind: "create-override"; userId: number; date: string }
|
||||||
| { kind: "edit-range"; entryId: number; userId: number; date: string }
|
| { kind: "edit-range"; entryId: number; userId: number; date: string }
|
||||||
| { kind: "edit-override"; overrideId: 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-in-range"; userId: number; date: string; entryId: number }
|
||||||
|
| { kind: "day"; userId: number; date: string }
|
||||||
| { kind: "view"; userId: number; date: string };
|
| { kind: "view"; userId: number; date: string };
|
||||||
|
|
||||||
function isoDate(d: Date): string {
|
function isoDate(d: Date): string {
|
||||||
@@ -150,16 +152,16 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
key: readonly unknown[],
|
key: readonly unknown[],
|
||||||
userId: number,
|
userId: number,
|
||||||
dates: string[],
|
dates: string[],
|
||||||
mutator: (prev: ResolvedCell | null) => ResolvedCell | null,
|
mutator: (prev: ResolvedCell[]) => ResolvedCell[],
|
||||||
): Record<string, ResolvedCell | null> | null {
|
): Record<string, ResolvedCell[]> | null {
|
||||||
const prev = snapshotGrid(key);
|
const prev = snapshotGrid(key);
|
||||||
if (!prev) return null;
|
if (!prev) return null;
|
||||||
const userPrev = prev.cells[userId] ?? {};
|
const userPrev = prev.cells[userId] ?? {};
|
||||||
const rolled: Record<string, ResolvedCell | null> = {};
|
const rolled: Record<string, ResolvedCell[]> = {};
|
||||||
const userNext: Record<string, ResolvedCell | null> = { ...userPrev };
|
const userNext: Record<string, ResolvedCell[]> = { ...userPrev };
|
||||||
for (const date of dates) {
|
for (const date of dates) {
|
||||||
rolled[date] = userPrev[date] ?? null;
|
rolled[date] = userPrev[date] ?? [];
|
||||||
userNext[date] = mutator(rolled[date]);
|
userNext[date] = mutator(rolled[date]).slice(0, 3);
|
||||||
}
|
}
|
||||||
qc.setQueryData(key, {
|
qc.setQueryData(key, {
|
||||||
...prev,
|
...prev,
|
||||||
@@ -244,7 +246,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
// the ResolvedCell mirrors the request body.
|
// the ResolvedCell mirrors the request body.
|
||||||
const days = eachDay(body.date_from, body.date_to);
|
const days = eachDay(body.date_from, body.date_to);
|
||||||
const id = data && typeof data.id === "number" ? data.id : null;
|
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({
|
makeEntryCell({
|
||||||
userId: body.user_id,
|
userId: body.user_id,
|
||||||
date: days[0],
|
date: days[0],
|
||||||
@@ -255,7 +257,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
rangeTo: body.date_to,
|
rangeTo: body.date_to,
|
||||||
entryId: id,
|
entryId: id,
|
||||||
}),
|
}),
|
||||||
);
|
...prev,
|
||||||
|
]);
|
||||||
// Stash the rollback on the mutation object so PlanWork can call
|
// Stash the rollback on the mutation object so PlanWork can call
|
||||||
// it from onError.
|
// it from onError.
|
||||||
(createEntry as any)._rolled = rolled;
|
(createEntry as any)._rolled = rolled;
|
||||||
@@ -294,8 +297,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
let ownerUserId: number | null = null;
|
let ownerUserId: number | null = null;
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const cell of Object.values(byDate)) {
|
for (const cells of Object.values(byDate)) {
|
||||||
if (cell && cell.entryId === id) {
|
if (cells.some((c) => c.entryId === id)) {
|
||||||
ownerUserId = Number(uidStr);
|
ownerUserId = Number(uidStr);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -304,20 +307,27 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (ownerUserId !== null) {
|
if (ownerUserId !== null) {
|
||||||
const rolled = patchCells(currentGridKey, ownerUserId, days, (prev) =>
|
const rolled = patchCells(
|
||||||
makeEntryCell({
|
currentGridKey,
|
||||||
|
ownerUserId,
|
||||||
|
days,
|
||||||
|
(prev) => {
|
||||||
|
const existing = prev.find((c) => c.entryId === id) ?? null;
|
||||||
|
const updated = makeEntryCell({
|
||||||
userId: ownerUserId!,
|
userId: ownerUserId!,
|
||||||
date: days[0],
|
date: days[0],
|
||||||
projectId:
|
projectId:
|
||||||
body.project_id === undefined
|
body.project_id === undefined
|
||||||
? (prev?.project_id ?? null)
|
? (existing?.project_id ?? null)
|
||||||
: body.project_id,
|
: body.project_id,
|
||||||
category: body.category ?? prev?.category ?? "work",
|
category: body.category ?? existing?.category ?? "work",
|
||||||
note: body.note ?? prev?.note ?? "",
|
note: body.note ?? existing?.note ?? "",
|
||||||
rangeFrom: body.date_from,
|
rangeFrom: body.date_from,
|
||||||
rangeTo: body.date_to,
|
rangeTo: body.date_to,
|
||||||
entryId: id,
|
entryId: id,
|
||||||
}),
|
});
|
||||||
|
return [updated, ...prev.filter((c) => c.entryId !== id)];
|
||||||
|
},
|
||||||
);
|
);
|
||||||
(updateEntry as any)._rolled = rolled;
|
(updateEntry as any)._rolled = rolled;
|
||||||
}
|
}
|
||||||
@@ -338,26 +348,29 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const [, cell] of Object.entries(byDate)) {
|
let range: { from: string; to: string } | null = null;
|
||||||
if (
|
for (const cells of Object.values(byDate)) {
|
||||||
cell &&
|
const hit = cells.find(
|
||||||
cell.entryId === vars.id &&
|
(c) => c.entryId === vars.id && c.rangeFrom && c.rangeTo,
|
||||||
cell.rangeFrom &&
|
);
|
||||||
cell.rangeTo
|
if (hit) {
|
||||||
) {
|
range = { from: hit.rangeFrom!, to: hit.rangeTo! };
|
||||||
const days = eachDay(cell.rangeFrom, cell.rangeTo);
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (range) {
|
||||||
|
const days = eachDay(range.from, range.to);
|
||||||
const rolled = patchCells(
|
const rolled = patchCells(
|
||||||
currentGridKey,
|
currentGridKey,
|
||||||
Number(uidStr),
|
Number(uidStr),
|
||||||
days,
|
days,
|
||||||
() => null,
|
(prev) => prev.filter((c) => c.entryId !== vars.id),
|
||||||
);
|
);
|
||||||
(deleteEntry as any)._rolled = rolled;
|
(deleteEntry as any)._rolled = rolled;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
invalidate();
|
invalidate();
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -375,7 +388,7 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
currentGridKey,
|
currentGridKey,
|
||||||
vars.user_id,
|
vars.user_id,
|
||||||
[vars.shift_date],
|
[vars.shift_date],
|
||||||
() =>
|
(prev) => [
|
||||||
makeOverrideCell({
|
makeOverrideCell({
|
||||||
userId: vars.user_id,
|
userId: vars.user_id,
|
||||||
date: vars.shift_date,
|
date: vars.shift_date,
|
||||||
@@ -384,6 +397,8 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
note: vars.note,
|
note: vars.note,
|
||||||
overrideId: id,
|
overrideId: id,
|
||||||
}),
|
}),
|
||||||
|
...prev,
|
||||||
|
],
|
||||||
);
|
);
|
||||||
(createOverride as any)._rolled = rolled;
|
(createOverride as any)._rolled = rolled;
|
||||||
invalidate();
|
invalidate();
|
||||||
@@ -411,21 +426,30 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const [date, cell] of Object.entries(byDate)) {
|
for (const [date, cells] of Object.entries(byDate)) {
|
||||||
if (cell && cell.overrideId === vars.id) {
|
if (cells.some((c) => c.overrideId === vars.id)) {
|
||||||
const rolled = patchCells(
|
const rolled = patchCells(
|
||||||
currentGridKey,
|
currentGridKey,
|
||||||
Number(uidStr),
|
Number(uidStr),
|
||||||
[date],
|
[date],
|
||||||
(prev) =>
|
(prev) => {
|
||||||
makeOverrideCell({
|
const existing =
|
||||||
|
prev.find((c) => c.overrideId === vars.id) ?? null;
|
||||||
|
const updated = makeOverrideCell({
|
||||||
userId: Number(uidStr),
|
userId: Number(uidStr),
|
||||||
date,
|
date,
|
||||||
projectId: vars.body.project_id ?? prev?.project_id ?? null,
|
projectId:
|
||||||
category: vars.body.category ?? prev?.category ?? "work",
|
vars.body.project_id ?? existing?.project_id ?? null,
|
||||||
note: vars.body.note ?? prev?.note ?? "",
|
category:
|
||||||
|
vars.body.category ?? existing?.category ?? "work",
|
||||||
|
note: vars.body.note ?? existing?.note ?? "",
|
||||||
overrideId: vars.id,
|
overrideId: vars.id,
|
||||||
}),
|
});
|
||||||
|
return [
|
||||||
|
updated,
|
||||||
|
...prev.filter((c) => c.overrideId !== vars.id),
|
||||||
|
];
|
||||||
|
},
|
||||||
);
|
);
|
||||||
(updateOverride as any)._rolled = rolled;
|
(updateOverride as any)._rolled = rolled;
|
||||||
break;
|
break;
|
||||||
@@ -446,13 +470,13 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const [date, cell] of Object.entries(byDate)) {
|
for (const [date, cells] of Object.entries(byDate)) {
|
||||||
if (cell && cell.overrideId === vars.id) {
|
if (cells.some((c) => c.overrideId === vars.id)) {
|
||||||
const rolled = patchCells(
|
const rolled = patchCells(
|
||||||
currentGridKey,
|
currentGridKey,
|
||||||
Number(uidStr),
|
Number(uidStr),
|
||||||
[date],
|
[date],
|
||||||
() => null,
|
(prev) => prev.filter((c) => c.overrideId !== vars.id),
|
||||||
);
|
);
|
||||||
(deleteOverride as any)._rolled = rolled;
|
(deleteOverride as any)._rolled = rolled;
|
||||||
break;
|
break;
|
||||||
@@ -472,15 +496,15 @@ export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
|||||||
// directly without the "weak type" mismatch a `{ _rolled? }` param causes.
|
// directly without the "weak type" mismatch a `{ _rolled? }` param causes.
|
||||||
function rollbackMutation(mutation: unknown, userId: number) {
|
function rollbackMutation(mutation: unknown, userId: number) {
|
||||||
const stash = mutation as {
|
const stash = mutation as {
|
||||||
_rolled?: Record<string, ResolvedCell | null> | null;
|
_rolled?: Record<string, ResolvedCell[]> | null;
|
||||||
};
|
};
|
||||||
if (!stash._rolled) return;
|
if (!stash._rolled) return;
|
||||||
const prev = qc.getQueryData<GridData>(currentGridKey as any);
|
const prev = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
if (!prev) return;
|
if (!prev) return;
|
||||||
const userPrev = prev.cells[userId] ?? {};
|
const userPrev = prev.cells[userId] ?? {};
|
||||||
const userNext = { ...userPrev };
|
const userNext = { ...userPrev };
|
||||||
for (const [date, cell] of Object.entries(stash._rolled)) {
|
for (const [date, cells] of Object.entries(stash._rolled)) {
|
||||||
userNext[date] = cell;
|
userNext[date] = cells;
|
||||||
}
|
}
|
||||||
qc.setQueryData(currentGridKey, {
|
qc.setQueryData(currentGridKey, {
|
||||||
...prev,
|
...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(
|
export function getCell(
|
||||||
grid: GridData | undefined,
|
grid: GridData | undefined,
|
||||||
userId: number,
|
userId: number,
|
||||||
date: string,
|
date: string,
|
||||||
): ResolvedCell | null {
|
): 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_from: string;
|
||||||
date_to: string;
|
date_to: string;
|
||||||
users: PlanUser[];
|
users: PlanUser[];
|
||||||
cells: Record<number, Record<string, ResolvedCell | null>>;
|
cells: Record<number, Record<string, ResolvedCell[]>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const planKeys = {
|
export const planKeys = {
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ interface DashData {
|
|||||||
pending_orders?: number;
|
pending_orders?: number;
|
||||||
unpaid_invoices?: number;
|
unpaid_invoices?: number;
|
||||||
pending_leave_requests?: number;
|
pending_leave_requests?: number;
|
||||||
today_plan?: TodayPlan | null;
|
today_plan?: TodayPlan[];
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +325,7 @@ export default function Dashboard() {
|
|||||||
{!dashLoading &&
|
{!dashLoading &&
|
||||||
(hasPermission("attendance.record") ||
|
(hasPermission("attendance.record") ||
|
||||||
hasPermission("attendance.manage")) && (
|
hasPermission("attendance.manage")) && (
|
||||||
<DashTodayPlan plan={dashData?.today_plan ?? null} />
|
<DashTodayPlan plans={dashData?.today_plan ?? []} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Quick actions */}
|
{/* Quick actions */}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { useAlert } from "../context/AlertContext";
|
|||||||
import {
|
import {
|
||||||
usePlanWork,
|
usePlanWork,
|
||||||
getCell,
|
getCell,
|
||||||
|
getCells,
|
||||||
type ModalMode as HookModalMode,
|
type ModalMode as HookModalMode,
|
||||||
} from "../hooks/usePlanWork";
|
} from "../hooks/usePlanWork";
|
||||||
import type { PlanCellModalMode } from "../components/PlanCellModal";
|
import type { PlanCellModalMode } from "../components/PlanCellModal";
|
||||||
@@ -17,7 +18,11 @@ import PlanCategoriesModal from "../components/PlanCategoriesModal";
|
|||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
import { Button, Alert, LoadingState, PageEnter } from "../ui";
|
import { Button, Alert, LoadingState, PageEnter } from "../ui";
|
||||||
import { projectListOptions, type Project } from "../lib/queries/projects";
|
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.
|
// plan.css is imported once globally in AdminApp.tsx — no per-page re-import.
|
||||||
|
|
||||||
const MONTH_NAMES = [
|
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.
|
// Null when the modal is closed or in a "create" state with no source cell.
|
||||||
const [modalCell, setModalCell] = useState<ReturnType<typeof getCell>>(null);
|
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(
|
const openCreate = useCallback(
|
||||||
(userId: number, date: string) => {
|
(userId: number, date: string, source: "entry" | "override" = "entry") => {
|
||||||
setModalCell(null);
|
setModalCell(null);
|
||||||
|
if (source === "override") {
|
||||||
|
setHookModal({ kind: "create-override", userId, date });
|
||||||
|
} else {
|
||||||
setHookModal({ kind: "create", userId, date });
|
setHookModal({ kind: "create", userId, date });
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[setHookModal],
|
[setHookModal],
|
||||||
);
|
);
|
||||||
|
|
||||||
const openCell = useCallback(
|
const openCell = useCallback(
|
||||||
(userId: number, date: string) => {
|
(userId: number, date: string, cells: ResolvedCell[]) => {
|
||||||
const cell = getCell(grid, userId, date);
|
const primary = cells[0] ?? null;
|
||||||
// Past-date guard: the server rejects create/edit on past dates with
|
// Past-date guard: the server rejects create/edit on past dates with
|
||||||
// a 403 (see assertNotPastDate in plan.service.ts). To keep the user
|
// a 403 (see assertNotPastDate in plan.service.ts). To keep the user
|
||||||
// out of the "click → modal opens → error toast" state, route any
|
// 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).
|
// past-day click to view mode (or to no-op if there's no record).
|
||||||
if (isPastDate(date, todayIsoLocal())) {
|
if (isPastDate(date, todayIsoLocal())) {
|
||||||
if (!cell) {
|
if (!primary) return;
|
||||||
// Empty past cell — nothing to show or edit.
|
setModalCell(primary);
|
||||||
return;
|
|
||||||
}
|
|
||||||
setModalCell(cell);
|
|
||||||
setHookModal({ kind: "view", userId, date });
|
setHookModal({ kind: "view", userId, date });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!cell) {
|
if (cells.length === 0) {
|
||||||
// Empty cell — open the create modal if the user can edit, otherwise
|
|
||||||
// there's nothing to view.
|
|
||||||
if (canEdit) openCreate(userId, date);
|
if (canEdit) openCreate(userId, date);
|
||||||
return;
|
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);
|
setModalCell(cell);
|
||||||
if (cell.source === "entry" && cell.entryId !== null) {
|
if (cell.source === "entry" && cell.entryId !== null) {
|
||||||
if (canEdit) {
|
if (cell.rangeFrom && cell.rangeTo && cell.rangeFrom !== cell.rangeTo) {
|
||||||
// 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({
|
setHookModal({
|
||||||
kind: "day-in-range",
|
kind: "day-in-range",
|
||||||
entryId: cell.entryId,
|
entryId: cell.entryId,
|
||||||
userId,
|
userId,
|
||||||
date,
|
date,
|
||||||
});
|
});
|
||||||
return;
|
} else {
|
||||||
}
|
|
||||||
setHookModal({
|
setHookModal({
|
||||||
kind: "edit-range",
|
kind: "edit-range",
|
||||||
entryId: cell.entryId,
|
entryId: cell.entryId,
|
||||||
userId,
|
userId,
|
||||||
date,
|
date,
|
||||||
});
|
});
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
// Read-only view
|
|
||||||
setHookModal({ kind: "view", userId, date });
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (cell.source === "override" && cell.overrideId !== null) {
|
if (cell.source === "override" && cell.overrideId !== null) {
|
||||||
if (canEdit) {
|
|
||||||
setHookModal({
|
setHookModal({
|
||||||
kind: "edit-override",
|
kind: "edit-override",
|
||||||
overrideId: cell.overrideId,
|
overrideId: cell.overrideId,
|
||||||
userId,
|
userId,
|
||||||
date,
|
date,
|
||||||
});
|
});
|
||||||
} else {
|
|
||||||
setHookModal({ kind: "view", userId, date });
|
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
|
||||||
// No source — treat as empty
|
|
||||||
if (canEdit) openCreate(userId, date);
|
|
||||||
},
|
},
|
||||||
[grid, canEdit, openCreate, setHookModal],
|
[setHookModal],
|
||||||
);
|
);
|
||||||
|
|
||||||
const closeModal = useCallback(() => {
|
const closeModal = useCallback(() => {
|
||||||
@@ -280,11 +287,14 @@ export default function PlanWork() {
|
|||||||
|
|
||||||
// Switch the modal from "day-in-range" to "edit-range" mode, keeping the
|
// 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.
|
// 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(
|
const switchToEditRange = useCallback(
|
||||||
(entryId: number, userId: number, date: string) => {
|
(entryId: number, userId: number, date: string) => {
|
||||||
const cell = getCell(grid, userId, date);
|
if (!modalCell) return;
|
||||||
if (!cell) return;
|
|
||||||
setModalCell(cell);
|
|
||||||
setHookModal({
|
setHookModal({
|
||||||
kind: "edit-range",
|
kind: "edit-range",
|
||||||
entryId,
|
entryId,
|
||||||
@@ -292,7 +302,7 @@ export default function PlanWork() {
|
|||||||
date,
|
date,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[grid, setHookModal],
|
[modalCell, setHookModal],
|
||||||
);
|
);
|
||||||
|
|
||||||
// --- Mutation wrappers -----------------------------------------------------
|
// --- Mutation wrappers -----------------------------------------------------
|
||||||
@@ -327,8 +337,9 @@ export default function PlanWork() {
|
|||||||
let firstDate: string | null = null;
|
let firstDate: string | null = null;
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const [date, cell] of Object.entries(byDate)) {
|
for (const [date, cells] of Object.entries(byDate)) {
|
||||||
if (cell && cell.entryId === id) {
|
const hit = cells.find((c) => c.entryId === id);
|
||||||
|
if (hit) {
|
||||||
userId = Number(uidStr);
|
userId = Number(uidStr);
|
||||||
firstDate = body.date_from ?? date;
|
firstDate = body.date_from ?? date;
|
||||||
break;
|
break;
|
||||||
@@ -357,10 +368,11 @@ export default function PlanWork() {
|
|||||||
let firstDate: string | null = null;
|
let firstDate: string | null = null;
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const [date, cell] of Object.entries(byDate)) {
|
for (const [date, cells] of Object.entries(byDate)) {
|
||||||
if (cell && cell.entryId === id) {
|
const hit = cells.find((c) => c.entryId === id);
|
||||||
|
if (hit) {
|
||||||
userId = Number(uidStr);
|
userId = Number(uidStr);
|
||||||
firstDate = cell.rangeFrom ?? date;
|
firstDate = hit.rangeFrom ?? date;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -402,8 +414,9 @@ export default function PlanWork() {
|
|||||||
let date: string | null = null;
|
let date: string | null = null;
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const [d, cell] of Object.entries(byDate)) {
|
for (const [d, cells] of Object.entries(byDate)) {
|
||||||
if (cell && cell.overrideId === id) {
|
const hit = cells.find((c) => c.overrideId === id);
|
||||||
|
if (hit) {
|
||||||
userId = Number(uidStr);
|
userId = Number(uidStr);
|
||||||
date = d;
|
date = d;
|
||||||
break;
|
break;
|
||||||
@@ -431,8 +444,9 @@ export default function PlanWork() {
|
|||||||
let date: string | null = null;
|
let date: string | null = null;
|
||||||
if (grid) {
|
if (grid) {
|
||||||
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
for (const [d, cell] of Object.entries(byDate)) {
|
for (const [d, cells] of Object.entries(byDate)) {
|
||||||
if (cell && cell.overrideId === id) {
|
const hit = cells.find((c) => c.overrideId === id);
|
||||||
|
if (hit) {
|
||||||
userId = Number(uidStr);
|
userId = Number(uidStr);
|
||||||
date = d;
|
date = d;
|
||||||
break;
|
break;
|
||||||
@@ -455,11 +469,14 @@ export default function PlanWork() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// "Create override from range" — turn a multi-day entry into a one-day
|
// "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
|
// override for the clicked date. We mirror the CLICKED record's fields
|
||||||
// create a new override mirroring its fields, locked to a single date.
|
// (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(
|
const createOverrideFromRange = useCallback(
|
||||||
async (entryId: number, userId: number, date: string) => {
|
async (entryId: number, userId: number, date: string) => {
|
||||||
const cell = getCell(grid, userId, date);
|
const cell = modalCell;
|
||||||
if (!cell) {
|
if (!cell) {
|
||||||
alert.error("Nepodařilo se najít zdrojový záznam");
|
alert.error("Nepodařilo se najít zdrojový záznam");
|
||||||
return;
|
return;
|
||||||
@@ -483,7 +500,7 @@ export default function PlanWork() {
|
|||||||
// symmetry with the modal contract.
|
// symmetry with the modal contract.
|
||||||
void entryId;
|
void entryId;
|
||||||
},
|
},
|
||||||
[grid, createOverride, alert, firePulse, rollbackMutation],
|
[modalCell, createOverride, alert, firePulse, rollbackMutation],
|
||||||
);
|
);
|
||||||
|
|
||||||
// --- Modal key for remount-on-mode-change ----------------------------------
|
// --- Modal key for remount-on-mode-change ----------------------------------
|
||||||
@@ -504,6 +521,9 @@ export default function PlanWork() {
|
|||||||
const modalMode: PlanCellModalMode = useMemo(() => {
|
const modalMode: PlanCellModalMode = useMemo(() => {
|
||||||
if (hookModal.kind === "closed") return { kind: "closed" };
|
if (hookModal.kind === "closed") return { kind: "closed" };
|
||||||
if (hookModal.kind === "create") return hookModal;
|
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 (hookModal.kind === "view") {
|
||||||
if (!modalCell) return { kind: "closed" };
|
if (!modalCell) return { kind: "closed" };
|
||||||
return {
|
return {
|
||||||
@@ -536,8 +556,16 @@ export default function PlanWork() {
|
|||||||
},
|
},
|
||||||
} as PlanCellModalMode;
|
} 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" };
|
return { kind: "closed" };
|
||||||
}, [hookModal, modalCell]);
|
}, [hookModal, modalCell, grid]);
|
||||||
|
|
||||||
if (!canEdit && !hasPermission("attendance.record")) {
|
if (!canEdit && !hasPermission("attendance.record")) {
|
||||||
// Hard block for users who have neither manage nor record permission.
|
// Hard block for users who have neither manage nor record permission.
|
||||||
@@ -691,6 +719,8 @@ export default function PlanWork() {
|
|||||||
onDeleteOverride={deleteOverrideFn}
|
onDeleteOverride={deleteOverrideFn}
|
||||||
onCreateOverrideFromRange={createOverrideFromRange}
|
onCreateOverrideFromRange={createOverrideFromRange}
|
||||||
onSwitchToEditRange={switchToEditRange}
|
onSwitchToEditRange={switchToEditRange}
|
||||||
|
onAddRecord={openCreate}
|
||||||
|
onEditRecord={editRecord}
|
||||||
/>
|
/>
|
||||||
<PlanCategoriesModal
|
<PlanCategoriesModal
|
||||||
isOpen={catModalOpen}
|
isOpen={catModalOpen}
|
||||||
|
|||||||
@@ -44,26 +44,27 @@ export default async function dashboardRoutes(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
|
// Today's work plan (personal) — powers the "Vaše dnešní zařazení" card.
|
||||||
// resolveCell applies override-beats-range precedence; null = the user has
|
// resolveCell returns 0–3 records (override-beats-range layering); an empty
|
||||||
// plan access but nothing is scheduled today. The category key is enriched
|
// array means the user has plan access but nothing is scheduled today. Each
|
||||||
// with its label + colour so the widget needs no extra query. todayStr uses
|
// record's category key is enriched with its label + colour so the widget
|
||||||
// local (Europe/Prague) calendar date — the plan's @db.Date day.
|
// needs no extra query. todayStr uses local (Europe/Prague) calendar date —
|
||||||
|
// the plan's @db.Date day.
|
||||||
if (has("attendance.record") || has("attendance.manage")) {
|
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 todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
||||||
const cell = await resolveCell(userId, todayStr);
|
const cells = await resolveCell(userId, todayStr);
|
||||||
if (cell) {
|
result.today_plan = await Promise.all(
|
||||||
|
cells.map(async (cell) => {
|
||||||
const cat = await prisma.plan_categories.findUnique({
|
const cat = await prisma.plan_categories.findUnique({
|
||||||
where: { key: cell.category },
|
where: { key: cell.category },
|
||||||
select: { label: true, color: true },
|
select: { label: true, color: true },
|
||||||
});
|
});
|
||||||
result.today_plan = {
|
return {
|
||||||
...cell,
|
...cell,
|
||||||
category_label: cat?.label ?? cell.category,
|
category_label: cat?.label ?? cell.category,
|
||||||
category_color: cat?.color ?? null,
|
category_color: cat?.color ?? null,
|
||||||
};
|
};
|
||||||
} else {
|
}),
|
||||||
result.today_plan = null;
|
);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attendance admin — only for attendance.manage
|
// Attendance admin — only for attendance.manage
|
||||||
|
|||||||
@@ -328,18 +328,6 @@ export default async function planRoutes(app: FastifyInstance) {
|
|||||||
);
|
);
|
||||||
if ("error" in result) return error(reply, result.error, result.status);
|
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({
|
await logAudit({
|
||||||
request,
|
request,
|
||||||
authData: request.authData,
|
authData: request.authData,
|
||||||
|
|||||||
@@ -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.
|
* Layering: if any override exists for the day, the overrides are returned
|
||||||
* Soft-deleted rows are ignored (is_deleted = false filter).
|
* (newest-first) and the range entries are hidden; otherwise the range
|
||||||
* If multiple entries cover the same day, the latest by created_at wins
|
* entries covering the day are returned (newest-first). Soft-deleted rows
|
||||||
* and a warning is logged.
|
* 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
|
* dateStr must be a YYYY-MM-DD string. The function builds a JS Date
|
||||||
* from it and Prisma handles timezone conversion against the MySQL
|
* from it and Prisma handles timezone conversion against the MySQL
|
||||||
@@ -122,31 +124,31 @@ export interface ResolvedCell {
|
|||||||
export async function resolveCell(
|
export async function resolveCell(
|
||||||
userId: number,
|
userId: number,
|
||||||
dateStr: string,
|
dateStr: string,
|
||||||
): Promise<ResolvedCell | null> {
|
): Promise<ResolvedCell[]> {
|
||||||
const date = new Date(dateStr);
|
const date = new Date(dateStr);
|
||||||
|
|
||||||
// 1. Single-day override for this exact date
|
const overrides = await prisma.work_plan_overrides.findMany({
|
||||||
const override = await prisma.work_plan_overrides.findFirst({
|
|
||||||
where: { user_id: userId, shift_date: date, is_deleted: false },
|
where: { user_id: userId, shift_date: date, is_deleted: false },
|
||||||
|
orderBy: { created_at: "desc" },
|
||||||
|
take: MAX_RECORDS_PER_CELL,
|
||||||
include: { projects: projectSelect },
|
include: { projects: projectSelect },
|
||||||
});
|
});
|
||||||
if (override) {
|
if (overrides.length > 0) {
|
||||||
return {
|
return overrides.map((o) => ({
|
||||||
source: "override",
|
source: "override" as const,
|
||||||
entryId: null,
|
entryId: null,
|
||||||
overrideId: override.id,
|
overrideId: o.id,
|
||||||
user_id: override.user_id,
|
user_id: o.user_id,
|
||||||
shift_date: dateStr,
|
shift_date: dateStr,
|
||||||
project_id: override.project_id,
|
project_id: o.project_id,
|
||||||
...projectFields(override.projects),
|
...projectFields(o.projects),
|
||||||
category: override.category,
|
category: o.category,
|
||||||
note: override.note,
|
note: o.note,
|
||||||
rangeFrom: null,
|
rangeFrom: null,
|
||||||
rangeTo: null,
|
rangeTo: null,
|
||||||
};
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Range entry that covers the day
|
|
||||||
const entries = await prisma.work_plan_entries.findMany({
|
const entries = await prisma.work_plan_entries.findMany({
|
||||||
where: {
|
where: {
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
@@ -155,24 +157,11 @@ export async function resolveCell(
|
|||||||
is_deleted: false,
|
is_deleted: false,
|
||||||
},
|
},
|
||||||
orderBy: { created_at: "desc" },
|
orderBy: { created_at: "desc" },
|
||||||
|
take: MAX_RECORDS_PER_CELL,
|
||||||
include: { projects: projectSelect },
|
include: { projects: projectSelect },
|
||||||
});
|
});
|
||||||
|
return entries.map((entry) => ({
|
||||||
if (entries.length === 0) return null;
|
source: "entry" as const,
|
||||||
|
|
||||||
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",
|
|
||||||
entryId: entry.id,
|
entryId: entry.id,
|
||||||
overrideId: null,
|
overrideId: null,
|
||||||
user_id: entry.user_id,
|
user_id: entry.user_id,
|
||||||
@@ -183,12 +172,14 @@ export async function resolveCell(
|
|||||||
note: entry.note,
|
note: entry.note,
|
||||||
rangeFrom: entry.date_from.toISOString().slice(0, 10),
|
rangeFrom: entry.date_from.toISOString().slice(0, 10),
|
||||||
rangeTo: entry.date_to.toISOString().slice(0, 10),
|
rangeTo: entry.date_to.toISOString().slice(0, 10),
|
||||||
};
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compute the effective plan cell for every (userId, date) in the
|
* Compute the effective plan records for every (userId, date) in the
|
||||||
* given range. Returns a 2D map: cells[userId][dateStr] = ResolvedCell | null.
|
* 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
|
* Implementation: load all entries and overrides for the range in two
|
||||||
* queries, then iterate the dates and resolve each cell in O(1) per
|
* queries, then iterate the dates and resolve each cell in O(1) per
|
||||||
@@ -198,7 +189,7 @@ export async function resolveGrid(
|
|||||||
userIds: number[],
|
userIds: number[],
|
||||||
dateFromStr: string,
|
dateFromStr: string,
|
||||||
dateToStr: string,
|
dateToStr: string,
|
||||||
): Promise<Record<number, Record<string, ResolvedCell | null>>> {
|
): Promise<Record<number, Record<string, ResolvedCell[]>>> {
|
||||||
const dateFrom = new Date(dateFromStr);
|
const dateFrom = new Date(dateFromStr);
|
||||||
const dateTo = new Date(dateToStr);
|
const dateTo = new Date(dateToStr);
|
||||||
|
|
||||||
@@ -219,11 +210,11 @@ export async function resolveGrid(
|
|||||||
is_deleted: false,
|
is_deleted: false,
|
||||||
shift_date: { gte: dateFrom, lte: dateTo },
|
shift_date: { gte: dateFrom, lte: dateTo },
|
||||||
},
|
},
|
||||||
|
orderBy: { created_at: "desc" },
|
||||||
include: { projects: projectSelect },
|
include: { projects: projectSelect },
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Build a date list (inclusive)
|
|
||||||
const dates: string[] = [];
|
const dates: string[] = [];
|
||||||
for (
|
for (
|
||||||
let d = new Date(dateFrom);
|
let d = new Date(dateFrom);
|
||||||
@@ -233,56 +224,52 @@ export async function resolveGrid(
|
|||||||
dates.push(d.toISOString().slice(0, 10));
|
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) {
|
for (const uid of userIds) {
|
||||||
result[uid] = {};
|
result[uid] = {};
|
||||||
for (const dateStr of dates) {
|
for (const dateStr of dates) {
|
||||||
// Override first
|
const day = new Date(dateStr);
|
||||||
const override = overrides.find(
|
const dayOverrides = overrides
|
||||||
|
.filter(
|
||||||
(o) =>
|
(o) =>
|
||||||
o.user_id === uid &&
|
o.user_id === uid &&
|
||||||
o.shift_date.toISOString().slice(0, 10) === dateStr,
|
o.shift_date.toISOString().slice(0, 10) === dateStr,
|
||||||
);
|
)
|
||||||
if (override) {
|
.slice(0, MAX_RECORDS_PER_CELL);
|
||||||
result[uid][dateStr] = {
|
if (dayOverrides.length > 0) {
|
||||||
source: "override",
|
result[uid][dateStr] = dayOverrides.map((o) => ({
|
||||||
|
source: "override" as const,
|
||||||
entryId: null,
|
entryId: null,
|
||||||
overrideId: override.id,
|
overrideId: o.id,
|
||||||
user_id: override.user_id,
|
user_id: o.user_id,
|
||||||
shift_date: dateStr,
|
shift_date: dateStr,
|
||||||
project_id: override.project_id,
|
project_id: o.project_id,
|
||||||
...projectFields(override.projects),
|
...projectFields(o.projects),
|
||||||
category: override.category,
|
category: o.category,
|
||||||
note: override.note,
|
note: o.note,
|
||||||
rangeFrom: null,
|
rangeFrom: null,
|
||||||
rangeTo: null,
|
rangeTo: null,
|
||||||
};
|
}));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// First (latest by created_at) matching entry
|
const dayEntries = entries
|
||||||
const entry = entries.find(
|
.filter(
|
||||||
(e) =>
|
(e) => e.user_id === uid && e.date_from <= day && e.date_to >= day,
|
||||||
e.user_id === uid &&
|
)
|
||||||
e.date_from <= new Date(dateStr) &&
|
.slice(0, MAX_RECORDS_PER_CELL);
|
||||||
e.date_to >= new Date(dateStr),
|
result[uid][dateStr] = dayEntries.map((e) => ({
|
||||||
);
|
source: "entry" as const,
|
||||||
if (entry) {
|
entryId: e.id,
|
||||||
result[uid][dateStr] = {
|
|
||||||
source: "entry",
|
|
||||||
entryId: entry.id,
|
|
||||||
overrideId: null,
|
overrideId: null,
|
||||||
user_id: entry.user_id,
|
user_id: e.user_id,
|
||||||
shift_date: dateStr,
|
shift_date: dateStr,
|
||||||
project_id: entry.project_id,
|
project_id: e.project_id,
|
||||||
...projectFields(entry.projects),
|
...projectFields(e.projects),
|
||||||
category: entry.category,
|
category: e.category,
|
||||||
note: entry.note,
|
note: e.note,
|
||||||
rangeFrom: entry.date_from.toISOString().slice(0, 10),
|
rangeFrom: e.date_from.toISOString().slice(0, 10),
|
||||||
rangeTo: entry.date_to.toISOString().slice(0, 10),
|
rangeTo: e.date_to.toISOString().slice(0, 10),
|
||||||
};
|
}));
|
||||||
} else {
|
|
||||||
result[uid][dateStr] = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,22 +364,14 @@ export function assertNotPastDate(
|
|||||||
* where `oldData` is null for creates and the pre-update snapshot for
|
* where `oldData` is null for creates and the pre-update snapshot for
|
||||||
* updates / deletes (so the route handler can call `logAudit` with it).
|
* 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 }`.
|
* On failure returns `{ error, status }`.
|
||||||
*/
|
*/
|
||||||
export type Result<T> =
|
export type Result<T> =
|
||||||
| {
|
| {
|
||||||
data: T;
|
data: T;
|
||||||
oldData: unknown | null;
|
oldData: unknown | null;
|
||||||
replacedData?: unknown | null;
|
|
||||||
/** Human-readable Czech subject for the audit-log row. */
|
/** Human-readable Czech subject for the audit-log row. */
|
||||||
description?: string;
|
description?: string;
|
||||||
/** Audit description for the `replacedData` soft-delete row, if any. */
|
|
||||||
replacedDescription?: string;
|
|
||||||
}
|
}
|
||||||
| { error: string; status: number };
|
| { error: string; status: number };
|
||||||
|
|
||||||
@@ -401,6 +380,46 @@ function toDateOnly(dateStr: string): Date {
|
|||||||
return new Date(dateStr + "T00:00:00.000Z");
|
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. */
|
/** Create a work_plan_entries row. Past dates require force=true. */
|
||||||
export async function createEntry(
|
export async function createEntry(
|
||||||
input: {
|
input: {
|
||||||
@@ -442,6 +461,13 @@ export async function createEntry(
|
|||||||
const catErr = await assertActiveCategory(input.category);
|
const catErr = await assertActiveCategory(input.category);
|
||||||
if (catErr) return catErr;
|
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({
|
const created = await prisma.work_plan_entries.create({
|
||||||
data: {
|
data: {
|
||||||
user_id: input.user_id,
|
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
|
* Create a work_plan_overrides row. Additive: stacks up to
|
||||||
* same (user_id, shift_date) — soft-deletes the old one. Past dates
|
* MAX_RECORDS_PER_CELL active overrides per (user_id, shift_date); a create
|
||||||
* require force=true.
|
* past the cap returns { error, status: 400 }. Past dates require force=true.
|
||||||
*
|
* Returns { data, oldData: null, description }.
|
||||||
* 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.
|
|
||||||
*/
|
*/
|
||||||
export async function createOverride(
|
export async function createOverride(
|
||||||
input: {
|
input: {
|
||||||
@@ -601,37 +624,22 @@ export async function createOverride(
|
|||||||
const catErr = await assertActiveCategory(input.category);
|
const catErr = await assertActiveCategory(input.category);
|
||||||
if (catErr) return catErr;
|
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 date = toDateOnly(input.shift_date);
|
||||||
|
|
||||||
const { created, replaced } = await prisma.$transaction(async (tx) => {
|
// Additive up to MAX_RECORDS_PER_CELL. (This previously REPLACED the existing
|
||||||
const existing = await tx.work_plan_overrides.findFirst({
|
// override; multi-record cells stack instead.) count+create runs in one
|
||||||
where: {
|
// transaction; a concurrent create could in theory add one extra row, but
|
||||||
user_id: input.user_id,
|
// resolve display caps at MAX_RECORDS_PER_CELL so that is benign.
|
||||||
shift_date: date,
|
let created;
|
||||||
is_deleted: false,
|
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 (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 },
|
|
||||||
});
|
});
|
||||||
|
if (count >= MAX_RECORDS_PER_CELL) {
|
||||||
|
throw Object.assign(new Error("cap"), { __cap: true });
|
||||||
}
|
}
|
||||||
|
return tx.work_plan_overrides.create({
|
||||||
const createdRow = await tx.work_plan_overrides.create({
|
|
||||||
data: {
|
data: {
|
||||||
user_id: input.user_id,
|
user_id: input.user_id,
|
||||||
shift_date: date,
|
shift_date: date,
|
||||||
@@ -641,9 +649,16 @@ export async function createOverride(
|
|||||||
created_by: actorUserId,
|
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(
|
const { userName, projectName } = await resolvePlanLabels(
|
||||||
created.user_id,
|
created.user_id,
|
||||||
@@ -658,26 +673,7 @@ export async function createOverride(
|
|||||||
force,
|
force,
|
||||||
});
|
});
|
||||||
|
|
||||||
let replacedDescription: string | undefined;
|
return { data: created, oldData: null, description };
|
||||||
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,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Update a work_plan_overrides row. */
|
/** Update a work_plan_overrides row. */
|
||||||
|
|||||||
Reference in New Issue
Block a user