Compare commits
79 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
852c127c00 | ||
|
|
71a0016a4a | ||
|
|
88c9b7c2b8 | ||
|
|
4a78d31a7f | ||
|
|
e845400fca | ||
|
|
fce27633a9 | ||
|
|
4d47897e27 | ||
|
|
aef4ab92ec | ||
|
|
5f36c34d48 | ||
|
|
b94f4879e3 | ||
|
|
dab5ad8aa5 | ||
|
|
8b77a0a905 | ||
|
|
4b1c42b17f | ||
|
|
a55356d417 | ||
|
|
c983747418 | ||
|
|
3db257faa9 | ||
|
|
d3d7f7e199 | ||
|
|
084ec9289b | ||
|
|
4a9c283789 | ||
|
|
2f76fe0bc1 | ||
|
|
9a11a8f001 | ||
|
|
f0816b126b | ||
|
|
f31797fb5b | ||
|
|
9c110abf46 | ||
|
|
a0f351b0aa | ||
|
|
916cf34efd | ||
|
|
003807a074 | ||
|
|
ca911bf96c | ||
|
|
9c10ff9f22 | ||
|
|
38a58b55c0 | ||
|
|
4d8fd62961 | ||
|
|
ef404e4362 | ||
|
|
fb022802ae | ||
|
|
795d4d5af9 | ||
|
|
74113035ae | ||
|
|
42f9561337 | ||
|
|
f79967d433 | ||
|
|
d410e7433e | ||
|
|
0711bafac0 | ||
|
|
5273f88272 | ||
|
|
182d4ca4b3 | ||
|
|
4773b5be22 | ||
|
|
6074d6163b | ||
|
|
652e3f91fc | ||
|
|
5233db2002 | ||
|
|
dac45baaa8 | ||
|
|
f389c4b3cf | ||
|
|
fdc7037e60 | ||
|
|
b02f6afe93 | ||
|
|
1b2ab7b4eb | ||
|
|
29975ecad9 | ||
|
|
e846f15126 | ||
|
|
86bebf9776 | ||
|
|
7b7c6bde68 | ||
|
|
935fb235a6 | ||
|
|
d2d1cdbb92 | ||
|
|
5f08b0e086 | ||
|
|
637499a8ec | ||
|
|
f413bae348 | ||
|
|
2b1de583fd | ||
|
|
5500cdb118 | ||
|
|
2254a13ad0 | ||
|
|
1f5885de84 | ||
|
|
705f58e3d1 | ||
|
|
0330453ad6 | ||
|
|
66b98e2765 | ||
|
|
55648c9a30 | ||
|
|
cd6d3daf43 | ||
|
|
1db5060c42 | ||
|
|
4cabba395d | ||
|
|
59b478f262 | ||
|
|
e4f14a24b7 | ||
|
|
3bd0d055d9 | ||
|
|
746d17e182 | ||
|
|
e96e51598a | ||
|
|
9abec36f07 | ||
|
|
ecd8e3679f | ||
|
|
ba95723b61 | ||
|
|
12289bdce3 |
@@ -1,43 +0,0 @@
|
|||||||
---
|
|
||||||
name: compare-php
|
|
||||||
description: Compare a feature between PHP boha-app and TS boha-app-ts to verify migration parity
|
|
||||||
---
|
|
||||||
|
|
||||||
# Compare PHP vs TS Implementation
|
|
||||||
|
|
||||||
Compare a specific feature, component, or endpoint between the original PHP project (D:\cortex\boha-app) and the TypeScript migration (D:\cortex\boha-app-ts).
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
The user will specify what to compare. Examples:
|
|
||||||
- `/compare-php attendance print`
|
|
||||||
- `/compare-php invoice PDF generation`
|
|
||||||
- `/compare-php offer numbering logic`
|
|
||||||
|
|
||||||
## Process
|
|
||||||
|
|
||||||
1. Search the PHP codebase (D:\cortex\boha-app) for the relevant implementation
|
|
||||||
2. Search the TS codebase (D:\cortex\boha-app-ts) for the same feature
|
|
||||||
3. Compare:
|
|
||||||
- API endpoints and request/response shape
|
|
||||||
- Business logic and calculations
|
|
||||||
- Database queries
|
|
||||||
- Frontend behavior
|
|
||||||
4. Report differences found — what's missing, what's different, what's extra
|
|
||||||
|
|
||||||
## Key directories
|
|
||||||
|
|
||||||
**PHP project:**
|
|
||||||
- API handlers: `D:\cortex\boha-app\api\admin\handlers\`
|
|
||||||
- API routes: `D:\cortex\boha-app\api\admin\`
|
|
||||||
- Frontend pages: `D:\cortex\boha-app\src\admin\pages\`
|
|
||||||
- Frontend components: `D:\cortex\boha-app\src\admin\components\`
|
|
||||||
- Frontend hooks: `D:\cortex\boha-app\src\admin\hooks\`
|
|
||||||
- Includes/utils: `D:\cortex\boha-app\api\includes\`
|
|
||||||
|
|
||||||
**TS project:**
|
|
||||||
- API routes: `D:\cortex\boha-app-ts\src\routes\admin\`
|
|
||||||
- Services: `D:\cortex\boha-app-ts\src\services\`
|
|
||||||
- Frontend pages: `D:\cortex\boha-app-ts\src\admin\pages\`
|
|
||||||
- Frontend components: `D:\cortex\boha-app-ts\src\admin\components\`
|
|
||||||
- Frontend hooks: `D:\cortex\boha-app-ts\src\admin\hooks\`
|
|
||||||
146
CLAUDE.md
146
CLAUDE.md
@@ -75,14 +75,20 @@ npm test # vitest run (single pass)
|
|||||||
npm run test:watch # vitest watch
|
npm run test:watch # vitest watch
|
||||||
|
|
||||||
# Database
|
# Database
|
||||||
npx prisma migrate dev # Apply migrations (dev)
|
npx prisma migrate dev # Create migration from schema changes + apply to dev
|
||||||
npx prisma migrate deploy # Apply migrations (prod)
|
npx prisma migrate dev --name <descriptive_name> # Named migration
|
||||||
npx prisma generate # Regenerate Prisma client after schema changes
|
npx prisma migrate deploy # Apply pending migrations to production
|
||||||
npx prisma studio # DB browser GUI
|
npx prisma generate # Regenerate Prisma client after schema changes
|
||||||
|
npx prisma studio # DB browser GUI
|
||||||
|
npx prisma db seed # (Re)seed the dev database
|
||||||
|
npx prisma migrate diff --from-url <url> --to-schema-datamodel prisma/schema.prisma --script # Preview SQL before prod deploy
|
||||||
|
npx prisma migrate resolve --applied <migration> # Mark migration as applied without running SQL
|
||||||
```
|
```
|
||||||
|
|
||||||
**Do not start the dev server.** The user manages it separately.
|
**Do not start the dev server.** The user manages it separately.
|
||||||
|
|
||||||
|
**Before running `prisma migrate dev` or `prisma db push`, ask the user to stop their dev server and wait for confirmation.** Migrations can conflict with an active database connection from the running server.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Environment Variables
|
## Environment Variables
|
||||||
@@ -248,6 +254,24 @@ When adding new features, add tests in `src/__tests__/`. Name test files `<featu
|
|||||||
- Custom hooks: `useApiCall`, `useListData`, `useTableSort`, `useDebounce`, `useModalLock`.
|
- Custom hooks: `useApiCall`, `useListData`, `useTableSort`, `useDebounce`, `useModalLock`.
|
||||||
- Styling: CSS files in `src/admin/` — no CSS-in-JS, no Tailwind. Use CSS variables.
|
- Styling: CSS files in `src/admin/` — no CSS-in-JS, no Tailwind. Use CSS variables.
|
||||||
|
|
||||||
|
### Query Invalidation Convention
|
||||||
|
|
||||||
|
Mutations must invalidate the **full domain** of any entity they touch. Prefer broad invalidation:
|
||||||
|
|
||||||
|
- `["users"]` over `["users", "list"]`
|
||||||
|
- `["trips"]` over `["trips", "vehicles"]`
|
||||||
|
|
||||||
|
Reason: React Query's `invalidateQueries` uses prefix matching, so `["trips"]` matches all
|
||||||
|
`["trips", ...]` sub-queries. This means new queries are automatically invalidated without
|
||||||
|
updating every mutation handler. Inactive queries are only marked stale, not refetched, so
|
||||||
|
the performance cost is minimal. Optimize to targeted keys only when profiling shows a problem.
|
||||||
|
|
||||||
|
When entity A embeds/references entity B, A's mutation handlers invalidate B's domain:
|
||||||
|
|
||||||
|
- User CRUD invalidates `["trips"]` and `["attendance"]` (both embed user data)
|
||||||
|
- Vehicle CRUD invalidates `["trips"]` (trips reference vehicles)
|
||||||
|
- Invoice CRUD invalidates `["orders"]` (orders reference invoices)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Database Conventions
|
## Database Conventions
|
||||||
@@ -260,6 +284,86 @@ When adding new features, add tests in `src/__tests__/`. Name test files `<featu
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Database Migrations (Critical Workflow)
|
||||||
|
|
||||||
|
**Golden rule: NEVER use `prisma db push`.** It bypasses migration history and causes drift
|
||||||
|
between the schema and migration tracking. Always use `prisma migrate dev` for every schema change.
|
||||||
|
|
||||||
|
**Every database change or manipulation must be a tracked Prisma migration.** This includes:
|
||||||
|
|
||||||
|
- Schema changes (tables, columns, indexes, constraints) — via `prisma migrate dev`
|
||||||
|
- Permission/role/seed data changes — via a migration that does the INSERTs/DELETEs explicitly
|
||||||
|
- Lookup data, default settings, or any other row-level baseline that production needs
|
||||||
|
- Backfills, data fixes, and one-shot corrections that should be in sync across environments
|
||||||
|
|
||||||
|
**What is NOT acceptable:**
|
||||||
|
|
||||||
|
- Running raw SQL against production (`mysql -e "..."`, `npx prisma db execute`, `pm2 exec`)
|
||||||
|
- `npx prisma db seed` as the only way to populate data (seed is dev-only convenience; prod must run the same SQL via a migration)
|
||||||
|
- "I'll fix it in the seed file" or "I'll add a row manually" without a migration to back it
|
||||||
|
|
||||||
|
The reason: every change to the production database must be reviewable, reversible, and reproducible from a fresh checkout. External SQL commands and seed-only changes cause drift — prod and dev diverge, rollback gets harder with every manual change, and the next deploy surprises us.
|
||||||
|
|
||||||
|
If you need to insert/update/seed data on production, write a migration. The migration's `migration.sql` is a normal SQL file — `INSERT INTO ...`, `UPDATE ...`, `DELETE ...` are all valid. Prisma will run it via `prisma migrate deploy` like any other migration.
|
||||||
|
|
||||||
|
### Making schema changes
|
||||||
|
|
||||||
|
```
|
||||||
|
1. Edit prisma/schema.prisma
|
||||||
|
2. npx prisma migrate dev --name descriptive_name
|
||||||
|
→ This creates a migration in prisma/migrations/ AND applies it to dev DB
|
||||||
|
3. npx prisma generate
|
||||||
|
4. Commit BOTH schema.prisma AND the new migration folder
|
||||||
|
git add prisma/schema.prisma prisma/migrations/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Verifying before production deploy
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Preview what SQL will run on production (no changes applied)
|
||||||
|
npx prisma migrate diff \
|
||||||
|
--from-url "mysql://user:pass@prod:3306/app" \
|
||||||
|
--to-schema-datamodel prisma/schema.prisma \
|
||||||
|
--script
|
||||||
|
|
||||||
|
# Empty output = no diff. If it shows SQL, review it before deploying.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deploying migrations to production
|
||||||
|
|
||||||
|
The release process runs `prisma migrate deploy` on production.
|
||||||
|
This applies only pending migrations — safe, idempotent.
|
||||||
|
|
||||||
|
### If migrations get out of sync (drift)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Diff production DB against local schema to find drift
|
||||||
|
npx prisma migrate diff \
|
||||||
|
--from-url "mysql://prod" \
|
||||||
|
--to-schema-datamodel prisma/schema.prisma \
|
||||||
|
--script
|
||||||
|
|
||||||
|
# If drift is safe (CREATE only, no DROPs): apply with db push ONCE, then baseline
|
||||||
|
# If drift includes DROPs: investigate before touching production
|
||||||
|
```
|
||||||
|
|
||||||
|
### Baselinining a database that has no migrations
|
||||||
|
|
||||||
|
If production was synced with `db push` and has no `_prisma_migrations` table:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Create initial migration locally
|
||||||
|
npx prisma migrate dev --name init
|
||||||
|
|
||||||
|
# 2. Copy to production and mark as applied (no SQL runs)
|
||||||
|
scp -r prisma/migrations user@prod:/var/www/app-ts/prisma/
|
||||||
|
ssh user@prod
|
||||||
|
cd /var/www/app-ts
|
||||||
|
npx prisma migrate resolve --applied <migration_name>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Known Issues & Gotchas
|
## Known Issues & Gotchas
|
||||||
|
|
||||||
1. **Date.prototype.toJSON override** — global monkey-patch in `src/config/env.ts`. Side-effects on third-party libraries that serialize dates. Do not remove without migrating all date serialization.
|
1. **Date.prototype.toJSON override** — global monkey-patch in `src/config/env.ts`. Side-effects on third-party libraries that serialize dates. Do not remove without migrating all date serialization.
|
||||||
@@ -276,12 +380,14 @@ When adding new features, add tests in `src/__tests__/`. Name test files `<featu
|
|||||||
|
|
||||||
7. **NAS_PATH file access** — Project file uploads write to a network share path. In dev, this path may not be mounted. Features using `NAS_PATH` will fail gracefully (or not) if the path is unavailable.
|
7. **NAS_PATH file access** — Project file uploads write to a network share path. In dev, this path may not be mounted. Features using `NAS_PATH` will fail gracefully (or not) if the path is unavailable.
|
||||||
|
|
||||||
8. **Prisma client regeneration** — After any schema change, run `npx prisma generate`. The generated client is not committed to git.
|
8. **Prisma client regeneration** — After any schema change and migration, run `npx prisma generate`. The generated client is not committed to git.
|
||||||
|
|
||||||
9. **No CSRF tokens** — CSRF protection relies on `SameSite=Strict` cookies + CORS. Do not weaken CORS configuration.
|
9. **No CSRF tokens** — CSRF protection relies on `SameSite=Strict` cookies + CORS. Do not weaken CORS configuration.
|
||||||
|
|
||||||
10. **Czech locale hardcoded** — Error messages, month names, and some business logic strings are Czech. This is intentional.
|
10. **Czech locale hardcoded** — Error messages, month names, and some business logic strings are Czech. This is intentional.
|
||||||
|
|
||||||
|
11. **Seed file is dev-only** — `prisma/seed.ts` is for local dev convenience. It is **not** the production data source. Any data the production database must have (permissions, default roles, baseline rows) belongs in a migration's `migration.sql`, not in the seed file. `npx prisma db seed` must never be run against production.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Release Process
|
## Release Process
|
||||||
@@ -300,4 +406,34 @@ When adding new features, add tests in `src/__tests__/`. Name test files `<featu
|
|||||||
- Apply Prisma migrations: `npx prisma migrate deploy`
|
- Apply Prisma migrations: `npx prisma migrate deploy`
|
||||||
- Restart: `pm2 restart app-ts --update-env`
|
- Restart: `pm2 restart app-ts --update-env`
|
||||||
|
|
||||||
|
### Hotfixing a migration that was added after the tarball was built
|
||||||
|
|
||||||
|
If you write a new `prisma/migrations/<timestamp>_*` folder **after** the
|
||||||
|
release tarball has already been built and shipped, that migration is
|
||||||
|
NOT in the tarball and `prisma migrate deploy` on prod will report
|
||||||
|
"No pending migrations". The release tarball re-build re-runs the whole
|
||||||
|
release, but for a one-off hotfix you can ship just the new migration
|
||||||
|
folder:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Local
|
||||||
|
cd prisma/migrations
|
||||||
|
tar -czf /tmp/warehouse_perms_migration.tar.gz <timestamp>_<name>/
|
||||||
|
scp /tmp/warehouse_perms_migration.tar.gz boha_admin@192.168.50.100:/tmp/
|
||||||
|
|
||||||
|
# On prod
|
||||||
|
ssh boha_admin@192.168.50.100
|
||||||
|
cd /var/www/app-ts/prisma/migrations
|
||||||
|
sudo -u boha_admin tar -xzf /tmp/warehouse_perms_migration.tar.gz
|
||||||
|
cd /var/www/app-ts
|
||||||
|
npx prisma migrate deploy
|
||||||
|
pm2 restart app-ts --update-env
|
||||||
|
```
|
||||||
|
|
||||||
|
The migration is still tracked in git and applied via `prisma migrate
|
||||||
|
deploy` — the only thing the tarball is doing is delivering the
|
||||||
|
`migration.sql` to prod, which is the same mechanism the main release
|
||||||
|
uses. This is preferred over running raw SQL on prod (which the policy
|
||||||
|
in "Database Migrations" forbids).
|
||||||
|
|
||||||
Do not push directly to production or restart services without confirmation.
|
Do not push directly to production or restart services without confirmation.
|
||||||
|
|||||||
37
boneyard.config.json
Normal file
37
boneyard.config.json
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"breakpoints": [375, 768, 1280],
|
||||||
|
"out": "./src/admin/bones",
|
||||||
|
"color": "#e0e0e0",
|
||||||
|
"animate": "shimmer",
|
||||||
|
"shimmerColor": "#f0f0f0",
|
||||||
|
"speed": "1.2s",
|
||||||
|
"shimmerAngle": 110,
|
||||||
|
"wait": 3000,
|
||||||
|
"routes": [
|
||||||
|
"/",
|
||||||
|
"/users",
|
||||||
|
"/attendance",
|
||||||
|
"/attendance/history",
|
||||||
|
"/attendance/admin",
|
||||||
|
"/attendance/balances",
|
||||||
|
"/attendance/requests",
|
||||||
|
"/attendance/approval",
|
||||||
|
"/attendance/create",
|
||||||
|
"/trips",
|
||||||
|
"/trips/history",
|
||||||
|
"/trips/admin",
|
||||||
|
"/vehicles",
|
||||||
|
"/offers",
|
||||||
|
"/offers/new",
|
||||||
|
"/offers/customers",
|
||||||
|
"/offers/templates",
|
||||||
|
"/orders",
|
||||||
|
"/orders/1",
|
||||||
|
"/projects",
|
||||||
|
"/projects/80",
|
||||||
|
"/invoices",
|
||||||
|
"/invoices/new",
|
||||||
|
"/settings",
|
||||||
|
"/audit-log"
|
||||||
|
]
|
||||||
|
}
|
||||||
450
docs/superpowers/specs/2026-06-05-plan-praci-design.md
Normal file
450
docs/superpowers/specs/2026-06-05-plan-praci-design.md
Normal file
@@ -0,0 +1,450 @@
|
|||||||
|
# Plán prací (Work Schedule) Module Design
|
||||||
|
|
||||||
|
**Date:** 2026-06-05
|
||||||
|
**Status:** Approved
|
||||||
|
**Module:** Work schedule / Rozpis prací for boha-app-ts
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
A new module under the "Docházka" sidebar section that lets a foreman plan
|
||||||
|
each employee's work on a per-day basis, weeks or months in advance, and lets
|
||||||
|
every employee see what they (and the team) are supposed to be doing on any
|
||||||
|
given day.
|
||||||
|
|
||||||
|
The reference for the UX is `simon/plan_boha.pdf` — a hand-rolled Excel grid
|
||||||
|
with employees as columns and dates as rows, each cell holding a free-text
|
||||||
|
task description. The module replaces that spreadsheet with a live, audited,
|
||||||
|
permission-aware grid in the existing admin app.
|
||||||
|
|
||||||
|
A plan entry is **what should happen**. It is intentionally separate from
|
||||||
|
attendance (which records **what actually happened**). The two are not
|
||||||
|
auto-linked.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Core
|
||||||
|
|
||||||
|
- Plan entries are stored as **date ranges** (e.g. "PLC upgrade VW USA"
|
||||||
|
from 8.6. to 26.6.), with an optional **per-day override** for the rare
|
||||||
|
case where one day in a range is different (e.g. "Volno po noční").
|
||||||
|
- Each entry has:
|
||||||
|
- `user_id` — the employee this plan is for.
|
||||||
|
- `date_from` / `date_to` — inclusive range.
|
||||||
|
- `project_id` — **optional** FK to the existing `projects` table.
|
||||||
|
- `category` — enum (see below), drives color-coding and reports.
|
||||||
|
- `note` — required free-text task description (max 500 chars).
|
||||||
|
- The project dropdown is populated from the existing `projects` table.
|
||||||
|
No new "task" or "sub-project" entity — the note is the human-readable
|
||||||
|
task description.
|
||||||
|
- A cell can be empty (unassigned / not planned). An empty cell is also
|
||||||
|
clickable for admins — opens the create-entry modal.
|
||||||
|
- A `work_plan_overrides` row covers a single `(user, date)` and takes
|
||||||
|
precedence over the range that would otherwise cover that day.
|
||||||
|
|
||||||
|
### Effective-cell resolution (runtime)
|
||||||
|
|
||||||
|
To compute the cell for user `U` on date `D`:
|
||||||
|
|
||||||
|
1. Look up `work_plan_overrides` for `(U, D)`. If present, use it.
|
||||||
|
2. Otherwise, look up `work_plan_entries` where `user_id = U` and
|
||||||
|
`date_from <= D <= date_to`. If multiple match, return the
|
||||||
|
**last-created** one and write a warning to the audit log.
|
||||||
|
3. Otherwise, the cell is empty.
|
||||||
|
|
||||||
|
### Editing rules
|
||||||
|
|
||||||
|
- **Lock past, free future.** Cells with `shift_date < today` are
|
||||||
|
read-only. Admins can override with `?force=1` on the API; the
|
||||||
|
override is recorded in the audit log.
|
||||||
|
- Today and future are always editable for users with `attendance.manage`.
|
||||||
|
- The modal offers three actions when editing a cell inside an existing
|
||||||
|
range:
|
||||||
|
- "Upravit celý rozsah" — edit the range.
|
||||||
|
- "Upravit pouze tento den" — creates an override.
|
||||||
|
- "Zrušit přiřazení tohoto dne" — creates an override with
|
||||||
|
`category = 'other'` and empty note, leaving the cell empty for
|
||||||
|
that day only.
|
||||||
|
|
||||||
|
### Categories
|
||||||
|
|
||||||
|
A new enum `plan_category` for color-coding and reports:
|
||||||
|
|
||||||
|
| Value | Czech label | Cell color hint |
|
||||||
|
| ------------- | -------------- | --------------- |
|
||||||
|
| `work` | Práce | blue |
|
||||||
|
| `preparation` | Příprava | teal |
|
||||||
|
| `travel` | Cesta / Montáž | amber |
|
||||||
|
| `leave` | Dovolená | green |
|
||||||
|
| `sick` | Nemoc | red |
|
||||||
|
| `training` | Školení | purple |
|
||||||
|
| `other` | Jiné | gray |
|
||||||
|
|
||||||
|
Plan overrides for leave/sick are **informational only**. They do not
|
||||||
|
create or modify `leave_requests` or `attendance` rows. Employees still
|
||||||
|
file leave through the existing `Žádosti` flow.
|
||||||
|
|
||||||
|
### Visibility & permissions
|
||||||
|
|
||||||
|
- **Single sidebar entry** under Docházka: `Plán prací` → `/attendance/plan`.
|
||||||
|
- The sidebar entry is gated by `attendance.manage || attendance.record`
|
||||||
|
(mirrors the existing `Žádosti` entry).
|
||||||
|
- The page is **one** (`PlanWork.tsx`):
|
||||||
|
- If `useAuth().hasPermission('attendance.manage')` → editor mode
|
||||||
|
(grid + edit modal + create/edit/delete affordances).
|
||||||
|
- Otherwise → view-only mode (same grid, read-only detail modal).
|
||||||
|
- All endpoints require `attendance.manage` for writes, and either
|
||||||
|
`attendance.manage` or `attendance.record` for reads. Employees
|
||||||
|
with `attendance.record` are scoped server-side to their own
|
||||||
|
`user_id` for any direct row read; the grid endpoint handles the
|
||||||
|
scoping transparently.
|
||||||
|
- Admin role bypasses all permission checks (existing behavior).
|
||||||
|
|
||||||
|
### Grid
|
||||||
|
|
||||||
|
- Default view is **week** (T23, T24, T25 … matches the PDF's week
|
||||||
|
numbering). A toggle at the top switches to **month** view.
|
||||||
|
- The grid is `employees × dates`. Columns are ordered by
|
||||||
|
role/team first, then alphabetically by name.
|
||||||
|
- Columns are users with the `attendance.record` permission (which
|
||||||
|
includes admin). A "Aktivní" toggle in the toolbar lets the planner
|
||||||
|
hide inactive users.
|
||||||
|
- Each cell shows: a colored chip for the category, the project name
|
||||||
|
(if any) in bold, and the note underneath. Empty cells are blank.
|
||||||
|
- Weekend cells have a subtle yellow background tint to match the
|
||||||
|
PDF's "So 6.6. ★" rows.
|
||||||
|
- Read-only employees see the same grid, but cells are non-clickable
|
||||||
|
for editing. A click opens a read-only detail modal showing project,
|
||||||
|
category, note, "Vytvořil: <user> · <date>" (the entry's
|
||||||
|
`created_by`), and (if the cell is part of a range) "Patří do
|
||||||
|
rozsahu: <date_from> – <date_to>".
|
||||||
|
|
||||||
|
### Audit
|
||||||
|
|
||||||
|
Every create/update/delete of `work_plan_entries` and
|
||||||
|
`work_plan_overrides` writes a row to `audit_logs` with
|
||||||
|
`entity_type = 'work_plan_entry' | 'work_plan_override'` and full
|
||||||
|
`old_values` / `new_values` JSON, following the same pattern as
|
||||||
|
`attendance` and `projects`. The `?force=1` past-edit override is
|
||||||
|
recorded in the description field.
|
||||||
|
|
||||||
|
### Non-goals (out of scope for v1)
|
||||||
|
|
||||||
|
- No automatic link to attendance (plan stays independent).
|
||||||
|
- No time-slot granularity (full days only).
|
||||||
|
- No shift / payroll calculation.
|
||||||
|
- No drag-fill on the grid.
|
||||||
|
- No "task list" entity — projects and free text only.
|
||||||
|
- No notification/email when a plan is changed.
|
||||||
|
- No browser tests (the codebase has none; manual verification in dev).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Module placement
|
||||||
|
|
||||||
|
- New module under the **Docházka** sidebar section.
|
||||||
|
- Reuses the existing `attendance.shift_date` concept (date column on
|
||||||
|
the `attendance` table) — the planner lives next to the calendar it
|
||||||
|
informs.
|
||||||
|
- No "administrativa" module exists; the sidebar "Administrativa"
|
||||||
|
section is the commercial back-office (offers, orders, invoices,
|
||||||
|
projects, customers) and is not the right home for HR-style planning.
|
||||||
|
|
||||||
|
### File layout
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── routes/admin/plan.ts # Fastify routes
|
||||||
|
├── services/plan.service.ts # Business logic
|
||||||
|
├── schemas/plan.schema.ts # Zod validation
|
||||||
|
└── __tests__/plan.test.ts # Vitest + Supertest tests
|
||||||
|
|
||||||
|
src/admin/
|
||||||
|
├── pages/PlanWork.tsx # The single page (editor or view-only)
|
||||||
|
├── hooks/usePlanWork.ts # State, modal, mutations
|
||||||
|
├── lib/queries/plan.ts # React Query queryOptions
|
||||||
|
└── components/
|
||||||
|
├── PlanGrid.tsx # Week/month grid (shared by both modes)
|
||||||
|
├── PlanCellModal.tsx # Edit modal (create / edit-range / override)
|
||||||
|
├── PlanCellDetailModal.tsx # Read-only detail modal
|
||||||
|
├── PlanRangeChips.tsx # Cell content chip with category color
|
||||||
|
└── plan.css # Module-specific styles only
|
||||||
|
```
|
||||||
|
|
||||||
|
The new CSS file holds only category color helpers and grid-specific
|
||||||
|
overrides. All form/modal/table styling reuses existing classes
|
||||||
|
(`.admin-table`, `.admin-table-sticky`, `FormField`, `FormModal`,
|
||||||
|
`ConfirmModal`, `AdminDatePicker`, etc.) — no new design tokens.
|
||||||
|
|
||||||
|
### React Query keys
|
||||||
|
|
||||||
|
Per the project's "invalidate the full domain" convention:
|
||||||
|
|
||||||
|
- `['plan', 'grid', { dateFrom, dateTo, view }]`
|
||||||
|
- `['plan', 'entries', { userId, dateFrom, dateTo }]`
|
||||||
|
- `['plan', 'overrides', { userId, dateFrom, dateTo }]`
|
||||||
|
- `['plan', 'users']`
|
||||||
|
|
||||||
|
A mutation on any plan row invalidates `['plan']` (covers all four
|
||||||
|
sub-queries by prefix match).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Database Schema
|
||||||
|
|
||||||
|
### New enum
|
||||||
|
|
||||||
|
```prisma
|
||||||
|
enum plan_category {
|
||||||
|
work
|
||||||
|
preparation
|
||||||
|
travel
|
||||||
|
leave
|
||||||
|
sick
|
||||||
|
training
|
||||||
|
other
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### New table: `work_plan_entries`
|
||||||
|
|
||||||
|
| Column | Type | Notes |
|
||||||
|
| ------------ | ------------------------ | ------------------------------------------------------- |
|
||||||
|
| `id` | int PK autoincrement | |
|
||||||
|
| `user_id` | int FK → `users(id)` | NOT NULL, indexed |
|
||||||
|
| `date_from` | Date | NOT NULL — first day of the range |
|
||||||
|
| `date_to` | Date | NOT NULL — last day of the range, must be ≥ `date_from` |
|
||||||
|
| `project_id` | int? FK → `projects(id)` | nullable — unlinked text entries are allowed |
|
||||||
|
| `category` | enum `plan_category` | NOT NULL, default `'work'` |
|
||||||
|
| `note` | varchar(500) | NOT NULL — free-text task description |
|
||||||
|
| `created_by` | int FK → `users(id)` | who entered it |
|
||||||
|
| `created_at` | DateTime | Prisma default `now()` |
|
||||||
|
| `updated_at` | DateTime | Prisma default `now()` |
|
||||||
|
| `is_deleted` | bool? default false | soft-delete |
|
||||||
|
|
||||||
|
Indexes:
|
||||||
|
|
||||||
|
- `(user_id, date_from)`
|
||||||
|
- `(user_id, date_to)`
|
||||||
|
- `(project_id)`
|
||||||
|
- `(date_from, date_to)` — for cross-user queries like
|
||||||
|
"what's planned for project X this month?"
|
||||||
|
|
||||||
|
### New table: `work_plan_overrides`
|
||||||
|
|
||||||
|
| Column | Type | Notes |
|
||||||
|
| ------------ | ------------------------ | ------------------------------------------------- |
|
||||||
|
| `id` | int PK autoincrement | |
|
||||||
|
| `user_id` | int FK → `users(id)` | NOT NULL, indexed |
|
||||||
|
| `shift_date` | Date | NOT NULL — the one day being overridden |
|
||||||
|
| `project_id` | int? FK → `projects(id)` | nullable |
|
||||||
|
| `category` | enum `plan_category` | NOT NULL — usually `'leave'`, `'sick'`, `'other'` |
|
||||||
|
| `note` | varchar(500) | NOT NULL |
|
||||||
|
| `created_by` | int FK → `users(id)` | |
|
||||||
|
| `created_at` | DateTime | |
|
||||||
|
| `updated_at` | DateTime | |
|
||||||
|
| `is_deleted` | bool? default false | soft-delete |
|
||||||
|
|
||||||
|
Indexes:
|
||||||
|
|
||||||
|
- **Unique** `(user_id, shift_date)` — exactly one non-deleted
|
||||||
|
override per user-day. MySQL unique indexes don't ignore
|
||||||
|
soft-deleted rows, so the service layer enforces "at most one
|
||||||
|
active override per `(user_id, shift_date)`" in application code
|
||||||
|
(the database unique constraint exists as a final safety net and
|
||||||
|
may be temporarily violated by soft-deleted rows, which is
|
||||||
|
acceptable). When restoring a soft-deleted override, the service
|
||||||
|
re-validates that no active override exists for the same day.
|
||||||
|
- `(shift_date)` — for cross-user "what's overridden today" queries.
|
||||||
|
|
||||||
|
### Read semantics (recap)
|
||||||
|
|
||||||
|
For user `U` and date `D`, the "effective" cell is:
|
||||||
|
|
||||||
|
1. Override `(U, D)` if it exists and is not soft-deleted.
|
||||||
|
2. Otherwise the latest `work_plan_entry` whose range covers `D`
|
||||||
|
for user `U` and is not soft-deleted. If multiple match, pick
|
||||||
|
the latest by `created_at` and write a warning to `audit_logs`.
|
||||||
|
3. Otherwise, empty.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API Surface
|
||||||
|
|
||||||
|
REST endpoints under `/api/admin/plan`. All routes use the existing
|
||||||
|
Zod-validated, `requirePermission`, `success`/`error` helpers, and
|
||||||
|
`logAudit` pattern. Czech error messages, following project convention.
|
||||||
|
|
||||||
|
| Method | Path | Permission | Body / Query | Returns |
|
||||||
|
| ------ | --------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- |
|
||||||
|
| GET | `/plan/grid` | `attendance.manage` OR `attendance.record` | `?date_from=&date_to=&view=week\|month` (range ≤ 92 days) | `{ days, users, cells }` — effective cells ready to render |
|
||||||
|
| GET | `/plan/entries` | `attendance.manage` OR `attendance.record` (employee scoped to self) | `?user_id=&date_from=&date_to=` | raw `work_plan_entries` rows in range |
|
||||||
|
| GET | `/plan/overrides` | `attendance.manage` OR `attendance.record` (employee scoped to self) | `?user_id=&date_from=&date_to=` | raw `work_plan_overrides` rows in range |
|
||||||
|
| GET | `/plan/users` | `attendance.manage` OR `attendance.record` | — | users with `attendance.record`, ordered by role/team then name |
|
||||||
|
| POST | `/plan/entries` | `attendance.manage` | `{ user_id, date_from, date_to, project_id?, category, note }` | created entry |
|
||||||
|
| PATCH | `/plan/entries/:id` | `attendance.manage` | partial of create body | updated entry |
|
||||||
|
| DELETE | `/plan/entries/:id` | `attendance.manage` | `?force=1` to bypass past-date lock | `{ ok: true }` (soft-delete) |
|
||||||
|
| POST | `/plan/overrides` | `attendance.manage` | `{ user_id, shift_date, project_id?, category, note }` | created override |
|
||||||
|
| PATCH | `/plan/overrides/:id` | `attendance.manage` | partial of create body | updated override |
|
||||||
|
| DELETE | `/plan/overrides/:id` | `attendance.manage` | `?force=1` | `{ ok: true }` (soft-delete) |
|
||||||
|
| GET | `/plan/audit` | `settings.audit` | `?entity_type=&entity_id=` | audit log entries for a row |
|
||||||
|
|
||||||
|
### Past-date lock
|
||||||
|
|
||||||
|
Server-enforced. POST/PATCH/DELETE with any `shift_date` / `date_from`
|
||||||
|
in the past returns 403 with a Czech error message:
|
||||||
|
|
||||||
|
```
|
||||||
|
Nelze upravovat plán pro datum v minulosti. Pro nouzovou opravu použijte ?force=1.
|
||||||
|
```
|
||||||
|
|
||||||
|
With `?force=1` and `attendance.manage`, the operation succeeds and
|
||||||
|
the audit log records `description = 'force-edit past date'`.
|
||||||
|
|
||||||
|
### Employee scoping
|
||||||
|
|
||||||
|
`GET /plan/entries` and `GET /plan/overrides` accept `?user_id=`. For
|
||||||
|
a user with only `attendance.record`, the service silently overrides
|
||||||
|
the query to scope to `user_id = auth.user.id`. The grid endpoint
|
||||||
|
returns the same data either way (employees see the full grid in
|
||||||
|
view-only mode).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Frontend Detail
|
||||||
|
|
||||||
|
### `PlanWork.tsx`
|
||||||
|
|
||||||
|
- Mounts and calls `useAuth()`. If `hasPermission('attendance.manage')`
|
||||||
|
→ editor state. Otherwise → view-only state.
|
||||||
|
- Renders the toolbar (view toggle, date navigator, active-toggle,
|
||||||
|
print) and `PlanGrid`.
|
||||||
|
- Owns the modal state machine for `PlanCellModal` (editor) or
|
||||||
|
`PlanCellDetailModal` (view).
|
||||||
|
|
||||||
|
### `PlanGrid.tsx`
|
||||||
|
|
||||||
|
- Pure presentational. Takes `users`, `days`, `cells` as props.
|
||||||
|
- Renders a `<table>` with sticky first column (date) and sticky
|
||||||
|
header (employee names).
|
||||||
|
- Each cell is a `<button>` (admin) or `<div>` (view-only) with the
|
||||||
|
colored chip + note.
|
||||||
|
- Calls `onCellClick(userId, date)` for the parent to open the modal.
|
||||||
|
- Reuses `.admin-table` and `.admin-table-sticky` from existing
|
||||||
|
stylesheets.
|
||||||
|
|
||||||
|
### `PlanCellModal.tsx` (editor)
|
||||||
|
|
||||||
|
Three modes, decided by what the user clicked:
|
||||||
|
|
||||||
|
- **Create** — empty cell. Fields: `user_id` (locked to clicked user,
|
||||||
|
can be switched), `date_from` (default = clicked date), `date_to`
|
||||||
|
(default = clicked date; "Jeden den" / "Rozsah dnů" toggle),
|
||||||
|
`project_id` (dropdown, populated from `projects`, nullable),
|
||||||
|
`category` (select), `note` (textarea, required).
|
||||||
|
- **Edit range** — cell is part of an existing range. Loads the
|
||||||
|
full range into the form. "Upravit celý rozsah" button is the
|
||||||
|
primary action.
|
||||||
|
- **Edit day in range** — cell is part of a range. Three buttons:
|
||||||
|
"Upravit celý rozsah" / "Upravit pouze tento den" /
|
||||||
|
"Zrušit přiřazení tohoto dne".
|
||||||
|
- **Edit single-day override** — cell is itself a `work_plan_overrides`
|
||||||
|
row. Standard edit form.
|
||||||
|
- Bottom: delete button (with `ConfirmModal`).
|
||||||
|
|
||||||
|
### `PlanCellDetailModal.tsx` (view-only)
|
||||||
|
|
||||||
|
Read-only. Shows project, category, note, "Vytvořil: <full name of
|
||||||
|
`created_by`> · <`created_at` in local Czech time>", and (if the
|
||||||
|
cell is part of a range) "Patří do rozsahu: <date_from> – <date_to>".
|
||||||
|
For override cells, the "Vytvořil" line refers to the override's own
|
||||||
|
`created_by` (not the parent range's). No edit, no delete.
|
||||||
|
|
||||||
|
### `usePlanWork.ts`
|
||||||
|
|
||||||
|
Owns:
|
||||||
|
|
||||||
|
- `view: 'week' | 'month'`, `anchorDate`, `filterActive`
|
||||||
|
- `effectiveCells` from `['plan', 'grid']` query
|
||||||
|
- `entries` and `overrides` for the cell being edited
|
||||||
|
- `modalState: { mode, userId, date, entryId?, overrideId? }`
|
||||||
|
- `createEntry`, `updateEntry`, `deleteEntry`,
|
||||||
|
`createOverride`, `updateOverride`, `deleteOverride` —
|
||||||
|
React Query mutations that invalidate `['plan']`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Migration
|
||||||
|
|
||||||
|
Single new migration:
|
||||||
|
|
||||||
|
`prisma/migrations/<timestamp>_add_work_plan/`
|
||||||
|
|
||||||
|
- `migration.sql`:
|
||||||
|
1. `CREATE TABLE work_plan_entries (...)` with columns and indexes.
|
||||||
|
2. `CREATE TABLE work_plan_overrides (...)` with columns and indexes.
|
||||||
|
3. `CREATE TYPE plan_category` (or in-table enum, per Prisma's
|
||||||
|
MySQL output).
|
||||||
|
|
||||||
|
No data migration. No `seed.ts` change. No new permission keys.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
`src/__tests__/plan.test.ts` — Vitest + Supertest against the real
|
||||||
|
test database (`.env.test`):
|
||||||
|
|
||||||
|
1. **Effective-cell resolution** — range + override returns the
|
||||||
|
override for that day, the range for the other days, `null`
|
||||||
|
for uncovered days.
|
||||||
|
2. **Past-date lock** — POST with `date_from < today` returns 403
|
||||||
|
for users without `attendance.manage`; allowed with `?force=1`
|
||||||
|
for users with `attendance.manage`; audit log records the force.
|
||||||
|
3. **Employee self-view scoping** — employee with `attendance.record`
|
||||||
|
calling `GET /plan/entries?user_id=<other>` is scoped to self.
|
||||||
|
4. **Soft-delete + is_deleted** — deleted rows are excluded from
|
||||||
|
`/plan/grid` but kept in `/plan/audit`.
|
||||||
|
5. **Project FK nullability** — entries with `project_id = null`
|
||||||
|
and `category = 'leave'` are valid and render correctly.
|
||||||
|
6. **Range overlap** — two ranges for the same `(user, day)` does
|
||||||
|
not error; the latest one wins; a warning is logged.
|
||||||
|
7. **Audit log on every write** — POST/PATCH/DELETE each insert
|
||||||
|
exactly one `audit_logs` row with `entity_type`,
|
||||||
|
`old_values`, `new_values`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Release Plan
|
||||||
|
|
||||||
|
1. Bump `package.json` version (minor, since new module).
|
||||||
|
2. `npm run build` — confirm clean compile.
|
||||||
|
3. Commit + push to Gitea.
|
||||||
|
4. Tarball + deploy to production via the existing release script
|
||||||
|
(per `CLAUDE.md` "Release Process" section).
|
||||||
|
5. `npx prisma migrate deploy` on prod.
|
||||||
|
6. `pm2 restart app-ts --update-env`.
|
||||||
|
7. Smoke test: log in, open Docházka → Plán prací, add a one-day
|
||||||
|
entry for yourself, reload, confirm it shows.
|
||||||
|
|
||||||
|
The deployment follows the same pattern as the warehouse module
|
||||||
|
release (see commit `5233db2` and the `2026-05-29-warehouse-module`
|
||||||
|
spec for reference).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Open items / future work
|
||||||
|
|
||||||
|
- Month view polish if the toggle proves popular.
|
||||||
|
- Drag-fill on the grid (out of scope for v1).
|
||||||
|
- Optional tie-in to attendance: pre-fill `notes` on
|
||||||
|
`AttendanceCreate` from today's plan (read-only hint). Not
|
||||||
|
pursued in v1.
|
||||||
|
- "Patří do rozsahu" link in the detail modal: clickable
|
||||||
|
jump to the range's full detail.
|
||||||
|
- Per-team filtering (if a "team" concept is added to `users` later).
|
||||||
412
package-lock.json
generated
412
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "app-ts",
|
"name": "app-ts",
|
||||||
"version": "1.5.3",
|
"version": "1.9.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "app-ts",
|
"name": "app-ts",
|
||||||
"version": "1.5.3",
|
"version": "1.9.0",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"@fastify/rate-limit": "^10.3.0",
|
"@fastify/rate-limit": "^10.3.0",
|
||||||
"@fastify/static": "^9.0.0",
|
"@fastify/static": "^9.0.0",
|
||||||
"@prisma/client": "^6.19.2",
|
"@prisma/client": "^6.19.2",
|
||||||
|
"@tanstack/react-query": "^5.100.5",
|
||||||
"@types/jsdom": "^28.0.1",
|
"@types/jsdom": "^28.0.1",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
@@ -350,21 +351,21 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@emnapi/core": {
|
"node_modules/@emnapi/core": {
|
||||||
"version": "1.9.0",
|
"version": "1.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
||||||
"integrity": "sha512-0DQ98G9ZQZOxfUcQn1waV2yS8aWdZ6kJMbYCJB3oUBecjWYO1fqJ+a1DRfPF3O5JEkwqwP1A9QEN/9mYm2Yd0w==",
|
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@emnapi/wasi-threads": "1.2.0",
|
"@emnapi/wasi-threads": "1.2.1",
|
||||||
"tslib": "^2.4.0"
|
"tslib": "^2.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@emnapi/runtime": {
|
"node_modules/@emnapi/runtime": {
|
||||||
"version": "1.9.0",
|
"version": "1.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
|
||||||
"integrity": "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw==",
|
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
@@ -373,9 +374,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@emnapi/wasi-threads": {
|
"node_modules/@emnapi/wasi-threads": {
|
||||||
"version": "1.2.0",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
|
||||||
"integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==",
|
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
@@ -1099,9 +1100,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@fastify/static": {
|
"node_modules/@fastify/static": {
|
||||||
"version": "9.0.0",
|
"version": "9.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.1.3.tgz",
|
||||||
"integrity": "sha512-r64H8Woe/vfilg5RTy7lwWlE8ZZcTrc3kebYFMEUBrMqlydhQyoiExQXdYAy2REVpST/G35+stAM8WYp1WGmMA==",
|
"integrity": "sha512-aXrYtsiryLhRxRNaxNqsn7FUISeb7rB9q4eHUPIot5aeQBLNahnz1m6thzm7JWC1poSGXS9XrX8DvuMivp2hkQ==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -1192,20 +1193,22 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@napi-rs/wasm-runtime": {
|
"node_modules/@napi-rs/wasm-runtime": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz",
|
||||||
"integrity": "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==",
|
"integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@emnapi/core": "^1.7.1",
|
|
||||||
"@emnapi/runtime": "^1.7.1",
|
|
||||||
"@tybys/wasm-util": "^0.10.1"
|
"@tybys/wasm-util": "^0.10.1"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "github",
|
"type": "github",
|
||||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@emnapi/core": "^1.7.1",
|
||||||
|
"@emnapi/runtime": "^1.7.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@noble/hashes": {
|
"node_modules/@noble/hashes": {
|
||||||
@@ -1220,20 +1223,10 @@
|
|||||||
"url": "https://paulmillr.com/funding/"
|
"url": "https://paulmillr.com/funding/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@oxc-project/runtime": {
|
|
||||||
"version": "0.115.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@oxc-project/runtime/-/runtime-0.115.0.tgz",
|
|
||||||
"integrity": "sha512-Rg8Wlt5dCbXhQnsXPrkOjL1DTSvXLgb2R/KYfnf1/K+R0k6UMLEmbQXPM+kwrWqSmWA2t0B1EtHy2/3zikQpvQ==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": "^20.19.0 || >=22.12.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@oxc-project/types": {
|
"node_modules/@oxc-project/types": {
|
||||||
"version": "0.115.0",
|
"version": "0.130.0",
|
||||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.115.0.tgz",
|
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.130.0.tgz",
|
||||||
"integrity": "sha512-4n91DKnebUS4yjUHl2g3/b2T+IUdCfmoZGhmwsovZCDaJSs+QkVAM+0AqqTxHSsHfeiMuueT75cZaZcT/m0pSw==",
|
"integrity": "sha512-ibD2usx9JRu7f5pu2tMKMI4cpA4NgXJQoYRP4pQ7Pxmn1l6k/53qWtQWZayhYy3X4QZkt90Ot+mJEaeXouio6Q==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
@@ -1292,34 +1285,34 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@prisma/config": {
|
"node_modules/@prisma/config": {
|
||||||
"version": "6.19.2",
|
"version": "6.19.3",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.19.2.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.19.3.tgz",
|
||||||
"integrity": "sha512-kadBGDl+aUswv/zZMk9Mx0C8UZs1kjao8H9/JpI4Wh4SHZaM7zkTwiKn/iFLfRg+XtOAo/Z/c6pAYhijKl0nzQ==",
|
"integrity": "sha512-CBPT44BjlQxEt8kiMEauji2WHTDoVBOKl7UlewXmUgBPnr/oPRZC3psci5chJnYmH0ivEIog2OU9PGWoki3DLQ==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"c12": "3.1.0",
|
"c12": "3.1.0",
|
||||||
"deepmerge-ts": "7.1.5",
|
"deepmerge-ts": "7.1.5",
|
||||||
"effect": "3.18.4",
|
"effect": "3.21.0",
|
||||||
"empathic": "2.0.0"
|
"empathic": "2.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@prisma/debug": {
|
"node_modules/@prisma/debug": {
|
||||||
"version": "6.19.2",
|
"version": "6.19.3",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.19.2.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.19.3.tgz",
|
||||||
"integrity": "sha512-lFnEZsLdFLmEVCVNdskLDCL8Uup41GDfU0LUfquw+ercJC8ODTuL0WNKgOKmYxCJVvFwf0OuZBzW99DuWmoH2A==",
|
"integrity": "sha512-ljkJ+SgpXNktLG0Q/n4JGYCkKf0f8oYLyjImS2I8e2q2WCfdRRtWER062ZV/ixaNP2M2VKlWXVJiGzZaUgbKZw==",
|
||||||
"license": "Apache-2.0"
|
"license": "Apache-2.0"
|
||||||
},
|
},
|
||||||
"node_modules/@prisma/engines": {
|
"node_modules/@prisma/engines": {
|
||||||
"version": "6.19.2",
|
"version": "6.19.3",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.19.2.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.19.3.tgz",
|
||||||
"integrity": "sha512-TTkJ8r+uk/uqczX40wb+ODG0E0icVsMgwCTyTHXehaEfb0uo80M9g1aW1tEJrxmFHeOZFXdI2sTA1j1AgcHi4A==",
|
"integrity": "sha512-RSYxtlYFl5pJ8ZePgMv0lZ9IzVCOdTPOegrs2qcbAEFrBI1G33h6wyC9kjQvo0DnYEhEVY0X4LsuFHXLKQk88g==",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@prisma/debug": "6.19.2",
|
"@prisma/debug": "6.19.3",
|
||||||
"@prisma/engines-version": "7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7",
|
"@prisma/engines-version": "7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7",
|
||||||
"@prisma/fetch-engine": "6.19.2",
|
"@prisma/fetch-engine": "6.19.3",
|
||||||
"@prisma/get-platform": "6.19.2"
|
"@prisma/get-platform": "6.19.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@prisma/engines-version": {
|
"node_modules/@prisma/engines-version": {
|
||||||
@@ -1329,23 +1322,23 @@
|
|||||||
"license": "Apache-2.0"
|
"license": "Apache-2.0"
|
||||||
},
|
},
|
||||||
"node_modules/@prisma/fetch-engine": {
|
"node_modules/@prisma/fetch-engine": {
|
||||||
"version": "6.19.2",
|
"version": "6.19.3",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.19.2.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.19.3.tgz",
|
||||||
"integrity": "sha512-h4Ff4Pho+SR1S8XerMCC12X//oY2bG3Iug/fUnudfcXEUnIeRiBdXHFdGlGOgQ3HqKgosTEhkZMvGM9tWtYC+Q==",
|
"integrity": "sha512-tKtl/qco9Nt7LU5iKhpultD8O4vMCZcU2CHjNTnRrL1QvSUr5W/GcyFPjNL87GtRrwBc7ubXXD9xy4EvLvt8JA==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@prisma/debug": "6.19.2",
|
"@prisma/debug": "6.19.3",
|
||||||
"@prisma/engines-version": "7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7",
|
"@prisma/engines-version": "7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7",
|
||||||
"@prisma/get-platform": "6.19.2"
|
"@prisma/get-platform": "6.19.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@prisma/get-platform": {
|
"node_modules/@prisma/get-platform": {
|
||||||
"version": "6.19.2",
|
"version": "6.19.3",
|
||||||
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.19.2.tgz",
|
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.19.3.tgz",
|
||||||
"integrity": "sha512-PGLr06JUSTqIvztJtAzIxOwtWKtJm5WwOG6xpsgD37Rc84FpfUBGLKz65YpJBGtkRQGXTYEFie7pYALocC3MtA==",
|
"integrity": "sha512-xFj1VcJ1N3MKooOQAGO0W5tsd0W2QzIvW7DD7c/8H14Zmp4jseeWAITm+w2LLoLrlhoHdPPh0NMZ8mfL6puoHA==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@prisma/debug": "6.19.2"
|
"@prisma/debug": "6.19.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@puppeteer/browsers": {
|
"node_modules/@puppeteer/browsers": {
|
||||||
@@ -1379,9 +1372,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-android-arm64": {
|
"node_modules/@rolldown/binding-android-arm64": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.1.tgz",
|
||||||
"integrity": "sha512-lcJL0bN5hpgJfSIz/8PIf02irmyL43P+j1pTCfbD1DbLkmGRuFIA4DD3B3ZOvGqG0XiVvRznbKtN0COQVaKUTg==",
|
"integrity": "sha512-fJI3I0r3C3Oj/zdBCpaCmBRZYf07xpaq4yCfDDoSFm+beWNzbIl26puW8RraUdugoJw/95zerNOn6jasAhzSmg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1396,9 +1389,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-darwin-arm64": {
|
"node_modules/@rolldown/binding-darwin-arm64": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.1.tgz",
|
||||||
"integrity": "sha512-J7Zk3kLYFsLtuH6U+F4pS2sYVzac0qkjcO5QxHS7OS7yZu2LRs+IXo+uvJ/mvpyUljDJ3LROZPoQfgBIpCMhdQ==",
|
"integrity": "sha512-cKnAhWEsV7TPcA/5EAteDp6KcJZBQ2G+BqE7zayMMi7kMvwRsbv7WT9aOnn0WNl4SKEIf43vjS31iUPu80nzXg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1413,9 +1406,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-darwin-x64": {
|
"node_modules/@rolldown/binding-darwin-x64": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.1.tgz",
|
||||||
"integrity": "sha512-iwtmmghy8nhfRGeNAIltcNXzD0QMNaaA5U/NyZc1Ia4bxrzFByNMDoppoC+hl7cDiUq5/1CnFthpT9n+UtfFyg==",
|
"integrity": "sha512-YKrVwQjIRBPo+5G/u03wGjbdy4q7pyzCe93DK9VJ7zkVmeg8LJ7GbgsiHWdR4xSoe4CAXRD7Bcjgbtr64bkXNg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1430,9 +1423,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-freebsd-x64": {
|
"node_modules/@rolldown/binding-freebsd-x64": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.1.tgz",
|
||||||
"integrity": "sha512-DLFYI78SCiZr5VvdEplsVC2Vx53lnA4/Ga5C65iyldMVaErr86aiqCoNBLl92PXPfDtUYjUh+xFFor40ueNs4Q==",
|
"integrity": "sha512-z/oBsREo46SsFqBwYtFe0kpJeBijAT48O/WXLI4suiCLBkr03RTtTJMCzSdDd2znlh8VJizL09XVkQgk8IZonw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1447,9 +1440,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.1.tgz",
|
||||||
"integrity": "sha512-CsjTmTwd0Hri6iTw/DRMK7kOZ7FwAkrO4h8YWKoX/kcj833e4coqo2wzIFywtch/8Eb5enQ/lwLM7w6JX1W5RQ==",
|
"integrity": "sha512-ik8q7GM11zxvYxFc2PeDcT6TBvhCQMaUxfph/M5l9sKuTs/Sjg3L+Byw0F7w0ZVLBZmx30P+gG0ECzzN+MFcmQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
@@ -1464,9 +1457,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.1.tgz",
|
||||||
"integrity": "sha512-2x9O2JbSPxpxMDhP9Z74mahAStibTlrBMW0520+epJH5sac7/LwZW5Bmg/E6CXuEF53JJFW509uP+lSedaUNxg==",
|
"integrity": "sha512-QoSx2EkyrrdZ6kcyE8stqZ62t0Yra8Fs5ia9lOxJrh6TMQJK7gQKmscdTHf7pOXKREKrVwOtJcQG3qVSfc866A==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1481,9 +1474,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.1.tgz",
|
||||||
"integrity": "sha512-JA1QRW31ogheAIRhIg9tjMfsYbglXXYGNPLdPEYrwFxdbkQCAzvpSCSHCDWNl4hTtrol8WeboCSEpjdZK8qrCg==",
|
"integrity": "sha512-uwNwFpwKeNiZawfAWBgg0VIztPTV3ihhh1vV334h9ivnNLorxnQMU6Fz8wG1Zb4Qh9LC1/MkcyT3YlDXG3Rsgg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1498,9 +1491,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.1.tgz",
|
||||||
"integrity": "sha512-aOKU9dJheda8Kj8Y3w9gnt9QFOO+qKPAl8SWd7JPHP+Cu0EuDAE5wokQubLzIDQWg2myXq2XhTpOVS07qqvT+w==",
|
"integrity": "sha512-zY1bul7OWr7DFBiJ++wofXvnr8B45ce3QsQUhKrIhXsygAh7bTkwyeM1bi1a2g5C/yC/N8TZyGDEoMfm/l9mpg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
@@ -1515,9 +1508,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.1.tgz",
|
||||||
"integrity": "sha512-OalO94fqj7IWRn3VdXWty75jC5dk4C197AWEuMhIpvVv2lw9fiPhud0+bW2ctCxb3YoBZor71QHbY+9/WToadA==",
|
"integrity": "sha512-0frlsT/f4Ft6I7SMESTKnF3cZsdicQn1dCMkF/jT9wDLE+gGoiQfv1nmT9e+s7s/fekvvy6tZM2jHvI2tkbJDQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
@@ -1532,9 +1525,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.1.tgz",
|
||||||
"integrity": "sha512-cVEl1vZtBsBZna3YMjGXNvnYYrOJ7RzuWvZU0ffvJUexWkukMaDuGhUXn0rjnV0ptzGVkvc+vW9Yqy6h8YX4pg==",
|
"integrity": "sha512-XABVmGp9Tg0WspTVvwduTc4fpqy6JnAUrSQe6OuyqD/03nI7r0O9OWUkMIwFrjKAIqolvqoA4ZrJppgwE0Gxmw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1549,9 +1542,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-linux-x64-musl": {
|
"node_modules/@rolldown/binding-linux-x64-musl": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.1.tgz",
|
||||||
"integrity": "sha512-UzYnKCIIc4heAKgI4PZ3dfBGUZefGCJ1TPDuLHoCzgrMYPb5Rv6TLFuYtyM4rWyHM7hymNdsg5ik2C+UD9VDbA==",
|
"integrity": "sha512-bV4fzswuzVcKD90o/VM6QqKxnxlDq0g2BISDLNVmxrnhpv1DDbyPhCIjYfvzYLV+MvkKKnQt2Q6AO86SEBULUQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1566,9 +1559,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-openharmony-arm64": {
|
"node_modules/@rolldown/binding-openharmony-arm64": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.1.tgz",
|
||||||
"integrity": "sha512-+6zoiF+RRyf5cdlFQP7nm58mq7+/2PFaY2DNQeD4B87N36JzfF/l9mdBkkmTvSYcYPE8tMh/o3cRlsx1ldLfog==",
|
"integrity": "sha512-/Mh0Zhq3OP7fVs0kcQHZP6lZEthMGTaSf8UBQYSFEZDWGXXlEC+nJ6EqenaK2t4LBXMe3A+K/G2BVXXdtOr4PQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1583,9 +1576,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-wasm32-wasi": {
|
"node_modules/@rolldown/binding-wasm32-wasi": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.1.tgz",
|
||||||
"integrity": "sha512-rgFN6sA/dyebil3YTlL2evvi/M+ivhfnyxec7AccTpRPccno/rPoNlqybEZQBkcbZu8Hy+eqNJCqfBR8P7Pg8g==",
|
"integrity": "sha512-+1xc9X45l8ufsBAm6Gjvx2qDRIY9lTVt0cgWNcJ+1gdhXvkbxePA60yRTwSTuXL09CMhyJmjpV7E3NoyxbqFQQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"wasm32"
|
"wasm32"
|
||||||
],
|
],
|
||||||
@@ -1593,16 +1586,18 @@
|
|||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@napi-rs/wasm-runtime": "^1.1.1"
|
"@emnapi/core": "1.10.0",
|
||||||
|
"@emnapi/runtime": "1.10.0",
|
||||||
|
"@napi-rs/wasm-runtime": "^1.1.4"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.0.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.1.tgz",
|
||||||
"integrity": "sha512-lHVNUG/8nlF1IQk1C0Ci574qKYyty2goMiPlRqkC5R+3LkXDkL5Dhx8ytbxq35m+pkHVIvIxviD+TWLdfeuadA==",
|
"integrity": "sha512-1D+UqZdfnuR+Jy1GgMJwi85bD40H21uNmOPRWQhw4oRSuolZ/B5rixZ45DK2KXOTCvmVCecauWgEhbw8bI7tOw==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -1617,9 +1612,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.1.tgz",
|
||||||
"integrity": "sha512-G0oA4+w1iY5AGi5HcDTxWsoxF509hrFIPB2rduV5aDqS9FtDg1CAfa7V34qImbjfhIcA8C+RekocJZA96EarwQ==",
|
"integrity": "sha512-INAycaWuhlOK3wk4mRHGsdgwYWmd9cChdPdE9bwWmy6rn9VqVNYNFGhOdXrofXUxwHIncSiPNb8tNm8knDVIeQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -1646,6 +1641,32 @@
|
|||||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@tanstack/query-core": {
|
||||||
|
"version": "5.100.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.100.5.tgz",
|
||||||
|
"integrity": "sha512-t20KrhKkf0HXzqQkPbJ5erhFesup68BAbwFgYmTrS7bxMF7O5MdmL8jUkik4thsG7Hg00fblz30h6yF1d5TxGg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/tannerlinsley"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tanstack/react-query": {
|
||||||
|
"version": "5.100.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.100.5.tgz",
|
||||||
|
"integrity": "sha512-aNwj1mi2v2bQ9IxkyR1grLOUkv3BYWoykHy9KDyLNbjC3tsahbOHJibK+Wjtr1wRhG59/AvJhiJG5OlthaCgJA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@tanstack/query-core": "5.100.5"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/tannerlinsley"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^18 || ^19"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tokenizer/token": {
|
"node_modules/@tokenizer/token": {
|
||||||
"version": "0.3.0",
|
"version": "0.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
|
||||||
@@ -1659,9 +1680,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@tybys/wasm-util": {
|
"node_modules/@tybys/wasm-util": {
|
||||||
"version": "0.10.1",
|
"version": "0.10.2",
|
||||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
|
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
|
||||||
"integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==",
|
"integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
@@ -2306,9 +2327,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/basic-ftp": {
|
"node_modules/basic-ftp": {
|
||||||
"version": "5.2.0",
|
"version": "5.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz",
|
||||||
"integrity": "sha512-VoMINM2rqJwJgfdHq6RiUudKt2BV+FY5ZFezP/ypmwayk68+NzzAQy4XXLlqsGD4MCzq3DrmNFD/uUmBJuGoXw==",
|
"integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
@@ -2832,9 +2853,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/defu": {
|
"node_modules/defu": {
|
||||||
"version": "6.1.4",
|
"version": "6.1.7",
|
||||||
"resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz",
|
||||||
"integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==",
|
"integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/degenerator": {
|
"node_modules/degenerator": {
|
||||||
@@ -2919,9 +2940,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/dompurify": {
|
"node_modules/dompurify": {
|
||||||
"version": "3.3.3",
|
"version": "3.4.5",
|
||||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.5.tgz",
|
||||||
"integrity": "sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==",
|
"integrity": "sha512-OrwIBKsdNSVEeubdJ1HBv/wNENRM9ytAVCv7YXt//A3vPdVMNuACRqK9mXCGCBW2ln7BT/A4X0jXHo2Gu89miA==",
|
||||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@types/trusted-types": "^2.0.7"
|
"@types/trusted-types": "^2.0.7"
|
||||||
@@ -2964,9 +2985,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/effect": {
|
"node_modules/effect": {
|
||||||
"version": "3.18.4",
|
"version": "3.21.0",
|
||||||
"resolved": "https://registry.npmjs.org/effect/-/effect-3.18.4.tgz",
|
"resolved": "https://registry.npmjs.org/effect/-/effect-3.21.0.tgz",
|
||||||
"integrity": "sha512-b1LXQJLe9D11wfnOKAk3PKxuqYshQ0Heez+y5pnkd3jLj1yx9QhM72zZ9uUrOQyNvrs2GZZd/3maL0ZV18YuDA==",
|
"integrity": "sha512-PPN80qRokCd1f015IANNhrwOnLO7GrrMQfk4/lnZRE/8j7UPWrNNjPV0uBrZutI/nHzernbW+J0hdqQysHiSnQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@standard-schema/spec": "^1.0.0",
|
"@standard-schema/spec": "^1.0.0",
|
||||||
@@ -3358,9 +3379,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/fast-uri": {
|
"node_modules/fast-uri": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
|
||||||
"integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",
|
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -3374,9 +3395,9 @@
|
|||||||
"license": "BSD-3-Clause"
|
"license": "BSD-3-Clause"
|
||||||
},
|
},
|
||||||
"node_modules/fastify": {
|
"node_modules/fastify": {
|
||||||
"version": "5.8.4",
|
"version": "5.8.5",
|
||||||
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.4.tgz",
|
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.5.tgz",
|
||||||
"integrity": "sha512-sa42J1xylbBAYUWALSBoyXKPDUvM3OoNOibIefA+Oha57FryXKKCZarA1iDntOCWp3O35voZLuDg2mdODXtPzQ==",
|
"integrity": "sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -3885,9 +3906,9 @@
|
|||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/ip-address": {
|
"node_modules/ip-address": {
|
||||||
"version": "10.1.0",
|
"version": "10.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
|
||||||
"integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",
|
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 12"
|
"node": ">= 12"
|
||||||
@@ -4411,9 +4432,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/lodash-es": {
|
"node_modules/lodash-es": {
|
||||||
"version": "4.17.23",
|
"version": "4.18.1",
|
||||||
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.23.tgz",
|
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",
|
||||||
"integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==",
|
"integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/lodash.clonedeep": {
|
"node_modules/lodash.clonedeep": {
|
||||||
@@ -4615,9 +4636,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/nanoid": {
|
"node_modules/nanoid": {
|
||||||
"version": "3.3.11",
|
"version": "3.3.12",
|
||||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
|
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
|
||||||
"integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
|
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -4658,23 +4679,23 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/nodemailer": {
|
"node_modules/nodemailer": {
|
||||||
"version": "8.0.4",
|
"version": "8.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.7.tgz",
|
||||||
"integrity": "sha512-k+jf6N8PfQJ0Fe8ZhJlgqU5qJU44Lpvp2yvidH3vp1lPnVQMgi4yEEMPXg5eJS1gFIJTVq1NHBk7Ia9ARdSBdQ==",
|
"integrity": "sha512-pkjE4mkBzQjdJT4/UmlKl3pX0rC9fZmjh7c6C9o7lv66Ac6w9WCnzPzhbPNxwZAzlF4mdq4CSWB5+FbK6FWCow==",
|
||||||
"license": "MIT-0",
|
"license": "MIT-0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.0.0"
|
"node": ">=6.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/nypm": {
|
"node_modules/nypm": {
|
||||||
"version": "0.6.5",
|
"version": "0.6.6",
|
||||||
"resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.5.tgz",
|
"resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.6.tgz",
|
||||||
"integrity": "sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ==",
|
"integrity": "sha512-vRyr0r4cbBapw07Xw8xrj9Teq3o7MUD35rSaTcanDbW+aK2XHDgJFiU6ZTj2GBw7Q12ysdsyFss+Vdz4hQ0Y6Q==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"citty": "^0.2.0",
|
"citty": "^0.2.2",
|
||||||
"pathe": "^2.0.3",
|
"pathe": "^2.0.3",
|
||||||
"tinyexec": "^1.0.2"
|
"tinyexec": "^1.1.1"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"nypm": "dist/cli.mjs"
|
"nypm": "dist/cli.mjs"
|
||||||
@@ -4684,9 +4705,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/nypm/node_modules/citty": {
|
"node_modules/nypm/node_modules/citty": {
|
||||||
"version": "0.2.1",
|
"version": "0.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/citty/-/citty-0.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz",
|
||||||
"integrity": "sha512-kEV95lFBhQgtogAPlQfJJ0WGVSokvLr/UEoFPiKKOXF7pl98HfUVUD0ejsuTCld/9xH9vogSywZ5KqHzXrZpqg==",
|
"integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/object-inspect": {
|
"node_modules/object-inspect": {
|
||||||
@@ -4978,13 +4999,13 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/pkg-types": {
|
"node_modules/pkg-types": {
|
||||||
"version": "2.3.0",
|
"version": "2.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.1.tgz",
|
||||||
"integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==",
|
"integrity": "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"confbox": "^0.2.2",
|
"confbox": "^0.2.4",
|
||||||
"exsolve": "^1.0.7",
|
"exsolve": "^1.0.8",
|
||||||
"pathe": "^2.0.3"
|
"pathe": "^2.0.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -4998,9 +5019,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.8",
|
"version": "8.5.14",
|
||||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
|
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.14.tgz",
|
||||||
"integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==",
|
"integrity": "sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -5027,14 +5048,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/prisma": {
|
"node_modules/prisma": {
|
||||||
"version": "6.19.2",
|
"version": "6.19.3",
|
||||||
"resolved": "https://registry.npmjs.org/prisma/-/prisma-6.19.2.tgz",
|
"resolved": "https://registry.npmjs.org/prisma/-/prisma-6.19.3.tgz",
|
||||||
"integrity": "sha512-XTKeKxtQElcq3U9/jHyxSPgiRgeYDKxWTPOf6NkXA0dNj5j40MfEsZkMbyNpwDWCUv7YBFUl7I2VK/6ALbmhEg==",
|
"integrity": "sha512-++ZJ0ijLrDJF6hNB4t4uxg2br3fC4H9Yc9tcbjr2fcNFP3rh/SBNrAgjhsqBU4Ght8JPrVofG/ZkXfnSfnYsFg==",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@prisma/config": "6.19.2",
|
"@prisma/config": "6.19.3",
|
||||||
"@prisma/engines": "6.19.2"
|
"@prisma/engines": "6.19.3"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"prisma": "build/index.js"
|
"prisma": "build/index.js"
|
||||||
@@ -5553,14 +5574,14 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/rolldown": {
|
"node_modules/rolldown": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.1.tgz",
|
||||||
"integrity": "sha512-9EbgWge7ZH+yqb4d2EnELAntgPTWbfL8ajiTW+SyhJEC4qhBbkCKbqFV4Ge4zmu5ziQuVbWxb/XwLZ+RIO7E8Q==",
|
"integrity": "sha512-X0KQHljNnEkWNqqiz9zJrGunh1B0HgOxLXvnFpCOcadzcy5qohZ3tqMEUg00vncoRovXuK3ZqCT9KnnKzoInFQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@oxc-project/types": "=0.115.0",
|
"@oxc-project/types": "=0.130.0",
|
||||||
"@rolldown/pluginutils": "1.0.0-rc.9"
|
"@rolldown/pluginutils": "^1.0.0"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"rolldown": "bin/cli.mjs"
|
"rolldown": "bin/cli.mjs"
|
||||||
@@ -5569,27 +5590,27 @@
|
|||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@rolldown/binding-android-arm64": "1.0.0-rc.9",
|
"@rolldown/binding-android-arm64": "1.0.1",
|
||||||
"@rolldown/binding-darwin-arm64": "1.0.0-rc.9",
|
"@rolldown/binding-darwin-arm64": "1.0.1",
|
||||||
"@rolldown/binding-darwin-x64": "1.0.0-rc.9",
|
"@rolldown/binding-darwin-x64": "1.0.1",
|
||||||
"@rolldown/binding-freebsd-x64": "1.0.0-rc.9",
|
"@rolldown/binding-freebsd-x64": "1.0.1",
|
||||||
"@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.9",
|
"@rolldown/binding-linux-arm-gnueabihf": "1.0.1",
|
||||||
"@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.9",
|
"@rolldown/binding-linux-arm64-gnu": "1.0.1",
|
||||||
"@rolldown/binding-linux-arm64-musl": "1.0.0-rc.9",
|
"@rolldown/binding-linux-arm64-musl": "1.0.1",
|
||||||
"@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.9",
|
"@rolldown/binding-linux-ppc64-gnu": "1.0.1",
|
||||||
"@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.9",
|
"@rolldown/binding-linux-s390x-gnu": "1.0.1",
|
||||||
"@rolldown/binding-linux-x64-gnu": "1.0.0-rc.9",
|
"@rolldown/binding-linux-x64-gnu": "1.0.1",
|
||||||
"@rolldown/binding-linux-x64-musl": "1.0.0-rc.9",
|
"@rolldown/binding-linux-x64-musl": "1.0.1",
|
||||||
"@rolldown/binding-openharmony-arm64": "1.0.0-rc.9",
|
"@rolldown/binding-openharmony-arm64": "1.0.1",
|
||||||
"@rolldown/binding-wasm32-wasi": "1.0.0-rc.9",
|
"@rolldown/binding-wasm32-wasi": "1.0.1",
|
||||||
"@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.9",
|
"@rolldown/binding-win32-arm64-msvc": "1.0.1",
|
||||||
"@rolldown/binding-win32-x64-msvc": "1.0.0-rc.9"
|
"@rolldown/binding-win32-x64-msvc": "1.0.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/rolldown/node_modules/@rolldown/pluginutils": {
|
"node_modules/rolldown/node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-rc.9",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.9.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
|
||||||
"integrity": "sha512-w6oiRWgEBl04QkFZgmW+jnU1EC9b57Oihi2ot3HNWIQRqgHp5PnYDia5iZ5FF7rpa4EQdiqMDXjlqKGXBhsoXw==",
|
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
@@ -6147,23 +6168,23 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/tinyexec": {
|
"node_modules/tinyexec": {
|
||||||
"version": "1.0.4",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.1.2.tgz",
|
||||||
"integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==",
|
"integrity": "sha512-dAqSqE/RabpBKI8+h26GfLq6Vb3JVXs30XYQjdMjaj/c2tS8IYYMbIzP599KtRj7c57/wYApb3QjgRgXmrCukA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tinyglobby": {
|
"node_modules/tinyglobby": {
|
||||||
"version": "0.2.15",
|
"version": "0.2.16",
|
||||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",
|
||||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
"integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fdir": "^6.5.0",
|
"fdir": "^6.5.0",
|
||||||
"picomatch": "^4.0.3"
|
"picomatch": "^4.0.4"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12.0.0"
|
"node": ">=12.0.0"
|
||||||
@@ -6331,18 +6352,17 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "8.0.0",
|
"version": "8.0.13",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-8.0.13.tgz",
|
||||||
"integrity": "sha512-fPGaRNj9Zytaf8LEiBhY7Z6ijnFKdzU/+mL8EFBaKr7Vw1/FWcTBAMW0wLPJAGMPX38ZPVCVgLceWiEqeoqL2Q==",
|
"integrity": "sha512-MFtjBYgzmSxmgA4RAfjIyXWpGe1oALnjgUTzzV7QLx/TKxCzjtMH6Fd9/eVK+5Fg1qNoz5VAwsmMs/NofrmJvw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@oxc-project/runtime": "0.115.0",
|
|
||||||
"lightningcss": "^1.32.0",
|
"lightningcss": "^1.32.0",
|
||||||
"picomatch": "^4.0.3",
|
"picomatch": "^4.0.4",
|
||||||
"postcss": "^8.5.8",
|
"postcss": "^8.5.14",
|
||||||
"rolldown": "1.0.0-rc.9",
|
"rolldown": "1.0.1",
|
||||||
"tinyglobby": "^0.2.15"
|
"tinyglobby": "^0.2.16"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"vite": "bin/vite.js"
|
"vite": "bin/vite.js"
|
||||||
@@ -6358,8 +6378,8 @@
|
|||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/node": "^20.19.0 || >=22.12.0",
|
"@types/node": "^20.19.0 || >=22.12.0",
|
||||||
"@vitejs/devtools": "^0.0.0-alpha.31",
|
"@vitejs/devtools": "^0.1.18",
|
||||||
"esbuild": "^0.27.0",
|
"esbuild": "^0.27.0 || ^0.28.0",
|
||||||
"jiti": ">=1.21.0",
|
"jiti": ">=1.21.0",
|
||||||
"less": "^4.0.0",
|
"less": "^4.0.0",
|
||||||
"sass": "^1.70.0",
|
"sass": "^1.70.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "app-ts",
|
"name": "app-ts",
|
||||||
"version": "1.5.5",
|
"version": "1.9.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "dist/server.js",
|
"main": "dist/server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -17,7 +17,11 @@
|
|||||||
"db:push": "prisma db push",
|
"db:push": "prisma db push",
|
||||||
"db:studio": "prisma studio",
|
"db:studio": "prisma studio",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:watch": "vitest"
|
"test:watch": "vitest",
|
||||||
|
"seed": "tsx prisma/seed.ts"
|
||||||
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "tsx prisma/seed.ts"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -34,6 +38,7 @@
|
|||||||
"@fastify/rate-limit": "^10.3.0",
|
"@fastify/rate-limit": "^10.3.0",
|
||||||
"@fastify/static": "^9.0.0",
|
"@fastify/static": "^9.0.0",
|
||||||
"@prisma/client": "^6.19.2",
|
"@prisma/client": "^6.19.2",
|
||||||
|
"@tanstack/react-query": "^5.100.5",
|
||||||
"@types/jsdom": "^28.0.1",
|
"@types/jsdom": "^28.0.1",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
-- Add billing_text column to invoices table
|
|
||||||
ALTER TABLE `invoices` ADD COLUMN `billing_text` VARCHAR(500) NULL AFTER `issued_by`;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
-- Add lock fields to quotations table for pessimistic locking
|
|
||||||
ALTER TABLE `quotations` ADD COLUMN `locked_by` INT NULL AFTER `scope_description`;
|
|
||||||
ALTER TABLE `quotations` ADD COLUMN `locked_at` DATETIME NULL AFTER `locked_by`;
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
CREATE TABLE `invoice_alert_log` (
|
|
||||||
`id` INT NOT NULL AUTO_INCREMENT,
|
|
||||||
`invoice_type` VARCHAR(20) NOT NULL,
|
|
||||||
`invoice_id` INT NOT NULL,
|
|
||||||
`alert_type` VARCHAR(20) NOT NULL,
|
|
||||||
`sent_at` DATETIME(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `invoice_type_invoice_id_alert_type` (`invoice_type`, `invoice_id`, `alert_type`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE `invoices` ADD COLUMN `language` VARCHAR(5) DEFAULT 'cs' AFTER `billing_text`;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
-- Add file_path column for NAS storage of received invoice files
|
|
||||||
ALTER TABLE `received_invoices` ADD COLUMN `file_path` VARCHAR(500) NULL AFTER `file_data`;
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
-- Remove file_data (BLOB) and file_path columns — files are now stored on NAS
|
|
||||||
-- Path is derived from year, month, and file_name
|
|
||||||
ALTER TABLE `received_invoices` DROP COLUMN `file_data`;
|
|
||||||
ALTER TABLE `received_invoices` DROP COLUMN `file_path`;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE `company_settings` ADD COLUMN `logo_data_dark` MEDIUMBLOB NULL AFTER `logo_data`;
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
ALTER TABLE `company_settings`
|
|
||||||
ADD COLUMN `offer_number_pattern` VARCHAR(100) NULL,
|
|
||||||
ADD COLUMN `order_number_pattern` VARCHAR(100) NULL,
|
|
||||||
ADD COLUMN `invoice_number_pattern` VARCHAR(100) NULL;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
ALTER TABLE `company_settings`
|
|
||||||
ADD COLUMN `smtp_from` VARCHAR(255) NULL,
|
|
||||||
ADD COLUMN `smtp_from_name` VARCHAR(255) NULL;
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
-- System settings columns on company_settings
|
|
||||||
ALTER TABLE `company_settings`
|
|
||||||
ADD COLUMN `break_threshold_hours` DECIMAL(4,2) DEFAULT 6,
|
|
||||||
ADD COLUMN `break_duration_short` INT DEFAULT 15,
|
|
||||||
ADD COLUMN `break_duration_long` INT DEFAULT 30,
|
|
||||||
ADD COLUMN `clock_rounding_minutes` INT DEFAULT 15,
|
|
||||||
ADD COLUMN `invoice_alert_email` VARCHAR(255) NULL,
|
|
||||||
ADD COLUMN `leave_notify_email` VARCHAR(255) NULL,
|
|
||||||
ADD COLUMN `max_login_attempts` INT DEFAULT 5,
|
|
||||||
ADD COLUMN `lockout_minutes` INT DEFAULT 15,
|
|
||||||
ADD COLUMN `max_requests_per_minute` INT DEFAULT 300,
|
|
||||||
ADD COLUMN `available_vat_rates` LONGTEXT NULL,
|
|
||||||
ADD COLUMN `available_currencies` LONGTEXT NULL;
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
-- Create new unified permission
|
|
||||||
INSERT INTO permissions (name, display_name, description, module)
|
|
||||||
VALUES ('settings.manage', 'Správa nastavení', 'Správa všech nastavení systému', 'settings')
|
|
||||||
ON DUPLICATE KEY UPDATE display_name = VALUES(display_name);
|
|
||||||
|
|
||||||
-- Grant to all roles that had any of the old 3
|
|
||||||
INSERT IGNORE INTO role_permissions (role_id, permission_id)
|
|
||||||
SELECT DISTINCT rp.role_id, (SELECT id FROM permissions WHERE name = 'settings.manage')
|
|
||||||
FROM role_permissions rp
|
|
||||||
JOIN permissions p ON p.id = rp.permission_id
|
|
||||||
WHERE p.name IN ('offers.settings', 'settings.roles', 'settings.security');
|
|
||||||
|
|
||||||
-- Clean up old role_permissions
|
|
||||||
DELETE FROM role_permissions
|
|
||||||
WHERE permission_id IN (SELECT id FROM permissions WHERE name IN ('offers.settings', 'settings.roles', 'settings.security'));
|
|
||||||
|
|
||||||
-- Remove old permissions
|
|
||||||
DELETE FROM permissions WHERE name IN ('offers.settings', 'settings.roles', 'settings.security');
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
-- Add unique constraint on number_sequences(type, year) for atomic numbering
|
|
||||||
ALTER TABLE number_sequences ADD UNIQUE INDEX idx_number_sequences_type_year (`type`, `year`);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
-- AlterTable
|
|
||||||
ALTER TABLE `users` ADD COLUMN `totp_last_used_counter` INTEGER NULL;
|
|
||||||
@@ -98,6 +98,7 @@ CREATE TABLE `company_settings` (
|
|||||||
`vat_id` VARCHAR(50) NULL,
|
`vat_id` VARCHAR(50) NULL,
|
||||||
`custom_fields` LONGTEXT NULL,
|
`custom_fields` LONGTEXT NULL,
|
||||||
`logo_data` LONGBLOB NULL,
|
`logo_data` LONGBLOB NULL,
|
||||||
|
`logo_data_dark` MEDIUMBLOB NULL,
|
||||||
`quotation_prefix` VARCHAR(20) NULL,
|
`quotation_prefix` VARCHAR(20) NULL,
|
||||||
`default_currency` VARCHAR(10) NULL DEFAULT 'CZK',
|
`default_currency` VARCHAR(10) NULL DEFAULT 'CZK',
|
||||||
`default_vat_rate` DECIMAL(5, 2) NULL DEFAULT 21.00,
|
`default_vat_rate` DECIMAL(5, 2) NULL DEFAULT 21.00,
|
||||||
@@ -108,7 +109,24 @@ CREATE TABLE `company_settings` (
|
|||||||
`order_type_code` VARCHAR(10) NULL,
|
`order_type_code` VARCHAR(10) NULL,
|
||||||
`invoice_type_code` VARCHAR(10) NULL,
|
`invoice_type_code` VARCHAR(10) NULL,
|
||||||
`require_2fa` BOOLEAN NOT NULL DEFAULT false,
|
`require_2fa` BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
`break_threshold_hours` DECIMAL(4, 2) NULL DEFAULT 6.00,
|
||||||
|
`break_duration_short` INTEGER NULL DEFAULT 15,
|
||||||
|
`break_duration_long` INTEGER NULL DEFAULT 30,
|
||||||
|
`clock_rounding_minutes` INTEGER NULL DEFAULT 15,
|
||||||
|
`invoice_alert_email` VARCHAR(255) NULL,
|
||||||
|
`leave_notify_email` VARCHAR(255) NULL,
|
||||||
|
`max_login_attempts` INTEGER NULL DEFAULT 5,
|
||||||
|
`lockout_minutes` INTEGER NULL DEFAULT 15,
|
||||||
|
`max_requests_per_minute` INTEGER NULL DEFAULT 300,
|
||||||
|
`available_vat_rates` LONGTEXT NULL,
|
||||||
|
`available_currencies` LONGTEXT NULL,
|
||||||
|
`smtp_from` VARCHAR(255) NULL,
|
||||||
|
`smtp_from_name` VARCHAR(255) NULL,
|
||||||
|
`offer_number_pattern` VARCHAR(100) NULL,
|
||||||
|
`order_number_pattern` VARCHAR(100) NULL,
|
||||||
|
`invoice_number_pattern` VARCHAR(100) NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `company_settings_uuid_key`(`uuid`),
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
@@ -167,14 +185,18 @@ CREATE TABLE `invoices` (
|
|||||||
`tax_date` DATE NULL,
|
`tax_date` DATE NULL,
|
||||||
`paid_date` DATE NULL,
|
`paid_date` DATE NULL,
|
||||||
`issued_by` VARCHAR(255) NULL,
|
`issued_by` VARCHAR(255) NULL,
|
||||||
|
`billing_text` VARCHAR(500) NULL,
|
||||||
|
`language` VARCHAR(5) NULL DEFAULT 'cs',
|
||||||
`notes` TEXT NULL,
|
`notes` TEXT NULL,
|
||||||
`internal_notes` TEXT NULL,
|
`internal_notes` TEXT NULL,
|
||||||
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
`modified_at` DATETIME(0) NULL,
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `idx_invoices_number_unique`(`invoice_number`),
|
||||||
INDEX `customer_id`(`customer_id`),
|
INDEX `customer_id`(`customer_id`),
|
||||||
INDEX `idx_invoices_due_date`(`due_date`),
|
INDEX `idx_invoices_due_date`(`due_date`),
|
||||||
INDEX `idx_invoices_status_issue`(`status`, `issue_date`),
|
INDEX `idx_invoices_status_issue`(`status`, `issue_date`),
|
||||||
|
INDEX `idx_invoices_status_due`(`status`, `due_date`),
|
||||||
INDEX `order_id`(`order_id`),
|
INDEX `order_id`(`order_id`),
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
@@ -239,6 +261,7 @@ CREATE TABLE `number_sequences` (
|
|||||||
`year` INTEGER NULL,
|
`year` INTEGER NULL,
|
||||||
`last_number` INTEGER NULL DEFAULT 0,
|
`last_number` INTEGER NULL DEFAULT 0,
|
||||||
|
|
||||||
|
UNIQUE INDEX `idx_number_sequences_type_year`(`type`, `year`),
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
@@ -294,6 +317,7 @@ CREATE TABLE `orders` (
|
|||||||
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
`modified_at` DATETIME(0) NULL,
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `idx_orders_number_unique`(`order_number`),
|
||||||
INDEX `customer_id`(`customer_id`),
|
INDEX `customer_id`(`customer_id`),
|
||||||
INDEX `quotation_id`(`quotation_id`),
|
INDEX `quotation_id`(`quotation_id`),
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
@@ -341,6 +365,7 @@ CREATE TABLE `projects` (
|
|||||||
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
`modified_at` DATETIME(0) NULL,
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `projects_project_number_key`(`project_number`),
|
||||||
INDEX `customer_id`(`customer_id`),
|
INDEX `customer_id`(`customer_id`),
|
||||||
INDEX `fk_projects_responsible_user`(`responsible_user_id`),
|
INDEX `fk_projects_responsible_user`(`responsible_user_id`),
|
||||||
INDEX `order_id`(`order_id`),
|
INDEX `order_id`(`order_id`),
|
||||||
@@ -386,10 +411,13 @@ CREATE TABLE `quotations` (
|
|||||||
`status` VARCHAR(20) NOT NULL DEFAULT 'active',
|
`status` VARCHAR(20) NOT NULL DEFAULT 'active',
|
||||||
`scope_title` VARCHAR(500) NULL,
|
`scope_title` VARCHAR(500) NULL,
|
||||||
`scope_description` TEXT NULL,
|
`scope_description` TEXT NULL,
|
||||||
|
`locked_by` INTEGER NULL,
|
||||||
|
`locked_at` DATETIME(0) NULL,
|
||||||
`uuid` VARCHAR(36) NULL,
|
`uuid` VARCHAR(36) NULL,
|
||||||
`modified_at` DATETIME(0) NULL,
|
`modified_at` DATETIME(0) NULL,
|
||||||
`sync_version` INTEGER NULL DEFAULT 0,
|
`sync_version` INTEGER NULL DEFAULT 0,
|
||||||
|
|
||||||
|
UNIQUE INDEX `quotations_quotation_number_key`(`quotation_number`),
|
||||||
INDEX `customer_id`(`customer_id`),
|
INDEX `customer_id`(`customer_id`),
|
||||||
INDEX `idx_quotations_number`(`quotation_number`),
|
INDEX `idx_quotations_number`(`quotation_number`),
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
@@ -411,7 +439,6 @@ CREATE TABLE `received_invoices` (
|
|||||||
`due_date` DATE NULL,
|
`due_date` DATE NULL,
|
||||||
`paid_date` DATE NULL,
|
`paid_date` DATE NULL,
|
||||||
`status` ENUM('unpaid', 'paid') NOT NULL DEFAULT 'unpaid',
|
`status` ENUM('unpaid', 'paid') NOT NULL DEFAULT 'unpaid',
|
||||||
`file_data` MEDIUMBLOB NULL,
|
|
||||||
`file_name` VARCHAR(255) NULL,
|
`file_name` VARCHAR(255) NULL,
|
||||||
`file_mime` VARCHAR(100) NULL,
|
`file_mime` VARCHAR(100) NULL,
|
||||||
`file_size` INTEGER UNSIGNED NULL,
|
`file_size` INTEGER UNSIGNED NULL,
|
||||||
@@ -572,6 +599,7 @@ CREATE TABLE `users` (
|
|||||||
`totp_secret` VARCHAR(255) NULL,
|
`totp_secret` VARCHAR(255) NULL,
|
||||||
`totp_enabled` BOOLEAN NOT NULL DEFAULT false,
|
`totp_enabled` BOOLEAN NOT NULL DEFAULT false,
|
||||||
`totp_backup_codes` TEXT NULL,
|
`totp_backup_codes` TEXT NULL,
|
||||||
|
`totp_last_used_counter` INTEGER NULL,
|
||||||
|
|
||||||
UNIQUE INDEX `username`(`username`),
|
UNIQUE INDEX `username`(`username`),
|
||||||
UNIQUE INDEX `email`(`email`),
|
UNIQUE INDEX `email`(`email`),
|
||||||
@@ -597,12 +625,28 @@ CREATE TABLE `vehicles` (
|
|||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `invoice_alert_log` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`invoice_type` VARCHAR(20) NOT NULL,
|
||||||
|
`invoice_id` INTEGER NOT NULL,
|
||||||
|
`alert_type` VARCHAR(20) NOT NULL,
|
||||||
|
`sent_at` DATETIME(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`created_at` DATETIME(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
|
||||||
|
UNIQUE INDEX `invoice_type_invoice_id_alert_type`(`invoice_type`, `invoice_id`, `alert_type`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
-- AddForeignKey
|
-- AddForeignKey
|
||||||
ALTER TABLE `attendance` ADD CONSTRAINT `attendance_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
ALTER TABLE `attendance` ADD CONSTRAINT `attendance_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||||
|
|
||||||
-- AddForeignKey
|
-- AddForeignKey
|
||||||
ALTER TABLE `attendance_project_logs` ADD CONSTRAINT `attendance_project_logs_attendance_id_fkey` FOREIGN KEY (`attendance_id`) REFERENCES `attendance`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
ALTER TABLE `attendance_project_logs` ADD CONSTRAINT `attendance_project_logs_attendance_id_fkey` FOREIGN KEY (`attendance_id`) REFERENCES `attendance`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `attendance_project_logs` ADD CONSTRAINT `attendance_project_logs_project_id_fkey` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||||
|
|
||||||
-- AddForeignKey
|
-- AddForeignKey
|
||||||
ALTER TABLE `invoice_items` ADD CONSTRAINT `invoice_items_ibfk_1` FOREIGN KEY (`invoice_id`) REFERENCES `invoices`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
ALTER TABLE `invoice_items` ADD CONSTRAINT `invoice_items_ibfk_1` FOREIGN KEY (`invoice_id`) REFERENCES `invoices`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||||
|
|
||||||
@@ -674,4 +718,3 @@ ALTER TABLE `trips` ADD CONSTRAINT `trips_vehicle_fk` FOREIGN KEY (`vehicle_id`)
|
|||||||
|
|
||||||
-- AddForeignKey
|
-- AddForeignKey
|
||||||
ALTER TABLE `users` ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION;
|
ALTER TABLE `users` ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION;
|
||||||
|
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- Insert the settings.system permission (also available via seed)
|
||||||
|
INSERT INTO `permissions` (`name`, `display_name`, `module`, `description`)
|
||||||
|
VALUES ('settings.system', 'Systémová nastavení', 'settings', 'Spravovat systémová nastavení, 2FA, e-maily, limity')
|
||||||
|
ON DUPLICATE KEY UPDATE `name` = `name`;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE `quotations` DROP COLUMN `exchange_rate`;
|
||||||
|
ALTER TABLE `quotations` DROP COLUMN `exchange_rate_date`;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE `invoice_items` ADD COLUMN `item_description` TEXT NULL;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- AlterTable: quotation_items
|
||||||
|
ALTER TABLE `quotation_items` DROP COLUMN `uuid`;
|
||||||
|
ALTER TABLE `quotation_items` DROP COLUMN `is_deleted`;
|
||||||
|
ALTER TABLE `quotation_items` DROP COLUMN `sync_version`;
|
||||||
|
|
||||||
|
-- AlterTable: quotations
|
||||||
|
ALTER TABLE `quotations` DROP COLUMN `uuid`;
|
||||||
|
ALTER TABLE `quotations` DROP COLUMN `sync_version`;
|
||||||
|
|
||||||
|
-- AlterTable: scope_sections
|
||||||
|
ALTER TABLE `scope_sections` DROP COLUMN `content_editor_height`;
|
||||||
|
ALTER TABLE `scope_sections` DROP COLUMN `uuid`;
|
||||||
|
ALTER TABLE `scope_sections` DROP COLUMN `is_deleted`;
|
||||||
|
ALTER TABLE `scope_sections` DROP COLUMN `sync_version`;
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_categories` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`name` VARCHAR(100) NOT NULL,
|
||||||
|
`description` TEXT NULL,
|
||||||
|
`sort_order` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_suppliers` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`name` VARCHAR(255) NOT NULL,
|
||||||
|
`ico` VARCHAR(20) NULL,
|
||||||
|
`dic` VARCHAR(20) NULL,
|
||||||
|
`contact_person` VARCHAR(255) NULL,
|
||||||
|
`email` VARCHAR(255) NULL,
|
||||||
|
`phone` VARCHAR(50) NULL,
|
||||||
|
`address` TEXT NULL,
|
||||||
|
`notes` TEXT NULL,
|
||||||
|
`is_active` BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_locations` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`code` VARCHAR(20) NOT NULL,
|
||||||
|
`name` VARCHAR(100) NOT NULL,
|
||||||
|
`description` TEXT NULL,
|
||||||
|
`is_active` BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `sklad_locations_code_key`(`code`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_items` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`item_number` VARCHAR(50) NULL,
|
||||||
|
`name` VARCHAR(255) NOT NULL,
|
||||||
|
`description` TEXT NULL,
|
||||||
|
`category_id` INTEGER NULL,
|
||||||
|
`unit` VARCHAR(20) NOT NULL,
|
||||||
|
`min_quantity` DECIMAL(12, 3) NULL,
|
||||||
|
`is_active` BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
`notes` TEXT NULL,
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `sklad_items_item_number_key`(`item_number`),
|
||||||
|
INDEX `sklad_items_category_id`(`category_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_batches` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`item_id` INTEGER NOT NULL,
|
||||||
|
`receipt_line_id` INTEGER NOT NULL,
|
||||||
|
`quantity` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`original_qty` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`unit_price` DECIMAL(12, 2) NOT NULL,
|
||||||
|
`received_at` DATETIME(0) NULL,
|
||||||
|
`is_consumed` BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
|
||||||
|
UNIQUE INDEX `sklad_batches_receipt_line_id_key`(`receipt_line_id`),
|
||||||
|
INDEX `sklad_batches_fifo`(`item_id`, `is_consumed`, `received_at`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_item_locations` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`item_id` INTEGER NOT NULL,
|
||||||
|
`location_id` INTEGER NOT NULL,
|
||||||
|
`quantity` DECIMAL(12, 3) NOT NULL DEFAULT 0,
|
||||||
|
|
||||||
|
UNIQUE INDEX `sklad_item_locations_unique`(`item_id`, `location_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_receipts` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`receipt_number` VARCHAR(50) NULL,
|
||||||
|
`supplier_id` INTEGER NULL,
|
||||||
|
`delivery_note_number` VARCHAR(100) NULL,
|
||||||
|
`delivery_note_date` DATETIME(0) NULL,
|
||||||
|
`received_by` INTEGER NULL,
|
||||||
|
`notes` TEXT NULL,
|
||||||
|
`status` ENUM('DRAFT', 'CONFIRMED', 'CANCELLED') NOT NULL DEFAULT 'DRAFT',
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_receipt_lines` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`receipt_id` INTEGER NOT NULL,
|
||||||
|
`item_id` INTEGER NOT NULL,
|
||||||
|
`quantity` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`unit_price` DECIMAL(12, 2) NOT NULL,
|
||||||
|
`location_id` INTEGER NULL,
|
||||||
|
`notes` VARCHAR(255) NULL,
|
||||||
|
|
||||||
|
INDEX `sklad_receipt_lines_receipt_id`(`receipt_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_receipt_attachments` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`receipt_id` INTEGER NOT NULL,
|
||||||
|
`file_name` VARCHAR(255) NOT NULL,
|
||||||
|
`file_mime` VARCHAR(100) NOT NULL,
|
||||||
|
`file_size` INTEGER NOT NULL,
|
||||||
|
`file_path` VARCHAR(500) NOT NULL,
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_issues` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`issue_number` VARCHAR(50) NULL,
|
||||||
|
`project_id` INTEGER NOT NULL,
|
||||||
|
`issued_by` INTEGER NULL,
|
||||||
|
`notes` TEXT NULL,
|
||||||
|
`status` ENUM('DRAFT', 'CONFIRMED', 'CANCELLED') NOT NULL DEFAULT 'DRAFT',
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_issue_lines` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`issue_id` INTEGER NOT NULL,
|
||||||
|
`item_id` INTEGER NOT NULL,
|
||||||
|
`batch_id` INTEGER NOT NULL,
|
||||||
|
`quantity` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`location_id` INTEGER NULL,
|
||||||
|
`reservation_id` INTEGER NULL,
|
||||||
|
`notes` VARCHAR(255) NULL,
|
||||||
|
|
||||||
|
INDEX `sklad_issue_lines_issue_id`(`issue_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_reservations` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`item_id` INTEGER NOT NULL,
|
||||||
|
`project_id` INTEGER NOT NULL,
|
||||||
|
`quantity` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`remaining_qty` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`reserved_by` INTEGER NULL,
|
||||||
|
`notes` TEXT NULL,
|
||||||
|
`status` ENUM('ACTIVE', 'FULFILLED', 'CANCELLED') NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
INDEX `sklad_reservations_item_status`(`item_id`, `status`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_inventory_sessions` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`session_number` VARCHAR(50) NULL,
|
||||||
|
`notes` TEXT NULL,
|
||||||
|
`status` ENUM('DRAFT', 'CONFIRMED') NOT NULL DEFAULT 'DRAFT',
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`modified_at` DATETIME(0) NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `sklad_inventory_lines` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`session_id` INTEGER NOT NULL,
|
||||||
|
`item_id` INTEGER NOT NULL,
|
||||||
|
`location_id` INTEGER NULL,
|
||||||
|
`system_qty` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`actual_qty` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`difference` DECIMAL(12, 3) NOT NULL,
|
||||||
|
`notes` VARCHAR(255) NULL,
|
||||||
|
|
||||||
|
INDEX `sklad_inventory_lines_session_id`(`session_id`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_items` ADD CONSTRAINT `sklad_items_category_id_fkey` FOREIGN KEY (`category_id`) REFERENCES `sklad_categories`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_batches` ADD CONSTRAINT `sklad_batches_item_id_fkey` FOREIGN KEY (`item_id`) REFERENCES `sklad_items`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_batches` ADD CONSTRAINT `sklad_batches_receipt_line_id_fkey` FOREIGN KEY (`receipt_line_id`) REFERENCES `sklad_receipt_lines`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_item_locations` ADD CONSTRAINT `sklad_item_locations_item_id_fkey` FOREIGN KEY (`item_id`) REFERENCES `sklad_items`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_item_locations` ADD CONSTRAINT `sklad_item_locations_location_id_fkey` FOREIGN KEY (`location_id`) REFERENCES `sklad_locations`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_receipts` ADD CONSTRAINT `sklad_receipts_supplier_id_fkey` FOREIGN KEY (`supplier_id`) REFERENCES `sklad_suppliers`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_receipts` ADD CONSTRAINT `sklad_receipts_received_by_fkey` FOREIGN KEY (`received_by`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_receipt_lines` ADD CONSTRAINT `sklad_receipt_lines_receipt_id_fkey` FOREIGN KEY (`receipt_id`) REFERENCES `sklad_receipts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_receipt_lines` ADD CONSTRAINT `sklad_receipt_lines_item_id_fkey` FOREIGN KEY (`item_id`) REFERENCES `sklad_items`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_receipt_lines` ADD CONSTRAINT `sklad_receipt_lines_location_id_fkey` FOREIGN KEY (`location_id`) REFERENCES `sklad_locations`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_receipt_attachments` ADD CONSTRAINT `sklad_receipt_attachments_receipt_id_fkey` FOREIGN KEY (`receipt_id`) REFERENCES `sklad_receipts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_issues` ADD CONSTRAINT `sklad_issues_project_id_fkey` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_issues` ADD CONSTRAINT `sklad_issues_issued_by_fkey` FOREIGN KEY (`issued_by`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_issue_lines` ADD CONSTRAINT `sklad_issue_lines_issue_id_fkey` FOREIGN KEY (`issue_id`) REFERENCES `sklad_issues`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_issue_lines` ADD CONSTRAINT `sklad_issue_lines_item_id_fkey` FOREIGN KEY (`item_id`) REFERENCES `sklad_items`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_issue_lines` ADD CONSTRAINT `sklad_issue_lines_batch_id_fkey` FOREIGN KEY (`batch_id`) REFERENCES `sklad_batches`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_issue_lines` ADD CONSTRAINT `sklad_issue_lines_location_id_fkey` FOREIGN KEY (`location_id`) REFERENCES `sklad_locations`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_issue_lines` ADD CONSTRAINT `sklad_issue_lines_reservation_id_fkey` FOREIGN KEY (`reservation_id`) REFERENCES `sklad_reservations`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_reservations` ADD CONSTRAINT `sklad_reservations_item_id_fkey` FOREIGN KEY (`item_id`) REFERENCES `sklad_items`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_reservations` ADD CONSTRAINT `sklad_reservations_project_id_fkey` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_reservations` ADD CONSTRAINT `sklad_reservations_reserved_by_fkey` FOREIGN KEY (`reserved_by`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_inventory_lines` ADD CONSTRAINT `sklad_inventory_lines_session_id_fkey` FOREIGN KEY (`session_id`) REFERENCES `sklad_inventory_sessions`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_inventory_lines` ADD CONSTRAINT `sklad_inventory_lines_item_id_fkey` FOREIGN KEY (`item_id`) REFERENCES `sklad_items`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `sklad_inventory_lines` ADD CONSTRAINT `sklad_inventory_lines_location_id_fkey` FOREIGN KEY (`location_id`) REFERENCES `sklad_locations`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE `company_settings` ADD COLUMN `warehouse_inventory_number_pattern` VARCHAR(100) NULL,
|
||||||
|
ADD COLUMN `warehouse_inventory_prefix` VARCHAR(20) NULL,
|
||||||
|
ADD COLUMN `warehouse_issue_number_pattern` VARCHAR(100) NULL,
|
||||||
|
ADD COLUMN `warehouse_issue_prefix` VARCHAR(20) NULL,
|
||||||
|
ADD COLUMN `warehouse_receipt_number_pattern` VARCHAR(100) NULL,
|
||||||
|
ADD COLUMN `warehouse_receipt_prefix` VARCHAR(20) NULL;
|
||||||
|
|
||||||
|
-- Set backward-compatible defaults for existing installations
|
||||||
|
UPDATE `company_settings`
|
||||||
|
SET
|
||||||
|
`warehouse_receipt_prefix` = 'PRI',
|
||||||
|
`warehouse_receipt_number_pattern` = '{PREFIX}-{YYYY}-{NNN}',
|
||||||
|
`warehouse_issue_prefix` = 'VYD',
|
||||||
|
`warehouse_issue_number_pattern` = '{PREFIX}-{YYYY}-{NNN}',
|
||||||
|
`warehouse_inventory_prefix` = 'INV',
|
||||||
|
`warehouse_inventory_number_pattern` = '{PREFIX}-{YYYY}-{NNN}';
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
-- Add warehouse module permissions and assign them to the admin role.
|
||||||
|
-- These rows used to be created by `prisma/seed.ts`, which is dev-only and
|
||||||
|
-- must not be run against production (per CLAUDE.md). This migration is
|
||||||
|
-- idempotent: re-running it is a no-op.
|
||||||
|
--
|
||||||
|
-- The 4 permissions match `prisma/seed.ts` lines 284-308 exactly.
|
||||||
|
|
||||||
|
-- 1. Insert the 4 warehouse permissions (INSERT IGNORE skips on duplicate
|
||||||
|
-- name, so re-running the migration is safe).
|
||||||
|
INSERT IGNORE INTO `permissions` (`name`, `display_name`, `module`, `description`, `created_at`) VALUES
|
||||||
|
('warehouse.view', 'Zobrazit sklad', 'warehouse', 'Prohlížet stav skladu, položky, reporty a historii pohybů', NOW()),
|
||||||
|
('warehouse.operate', 'Příjem a výdej', 'warehouse', 'Vytvářet a potvrzovat příjmy, výdeje a rezervace', NOW()),
|
||||||
|
('warehouse.manage', 'Správa skladu', 'warehouse', 'Spravovat katalog materiálů, dodavatele, lokace a kategorie', NOW()),
|
||||||
|
('warehouse.inventory', 'Inventura', 'warehouse', 'Vytvářet a potvrzovat inventurní sčítkání', NOW());
|
||||||
|
|
||||||
|
-- 2. Assign all 4 permissions to the admin role. INSERT IGNORE on the
|
||||||
|
-- composite primary key (role_id, permission_id) makes this idempotent
|
||||||
|
-- and preserves any other role assignments that already exist.
|
||||||
|
INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`)
|
||||||
|
SELECT r.id, p.id
|
||||||
|
FROM `roles` r
|
||||||
|
CROSS JOIN `permissions` p
|
||||||
|
WHERE r.name = 'admin'
|
||||||
|
AND p.name IN (
|
||||||
|
'warehouse.view',
|
||||||
|
'warehouse.operate',
|
||||||
|
'warehouse.manage',
|
||||||
|
'warehouse.inventory'
|
||||||
|
);
|
||||||
61
prisma/migrations/20260605120000_add_work_plan/migration.sql
Normal file
61
prisma/migrations/20260605120000_add_work_plan/migration.sql
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
-- Add work_plan_entries and work_plan_overrides tables plus the plan_category
|
||||||
|
-- enum. Both tables are owned by users (Cascade on delete) and reference
|
||||||
|
-- projects (SetNull). `created_by` uses Restrict so we never silently lose
|
||||||
|
-- the audit trail of who created the entry.
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `work_plan_entries` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`user_id` INTEGER NOT NULL,
|
||||||
|
`date_from` DATE NOT NULL,
|
||||||
|
`date_to` DATE NOT NULL,
|
||||||
|
`project_id` INTEGER NULL,
|
||||||
|
`category` ENUM('work', 'preparation', 'travel', 'leave', 'sick', 'training', 'other') NOT NULL DEFAULT 'work',
|
||||||
|
`note` VARCHAR(500) NOT NULL,
|
||||||
|
`created_by` INTEGER NOT NULL,
|
||||||
|
`created_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`updated_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`is_deleted` BOOLEAN NULL DEFAULT false,
|
||||||
|
|
||||||
|
INDEX `idx_wpe_user_from`(`user_id`, `date_from`),
|
||||||
|
INDEX `idx_wpe_user_to`(`user_id`, `date_to`),
|
||||||
|
INDEX `idx_wpe_project`(`project_id`),
|
||||||
|
INDEX `idx_wpe_dates`(`date_from`, `date_to`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `work_plan_overrides` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`user_id` INTEGER NOT NULL,
|
||||||
|
`shift_date` DATE NOT NULL,
|
||||||
|
`project_id` INTEGER NULL,
|
||||||
|
`category` ENUM('work', 'preparation', 'travel', 'leave', 'sick', 'training', 'other') NOT NULL,
|
||||||
|
`note` VARCHAR(500) NOT NULL,
|
||||||
|
`created_by` INTEGER NOT NULL,
|
||||||
|
`created_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`updated_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`is_deleted` BOOLEAN NULL DEFAULT false,
|
||||||
|
|
||||||
|
INDEX `idx_wpo_date`(`shift_date`),
|
||||||
|
UNIQUE INDEX `uniq_wpo_user_date`(`user_id`, `shift_date`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `work_plan_entries` ADD CONSTRAINT `work_plan_entries_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `work_plan_entries` ADD CONSTRAINT `work_plan_entries_project_id_fkey` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `work_plan_entries` ADD CONSTRAINT `work_plan_entries_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `work_plan_overrides` ADD CONSTRAINT `work_plan_overrides_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `work_plan_overrides` ADD CONSTRAINT `work_plan_overrides_project_id_fkey` FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON DELETE SET NULL ON UPDATE NO ACTION;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `work_plan_overrides` ADD CONSTRAINT `work_plan_overrides_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- Drop the unique index on (user_id, shift_date) for work_plan_overrides.
|
||||||
|
-- MySQL unique indexes don't ignore soft-deleted rows, which would prevent
|
||||||
|
-- createOverride from soft-deleting an existing override and creating a new
|
||||||
|
-- one for the same (user_id, shift_date). Application code enforces the
|
||||||
|
-- "at most one active override per (user_id, shift_date)" invariant.
|
||||||
|
-- The application-level check is wrapped in a transaction; see
|
||||||
|
-- src/services/plan.service.ts:createOverride.
|
||||||
|
--
|
||||||
|
-- The original index was created in
|
||||||
|
-- 20260605120000_add_work_plan/migration.sql as `uniq_wpo_user_date`.
|
||||||
|
|
||||||
|
-- IMPORTANT ordering: `uniq_wpo_user_date` is the only index covering the
|
||||||
|
-- `user_id` foreign key, and MySQL refuses to drop an index still needed by a
|
||||||
|
-- FK. So we CREATE the replacement non-unique index FIRST (giving the FK
|
||||||
|
-- another covering index), THEN drop the unique one. The reverse order fails
|
||||||
|
-- with "Cannot drop index ... needed in a foreign key constraint" on a fresh
|
||||||
|
-- apply.
|
||||||
|
|
||||||
|
-- Add a non-unique index for the (user_id, shift_date) lookup used by
|
||||||
|
-- createOverride's "is there an active override for this user-day?" query
|
||||||
|
-- and by resolveCell / resolveGrid. This is a plain index, not a unique
|
||||||
|
-- one — multiple rows (active and soft-deleted) can share the same
|
||||||
|
-- (user_id, shift_date) pair.
|
||||||
|
CREATE INDEX `idx_wpo_user_date` ON `work_plan_overrides`(`user_id`, `shift_date`);
|
||||||
|
|
||||||
|
DROP INDEX `uniq_wpo_user_date` ON `work_plan_overrides`;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
-- Add plan_categories table and convert category columns from ENUM to VARCHAR(50)
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `plan_categories` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`key` VARCHAR(50) NOT NULL,
|
||||||
|
`label` VARCHAR(100) NOT NULL,
|
||||||
|
`color` VARCHAR(7) NOT NULL,
|
||||||
|
`sort_order` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`is_active` BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
`updated_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||||
|
|
||||||
|
UNIQUE INDEX `plan_categories_key_key`(`key`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- AlterTable: change category from ENUM to VARCHAR(50) in work_plan_entries
|
||||||
|
ALTER TABLE `work_plan_entries` MODIFY `category` VARCHAR(50) NOT NULL DEFAULT 'work';
|
||||||
|
|
||||||
|
-- AlterTable: change category from ENUM to VARCHAR(50) in work_plan_overrides
|
||||||
|
ALTER TABLE `work_plan_overrides` MODIFY `category` VARCHAR(50) NOT NULL;
|
||||||
|
|
||||||
|
-- Seed the categories that were previously the plan_category enum
|
||||||
|
INSERT INTO `plan_categories` (`key`, `label`, `color`, `sort_order`, `is_active`) VALUES
|
||||||
|
('work', 'Práce', '#2563eb', 1, true),
|
||||||
|
('preparation', 'Příprava', '#0d9488', 2, true),
|
||||||
|
('travel', 'Cesta / Montáž', '#ca8a04', 3, true),
|
||||||
|
('leave', 'Dovolená', '#16a34a', 4, true),
|
||||||
|
('sick', 'Nemoc', '#dc2626', 5, true),
|
||||||
|
('training', 'Školení', '#7c3aed', 6, true),
|
||||||
|
('other', 'Jiné', '#6b7280', 7, true);
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
# Please do not edit this file manually
|
# Please do not edit this file manually
|
||||||
# It should be added in your version-control system (i.e. Git)
|
# It should be added in your version-control system (e.g., Git)
|
||||||
provider = "mysql"
|
provider = "mysql"
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ model attendance {
|
|||||||
users users @relation(fields: [user_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "attendance_ibfk_1")
|
users users @relation(fields: [user_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "attendance_ibfk_1")
|
||||||
attendance_project_logs attendance_project_logs[]
|
attendance_project_logs attendance_project_logs[]
|
||||||
|
|
||||||
@@unique([user_id, shift_date], map: "idx_attendance_user_date")
|
@@index([user_id, shift_date], map: "idx_attendance_user_date")
|
||||||
@@index([user_id, departure_time], map: "idx_attendance_user_departure")
|
@@index([user_id, departure_time], map: "idx_attendance_user_departure")
|
||||||
@@index([project_id], map: "idx_project_id")
|
@@index([project_id], map: "idx_project_id")
|
||||||
}
|
}
|
||||||
@@ -101,7 +101,7 @@ model company_settings {
|
|||||||
vat_id String? @db.VarChar(50)
|
vat_id String? @db.VarChar(50)
|
||||||
custom_fields String? @db.LongText
|
custom_fields String? @db.LongText
|
||||||
logo_data Bytes?
|
logo_data Bytes?
|
||||||
logo_data_dark Bytes?
|
logo_data_dark Bytes? @db.MediumBlob
|
||||||
quotation_prefix String? @db.VarChar(20)
|
quotation_prefix String? @db.VarChar(20)
|
||||||
default_currency String? @default("CZK") @db.VarChar(10)
|
default_currency String? @default("CZK") @db.VarChar(10)
|
||||||
default_vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
default_vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||||
@@ -112,7 +112,7 @@ model company_settings {
|
|||||||
order_type_code String? @db.VarChar(10)
|
order_type_code String? @db.VarChar(10)
|
||||||
invoice_type_code String? @db.VarChar(10)
|
invoice_type_code String? @db.VarChar(10)
|
||||||
require_2fa Boolean @default(false)
|
require_2fa Boolean @default(false)
|
||||||
break_threshold_hours Decimal? @default(6) @db.Decimal(4, 2)
|
break_threshold_hours Decimal? @default(6.00) @db.Decimal(4, 2)
|
||||||
break_duration_short Int? @default(15)
|
break_duration_short Int? @default(15)
|
||||||
break_duration_long Int? @default(30)
|
break_duration_long Int? @default(30)
|
||||||
clock_rounding_minutes Int? @default(15)
|
clock_rounding_minutes Int? @default(15)
|
||||||
@@ -128,6 +128,12 @@ model company_settings {
|
|||||||
offer_number_pattern String? @db.VarChar(100)
|
offer_number_pattern String? @db.VarChar(100)
|
||||||
order_number_pattern String? @db.VarChar(100)
|
order_number_pattern String? @db.VarChar(100)
|
||||||
invoice_number_pattern String? @db.VarChar(100)
|
invoice_number_pattern String? @db.VarChar(100)
|
||||||
|
warehouse_receipt_prefix String? @db.VarChar(20)
|
||||||
|
warehouse_receipt_number_pattern String? @db.VarChar(100)
|
||||||
|
warehouse_issue_prefix String? @db.VarChar(20)
|
||||||
|
warehouse_issue_number_pattern String? @db.VarChar(100)
|
||||||
|
warehouse_inventory_prefix String? @db.VarChar(20)
|
||||||
|
warehouse_inventory_number_pattern String? @db.VarChar(100)
|
||||||
}
|
}
|
||||||
|
|
||||||
model customers {
|
model customers {
|
||||||
@@ -153,8 +159,9 @@ model customers {
|
|||||||
model invoice_items {
|
model invoice_items {
|
||||||
id Int @id @default(autoincrement())
|
id Int @id @default(autoincrement())
|
||||||
invoice_id Int
|
invoice_id Int
|
||||||
description String? @db.VarChar(500)
|
description String? @db.VarChar(500)
|
||||||
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
item_description String? @db.Text
|
||||||
|
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
||||||
unit String? @db.VarChar(20)
|
unit String? @db.VarChar(20)
|
||||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||||
@@ -356,6 +363,10 @@ model projects {
|
|||||||
modified_at DateTime? @db.DateTime(0)
|
modified_at DateTime? @db.DateTime(0)
|
||||||
attendance_project_logs attendance_project_logs[]
|
attendance_project_logs attendance_project_logs[]
|
||||||
project_notes project_notes[]
|
project_notes project_notes[]
|
||||||
|
sklad_issues sklad_issues[]
|
||||||
|
sklad_reservations sklad_reservations[]
|
||||||
|
work_plan_entries work_plan_entries[]
|
||||||
|
work_plan_overrides work_plan_overrides[]
|
||||||
users users? @relation(fields: [responsible_user_id], references: [id], onUpdate: NoAction, map: "fk_projects_responsible_user")
|
users users? @relation(fields: [responsible_user_id], references: [id], onUpdate: NoAction, map: "fk_projects_responsible_user")
|
||||||
customers customers? @relation(fields: [customer_id], references: [id], onUpdate: NoAction, map: "projects_ibfk_1")
|
customers customers? @relation(fields: [customer_id], references: [id], onUpdate: NoAction, map: "projects_ibfk_1")
|
||||||
quotations quotations? @relation(fields: [quotation_id], references: [id], onUpdate: NoAction, map: "projects_ibfk_2")
|
quotations quotations? @relation(fields: [quotation_id], references: [id], onUpdate: NoAction, map: "projects_ibfk_2")
|
||||||
@@ -377,10 +388,7 @@ model quotation_items {
|
|||||||
unit String? @db.VarChar(20)
|
unit String? @db.VarChar(20)
|
||||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||||
is_included_in_total Boolean? @default(true)
|
is_included_in_total Boolean? @default(true)
|
||||||
uuid String? @db.VarChar(36)
|
|
||||||
modified_at DateTime? @db.DateTime(0)
|
modified_at DateTime? @db.DateTime(0)
|
||||||
is_deleted Boolean? @default(false)
|
|
||||||
sync_version Int? @default(0)
|
|
||||||
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "quotation_items_ibfk_1")
|
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "quotation_items_ibfk_1")
|
||||||
|
|
||||||
@@index([quotation_id], map: "quotation_id")
|
@@index([quotation_id], map: "quotation_id")
|
||||||
@@ -389,7 +397,7 @@ model quotation_items {
|
|||||||
model quotations {
|
model quotations {
|
||||||
id Int @id @default(autoincrement())
|
id Int @id @default(autoincrement())
|
||||||
quotation_number String? @unique @db.VarChar(50)
|
quotation_number String? @unique @db.VarChar(50)
|
||||||
project_code String? @db.VarChar(50)
|
project_code String? @db.VarChar(100)
|
||||||
customer_id Int?
|
customer_id Int?
|
||||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
valid_until DateTime? @db.Date
|
valid_until DateTime? @db.Date
|
||||||
@@ -397,17 +405,13 @@ model quotations {
|
|||||||
language String? @default("cs") @db.VarChar(5)
|
language String? @default("cs") @db.VarChar(5)
|
||||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||||
apply_vat Boolean? @default(true)
|
apply_vat Boolean? @default(true)
|
||||||
exchange_rate Decimal? @default(1.0000) @db.Decimal(10, 4)
|
|
||||||
exchange_rate_date DateTime? @db.Date
|
|
||||||
order_id Int?
|
order_id Int?
|
||||||
status String @default("active") @db.VarChar(20)
|
status String @default("active") @db.VarChar(20)
|
||||||
scope_title String? @db.VarChar(500)
|
scope_title String? @db.VarChar(500)
|
||||||
scope_description String? @db.Text
|
scope_description String? @db.Text
|
||||||
locked_by Int?
|
locked_by Int?
|
||||||
locked_at DateTime? @db.DateTime(0)
|
locked_at DateTime? @db.DateTime(0)
|
||||||
uuid String? @db.VarChar(36)
|
|
||||||
modified_at DateTime? @db.DateTime(0)
|
modified_at DateTime? @db.DateTime(0)
|
||||||
sync_version Int? @default(0)
|
|
||||||
orders orders[]
|
orders orders[]
|
||||||
projects projects[]
|
projects projects[]
|
||||||
quotation_items quotation_items[]
|
quotation_items quotation_items[]
|
||||||
@@ -437,7 +441,7 @@ model received_invoices {
|
|||||||
file_mime String? @db.VarChar(100)
|
file_mime String? @db.VarChar(100)
|
||||||
file_size Int? @db.UnsignedInt
|
file_size Int? @db.UnsignedInt
|
||||||
notes String? @db.Text
|
notes String? @db.Text
|
||||||
uploaded_by Int?
|
uploaded_by Int? @db.UnsignedInt
|
||||||
created_at DateTime @default(now()) @db.DateTime(0)
|
created_at DateTime @default(now()) @db.DateTime(0)
|
||||||
modified_at DateTime @default(now()) @db.DateTime(0)
|
modified_at DateTime @default(now()) @db.DateTime(0)
|
||||||
|
|
||||||
@@ -449,7 +453,7 @@ model received_invoices {
|
|||||||
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
|
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
|
||||||
model refresh_tokens {
|
model refresh_tokens {
|
||||||
id Int @id @default(autoincrement()) @db.UnsignedInt
|
id Int @id @default(autoincrement()) @db.UnsignedInt
|
||||||
user_id Int
|
user_id Int @db.UnsignedInt
|
||||||
token_hash String @unique(map: "token_hash") @db.VarChar(64)
|
token_hash String @unique(map: "token_hash") @db.VarChar(64)
|
||||||
expires_at DateTime @db.DateTime(0)
|
expires_at DateTime @db.DateTime(0)
|
||||||
replaced_at DateTime? @db.DateTime(0)
|
replaced_at DateTime? @db.DateTime(0)
|
||||||
@@ -492,11 +496,7 @@ model scope_sections {
|
|||||||
title String? @db.VarChar(500)
|
title String? @db.VarChar(500)
|
||||||
title_cz String? @db.VarChar(500)
|
title_cz String? @db.VarChar(500)
|
||||||
content String? @db.Text
|
content String? @db.Text
|
||||||
content_editor_height Int?
|
|
||||||
uuid String? @db.VarChar(36)
|
|
||||||
modified_at DateTime? @db.DateTime(0)
|
modified_at DateTime? @db.DateTime(0)
|
||||||
is_deleted Boolean? @default(false)
|
|
||||||
sync_version Int? @default(0)
|
|
||||||
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "scope_sections_ibfk_1")
|
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "scope_sections_ibfk_1")
|
||||||
|
|
||||||
@@index([quotation_id], map: "quotation_id")
|
@@index([quotation_id], map: "quotation_id")
|
||||||
@@ -590,6 +590,13 @@ model users {
|
|||||||
leave_requests_leave_requests_reviewer_idTousers leave_requests[] @relation("leave_requests_reviewer_idTousers")
|
leave_requests_leave_requests_reviewer_idTousers leave_requests[] @relation("leave_requests_reviewer_idTousers")
|
||||||
projects projects[]
|
projects projects[]
|
||||||
trips trips[]
|
trips trips[]
|
||||||
|
sklad_receipts_received sklad_receipts[] @relation("SkladReceivedBy")
|
||||||
|
sklad_issues_issued sklad_issues[] @relation("SkladIssuedBy")
|
||||||
|
sklad_reservations sklad_reservations[] @relation("SkladReservedBy")
|
||||||
|
work_plan_entries work_plan_entries[] @relation("work_plan_entries_creator")
|
||||||
|
work_plan_entries_owned work_plan_entries[]
|
||||||
|
work_plan_overrides work_plan_overrides[] @relation("work_plan_overrides_creator")
|
||||||
|
work_plan_overrides_owned work_plan_overrides[]
|
||||||
roles roles? @relation(fields: [role_id], references: [id], onUpdate: NoAction, map: "users_ibfk_1")
|
roles roles? @relation(fields: [role_id], references: [id], onUpdate: NoAction, map: "users_ibfk_1")
|
||||||
|
|
||||||
@@index([is_active], map: "idx_users_is_active")
|
@@index([is_active], map: "idx_users_is_active")
|
||||||
@@ -632,7 +639,7 @@ model invoice_alert_log {
|
|||||||
sent_at DateTime @default(now()) @db.DateTime(0)
|
sent_at DateTime @default(now()) @db.DateTime(0)
|
||||||
created_at DateTime @default(now()) @db.DateTime(0)
|
created_at DateTime @default(now()) @db.DateTime(0)
|
||||||
|
|
||||||
@@unique([invoice_type, invoice_id, alert_type])
|
@@unique([invoice_type, invoice_id, alert_type], map: "invoice_type_invoice_id_alert_type")
|
||||||
}
|
}
|
||||||
|
|
||||||
enum received_invoices_status {
|
enum received_invoices_status {
|
||||||
@@ -647,3 +654,324 @@ enum attendance_leave_type {
|
|||||||
holiday
|
holiday
|
||||||
unpaid
|
unpaid
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum sklad_receipt_status {
|
||||||
|
DRAFT
|
||||||
|
CONFIRMED
|
||||||
|
CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum sklad_issue_status {
|
||||||
|
DRAFT
|
||||||
|
CONFIRMED
|
||||||
|
CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum sklad_reservation_status {
|
||||||
|
ACTIVE
|
||||||
|
FULFILLED
|
||||||
|
CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum sklad_inventory_status {
|
||||||
|
DRAFT
|
||||||
|
CONFIRMED
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_categories {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
description String? @db.Text
|
||||||
|
sort_order Int @default(0)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
items sklad_items[]
|
||||||
|
|
||||||
|
@@map("sklad_categories")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_suppliers {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(255)
|
||||||
|
ico String? @db.VarChar(20)
|
||||||
|
dic String? @db.VarChar(20)
|
||||||
|
contact_person String? @db.VarChar(255)
|
||||||
|
email String? @db.VarChar(255)
|
||||||
|
phone String? @db.VarChar(50)
|
||||||
|
address String? @db.Text
|
||||||
|
notes String? @db.Text
|
||||||
|
is_active Boolean @default(true)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
receipts sklad_receipts[]
|
||||||
|
|
||||||
|
@@map("sklad_suppliers")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_locations {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
code String @unique @db.VarChar(20)
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
description String? @db.Text
|
||||||
|
is_active Boolean @default(true)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
items sklad_item_locations[]
|
||||||
|
receipt_lines sklad_receipt_lines[]
|
||||||
|
issue_lines sklad_issue_lines[]
|
||||||
|
inventory_lines sklad_inventory_lines[]
|
||||||
|
|
||||||
|
@@map("sklad_locations")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_items {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
item_number String? @unique @db.VarChar(50)
|
||||||
|
name String @db.VarChar(255)
|
||||||
|
description String? @db.Text
|
||||||
|
category_id Int?
|
||||||
|
unit String @db.VarChar(20)
|
||||||
|
min_quantity Decimal? @db.Decimal(12, 3)
|
||||||
|
is_active Boolean @default(true)
|
||||||
|
notes String? @db.Text
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
category sklad_categories? @relation(fields: [category_id], references: [id])
|
||||||
|
batches sklad_batches[]
|
||||||
|
item_locations sklad_item_locations[]
|
||||||
|
receipt_lines sklad_receipt_lines[]
|
||||||
|
issue_lines sklad_issue_lines[]
|
||||||
|
reservations sklad_reservations[]
|
||||||
|
inventory_lines sklad_inventory_lines[]
|
||||||
|
|
||||||
|
@@index([category_id], map: "sklad_items_category_id")
|
||||||
|
@@map("sklad_items")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_batches {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
item_id Int
|
||||||
|
receipt_line_id Int @unique
|
||||||
|
quantity Decimal @db.Decimal(12, 3)
|
||||||
|
original_qty Decimal @db.Decimal(12, 3)
|
||||||
|
unit_price Decimal @db.Decimal(12, 2)
|
||||||
|
received_at DateTime? @db.DateTime(0)
|
||||||
|
is_consumed Boolean @default(false)
|
||||||
|
|
||||||
|
item sklad_items @relation(fields: [item_id], references: [id])
|
||||||
|
receipt_line sklad_receipt_lines @relation(fields: [receipt_line_id], references: [id])
|
||||||
|
issue_lines sklad_issue_lines[]
|
||||||
|
|
||||||
|
@@index([item_id, is_consumed, received_at], map: "sklad_batches_fifo")
|
||||||
|
@@map("sklad_batches")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_item_locations {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
item_id Int
|
||||||
|
location_id Int
|
||||||
|
quantity Decimal @default(0) @db.Decimal(12, 3)
|
||||||
|
|
||||||
|
item sklad_items @relation(fields: [item_id], references: [id])
|
||||||
|
location sklad_locations @relation(fields: [location_id], references: [id])
|
||||||
|
|
||||||
|
@@unique([item_id, location_id], map: "sklad_item_locations_unique")
|
||||||
|
@@map("sklad_item_locations")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_receipts {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
receipt_number String? @db.VarChar(50)
|
||||||
|
supplier_id Int?
|
||||||
|
delivery_note_number String? @db.VarChar(100)
|
||||||
|
delivery_note_date DateTime? @db.DateTime(0)
|
||||||
|
received_by Int?
|
||||||
|
notes String? @db.Text
|
||||||
|
status sklad_receipt_status @default(DRAFT)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
supplier sklad_suppliers? @relation(fields: [supplier_id], references: [id])
|
||||||
|
received_by_user users? @relation("SkladReceivedBy", fields: [received_by], references: [id])
|
||||||
|
items sklad_receipt_lines[]
|
||||||
|
attachments sklad_receipt_attachments[]
|
||||||
|
|
||||||
|
@@map("sklad_receipts")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_receipt_lines {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
receipt_id Int
|
||||||
|
item_id Int
|
||||||
|
quantity Decimal @db.Decimal(12, 3)
|
||||||
|
unit_price Decimal @db.Decimal(12, 2)
|
||||||
|
location_id Int?
|
||||||
|
notes String? @db.VarChar(255)
|
||||||
|
|
||||||
|
receipt sklad_receipts @relation(fields: [receipt_id], references: [id])
|
||||||
|
item sklad_items @relation(fields: [item_id], references: [id])
|
||||||
|
location sklad_locations? @relation(fields: [location_id], references: [id])
|
||||||
|
batch sklad_batches?
|
||||||
|
|
||||||
|
@@index([receipt_id], map: "sklad_receipt_lines_receipt_id")
|
||||||
|
@@map("sklad_receipt_lines")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_receipt_attachments {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
receipt_id Int
|
||||||
|
file_name String @db.VarChar(255)
|
||||||
|
file_mime String @db.VarChar(100)
|
||||||
|
file_size Int
|
||||||
|
file_path String @db.VarChar(500)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
|
||||||
|
receipt sklad_receipts @relation(fields: [receipt_id], references: [id])
|
||||||
|
|
||||||
|
@@map("sklad_receipt_attachments")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_issues {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
issue_number String? @db.VarChar(50)
|
||||||
|
project_id Int
|
||||||
|
issued_by Int?
|
||||||
|
notes String? @db.Text
|
||||||
|
status sklad_issue_status @default(DRAFT)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
project projects @relation(fields: [project_id], references: [id])
|
||||||
|
issued_by_user users? @relation("SkladIssuedBy", fields: [issued_by], references: [id])
|
||||||
|
items sklad_issue_lines[]
|
||||||
|
|
||||||
|
@@map("sklad_issues")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_issue_lines {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
issue_id Int
|
||||||
|
item_id Int
|
||||||
|
batch_id Int
|
||||||
|
quantity Decimal @db.Decimal(12, 3)
|
||||||
|
location_id Int?
|
||||||
|
reservation_id Int?
|
||||||
|
notes String? @db.VarChar(255)
|
||||||
|
|
||||||
|
issue sklad_issues @relation(fields: [issue_id], references: [id])
|
||||||
|
item sklad_items @relation(fields: [item_id], references: [id])
|
||||||
|
batch sklad_batches @relation(fields: [batch_id], references: [id])
|
||||||
|
location sklad_locations? @relation(fields: [location_id], references: [id])
|
||||||
|
reservation sklad_reservations? @relation(fields: [reservation_id], references: [id])
|
||||||
|
|
||||||
|
@@index([issue_id], map: "sklad_issue_lines_issue_id")
|
||||||
|
@@map("sklad_issue_lines")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_reservations {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
item_id Int
|
||||||
|
project_id Int
|
||||||
|
quantity Decimal @db.Decimal(12, 3)
|
||||||
|
remaining_qty Decimal @db.Decimal(12, 3)
|
||||||
|
reserved_by Int?
|
||||||
|
notes String? @db.Text
|
||||||
|
status sklad_reservation_status @default(ACTIVE)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
item sklad_items @relation(fields: [item_id], references: [id])
|
||||||
|
project projects @relation(fields: [project_id], references: [id])
|
||||||
|
reserved_by_user users? @relation("SkladReservedBy", fields: [reserved_by], references: [id])
|
||||||
|
issue_lines sklad_issue_lines[]
|
||||||
|
|
||||||
|
@@index([item_id, status], map: "sklad_reservations_item_status")
|
||||||
|
@@map("sklad_reservations")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_inventory_sessions {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
session_number String? @db.VarChar(50)
|
||||||
|
notes String? @db.Text
|
||||||
|
status sklad_inventory_status @default(DRAFT)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
modified_at DateTime? @db.DateTime(0)
|
||||||
|
|
||||||
|
items sklad_inventory_lines[]
|
||||||
|
|
||||||
|
@@map("sklad_inventory_sessions")
|
||||||
|
}
|
||||||
|
|
||||||
|
model sklad_inventory_lines {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
session_id Int
|
||||||
|
item_id Int
|
||||||
|
location_id Int?
|
||||||
|
system_qty Decimal @db.Decimal(12, 3)
|
||||||
|
actual_qty Decimal @db.Decimal(12, 3)
|
||||||
|
difference Decimal @db.Decimal(12, 3)
|
||||||
|
notes String? @db.VarChar(255)
|
||||||
|
|
||||||
|
session sklad_inventory_sessions @relation(fields: [session_id], references: [id])
|
||||||
|
item sklad_items @relation(fields: [item_id], references: [id])
|
||||||
|
location sklad_locations? @relation(fields: [location_id], references: [id])
|
||||||
|
|
||||||
|
@@index([session_id], map: "sklad_inventory_lines_session_id")
|
||||||
|
@@map("sklad_inventory_lines")
|
||||||
|
}
|
||||||
|
|
||||||
|
model plan_categories {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
key String @unique @db.VarChar(50)
|
||||||
|
label String @db.VarChar(100)
|
||||||
|
color String @db.VarChar(7)
|
||||||
|
sort_order Int @default(0)
|
||||||
|
is_active Boolean @default(true)
|
||||||
|
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||||
|
updated_at DateTime? @default(now()) @updatedAt @db.DateTime(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
model work_plan_entries {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
user_id Int
|
||||||
|
date_from DateTime @db.Date
|
||||||
|
date_to DateTime @db.Date
|
||||||
|
project_id Int?
|
||||||
|
category String @default("work") @db.VarChar(50)
|
||||||
|
note String @db.VarChar(500)
|
||||||
|
created_by Int
|
||||||
|
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||||
|
updated_at DateTime? @default(now()) @db.Timestamp(0)
|
||||||
|
is_deleted Boolean? @default(false)
|
||||||
|
users users @relation(fields: [user_id], references: [id], onDelete: Cascade, onUpdate: NoAction)
|
||||||
|
projects projects? @relation(fields: [project_id], references: [id], onDelete: SetNull, onUpdate: NoAction)
|
||||||
|
creator users @relation("work_plan_entries_creator", fields: [created_by], references: [id], onDelete: Restrict, onUpdate: NoAction)
|
||||||
|
|
||||||
|
@@index([user_id, date_from], map: "idx_wpe_user_from")
|
||||||
|
@@index([user_id, date_to], map: "idx_wpe_user_to")
|
||||||
|
@@index([project_id], map: "idx_wpe_project")
|
||||||
|
@@index([date_from, date_to], map: "idx_wpe_dates")
|
||||||
|
}
|
||||||
|
|
||||||
|
model work_plan_overrides {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
user_id Int
|
||||||
|
shift_date DateTime @db.Date
|
||||||
|
project_id Int?
|
||||||
|
category String @db.VarChar(50)
|
||||||
|
note String @db.VarChar(500)
|
||||||
|
created_by Int
|
||||||
|
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||||
|
updated_at DateTime? @default(now()) @db.Timestamp(0)
|
||||||
|
is_deleted Boolean? @default(false)
|
||||||
|
users users @relation(fields: [user_id], references: [id], onDelete: Cascade, onUpdate: NoAction)
|
||||||
|
projects projects? @relation(fields: [project_id], references: [id], onDelete: SetNull, onUpdate: NoAction)
|
||||||
|
creator users @relation("work_plan_overrides_creator", fields: [created_by], references: [id], onDelete: Restrict, onUpdate: NoAction)
|
||||||
|
|
||||||
|
@@index([user_id, shift_date], map: "idx_wpo_user_date")
|
||||||
|
@@index([shift_date], map: "idx_wpo_date")
|
||||||
|
}
|
||||||
|
|||||||
469
prisma/seed.ts
Normal file
469
prisma/seed.ts
Normal file
@@ -0,0 +1,469 @@
|
|||||||
|
import { PrismaClient } from "@prisma/client";
|
||||||
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
const PERMISSIONS: {
|
||||||
|
name: string;
|
||||||
|
display_name: string;
|
||||||
|
module: string;
|
||||||
|
description: string;
|
||||||
|
}[] = [
|
||||||
|
// Docházka
|
||||||
|
{
|
||||||
|
name: "attendance.record",
|
||||||
|
display_name: "Záznam docházky",
|
||||||
|
module: "attendance",
|
||||||
|
description: "Zapisovat příchody/odchody",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "attendance.history",
|
||||||
|
display_name: "Historie docházky",
|
||||||
|
module: "attendance",
|
||||||
|
description: "Prohlížet vlastní historii docházky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "attendance.approve",
|
||||||
|
display_name: "Schvalování docházky",
|
||||||
|
module: "attendance",
|
||||||
|
description: "Schvalovat žádosti o dovolenou/nemoc",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "attendance.manage",
|
||||||
|
display_name: "Správa docházky",
|
||||||
|
module: "attendance",
|
||||||
|
description: "Spravovat všechny záznamy, vytvářet/editovat/mazat",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "attendance.balances",
|
||||||
|
display_name: "Správa bilancí",
|
||||||
|
module: "attendance",
|
||||||
|
description: "Spravovat zůstatky dovolené a sick days",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Kniha jízd
|
||||||
|
{
|
||||||
|
name: "trips.record",
|
||||||
|
display_name: "Záznam jízd",
|
||||||
|
module: "trips",
|
||||||
|
description: "Zapisovat jízdy",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "trips.history",
|
||||||
|
display_name: "Historie jízd",
|
||||||
|
module: "trips",
|
||||||
|
description: "Prohlížet vlastní historii jízd",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "trips.manage",
|
||||||
|
display_name: "Správa jízd",
|
||||||
|
module: "trips",
|
||||||
|
description: "Spravovat všechny jízdy",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Vozidla
|
||||||
|
{
|
||||||
|
name: "vehicles.manage",
|
||||||
|
display_name: "Správa vozidel",
|
||||||
|
module: "vehicles",
|
||||||
|
description: "Spravovat vozový park",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Nabídky
|
||||||
|
{
|
||||||
|
name: "offers.view",
|
||||||
|
display_name: "Zobrazit nabídky",
|
||||||
|
module: "offers",
|
||||||
|
description: "Prohlížet seznam nabídek",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "offers.create",
|
||||||
|
display_name: "Vytvořit nabídku",
|
||||||
|
module: "offers",
|
||||||
|
description: "Vytvářet nové nabídky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "offers.edit",
|
||||||
|
display_name: "Upravit nabídku",
|
||||||
|
module: "offers",
|
||||||
|
description: "Upravovat existující nabídky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "offers.delete",
|
||||||
|
display_name: "Smazat nabídku",
|
||||||
|
module: "offers",
|
||||||
|
description: "Mazat nabídky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "offers.export",
|
||||||
|
display_name: "Exportovat nabídku",
|
||||||
|
module: "offers",
|
||||||
|
description: "Exportovat nabídky do PDF",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Objednávky
|
||||||
|
{
|
||||||
|
name: "orders.view",
|
||||||
|
display_name: "Zobrazit objednávky",
|
||||||
|
module: "orders",
|
||||||
|
description: "Prohlížet seznam objednávek",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "orders.create",
|
||||||
|
display_name: "Vytvořit objednávku",
|
||||||
|
module: "orders",
|
||||||
|
description: "Vytvářet nové objednávky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "orders.edit",
|
||||||
|
display_name: "Upravit objednávku",
|
||||||
|
module: "orders",
|
||||||
|
description: "Upravovat existující objednávky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "orders.delete",
|
||||||
|
display_name: "Smazat objednávku",
|
||||||
|
module: "orders",
|
||||||
|
description: "Mazat objednávky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "orders.export",
|
||||||
|
display_name: "Exportovat objednávku",
|
||||||
|
module: "orders",
|
||||||
|
description: "Exportovat objednávky do PDF",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Faktury
|
||||||
|
{
|
||||||
|
name: "invoices.view",
|
||||||
|
display_name: "Zobrazit faktury",
|
||||||
|
module: "invoices",
|
||||||
|
description: "Prohlížet seznam faktur",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invoices.create",
|
||||||
|
display_name: "Vytvořit fakturu",
|
||||||
|
module: "invoices",
|
||||||
|
description: "Vytvářet nové faktury",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invoices.edit",
|
||||||
|
display_name: "Upravit fakturu",
|
||||||
|
module: "invoices",
|
||||||
|
description: "Upravovat existující faktury",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invoices.delete",
|
||||||
|
display_name: "Smazat fakturu",
|
||||||
|
module: "invoices",
|
||||||
|
description: "Mazat faktury",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invoices.export",
|
||||||
|
display_name: "Exportovat fakturu",
|
||||||
|
module: "invoices",
|
||||||
|
description: "Exportovat faktury do PDF",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Projekty
|
||||||
|
{
|
||||||
|
name: "projects.view",
|
||||||
|
display_name: "Zobrazit projekty",
|
||||||
|
module: "projects",
|
||||||
|
description: "Prohlížet seznam projektů",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "projects.edit",
|
||||||
|
display_name: "Upravit projekt",
|
||||||
|
module: "projects",
|
||||||
|
description: "Upravovat existující projekty",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "projects.delete",
|
||||||
|
display_name: "Smazat projekt",
|
||||||
|
module: "projects",
|
||||||
|
description: "Mazat projekty",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "projects.files",
|
||||||
|
display_name: "Soubory projektu",
|
||||||
|
module: "projects",
|
||||||
|
description: "Spravovat soubory a složky projektu",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Zákazníci
|
||||||
|
{
|
||||||
|
name: "customers.view",
|
||||||
|
display_name: "Zobrazit zákazníky",
|
||||||
|
module: "customers",
|
||||||
|
description: "Prohlížet seznam zákazníků",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "customers.create",
|
||||||
|
display_name: "Vytvořit zákazníka",
|
||||||
|
module: "customers",
|
||||||
|
description: "Vytvářet nové zákazníky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "customers.edit",
|
||||||
|
display_name: "Upravit zákazníka",
|
||||||
|
module: "customers",
|
||||||
|
description: "Upravovat existující zákazníky",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "customers.delete",
|
||||||
|
display_name: "Smazat zákazníka",
|
||||||
|
module: "customers",
|
||||||
|
description: "Mazat zákazníky",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Uživatelé
|
||||||
|
{
|
||||||
|
name: "users.view",
|
||||||
|
display_name: "Zobrazit uživatele",
|
||||||
|
module: "users",
|
||||||
|
description: "Prohlížet seznam uživatelů",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "users.create",
|
||||||
|
display_name: "Vytvořit uživatele",
|
||||||
|
module: "users",
|
||||||
|
description: "Vytvářet nové uživatele",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "users.edit",
|
||||||
|
display_name: "Upravit uživatele",
|
||||||
|
module: "users",
|
||||||
|
description: "Upravovat existující uživatele",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "users.delete",
|
||||||
|
display_name: "Smazat uživatele",
|
||||||
|
module: "users",
|
||||||
|
description: "Mazat uživatele",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Nastavení
|
||||||
|
{
|
||||||
|
name: "settings.company",
|
||||||
|
display_name: "Nastavení společnosti",
|
||||||
|
module: "settings",
|
||||||
|
description: "Upravovat údaje o společnosti, logo",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "settings.system",
|
||||||
|
display_name: "Systémová nastavení",
|
||||||
|
module: "settings",
|
||||||
|
description: "Spravovat systémová nastavení, 2FA, e-maily, limity",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "settings.banking",
|
||||||
|
display_name: "Bankovní účty",
|
||||||
|
module: "settings",
|
||||||
|
description: "Spravovat bankovní účty společnosti",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "settings.roles",
|
||||||
|
display_name: "Role a oprávnění",
|
||||||
|
module: "settings",
|
||||||
|
description: "Spravovat role a přiřazovat oprávnění",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "settings.templates",
|
||||||
|
display_name: "Šablony",
|
||||||
|
module: "settings",
|
||||||
|
description: "Spravovat šablony nabídek a položek",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "settings.audit",
|
||||||
|
display_name: "Audit log",
|
||||||
|
module: "settings",
|
||||||
|
description: "Prohlížet auditní logy",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Sklad
|
||||||
|
{
|
||||||
|
name: "warehouse.view",
|
||||||
|
display_name: "Zobrazit sklad",
|
||||||
|
module: "warehouse",
|
||||||
|
description: "Prohlížet stav skladu, položky, reporty a historii pohybů",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "warehouse.operate",
|
||||||
|
display_name: "Příjem a výdej",
|
||||||
|
module: "warehouse",
|
||||||
|
description: "Vytvářet a potvrzovat příjmy, výdeje a rezervace",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "warehouse.manage",
|
||||||
|
display_name: "Správa skladu",
|
||||||
|
module: "warehouse",
|
||||||
|
description: "Spravovat katalog materiálů, dodavatele, lokace a kategorie",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "warehouse.inventory",
|
||||||
|
display_name: "Inventura",
|
||||||
|
module: "warehouse",
|
||||||
|
description: "Vytvářet a potvrzovat inventurní sčítkání",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log("Seeding permissions...");
|
||||||
|
|
||||||
|
// 1. Clear existing permissions and re-insert current set
|
||||||
|
await prisma.role_permissions.deleteMany({});
|
||||||
|
await prisma.permissions.deleteMany({});
|
||||||
|
console.log(" Cleared old permissions");
|
||||||
|
|
||||||
|
for (const perm of PERMISSIONS) {
|
||||||
|
await prisma.permissions.create({ data: perm });
|
||||||
|
}
|
||||||
|
console.log(` Inserted ${PERMISSIONS.length} permissions`);
|
||||||
|
|
||||||
|
// 2. Ensure admin role exists
|
||||||
|
let adminRole = await prisma.roles.findFirst({ where: { name: "admin" } });
|
||||||
|
if (!adminRole) {
|
||||||
|
adminRole = await prisma.roles.create({
|
||||||
|
data: {
|
||||||
|
name: "admin",
|
||||||
|
display_name: "Administrátor",
|
||||||
|
description: "Hlavní administrátor s plným přístupem",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log(" Created admin role");
|
||||||
|
} else {
|
||||||
|
console.log(" Admin role already exists (id=" + adminRole.id + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Assign all permissions to admin role
|
||||||
|
const allPerms = await prisma.permissions.findMany();
|
||||||
|
const existingAssignments = await prisma.role_permissions.findMany({
|
||||||
|
where: { role_id: adminRole.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete stale assignments (permissions no longer in the list)
|
||||||
|
const validIds = new Set(allPerms.map((p) => p.id));
|
||||||
|
const staleIds = existingAssignments.filter(
|
||||||
|
(a) => !validIds.has(a.permission_id),
|
||||||
|
);
|
||||||
|
if (staleIds.length > 0) {
|
||||||
|
for (const s of staleIds) {
|
||||||
|
await prisma.role_permissions.delete({
|
||||||
|
where: {
|
||||||
|
role_id_permission_id: {
|
||||||
|
role_id: adminRole.id,
|
||||||
|
permission_id: s.permission_id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log(` Removed ${staleIds.length} stale role_permissions`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add missing assignments
|
||||||
|
const existingIds = new Set(existingAssignments.map((a) => a.permission_id));
|
||||||
|
let added = 0;
|
||||||
|
for (const perm of allPerms) {
|
||||||
|
if (!existingIds.has(perm.id)) {
|
||||||
|
await prisma.role_permissions.create({
|
||||||
|
data: { role_id: adminRole.id, permission_id: perm.id },
|
||||||
|
});
|
||||||
|
added++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (added > 0) console.log(` Added ${added} role_permission assignments`);
|
||||||
|
console.log(` Admin role now has all ${allPerms.length} permissions`);
|
||||||
|
|
||||||
|
// 4. Ensure admin user exists
|
||||||
|
let adminUser = await prisma.users.findFirst({
|
||||||
|
where: { username: "admin" },
|
||||||
|
});
|
||||||
|
if (!adminUser) {
|
||||||
|
const hash = bcrypt.hashSync("admin", 10);
|
||||||
|
adminUser = await prisma.users.create({
|
||||||
|
data: {
|
||||||
|
username: "admin",
|
||||||
|
email: "admin@boha.local",
|
||||||
|
password_hash: hash,
|
||||||
|
first_name: "Admin",
|
||||||
|
last_name: "BOHA",
|
||||||
|
role_id: adminRole.id,
|
||||||
|
is_active: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log(" Created admin user (admin / admin)");
|
||||||
|
} else if (adminUser.role_id !== adminRole.id) {
|
||||||
|
await prisma.users.update({
|
||||||
|
where: { id: adminUser.id },
|
||||||
|
data: { role_id: adminRole.id },
|
||||||
|
});
|
||||||
|
console.log(" Updated admin user role_id to admin role");
|
||||||
|
} else {
|
||||||
|
console.log(" Admin user already exists with correct role");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Create default company_settings if not exists
|
||||||
|
const existingSettings = await prisma.company_settings.findFirst();
|
||||||
|
if (!existingSettings) {
|
||||||
|
await prisma.company_settings.create({
|
||||||
|
data: {
|
||||||
|
company_name: "BOHA s.r.o.",
|
||||||
|
default_currency: "CZK",
|
||||||
|
default_vat_rate: 21.0,
|
||||||
|
available_vat_rates: JSON.stringify([0, 10, 15, 21]),
|
||||||
|
available_currencies: JSON.stringify(["CZK", "EUR"]),
|
||||||
|
offer_number_pattern: "NAB-{YYYY}-{NNN}",
|
||||||
|
order_number_pattern: "OBJ-{YYYY}-{NNN}",
|
||||||
|
invoice_number_pattern: "FV-{YYYY}-{NNN}",
|
||||||
|
break_threshold_hours: 6.0,
|
||||||
|
break_duration_short: 15,
|
||||||
|
break_duration_long: 30,
|
||||||
|
clock_rounding_minutes: 15,
|
||||||
|
require_2fa: false,
|
||||||
|
max_login_attempts: 5,
|
||||||
|
lockout_minutes: 15,
|
||||||
|
max_requests_per_minute: 300,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log(" Created default company_settings");
|
||||||
|
} else {
|
||||||
|
console.log(" company_settings already exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Initialize number_sequences for current year
|
||||||
|
const year = new Date().getFullYear();
|
||||||
|
const types = [
|
||||||
|
"quotation",
|
||||||
|
"order",
|
||||||
|
"invoice",
|
||||||
|
"warehouse_receipt",
|
||||||
|
"warehouse_issue",
|
||||||
|
"warehouse_inventory",
|
||||||
|
];
|
||||||
|
for (const type of types) {
|
||||||
|
const existing = await prisma.number_sequences.findFirst({
|
||||||
|
where: { type, year },
|
||||||
|
});
|
||||||
|
if (!existing) {
|
||||||
|
await prisma.number_sequences.create({
|
||||||
|
data: { type, year, last_number: 0 },
|
||||||
|
});
|
||||||
|
console.log(` Created number_sequence: ${type}/${year}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(" number_sequences ready");
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
"\nSeed complete — " +
|
||||||
|
PERMISSIONS.length +
|
||||||
|
" permissions, 1 admin role, company_settings + number_sequences ready.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error("Seed failed:", e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(() => prisma.$disconnect());
|
||||||
886
src/__tests__/plan.test.ts
Normal file
886
src/__tests__/plan.test.ts
Normal file
@@ -0,0 +1,886 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest";
|
||||||
|
import Fastify from "fastify";
|
||||||
|
import cookie from "@fastify/cookie";
|
||||||
|
import rateLimit from "@fastify/rate-limit";
|
||||||
|
import jwt from "jsonwebtoken";
|
||||||
|
import prisma from "../config/database";
|
||||||
|
import { config } from "../config/env";
|
||||||
|
import { securityHeaders } from "../middleware/security";
|
||||||
|
import planRoutes from "../routes/admin/plan";
|
||||||
|
import {
|
||||||
|
resolveCell,
|
||||||
|
resolveGrid,
|
||||||
|
listPlanUsers,
|
||||||
|
assertNotPastDate,
|
||||||
|
createEntry,
|
||||||
|
updateEntry,
|
||||||
|
deleteEntry,
|
||||||
|
createOverride,
|
||||||
|
updateOverride,
|
||||||
|
deleteOverride,
|
||||||
|
listEntries,
|
||||||
|
listOverrides,
|
||||||
|
} from "../services/plan.service";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Test fixtures
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Note-prefix for test-created rows so we can clean them up safely. */
|
||||||
|
const N = "wh_plan_";
|
||||||
|
|
||||||
|
let adminUserId: number;
|
||||||
|
let noPermUserId: number;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
// Pick the first admin user from the test database as our fixture.
|
||||||
|
// The users -> roles relation is named `roles` in the Prisma schema
|
||||||
|
// (users.role_id references roles.id).
|
||||||
|
const admin = await prisma.users.findFirst({
|
||||||
|
where: { roles: { name: "admin" } },
|
||||||
|
});
|
||||||
|
if (!admin) throw new Error("Test setup: admin user not found");
|
||||||
|
adminUserId = admin.id;
|
||||||
|
|
||||||
|
// For list-scoping tests: any non-admin user that is NOT the admin we use
|
||||||
|
// for create tests. Just pick the second user.
|
||||||
|
const allUsers = await prisma.users.findMany({ take: 2 });
|
||||||
|
noPermUserId =
|
||||||
|
allUsers.find((u) => u.id !== adminUserId)?.id ?? allUsers[0].id;
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
// Clean up any leftover test data from previous runs. We only touch rows
|
||||||
|
// whose `note` contains our test prefix, so we never disturb real data.
|
||||||
|
await prisma.work_plan_entries.deleteMany({
|
||||||
|
where: { note: { contains: N } },
|
||||||
|
});
|
||||||
|
await prisma.work_plan_overrides.deleteMany({
|
||||||
|
where: { note: { contains: N } },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
// Final cleanup so we never leave soft-deleted test rows behind.
|
||||||
|
await prisma.work_plan_entries.deleteMany({
|
||||||
|
where: { note: { contains: N } },
|
||||||
|
});
|
||||||
|
await prisma.work_plan_overrides.deleteMany({
|
||||||
|
where: { note: { contains: N } },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// resolveCell
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.resolveCell", () => {
|
||||||
|
it("returns null when nothing covers the date", async () => {
|
||||||
|
// No entry, no override for (adminUserId, "2099-01-01")
|
||||||
|
const result = await resolveCell(adminUserId, "2099-01-01");
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the entry that covers the date", 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}PLC upgrade`,
|
||||||
|
created_by: adminUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result?.source).toBe("entry");
|
||||||
|
expect(result?.note).toBe(`${N}PLC upgrade`);
|
||||||
|
expect(result?.category).toBe("work");
|
||||||
|
expect(result?.rangeFrom).toBe("2099-06-01");
|
||||||
|
expect(result?.rangeTo).toBe("2099-06-10");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the override for that day, not the entry", async () => {
|
||||||
|
// An entry covers 2099-06-01..2099-06-10, but an override on 2099-06-05
|
||||||
|
// takes precedence.
|
||||||
|
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}PLC upgrade`,
|
||||||
|
created_by: adminUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await prisma.work_plan_overrides.create({
|
||||||
|
data: {
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: new Date("2099-06-05"),
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}Volno po noční`,
|
||||||
|
created_by: adminUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result?.source).toBe("override");
|
||||||
|
expect(result?.note).toBe(`${N}Volno po noční`);
|
||||||
|
expect(result?.category).toBe("leave");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores soft-deleted entries and overrides", 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}deleted entry`,
|
||||||
|
is_deleted: true,
|
||||||
|
created_by: adminUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const result = await resolveCell(adminUserId, "2099-06-05");
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// resolveGrid
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.resolveGrid", () => {
|
||||||
|
it("returns a 2D map keyed by userId then date", async () => {
|
||||||
|
await prisma.work_plan_entries.create({
|
||||||
|
data: {
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: new Date("2099-06-01"),
|
||||||
|
date_to: new Date("2099-06-03"),
|
||||||
|
category: "work",
|
||||||
|
note: `${N}A`,
|
||||||
|
created_by: adminUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-05");
|
||||||
|
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
|
||||||
|
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}A`);
|
||||||
|
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
||||||
|
expect(cells[adminUserId]["2099-06-04"]).toBeNull();
|
||||||
|
expect(cells[adminUserId]["2099-06-05"]).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies override on a covered day", async () => {
|
||||||
|
await prisma.work_plan_entries.create({
|
||||||
|
data: {
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: new Date("2099-06-01"),
|
||||||
|
date_to: new Date("2099-06-03"),
|
||||||
|
category: "work",
|
||||||
|
note: `${N}A`,
|
||||||
|
created_by: adminUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await prisma.work_plan_overrides.create({
|
||||||
|
data: {
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: new Date("2099-06-02"),
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}B`,
|
||||||
|
created_by: adminUserId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const cells = await resolveGrid([adminUserId], "2099-06-01", "2099-06-03");
|
||||||
|
expect(cells[adminUserId]["2099-06-01"]?.note).toBe(`${N}A`);
|
||||||
|
expect(cells[adminUserId]["2099-06-02"]?.note).toBe(`${N}B`);
|
||||||
|
expect(cells[adminUserId]["2099-06-03"]?.note).toBe(`${N}A`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// listPlanUsers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.listPlanUsers", () => {
|
||||||
|
it("returns at least the admin user", async () => {
|
||||||
|
const users = await listPlanUsers();
|
||||||
|
const found = users.find((u) => u.id === adminUserId);
|
||||||
|
expect(found).toBeDefined();
|
||||||
|
expect(found?.has_attendance_record).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// assertNotPastDate
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.assertNotPastDate", () => {
|
||||||
|
it("returns error for a past date", () => {
|
||||||
|
const result = assertNotPastDate("2000-01-01", false);
|
||||||
|
expect(result).toEqual({
|
||||||
|
error:
|
||||||
|
"Nelze upravovat plán pro datum v minulosti. Pro nouzovou opravu použijte ?force=1.",
|
||||||
|
status: 403,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for a future date", () => {
|
||||||
|
const result = assertNotPastDate("2099-01-01", false);
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for a past date with force=true", () => {
|
||||||
|
const result = assertNotPastDate("2000-01-01", true);
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// createEntry
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.createEntry", () => {
|
||||||
|
it("creates an entry and returns { data, oldData: null }", async () => {
|
||||||
|
const result = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2099-07-01",
|
||||||
|
date_to: "2099-07-05",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}new entry`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("data" in result).toBe(true);
|
||||||
|
if ("data" in result) {
|
||||||
|
expect(result.data.note).toBe(`${N}new entry`);
|
||||||
|
expect(result.oldData).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a past date without force", async () => {
|
||||||
|
const result = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2000-01-01",
|
||||||
|
date_to: "2000-01-02",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}past`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("error" in result).toBe(true);
|
||||||
|
if ("error" in result) expect(result.status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows a past date with force", async () => {
|
||||||
|
const result = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2000-01-01",
|
||||||
|
date_to: "2000-01-02",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}past forced`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect("data" in result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects when date_to < date_from", async () => {
|
||||||
|
const result = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2099-07-10",
|
||||||
|
date_to: "2099-07-05",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}invalid range`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("error" in result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows an empty note (text is optional)", async () => {
|
||||||
|
const result = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2099-07-15",
|
||||||
|
date_to: "2099-07-15",
|
||||||
|
category: "work",
|
||||||
|
note: "",
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("data" in result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a range whose date_to is in the past, even if date_from is today", async () => {
|
||||||
|
// The range check `date_to >= date_from` fires before the past-date
|
||||||
|
// check, so a backwards range returns 400 (correct UX). The to-endpoint
|
||||||
|
// past-date check matters when updating an existing entry — see the
|
||||||
|
// matching test in updateEntry below. Here we just confirm that a
|
||||||
|
// range whose start is in the past is rejected as 403.
|
||||||
|
const result = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2000-01-01",
|
||||||
|
date_to: "2000-01-05",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}past-both`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("error" in result).toBe(true);
|
||||||
|
if ("error" in result) expect(result.status).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// updateEntry
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.updateEntry", () => {
|
||||||
|
it("updates the note and returns the old data", async () => {
|
||||||
|
const created = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2099-08-01",
|
||||||
|
date_to: "2099-08-03",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}original`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if (!("data" in created)) throw new Error("setup failed");
|
||||||
|
|
||||||
|
const updated = await updateEntry(
|
||||||
|
created.data.id,
|
||||||
|
{ note: `${N}updated` },
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("data" in updated).toBe(true);
|
||||||
|
if ("data" in updated) {
|
||||||
|
expect(updated.data.note).toBe(`${N}updated`);
|
||||||
|
expect((updated.oldData as any).note).toBe(`${N}original`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an update that pushes date_to into the past", async () => {
|
||||||
|
// Future entry, but the user tries to extend its end backwards into
|
||||||
|
// the past. The to-endpoint past-date check should fire.
|
||||||
|
const created = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2099-08-10",
|
||||||
|
date_to: "2099-08-15",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}to-shorten`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if (!("data" in created)) throw new Error("setup failed");
|
||||||
|
const updated = await updateEntry(
|
||||||
|
created.data.id,
|
||||||
|
{ date_to: "2000-01-05" },
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("error" in updated).toBe(true);
|
||||||
|
if ("error" in updated) expect(updated.status).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// deleteEntry
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.deleteEntry", () => {
|
||||||
|
it("soft-deletes the row and returns the old data", async () => {
|
||||||
|
const created = await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2099-09-01",
|
||||||
|
date_to: "2099-09-01",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}to delete`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if (!("data" in created)) throw new Error("setup failed");
|
||||||
|
|
||||||
|
const result = await deleteEntry(created.data.id, adminUserId, false);
|
||||||
|
expect("data" in result).toBe(true);
|
||||||
|
if ("data" in result) {
|
||||||
|
expect(result.data).toEqual({ ok: true });
|
||||||
|
expect((result.oldData as any).note).toBe(`${N}to delete`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const stillThere = await prisma.work_plan_entries.findUnique({
|
||||||
|
where: { id: created.data.id },
|
||||||
|
});
|
||||||
|
expect(stillThere?.is_deleted).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// createOverride
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.createOverride", () => {
|
||||||
|
it("creates an override and returns { data, oldData: null, replacedData: null }", async () => {
|
||||||
|
const result = await createOverride(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2099-10-01",
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}day off`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("data" in result).toBe(true);
|
||||||
|
if ("data" in result) {
|
||||||
|
expect(result.data.note).toBe(`${N}day off`);
|
||||||
|
expect(result.oldData).toBeNull();
|
||||||
|
expect(result.replacedData).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("soft-deletes the existing override and reports it in replacedData", async () => {
|
||||||
|
await createOverride(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2099-10-02",
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}first`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
const second = await createOverride(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2099-10-02",
|
||||||
|
category: "sick",
|
||||||
|
note: `${N}second`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("data" in second).toBe(true);
|
||||||
|
if ("data" in second) {
|
||||||
|
expect((second.replacedData as any)?.note).toBe(`${N}first`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const all = await prisma.work_plan_overrides.findMany({
|
||||||
|
where: { user_id: adminUserId, shift_date: new Date("2099-10-02") },
|
||||||
|
});
|
||||||
|
// The first should be soft-deleted, the second active
|
||||||
|
expect(all.find((o) => o.note === `${N}first`)?.is_deleted).toBe(true);
|
||||||
|
expect(all.find((o) => o.note === `${N}second`)?.is_deleted).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a past date without force", async () => {
|
||||||
|
const result = await createOverride(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2000-01-01",
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}past`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("error" in result).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// updateOverride
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.updateOverride", () => {
|
||||||
|
it("updates the note and returns the old data", async () => {
|
||||||
|
const created = await createOverride(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2099-11-01",
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}original`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if (!("data" in created)) throw new Error("setup");
|
||||||
|
const updated = await updateOverride(
|
||||||
|
created.data.id,
|
||||||
|
{ note: `${N}updated` },
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect("data" in updated).toBe(true);
|
||||||
|
if ("data" in updated) {
|
||||||
|
expect(updated.data.note).toBe(`${N}updated`);
|
||||||
|
expect((updated.oldData as any).note).toBe(`${N}original`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// deleteOverride
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.deleteOverride", () => {
|
||||||
|
it("soft-deletes the override and returns the old data", async () => {
|
||||||
|
const created = await createOverride(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2099-12-01",
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}to delete`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if (!("data" in created)) throw new Error("setup");
|
||||||
|
const result = await deleteOverride(created.data.id, adminUserId, false);
|
||||||
|
expect("data" in result).toBe(true);
|
||||||
|
if ("data" in result) {
|
||||||
|
expect(result.data).toEqual({ ok: true });
|
||||||
|
expect((result.oldData as any).note).toBe(`${N}to delete`);
|
||||||
|
}
|
||||||
|
const still = await prisma.work_plan_overrides.findUnique({
|
||||||
|
where: { id: created.data.id },
|
||||||
|
});
|
||||||
|
expect(still?.is_deleted).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// listEntries / listOverrides (employee scoping)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe("plan.service.listEntries (employee scoping)", () => {
|
||||||
|
it("returns entries for the actor user when scoped", async () => {
|
||||||
|
await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2098-01-01",
|
||||||
|
date_to: "2098-01-05",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}scope test`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
const rows = await listEntries(
|
||||||
|
{ user_id: adminUserId, date_from: "2098-01-01", date_to: "2098-01-31" },
|
||||||
|
adminUserId,
|
||||||
|
true, // isAdmin
|
||||||
|
);
|
||||||
|
expect(rows.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("scopes non-admin to actor user_id when querying for another user", async () => {
|
||||||
|
await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2098-02-01",
|
||||||
|
date_to: "2098-02-05",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}admin entry`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
const rows = await listEntries(
|
||||||
|
{ user_id: adminUserId, date_from: "2098-02-01", date_to: "2098-02-28" },
|
||||||
|
noPermUserId,
|
||||||
|
false, // not admin
|
||||||
|
);
|
||||||
|
expect(rows).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("plan.service.listOverrides (employee scoping)", () => {
|
||||||
|
it("scopes non-admin to actor user_id", async () => {
|
||||||
|
await createOverride(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2098-03-01",
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}admin override`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
const rows = await listOverrides(
|
||||||
|
{ user_id: adminUserId, date_from: "2098-03-01", date_to: "2098-03-31" },
|
||||||
|
noPermUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(rows).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// HTTP route tests (Fastify inject)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Build a Fastify app with only the plan routes registered under
|
||||||
|
// /api/admin/plan. rateLimit max=1000 keeps the 7 tests from tripping it.
|
||||||
|
let app: Awaited<ReturnType<typeof buildApp>>;
|
||||||
|
let adminToken: string;
|
||||||
|
let noPermToken: string;
|
||||||
|
let noPermRoleId: number;
|
||||||
|
|
||||||
|
async function buildApp() {
|
||||||
|
const a = Fastify({ logger: false });
|
||||||
|
await a.register(cookie);
|
||||||
|
await a.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||||
|
a.addHook("onRequest", securityHeaders);
|
||||||
|
await a.register(planRoutes, { prefix: "/api/admin/plan" });
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a JWT access token. `requireAuth` re-loads auth data from the
|
||||||
|
* DB via `loadAuthData(payload.sub)`, so the `role` claim is ignored —
|
||||||
|
* only the `sub` (user id) matters for these tests.
|
||||||
|
*/
|
||||||
|
function generateToken(user: {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
roleName: string | null;
|
||||||
|
}): string {
|
||||||
|
return jwt.sign(
|
||||||
|
{ sub: user.id, username: user.username, role: user.roleName },
|
||||||
|
config.jwt.secret,
|
||||||
|
{ expiresIn: "15m" },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authGet(path: string, token: string) {
|
||||||
|
return app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: path,
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authPost(path: string, token: string, body: unknown) {
|
||||||
|
return app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: path,
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
payload: body as object,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authPatch(path: string, token: string, body: unknown) {
|
||||||
|
return app.inject({
|
||||||
|
method: "PATCH",
|
||||||
|
url: path,
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
payload: body as object,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authDelete(path: string, token: string) {
|
||||||
|
return app.inject({
|
||||||
|
method: "DELETE",
|
||||||
|
url: path,
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await buildApp();
|
||||||
|
|
||||||
|
// Re-fetch the admin user with the roles relation so we can build a token.
|
||||||
|
const admin = await prisma.users.findFirst({
|
||||||
|
where: { roles: { name: "admin" } },
|
||||||
|
include: { roles: true },
|
||||||
|
});
|
||||||
|
if (!admin) throw new Error("admin user not found in test setup");
|
||||||
|
adminUserId = admin.id;
|
||||||
|
adminToken = generateToken({
|
||||||
|
id: admin.id,
|
||||||
|
username: admin.username,
|
||||||
|
roleName: admin.roles?.name ?? null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a no-permission role + user; the role has zero permissions so
|
||||||
|
// any permission check returns 403.
|
||||||
|
const stamp = Date.now();
|
||||||
|
const noPermRole = await prisma.roles.create({
|
||||||
|
data: {
|
||||||
|
name: `noperm_plan_${stamp}`,
|
||||||
|
display_name: "No Perm Plan Test",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
noPermRoleId = noPermRole.id;
|
||||||
|
const noPermUser = await prisma.users.create({
|
||||||
|
data: {
|
||||||
|
username: `noperm_plan_${stamp}`,
|
||||||
|
first_name: "No",
|
||||||
|
last_name: "Perm",
|
||||||
|
email: `noperm_plan_${stamp}@test.local`,
|
||||||
|
password_hash:
|
||||||
|
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||||
|
role_id: noPermRole.id,
|
||||||
|
is_active: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
noPermUserId = noPermUser.id;
|
||||||
|
noPermToken = generateToken({
|
||||||
|
id: noPermUser.id,
|
||||||
|
username: noPermUser.username,
|
||||||
|
roleName: noPermRole.name,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (app) await app.close();
|
||||||
|
if (noPermUserId) {
|
||||||
|
await prisma.users
|
||||||
|
.deleteMany({ where: { id: noPermUserId } })
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
if (noPermRoleId) {
|
||||||
|
await prisma.roles
|
||||||
|
.deleteMany({ where: { id: noPermRoleId } })
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("HTTP /api/admin/plan", () => {
|
||||||
|
it("GET /users requires auth", async () => {
|
||||||
|
const res = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/api/admin/plan/users",
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("GET /users returns plan users for an admin", async () => {
|
||||||
|
const res = await authGet("/api/admin/plan/users", adminToken);
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(Array.isArray(body.data)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("GET /grid returns days, users, cells", async () => {
|
||||||
|
// Seed an entry so the cell on 2097-06-01 has a known note.
|
||||||
|
await createEntry(
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2097-06-01",
|
||||||
|
date_to: "2097-06-05",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}grid test`,
|
||||||
|
},
|
||||||
|
adminUserId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
const res = await authGet(
|
||||||
|
"/api/admin/plan/grid?date_from=2097-06-01&date_to=2097-06-05",
|
||||||
|
adminToken,
|
||||||
|
);
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.data.users).toBeDefined();
|
||||||
|
expect(body.data.cells[adminUserId]).toBeDefined();
|
||||||
|
expect(body.data.cells[adminUserId]["2097-06-01"].note).toBe(
|
||||||
|
`${N}grid test`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("GET /grid rejects ranges > 92 days", async () => {
|
||||||
|
const res = await authGet(
|
||||||
|
"/api/admin/plan/grid?date_from=2097-01-01&date_to=2097-12-31",
|
||||||
|
adminToken,
|
||||||
|
);
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /entries requires attendance.manage", async () => {
|
||||||
|
const res = await authPost("/api/admin/plan/entries", noPermToken, {
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2097-07-01",
|
||||||
|
date_to: "2097-07-01",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}forbidden`,
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /entries works for admin", async () => {
|
||||||
|
const res = await authPost("/api/admin/plan/entries", adminToken, {
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2097-08-01",
|
||||||
|
date_to: "2097-08-01",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}http create`,
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(201);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(body.data.note).toBe(`${N}http create`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /entries accepts an empty note (note is optional)", async () => {
|
||||||
|
const res = await authPost("/api/admin/plan/entries", adminToken, {
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2097-08-05",
|
||||||
|
date_to: "2097-08-05",
|
||||||
|
category: "work",
|
||||||
|
note: "",
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(201);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /entries rejects a past date without ?force=1", async () => {
|
||||||
|
const res = await authPost("/api/admin/plan/entries", adminToken, {
|
||||||
|
user_id: adminUserId,
|
||||||
|
date_from: "2000-02-01",
|
||||||
|
date_to: "2000-02-01",
|
||||||
|
category: "work",
|
||||||
|
note: `${N}past http`,
|
||||||
|
});
|
||||||
|
expect(res.statusCode).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /overrides with force=1 allows past date", async () => {
|
||||||
|
const res = await authPost(
|
||||||
|
"/api/admin/plan/overrides?force=1",
|
||||||
|
adminToken,
|
||||||
|
{
|
||||||
|
user_id: adminUserId,
|
||||||
|
shift_date: "2000-01-15",
|
||||||
|
category: "leave",
|
||||||
|
note: `${N}forced past`,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(res.statusCode).toBe(201);
|
||||||
|
});
|
||||||
|
});
|
||||||
95
src/__tests__/planAuditDescription.test.ts
Normal file
95
src/__tests__/planAuditDescription.test.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import {
|
||||||
|
planCategoryLabel,
|
||||||
|
buildPlanAuditDescription,
|
||||||
|
} from "../utils/planAuditDescription";
|
||||||
|
|
||||||
|
describe("planCategoryLabel", () => {
|
||||||
|
it("maps known plan categories to Czech labels", () => {
|
||||||
|
expect(planCategoryLabel("work")).toBe("Práce");
|
||||||
|
expect(planCategoryLabel("preparation")).toBe("Příprava");
|
||||||
|
expect(planCategoryLabel("travel")).toBe("Cesta / Montáž");
|
||||||
|
expect(planCategoryLabel("leave")).toBe("Dovolená");
|
||||||
|
expect(planCategoryLabel("sick")).toBe("Nemoc");
|
||||||
|
expect(planCategoryLabel("training")).toBe("Školení");
|
||||||
|
expect(planCategoryLabel("other")).toBe("Jiné");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the raw value for an unknown category", () => {
|
||||||
|
expect(planCategoryLabel("unknown_xyz")).toBe("unknown_xyz");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildPlanAuditDescription", () => {
|
||||||
|
it("describes a multi-day entry with project", () => {
|
||||||
|
const desc = buildPlanAuditDescription({
|
||||||
|
userName: "Jan Novák",
|
||||||
|
categoryLabel: "Práce",
|
||||||
|
projectName: "Rekonstrukce haly",
|
||||||
|
dateFrom: "2026-06-08",
|
||||||
|
dateTo: "2026-06-12",
|
||||||
|
});
|
||||||
|
expect(desc).toBe(
|
||||||
|
"Jan Novák · 08.06.2026 – 12.06.2026 · Práce · Rekonstrukce haly",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("collapses a single-day range to one date", () => {
|
||||||
|
const desc = buildPlanAuditDescription({
|
||||||
|
userName: "Jan Novák",
|
||||||
|
categoryLabel: "Práce",
|
||||||
|
projectName: "Rekonstrukce haly",
|
||||||
|
dateFrom: "2026-06-08",
|
||||||
|
dateTo: "2026-06-08",
|
||||||
|
});
|
||||||
|
expect(desc).toBe("Jan Novák · 08.06.2026 · Práce · Rekonstrukce haly");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("omits the project segment when there is no project", () => {
|
||||||
|
const desc = buildPlanAuditDescription({
|
||||||
|
userName: "Petr Svoboda",
|
||||||
|
categoryLabel: "Dovolená",
|
||||||
|
projectName: null,
|
||||||
|
dateFrom: "2026-06-10",
|
||||||
|
dateTo: "2026-06-10",
|
||||||
|
});
|
||||||
|
expect(desc).toBe("Petr Svoboda · 10.06.2026 · Dovolená");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("appends the emergency-edit note when force is set", () => {
|
||||||
|
const desc = buildPlanAuditDescription({
|
||||||
|
userName: "Jan Novák",
|
||||||
|
categoryLabel: "Práce",
|
||||||
|
projectName: null,
|
||||||
|
dateFrom: "2026-01-02",
|
||||||
|
dateTo: "2026-01-02",
|
||||||
|
force: true,
|
||||||
|
});
|
||||||
|
expect(desc).toBe("Jan Novák · 02.01.2026 · Práce · nouzová úprava");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("appends a custom suffix (e.g. replaced override)", () => {
|
||||||
|
const desc = buildPlanAuditDescription({
|
||||||
|
userName: "Jan Novák",
|
||||||
|
categoryLabel: "Nemoc",
|
||||||
|
projectName: null,
|
||||||
|
dateFrom: "2026-06-10",
|
||||||
|
dateTo: "2026-06-10",
|
||||||
|
suffix: "nahrazeno novým záznamem",
|
||||||
|
});
|
||||||
|
expect(desc).toBe(
|
||||||
|
"Jan Novák · 10.06.2026 · Nemoc · nahrazeno novým záznamem",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats a whitespace-only project name as no project", () => {
|
||||||
|
const desc = buildPlanAuditDescription({
|
||||||
|
userName: "Jan Novák",
|
||||||
|
categoryLabel: "Práce",
|
||||||
|
projectName: " ",
|
||||||
|
dateFrom: "2026-06-08",
|
||||||
|
dateTo: "2026-06-08",
|
||||||
|
});
|
||||||
|
expect(desc).toBe("Jan Novák · 08.06.2026 · Práce");
|
||||||
|
});
|
||||||
|
});
|
||||||
129
src/__tests__/planCategory.test.ts
Normal file
129
src/__tests__/planCategory.test.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import { describe, it, expect, afterAll } from "vitest";
|
||||||
|
import prisma from "../config/database";
|
||||||
|
import {
|
||||||
|
listPlanCategories,
|
||||||
|
createPlanCategory,
|
||||||
|
updatePlanCategory,
|
||||||
|
deactivatePlanCategory,
|
||||||
|
deletePlanCategory,
|
||||||
|
isCategoryKeyActive,
|
||||||
|
slugifyCategory,
|
||||||
|
} from "../services/planCategory.service";
|
||||||
|
|
||||||
|
const created: number[] = [];
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (created.length) {
|
||||||
|
await prisma.plan_categories.deleteMany({ where: { id: { in: created } } });
|
||||||
|
}
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("slugifyCategory", () => {
|
||||||
|
it("strips Czech diacritics and non-alphanumerics", () => {
|
||||||
|
expect(slugifyCategory("Cesta / Montáž")).toBe("cesta_montaz");
|
||||||
|
expect(slugifyCategory("Příprava")).toBe("priprava");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("plan category service", () => {
|
||||||
|
it("seeds are present and ordered", async () => {
|
||||||
|
const cats = await listPlanCategories(true);
|
||||||
|
const keys = cats.map((c) => c.key);
|
||||||
|
expect(keys).toContain("work");
|
||||||
|
expect(keys).toContain("other");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates a category with a unique slug and next sort_order", async () => {
|
||||||
|
const res = await createPlanCategory({
|
||||||
|
label: "Test Kategorie ZZ",
|
||||||
|
color: "#123456",
|
||||||
|
});
|
||||||
|
if ("error" in res) throw new Error(res.error);
|
||||||
|
created.push(res.data.id);
|
||||||
|
expect(res.data.key).toBe("test_kategorie_zz");
|
||||||
|
expect(res.data.color).toBe("#123456");
|
||||||
|
expect(res.data.is_active).toBe(true);
|
||||||
|
expect(await isCategoryKeyActive("test_kategorie_zz")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dedupes a colliding slug", async () => {
|
||||||
|
const res = await createPlanCategory({
|
||||||
|
label: "Test Kategorie ZZ",
|
||||||
|
color: "#222222",
|
||||||
|
});
|
||||||
|
if ("error" in res) throw new Error(res.error);
|
||||||
|
created.push(res.data.id);
|
||||||
|
expect(res.data.key).toBe("test_kategorie_zz_2");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("updates label and color (key immutable)", async () => {
|
||||||
|
const res = await createPlanCategory({
|
||||||
|
label: "Test Upd ZZ",
|
||||||
|
color: "#aaaaaa",
|
||||||
|
});
|
||||||
|
if ("error" in res) throw new Error(res.error);
|
||||||
|
created.push(res.data.id);
|
||||||
|
const upd = await updatePlanCategory(res.data.id, {
|
||||||
|
label: "Test Upd2 ZZ",
|
||||||
|
color: "#bbbbbb",
|
||||||
|
});
|
||||||
|
if ("error" in upd) throw new Error(upd.error);
|
||||||
|
expect(upd.data.label).toBe("Test Upd2 ZZ");
|
||||||
|
expect(upd.data.color).toBe("#bbbbbb");
|
||||||
|
expect(upd.data.key).toBe("test_upd_zz");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("deactivate hides the key from active check", async () => {
|
||||||
|
const res = await createPlanCategory({
|
||||||
|
label: "Test Deact ZZ",
|
||||||
|
color: "#cccccc",
|
||||||
|
});
|
||||||
|
if ("error" in res) throw new Error(res.error);
|
||||||
|
created.push(res.data.id);
|
||||||
|
await deactivatePlanCategory(res.data.id);
|
||||||
|
expect(await isCategoryKeyActive("test_deact_zz")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hard-deletes an unused category", async () => {
|
||||||
|
const res = await createPlanCategory({
|
||||||
|
label: "Test Del ZZ",
|
||||||
|
color: "#dddddd",
|
||||||
|
});
|
||||||
|
if ("error" in res) throw new Error(res.error);
|
||||||
|
const del = await deletePlanCategory(res.data.id);
|
||||||
|
expect("data" in del).toBe(true);
|
||||||
|
const stillThere = await prisma.plan_categories.findUnique({
|
||||||
|
where: { id: res.data.id },
|
||||||
|
});
|
||||||
|
expect(stillThere).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses to hard-delete a category in use", async () => {
|
||||||
|
const res = await createPlanCategory({
|
||||||
|
label: "Test InUse ZZ",
|
||||||
|
color: "#eeeeee",
|
||||||
|
});
|
||||||
|
if ("error" in res) throw new Error(res.error);
|
||||||
|
created.push(res.data.id);
|
||||||
|
const user = await prisma.users.findFirst({ select: { id: true } });
|
||||||
|
if (!user) throw new Error("no user in test DB");
|
||||||
|
const entry = await prisma.work_plan_entries.create({
|
||||||
|
data: {
|
||||||
|
user_id: user.id,
|
||||||
|
date_from: new Date("2026-06-10T00:00:00.000Z"),
|
||||||
|
date_to: new Date("2026-06-10T00:00:00.000Z"),
|
||||||
|
category: res.data.key,
|
||||||
|
note: "test in-use",
|
||||||
|
created_by: user.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const del = await deletePlanCategory(res.data.id);
|
||||||
|
expect("error" in del).toBe(true);
|
||||||
|
if ("error" in del) expect(del.status).toBe(409);
|
||||||
|
} finally {
|
||||||
|
await prisma.work_plan_entries.delete({ where: { id: entry.id } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
1244
src/__tests__/warehouse.test.ts
Normal file
1244
src/__tests__/warehouse.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,9 @@
|
|||||||
import { lazy, Suspense } from "react";
|
import { lazy, Suspense } from "react";
|
||||||
import { Routes, Route } from "react-router-dom";
|
import { Routes, Route } from "react-router-dom";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { AuthProvider } from "./context/AuthContext";
|
import { AuthProvider } from "./context/AuthContext";
|
||||||
import { AlertProvider } from "./context/AlertContext";
|
import { AlertProvider } from "./context/AlertContext";
|
||||||
|
import { queryClient } from "./lib/queryClient";
|
||||||
import ErrorBoundary from "./components/ErrorBoundary";
|
import ErrorBoundary from "./components/ErrorBoundary";
|
||||||
import AdminLayout from "./components/AdminLayout";
|
import AdminLayout from "./components/AdminLayout";
|
||||||
import AlertContainer from "./components/AlertContainer";
|
import AlertContainer from "./components/AlertContainer";
|
||||||
@@ -14,7 +16,6 @@ import "./buttons.css";
|
|||||||
import "./layout.css";
|
import "./layout.css";
|
||||||
import "./components.css";
|
import "./components.css";
|
||||||
import "./tables.css";
|
import "./tables.css";
|
||||||
import "./skeleton.css";
|
|
||||||
import "./datepicker.css";
|
import "./datepicker.css";
|
||||||
import "./filemanager.css";
|
import "./filemanager.css";
|
||||||
import "./pagination.css";
|
import "./pagination.css";
|
||||||
@@ -22,9 +23,11 @@ import "./responsive.css";
|
|||||||
import "./login.css";
|
import "./login.css";
|
||||||
import "./dashboard.css";
|
import "./dashboard.css";
|
||||||
import "./attendance.css";
|
import "./attendance.css";
|
||||||
|
import "./plan.css";
|
||||||
import "./settings.css";
|
import "./settings.css";
|
||||||
import "./offers.css";
|
import "./offers.css";
|
||||||
import "./invoices.css";
|
import "./invoices.css";
|
||||||
|
import "./warehouse.css";
|
||||||
|
|
||||||
const Users = lazy(() => import("./pages/Users"));
|
const Users = lazy(() => import("./pages/Users"));
|
||||||
const Attendance = lazy(() => import("./pages/Attendance"));
|
const Attendance = lazy(() => import("./pages/Attendance"));
|
||||||
@@ -35,6 +38,7 @@ const AttendanceCreate = lazy(() => import("./pages/AttendanceCreate"));
|
|||||||
const LeaveRequests = lazy(() => import("./pages/LeaveRequests"));
|
const LeaveRequests = lazy(() => import("./pages/LeaveRequests"));
|
||||||
const LeaveApproval = lazy(() => import("./pages/LeaveApproval"));
|
const LeaveApproval = lazy(() => import("./pages/LeaveApproval"));
|
||||||
const AttendanceLocation = lazy(() => import("./pages/AttendanceLocation"));
|
const AttendanceLocation = lazy(() => import("./pages/AttendanceLocation"));
|
||||||
|
const PlanWork = lazy(() => import("./pages/PlanWork"));
|
||||||
const Trips = lazy(() => import("./pages/Trips"));
|
const Trips = lazy(() => import("./pages/Trips"));
|
||||||
const TripsHistory = lazy(() => import("./pages/TripsHistory"));
|
const TripsHistory = lazy(() => import("./pages/TripsHistory"));
|
||||||
const TripsAdmin = lazy(() => import("./pages/TripsAdmin"));
|
const TripsAdmin = lazy(() => import("./pages/TripsAdmin"));
|
||||||
@@ -52,68 +56,181 @@ const InvoiceDetail = lazy(() => import("./pages/InvoiceDetail"));
|
|||||||
const Settings = lazy(() => import("./pages/Settings"));
|
const Settings = lazy(() => import("./pages/Settings"));
|
||||||
const AuditLog = lazy(() => import("./pages/AuditLog"));
|
const AuditLog = lazy(() => import("./pages/AuditLog"));
|
||||||
const NotFound = lazy(() => import("./pages/NotFound"));
|
const NotFound = lazy(() => import("./pages/NotFound"));
|
||||||
|
const Warehouse = lazy(() => import("./pages/Warehouse"));
|
||||||
|
const WarehouseItems = lazy(() => import("./pages/WarehouseItems"));
|
||||||
|
const WarehouseItemDetail = lazy(() => import("./pages/WarehouseItemDetail"));
|
||||||
|
const WarehouseReceipts = lazy(() => import("./pages/WarehouseReceipts"));
|
||||||
|
const WarehouseReceiptDetail = lazy(
|
||||||
|
() => import("./pages/WarehouseReceiptDetail"),
|
||||||
|
);
|
||||||
|
const WarehouseReceiptForm = lazy(() => import("./pages/WarehouseReceiptForm"));
|
||||||
|
const WarehouseIssues = lazy(() => import("./pages/WarehouseIssues"));
|
||||||
|
const WarehouseIssueDetail = lazy(() => import("./pages/WarehouseIssueDetail"));
|
||||||
|
const WarehouseIssueForm = lazy(() => import("./pages/WarehouseIssueForm"));
|
||||||
|
const WarehouseReservations = lazy(
|
||||||
|
() => import("./pages/WarehouseReservations"),
|
||||||
|
);
|
||||||
|
const WarehouseInventory = lazy(() => import("./pages/WarehouseInventory"));
|
||||||
|
const WarehouseInventoryDetail = lazy(
|
||||||
|
() => import("./pages/WarehouseInventoryDetail"),
|
||||||
|
);
|
||||||
|
const WarehouseInventoryForm = lazy(
|
||||||
|
() => import("./pages/WarehouseInventoryForm"),
|
||||||
|
);
|
||||||
|
const WarehouseReports = lazy(() => import("./pages/WarehouseReports"));
|
||||||
|
const WarehouseSuppliers = lazy(() => import("./pages/WarehouseSuppliers"));
|
||||||
|
const WarehouseLocations = lazy(() => import("./pages/WarehouseLocations"));
|
||||||
|
const WarehouseCategories = lazy(() => import("./pages/WarehouseCategories"));
|
||||||
|
|
||||||
export default function AdminApp() {
|
export default function AdminApp() {
|
||||||
return (
|
return (
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<AlertProvider>
|
<AlertProvider>
|
||||||
<AlertContainer />
|
<QueryClientProvider client={queryClient}>
|
||||||
<ErrorBoundary>
|
<AlertContainer />
|
||||||
<Suspense
|
<ErrorBoundary>
|
||||||
fallback={
|
<Suspense
|
||||||
<div className="admin-loading">
|
fallback={
|
||||||
<div className="admin-spinner" />
|
<div className="admin-loading">
|
||||||
</div>
|
<div className="admin-spinner" />
|
||||||
}
|
</div>
|
||||||
>
|
}
|
||||||
<Routes>
|
>
|
||||||
<Route path="login" element={<Login />} />
|
<Routes>
|
||||||
<Route element={<AdminLayout />}>
|
<Route path="login" element={<Login />} />
|
||||||
<Route index element={<Dashboard />} />
|
<Route element={<AdminLayout />}>
|
||||||
<Route path="users" element={<Users />} />
|
<Route index element={<Dashboard />} />
|
||||||
<Route path="attendance" element={<Attendance />} />
|
<Route path="users" element={<Users />} />
|
||||||
<Route
|
<Route path="attendance" element={<Attendance />} />
|
||||||
path="attendance/history"
|
<Route
|
||||||
element={<AttendanceHistory />}
|
path="attendance/history"
|
||||||
/>
|
element={<AttendanceHistory />}
|
||||||
<Route path="attendance/admin" element={<AttendanceAdmin />} />
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="attendance/balances"
|
path="attendance/admin"
|
||||||
element={<AttendanceBalances />}
|
element={<AttendanceAdmin />}
|
||||||
/>
|
/>
|
||||||
<Route path="attendance/requests" element={<LeaveRequests />} />
|
<Route
|
||||||
<Route path="attendance/approval" element={<LeaveApproval />} />
|
path="attendance/balances"
|
||||||
<Route
|
element={<AttendanceBalances />}
|
||||||
path="attendance/create"
|
/>
|
||||||
element={<AttendanceCreate />}
|
<Route
|
||||||
/>
|
path="attendance/requests"
|
||||||
<Route
|
element={<LeaveRequests />}
|
||||||
path="attendance/location/:id"
|
/>
|
||||||
element={<AttendanceLocation />}
|
<Route
|
||||||
/>
|
path="attendance/approval"
|
||||||
<Route path="trips" element={<Trips />} />
|
element={<LeaveApproval />}
|
||||||
<Route path="trips/history" element={<TripsHistory />} />
|
/>
|
||||||
<Route path="trips/admin" element={<TripsAdmin />} />
|
<Route
|
||||||
<Route path="vehicles" element={<Vehicles />} />
|
path="attendance/create"
|
||||||
<Route path="offers" element={<Offers />} />
|
element={<AttendanceCreate />}
|
||||||
<Route path="offers/new" element={<OfferDetail />} />
|
/>
|
||||||
<Route path="offers/:id" element={<OfferDetail />} />
|
<Route
|
||||||
<Route path="offers/customers" element={<OffersCustomers />} />
|
path="attendance/location/:id"
|
||||||
<Route path="offers/templates" element={<OffersTemplates />} />
|
element={<AttendanceLocation />}
|
||||||
<Route path="orders" element={<Orders />} />
|
/>
|
||||||
<Route path="orders/:id" element={<OrderDetail />} />
|
<Route path="plan-work" element={<PlanWork />} />
|
||||||
<Route path="projects" element={<Projects />} />
|
<Route path="trips" element={<Trips />} />
|
||||||
<Route path="projects/:id" element={<ProjectDetail />} />
|
<Route path="trips/history" element={<TripsHistory />} />
|
||||||
<Route path="invoices" element={<Invoices />} />
|
<Route path="trips/admin" element={<TripsAdmin />} />
|
||||||
<Route path="invoices/new" element={<InvoiceDetail />} />
|
<Route path="vehicles" element={<Vehicles />} />
|
||||||
<Route path="invoices/:id" element={<InvoiceDetail />} />
|
<Route path="offers" element={<Offers />} />
|
||||||
<Route path="settings" element={<Settings />} />
|
<Route path="offers/new" element={<OfferDetail />} />
|
||||||
<Route path="audit-log" element={<AuditLog />} />
|
<Route path="offers/:id" element={<OfferDetail />} />
|
||||||
</Route>
|
<Route
|
||||||
<Route path="*" element={<NotFound />} />
|
path="offers/customers"
|
||||||
</Routes>
|
element={<OffersCustomers />}
|
||||||
</Suspense>
|
/>
|
||||||
</ErrorBoundary>
|
<Route
|
||||||
|
path="offers/templates"
|
||||||
|
element={<OffersTemplates />}
|
||||||
|
/>
|
||||||
|
<Route path="orders" element={<Orders />} />
|
||||||
|
<Route path="orders/:id" element={<OrderDetail />} />
|
||||||
|
<Route path="projects" element={<Projects />} />
|
||||||
|
<Route path="projects/:id" element={<ProjectDetail />} />
|
||||||
|
<Route path="invoices" element={<Invoices />} />
|
||||||
|
<Route path="invoices/new" element={<InvoiceDetail />} />
|
||||||
|
<Route path="invoices/:id" element={<InvoiceDetail />} />
|
||||||
|
<Route path="settings" element={<Settings />} />
|
||||||
|
<Route path="audit-log" element={<AuditLog />} />
|
||||||
|
<Route path="warehouse" element={<Warehouse />} />
|
||||||
|
<Route path="warehouse/items" element={<WarehouseItems />} />
|
||||||
|
<Route
|
||||||
|
path="warehouse/items/:id"
|
||||||
|
element={<WarehouseItemDetail />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/receipts"
|
||||||
|
element={<WarehouseReceipts />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/receipts/new"
|
||||||
|
element={<WarehouseReceiptForm />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/receipts/:id"
|
||||||
|
element={<WarehouseReceiptDetail />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/receipts/:id/edit"
|
||||||
|
element={<WarehouseReceiptForm />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/issues"
|
||||||
|
element={<WarehouseIssues />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/issues/new"
|
||||||
|
element={<WarehouseIssueForm />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/issues/:id"
|
||||||
|
element={<WarehouseIssueDetail />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/issues/:id/edit"
|
||||||
|
element={<WarehouseIssueForm />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/reservations"
|
||||||
|
element={<WarehouseReservations />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/inventory"
|
||||||
|
element={<WarehouseInventory />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/inventory/new"
|
||||||
|
element={<WarehouseInventoryForm />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/inventory/:id"
|
||||||
|
element={<WarehouseInventoryDetail />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/reports"
|
||||||
|
element={<WarehouseReports />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/suppliers"
|
||||||
|
element={<WarehouseSuppliers />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/locations"
|
||||||
|
element={<WarehouseLocations />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="warehouse/categories"
|
||||||
|
element={<WarehouseCategories />}
|
||||||
|
/>
|
||||||
|
</Route>
|
||||||
|
<Route path="*" element={<NotFound />} />
|
||||||
|
</Routes>
|
||||||
|
</Suspense>
|
||||||
|
</ErrorBoundary>
|
||||||
|
</QueryClientProvider>
|
||||||
</AlertProvider>
|
</AlertProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -318,12 +318,14 @@
|
|||||||
|
|
||||||
/* Leave Type Badges */
|
/* Leave Type Badges */
|
||||||
.attendance-leave-badge {
|
.attendance-leave-badge {
|
||||||
display: inline-block;
|
display: inline-flex;
|
||||||
padding: 0.25rem 0.5rem;
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 0.25rem 0.55rem;
|
||||||
border-radius: var(--border-radius-sm);
|
border-radius: var(--border-radius-sm);
|
||||||
font-size: 0.75rem;
|
font-size: 0.75rem;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
margin-right: 0.25rem;
|
line-height: 1.2;
|
||||||
background: var(--bg-tertiary);
|
background: var(--bg-tertiary);
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -330,15 +330,6 @@ img {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes shimmer {
|
|
||||||
0% {
|
|
||||||
background-position: -200% 0;
|
|
||||||
}
|
|
||||||
100% {
|
|
||||||
background-position: 200% 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── Additional Utilities ─────────────────────────────────────────── */
|
/* ── Additional Utilities ─────────────────────────────────────────── */
|
||||||
|
|
||||||
/* Font sizes */
|
/* Font sizes */
|
||||||
|
|||||||
@@ -8,7 +8,10 @@
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
padding: 8px 14px;
|
padding: 8px 14px;
|
||||||
border: none;
|
/* 1px transparent border on ALL buttons so switching between primary
|
||||||
|
and secondary doesn't cause a 1px layout shift (the border is always
|
||||||
|
1px — only the colour changes). */
|
||||||
|
border: 1px solid transparent;
|
||||||
border-radius: var(--border-radius-sm);
|
border-radius: var(--border-radius-sm);
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 550;
|
font-weight: 550;
|
||||||
@@ -38,11 +41,13 @@
|
|||||||
|
|
||||||
.admin-btn-primary {
|
.admin-btn-primary {
|
||||||
background: var(--accent-color);
|
background: var(--accent-color);
|
||||||
|
border-color: var(--accent-color);
|
||||||
color: #fff;
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-btn-primary:hover:not(:disabled) {
|
.admin-btn-primary:hover:not(:disabled) {
|
||||||
background: var(--accent-hover);
|
background: var(--accent-hover);
|
||||||
|
border-color: var(--accent-hover);
|
||||||
transform: translateY(-1px);
|
transform: translateY(-1px);
|
||||||
box-shadow: 0 4px 12px rgba(214, 48, 49, 0.3);
|
box-shadow: 0 4px 12px rgba(214, 48, 49, 0.3);
|
||||||
}
|
}
|
||||||
@@ -75,6 +80,24 @@
|
|||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.admin-btn-danger {
|
||||||
|
background: var(--danger);
|
||||||
|
border-color: var(--danger);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-btn-danger:hover:not(:disabled) {
|
||||||
|
background: color-mix(in srgb, var(--danger) 88%, #000);
|
||||||
|
border-color: color-mix(in srgb, var(--danger) 88%, #000);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 12px color-mix(in srgb, var(--danger) 30%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-btn-danger .admin-spinner {
|
||||||
|
border-color: rgba(255, 255, 255, 0.3);
|
||||||
|
border-top-color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
.admin-btn-icon {
|
.admin-btn-icon {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -41,6 +41,11 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Danger card — highlighted border for alert/important cards */
|
||||||
|
.admin-card-danger {
|
||||||
|
border: 2px solid var(--danger);
|
||||||
|
}
|
||||||
|
|
||||||
/* ============================================================================
|
/* ============================================================================
|
||||||
Badges
|
Badges
|
||||||
============================================================================ */
|
============================================================================ */
|
||||||
@@ -123,6 +128,16 @@
|
|||||||
color: var(--danger);
|
color: var(--danger);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.admin-badge-incoming {
|
||||||
|
background: var(--success-soft);
|
||||||
|
color: var(--success);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-badge-outgoing {
|
||||||
|
background: var(--info-soft);
|
||||||
|
color: var(--info);
|
||||||
|
}
|
||||||
|
|
||||||
/* Status Badges - Leave Requests */
|
/* Status Badges - Leave Requests */
|
||||||
.badge-pending {
|
.badge-pending {
|
||||||
background: color-mix(in srgb, var(--warning) 15%, transparent);
|
background: color-mix(in srgb, var(--warning) 15%, transparent);
|
||||||
@@ -716,6 +731,7 @@
|
|||||||
.admin-kpi-grid {
|
.admin-kpi-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 0.875rem;
|
gap: 0.875rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-kpi-4 {
|
.admin-kpi-4 {
|
||||||
@@ -923,3 +939,163 @@
|
|||||||
max-height: 80px;
|
max-height: 80px;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============================================================================
|
||||||
|
Search Bar & Filters
|
||||||
|
============================================================================ */
|
||||||
|
|
||||||
|
.admin-search-bar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-bar .admin-form-input,
|
||||||
|
.admin-search-bar .admin-form-select {
|
||||||
|
flex: 1 1 140px;
|
||||||
|
min-width: 140px;
|
||||||
|
max-width: 280px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-bar .react-datepicker-wrapper {
|
||||||
|
flex: 1 1 140px;
|
||||||
|
min-width: 140px;
|
||||||
|
max-width: 280px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-bar .admin-btn {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search {
|
||||||
|
position: relative;
|
||||||
|
flex: 1 1 200px;
|
||||||
|
min-width: 180px;
|
||||||
|
max-width: 320px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search svg {
|
||||||
|
position: absolute;
|
||||||
|
left: 10px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search .admin-form-input {
|
||||||
|
padding-left: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.admin-search-bar {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-bar .admin-form-input,
|
||||||
|
.admin-search-bar .admin-form-select {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-bar .react-datepicker-wrapper {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search {
|
||||||
|
max-width: 100%;
|
||||||
|
flex: 1 1 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.admin-search-bar .admin-form-input,
|
||||||
|
.admin-search-bar .admin-form-select {
|
||||||
|
min-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-search-bar .react-datepicker-wrapper {
|
||||||
|
min-width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================================
|
||||||
|
Item Picker (Warehouse)
|
||||||
|
============================================================================ */
|
||||||
|
|
||||||
|
.admin-item-picker-list {
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
z-index: 100;
|
||||||
|
max-height: 240px;
|
||||||
|
overflow-y: auto;
|
||||||
|
overscroll-behavior: contain;
|
||||||
|
background: var(--bg-primary);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-top: none;
|
||||||
|
border-radius: 0 0 var(--border-radius-sm) var(--border-radius-sm);
|
||||||
|
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||||
|
padding: 4px 0;
|
||||||
|
margin: 0;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-list::-webkit-scrollbar {
|
||||||
|
width: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-list::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-list::-webkit-scrollbar-thumb {
|
||||||
|
background: var(--border-color);
|
||||||
|
border-radius: 99px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-list::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 8px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background var(--transition);
|
||||||
|
border-radius: 4px;
|
||||||
|
margin: 0 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-item:hover,
|
||||||
|
.admin-item-picker-item.active {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-name {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-number {
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--text-tertiary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-item-picker-qty {
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { forwardRef, useMemo } from "react";
|
import { forwardRef } from "react";
|
||||||
import DatePicker, { registerLocale } from "react-datepicker";
|
import DatePicker, { registerLocale } from "react-datepicker";
|
||||||
import { cs } from "date-fns/locale";
|
import { cs } from "date-fns/locale";
|
||||||
import { parse, format } from "date-fns";
|
import { parse, format } from "date-fns";
|
||||||
@@ -124,7 +124,7 @@ export default function AdminDatePicker({
|
|||||||
disabled,
|
disabled,
|
||||||
placeholder,
|
placeholder,
|
||||||
}: AdminDatePickerProps) {
|
}: AdminDatePickerProps) {
|
||||||
const useNative = useMemo(() => isTouchDevice(), []);
|
const useNative = isTouchDevice();
|
||||||
|
|
||||||
if (useNative) {
|
if (useNative) {
|
||||||
return (
|
return (
|
||||||
@@ -178,15 +178,12 @@ export default function AdminDatePicker({
|
|||||||
return undefined;
|
return undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
const customInput = useMemo(
|
const customInput = (
|
||||||
() => (
|
<CustomInput
|
||||||
<CustomInput
|
required={required}
|
||||||
required={required}
|
placeholder={placeholder}
|
||||||
placeholder={placeholder}
|
disabled={disabled}
|
||||||
disabled={disabled}
|
/>
|
||||||
/>
|
|
||||||
),
|
|
||||||
[required, placeholder, disabled],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const commonProps = {
|
const commonProps = {
|
||||||
@@ -194,6 +191,7 @@ export default function AdminDatePicker({
|
|||||||
onChange: handleChange,
|
onChange: handleChange,
|
||||||
locale: "cs",
|
locale: "cs",
|
||||||
customInput,
|
customInput,
|
||||||
|
placeholderText: placeholder,
|
||||||
minDate: parseMinMax(minDate),
|
minDate: parseMinMax(minDate),
|
||||||
maxDate: parseMinMax(maxDate),
|
maxDate: parseMinMax(maxDate),
|
||||||
popperPlacement: "bottom-start" as const,
|
popperPlacement: "bottom-start" as const,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
formatDate,
|
formatDate,
|
||||||
formatDatetime,
|
formatDatetime,
|
||||||
@@ -8,34 +8,13 @@ import {
|
|||||||
getLeaveTypeName,
|
getLeaveTypeName,
|
||||||
getLeaveTypeBadgeClass,
|
getLeaveTypeBadgeClass,
|
||||||
} from "../utils/attendanceHelpers";
|
} from "../utils/attendanceHelpers";
|
||||||
|
import type { AttendanceRecord as HookAttendanceRecord } from "../hooks/useAttendanceAdmin";
|
||||||
|
|
||||||
interface ProjectLog {
|
interface AttendanceRecord extends HookAttendanceRecord {
|
||||||
id?: number;
|
|
||||||
project_id?: number;
|
|
||||||
project_name?: string;
|
|
||||||
started_at?: string;
|
|
||||||
ended_at?: string | null;
|
|
||||||
hours?: string | number | null;
|
|
||||||
minutes?: string | number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AttendanceRecord {
|
|
||||||
id: number;
|
|
||||||
shift_date: string;
|
|
||||||
user_name: string;
|
|
||||||
leave_type?: string;
|
|
||||||
leave_hours?: number;
|
|
||||||
arrival_time?: string | null;
|
|
||||||
departure_time?: string | null;
|
|
||||||
break_start?: string | null;
|
|
||||||
break_end?: string | null;
|
|
||||||
arrival_lat?: number | string | null;
|
arrival_lat?: number | string | null;
|
||||||
arrival_lng?: number | string | null;
|
arrival_lng?: number | string | null;
|
||||||
departure_lat?: number | string | null;
|
departure_lat?: number | string | null;
|
||||||
departure_lng?: number | string | null;
|
departure_lng?: number | string | null;
|
||||||
project_name?: string;
|
|
||||||
project_logs?: ProjectLog[];
|
|
||||||
notes?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AttendanceShiftTableProps {
|
interface AttendanceShiftTableProps {
|
||||||
@@ -51,7 +30,7 @@ function formatBreak(record: AttendanceRecord): string {
|
|||||||
if (record.break_start) {
|
if (record.break_start) {
|
||||||
return `${formatTime(record.break_start)} - ?`;
|
return `${formatTime(record.break_start)} - ?`;
|
||||||
}
|
}
|
||||||
return "\u2014";
|
return "—";
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderProjectCell(record: AttendanceRecord): React.ReactNode {
|
function renderProjectCell(record: AttendanceRecord): React.ReactNode {
|
||||||
@@ -97,7 +76,7 @@ function renderProjectCell(record: AttendanceRecord): React.ReactNode {
|
|||||||
>
|
>
|
||||||
{log.project_name || `#${log.project_id}`}{" "}
|
{log.project_name || `#${log.project_id}`}{" "}
|
||||||
{durationValid
|
{durationValid
|
||||||
? `(${h}:${String(m).padStart(2, "0")}h${isActive ? " \u25B8" : ""})`
|
? `(${h}:${String(m).padStart(2, "0")}h${isActive ? " ▸" : ""})`
|
||||||
: "—"}
|
: "—"}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
@@ -115,7 +94,7 @@ function renderProjectCell(record: AttendanceRecord): React.ReactNode {
|
|||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return "\u2014";
|
return "—";
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function AttendanceShiftTable({
|
export default function AttendanceShiftTable({
|
||||||
@@ -156,7 +135,10 @@ export default function AttendanceShiftTable({
|
|||||||
const workMinutes = isLeave
|
const workMinutes = isLeave
|
||||||
? (record.leave_hours != null ? Number(record.leave_hours) : 8) *
|
? (record.leave_hours != null ? Number(record.leave_hours) : 8) *
|
||||||
60
|
60
|
||||||
: calculateWorkMinutes(record);
|
: calculateWorkMinutes({
|
||||||
|
...record,
|
||||||
|
notes: record.notes ?? undefined,
|
||||||
|
});
|
||||||
const hasLocation =
|
const hasLocation =
|
||||||
(record.arrival_lat && record.arrival_lng) ||
|
(record.arrival_lat && record.arrival_lng) ||
|
||||||
(record.departure_lat && record.departure_lng);
|
(record.departure_lat && record.departure_lng);
|
||||||
@@ -173,18 +155,16 @@ export default function AttendanceShiftTable({
|
|||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="admin-mono">
|
<td className="admin-mono">
|
||||||
{isLeave ? "\u2014" : formatDatetime(record.arrival_time)}
|
{isLeave ? "—" : formatDatetime(record.arrival_time)}
|
||||||
</td>
|
</td>
|
||||||
<td className="admin-mono">
|
<td className="admin-mono">
|
||||||
{isLeave ? "\u2014" : formatBreak(record)}
|
{isLeave ? "—" : formatBreak(record)}
|
||||||
</td>
|
</td>
|
||||||
<td className="admin-mono">
|
<td className="admin-mono">
|
||||||
{isLeave ? "\u2014" : formatDatetime(record.departure_time)}
|
{isLeave ? "—" : formatDatetime(record.departure_time)}
|
||||||
</td>
|
</td>
|
||||||
<td className="admin-mono">
|
<td className="admin-mono">
|
||||||
{workMinutes > 0
|
{workMinutes > 0 ? `${formatMinutes(workMinutes)} h` : "—"}
|
||||||
? `${formatMinutes(workMinutes)} h`
|
|
||||||
: "\u2014"}
|
|
||||||
</td>
|
</td>
|
||||||
<td>{renderProjectCell(record)}</td>
|
<td>{renderProjectCell(record)}</td>
|
||||||
<td>
|
<td>
|
||||||
@@ -195,10 +175,10 @@ export default function AttendanceShiftTable({
|
|||||||
title="Zobrazit polohu"
|
title="Zobrazit polohu"
|
||||||
aria-label="Zobrazit polohu"
|
aria-label="Zobrazit polohu"
|
||||||
>
|
>
|
||||||
<span aria-hidden="true">{"\uD83D\uDCCD"}</span>
|
<span aria-hidden="true">{"📍"}</span>
|
||||||
</Link>
|
</Link>
|
||||||
) : (
|
) : (
|
||||||
"\u2014"
|
"—"
|
||||||
)}
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td
|
<td
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ReactNode } from "react";
|
import { useEffect, type ReactNode } from "react";
|
||||||
import { motion, AnimatePresence } from "framer-motion";
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
|
||||||
interface ConfirmModalProps {
|
interface ConfirmModalProps {
|
||||||
@@ -91,6 +91,19 @@ export default function ConfirmModal({
|
|||||||
confirmVariant,
|
confirmVariant,
|
||||||
loading,
|
loading,
|
||||||
}: ConfirmModalProps) {
|
}: ConfirmModalProps) {
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen) return;
|
||||||
|
|
||||||
|
function handleKeyDown(e: KeyboardEvent) {
|
||||||
|
if (e.key === "Escape" && !loading) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||||
|
}, [isOpen, loading, onClose]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AnimatePresence>
|
<AnimatePresence>
|
||||||
{isOpen && (
|
{isOpen && (
|
||||||
|
|||||||
118
src/admin/components/FormModal.tsx
Normal file
118
src/admin/components/FormModal.tsx
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
import { useEffect, type ReactNode, type FormEvent } from "react";
|
||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
import useModalLock from "../hooks/useModalLock";
|
||||||
|
|
||||||
|
export interface FormModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onSubmit?: () => void; // called when user clicks primary button (only if provided)
|
||||||
|
title: string;
|
||||||
|
children: ReactNode; // modal body (form fields)
|
||||||
|
submitLabel?: string; // primary button text
|
||||||
|
cancelLabel?: string; // cancel button text
|
||||||
|
loading?: boolean;
|
||||||
|
hideFooter?: boolean; // for "view-only" modals
|
||||||
|
size?: "sm" | "md" | "lg"; // optional
|
||||||
|
closeOnBackdrop?: boolean; // default true
|
||||||
|
closeOnEsc?: boolean; // default true
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function FormModal({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
onSubmit,
|
||||||
|
title,
|
||||||
|
children,
|
||||||
|
submitLabel = "Uložit",
|
||||||
|
cancelLabel = "Zrušit",
|
||||||
|
loading = false,
|
||||||
|
hideFooter = false,
|
||||||
|
size = "md",
|
||||||
|
closeOnBackdrop = true,
|
||||||
|
closeOnEsc = true,
|
||||||
|
}: FormModalProps) {
|
||||||
|
useModalLock(isOpen);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen || !closeOnEsc) return;
|
||||||
|
|
||||||
|
function handleKeyDown(e: KeyboardEvent) {
|
||||||
|
if (e.key === "Escape" && !loading) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||||
|
}, [isOpen, closeOnEsc, loading, onClose]);
|
||||||
|
|
||||||
|
const handleBackdropClick = () => {
|
||||||
|
if (closeOnBackdrop && !loading) onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePrimaryClick = (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (onSubmit) onSubmit();
|
||||||
|
};
|
||||||
|
|
||||||
|
const titleId = "form-modal-title";
|
||||||
|
const modalClassName =
|
||||||
|
size === "lg" ? "admin-modal admin-modal-lg" : "admin-modal";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnimatePresence>
|
||||||
|
{isOpen && (
|
||||||
|
<motion.div
|
||||||
|
className="admin-modal-overlay"
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
>
|
||||||
|
<div className="admin-modal-backdrop" onClick={handleBackdropClick} />
|
||||||
|
<motion.div
|
||||||
|
className={modalClassName}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||||
|
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
>
|
||||||
|
<div className="admin-modal-header">
|
||||||
|
<h2 id={titleId} className="admin-modal-title">
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="admin-modal-body">{children}</div>
|
||||||
|
|
||||||
|
{!hideFooter && (
|
||||||
|
<div className="admin-modal-footer">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => !loading && onClose()}
|
||||||
|
className="admin-btn admin-btn-secondary"
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
{cancelLabel}
|
||||||
|
</button>
|
||||||
|
{onSubmit && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handlePrimaryClick}
|
||||||
|
className="admin-btn admin-btn-primary"
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
{loading ? "Zpracování..." : submitLabel}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</motion.div>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
);
|
||||||
|
}
|
||||||
210
src/admin/components/PlanCategoriesModal.tsx
Normal file
210
src/admin/components/PlanCategoriesModal.tsx
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import FormModal from "./FormModal";
|
||||||
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
|
import { useAlert } from "../context/AlertContext";
|
||||||
|
import { PlanCategory } from "../lib/queries/plan";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
categories: PlanCategory[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_NEW_COLOR = "#2563eb";
|
||||||
|
|
||||||
|
export default function PlanCategoriesModal({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
categories,
|
||||||
|
}: Props) {
|
||||||
|
const alert = useAlert();
|
||||||
|
const [newLabel, setNewLabel] = useState("");
|
||||||
|
const [newColor, setNewColor] = useState(DEFAULT_NEW_COLOR);
|
||||||
|
// Id of the row showing the inline "really delete?" confirm, or null.
|
||||||
|
const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
const createCat = useApiMutation<
|
||||||
|
{ label: string; color: string },
|
||||||
|
PlanCategory
|
||||||
|
>({
|
||||||
|
url: "/api/admin/plan/categories",
|
||||||
|
method: "POST",
|
||||||
|
invalidate: ["plan", "dashboard", "audit-log"],
|
||||||
|
});
|
||||||
|
const updateCat = useApiMutation<
|
||||||
|
{ id: number; label?: string; color?: string; is_active?: boolean },
|
||||||
|
PlanCategory
|
||||||
|
>({
|
||||||
|
url: (v) => `/api/admin/plan/categories/${v.id}`,
|
||||||
|
method: "PATCH",
|
||||||
|
invalidate: ["plan", "dashboard", "audit-log"],
|
||||||
|
});
|
||||||
|
const deleteCat = useApiMutation<{ id: number }, { ok: true }>({
|
||||||
|
url: (v) => `/api/admin/plan/categories/${v.id}`,
|
||||||
|
method: "DELETE",
|
||||||
|
invalidate: ["plan", "dashboard", "audit-log"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleAdd = () => {
|
||||||
|
const label = newLabel.trim();
|
||||||
|
if (!label) {
|
||||||
|
alert.error("Zadejte název kategorie");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
createCat.mutate(
|
||||||
|
{ label, color: newColor },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
setNewLabel("");
|
||||||
|
setNewColor(DEFAULT_NEW_COLOR);
|
||||||
|
},
|
||||||
|
onError: (e) => alert.error(e.message),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const patch = (
|
||||||
|
id: number,
|
||||||
|
body: { label?: string; color?: string; is_active?: boolean },
|
||||||
|
) => {
|
||||||
|
updateCat.mutate(
|
||||||
|
{ id, ...body },
|
||||||
|
{ onError: (e) => alert.error(e.message) },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = (id: number) => {
|
||||||
|
deleteCat.mutate(
|
||||||
|
{ id },
|
||||||
|
{
|
||||||
|
onSuccess: () => setConfirmDeleteId(null),
|
||||||
|
// Server blocks deleting a category that is still in use (409) — show
|
||||||
|
// the Czech message ("…můžete ji skrýt") and keep the row.
|
||||||
|
onError: (e) => {
|
||||||
|
alert.error(e.message);
|
||||||
|
setConfirmDeleteId(null);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const busy =
|
||||||
|
createCat.isPending || updateCat.isPending || deleteCat.isPending;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormModal
|
||||||
|
isOpen={isOpen}
|
||||||
|
onClose={onClose}
|
||||||
|
title="Správa kategorií"
|
||||||
|
hideFooter
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
<div className="plan-cat-manager">
|
||||||
|
{categories.map((c) => (
|
||||||
|
<div
|
||||||
|
key={c.id}
|
||||||
|
className={`plan-cat-row${c.is_active ? "" : " plan-cat-row--inactive"}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
className="plan-cat-color"
|
||||||
|
// Uncontrolled + patch on blur (like the rename input): the
|
||||||
|
// native color picker fires onChange on every drag tick, which
|
||||||
|
// would spam PATCH requests and the audit log. onBlur commits
|
||||||
|
// once when the picker closes.
|
||||||
|
defaultValue={c.color}
|
||||||
|
key={c.color}
|
||||||
|
disabled={busy}
|
||||||
|
onBlur={(e) => {
|
||||||
|
if (e.target.value !== c.color) {
|
||||||
|
patch(c.id, { color: e.target.value });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
aria-label={`Barva – ${c.label}`}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="admin-form-input"
|
||||||
|
defaultValue={c.label}
|
||||||
|
disabled={busy}
|
||||||
|
onBlur={(e) => {
|
||||||
|
const v = e.target.value.trim();
|
||||||
|
if (v && v !== c.label) patch(c.id, { label: v });
|
||||||
|
}}
|
||||||
|
aria-label={`Název – ${c.label}`}
|
||||||
|
/>
|
||||||
|
{confirmDeleteId === c.id ? (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-danger admin-btn-sm"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => handleDelete(c.id)}
|
||||||
|
>
|
||||||
|
Opravdu smazat
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => setConfirmDeleteId(null)}
|
||||||
|
>
|
||||||
|
Zrušit
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-secondary admin-btn-sm"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => patch(c.id, { is_active: !c.is_active })}
|
||||||
|
>
|
||||||
|
{c.is_active ? "Skrýt" : "Obnovit"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-danger admin-btn-sm plan-cat-delete"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => setConfirmDeleteId(c.id)}
|
||||||
|
aria-label={`Smazat – ${c.label}`}
|
||||||
|
title="Smazat kategorii"
|
||||||
|
>
|
||||||
|
Smazat
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<div className="plan-cat-row plan-cat-row--new">
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
className="plan-cat-color"
|
||||||
|
value={newColor}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) => setNewColor(e.target.value)}
|
||||||
|
aria-label="Barva nové kategorie"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="admin-form-input"
|
||||||
|
placeholder="Nová kategorie…"
|
||||||
|
value={newLabel}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) => setNewLabel(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && handleAdd()}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-primary admin-btn-sm"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={handleAdd}
|
||||||
|
>
|
||||||
|
Přidat
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</FormModal>
|
||||||
|
);
|
||||||
|
}
|
||||||
482
src/admin/components/PlanCellModal.tsx
Normal file
482
src/admin/components/PlanCellModal.tsx
Normal file
@@ -0,0 +1,482 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
import FormModal from "./FormModal";
|
||||||
|
import FormField from "./FormField";
|
||||||
|
import AdminDatePicker from "./AdminDatePicker";
|
||||||
|
import ConfirmModal from "./ConfirmModal";
|
||||||
|
import useReducedMotion from "../hooks/useReducedMotion";
|
||||||
|
import {
|
||||||
|
ResolvedCell,
|
||||||
|
PlanCategory,
|
||||||
|
planCategoryLabel,
|
||||||
|
cellProjectLabel,
|
||||||
|
} from "../lib/queries/plan";
|
||||||
|
import { formatDate } from "../utils/formatters";
|
||||||
|
|
||||||
|
interface Project {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
project_number?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PlanCellModalMode =
|
||||||
|
| { kind: "closed" }
|
||||||
|
| { kind: "create"; userId: number; date: string }
|
||||||
|
| {
|
||||||
|
kind: "edit-range";
|
||||||
|
entryId: number;
|
||||||
|
userId: number;
|
||||||
|
date: string;
|
||||||
|
range: {
|
||||||
|
date_from: string;
|
||||||
|
date_to: string;
|
||||||
|
project_id: number | null;
|
||||||
|
category: string;
|
||||||
|
note: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
kind: "edit-override";
|
||||||
|
overrideId: number;
|
||||||
|
userId: number;
|
||||||
|
date: string;
|
||||||
|
cell: ResolvedCell;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
kind: "day-in-range";
|
||||||
|
entryId: number;
|
||||||
|
userId: number;
|
||||||
|
date: string;
|
||||||
|
range: {
|
||||||
|
date_from: string;
|
||||||
|
date_to: string;
|
||||||
|
project_id: number | null;
|
||||||
|
category: string;
|
||||||
|
note: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
| { kind: "view"; userId: number; date: string; cell: ResolvedCell };
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
mode: PlanCellModalMode;
|
||||||
|
projects: Project[];
|
||||||
|
categories: PlanCategory[];
|
||||||
|
onClose: () => void;
|
||||||
|
onSaveEntry: (body: any) => Promise<void>;
|
||||||
|
onUpdateEntry: (id: number, body: any) => Promise<void>;
|
||||||
|
onDeleteEntry: (id: number) => Promise<void>;
|
||||||
|
onSaveOverride: (body: any) => Promise<void>;
|
||||||
|
onUpdateOverride: (id: number, body: any) => Promise<void>;
|
||||||
|
onDeleteOverride: (id: number) => Promise<void>;
|
||||||
|
onCreateOverrideFromRange: (
|
||||||
|
entryId: number,
|
||||||
|
userId: number,
|
||||||
|
date: string,
|
||||||
|
) => Promise<void>;
|
||||||
|
onSwitchToEditRange: (entryId: number, userId: number, date: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PlanCellModal(props: Props) {
|
||||||
|
const { open, mode, onClose } = props;
|
||||||
|
if (!open || mode.kind === "closed") return null;
|
||||||
|
if (mode.kind === "view") return <ViewModal {...props} />;
|
||||||
|
if (mode.kind === "day-in-range")
|
||||||
|
return <DayInRangeModal {...props} mode={mode} />;
|
||||||
|
return <EditForm {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function EditForm(props: Props) {
|
||||||
|
const {
|
||||||
|
mode,
|
||||||
|
onClose,
|
||||||
|
onSaveEntry,
|
||||||
|
onUpdateEntry,
|
||||||
|
onDeleteEntry,
|
||||||
|
onSaveOverride,
|
||||||
|
onUpdateOverride,
|
||||||
|
onDeleteOverride,
|
||||||
|
projects,
|
||||||
|
} = props;
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||||
|
|
||||||
|
// Narrow mode to the kinds EditForm actually handles. The call site in
|
||||||
|
// PlanCellModal only passes "create" | "edit-range" | "edit-override" but
|
||||||
|
// the parameter type is the full union, so we narrow explicitly here.
|
||||||
|
if (
|
||||||
|
mode.kind !== "create" &&
|
||||||
|
mode.kind !== "edit-range" &&
|
||||||
|
mode.kind !== "edit-override"
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isOverride = mode.kind === "edit-override";
|
||||||
|
const activeCategories = props.categories.filter((c) => c.is_active);
|
||||||
|
|
||||||
|
const initial = (() => {
|
||||||
|
if (mode.kind === "create") {
|
||||||
|
return {
|
||||||
|
date_from: mode.date,
|
||||||
|
date_to: mode.date,
|
||||||
|
is_range: false,
|
||||||
|
project_id: null as number | null,
|
||||||
|
// Default to "work" when it's active, otherwise the first active
|
||||||
|
// category, so a new entry never starts on a retired key.
|
||||||
|
category: activeCategories.some((c) => c.key === "work")
|
||||||
|
? "work"
|
||||||
|
: (activeCategories[0]?.key ?? "work"),
|
||||||
|
note: "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (mode.kind === "edit-range") {
|
||||||
|
return {
|
||||||
|
date_from: mode.range.date_from,
|
||||||
|
date_to: mode.range.date_to,
|
||||||
|
is_range: mode.range.date_from !== mode.range.date_to,
|
||||||
|
project_id: mode.range.project_id,
|
||||||
|
category: mode.range.category,
|
||||||
|
note: mode.range.note,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// mode.kind === "edit-override" (narrowed above)
|
||||||
|
return {
|
||||||
|
date_from: mode.date,
|
||||||
|
date_to: mode.date,
|
||||||
|
is_range: false,
|
||||||
|
project_id: mode.cell.project_id,
|
||||||
|
category: mode.cell.category,
|
||||||
|
note: mode.cell.note,
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
|
const [dateFrom, setDateFrom] = useState(initial.date_from);
|
||||||
|
const [dateTo, setDateTo] = useState(initial.date_to);
|
||||||
|
const [isRange, setIsRange] = useState(initial.is_range);
|
||||||
|
const [projectId, setProjectId] = useState<number | null>(initial.project_id);
|
||||||
|
const [category, setCategory] = useState(initial.category);
|
||||||
|
const [note, setNote] = useState(initial.note);
|
||||||
|
|
||||||
|
const title =
|
||||||
|
mode.kind === "create"
|
||||||
|
? "Nový záznam plánu"
|
||||||
|
: mode.kind === "edit-range"
|
||||||
|
? "Upravit rozsah"
|
||||||
|
: "Upravit přepsání dne";
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
if (mode.kind === "create") {
|
||||||
|
const userId = mode.userId;
|
||||||
|
await onSaveEntry({
|
||||||
|
user_id: userId,
|
||||||
|
date_from: dateFrom,
|
||||||
|
date_to: isRange ? dateTo : dateFrom,
|
||||||
|
project_id: projectId,
|
||||||
|
category,
|
||||||
|
note,
|
||||||
|
});
|
||||||
|
} else if (mode.kind === "edit-range") {
|
||||||
|
await onUpdateEntry(mode.entryId, {
|
||||||
|
date_from: dateFrom,
|
||||||
|
date_to: isRange ? dateTo : dateFrom,
|
||||||
|
project_id: projectId,
|
||||||
|
category,
|
||||||
|
note,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await onUpdateOverride(mode.overrideId, {
|
||||||
|
project_id: projectId,
|
||||||
|
category,
|
||||||
|
note,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
onClose();
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
if (mode.kind === "edit-range") {
|
||||||
|
await onDeleteEntry(mode.entryId);
|
||||||
|
} else if (mode.kind === "edit-override") {
|
||||||
|
await onDeleteOverride(mode.overrideId);
|
||||||
|
}
|
||||||
|
onClose();
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<FormModal
|
||||||
|
isOpen
|
||||||
|
title={title}
|
||||||
|
onClose={onClose}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
submitLabel={mode.kind === "create" ? "Vytvořit" : "Uložit"}
|
||||||
|
loading={submitting}
|
||||||
|
footerLeft={
|
||||||
|
mode.kind !== "create" ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-secondary"
|
||||||
|
onClick={() => setConfirmDelete(true)}
|
||||||
|
disabled={submitting}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="14"
|
||||||
|
height="14"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden
|
||||||
|
>
|
||||||
|
<polyline points="3 6 5 6 21 6" />
|
||||||
|
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
|
||||||
|
<path d="M10 11v6" />
|
||||||
|
<path d="M14 11v6" />
|
||||||
|
<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
|
||||||
|
</svg>
|
||||||
|
Smazat
|
||||||
|
</button>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<FormField label="Datum od">
|
||||||
|
<AdminDatePicker
|
||||||
|
value={dateFrom}
|
||||||
|
onChange={setDateFrom}
|
||||||
|
disabled={isOverride}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
{!isOverride && (
|
||||||
|
<FormField label="Rozsah dnů">
|
||||||
|
<label className="admin-form-checkbox">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={isRange}
|
||||||
|
onChange={(e) => setIsRange(e.target.checked)}
|
||||||
|
/>
|
||||||
|
<span>Více dní</span>
|
||||||
|
</label>
|
||||||
|
</FormField>
|
||||||
|
)}
|
||||||
|
{!isOverride && isRange && (
|
||||||
|
<FormField label="Datum do">
|
||||||
|
<AdminDatePicker value={dateTo} onChange={setDateTo} />
|
||||||
|
</FormField>
|
||||||
|
)}
|
||||||
|
<FormField label="Projekt">
|
||||||
|
<select
|
||||||
|
className="admin-form-select"
|
||||||
|
value={projectId ?? ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setProjectId(e.target.value ? Number(e.target.value) : null)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">— bez projektu —</option>
|
||||||
|
{projects.map((p) => (
|
||||||
|
<option key={p.id} value={p.id}>
|
||||||
|
{p.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</FormField>
|
||||||
|
<FormField label="Kategorie">
|
||||||
|
<select
|
||||||
|
className="admin-form-select"
|
||||||
|
value={category}
|
||||||
|
onChange={(e) => setCategory(e.target.value)}
|
||||||
|
>
|
||||||
|
{/* If the row's current category was retired/hidden, still show it
|
||||||
|
(marked) so the select reflects reality instead of silently
|
||||||
|
snapping to the first active option. The server only re-checks
|
||||||
|
the category if it changes, so keeping it saves fine. */}
|
||||||
|
{category && !activeCategories.some((c) => c.key === category) && (
|
||||||
|
<option value={category}>
|
||||||
|
{planCategoryLabel(
|
||||||
|
category,
|
||||||
|
Object.fromEntries(props.categories.map((x) => [x.key, x])),
|
||||||
|
)}{" "}
|
||||||
|
(skrytá)
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{activeCategories.map((c) => (
|
||||||
|
<option key={c.key} value={c.key}>
|
||||||
|
{c.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</FormField>
|
||||||
|
<FormField label="Text poznámky (volitelný)">
|
||||||
|
<textarea
|
||||||
|
className="admin-form-textarea"
|
||||||
|
value={note}
|
||||||
|
onChange={(e) => setNote(e.target.value)}
|
||||||
|
maxLength={500}
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
</FormModal>
|
||||||
|
|
||||||
|
<ConfirmModal
|
||||||
|
isOpen={confirmDelete}
|
||||||
|
title="Smazat záznam plánu?"
|
||||||
|
message="Tato akce je nevratná (záznam bude soft-delete)."
|
||||||
|
confirmText="Smazat"
|
||||||
|
type="danger"
|
||||||
|
confirmVariant="danger"
|
||||||
|
loading={submitting}
|
||||||
|
onClose={() => setConfirmDelete(false)}
|
||||||
|
onConfirm={handleDelete}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DayInRangeModal(
|
||||||
|
props: Props & { mode: Extract<PlanCellModalMode, { kind: "day-in-range" }> },
|
||||||
|
) {
|
||||||
|
const { mode, onClose, onCreateOverrideFromRange, onSwitchToEditRange } =
|
||||||
|
props;
|
||||||
|
const reducedMotion = useReducedMotion();
|
||||||
|
|
||||||
|
// Two clear paths: edit the whole range (default, safe) or carve out
|
||||||
|
// a one-day override (deviates from the plan). Close = no action.
|
||||||
|
const choices = [
|
||||||
|
{
|
||||||
|
key: "edit-range",
|
||||||
|
title: "Upravit celý rozsah",
|
||||||
|
desc: `Změní projekt, kategorii nebo poznámku pro všechny dny v rozsahu ${mode.range.date_from} – ${mode.range.date_to}.`,
|
||||||
|
tone: "primary" as const,
|
||||||
|
onClick: () => onSwitchToEditRange(mode.entryId, mode.userId, mode.date),
|
||||||
|
cta: "Upravit rozsah",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "override-day",
|
||||||
|
title: "Upravit pouze tento den",
|
||||||
|
desc: `Vytvoří přepsání pro ${mode.range.date_from === mode.date ? "tento" : mode.date}; zbytek rozsahu zůstane beze změny.`,
|
||||||
|
tone: "secondary" as const,
|
||||||
|
onClick: async () => {
|
||||||
|
await onCreateOverrideFromRange(mode.entryId, mode.userId, mode.date);
|
||||||
|
onClose();
|
||||||
|
},
|
||||||
|
cta: "Vytvořit přepsání",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormModal
|
||||||
|
isOpen
|
||||||
|
title="Den je součástí rozsahu"
|
||||||
|
onClose={onClose}
|
||||||
|
hideFooter
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
<p className="plan-modal-intro">
|
||||||
|
Den <strong>{mode.date}</strong> je součástí rozsahu{" "}
|
||||||
|
<strong>
|
||||||
|
{mode.range.date_from} – {mode.range.date_to}
|
||||||
|
</strong>
|
||||||
|
. Vyberte, co chcete udělat:
|
||||||
|
</p>
|
||||||
|
<ul className="plan-choices">
|
||||||
|
<AnimatePresence>
|
||||||
|
{choices.map((c, i) => (
|
||||||
|
<motion.li
|
||||||
|
key={c.key}
|
||||||
|
className={`plan-choice plan-choice-${c.tone}`}
|
||||||
|
initial={reducedMotion ? false : { opacity: 0, y: 8 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={reducedMotion ? undefined : { opacity: 0, y: -4 }}
|
||||||
|
transition={{
|
||||||
|
duration: reducedMotion ? 0 : 0.22,
|
||||||
|
delay: reducedMotion ? 0 : 0.04 + i * 0.05,
|
||||||
|
ease: [0.16, 1, 0.3, 1],
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="plan-choice-body">
|
||||||
|
<div className="plan-choice-title">{c.title}</div>
|
||||||
|
<div className="plan-choice-desc">{c.desc}</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={
|
||||||
|
c.tone === "primary"
|
||||||
|
? "admin-btn admin-btn-primary"
|
||||||
|
: "admin-btn admin-btn-secondary"
|
||||||
|
}
|
||||||
|
onClick={c.onClick}
|
||||||
|
>
|
||||||
|
{c.cta}
|
||||||
|
</button>
|
||||||
|
</motion.li>
|
||||||
|
))}
|
||||||
|
</AnimatePresence>
|
||||||
|
</ul>
|
||||||
|
<div className="plan-modal-actions plan-modal-actions--solo">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-secondary"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
Zavřít — ponechat rozsah beze změny
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</FormModal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ViewModal(props: Props) {
|
||||||
|
const { mode, onClose, projects, categories } = props;
|
||||||
|
if (mode.kind !== "view") return null;
|
||||||
|
const c = mode.cell;
|
||||||
|
// Prefer the server-embedded project label; fall back to the projects-list
|
||||||
|
// lookup only for cells that predate the embed (stale cache).
|
||||||
|
const fallback = c.project_id
|
||||||
|
? (projects.find((p) => p.id === c.project_id) ?? null)
|
||||||
|
: null;
|
||||||
|
const projectLabel =
|
||||||
|
cellProjectLabel(c) ??
|
||||||
|
(fallback
|
||||||
|
? fallback.project_number
|
||||||
|
? `${fallback.project_number} — ${fallback.name}`
|
||||||
|
: fallback.name
|
||||||
|
: null);
|
||||||
|
return (
|
||||||
|
<FormModal isOpen title="Detail plánu" onClose={onClose} hideFooter>
|
||||||
|
<p>
|
||||||
|
<strong>Datum:</strong> {formatDate(c.shift_date)}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>Kategorie:</strong>{" "}
|
||||||
|
{planCategoryLabel(
|
||||||
|
c.category,
|
||||||
|
Object.fromEntries(categories.map((x) => [x.key, x])),
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>Projekt:</strong> {projectLabel || "—"}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>Text:</strong> {c.note || "—"}
|
||||||
|
</p>
|
||||||
|
{c.rangeFrom && c.rangeTo && (
|
||||||
|
<p>
|
||||||
|
<strong>Patří do rozsahu:</strong> {formatDate(c.rangeFrom)} –{" "}
|
||||||
|
{formatDate(c.rangeTo)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</FormModal>
|
||||||
|
);
|
||||||
|
}
|
||||||
260
src/admin/components/PlanGrid.tsx
Normal file
260
src/admin/components/PlanGrid.tsx
Normal file
@@ -0,0 +1,260 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import type { CSSProperties } from "react";
|
||||||
|
import {
|
||||||
|
GridData,
|
||||||
|
ResolvedCell,
|
||||||
|
planCategoryLabel,
|
||||||
|
categoryMap,
|
||||||
|
PlanCategory,
|
||||||
|
} from "../lib/queries/plan";
|
||||||
|
import type { Project } from "../lib/queries/projects";
|
||||||
|
import PlanRangeChips from "./PlanRangeChips";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
data: GridData | undefined;
|
||||||
|
canEdit: boolean;
|
||||||
|
projects: Project[];
|
||||||
|
categories: PlanCategory[];
|
||||||
|
// The (userId, date) of the most recent successful mutation. The
|
||||||
|
// matching cell gets a one-shot highlight pulse. `nonce` is part of
|
||||||
|
// the value so back-to-back mutations on the same cell re-trigger
|
||||||
|
// the animation (React needs a new key to re-mount the class).
|
||||||
|
pulseKey?: { userId: number; date: string; nonce: number } | null;
|
||||||
|
onCellClick: (
|
||||||
|
userId: number,
|
||||||
|
date: string,
|
||||||
|
cell: ResolvedCell | null,
|
||||||
|
) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full Czech weekday names, indexed by Date.getUTCDay() (0 = Sunday).
|
||||||
|
// Used in the date column "stamp" so the day name reads in full rather
|
||||||
|
// than as a 2-letter abbreviation — easier to scan when the planner
|
||||||
|
// spans several weeks.
|
||||||
|
const CZECH_WEEKDAYS = [
|
||||||
|
"Neděle",
|
||||||
|
"Pondělí",
|
||||||
|
"Úterý",
|
||||||
|
"Středa",
|
||||||
|
"Čtvrtek",
|
||||||
|
"Pátek",
|
||||||
|
"Sobota",
|
||||||
|
];
|
||||||
|
|
||||||
|
function eachDay(from: string, to: string): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
const a = new Date(from + "T00:00:00.000Z");
|
||||||
|
const b = new Date(to + "T00:00:00.000Z");
|
||||||
|
for (let d = new Date(a); d <= b; d.setUTCDate(d.getUTCDate() + 1)) {
|
||||||
|
out.push(d.toISOString().slice(0, 10));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function czechWeekday(dateStr: string): string {
|
||||||
|
return CZECH_WEEKDAYS[new Date(dateStr + "T00:00:00.000Z").getUTCDay()];
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWeekend(dateStr: string): boolean {
|
||||||
|
const day = new Date(dateStr + "T00:00:00.000Z").getUTCDay();
|
||||||
|
return day === 0 || day === 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Today's local date as YYYY-MM-DD. Used to mark the current row and to
|
||||||
|
// gate past-day editing. Uses local time (matches the project's date
|
||||||
|
// conventions in CLAUDE.md and the server's `assertNotPastDate` guard in
|
||||||
|
// src/services/plan.service.ts).
|
||||||
|
function todayIso(): string {
|
||||||
|
const d = new Date();
|
||||||
|
const y = d.getFullYear();
|
||||||
|
const m = String(d.getMonth() + 1).padStart(2, "0");
|
||||||
|
const day = String(d.getDate()).padStart(2, "0");
|
||||||
|
return `${y}-${m}-${day}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// True when the given YYYY-MM-DD cell date is strictly before today (local).
|
||||||
|
// Used to gate the create / edit UI on past days — the server still enforces
|
||||||
|
// the rule with a 403, but the client should never put the user in the
|
||||||
|
// "I clicked, modal opened, error toast" state in the first place.
|
||||||
|
function isPastDate(dateStr: string, today: string): boolean {
|
||||||
|
return dateStr < today;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split a full name into first / last for the column header.
|
||||||
|
function splitName(full: string): { first: string; last: string } {
|
||||||
|
const parts = full.trim().split(/\s+/);
|
||||||
|
if (parts.length === 1) return { first: parts[0], last: "" };
|
||||||
|
return { first: parts[0], last: parts.slice(1).join(" ") };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Short role label for the column header sub-line.
|
||||||
|
function shortRole(role: string | null): string {
|
||||||
|
if (!role) return "";
|
||||||
|
// Keep it brief — column header is tight
|
||||||
|
if (/^admin$/i.test(role)) return "Admin";
|
||||||
|
if (/^viewer$/i.test(role)) return "Viewer";
|
||||||
|
return role.length > 10 ? role.slice(0, 9) + "…" : role;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PlanGrid({
|
||||||
|
data,
|
||||||
|
canEdit,
|
||||||
|
projects,
|
||||||
|
categories,
|
||||||
|
pulseKey,
|
||||||
|
onCellClick,
|
||||||
|
}: Props) {
|
||||||
|
const today = useMemo(() => todayIso(), []);
|
||||||
|
const catMap = useMemo(() => categoryMap(categories), [categories]);
|
||||||
|
|
||||||
|
if (!data)
|
||||||
|
return (
|
||||||
|
<div className="admin-loading">
|
||||||
|
<div className="admin-spinner" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
const days = eachDay(data.date_from, data.date_to);
|
||||||
|
const users = data.users;
|
||||||
|
// pulseKey?.nonce is included in the data-pulse attribute so a second
|
||||||
|
// mutation on the same cell re-triggers the animation (CSS animations
|
||||||
|
// don't restart unless the keyframe applies to a fresh element/class
|
||||||
|
// binding).
|
||||||
|
const pulseAttr = pulseKey
|
||||||
|
? `${pulseKey.userId}|${pulseKey.date}|${pulseKey.nonce}`
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="plan-grid-wrap" data-pulse={pulseAttr}>
|
||||||
|
<table className="plan-grid">
|
||||||
|
{/* The colgroup is what actually controls column width in a
|
||||||
|
table — `min-width` on `<th>`/`<td>` is just a floor that
|
||||||
|
`table-layout: auto` happily blows past. The first column
|
||||||
|
gets a fixed width via the col element so the date stamp
|
||||||
|
doesn't get stretched to share space with person columns. */}
|
||||||
|
<colgroup>
|
||||||
|
<col className="plan-grid-date-col" />
|
||||||
|
{users.map((u) => (
|
||||||
|
<col key={u.id} />
|
||||||
|
))}
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th className="plan-grid-date-col">Datum</th>
|
||||||
|
{users.map((u) => {
|
||||||
|
const { first, last } = splitName(u.full_name);
|
||||||
|
return (
|
||||||
|
<th key={u.id}>
|
||||||
|
<span className="plan-person-head">
|
||||||
|
<span className="plan-person-dot" aria-hidden />
|
||||||
|
<span className="plan-person-name">
|
||||||
|
<strong title={u.full_name}>
|
||||||
|
{first}
|
||||||
|
{last ? ` ${last}` : ""}
|
||||||
|
</strong>
|
||||||
|
{shortRole(u.role_name) && (
|
||||||
|
<small>{shortRole(u.role_name)}</small>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</th>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{days.map((date) => {
|
||||||
|
const dow = czechWeekday(date);
|
||||||
|
const dayNum = date.slice(8, 10);
|
||||||
|
const isToday = date === today;
|
||||||
|
const trCls = [
|
||||||
|
isWeekend(date) ? "plan-grid-weekend" : "",
|
||||||
|
isToday ? "is-today" : "",
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ");
|
||||||
|
return (
|
||||||
|
<tr key={date} className={trCls}>
|
||||||
|
<td className="plan-grid-date-col">
|
||||||
|
<span className="plan-date-stamp">
|
||||||
|
<span className="plan-date-daynum">{dayNum}</span>
|
||||||
|
<span className="plan-date-dow">{dow}</span>
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
{users.map((u) => {
|
||||||
|
const cell = data.cells[u.id]?.[date] ?? null;
|
||||||
|
const past = isPastDate(date, today);
|
||||||
|
// Past-day cells are read-only in the UI: an empty past
|
||||||
|
// cell is non-interactive (no create modal, no "+" hint),
|
||||||
|
// a past cell with data opens in view mode only. The
|
||||||
|
// server still enforces the past-date rule with a 403
|
||||||
|
// (defense in depth), but the click path here never
|
||||||
|
// reaches a create/edit submission for a past date.
|
||||||
|
const isLocked = !canEdit || past;
|
||||||
|
// `isPulsing` is true for the single (user, date) cell
|
||||||
|
// that the most recent successful mutation touched.
|
||||||
|
// CSS restarts the keyframe animation whenever the
|
||||||
|
// `nonce` changes (we embed it in data-pulse on the
|
||||||
|
// wrapper, see above), so back-to-back mutations on the
|
||||||
|
// same cell re-trigger the pulse.
|
||||||
|
const isPulsing =
|
||||||
|
!!pulseKey &&
|
||||||
|
pulseKey.userId === u.id &&
|
||||||
|
pulseKey.date === date;
|
||||||
|
let cls: string;
|
||||||
|
if (cell) {
|
||||||
|
cls = isLocked
|
||||||
|
? `plan-cell plan-cell--readonly${past ? " plan-cell--past" : ""}`
|
||||||
|
: "plan-cell";
|
||||||
|
} else {
|
||||||
|
cls = isLocked
|
||||||
|
? `plan-cell plan-cell--empty plan-cell--readonly${past ? " plan-cell--past" : ""}`
|
||||||
|
: "plan-cell plan-cell--empty";
|
||||||
|
}
|
||||||
|
if (isPulsing) cls += " plan-cell--pulse";
|
||||||
|
return (
|
||||||
|
<td key={u.id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cls}
|
||||||
|
style={
|
||||||
|
cell
|
||||||
|
? ({
|
||||||
|
"--cat-color": catMap[cell.category]?.color,
|
||||||
|
} as CSSProperties)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onClick={() => onCellClick(u.id, date, cell)}
|
||||||
|
aria-label={
|
||||||
|
cell
|
||||||
|
? `${u.full_name}, ${date}, ${planCategoryLabel(cell.category, catMap)}`
|
||||||
|
: isLocked
|
||||||
|
? `${u.full_name}, ${date}, ${past ? "uplynulý den" : "prázdné"} — bez záznamu`
|
||||||
|
: `${u.full_name}, ${date}, prázdné — přidat záznam`
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<PlanRangeChips
|
||||||
|
cell={cell}
|
||||||
|
project={
|
||||||
|
cell?.project_id
|
||||||
|
? (projects.find(
|
||||||
|
(p) => p.id === cell.project_id,
|
||||||
|
) ?? null)
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
readonly={!canEdit}
|
||||||
|
categoryLabel={
|
||||||
|
cell ? planCategoryLabel(cell.category, catMap) : ""
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
42
src/admin/components/PlanRangeChips.tsx
Normal file
42
src/admin/components/PlanRangeChips.tsx
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { ResolvedCell, cellProjectLabel } from "../lib/queries/plan";
|
||||||
|
import type { Project } from "../lib/queries/projects";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
cell: ResolvedCell | null;
|
||||||
|
project: Project | null;
|
||||||
|
readonly?: boolean;
|
||||||
|
categoryLabel: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PlanRangeChips({
|
||||||
|
cell,
|
||||||
|
project,
|
||||||
|
readonly,
|
||||||
|
categoryLabel,
|
||||||
|
}: Props) {
|
||||||
|
void readonly;
|
||||||
|
if (!cell) return null;
|
||||||
|
// Prefer the server-embedded project label (always present). Fall back to
|
||||||
|
// the looked-up `project` prop only if the cell predates the embed (stale
|
||||||
|
// cache).
|
||||||
|
const fallbackLabel = project
|
||||||
|
? project.project_number
|
||||||
|
? `${project.project_number} — ${project.name}`
|
||||||
|
: project.name
|
||||||
|
: null;
|
||||||
|
const projectLabel = cellProjectLabel(cell) ?? fallbackLabel;
|
||||||
|
const projectTitle = projectLabel ?? undefined;
|
||||||
|
return (
|
||||||
|
<div className="plan-chip-block">
|
||||||
|
<div className="plan-chip-line">
|
||||||
|
<span className="plan-chip">{categoryLabel}</span>
|
||||||
|
{projectLabel && (
|
||||||
|
<span className="plan-chip-project" title={projectTitle}>
|
||||||
|
{projectLabel}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{cell.note && <div className="plan-cell-note">{cell.note}</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useState, useEffect, useRef, useCallback } from "react";
|
import { useState, useRef } from "react";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { projectFilesOptions } from "../lib/queries/projects";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import ConfirmModal from "./ConfirmModal";
|
import ConfirmModal from "./ConfirmModal";
|
||||||
import apiFetch from "../utils/api";
|
import apiFetch from "../utils/api";
|
||||||
@@ -196,14 +198,11 @@ export default function ProjectFileManager({
|
|||||||
hasNasFolder,
|
hasNasFolder,
|
||||||
}: ProjectFileManagerProps) {
|
}: ProjectFileManagerProps) {
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const isCancelling = useRef(false);
|
const isCancelling = useRef(false);
|
||||||
|
|
||||||
const [items, setItems] = useState<FileItem[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [currentPath, setCurrentPath] = useState("");
|
const [currentPath, setCurrentPath] = useState("");
|
||||||
const [breadcrumb, setBreadcrumb] = useState<string[]>([""]);
|
|
||||||
const [fullPath, setFullPath] = useState("");
|
|
||||||
|
|
||||||
const [dragOver, setDragOver] = useState(false);
|
const [dragOver, setDragOver] = useState(false);
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
@@ -217,59 +216,25 @@ export default function ProjectFileManager({
|
|||||||
|
|
||||||
const [deleteTarget, setDeleteTarget] = useState<FileItem | null>(null);
|
const [deleteTarget, setDeleteTarget] = useState<FileItem | null>(null);
|
||||||
const [deleting, setDeleting] = useState(false);
|
const [deleting, setDeleting] = useState(false);
|
||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const canManage = hasPermission("projects.files");
|
const canManage = hasPermission("projects.files");
|
||||||
|
|
||||||
const fetchFiles = useCallback(
|
const {
|
||||||
async (path = "", options: { ignore?: boolean } = {}) => {
|
data: filesData,
|
||||||
setLoading(true);
|
isPending: filesLoading,
|
||||||
setErrorMessage(null);
|
error: filesError,
|
||||||
try {
|
} = useQuery(projectFilesOptions(projectId, currentPath));
|
||||||
const params = new URLSearchParams({ project_id: String(projectId) });
|
const items = filesData?.items ?? [];
|
||||||
if (path) {
|
const breadcrumb = filesData?.breadcrumb ?? [""];
|
||||||
params.set("path", path);
|
const fullPath = filesData?.full_path ?? "";
|
||||||
}
|
const errorMessage = filesError
|
||||||
const res = await apiFetch(`${API_BASE}/project-files?${params}`);
|
? filesError.message || "Nepodařilo se načíst soubory"
|
||||||
if (options.ignore) return;
|
: null;
|
||||||
if (res.status === 401) return;
|
|
||||||
const data = await res.json();
|
|
||||||
if (data.success) {
|
|
||||||
setItems(data.data.items || []);
|
|
||||||
setBreadcrumb(data.data.breadcrumb || [""]);
|
|
||||||
setCurrentPath(data.data.path || "");
|
|
||||||
setFullPath(data.data.full_path || "");
|
|
||||||
} else if (res.status === 404) {
|
|
||||||
setItems([]);
|
|
||||||
setBreadcrumb([""]);
|
|
||||||
} else {
|
|
||||||
setErrorMessage(data.error || "Nepodařilo se načíst soubory");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
if (!options.ignore) {
|
|
||||||
setErrorMessage("Chyba připojení");
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (!options.ignore) {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[projectId],
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const opts = { ignore: false };
|
|
||||||
fetchFiles("", opts);
|
|
||||||
return () => {
|
|
||||||
opts.ignore = true;
|
|
||||||
};
|
|
||||||
}, [fetchFiles]);
|
|
||||||
|
|
||||||
const navigateTo = (path: string) => {
|
const navigateTo = (path: string) => {
|
||||||
setNewFolderMode(false);
|
setNewFolderMode(false);
|
||||||
setRenamingItem(null);
|
setRenamingItem(null);
|
||||||
fetchFiles(path);
|
setCurrentPath(path);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleBreadcrumbClick = (index: number) => {
|
const handleBreadcrumbClick = (index: number) => {
|
||||||
@@ -332,7 +297,9 @@ export default function ProjectFileManager({
|
|||||||
? "Soubor byl nahrán"
|
? "Soubor byl nahrán"
|
||||||
: `Nahráno ${successCount} souborů`;
|
: `Nahráno ${successCount} souborů`;
|
||||||
alert.success(msg);
|
alert.success(msg);
|
||||||
fetchFiles(currentPath);
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["projects", String(projectId), "files"],
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (errorMsg) {
|
if (errorMsg) {
|
||||||
alert.error(errorMsg);
|
alert.error(errorMsg);
|
||||||
@@ -383,7 +350,9 @@ export default function ProjectFileManager({
|
|||||||
alert.success("Složka byla vytvořena");
|
alert.success("Složka byla vytvořena");
|
||||||
setNewFolderMode(false);
|
setNewFolderMode(false);
|
||||||
setNewFolderName("");
|
setNewFolderName("");
|
||||||
fetchFiles(currentPath);
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["projects", String(projectId), "files"],
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
alert.error(data.error || "Nepodařilo se vytvořit složku");
|
alert.error(data.error || "Nepodařilo se vytvořit složku");
|
||||||
}
|
}
|
||||||
@@ -444,7 +413,9 @@ export default function ProjectFileManager({
|
|||||||
? "Složka byla smazána"
|
? "Složka byla smazána"
|
||||||
: "Soubor byl smazán",
|
: "Soubor byl smazán",
|
||||||
);
|
);
|
||||||
fetchFiles(currentPath);
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["projects", String(projectId), "files"],
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
alert.error(data.error || "Nepodařilo se smazat");
|
alert.error(data.error || "Nepodařilo se smazat");
|
||||||
}
|
}
|
||||||
@@ -479,7 +450,9 @@ export default function ProjectFileManager({
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
alert.success("Přejmenováno");
|
alert.success("Přejmenováno");
|
||||||
fetchFiles(currentPath);
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["projects", String(projectId), "files"],
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
alert.error(data.error || "Nepodařilo se přejmenovat");
|
alert.error(data.error || "Nepodařilo se přejmenovat");
|
||||||
}
|
}
|
||||||
@@ -495,31 +468,10 @@ export default function ProjectFileManager({
|
|||||||
setRenameValue(item.name);
|
setRenameValue(item.name);
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading && items.length === 0 && !errorMessage) {
|
if (filesLoading && items.length === 0 && !errorMessage) {
|
||||||
return (
|
return (
|
||||||
<div className="admin-card">
|
<div className="admin-loading">
|
||||||
<div className="admin-card-body">
|
<div className="admin-spinner" />
|
||||||
<h3 className="admin-card-title">Soubory</h3>
|
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "0.5rem" }}>
|
|
||||||
{[0, 1, 2, 3].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "18px",
|
|
||||||
height: "18px",
|
|
||||||
borderRadius: "4px",
|
|
||||||
flexShrink: 0,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: `${60 + i * 10}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -710,7 +662,7 @@ export default function ProjectFileManager({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{items.length === 0 && !loading ? (
|
{items.length === 0 && !filesLoading ? (
|
||||||
<div className="fm-empty">
|
<div className="fm-empty">
|
||||||
<svg
|
<svg
|
||||||
width="32"
|
width="32"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo, useRef, useCallback, useEffect } from "react";
|
import { useMemo, useRef, useCallback, useLayoutEffect } from "react";
|
||||||
import ReactQuill from "react-quill-new";
|
import ReactQuill from "react-quill-new";
|
||||||
import "react-quill-new/dist/quill.snow.css";
|
import "react-quill-new/dist/quill.snow.css";
|
||||||
|
|
||||||
@@ -96,11 +96,11 @@ export default function RichEditor({
|
|||||||
[onChange],
|
[onChange],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (!quillRef.current) return;
|
if (!quillRef.current) return;
|
||||||
const editor = quillRef.current.getEditor();
|
const editor = quillRef.current.getEditor();
|
||||||
editor.format("font", "tahoma");
|
editor.root.style.fontFamily = "Tahoma, sans-serif";
|
||||||
editor.format("size", "14px");
|
editor.root.style.fontSize = "14px";
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -85,7 +85,15 @@ export interface ShiftFormModalProps {
|
|||||||
|
|
||||||
function ProjectTimeStatus({ form, projectLogs }: ProjectTimeStatusProps) {
|
function ProjectTimeStatus({ form, projectLogs }: ProjectTimeStatusProps) {
|
||||||
const totalWork = calcFormWorkMinutes(form);
|
const totalWork = calcFormWorkMinutes(form);
|
||||||
const totalProject = calcProjectMinutesTotal(projectLogs);
|
const totalProject = calcProjectMinutesTotal(
|
||||||
|
projectLogs.map((l) => ({
|
||||||
|
...l,
|
||||||
|
project_id:
|
||||||
|
l.project_id !== "" && l.project_id != null
|
||||||
|
? Number(l.project_id)
|
||||||
|
: undefined,
|
||||||
|
})),
|
||||||
|
);
|
||||||
const remaining = totalWork - totalProject;
|
const remaining = totalWork - totalProject;
|
||||||
const hasLogs = projectLogs.some((l) => l.project_id);
|
const hasLogs = projectLogs.some((l) => l.project_id);
|
||||||
|
|
||||||
@@ -329,7 +337,6 @@ export default function ShiftFormModal({
|
|||||||
<option value="work">Práce</option>
|
<option value="work">Práce</option>
|
||||||
<option value="vacation">Dovolená</option>
|
<option value="vacation">Dovolená</option>
|
||||||
<option value="sick">Nemoc</option>
|
<option value="sick">Nemoc</option>
|
||||||
<option value="holiday">Svátek</option>
|
|
||||||
<option value="unpaid">Neplacené volno</option>
|
<option value="unpaid">Neplacené volno</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ const menuSections: MenuSection[] = [
|
|||||||
{
|
{
|
||||||
path: "/attendance/admin",
|
path: "/attendance/admin",
|
||||||
label: "Správa",
|
label: "Správa",
|
||||||
permission: "attendance.admin",
|
permission: "attendance.manage",
|
||||||
matchPrefix: "/attendance/admin",
|
matchPrefix: "/attendance/admin",
|
||||||
matchAlso: ["/attendance/create", "/attendance/location"],
|
matchAlso: ["/attendance/create", "/attendance/location"],
|
||||||
icon: (
|
icon: (
|
||||||
@@ -155,6 +155,26 @@ const menuSections: MenuSection[] = [
|
|||||||
</svg>
|
</svg>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: "/plan-work",
|
||||||
|
label: "Plán prací",
|
||||||
|
permission: ["attendance.manage", "attendance.record"],
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
>
|
||||||
|
<rect x="3" y="4" width="18" height="18" rx="2" />
|
||||||
|
<line x1="16" y1="2" x2="16" y2="6" />
|
||||||
|
<line x1="8" y1="2" x2="8" y2="6" />
|
||||||
|
<line x1="3" y1="10" x2="21" y2="10" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -198,7 +218,7 @@ const menuSections: MenuSection[] = [
|
|||||||
{
|
{
|
||||||
path: "/trips/admin",
|
path: "/trips/admin",
|
||||||
label: "Správa",
|
label: "Správa",
|
||||||
permission: "trips.admin",
|
permission: "trips.manage",
|
||||||
icon: (
|
icon: (
|
||||||
<svg
|
<svg
|
||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
@@ -221,7 +241,7 @@ const menuSections: MenuSection[] = [
|
|||||||
{
|
{
|
||||||
path: "/vehicles",
|
path: "/vehicles",
|
||||||
label: "Vozidla",
|
label: "Vozidla",
|
||||||
permission: "trips.vehicles",
|
permission: "vehicles.manage",
|
||||||
icon: (
|
icon: (
|
||||||
<svg
|
<svg
|
||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
@@ -315,7 +335,202 @@ const menuSections: MenuSection[] = [
|
|||||||
{
|
{
|
||||||
path: "/offers/customers",
|
path: "/offers/customers",
|
||||||
label: "Zákazníci",
|
label: "Zákazníci",
|
||||||
permission: "offers.view",
|
permission: "customers.view",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||||
|
<circle cx="9" cy="7" r="4" />
|
||||||
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
|
||||||
|
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Sklad",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
path: "/warehouse",
|
||||||
|
label: "Přehled",
|
||||||
|
permission: "warehouse.view",
|
||||||
|
end: true,
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
>
|
||||||
|
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
|
||||||
|
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
|
||||||
|
<line x1="12" y1="22.08" x2="12" y2="12" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/items",
|
||||||
|
label: "Položky",
|
||||||
|
permission: "warehouse.view",
|
||||||
|
matchPrefix: "/warehouse/items",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
|
||||||
|
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
|
||||||
|
<line x1="12" y1="22.08" x2="12" y2="12" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/receipts",
|
||||||
|
label: "Příjmy",
|
||||||
|
permission: "warehouse.operate",
|
||||||
|
matchPrefix: "/warehouse/receipts",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<polyline points="17 11 12 6 7 11" />
|
||||||
|
<line x1="12" y1="6" x2="12" y2="18" />
|
||||||
|
<path d="M5 19h14" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/issues",
|
||||||
|
label: "Výdeje",
|
||||||
|
permission: "warehouse.operate",
|
||||||
|
matchPrefix: "/warehouse/issues",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<polyline points="7 13 12 18 17 13" />
|
||||||
|
<line x1="12" y1="18" x2="12" y2="6" />
|
||||||
|
<path d="M5 5h14" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/reservations",
|
||||||
|
label: "Rezervace",
|
||||||
|
permission: "warehouse.operate",
|
||||||
|
matchPrefix: "/warehouse/reservations",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
|
||||||
|
<circle cx="9" cy="7" r="4" />
|
||||||
|
<line x1="19" y1="8" x2="19" y2="14" />
|
||||||
|
<line x1="22" y1="11" x2="16" y2="11" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/inventory",
|
||||||
|
label: "Inventura",
|
||||||
|
permission: "warehouse.inventory",
|
||||||
|
matchPrefix: "/warehouse/inventory",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M9 11l3 3L22 4" />
|
||||||
|
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/reports",
|
||||||
|
label: "Reporty",
|
||||||
|
permission: "warehouse.view",
|
||||||
|
end: true,
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<line x1="18" y1="20" x2="18" y2="10" />
|
||||||
|
<line x1="12" y1="20" x2="12" y2="4" />
|
||||||
|
<line x1="6" y1="20" x2="6" y2="14" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/categories",
|
||||||
|
label: "Kategorie",
|
||||||
|
permission: "warehouse.manage",
|
||||||
|
matchPrefix: "/warehouse/categories",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<line x1="4" y1="21" x2="4" y2="14" />
|
||||||
|
<line x1="4" y1="10" x2="4" y2="3" />
|
||||||
|
<line x1="12" y1="21" x2="12" y2="12" />
|
||||||
|
<line x1="12" y1="8" x2="12" y2="3" />
|
||||||
|
<line x1="20" y1="21" x2="20" y2="16" />
|
||||||
|
<line x1="20" y1="12" x2="20" y2="3" />
|
||||||
|
<line x1="1" y1="14" x2="7" y2="14" />
|
||||||
|
<line x1="9" y1="8" x2="15" y2="8" />
|
||||||
|
<line x1="17" y1="16" x2="23" y2="16" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/locations",
|
||||||
|
label: "Lokace",
|
||||||
|
permission: "warehouse.manage",
|
||||||
|
matchPrefix: "/warehouse/locations",
|
||||||
|
icon: (
|
||||||
|
<svg
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<rect x="3" y="3" width="7" height="7" rx="1" />
|
||||||
|
<rect x="14" y="3" width="7" height="7" rx="1" />
|
||||||
|
<rect x="3" y="14" width="7" height="7" rx="1" />
|
||||||
|
<rect x="14" y="14" width="7" height="7" rx="1" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "/warehouse/suppliers",
|
||||||
|
label: "Dodavatelé",
|
||||||
|
permission: "warehouse.manage",
|
||||||
|
matchPrefix: "/warehouse/suppliers",
|
||||||
icon: (
|
icon: (
|
||||||
<svg
|
<svg
|
||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
@@ -356,7 +571,13 @@ const menuSections: MenuSection[] = [
|
|||||||
{
|
{
|
||||||
path: "/settings",
|
path: "/settings",
|
||||||
label: "Nastavení",
|
label: "Nastavení",
|
||||||
permission: "settings.manage",
|
permission: [
|
||||||
|
"settings.company",
|
||||||
|
"settings.banking",
|
||||||
|
"settings.roles",
|
||||||
|
"settings.system",
|
||||||
|
"settings.templates",
|
||||||
|
],
|
||||||
icon: (
|
icon: (
|
||||||
<svg
|
<svg
|
||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
|
|||||||
@@ -89,6 +89,21 @@ export default function DashProfile({
|
|||||||
const handleSubmit = async (e?: React.FormEvent) => {
|
const handleSubmit = async (e?: React.FormEvent) => {
|
||||||
e?.preventDefault();
|
e?.preventDefault();
|
||||||
const dataToSave = { ...formData };
|
const dataToSave = { ...formData };
|
||||||
|
|
||||||
|
if (dataToSave.new_password && !dataToSave.current_password) {
|
||||||
|
alert.error("Pro změnu hesla zadejte aktuální heslo");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (dataToSave.current_password && !dataToSave.new_password) {
|
||||||
|
alert.error("Pro změnu hesla zadejte nové heslo");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip empty password fields so Zod doesn't reject ""
|
||||||
|
if (!dataToSave.current_password)
|
||||||
|
delete (dataToSave as any).current_password;
|
||||||
|
if (!dataToSave.new_password) delete (dataToSave as any).new_password;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/profile`, {
|
const response = await apiFetch(`${API_BASE}/profile`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
@@ -329,9 +344,24 @@ export default function DashProfile({
|
|||||||
className="admin-form-input"
|
className="admin-form-input"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="admin-form-group">
|
||||||
|
<label className="admin-form-label">Aktuální heslo</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={formData.current_password}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
current_password: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="admin-form-input"
|
||||||
|
placeholder="Pro změnu hesla, zadejte aktuální heslo"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div className="admin-form-group">
|
<div className="admin-form-group">
|
||||||
<label className="admin-form-label">
|
<label className="admin-form-label">
|
||||||
Nové heslo (ponechte prázdné pro zachování stávajícího)
|
Nové heslo
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
type="password"
|
type="password"
|
||||||
@@ -343,27 +373,9 @@ export default function DashProfile({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
className="admin-form-input"
|
className="admin-form-input"
|
||||||
|
placeholder="Pro změnu hesla, zadejte nové heslo"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{formData.new_password && (
|
|
||||||
<div className="admin-form-group">
|
|
||||||
<label className="admin-form-label required">
|
|
||||||
Aktuální heslo
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={formData.current_password}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
current_password: e.target.value,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="admin-form-input"
|
|
||||||
placeholder="Zadejte aktuální heslo pro potvrzení"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-modal-footer">
|
<div className="admin-modal-footer">
|
||||||
|
|||||||
@@ -1,27 +1,15 @@
|
|||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState } from "react";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import { useAlert } from "../../context/AlertContext";
|
import { useAlert } from "../../context/AlertContext";
|
||||||
import ConfirmModal from "../ConfirmModal";
|
import ConfirmModal from "../ConfirmModal";
|
||||||
import useModalLock from "../../hooks/useModalLock";
|
import useModalLock from "../../hooks/useModalLock";
|
||||||
import apiFetch from "../../utils/api";
|
import apiFetch from "../../utils/api";
|
||||||
import { formatSessionDate } from "../../utils/dashboardHelpers";
|
import { formatSessionDate } from "../../utils/dashboardHelpers";
|
||||||
|
import { sessionsOptions, type Session } from "../../lib/queries/dashboard";
|
||||||
|
|
||||||
const API_BASE = "/api/admin";
|
const API_BASE = "/api/admin";
|
||||||
|
|
||||||
interface DeviceInfo {
|
|
||||||
icon?: string;
|
|
||||||
browser?: string;
|
|
||||||
os?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Session {
|
|
||||||
id: number | string;
|
|
||||||
is_current: boolean;
|
|
||||||
device_info?: DeviceInfo;
|
|
||||||
ip_address: string;
|
|
||||||
created_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DeleteModalState {
|
interface DeleteModalState {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
session: Session | null;
|
session: Session | null;
|
||||||
@@ -77,9 +65,10 @@ function getDeviceIcon(iconType?: string) {
|
|||||||
|
|
||||||
export default function DashSessions() {
|
export default function DashSessions() {
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [sessions, setSessions] = useState<Session[]>([]);
|
const { data: sessions = [], isPending: sessionsLoading } =
|
||||||
const [sessionsLoading, setSessionsLoading] = useState(true);
|
useQuery(sessionsOptions());
|
||||||
const [deleteModal, setDeleteModal] = useState<DeleteModalState>({
|
const [deleteModal, setDeleteModal] = useState<DeleteModalState>({
|
||||||
isOpen: false,
|
isOpen: false,
|
||||||
session: null,
|
session: null,
|
||||||
@@ -89,26 +78,6 @@ export default function DashSessions() {
|
|||||||
|
|
||||||
useModalLock(deleteAllModal);
|
useModalLock(deleteAllModal);
|
||||||
|
|
||||||
const fetchSessions = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(`${API_BASE}/sessions`);
|
|
||||||
const data = await response.json();
|
|
||||||
if (data.success) {
|
|
||||||
setSessions(
|
|
||||||
Array.isArray(data.data) ? data.data : data.data?.sessions || [],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// session fetch failed silently
|
|
||||||
} finally {
|
|
||||||
setSessionsLoading(false);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchSessions();
|
|
||||||
}, [fetchSessions]);
|
|
||||||
|
|
||||||
const handleDeleteSession = async () => {
|
const handleDeleteSession = async () => {
|
||||||
if (!deleteModal.session) {
|
if (!deleteModal.session) {
|
||||||
return;
|
return;
|
||||||
@@ -122,7 +91,7 @@ export default function DashSessions() {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setDeleteModal({ isOpen: false, session: null });
|
setDeleteModal({ isOpen: false, session: null });
|
||||||
setSessions((prev) => prev.filter((s) => s.id !== sessionId));
|
queryClient.invalidateQueries({ queryKey: ["sessions"] });
|
||||||
alert.success("Relace byla ukončena");
|
alert.success("Relace byla ukončena");
|
||||||
} else {
|
} else {
|
||||||
alert.error(data.error || "Nepodařilo se ukončit relaci");
|
alert.error(data.error || "Nepodařilo se ukončit relaci");
|
||||||
@@ -143,7 +112,7 @@ export default function DashSessions() {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setDeleteAllModal(false);
|
setDeleteAllModal(false);
|
||||||
setSessions((prev) => prev.filter((s) => s.is_current));
|
queryClient.invalidateQueries({ queryKey: ["sessions"] });
|
||||||
alert.success(data.message || "Ostatní relace byly ukončeny");
|
alert.success(data.message || "Ostatní relace byly ukončeny");
|
||||||
} else {
|
} else {
|
||||||
alert.error(data.error || "Nepodařilo se ukončit relace");
|
alert.error(data.error || "Nepodařilo se ukončit relace");
|
||||||
@@ -183,97 +152,83 @@ export default function DashSessions() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-card-body" style={{ padding: 0 }}>
|
<div className="admin-card-body" style={{ padding: 0 }}>
|
||||||
{sessionsLoading && (
|
{sessionsLoading ? (
|
||||||
<div
|
<div className="admin-loading">
|
||||||
className="admin-skeleton"
|
<div className="admin-spinner" />
|
||||||
style={{ padding: "1rem", gap: "1rem" }}
|
|
||||||
>
|
|
||||||
{[0, 1, 2].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div className="admin-skeleton-line circle" />
|
|
||||||
<div className="flex-1">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/2"
|
|
||||||
style={{ marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/3"
|
|
||||||
style={{ height: "10px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
) : (
|
||||||
{!sessionsLoading && sessions.length === 0 && (
|
<>
|
||||||
<div
|
{sessions.length === 0 && (
|
||||||
className="text-secondary"
|
|
||||||
style={{
|
|
||||||
padding: "1.5rem",
|
|
||||||
textAlign: "center",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Žádné aktivní relace
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!sessionsLoading && sessions.length > 0 && (
|
|
||||||
<div className="dash-sessions-list">
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<div
|
<div
|
||||||
key={session.id}
|
className="text-secondary"
|
||||||
className={`dash-session-item ${session.is_current ? "dash-session-item-current" : ""}`}
|
style={{
|
||||||
|
padding: "1.5rem",
|
||||||
|
textAlign: "center",
|
||||||
|
fontSize: "0.875rem",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<div className="dash-session-icon">
|
Žádné aktivní relace
|
||||||
{getDeviceIcon(session.device_info?.icon)}
|
|
||||||
</div>
|
|
||||||
<div className="dash-session-info">
|
|
||||||
<div className="dash-session-device">
|
|
||||||
{session.device_info?.browser} na{" "}
|
|
||||||
{session.device_info?.os}
|
|
||||||
{session.is_current && (
|
|
||||||
<span
|
|
||||||
className="admin-badge admin-badge-success"
|
|
||||||
style={{ marginLeft: "0.5rem" }}
|
|
||||||
>
|
|
||||||
Aktuální
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="dash-session-meta">
|
|
||||||
<span>{session.ip_address}</span>
|
|
||||||
<span className="dash-session-meta-separator">|</span>
|
|
||||||
<span>{formatSessionDate(session.created_at)}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="dash-session-actions">
|
|
||||||
{!session.is_current && (
|
|
||||||
<button
|
|
||||||
onClick={() =>
|
|
||||||
setDeleteModal({ isOpen: true, session })
|
|
||||||
}
|
|
||||||
className="admin-btn-icon danger"
|
|
||||||
title="Ukončit relaci"
|
|
||||||
aria-label="Ukončit relaci"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
width="16"
|
|
||||||
height="16"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
>
|
|
||||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
|
||||||
<polyline points="16 17 21 12 16 7" />
|
|
||||||
<line x1="21" y1="12" x2="9" y2="12" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
)}
|
||||||
</div>
|
{sessions.length > 0 && (
|
||||||
|
<div className="dash-sessions-list">
|
||||||
|
{sessions.map((session) => (
|
||||||
|
<div
|
||||||
|
key={session.id}
|
||||||
|
className={`dash-session-item ${session.is_current ? "dash-session-item-current" : ""}`}
|
||||||
|
>
|
||||||
|
<div className="dash-session-icon">
|
||||||
|
{getDeviceIcon(session.device_info?.icon)}
|
||||||
|
</div>
|
||||||
|
<div className="dash-session-info">
|
||||||
|
<div className="dash-session-device">
|
||||||
|
{session.device_info?.browser} na{" "}
|
||||||
|
{session.device_info?.os}
|
||||||
|
{session.is_current && (
|
||||||
|
<span
|
||||||
|
className="admin-badge admin-badge-success"
|
||||||
|
style={{ marginLeft: "0.5rem" }}
|
||||||
|
>
|
||||||
|
Aktuální
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="dash-session-meta">
|
||||||
|
<span>{session.ip_address}</span>
|
||||||
|
<span className="dash-session-meta-separator">|</span>
|
||||||
|
<span>{formatSessionDate(session.created_at)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dash-session-actions">
|
||||||
|
{!session.is_current && (
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
setDeleteModal({ isOpen: true, session })
|
||||||
|
}
|
||||||
|
className="admin-btn-icon danger"
|
||||||
|
title="Ukončit relaci"
|
||||||
|
aria-label="Ukončit relaci"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="16"
|
||||||
|
height="16"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
||||||
|
<polyline points="16 17 21 12 16 7" />
|
||||||
|
<line x1="21" y1="12" x2="9" y2="12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
74
src/admin/components/warehouse/BatchPicker.tsx
Normal file
74
src/admin/components/warehouse/BatchPicker.tsx
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../../lib/apiAdapter";
|
||||||
|
|
||||||
|
interface Batch {
|
||||||
|
id: number;
|
||||||
|
quantity: number;
|
||||||
|
unit_price: number;
|
||||||
|
received_at: string;
|
||||||
|
is_consumed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BatchesResponse {
|
||||||
|
batches: Batch[];
|
||||||
|
total_stock: number;
|
||||||
|
reserved_quantity: number;
|
||||||
|
available_quantity: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BatchPickerProps {
|
||||||
|
itemId: number | null;
|
||||||
|
value: number | null;
|
||||||
|
onChange: (batchId: number, unitPrice: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function BatchPicker({
|
||||||
|
itemId,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: BatchPickerProps) {
|
||||||
|
const { data: response } = useQuery({
|
||||||
|
queryKey: ["warehouse", "batches", itemId],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<BatchesResponse>(
|
||||||
|
`/api/admin/warehouse/items/${itemId}/batches`,
|
||||||
|
),
|
||||||
|
enabled: !!itemId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const batches = response?.batches ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{response && response.reserved_quantity > 0 && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
color: "var(--text-tertiary)",
|
||||||
|
marginBottom: "0.25rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Dostupné: {response.available_quantity} ks (z toho rezervováno:{" "}
|
||||||
|
{response.reserved_quantity} ks)
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<select
|
||||||
|
className="admin-form-select"
|
||||||
|
value={value ?? ""}
|
||||||
|
onChange={(e) => {
|
||||||
|
const batchId = Number(e.target.value);
|
||||||
|
const batch = batches.find((b) => b.id === batchId);
|
||||||
|
if (batch) onChange(batch.id, Number(batch.unit_price));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">-- auto FIFO --</option>
|
||||||
|
{batches.map((b) => (
|
||||||
|
<option key={b.id} value={b.id}>
|
||||||
|
{new Date(b.received_at).toLocaleDateString("cs-CZ")} | {b.quantity}{" "}
|
||||||
|
ks | {Number(b.unit_price).toFixed(2)} Kč
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
228
src/admin/components/warehouse/ItemPicker.tsx
Normal file
228
src/admin/components/warehouse/ItemPicker.tsx
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
import { useState, useRef, useEffect, useCallback, useId } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { warehouseItemListOptions } from "../../lib/queries/warehouse";
|
||||||
|
|
||||||
|
interface ItemPickerProps {
|
||||||
|
value: number | null;
|
||||||
|
onChange: (itemId: number) => void;
|
||||||
|
itemName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ItemPicker({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
itemName,
|
||||||
|
}: ItemPickerProps) {
|
||||||
|
const [search, setSearch] = useState(itemName ?? "");
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const { data } = useQuery(warehouseItemListOptions({ search, perPage: 20 }));
|
||||||
|
const items = data?.data ?? [];
|
||||||
|
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const activeIndexRef = useRef<number>(-1);
|
||||||
|
const listboxId = useId();
|
||||||
|
const [activeIndex, setActiveIndex] = useState<number>(-1);
|
||||||
|
|
||||||
|
const [dropdownStyle, setDropdownStyle] = useState<{
|
||||||
|
position: "fixed";
|
||||||
|
top: number;
|
||||||
|
left: number;
|
||||||
|
width: number;
|
||||||
|
zIndex: number;
|
||||||
|
} | null>(null);
|
||||||
|
|
||||||
|
const updatePosition = useCallback(() => {
|
||||||
|
if (!containerRef.current) return;
|
||||||
|
const rect = containerRef.current.getBoundingClientRect();
|
||||||
|
setDropdownStyle({
|
||||||
|
position: "fixed",
|
||||||
|
top: rect.bottom + 2,
|
||||||
|
left: rect.left,
|
||||||
|
width: rect.width,
|
||||||
|
zIndex: 100,
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Reset active index when items change
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeIndex >= items.length) {
|
||||||
|
activeIndexRef.current = -1;
|
||||||
|
setActiveIndex(-1);
|
||||||
|
}
|
||||||
|
}, [items, activeIndex]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
updatePosition();
|
||||||
|
const onScroll = () => updatePosition();
|
||||||
|
const onClose = () => setOpen(false);
|
||||||
|
window.addEventListener("scroll", onScroll, true);
|
||||||
|
window.addEventListener("resize", onClose);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("scroll", onScroll, true);
|
||||||
|
window.removeEventListener("resize", onClose);
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
setDropdownStyle(null);
|
||||||
|
activeIndexRef.current = -1;
|
||||||
|
setActiveIndex(-1);
|
||||||
|
}
|
||||||
|
}, [open, updatePosition]);
|
||||||
|
|
||||||
|
// Close on click-outside via mousedown on document
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const onDocMouseDown = (e: MouseEvent) => {
|
||||||
|
const target = e.target;
|
||||||
|
if (containerRef.current && target instanceof Node) {
|
||||||
|
if (!containerRef.current.contains(target)) {
|
||||||
|
// Don't close if click landed on an option in the portal
|
||||||
|
const listEl = document.getElementById(listboxId);
|
||||||
|
if (listEl && listEl.contains(target)) return;
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("mousedown", onDocMouseDown);
|
||||||
|
return () => document.removeEventListener("mousedown", onDocMouseDown);
|
||||||
|
}, [open, listboxId]);
|
||||||
|
|
||||||
|
const handleSelect = (itemId: number, name: string) => {
|
||||||
|
onChange(itemId);
|
||||||
|
setOpen(false);
|
||||||
|
setSearch(name);
|
||||||
|
};
|
||||||
|
|
||||||
|
const setActive = (index: number) => {
|
||||||
|
activeIndexRef.current = index;
|
||||||
|
setActiveIndex(index);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (e.key === "ArrowDown") {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!open) {
|
||||||
|
setOpen(true);
|
||||||
|
if (items.length > 0) setActive(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const next =
|
||||||
|
activeIndexRef.current < items.length - 1
|
||||||
|
? activeIndexRef.current + 1
|
||||||
|
: 0;
|
||||||
|
setActive(next);
|
||||||
|
} else if (e.key === "ArrowUp") {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!open) {
|
||||||
|
setOpen(true);
|
||||||
|
if (items.length > 0) setActive(items.length - 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const prev =
|
||||||
|
activeIndexRef.current > 0
|
||||||
|
? activeIndexRef.current - 1
|
||||||
|
: items.length - 1;
|
||||||
|
setActive(prev);
|
||||||
|
} else if (e.key === "Enter") {
|
||||||
|
if (
|
||||||
|
open &&
|
||||||
|
activeIndexRef.current >= 0 &&
|
||||||
|
activeIndexRef.current < items.length
|
||||||
|
) {
|
||||||
|
e.preventDefault();
|
||||||
|
const item = items[activeIndexRef.current];
|
||||||
|
handleSelect(item.id, item.name);
|
||||||
|
}
|
||||||
|
} else if (e.key === "Escape") {
|
||||||
|
if (open) {
|
||||||
|
e.preventDefault();
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
} else if (e.key === "Home") {
|
||||||
|
if (open && items.length > 0) {
|
||||||
|
e.preventDefault();
|
||||||
|
setActive(0);
|
||||||
|
}
|
||||||
|
} else if (e.key === "End") {
|
||||||
|
if (open && items.length > 0) {
|
||||||
|
e.preventDefault();
|
||||||
|
setActive(items.length - 1);
|
||||||
|
}
|
||||||
|
} else if (e.key === "Tab") {
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeId =
|
||||||
|
activeIndex >= 0 ? `${listboxId}-option-${activeIndex}` : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
style={{ position: "relative" }}
|
||||||
|
role="combobox"
|
||||||
|
aria-haspopup="listbox"
|
||||||
|
aria-expanded={open}
|
||||||
|
aria-owns={listboxId}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="admin-form-input"
|
||||||
|
placeholder="Hledat položku..."
|
||||||
|
value={search}
|
||||||
|
role="searchbox"
|
||||||
|
aria-autocomplete="list"
|
||||||
|
aria-controls={listboxId}
|
||||||
|
aria-activedescendant={activeId}
|
||||||
|
onChange={(e) => {
|
||||||
|
setSearch(e.target.value);
|
||||||
|
setOpen(true);
|
||||||
|
}}
|
||||||
|
onFocus={() => {
|
||||||
|
setOpen(true);
|
||||||
|
updatePosition();
|
||||||
|
}}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
/>
|
||||||
|
{open &&
|
||||||
|
items.length > 0 &&
|
||||||
|
dropdownStyle &&
|
||||||
|
createPortal(
|
||||||
|
<ul
|
||||||
|
id={listboxId}
|
||||||
|
role="listbox"
|
||||||
|
className="admin-item-picker-list"
|
||||||
|
style={dropdownStyle}
|
||||||
|
>
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<li
|
||||||
|
key={item.id}
|
||||||
|
id={`${listboxId}-option-${index}`}
|
||||||
|
role="option"
|
||||||
|
aria-selected={value === item.id}
|
||||||
|
className={`admin-item-picker-item ${activeIndex === index ? "active" : ""}`}
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
handleSelect(item.id, item.name);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="admin-item-picker-name">{item.name}</span>
|
||||||
|
{item.item_number && (
|
||||||
|
<span className="admin-item-picker-number">
|
||||||
|
{item.item_number}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{item.available_quantity !== undefined && (
|
||||||
|
<span className="admin-item-picker-qty">
|
||||||
|
{item.available_quantity} {item.unit}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>,
|
||||||
|
document.body,
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
src/admin/components/warehouse/LocationSelect.tsx
Normal file
31
src/admin/components/warehouse/LocationSelect.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
warehouseLocationListOptions,
|
||||||
|
type WarehouseLocation,
|
||||||
|
} from "../../lib/queries/warehouse";
|
||||||
|
|
||||||
|
interface LocationSelectProps {
|
||||||
|
value: number | null;
|
||||||
|
onChange: (locationId: number | null) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function LocationSelect({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: LocationSelectProps) {
|
||||||
|
const { data: locations } = useQuery(warehouseLocationListOptions());
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="admin-form-select"
|
||||||
|
value={value ?? ""}
|
||||||
|
onChange={(e) => onChange(e.target.value ? Number(e.target.value) : null)}
|
||||||
|
>
|
||||||
|
<option value="">-- bez lokace --</option>
|
||||||
|
{locations?.map((loc: WarehouseLocation) => (
|
||||||
|
<option key={loc.id} value={loc.id}>
|
||||||
|
{loc.code} - {loc.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
54
src/admin/components/warehouse/ReservationPicker.tsx
Normal file
54
src/admin/components/warehouse/ReservationPicker.tsx
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { warehouseReservationListOptions } from "../../lib/queries/warehouse";
|
||||||
|
|
||||||
|
interface ReservationPickerProps {
|
||||||
|
itemId: number | null;
|
||||||
|
projectId: number | null;
|
||||||
|
value: number | null;
|
||||||
|
onChange: (reservationId: number | null, remainingQty: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ReservationPicker({
|
||||||
|
itemId,
|
||||||
|
projectId,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: ReservationPickerProps) {
|
||||||
|
const { data: result } = useQuery(
|
||||||
|
warehouseReservationListOptions({
|
||||||
|
item_id: itemId ?? undefined,
|
||||||
|
project_id: projectId ?? undefined,
|
||||||
|
status: "ACTIVE",
|
||||||
|
perPage: 100,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const reservations = result?.data ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="admin-form-select"
|
||||||
|
value={value ?? ""}
|
||||||
|
onChange={(e) => {
|
||||||
|
const val = e.target.value;
|
||||||
|
if (!val) {
|
||||||
|
onChange(null, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const reservationId = Number(val);
|
||||||
|
const reservation = reservations.find((r) => r.id === reservationId);
|
||||||
|
if (reservation) {
|
||||||
|
onChange(reservationId, Number(reservation.remaining_qty));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">— žádná rezervace —</option>
|
||||||
|
{reservations.map((r) => (
|
||||||
|
<option key={r.id} value={r.id}>
|
||||||
|
R{r.id} — {r.project?.name ?? `Projekt #${r.project_id}`} — zbývá:{" "}
|
||||||
|
{Number(r.remaining_qty)} {r.item?.unit ?? "ks"}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
33
src/admin/components/warehouse/SupplierSelect.tsx
Normal file
33
src/admin/components/warehouse/SupplierSelect.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
warehouseSupplierListOptions,
|
||||||
|
type WarehouseSupplier,
|
||||||
|
} from "../../lib/queries/warehouse";
|
||||||
|
|
||||||
|
interface SupplierSelectProps {
|
||||||
|
value: number | null;
|
||||||
|
onChange: (supplierId: number | null) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SupplierSelect({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: SupplierSelectProps) {
|
||||||
|
const { data } = useQuery(warehouseSupplierListOptions({ perPage: 100 }));
|
||||||
|
const suppliers = data?.data ?? [];
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className="admin-form-select"
|
||||||
|
value={value ?? ""}
|
||||||
|
onChange={(e) => onChange(e.target.value ? Number(e.target.value) : null)}
|
||||||
|
>
|
||||||
|
<option value="">-- bez dodavatele --</option>
|
||||||
|
{suppliers.map((s: WarehouseSupplier) => (
|
||||||
|
<option key={s.id} value={s.id}>
|
||||||
|
{s.name}
|
||||||
|
{s.ico ? ` (${s.ico})` : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
249
src/admin/components/warehouse/WarehouseMovementTable.tsx
Normal file
249
src/admin/components/warehouse/WarehouseMovementTable.tsx
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
import { ReactNode, useId, useRef } from "react";
|
||||||
|
import ItemPicker from "./ItemPicker";
|
||||||
|
import LocationSelect from "./LocationSelect";
|
||||||
|
import BatchPicker from "./BatchPicker";
|
||||||
|
|
||||||
|
export interface MovementItem {
|
||||||
|
key: string;
|
||||||
|
item_id: number | null;
|
||||||
|
item_name?: string;
|
||||||
|
quantity: number;
|
||||||
|
unit_price: number;
|
||||||
|
location_id: number | null;
|
||||||
|
batch_id: number | null;
|
||||||
|
reservation_id: number | null;
|
||||||
|
notes: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MovementRowRenderer<T> = (
|
||||||
|
item: T,
|
||||||
|
index: number,
|
||||||
|
updateItem: (field: string, value: unknown) => void,
|
||||||
|
removeItem: () => void,
|
||||||
|
) => ReactNode;
|
||||||
|
|
||||||
|
interface WarehouseMovementTableProps<T extends { key: string }> {
|
||||||
|
items: T[];
|
||||||
|
onChange: (items: T[]) => void;
|
||||||
|
mode: "receipt" | "issue" | "inventory";
|
||||||
|
defaultItem?: () => Omit<T, "key">;
|
||||||
|
renderRow?: MovementRowRenderer<T>;
|
||||||
|
renderHeader?: () => ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDecimal(raw: string): number {
|
||||||
|
// Strip leading minus if you want negative support; here we want only positive
|
||||||
|
const cleaned = raw.replace(/[eE+\-]/g, "");
|
||||||
|
const n = Number(cleaned);
|
||||||
|
return Number.isFinite(n) ? n : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const builtInDefaultMovementItem = (): Omit<MovementItem, "key"> => ({
|
||||||
|
item_id: null,
|
||||||
|
quantity: 0,
|
||||||
|
unit_price: 0,
|
||||||
|
location_id: null,
|
||||||
|
batch_id: null,
|
||||||
|
reservation_id: null,
|
||||||
|
notes: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
export default function WarehouseMovementTable<T extends { key: string }>({
|
||||||
|
items,
|
||||||
|
onChange,
|
||||||
|
mode,
|
||||||
|
defaultItem,
|
||||||
|
renderRow,
|
||||||
|
renderHeader,
|
||||||
|
}: WarehouseMovementTableProps<T>) {
|
||||||
|
const baseId = useId();
|
||||||
|
const counterRef = useRef(0);
|
||||||
|
const nextKey = () => `${baseId}-item-${counterRef.current++}`;
|
||||||
|
|
||||||
|
const addItem = () => {
|
||||||
|
const factory =
|
||||||
|
defaultItem ??
|
||||||
|
(builtInDefaultMovementItem as unknown as () => Omit<T, "key">);
|
||||||
|
onChange([...items, { ...(factory() as object), key: nextKey() } as T]);
|
||||||
|
};
|
||||||
|
const removeItem = (index: number) => {
|
||||||
|
onChange(items.filter((_, i) => i !== index));
|
||||||
|
};
|
||||||
|
const updateItem = (index: number, field: string, value: unknown) => {
|
||||||
|
const updated = [...items];
|
||||||
|
updated[index] = { ...updated[index], [field]: value };
|
||||||
|
onChange(updated);
|
||||||
|
};
|
||||||
|
|
||||||
|
// If a custom row renderer is supplied, the caller is fully in charge of
|
||||||
|
// the row layout (and typically the column headers too — see inventory mode).
|
||||||
|
if (renderRow) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="admin-warehouse-movement-table">
|
||||||
|
<table className="admin-table">
|
||||||
|
{renderHeader && (
|
||||||
|
<thead>
|
||||||
|
<tr>{renderHeader()}</tr>
|
||||||
|
</thead>
|
||||||
|
)}
|
||||||
|
<tbody>
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<tr key={item.key}>
|
||||||
|
{renderRow(
|
||||||
|
item,
|
||||||
|
index,
|
||||||
|
(field, value) => updateItem(index, field, value),
|
||||||
|
() => removeItem(index),
|
||||||
|
)}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-secondary"
|
||||||
|
onClick={addItem}
|
||||||
|
>
|
||||||
|
+ Přidat řádek
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default rendering: only valid for "receipt" | "issue" — narrow at runtime.
|
||||||
|
const movementItems = items as unknown as MovementItem[];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="admin-warehouse-movement-table">
|
||||||
|
<table className="admin-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th className="admin-warehouse-col-item">Položka</th>
|
||||||
|
{mode === "issue" && (
|
||||||
|
<th className="admin-warehouse-col-batch">Šarže</th>
|
||||||
|
)}
|
||||||
|
<th className="admin-warehouse-col-qty">Množství</th>
|
||||||
|
<th className="admin-warehouse-col-price">Cena/ks</th>
|
||||||
|
<th className="admin-warehouse-col-location">Lokace</th>
|
||||||
|
<th className="admin-warehouse-col-notes">Poznámka</th>
|
||||||
|
<th>Akce</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{movementItems.map((item, index) => (
|
||||||
|
<tr key={item.key}>
|
||||||
|
<td className="admin-warehouse-col-item">
|
||||||
|
<ItemPicker
|
||||||
|
value={item.item_id}
|
||||||
|
itemName={item.item_name}
|
||||||
|
onChange={(id) => updateItem(index, "item_id", id)}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
{mode === "issue" && (
|
||||||
|
<td className="admin-warehouse-col-batch">
|
||||||
|
<BatchPicker
|
||||||
|
itemId={item.item_id}
|
||||||
|
value={item.batch_id}
|
||||||
|
onChange={(batchId, unitPrice) => {
|
||||||
|
updateItem(index, "batch_id", batchId);
|
||||||
|
updateItem(index, "unit_price", unitPrice);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
)}
|
||||||
|
<td className="admin-warehouse-col-qty">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
className="admin-form-input"
|
||||||
|
value={item.quantity || ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateItem(
|
||||||
|
index,
|
||||||
|
"quantity",
|
||||||
|
parseDecimal(e.target.value),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
min="0"
|
||||||
|
step="0.001"
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]+([\.,][0-9]+)?"
|
||||||
|
aria-label={`Množství, řádek ${index + 1}`}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="admin-warehouse-col-price">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
className="admin-form-input"
|
||||||
|
value={item.unit_price || ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateItem(
|
||||||
|
index,
|
||||||
|
"unit_price",
|
||||||
|
parseDecimal(e.target.value),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
disabled={mode === "issue"}
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]+([\.,][0-9]+)?"
|
||||||
|
aria-label={`Cena za kus, řádek ${index + 1}`}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="admin-warehouse-col-location">
|
||||||
|
<LocationSelect
|
||||||
|
value={item.location_id}
|
||||||
|
onChange={(id) => updateItem(index, "location_id", id)}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="admin-warehouse-col-notes">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="admin-form-input"
|
||||||
|
value={item.notes ?? ""}
|
||||||
|
onChange={(e) => updateItem(index, "notes", e.target.value)}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div className="admin-table-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn-icon danger"
|
||||||
|
onClick={() => removeItem(index)}
|
||||||
|
title="Odebrat řádek"
|
||||||
|
aria-label="Odebrat řádek"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="16"
|
||||||
|
height="16"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
>
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18" />
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-btn admin-btn-secondary"
|
||||||
|
onClick={addItem}
|
||||||
|
>
|
||||||
|
+ Přidat řádek
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -90,6 +90,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
const cachedUserRef = useRef<User | null>(null);
|
const cachedUserRef = useRef<User | null>(null);
|
||||||
const sessionFetchedRef = useRef(false);
|
const sessionFetchedRef = useRef(false);
|
||||||
const silentRefreshInFlightRef = useRef<Promise<boolean> | null>(null);
|
const silentRefreshInFlightRef = useRef<Promise<boolean> | null>(null);
|
||||||
|
const hadValidSessionRef = useRef(false);
|
||||||
const [user, setUser] = useState<User | null>(cachedUserRef.current);
|
const [user, setUser] = useState<User | null>(cachedUserRef.current);
|
||||||
const [loading, setLoading] = useState(!sessionFetchedRef.current);
|
const [loading, setLoading] = useState(!sessionFetchedRef.current);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -138,13 +139,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
if (data.success && data.data?.access_token) {
|
if (data.success && data.data?.access_token) {
|
||||||
setAccessTokenFn(data.data.access_token, data.data.expires_in);
|
setAccessTokenFn(data.data.access_token, data.data.expires_in);
|
||||||
setUser(mapUser(data.data.user));
|
setUser(mapUser(data.data.user));
|
||||||
|
hadValidSessionRef.current = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
accessTokenRef.current = null;
|
accessTokenRef.current = null;
|
||||||
tokenExpiresAtRef.current = null;
|
tokenExpiresAtRef.current = null;
|
||||||
setUser(null);
|
setUser(null);
|
||||||
cachedUserRef.current = null;
|
cachedUserRef.current = null;
|
||||||
setSessionExpired();
|
if (hadValidSessionRef.current) setSessionExpired();
|
||||||
return false;
|
return false;
|
||||||
} catch {
|
} catch {
|
||||||
// Network error — don't kick the user out, just return false
|
// Network error — don't kick the user out, just return false
|
||||||
@@ -178,6 +180,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
if (data.data.access_token) setAccessTokenFn(data.data.access_token);
|
if (data.data.access_token) setAccessTokenFn(data.data.access_token);
|
||||||
setUser(mapUser(data.data.user));
|
setUser(mapUser(data.data.user));
|
||||||
cachedUserRef.current = mapUser(data.data.user);
|
cachedUserRef.current = mapUser(data.data.user);
|
||||||
|
hadValidSessionRef.current = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -233,6 +236,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
setUser(mapUser(data.data.user));
|
setUser(mapUser(data.data.user));
|
||||||
cachedUserRef.current = mapUser(data.data.user);
|
cachedUserRef.current = mapUser(data.data.user);
|
||||||
sessionFetchedRef.current = true;
|
sessionFetchedRef.current = true;
|
||||||
|
hadValidSessionRef.current = true;
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
setError(data.error);
|
setError(data.error);
|
||||||
@@ -273,6 +277,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
setUser(mapUser(data.data.user));
|
setUser(mapUser(data.data.user));
|
||||||
cachedUserRef.current = mapUser(data.data.user);
|
cachedUserRef.current = mapUser(data.data.user);
|
||||||
sessionFetchedRef.current = true;
|
sessionFetchedRef.current = true;
|
||||||
|
hadValidSessionRef.current = true;
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
setError(data.error);
|
setError(data.error);
|
||||||
@@ -302,6 +307,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
setUser(null);
|
setUser(null);
|
||||||
cachedUserRef.current = null;
|
cachedUserRef.current = null;
|
||||||
sessionFetchedRef.current = false;
|
sessionFetchedRef.current = false;
|
||||||
|
hadValidSessionRef.current = false;
|
||||||
if (refreshTimeoutRef.current) {
|
if (refreshTimeoutRef.current) {
|
||||||
clearTimeout(refreshTimeoutRef.current);
|
clearTimeout(refreshTimeoutRef.current);
|
||||||
refreshTimeoutRef.current = null;
|
refreshTimeoutRef.current = null;
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
import { useCallback, useRef } from "react";
|
|
||||||
import { useAlert } from "../context/AlertContext";
|
|
||||||
import apiFetch from "../utils/api";
|
|
||||||
|
|
||||||
interface ApiCallResult<T> {
|
|
||||||
data: T | null;
|
|
||||||
ok: boolean;
|
|
||||||
response: Response | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function useApiCall() {
|
|
||||||
const alert = useAlert();
|
|
||||||
const abortRef = useRef<AbortController | null>(null);
|
|
||||||
|
|
||||||
const call = useCallback(
|
|
||||||
async <T = unknown>(
|
|
||||||
url: string,
|
|
||||||
options: RequestInit = {},
|
|
||||||
errorMsg = "Chyba při načítání dat",
|
|
||||||
): Promise<ApiCallResult<T>> => {
|
|
||||||
if (abortRef.current) abortRef.current.abort();
|
|
||||||
const controller = new AbortController();
|
|
||||||
abortRef.current = controller;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { signal: _, ...restOptions } = options;
|
|
||||||
const response = await apiFetch(url, {
|
|
||||||
...restOptions,
|
|
||||||
signal: controller.signal,
|
|
||||||
});
|
|
||||||
const data = await response.json();
|
|
||||||
if (!response.ok || !data.success) {
|
|
||||||
alert.error(data.error || errorMsg);
|
|
||||||
return { data: null, ok: false, response };
|
|
||||||
}
|
|
||||||
return { data: data.data as T, ok: true, response };
|
|
||||||
} catch (err: unknown) {
|
|
||||||
if (err instanceof Error && err.name === "AbortError") {
|
|
||||||
return { data: null, ok: false, response: null };
|
|
||||||
}
|
|
||||||
alert.error(errorMsg);
|
|
||||||
return { data: null, ok: false, response: null };
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[alert],
|
|
||||||
);
|
|
||||||
|
|
||||||
return { call };
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from "react";
|
import { useState, useEffect, useCallback, useRef } from "react";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import apiFetch from "../utils/api";
|
import apiFetch from "../utils/api";
|
||||||
|
import { isHoliday } from "../../utils/czech-holidays";
|
||||||
import {
|
import {
|
||||||
calcProjectMinutesTotal,
|
calcProjectMinutesTotal,
|
||||||
calcFormWorkMinutes,
|
calcFormWorkMinutes,
|
||||||
@@ -9,9 +11,17 @@ import {
|
|||||||
formatDate,
|
formatDate,
|
||||||
formatMinutes,
|
formatMinutes,
|
||||||
getLeaveTypeName,
|
getLeaveTypeName,
|
||||||
getLeaveTypeBadgeClass,
|
|
||||||
formatTimeOrDatetimePrint,
|
formatTimeOrDatetimePrint,
|
||||||
calculateWorkMinutesPrint,
|
calculateWorkMinutesPrint,
|
||||||
|
isWeekendDate,
|
||||||
|
getDaysInMonth,
|
||||||
|
shiftDateForMonth,
|
||||||
|
formatHoursDecimal,
|
||||||
|
calculateNightMinutes,
|
||||||
|
normalizeDateStr,
|
||||||
|
holidaysInMonth,
|
||||||
|
calculateFreeHolidayHours,
|
||||||
|
getCzechWeekday,
|
||||||
} from "../utils/attendanceHelpers";
|
} from "../utils/attendanceHelpers";
|
||||||
import type {
|
import type {
|
||||||
ShiftFormData,
|
ShiftFormData,
|
||||||
@@ -28,7 +38,7 @@ interface AlertContext {
|
|||||||
alert: { success: (msg: string) => void; error: (msg: string) => void };
|
alert: { success: (msg: string) => void; error: (msg: string) => void };
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AttendanceRecord {
|
export interface AttendanceRecord {
|
||||||
id: number;
|
id: number;
|
||||||
user_id: number;
|
user_id: number;
|
||||||
shift_date: string;
|
shift_date: string;
|
||||||
@@ -38,7 +48,7 @@ interface AttendanceRecord {
|
|||||||
departure_time?: string | null;
|
departure_time?: string | null;
|
||||||
break_start?: string | null;
|
break_start?: string | null;
|
||||||
break_end?: string | null;
|
break_end?: string | null;
|
||||||
notes?: string;
|
notes?: string | null;
|
||||||
project_id?: number | null;
|
project_id?: number | null;
|
||||||
project_name?: string;
|
project_name?: string;
|
||||||
project_logs?: Array<{
|
project_logs?: Array<{
|
||||||
@@ -72,7 +82,6 @@ interface UserTotal {
|
|||||||
working: boolean;
|
working: boolean;
|
||||||
vacation_hours: number;
|
vacation_hours: number;
|
||||||
sick_hours: number;
|
sick_hours: number;
|
||||||
holiday_hours: number;
|
|
||||||
unpaid_hours: number;
|
unpaid_hours: number;
|
||||||
overtime: number;
|
overtime: number;
|
||||||
missing: number;
|
missing: number;
|
||||||
@@ -80,6 +89,16 @@ interface UserTotal {
|
|||||||
business_days: number;
|
business_days: number;
|
||||||
worked_hours: number;
|
worked_hours: number;
|
||||||
covered: number;
|
covered: number;
|
||||||
|
// mzda-style summary fields (set by computeUserTotals)
|
||||||
|
worked_hours_raw?: number;
|
||||||
|
odpracovano?: number;
|
||||||
|
vcetne_svatku?: number;
|
||||||
|
prescas?: number;
|
||||||
|
svatek?: number;
|
||||||
|
weekend_hours?: number;
|
||||||
|
night_minutes?: number;
|
||||||
|
worked_holiday_hours?: number; // sum of hours worked ON a holiday
|
||||||
|
records?: AttendanceRecord[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface LeaveBalance {
|
interface LeaveBalance {
|
||||||
@@ -120,6 +139,11 @@ const combineDatetime = (date: string, time: string): string | null =>
|
|||||||
/**
|
/**
|
||||||
* Compute per-user totals from raw attendance records.
|
* Compute per-user totals from raw attendance records.
|
||||||
* This replaces the server-side `user_totals` that the PHP backend returned.
|
* This replaces the server-side `user_totals` that the PHP backend returned.
|
||||||
|
*
|
||||||
|
* Adds mzda-style summary fields (odpracovano, vcetne_svatku, prescas, svatek,
|
||||||
|
* weekend_hours, night_minutes) and a fund computed as
|
||||||
|
* (rawBizDays + holidayCount) × 8 — holidays count as work days for fund
|
||||||
|
* purposes, per the mzda.pdf model.
|
||||||
*/
|
*/
|
||||||
function computeUserTotals(
|
function computeUserTotals(
|
||||||
records: AttendanceRecord[],
|
records: AttendanceRecord[],
|
||||||
@@ -127,6 +151,7 @@ function computeUserTotals(
|
|||||||
month: string,
|
month: string,
|
||||||
): Record<string, UserTotal> {
|
): Record<string, UserTotal> {
|
||||||
const totals: Record<string, UserTotal> = {};
|
const totals: Record<string, UserTotal> = {};
|
||||||
|
const recordsByUser = new Map<number, AttendanceRecord[]>();
|
||||||
|
|
||||||
for (const rec of records) {
|
for (const rec of records) {
|
||||||
const uid = String(rec.user_id);
|
const uid = String(rec.user_id);
|
||||||
@@ -143,7 +168,6 @@ function computeUserTotals(
|
|||||||
working: false,
|
working: false,
|
||||||
vacation_hours: 0,
|
vacation_hours: 0,
|
||||||
sick_hours: 0,
|
sick_hours: 0,
|
||||||
holiday_hours: 0,
|
|
||||||
unpaid_hours: 0,
|
unpaid_hours: 0,
|
||||||
overtime: 0,
|
overtime: 0,
|
||||||
missing: 0,
|
missing: 0,
|
||||||
@@ -151,15 +175,23 @@ function computeUserTotals(
|
|||||||
business_days: 0,
|
business_days: 0,
|
||||||
worked_hours: 0,
|
worked_hours: 0,
|
||||||
covered: 0,
|
covered: 0,
|
||||||
|
records: [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const t = totals[uid];
|
const t = totals[uid];
|
||||||
|
t.records!.push(rec);
|
||||||
|
if (!recordsByUser.has(rec.user_id)) recordsByUser.set(rec.user_id, []);
|
||||||
|
recordsByUser.get(rec.user_id)!.push(rec);
|
||||||
|
|
||||||
const leaveType = rec.leave_type || "work";
|
const leaveType = rec.leave_type || "work";
|
||||||
|
|
||||||
if (leaveType === "work") {
|
if (leaveType === "work") {
|
||||||
// Only work records contribute to "minutes" (matching PHP calculateUserTotals)
|
// Only work records contribute to "minutes" (matching PHP calculateUserTotals)
|
||||||
t.minutes += calculateWorkMinutes(rec);
|
t.minutes += calculateWorkMinutes({
|
||||||
|
...rec,
|
||||||
|
notes: rec.notes ?? undefined,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
const leaveHours = Number(rec.leave_hours) || 8;
|
const leaveHours = Number(rec.leave_hours) || 8;
|
||||||
switch (leaveType) {
|
switch (leaveType) {
|
||||||
@@ -169,12 +201,14 @@ function computeUserTotals(
|
|||||||
case "sick":
|
case "sick":
|
||||||
t.sick_hours += leaveHours;
|
t.sick_hours += leaveHours;
|
||||||
break;
|
break;
|
||||||
case "holiday":
|
|
||||||
t.holiday_hours += leaveHours;
|
|
||||||
break;
|
|
||||||
case "unpaid":
|
case "unpaid":
|
||||||
t.unpaid_hours += leaveHours;
|
t.unpaid_hours += leaveHours;
|
||||||
break;
|
break;
|
||||||
|
// "holiday" leave_type is no longer selectable in the UI — it is
|
||||||
|
// auto-computed from Czech public holidays (see freeHolidayHours
|
||||||
|
// below). Old records may still exist in the DB; treat them as a
|
||||||
|
// paid non-work entry and skip so they don't double-count with
|
||||||
|
// the auto-detected svátek.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,7 +223,10 @@ function computeUserTotals(
|
|||||||
const yr = parseInt(yearStr, 10);
|
const yr = parseInt(yearStr, 10);
|
||||||
const mo = parseInt(monthStr, 10) - 1;
|
const mo = parseInt(monthStr, 10) - 1;
|
||||||
|
|
||||||
// Count business days in month (Mon-Fri)
|
// Count Mon-Fri business days in month (INCLUDING holidays).
|
||||||
|
// The fund is rawBizDays × 8 — holidays stay in the count so the
|
||||||
|
// user is paid for them via the fund. Svátek (free holiday hours) is
|
||||||
|
// computed separately as "8h per holiday the user did not work".
|
||||||
let rawBizDays = 0;
|
let rawBizDays = 0;
|
||||||
const cur = new Date(yr, mo, 1);
|
const cur = new Date(yr, mo, 1);
|
||||||
while (cur.getMonth() === mo) {
|
while (cur.getMonth() === mo) {
|
||||||
@@ -198,23 +235,100 @@ function computeUserTotals(
|
|||||||
cur.setDate(cur.getDate() + 1);
|
cur.setDate(cur.getDate() + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const holidayDates = holidaysInMonth(yr, mo + 1);
|
||||||
|
const holidayCount = holidayDates.length;
|
||||||
|
|
||||||
for (const uid of Object.keys(totals)) {
|
for (const uid of Object.keys(totals)) {
|
||||||
const t = totals[uid];
|
const t = totals[uid];
|
||||||
// Subtract holiday days from business days for this user
|
const userRecords = recordsByUser.get(Number(uid)) || [];
|
||||||
const holidayDays = Math.round(t.holiday_hours / 8);
|
|
||||||
const bizDays = Math.max(0, rawBizDays - holidayDays);
|
// Odpracováno: floor(worked / 8) × 8 — round to whole days, drop remainder.
|
||||||
const fund = bizDays * 8;
|
const workedHoursRaw = t.minutes / 60;
|
||||||
const workedHours = Math.round((t.minutes / 60) * 10) / 10;
|
const odpracovano = Math.floor(workedHoursRaw / 8) * 8;
|
||||||
// Covered = worked + vacation + sick (NOT holiday/unpaid — matching PHP)
|
|
||||||
const leaveHours = t.vacation_hours + t.sick_hours;
|
// So/Ne: sum of worked hours on Sat/Sun (raw, not rounded).
|
||||||
const covered = Math.round((workedHours + leaveHours) * 10) / 10;
|
const weekendHours = userRecords
|
||||||
|
.filter(
|
||||||
|
(r) =>
|
||||||
|
(r.leave_type || "work") === "work" && isWeekendDate(r.shift_date),
|
||||||
|
)
|
||||||
|
.reduce((sum, r) => sum + calculateWorkMinutesPrint(r) / 60, 0);
|
||||||
|
|
||||||
|
// Práce v noci: minutes in 22:00-06:00 across all work records.
|
||||||
|
const nightMinutes = userRecords
|
||||||
|
.filter((r) => (r.leave_type || "work") === "work")
|
||||||
|
.reduce((sum, r) => sum + calculateNightMinutes(r), 0);
|
||||||
|
|
||||||
|
// Svátek (free): 8h per holiday the user did not work.
|
||||||
|
const freeHolidayHours = calculateFreeHolidayHours(
|
||||||
|
userRecords,
|
||||||
|
holidayDates,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Worked holidays: holidays the user DID work (counted toward
|
||||||
|
// Odpracováno, but their 8h must not flow into Přesčas).
|
||||||
|
const workedDatesSet = new Set(
|
||||||
|
userRecords
|
||||||
|
.filter((r) => (r.leave_type || "work") === "work")
|
||||||
|
.map((r) => normalizeDateStr(r.shift_date))
|
||||||
|
.filter(Boolean),
|
||||||
|
);
|
||||||
|
let workedHolidayCount = 0;
|
||||||
|
let workedHolidayHours = 0;
|
||||||
|
for (const hd of holidayDates) {
|
||||||
|
if (workedDatesSet.has(hd)) workedHolidayCount++;
|
||||||
|
}
|
||||||
|
// Sum the actual hours worked on holiday dates (for the KPI card's
|
||||||
|
// "fond used" total = real_work + vacation + worked_holiday + free_holiday).
|
||||||
|
for (const r of userRecords) {
|
||||||
|
if ((r.leave_type || "work") !== "work") continue;
|
||||||
|
const d = normalizeDateStr(r.shift_date);
|
||||||
|
if (d && holidayDates.includes(d)) {
|
||||||
|
workedHolidayHours += calculateWorkMinutesPrint(r) / 60;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fund = Mon-Fri × 8h. Holidays count as work days (already in rawBizDays).
|
||||||
|
const fund = rawBizDays * 8;
|
||||||
|
|
||||||
|
// Včetně svátků a přesčasů (mzda formula):
|
||||||
|
// odpracovano + vacation + remainder − min(freeHols, workedHols × 8)
|
||||||
|
//
|
||||||
|
// Two-way logic matching the print:
|
||||||
|
// • If the user worked at least one holiday, that worked holiday's
|
||||||
|
// 8h is in Odpracováno and shouldn't also count as Přesčas. We
|
||||||
|
// subtract one 8h per worked holiday (capped at the total free
|
||||||
|
// holiday hours — can't go negative).
|
||||||
|
// • If the user did NOT work any holiday, no adjustment is needed:
|
||||||
|
// all unworked holidays are already paid via the Svátek line and
|
||||||
|
// don't flow into Přesčas, so vcetne_svatku just equals the
|
||||||
|
// work + vacation + remainder.
|
||||||
|
const remainder = workedHoursRaw - odpracovano;
|
||||||
|
const holidayAdj = Math.min(freeHolidayHours, workedHolidayCount * 8);
|
||||||
|
const vcetneSv = odpracovano - holidayAdj + t.vacation_hours + remainder;
|
||||||
|
|
||||||
|
// Přesčas = vcetneSv − odpracovano (derived).
|
||||||
|
const prescas = vcetneSv - odpracovano;
|
||||||
|
|
||||||
|
// Legacy fields (kept so existing UI doesn't break).
|
||||||
|
const workedHours = Math.round(workedHoursRaw * 10) / 10;
|
||||||
|
const covered = Math.round((workedHours + t.vacation_hours) * 10) / 10;
|
||||||
|
|
||||||
t.fund = fund;
|
t.fund = fund;
|
||||||
t.business_days = bizDays;
|
t.business_days = rawBizDays;
|
||||||
t.worked_hours = workedHours;
|
t.worked_hours = workedHours;
|
||||||
t.covered = covered;
|
t.covered = covered;
|
||||||
t.missing = Math.max(0, Math.round((fund - covered) * 10) / 10);
|
t.missing = Math.max(0, Math.round((fund - covered) * 10) / 10);
|
||||||
t.overtime = Math.max(0, Math.round((covered - fund) * 10) / 10);
|
t.overtime = Math.max(0, Math.round((covered - fund) * 10) / 10);
|
||||||
|
|
||||||
|
t.worked_hours_raw = workedHoursRaw;
|
||||||
|
t.odpracovano = odpracovano;
|
||||||
|
t.vcetne_svatku = vcetneSv;
|
||||||
|
t.prescas = prescas;
|
||||||
|
t.svatek = freeHolidayHours;
|
||||||
|
t.weekend_hours = weekendHours;
|
||||||
|
t.night_minutes = nightMinutes;
|
||||||
|
t.worked_holiday_hours = workedHolidayHours;
|
||||||
}
|
}
|
||||||
|
|
||||||
return totals;
|
return totals;
|
||||||
@@ -233,14 +347,6 @@ function escapeHtml(str: string): string {
|
|||||||
.replace(/'/g, "'");
|
.replace(/'/g, "'");
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderFundStatus(userData: Record<string, any>): string {
|
|
||||||
if (userData.overtime > 0)
|
|
||||||
return `<span class="leave-badge badge-overtime">+${escapeHtml(String(userData.overtime))}h přesčas</span>`;
|
|
||||||
if (userData.missing > 0)
|
|
||||||
return `<span style="color:#dc2626">−${escapeHtml(String(userData.missing))}h</span>`;
|
|
||||||
return '<span style="color:#16a34a">splněno</span>';
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildProjectLogsHtml(record: Record<string, any>): string {
|
function buildProjectLogsHtml(record: Record<string, any>): string {
|
||||||
if (record.project_logs && record.project_logs.length > 0) {
|
if (record.project_logs && record.project_logs.length > 0) {
|
||||||
return record.project_logs
|
return record.project_logs
|
||||||
@@ -271,94 +377,220 @@ function buildProjectLogsHtml(record: Record<string, any>): string {
|
|||||||
return escapeHtml(record.project_name || "—");
|
return escapeHtml(record.project_name || "—");
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildLeaveSummaryHtml(
|
|
||||||
userId: string,
|
|
||||||
userData: Record<string, any>,
|
|
||||||
printData: Record<string, any>,
|
|
||||||
): string {
|
|
||||||
const bal = printData.leave_balances[userId];
|
|
||||||
let parts = `<strong>Dovolená ${escapeHtml(String(printData.year))}:</strong> Zbývá ${bal.vacation_remaining.toFixed(1)}h z ${bal.vacation_total}h`;
|
|
||||||
if (userData.vacation_hours > 0)
|
|
||||||
parts += ` | <span class="leave-badge badge-vacation">Tento měsíc: ${escapeHtml(String(userData.vacation_hours))}h</span>`;
|
|
||||||
if (userData.sick_hours > 0)
|
|
||||||
parts += ` | <span class="leave-badge badge-sick">Nemoc: ${escapeHtml(String(userData.sick_hours))}h</span>`;
|
|
||||||
if (userData.holiday_hours > 0)
|
|
||||||
parts += ` | <span class="leave-badge badge-holiday">Svátek: ${escapeHtml(String(userData.holiday_hours))}h</span>`;
|
|
||||||
if (userData.overtime > 0)
|
|
||||||
parts += ` | <span class="leave-badge badge-overtime">Přesčas: +${escapeHtml(String(userData.overtime))}h</span>`;
|
|
||||||
return `<div class="leave-summary">${parts}</div>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildUserSectionHtml(
|
function buildUserSectionHtml(
|
||||||
userId: string,
|
userId: string,
|
||||||
userData: Record<string, any>,
|
userData: Record<string, any>,
|
||||||
printData: Record<string, any>,
|
printData: Record<string, any>,
|
||||||
): string {
|
): string {
|
||||||
const leaveHtml = printData.leave_balances[userId]
|
// Build a date-keyed lookup of the user's records.
|
||||||
? buildLeaveSummaryHtml(userId, userData, printData)
|
const recordsByDate = new Map<string, Record<string, any>>();
|
||||||
: "";
|
for (const r of userData.records || []) {
|
||||||
|
recordsByDate.set(normalizeDateStr(r.shift_date), r);
|
||||||
|
}
|
||||||
|
|
||||||
const recordRows = (userData.records || [])
|
// Iterate one row per day of the month.
|
||||||
.map((record: any) => {
|
const [yearStr, monthStr] = printData.month.split("-");
|
||||||
const leaveType = record.leave_type || "work";
|
const yr = parseInt(yearStr, 10);
|
||||||
const isLeave = leaveType !== "work";
|
const mo = parseInt(monthStr, 10);
|
||||||
const workMinutes = calculateWorkMinutesPrint(record);
|
const daysInMonth = getDaysInMonth(yr, mo);
|
||||||
const hours = Math.floor(workMinutes / 60);
|
|
||||||
const mins = workMinutes % 60;
|
|
||||||
const breakCell =
|
|
||||||
isLeave || !record.break_start || !record.break_end
|
|
||||||
? "—"
|
|
||||||
: `${escapeHtml(formatTimeOrDatetimePrint(record.break_start, record.shift_date))} - ${escapeHtml(formatTimeOrDatetimePrint(record.break_end, record.shift_date))}`;
|
|
||||||
|
|
||||||
return `<tr>
|
const userRecords = (userData.records || []) as Record<string, any>[];
|
||||||
<td>${escapeHtml(formatDate(record.shift_date))}</td>
|
|
||||||
<td><span class="leave-badge ${escapeHtml(getLeaveTypeBadgeClass(leaveType))}">${escapeHtml(getLeaveTypeName(leaveType))}</span></td>
|
const rows: string[] = [];
|
||||||
|
for (let d = 1; d <= daysInMonth; d++) {
|
||||||
|
const dateStr = shiftDateForMonth(yr, mo, d);
|
||||||
|
const record = recordsByDate.get(dateStr);
|
||||||
|
const weekend = isWeekendDate(dateStr);
|
||||||
|
const holiday = isHoliday(dateStr);
|
||||||
|
const leaveType = (record?.leave_type as string) || "work";
|
||||||
|
const rowClasses = [
|
||||||
|
weekend && "weekend",
|
||||||
|
holiday && "holiday",
|
||||||
|
leaveType === "vacation" && "vacation",
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ");
|
||||||
|
|
||||||
|
if (!record) {
|
||||||
|
rows.push(`<tr class="${rowClasses}">
|
||||||
|
<td>${escapeHtml(formatDate(dateStr))}</td>
|
||||||
|
<td>${escapeHtml(getCzechWeekday(dateStr))}</td>
|
||||||
|
<td>—</td>
|
||||||
|
<td class="text-center">—</td>
|
||||||
|
<td class="text-center">—</td>
|
||||||
|
<td class="text-center">—</td>
|
||||||
|
<td class="text-center">—</td>
|
||||||
|
<td></td>
|
||||||
|
<td></td>
|
||||||
|
</tr>`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isLeave = leaveType !== "work";
|
||||||
|
const workMinutes = calculateWorkMinutesPrint(record);
|
||||||
|
const hours = Math.floor(workMinutes / 60);
|
||||||
|
const mins = workMinutes % 60;
|
||||||
|
const breakCell =
|
||||||
|
isLeave || !record.break_start || !record.break_end
|
||||||
|
? "—"
|
||||||
|
: `${escapeHtml(formatTimeOrDatetimePrint(record.break_start, record.shift_date))} - ${escapeHtml(formatTimeOrDatetimePrint(record.break_end, record.shift_date))}`;
|
||||||
|
|
||||||
|
let hoursCell: string;
|
||||||
|
if (workMinutes > 0 && !isLeave) {
|
||||||
|
hoursCell = `${hours}:${String(mins).padStart(2, "0")} (${formatHoursDecimal(workMinutes)})`;
|
||||||
|
} else if (isLeave) {
|
||||||
|
hoursCell = formatHoursDecimal((Number(record.leave_hours) || 8) * 60);
|
||||||
|
} else {
|
||||||
|
hoursCell = "—";
|
||||||
|
}
|
||||||
|
|
||||||
|
rows.push(`<tr class="${rowClasses}">
|
||||||
|
<td>${escapeHtml(formatDate(dateStr))}</td>
|
||||||
|
<td>${escapeHtml(getCzechWeekday(dateStr))}</td>
|
||||||
|
<td>${escapeHtml(getLeaveTypeName(leaveType))}</td>
|
||||||
<td class="text-center">${isLeave ? "—" : escapeHtml(formatTimeOrDatetimePrint(record.arrival_time, record.shift_date))}</td>
|
<td class="text-center">${isLeave ? "—" : escapeHtml(formatTimeOrDatetimePrint(record.arrival_time, record.shift_date))}</td>
|
||||||
<td class="text-center">${breakCell}</td>
|
<td class="text-center">${breakCell}</td>
|
||||||
<td class="text-center">${isLeave ? "—" : escapeHtml(formatTimeOrDatetimePrint(record.departure_time, record.shift_date))}</td>
|
<td class="text-center">${isLeave ? "—" : escapeHtml(formatTimeOrDatetimePrint(record.departure_time, record.shift_date))}</td>
|
||||||
<td class="text-center">${workMinutes > 0 ? `${hours}:${String(mins).padStart(2, "0")}` : "—"}</td>
|
<td class="text-center">${hoursCell}</td>
|
||||||
<td style="font-size:8px">${buildProjectLogsHtml(record)}</td>
|
<td style="font-size:8px">${buildProjectLogsHtml(record)}</td>
|
||||||
<td>${escapeHtml(record.notes || "")}</td>
|
<td>${escapeHtml(record.notes || "")}</td>
|
||||||
</tr>`;
|
</tr>`);
|
||||||
})
|
}
|
||||||
.join("");
|
|
||||||
|
|
||||||
const fundRow =
|
// ----- mzda-style summary numbers (computed here, not from userData,
|
||||||
userData.fund !== null
|
// because the backend's getPrintData only returns the legacy fields). -----
|
||||||
? `<tr>
|
|
||||||
<td colspan="6" class="text-right">Fond měsíce:</td>
|
// Worked minutes: sum of calculateWorkMinutesPrint across work records.
|
||||||
<td class="text-center">${escapeHtml(String(userData.covered))}h / ${escapeHtml(String(userData.fund))}h</td>
|
let workedMinutes = 0;
|
||||||
<td colspan="2">${renderFundStatus(userData)}</td>
|
let weekendHoursRaw = 0;
|
||||||
</tr>`
|
let nightMinutes = 0;
|
||||||
: "";
|
for (const r of userRecords) {
|
||||||
|
const leaveType = r.leave_type || "work";
|
||||||
|
if (leaveType !== "work") continue;
|
||||||
|
const m = calculateWorkMinutesPrint(r);
|
||||||
|
workedMinutes += m;
|
||||||
|
if (isWeekendDate(r.shift_date)) {
|
||||||
|
weekendHoursRaw += m / 60;
|
||||||
|
}
|
||||||
|
nightMinutes += calculateNightMinutes(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sum of vacation/sick/unpaid hours (in hours, not minutes). The
|
||||||
|
// "holiday" leave_type is auto-computed from Czech holidays further down
|
||||||
|
// and no longer selectable in the UI, so it's deliberately omitted here.
|
||||||
|
let vacationHours = 0,
|
||||||
|
sickHours = 0;
|
||||||
|
for (const r of userRecords) {
|
||||||
|
const lt = r.leave_type || "work";
|
||||||
|
if (lt === "work") continue;
|
||||||
|
const h = Number(r.leave_hours) || 8;
|
||||||
|
if (lt === "vacation") vacationHours += h;
|
||||||
|
else if (lt === "sick") sickHours += h;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Odpracováno: floor(worked / 8) × 8.
|
||||||
|
const workedHoursRaw = workedMinutes / 60;
|
||||||
|
const odpracovano = Math.floor(workedHoursRaw / 8) * 8;
|
||||||
|
|
||||||
|
// Free Svátek: 8h per holiday date the user did not work.
|
||||||
|
const holidayDates = holidaysInMonth(yr, mo);
|
||||||
|
const holidayCount = holidayDates.length;
|
||||||
|
const workedDates = new Set(
|
||||||
|
userRecords
|
||||||
|
.filter((r) => (r.leave_type || "work") === "work")
|
||||||
|
.map((r) => normalizeDateStr(r.shift_date))
|
||||||
|
.filter(Boolean),
|
||||||
|
);
|
||||||
|
let freeHolidayHours = 0;
|
||||||
|
let workedHolidayCount = 0;
|
||||||
|
for (const hd of holidayDates) {
|
||||||
|
if (workedDates.has(hd)) workedHolidayCount++;
|
||||||
|
else freeHolidayHours += 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fund: count Mon-Fri (incl. holidays) × 8h.
|
||||||
|
let rawBizDays = 0;
|
||||||
|
const cur = new Date(yr, mo - 1, 1);
|
||||||
|
while (cur.getMonth() === mo - 1) {
|
||||||
|
const dow = cur.getDay();
|
||||||
|
if (dow !== 0 && dow !== 6) rawBizDays++;
|
||||||
|
cur.setDate(cur.getDate() + 1);
|
||||||
|
}
|
||||||
|
const businessDays = rawBizDays;
|
||||||
|
const fund = businessDays * 8;
|
||||||
|
|
||||||
|
// Včetně svátků a přesčasů: floor(worked/8)*8 − worked_holiday*8 + vacation + remainder.
|
||||||
|
// (A worked holiday counts toward Odpracováno, but its 8h should not flow
|
||||||
|
// into Přesčas — so we subtract it here. Unworked holidays are paid via
|
||||||
|
// the fund and don't affect this line.)
|
||||||
|
const remainder = workedHoursRaw - odpracovano;
|
||||||
|
const vcetneSv =
|
||||||
|
odpracovano - workedHolidayCount * 8 + vacationHours + remainder;
|
||||||
|
|
||||||
|
// Přesčas = #2 - #1.
|
||||||
|
const prescas = vcetneSv - odpracovano;
|
||||||
|
|
||||||
|
const summaryHtml = `<div class="user-summary">
|
||||||
|
<div class="summary-row">
|
||||||
|
<span class="summary-label">Odpracováno:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(odpracovano * 60)}h</span>
|
||||||
|
</div>
|
||||||
|
<div class="summary-row">
|
||||||
|
<span class="summary-label">Odpracováno včetně svátků a přesčasů:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(vcetneSv * 60)}h</span>
|
||||||
|
</div>
|
||||||
|
<div class="summary-row">
|
||||||
|
<span class="summary-label">Dovolená:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(vacationHours * 60)}h</span>
|
||||||
|
</div>
|
||||||
|
<div class="summary-row">
|
||||||
|
<span class="summary-label">Přesčas:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(prescas * 60)}h</span>
|
||||||
|
</div>
|
||||||
|
<div class="summary-row">
|
||||||
|
<span class="summary-label">Svátek:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(freeHolidayHours * 60)}h</span>
|
||||||
|
</div>
|
||||||
|
<div class="summary-row">
|
||||||
|
<span class="summary-label">So/Ne:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(weekendHoursRaw * 60)}h</span>
|
||||||
|
</div>
|
||||||
|
<div class="summary-row">
|
||||||
|
<span class="summary-label">Práce v noci:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(nightMinutes)}h</span>
|
||||||
|
</div>
|
||||||
|
<div class="summary-row summary-fund">
|
||||||
|
<span class="summary-label">Fond měsíce:</span>
|
||||||
|
<span class="summary-value">${formatHoursDecimal(fund * 60)}h (${businessDays} dnů)</span>
|
||||||
|
</div>
|
||||||
|
<div class="legend">
|
||||||
|
<span class="legend-item"><span class="legend-swatch weekend"></span>Víkend (So/Ne)</span>
|
||||||
|
<span class="legend-item"><span class="legend-swatch holiday"></span>Svátek</span>
|
||||||
|
<span class="legend-item"><span class="legend-swatch weekend-holiday"></span>Víkend + svátek</span>
|
||||||
|
<span class="legend-item"><span class="legend-swatch vacation"></span>Dovolená</span>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
return `<div class="user-section">
|
return `<div class="user-section">
|
||||||
<div class="user-header">
|
<div class="user-header">
|
||||||
<h3>${escapeHtml(userData.name)}</h3>
|
<h3>${escapeHtml(userData.name)}</h3>
|
||||||
<span class="total">Odpracováno: ${escapeHtml(formatMinutes(userData.minutes))} h</span>
|
<span class="total">Odpracováno: ${escapeHtml(formatMinutes(userData.minutes))} h</span>
|
||||||
</div>
|
</div>
|
||||||
${leaveHtml}
|
|
||||||
<table>
|
<table>
|
||||||
<thead><tr>
|
<thead><tr>
|
||||||
<th style="width:70px">Datum</th>
|
<th style="width:55px">Datum</th>
|
||||||
<th style="width:70px">Typ</th>
|
<th style="width:55px">Den</th>
|
||||||
<th class="text-center" style="width:70px">Příchod</th>
|
<th style="width:60px">Typ</th>
|
||||||
<th class="text-center" style="width:90px">Pauza</th>
|
<th class="text-center" style="width:55px">Příchod</th>
|
||||||
<th class="text-center" style="width:70px">Odchod</th>
|
<th class="text-center" style="width:80px">Pauza</th>
|
||||||
<th class="text-center" style="width:80px">Hodiny</th>
|
<th class="text-center" style="width:55px">Odchod</th>
|
||||||
|
<th class="text-center" style="width:85px">Hodiny</th>
|
||||||
<th>Projekty</th>
|
<th>Projekty</th>
|
||||||
<th>Poznámka</th>
|
<th>Poznámka</th>
|
||||||
</tr></thead>
|
</tr></thead>
|
||||||
<tbody>${recordRows}</tbody>
|
<tbody>${rows.join("")}</tbody>
|
||||||
<tfoot>
|
|
||||||
<tr>
|
|
||||||
<td colspan="6" class="text-right">Odpracováno:</td>
|
|
||||||
<td class="text-center">${escapeHtml(formatMinutes(userData.minutes))} h</td>
|
|
||||||
<td colspan="2"></td>
|
|
||||||
</tr>
|
|
||||||
${fundRow}
|
|
||||||
</tfoot>
|
|
||||||
</table>
|
</table>
|
||||||
|
${summaryHtml}
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -376,7 +608,13 @@ function buildPrintHtml(
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Docházka - ${escapeHtml(pData.month_name)}</title>
|
<title>Docházka - ${escapeHtml(pData.month_name)}</title>
|
||||||
<style>
|
<style>
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
-webkit-print-color-adjust: exact;
|
||||||
|
print-color-adjust: exact;
|
||||||
|
}
|
||||||
body {
|
body {
|
||||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||||
font-size: 11px; line-height: 1.4; color: #000; background: #fff; padding: 15mm;
|
font-size: 11px; line-height: 1.4; color: #000; background: #fff; padding: 15mm;
|
||||||
@@ -406,19 +644,47 @@ function buildPrintHtml(
|
|||||||
.user-section th { background: #333; color: #fff; font-weight: 600; font-size: 10px; text-transform: uppercase; }
|
.user-section th { background: #333; color: #fff; font-weight: 600; font-size: 10px; text-transform: uppercase; }
|
||||||
.user-section td { font-size: 10px; }
|
.user-section td { font-size: 10px; }
|
||||||
.user-section tr:nth-child(even) { background: #f9f9f9; }
|
.user-section tr:nth-child(even) { background: #f9f9f9; }
|
||||||
|
/* Weekend and holiday row highlighting — must come after the
|
||||||
|
:nth-child(even) rule and use higher specificity (tr.X td) to win. */
|
||||||
|
.user-section tr.weekend td { background: #fde68a; }
|
||||||
|
.user-section tr.holiday td { background: #bbf7d0; }
|
||||||
|
.user-section tr.weekend.holiday td { background: #fcd34d; }
|
||||||
|
.user-section tr.vacation td { background: #bfdbfe; }
|
||||||
.text-center { text-align: center; }
|
.text-center { text-align: center; }
|
||||||
.text-right { text-align: right; }
|
.text-right { text-align: right; }
|
||||||
.user-section tfoot td { background: #eee; font-weight: 600; }
|
|
||||||
.leave-badge { display: inline-block; padding: 2px 6px; border-radius: 3px; font-size: 9px; font-weight: 500; }
|
.leave-badge { display: inline-block; padding: 2px 6px; border-radius: 3px; font-size: 9px; font-weight: 500; }
|
||||||
.badge-vacation { background: #dbeafe; color: #1d4ed8; }
|
.badge-vacation { background: #dbeafe; color: #1d4ed8; }
|
||||||
.badge-sick { background: #fee2e2; color: #dc2626; }
|
.badge-sick { background: #fee2e2; color: #dc2626; }
|
||||||
.badge-holiday { background: #dcfce7; color: #16a34a; }
|
.badge-holiday { background: #dcfce7; color: #16a34a; }
|
||||||
.badge-unpaid { background: #f3f4f6; color: #6b7280; }
|
.badge-unpaid { background: #f3f4f6; color: #6b7280; }
|
||||||
.badge-overtime { background: #fef3c7; color: #d97706; }
|
.badge-overtime { background: #fef3c7; color: #d97706; }
|
||||||
.leave-summary {
|
.user-summary {
|
||||||
margin-top: 10px; padding: 8px 15px; background: #f9f9f9;
|
margin-top: 10px; padding: 10px 15px;
|
||||||
border: 1px solid #ddd; font-size: 10px;
|
background: #f9f9f9; border: 1px solid #ddd; font-size: 10px;
|
||||||
}
|
}
|
||||||
|
.user-summary .summary-row {
|
||||||
|
display: flex; justify-content: space-between; padding: 2px 0;
|
||||||
|
}
|
||||||
|
.user-summary .summary-label { color: #555; }
|
||||||
|
.user-summary .summary-value { font-weight: 600; }
|
||||||
|
.user-summary .summary-fund {
|
||||||
|
border-top: 1px solid #ddd; margin-top: 4px; padding-top: 6px;
|
||||||
|
}
|
||||||
|
.legend {
|
||||||
|
display: flex; flex-wrap: wrap; gap: 14px;
|
||||||
|
margin-top: 8px; padding-top: 6px;
|
||||||
|
border-top: 1px dashed #ddd;
|
||||||
|
font-size: 9px; color: #555;
|
||||||
|
}
|
||||||
|
.legend-item { display: inline-flex; align-items: center; gap: 5px; }
|
||||||
|
.legend-swatch {
|
||||||
|
display: inline-block; width: 12px; height: 12px;
|
||||||
|
border: 1px solid #333; vertical-align: middle;
|
||||||
|
}
|
||||||
|
.legend-swatch.weekend { background: #fde68a; }
|
||||||
|
.legend-swatch.holiday { background: #bbf7d0; }
|
||||||
|
.legend-swatch.weekend-holiday { background: #fcd34d; }
|
||||||
|
.legend-swatch.vacation { background: #bfdbfe; }
|
||||||
.print-wrapper-table { width: 100%; border-collapse: collapse; border: none; }
|
.print-wrapper-table { width: 100%; border-collapse: collapse; border: none; }
|
||||||
.print-wrapper-table > thead > tr > td,
|
.print-wrapper-table > thead > tr > td,
|
||||||
.print-wrapper-table > tbody > tr > td { padding: 0; border: none; background: none; }
|
.print-wrapper-table > tbody > tr > td { padding: 0; border: none; background: none; }
|
||||||
@@ -461,6 +727,7 @@ function buildPrintHtml(
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export default function useAttendanceAdmin({ alert }: AlertContext) {
|
export default function useAttendanceAdmin({ alert }: AlertContext) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
// ---- Core state ----
|
// ---- Core state ----
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [month, setMonth] = useState(() => {
|
const [month, setMonth] = useState(() => {
|
||||||
@@ -662,7 +929,15 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
|||||||
formData: ShiftFormData,
|
formData: ShiftFormData,
|
||||||
): boolean => {
|
): boolean => {
|
||||||
const totalWork = calcFormWorkMinutes(formData);
|
const totalWork = calcFormWorkMinutes(formData);
|
||||||
const totalProject = calcProjectMinutesTotal(logs);
|
const totalProject = calcProjectMinutesTotal(
|
||||||
|
logs.map((l) => ({
|
||||||
|
...l,
|
||||||
|
project_id:
|
||||||
|
l.project_id !== "" && l.project_id != null
|
||||||
|
? Number(l.project_id)
|
||||||
|
: undefined,
|
||||||
|
})),
|
||||||
|
);
|
||||||
if (totalWork > 0 && totalProject !== totalWork) {
|
if (totalWork > 0 && totalProject !== totalWork) {
|
||||||
const wH = Math.floor(totalWork / 60);
|
const wH = Math.floor(totalWork / 60);
|
||||||
const wM = totalWork % 60;
|
const wM = totalWork % 60;
|
||||||
@@ -771,6 +1046,7 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
|||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
setShowCreateModal(false);
|
setShowCreateModal(false);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["attendance"] });
|
||||||
await fetchData(false);
|
await fetchData(false);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||||
alert.success(
|
alert.success(
|
||||||
@@ -842,6 +1118,7 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
|||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
setShowBulkModal(false);
|
setShowBulkModal(false);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["attendance"] });
|
||||||
await fetchData(false);
|
await fetchData(false);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||||
alert.success(
|
alert.success(
|
||||||
@@ -865,7 +1142,7 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
|||||||
const userName = record.users
|
const userName = record.users
|
||||||
? `${record.users.first_name} ${record.users.last_name}`.trim() ||
|
? `${record.users.first_name} ${record.users.last_name}`.trim() ||
|
||||||
record.users.username
|
record.users.username
|
||||||
: ((record as Record<string, unknown>).user_name as string) ||
|
: ((record as unknown as Record<string, unknown>).user_name as string) ||
|
||||||
`User #${record.user_id}`;
|
`User #${record.user_id}`;
|
||||||
const enriched = { ...record, user_name: userName };
|
const enriched = { ...record, user_name: userName };
|
||||||
setEditingRecord(enriched);
|
setEditingRecord(enriched);
|
||||||
@@ -976,6 +1253,7 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
|||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
setShowEditModal(false);
|
setShowEditModal(false);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["attendance"] });
|
||||||
await fetchData(false);
|
await fetchData(false);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||||
alert.success(
|
alert.success(
|
||||||
@@ -1005,6 +1283,7 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
|
|||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
setDeleteConfirm({ show: false, record: null });
|
setDeleteConfirm({ show: false, record: null });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["attendance"] });
|
||||||
await fetchData(false);
|
await fetchData(false);
|
||||||
alert.success(
|
alert.success(
|
||||||
result.message || result.data?.message || "Záznam smazán",
|
result.message || result.data?.message || "Záznam smazán",
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from "react";
|
|
||||||
import { useAlert } from "../context/AlertContext";
|
|
||||||
import apiFetch from "../utils/api";
|
|
||||||
import useDebounce from "./useDebounce";
|
|
||||||
|
|
||||||
const API_BASE = "/api/admin";
|
|
||||||
|
|
||||||
interface PaginationData {
|
|
||||||
total: number;
|
|
||||||
page: number;
|
|
||||||
per_page: number;
|
|
||||||
total_pages: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UseListDataOptions {
|
|
||||||
dataKey?: string;
|
|
||||||
search?: string;
|
|
||||||
sort?: string;
|
|
||||||
order?: string;
|
|
||||||
page?: number;
|
|
||||||
perPage?: number;
|
|
||||||
extraParams?: Record<string, string>;
|
|
||||||
errorMsg?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function useListData<T = unknown>(
|
|
||||||
endpoint: string,
|
|
||||||
options: UseListDataOptions = {},
|
|
||||||
) {
|
|
||||||
const {
|
|
||||||
dataKey,
|
|
||||||
search = "",
|
|
||||||
sort,
|
|
||||||
order,
|
|
||||||
page = 1,
|
|
||||||
perPage = 25,
|
|
||||||
extraParams = {},
|
|
||||||
errorMsg = "Nepodařilo se načíst data",
|
|
||||||
} = options;
|
|
||||||
const alert = useAlert();
|
|
||||||
const [items, setItems] = useState<T[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [initialLoad, setInitialLoad] = useState(true);
|
|
||||||
const [pagination, setPagination] = useState<PaginationData | null>(null);
|
|
||||||
const abortRef = useRef<AbortController | null>(null);
|
|
||||||
const mountedRef = useRef(true);
|
|
||||||
const debouncedSearch = useDebounce(search, 300);
|
|
||||||
|
|
||||||
const extraParamsKey = Object.entries(extraParams)
|
|
||||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
|
||||||
.map(([k, v]) => `${k}=${v}`)
|
|
||||||
.join("&");
|
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
|
||||||
if (abortRef.current) abortRef.current.abort();
|
|
||||||
const controller = new AbortController();
|
|
||||||
abortRef.current = controller;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
page: String(page),
|
|
||||||
per_page: String(perPage),
|
|
||||||
});
|
|
||||||
if (debouncedSearch) params.set("search", debouncedSearch);
|
|
||||||
if (sort) params.set("sort", sort);
|
|
||||||
if (order) params.set("order", order);
|
|
||||||
Object.entries(extraParams).forEach(([k, v]) => {
|
|
||||||
if (v) params.set(k, v);
|
|
||||||
});
|
|
||||||
|
|
||||||
const url = endpoint.startsWith("/")
|
|
||||||
? `${endpoint}?${params}`
|
|
||||||
: `${API_BASE}/${endpoint}?${params}`;
|
|
||||||
const response = await apiFetch(url, { signal: controller.signal });
|
|
||||||
if (response.status === 401) {
|
|
||||||
window.location.href = "/login";
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
const data = dataKey
|
|
||||||
? result.data[dataKey]
|
|
||||||
: Array.isArray(result.data)
|
|
||||||
? result.data
|
|
||||||
: result.data?.items || [];
|
|
||||||
setItems(data || []);
|
|
||||||
const pag =
|
|
||||||
result.pagination ||
|
|
||||||
(!Array.isArray(result.data) && result.data?.pagination) ||
|
|
||||||
null;
|
|
||||||
setPagination(
|
|
||||||
pag || {
|
|
||||||
total: data?.length ?? 0,
|
|
||||||
page,
|
|
||||||
per_page: perPage,
|
|
||||||
total_pages: 1,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
alert.error(result.error || errorMsg);
|
|
||||||
}
|
|
||||||
} catch (err: unknown) {
|
|
||||||
if (err instanceof Error && err.name === "AbortError") return;
|
|
||||||
if (!mountedRef.current) return;
|
|
||||||
alert.error(errorMsg);
|
|
||||||
} finally {
|
|
||||||
if (!mountedRef.current) return;
|
|
||||||
setLoading(false);
|
|
||||||
setInitialLoad(false);
|
|
||||||
}
|
|
||||||
}, [
|
|
||||||
endpoint,
|
|
||||||
debouncedSearch,
|
|
||||||
sort,
|
|
||||||
order,
|
|
||||||
page,
|
|
||||||
perPage,
|
|
||||||
dataKey,
|
|
||||||
extraParamsKey,
|
|
||||||
]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
mountedRef.current = true;
|
|
||||||
fetchData();
|
|
||||||
return () => {
|
|
||||||
mountedRef.current = false;
|
|
||||||
if (abortRef.current) abortRef.current.abort();
|
|
||||||
};
|
|
||||||
}, [fetchData]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
items,
|
|
||||||
setItems,
|
|
||||||
loading,
|
|
||||||
initialLoad,
|
|
||||||
pagination,
|
|
||||||
refetch: fetchData,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
44
src/admin/hooks/usePaginatedQuery.ts
Normal file
44
src/admin/hooks/usePaginatedQuery.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import {
|
||||||
|
useQuery,
|
||||||
|
keepPreviousData,
|
||||||
|
useQueryClient,
|
||||||
|
} from "@tanstack/react-query";
|
||||||
|
import type { UseQueryOptions } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
interface PaginatedResult<T> {
|
||||||
|
data: T[];
|
||||||
|
pagination: {
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
per_page: number;
|
||||||
|
total_pages: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrapper around useQuery for paginated list endpoints.
|
||||||
|
* Accepts the return value of queryOptions() from lib/queries/*
|
||||||
|
* and extracts items + pagination from the response.
|
||||||
|
*/
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
export function usePaginatedQuery<T>(options: any) {
|
||||||
|
const query = useQuery({
|
||||||
|
...options,
|
||||||
|
placeholderData: keepPreviousData,
|
||||||
|
} as UseQueryOptions<PaginatedResult<T>>);
|
||||||
|
|
||||||
|
const data = query.data as PaginatedResult<T> | undefined;
|
||||||
|
|
||||||
|
return {
|
||||||
|
items: (data?.data ?? []) as T[],
|
||||||
|
pagination: data?.pagination ?? null,
|
||||||
|
isPending: query.isPending,
|
||||||
|
isFetching: query.isFetching,
|
||||||
|
isPlaceholderData: query.isPlaceholderData,
|
||||||
|
isError: query.isError,
|
||||||
|
error: query.error,
|
||||||
|
refetch: query.refetch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { useQueryClient, useQuery, keepPreviousData };
|
||||||
527
src/admin/hooks/usePlanWork.ts
Normal file
527
src/admin/hooks/usePlanWork.ts
Normal file
@@ -0,0 +1,527 @@
|
|||||||
|
import { useState, useCallback, useMemo } from "react";
|
||||||
|
import {
|
||||||
|
useQuery,
|
||||||
|
useQueryClient,
|
||||||
|
useMutation,
|
||||||
|
keepPreviousData,
|
||||||
|
} from "@tanstack/react-query";
|
||||||
|
import apiFetch from "../utils/api";
|
||||||
|
import { planKeys, GridData, ResolvedCell } from "../lib/queries/plan";
|
||||||
|
|
||||||
|
export type ViewMode = "week" | "month";
|
||||||
|
export type ModalMode =
|
||||||
|
| { kind: "closed" }
|
||||||
|
| { kind: "create"; userId: number; date: string }
|
||||||
|
| { kind: "edit-range"; entryId: number; userId: number; date: string }
|
||||||
|
| { kind: "edit-override"; overrideId: number; userId: number; date: string }
|
||||||
|
| { kind: "day-in-range"; userId: number; date: string; entryId: number }
|
||||||
|
| { kind: "view"; userId: number; date: string };
|
||||||
|
|
||||||
|
function isoDate(d: Date): string {
|
||||||
|
return d.toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startOfWeek(d: Date): Date {
|
||||||
|
const day = d.getUTCDay(); // 0 = Sun
|
||||||
|
const diff = day === 0 ? -6 : 1 - day; // Monday-start
|
||||||
|
const r = new Date(d);
|
||||||
|
r.setUTCDate(d.getUTCDate() + diff);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addDays(d: Date, n: number): Date {
|
||||||
|
const r = new Date(d);
|
||||||
|
r.setUTCDate(d.getUTCDate() + n);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apiCall(
|
||||||
|
url: string,
|
||||||
|
options: RequestInit = {},
|
||||||
|
): Promise<unknown> {
|
||||||
|
const res = await apiFetch(url, options);
|
||||||
|
if (!res.ok) {
|
||||||
|
let message = "Chyba serveru";
|
||||||
|
try {
|
||||||
|
const body = await res.json();
|
||||||
|
if (body && typeof body.error === "string") message = body.error;
|
||||||
|
} catch {
|
||||||
|
// body wasn't JSON; use default
|
||||||
|
}
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await res.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UsePlanWorkArgs {
|
||||||
|
initialDate?: Date;
|
||||||
|
canEdit: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePlanWork({ initialDate, canEdit }: UsePlanWorkArgs) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [view, setView] = useState<ViewMode>("week");
|
||||||
|
const [anchor, setAnchor] = useState<Date>(initialDate ?? new Date());
|
||||||
|
const [filterActive, setFilterActive] = useState(true);
|
||||||
|
const [modal, setModal] = useState<ModalMode>({ kind: "closed" });
|
||||||
|
|
||||||
|
const range = useMemo(() => {
|
||||||
|
if (view === "week") {
|
||||||
|
const from = startOfWeek(anchor);
|
||||||
|
const to = addDays(from, 6);
|
||||||
|
return { from, to };
|
||||||
|
}
|
||||||
|
const from = new Date(
|
||||||
|
Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth(), 1),
|
||||||
|
);
|
||||||
|
const to = new Date(
|
||||||
|
Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth() + 1, 0),
|
||||||
|
);
|
||||||
|
return { from, to };
|
||||||
|
}, [view, anchor]);
|
||||||
|
|
||||||
|
const gridQuery = useQuery({
|
||||||
|
queryKey: planKeys.grid(isoDate(range.from), isoDate(range.to), view),
|
||||||
|
queryFn: () =>
|
||||||
|
apiFetch(
|
||||||
|
`/api/admin/plan/grid?date_from=${isoDate(range.from)}&date_to=${isoDate(range.to)}&view=${view}`,
|
||||||
|
).then((r) => r.json().then((b: any) => b.data as GridData)),
|
||||||
|
// keepPreviousData holds the old range's data visible while the new
|
||||||
|
// range's fetch is in flight. Without this, `gridQuery.data` is
|
||||||
|
// immediately undefined on key change and the grid flashes empty.
|
||||||
|
// `isPlaceholderData` is true while the displayed data is stale.
|
||||||
|
placeholderData: keepPreviousData,
|
||||||
|
});
|
||||||
|
|
||||||
|
const invalidate = useCallback(() => {
|
||||||
|
qc.invalidateQueries({ queryKey: planKeys.all });
|
||||||
|
// Plan mutations write audit-log rows, so they touch the audit domain
|
||||||
|
// too. Invalidate the dashboard activity feed and the audit-log page so
|
||||||
|
// they reflect the change without a manual F5 (prefix-matches all
|
||||||
|
// ["audit-log", {...}] filter variants). The dashboard query is active
|
||||||
|
// when visible and refetches immediately despite its staleTime.
|
||||||
|
qc.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["audit-log"] });
|
||||||
|
}, [qc]);
|
||||||
|
|
||||||
|
// --- Optimistic cache patches ---------------------------------------------
|
||||||
|
// After a mutation succeeds, we patch the visible grid query's data
|
||||||
|
// *before* the refetch resolves. This is what stops the full-grid
|
||||||
|
// re-animation: the visible data updates in place (and the new cell
|
||||||
|
// gets a one-shot pulse via PlanWork's lastMutated state), so the grid
|
||||||
|
// never unmounts. The subsequent invalidate+refetch confirms the patch
|
||||||
|
// from the server (which is the source of truth) and is a no-op if the
|
||||||
|
// server's data matches our patch.
|
||||||
|
//
|
||||||
|
// If the mutation fails, the mutation's onError handler in PlanWork
|
||||||
|
// rolls the cache back to the snapshot we took before the patch.
|
||||||
|
|
||||||
|
const currentGridKey = planKeys.grid(
|
||||||
|
isoDate(range.from),
|
||||||
|
isoDate(range.to),
|
||||||
|
view,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Walk the days in [from, to] inclusive (YYYY-MM-DD strings). Used to
|
||||||
|
// figure out which cell keys to patch for a range entry.
|
||||||
|
function eachDay(from: string, to: string): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
const a = new Date(from + "T00:00:00.000Z");
|
||||||
|
const b = new Date(to + "T00:00:00.000Z");
|
||||||
|
for (let d = new Date(a); d <= b; d.setUTCDate(d.getUTCDate() + 1)) {
|
||||||
|
out.push(d.toISOString().slice(0, 10));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot the currently-cached grid for a given key. Returns
|
||||||
|
// `undefined` if there's nothing cached (we don't patch empty data).
|
||||||
|
function snapshotGrid(key: readonly unknown[]): GridData | undefined {
|
||||||
|
return qc.getQueryData<GridData>(key as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply a per-date cell patch to the cached grid at `key`. Returns the
|
||||||
|
// previous cells[userId] map so the caller can roll back on error.
|
||||||
|
function patchCells(
|
||||||
|
key: readonly unknown[],
|
||||||
|
userId: number,
|
||||||
|
dates: string[],
|
||||||
|
mutator: (prev: ResolvedCell | null) => ResolvedCell | null,
|
||||||
|
): Record<string, ResolvedCell | null> | null {
|
||||||
|
const prev = snapshotGrid(key);
|
||||||
|
if (!prev) return null;
|
||||||
|
const userPrev = prev.cells[userId] ?? {};
|
||||||
|
const rolled: Record<string, ResolvedCell | null> = {};
|
||||||
|
const userNext: Record<string, ResolvedCell | null> = { ...userPrev };
|
||||||
|
for (const date of dates) {
|
||||||
|
rolled[date] = userPrev[date] ?? null;
|
||||||
|
userNext[date] = mutator(rolled[date]);
|
||||||
|
}
|
||||||
|
qc.setQueryData(key, {
|
||||||
|
...prev,
|
||||||
|
cells: { ...prev.cells, [userId]: userNext },
|
||||||
|
});
|
||||||
|
return rolled;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build a ResolvedCell for a freshly-created entry. The server returns
|
||||||
|
// a row with the same fields, so we mirror that shape. We don't have
|
||||||
|
// entryId/overrideId from the request body — but the createEntry
|
||||||
|
// response *does* include id; we could plumb it through. For now we
|
||||||
|
// leave entryId as a placeholder that the refetch will replace.
|
||||||
|
// (PlanGrid only uses source/entryId/overrideId to decide edit flow;
|
||||||
|
// a fresh cell from an entry is "entry" source — the refetch fills
|
||||||
|
// the actual id within ~200ms.)
|
||||||
|
function makeEntryCell(args: {
|
||||||
|
userId: number;
|
||||||
|
date: string;
|
||||||
|
projectId: number | null;
|
||||||
|
category: string;
|
||||||
|
note: string;
|
||||||
|
rangeFrom: string;
|
||||||
|
rangeTo: string;
|
||||||
|
entryId: number | null;
|
||||||
|
}): ResolvedCell {
|
||||||
|
return {
|
||||||
|
source: "entry",
|
||||||
|
entryId: args.entryId,
|
||||||
|
overrideId: null,
|
||||||
|
user_id: args.userId,
|
||||||
|
shift_date: args.date,
|
||||||
|
project_id: args.projectId,
|
||||||
|
// Optimistic placeholder — the invalidate+refetch fills the real
|
||||||
|
// project label (resolveGrid embeds it) within ~200ms.
|
||||||
|
project_number: null,
|
||||||
|
project_name: null,
|
||||||
|
category: args.category,
|
||||||
|
note: args.note,
|
||||||
|
rangeFrom: args.rangeFrom,
|
||||||
|
rangeTo: args.rangeTo,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeOverrideCell(args: {
|
||||||
|
userId: number;
|
||||||
|
date: string;
|
||||||
|
projectId: number | null;
|
||||||
|
category: string;
|
||||||
|
note: string;
|
||||||
|
overrideId: number | null;
|
||||||
|
}): ResolvedCell {
|
||||||
|
return {
|
||||||
|
source: "override",
|
||||||
|
entryId: null,
|
||||||
|
overrideId: args.overrideId,
|
||||||
|
user_id: args.userId,
|
||||||
|
shift_date: args.date,
|
||||||
|
project_id: args.projectId,
|
||||||
|
// Optimistic placeholder — refetch fills the real project label.
|
||||||
|
project_number: null,
|
||||||
|
project_name: null,
|
||||||
|
category: args.category,
|
||||||
|
note: args.note,
|
||||||
|
rangeFrom: null,
|
||||||
|
rangeTo: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Mutations ---
|
||||||
|
|
||||||
|
const createEntry = useMutation({
|
||||||
|
mutationFn: (body: any) =>
|
||||||
|
apiCall("/api/admin/plan/entries", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}),
|
||||||
|
onSuccess: (data: any, body: any) => {
|
||||||
|
// Patch the visible grid with the new entry. We use the response
|
||||||
|
// id (server-assigned) for the new entry's entryId; the rest of
|
||||||
|
// the ResolvedCell mirrors the request body.
|
||||||
|
const days = eachDay(body.date_from, body.date_to);
|
||||||
|
const id = data && typeof data.id === "number" ? data.id : null;
|
||||||
|
const rolled = patchCells(currentGridKey, body.user_id, days, () =>
|
||||||
|
makeEntryCell({
|
||||||
|
userId: body.user_id,
|
||||||
|
date: days[0],
|
||||||
|
projectId: body.project_id ?? null,
|
||||||
|
category: body.category,
|
||||||
|
note: body.note,
|
||||||
|
rangeFrom: body.date_from,
|
||||||
|
rangeTo: body.date_to,
|
||||||
|
entryId: id,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// Stash the rollback on the mutation object so PlanWork can call
|
||||||
|
// it from onError.
|
||||||
|
(createEntry as any)._rolled = rolled;
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateEntry = useMutation({
|
||||||
|
mutationFn: ({
|
||||||
|
id,
|
||||||
|
body,
|
||||||
|
force,
|
||||||
|
}: {
|
||||||
|
id: number;
|
||||||
|
body: any;
|
||||||
|
force?: boolean;
|
||||||
|
}) =>
|
||||||
|
apiCall(`/api/admin/plan/entries/${id}${force ? "?force=1" : ""}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}),
|
||||||
|
onSuccess: (_data, vars) => {
|
||||||
|
// We don't know the new full range without the response, but we
|
||||||
|
// do have the body's date_from/date_to. If those are present,
|
||||||
|
// patch the new range. Old cells outside the new range are NOT
|
||||||
|
// cleared here — they'll either still be valid (date_from/to
|
||||||
|
// were partial updates) or the refetch will fix them.
|
||||||
|
const { id, body } = vars;
|
||||||
|
if (body.date_from && body.date_to) {
|
||||||
|
const days = eachDay(body.date_from, body.date_to);
|
||||||
|
// Find the user that owns this entry in the current grid by
|
||||||
|
// looking for any cell with entryId === id (we already know
|
||||||
|
// the id from vars; it doesn't change across the update).
|
||||||
|
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
|
let ownerUserId: number | null = null;
|
||||||
|
if (grid) {
|
||||||
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
|
for (const cell of Object.values(byDate)) {
|
||||||
|
if (cell && cell.entryId === id) {
|
||||||
|
ownerUserId = Number(uidStr);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ownerUserId !== null) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ownerUserId !== null) {
|
||||||
|
const rolled = patchCells(currentGridKey, ownerUserId, days, (prev) =>
|
||||||
|
makeEntryCell({
|
||||||
|
userId: ownerUserId!,
|
||||||
|
date: days[0],
|
||||||
|
projectId:
|
||||||
|
body.project_id === undefined
|
||||||
|
? (prev?.project_id ?? null)
|
||||||
|
: body.project_id,
|
||||||
|
category: body.category ?? prev?.category ?? "work",
|
||||||
|
note: body.note ?? prev?.note ?? "",
|
||||||
|
rangeFrom: body.date_from,
|
||||||
|
rangeTo: body.date_to,
|
||||||
|
entryId: id,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
(updateEntry as any)._rolled = rolled;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteEntry = useMutation({
|
||||||
|
mutationFn: ({ id, force }: { id: number; force?: boolean }) =>
|
||||||
|
apiCall(`/api/admin/plan/entries/${id}${force ? "?force=1" : ""}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
}),
|
||||||
|
onSuccess: (_data, vars) => {
|
||||||
|
// For delete we need to know the entry's user_id and full range.
|
||||||
|
// Look it up from the current grid: find the user that has a cell
|
||||||
|
// with entryId === id, and read rangeFrom/rangeTo from that cell.
|
||||||
|
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
|
if (grid) {
|
||||||
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
|
for (const [, cell] of Object.entries(byDate)) {
|
||||||
|
if (
|
||||||
|
cell &&
|
||||||
|
cell.entryId === vars.id &&
|
||||||
|
cell.rangeFrom &&
|
||||||
|
cell.rangeTo
|
||||||
|
) {
|
||||||
|
const days = eachDay(cell.rangeFrom, cell.rangeTo);
|
||||||
|
const rolled = patchCells(
|
||||||
|
currentGridKey,
|
||||||
|
Number(uidStr),
|
||||||
|
days,
|
||||||
|
() => null,
|
||||||
|
);
|
||||||
|
(deleteEntry as any)._rolled = rolled;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const createOverride = useMutation({
|
||||||
|
mutationFn: (body: any) =>
|
||||||
|
apiCall("/api/admin/plan/overrides", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}),
|
||||||
|
onSuccess: (data: any, vars: any) => {
|
||||||
|
const id = data && typeof data.id === "number" ? data.id : null;
|
||||||
|
const rolled = patchCells(
|
||||||
|
currentGridKey,
|
||||||
|
vars.user_id,
|
||||||
|
[vars.shift_date],
|
||||||
|
() =>
|
||||||
|
makeOverrideCell({
|
||||||
|
userId: vars.user_id,
|
||||||
|
date: vars.shift_date,
|
||||||
|
projectId: vars.project_id ?? null,
|
||||||
|
category: vars.category,
|
||||||
|
note: vars.note,
|
||||||
|
overrideId: id,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
(createOverride as any)._rolled = rolled;
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateOverride = useMutation({
|
||||||
|
mutationFn: ({
|
||||||
|
id,
|
||||||
|
body,
|
||||||
|
force,
|
||||||
|
}: {
|
||||||
|
id: number;
|
||||||
|
body: any;
|
||||||
|
force?: boolean;
|
||||||
|
}) =>
|
||||||
|
apiCall(`/api/admin/plan/overrides/${id}${force ? "?force=1" : ""}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}),
|
||||||
|
onSuccess: (_data, vars) => {
|
||||||
|
// Find the user/date for this overrideId in the current grid, then
|
||||||
|
// patch that single cell with the new values.
|
||||||
|
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
|
if (grid) {
|
||||||
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
|
for (const [date, cell] of Object.entries(byDate)) {
|
||||||
|
if (cell && cell.overrideId === vars.id) {
|
||||||
|
const rolled = patchCells(
|
||||||
|
currentGridKey,
|
||||||
|
Number(uidStr),
|
||||||
|
[date],
|
||||||
|
(prev) =>
|
||||||
|
makeOverrideCell({
|
||||||
|
userId: Number(uidStr),
|
||||||
|
date,
|
||||||
|
projectId: vars.body.project_id ?? prev?.project_id ?? null,
|
||||||
|
category: vars.body.category ?? prev?.category ?? "work",
|
||||||
|
note: vars.body.note ?? prev?.note ?? "",
|
||||||
|
overrideId: vars.id,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
(updateOverride as any)._rolled = rolled;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteOverride = useMutation({
|
||||||
|
mutationFn: ({ id, force }: { id: number; force?: boolean }) =>
|
||||||
|
apiCall(`/api/admin/plan/overrides/${id}${force ? "?force=1" : ""}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
}),
|
||||||
|
onSuccess: (_data, vars) => {
|
||||||
|
const grid = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
|
if (grid) {
|
||||||
|
for (const [uidStr, byDate] of Object.entries(grid.cells)) {
|
||||||
|
for (const [date, cell] of Object.entries(byDate)) {
|
||||||
|
if (cell && cell.overrideId === vars.id) {
|
||||||
|
const rolled = patchCells(
|
||||||
|
currentGridKey,
|
||||||
|
Number(uidStr),
|
||||||
|
[date],
|
||||||
|
() => null,
|
||||||
|
);
|
||||||
|
(deleteOverride as any)._rolled = rolled;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Roll back an optimistic patch on mutation error. Called from
|
||||||
|
// PlanWork's mutation wrappers via `rollbackMutation(mutation, key)`.
|
||||||
|
// `mutation` is a TanStack mutation result with a `_rolled` snapshot stashed
|
||||||
|
// on it (see the `(createEntry as any)._rolled = …` writes above). Typed as
|
||||||
|
// `unknown` + an explicit cast so callers can pass the mutation object
|
||||||
|
// directly without the "weak type" mismatch a `{ _rolled? }` param causes.
|
||||||
|
function rollbackMutation(mutation: unknown, userId: number) {
|
||||||
|
const stash = mutation as {
|
||||||
|
_rolled?: Record<string, ResolvedCell | null> | null;
|
||||||
|
};
|
||||||
|
if (!stash._rolled) return;
|
||||||
|
const prev = qc.getQueryData<GridData>(currentGridKey as any);
|
||||||
|
if (!prev) return;
|
||||||
|
const userPrev = prev.cells[userId] ?? {};
|
||||||
|
const userNext = { ...userPrev };
|
||||||
|
for (const [date, cell] of Object.entries(stash._rolled)) {
|
||||||
|
userNext[date] = cell;
|
||||||
|
}
|
||||||
|
qc.setQueryData(currentGridKey, {
|
||||||
|
...prev,
|
||||||
|
cells: { ...prev.cells, [userId]: userNext },
|
||||||
|
});
|
||||||
|
stash._rolled = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
view,
|
||||||
|
setView,
|
||||||
|
anchor,
|
||||||
|
setAnchor,
|
||||||
|
filterActive,
|
||||||
|
setFilterActive,
|
||||||
|
range,
|
||||||
|
grid: gridQuery.data,
|
||||||
|
gridLoading: gridQuery.isLoading,
|
||||||
|
gridFetching: gridQuery.isFetching,
|
||||||
|
gridIsPlaceholder: gridQuery.isPlaceholderData,
|
||||||
|
modal,
|
||||||
|
setModal,
|
||||||
|
canEdit,
|
||||||
|
createEntry,
|
||||||
|
updateEntry,
|
||||||
|
deleteEntry,
|
||||||
|
createOverride,
|
||||||
|
updateOverride,
|
||||||
|
deleteOverride,
|
||||||
|
invalidate,
|
||||||
|
// Exposed so PlanWork can roll back an optimistic patch when a
|
||||||
|
// mutation throws. Pass the failed mutation and the userId it
|
||||||
|
// targeted.
|
||||||
|
rollbackMutation,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCell(
|
||||||
|
grid: GridData | undefined,
|
||||||
|
userId: number,
|
||||||
|
date: string,
|
||||||
|
): ResolvedCell | null {
|
||||||
|
return grid?.cells?.[userId]?.[date] ?? null;
|
||||||
|
}
|
||||||
24
src/admin/hooks/useReducedMotion.ts
Normal file
24
src/admin/hooks/useReducedMotion.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true when the user has expressed a preference for reduced motion
|
||||||
|
* (OS-level setting: `prefers-reduced-motion: reduce`).
|
||||||
|
*
|
||||||
|
* SSR-safe: starts as `false` (the default state), so the first render uses
|
||||||
|
* the normal animation. The effect then reconciles with the live matchMedia
|
||||||
|
* state on the client and re-renders if needed.
|
||||||
|
*/
|
||||||
|
export default function useReducedMotion(): boolean {
|
||||||
|
const [reduced, setReduced] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === "undefined" || !window.matchMedia) return;
|
||||||
|
const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||||
|
setReduced(mq.matches);
|
||||||
|
const onChange = () => setReduced(mq.matches);
|
||||||
|
mq.addEventListener("change", onChange);
|
||||||
|
return () => mq.removeEventListener("change", onChange);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return reduced;
|
||||||
|
}
|
||||||
83
src/admin/lib/apiAdapter.ts
Normal file
83
src/admin/lib/apiAdapter.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import apiFetch from "../utils/api";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thin adapter that converts apiFetch responses into the shape TanStack Query expects.
|
||||||
|
* - Checks response.ok and result.success
|
||||||
|
* - Throws on errors so TanStack Query can handle retry/error states
|
||||||
|
* - Returns result.data directly (unwrapped from the API envelope)
|
||||||
|
*/
|
||||||
|
export async function jsonQuery<T>(
|
||||||
|
url: string,
|
||||||
|
options?: RequestInit,
|
||||||
|
): Promise<T> {
|
||||||
|
const response = await apiFetch(url, options);
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
throw new Error("Unauthorized");
|
||||||
|
}
|
||||||
|
|
||||||
|
let result: { success: boolean; data?: unknown; error?: string };
|
||||||
|
try {
|
||||||
|
result = (await response.json()) as typeof result;
|
||||||
|
} catch {
|
||||||
|
throw new Error("Invalid JSON response");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok || !result.success) {
|
||||||
|
throw new Error(result.error || `Request failed (${response.status})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.data as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginationMeta {
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
per_page: number;
|
||||||
|
total_pages: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginatedResult<T> {
|
||||||
|
data: T[];
|
||||||
|
pagination: PaginationMeta;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function paginatedJsonQuery<T>(
|
||||||
|
url: string,
|
||||||
|
options?: RequestInit,
|
||||||
|
): Promise<PaginatedResult<T>> {
|
||||||
|
const response = await apiFetch(url, options);
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
throw new Error("Unauthorized");
|
||||||
|
}
|
||||||
|
|
||||||
|
let result: {
|
||||||
|
success: boolean;
|
||||||
|
data?: unknown;
|
||||||
|
error?: string;
|
||||||
|
pagination?: PaginationMeta;
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
result = (await response.json()) as typeof result;
|
||||||
|
} catch {
|
||||||
|
throw new Error("Invalid JSON response");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok || !result.success) {
|
||||||
|
throw new Error(result.error || `Request failed (${response.status})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = Array.isArray(result.data)
|
||||||
|
? result.data
|
||||||
|
: ((result.data as { items?: T[] })?.items ?? []);
|
||||||
|
const pagination = result.pagination ??
|
||||||
|
(result.data as { pagination?: PaginationMeta })?.pagination ?? {
|
||||||
|
total: items.length,
|
||||||
|
page: 1,
|
||||||
|
per_page: items.length,
|
||||||
|
total_pages: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { data: items as T[], pagination };
|
||||||
|
}
|
||||||
185
src/admin/lib/queries/attendance.ts
Normal file
185
src/admin/lib/queries/attendance.ts
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import apiFetch from "../../utils/api";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
interface LocationRaw {
|
||||||
|
users?: { first_name: string; last_name: string };
|
||||||
|
user_name?: string;
|
||||||
|
shift_date: string;
|
||||||
|
arrival_time?: string | null;
|
||||||
|
departure_time?: string | null;
|
||||||
|
arrival_lat?: string | number | null;
|
||||||
|
arrival_lng?: string | number | null;
|
||||||
|
arrival_accuracy?: number | null;
|
||||||
|
arrival_address?: string | null;
|
||||||
|
departure_lat?: string | number | null;
|
||||||
|
departure_lng?: string | number | null;
|
||||||
|
departure_accuracy?: number | null;
|
||||||
|
departure_address?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LocationRecord {
|
||||||
|
user_name: string;
|
||||||
|
shift_date: string;
|
||||||
|
arrival_time?: string | null;
|
||||||
|
departure_time?: string | null;
|
||||||
|
arrival_lat?: string | number | null;
|
||||||
|
arrival_lng?: string | number | null;
|
||||||
|
arrival_accuracy?: number | null;
|
||||||
|
arrival_address?: string | null;
|
||||||
|
departure_lat?: string | number | null;
|
||||||
|
departure_lng?: string | number | null;
|
||||||
|
departure_accuracy?: number | null;
|
||||||
|
departure_address?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectLogEntry {
|
||||||
|
id?: number;
|
||||||
|
project_id?: number;
|
||||||
|
project_name?: string;
|
||||||
|
started_at?: string;
|
||||||
|
ended_at?: string | null;
|
||||||
|
hours?: string | number | null;
|
||||||
|
minutes?: string | number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttendanceRecord {
|
||||||
|
id: number;
|
||||||
|
shift_date: string;
|
||||||
|
leave_type?: string;
|
||||||
|
leave_hours?: number;
|
||||||
|
arrival_time?: string | null;
|
||||||
|
departure_time?: string | null;
|
||||||
|
break_start?: string | null;
|
||||||
|
break_end?: string | null;
|
||||||
|
notes?: string;
|
||||||
|
project_name?: string;
|
||||||
|
project_logs?: ProjectLogEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BalanceEntry {
|
||||||
|
name: string;
|
||||||
|
vacation_total: number;
|
||||||
|
vacation_used: number;
|
||||||
|
vacation_remaining: number;
|
||||||
|
sick_used: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserShort {
|
||||||
|
id: number | string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BalancesData {
|
||||||
|
users: UserShort[];
|
||||||
|
balances: Record<string, BalanceEntry>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FundUserData {
|
||||||
|
name: string;
|
||||||
|
worked: number;
|
||||||
|
covered: number;
|
||||||
|
overtime: number;
|
||||||
|
missing: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MonthFundData {
|
||||||
|
month_name: string;
|
||||||
|
fund: number;
|
||||||
|
fund_to_date: number;
|
||||||
|
business_days: number;
|
||||||
|
users?: Record<string, FundUserData>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FundData {
|
||||||
|
months: Record<string, MonthFundData>;
|
||||||
|
holidays: unknown[];
|
||||||
|
users: UserShort[];
|
||||||
|
balances: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectUser {
|
||||||
|
user_id: number;
|
||||||
|
user_name: string;
|
||||||
|
hours: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectEntry {
|
||||||
|
project_id: number | null;
|
||||||
|
project_number?: string;
|
||||||
|
project_name?: string;
|
||||||
|
hours: number;
|
||||||
|
users: ProjectUser[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MonthProjectData {
|
||||||
|
month_name: string;
|
||||||
|
projects: ProjectEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectData {
|
||||||
|
months: Record<string, MonthProjectData>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const attendanceHistoryOptions = (filters: {
|
||||||
|
month?: string;
|
||||||
|
userId?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["attendance", "history", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.set("limit", "1000");
|
||||||
|
if (filters.month) params.set("month", filters.month);
|
||||||
|
if (filters.userId) params.set("user_id", String(filters.userId));
|
||||||
|
return jsonQuery<AttendanceRecord[]>(
|
||||||
|
`/api/admin/attendance?${params.toString()}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const attendanceBalancesOptions = (year: number) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["attendance", "balances", year],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<BalancesData>(
|
||||||
|
`/api/admin/attendance?action=balances&year=${year}`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const attendanceWorkFundOptions = (year: number) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["attendance", "workfund", year],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<FundData>(`/api/admin/attendance?action=workfund&year=${year}`),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const attendanceProjectReportOptions = (year: number) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["attendance", "project-report", year],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<ProjectData>(
|
||||||
|
`/api/admin/attendance?action=project_report&year=${year}`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const attendanceLocationOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["attendance", "location", id],
|
||||||
|
queryFn: async (): Promise<LocationRecord> => {
|
||||||
|
const response = await apiFetch(
|
||||||
|
`/api/admin/attendance?action=location&id=${id}`,
|
||||||
|
);
|
||||||
|
const result = await response.json();
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || "Záznam nebyl nalezen");
|
||||||
|
}
|
||||||
|
const raw = (result.data.record || result.data) as LocationRaw;
|
||||||
|
const userName = raw.users
|
||||||
|
? `${raw.users.first_name} ${raw.users.last_name}`.trim()
|
||||||
|
: raw.user_name || "";
|
||||||
|
const { users: _users, ...rest } = raw;
|
||||||
|
return { ...rest, user_name: userName };
|
||||||
|
},
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
28
src/admin/lib/queries/auditLog.ts
Normal file
28
src/admin/lib/queries/auditLog.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export const auditLogOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
action?: string;
|
||||||
|
entityType?: string;
|
||||||
|
dateFrom?: string;
|
||||||
|
dateTo?: string;
|
||||||
|
page?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["audit-log", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.action) params.set("action", filters.action);
|
||||||
|
if (filters.entityType) params.set("entity_type", filters.entityType);
|
||||||
|
if (filters.dateFrom) params.set("date_from", filters.dateFrom);
|
||||||
|
if (filters.dateTo) params.set("date_to", filters.dateTo);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
const qs = params.toString();
|
||||||
|
return jsonQuery<{
|
||||||
|
data: Record<string, unknown>[];
|
||||||
|
pagination: Record<string, unknown>;
|
||||||
|
}>(`/api/admin/audit-log${qs ? `?${qs}` : ""}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
28
src/admin/lib/queries/common.ts
Normal file
28
src/admin/lib/queries/common.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface BankAccount {
|
||||||
|
id: number;
|
||||||
|
account_name: string;
|
||||||
|
bank_name: string;
|
||||||
|
account_number: string;
|
||||||
|
iban: string;
|
||||||
|
bic: string;
|
||||||
|
currency: string;
|
||||||
|
is_default: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const bankAccountsOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["bank-accounts"],
|
||||||
|
queryFn: () => jsonQuery<BankAccount[]>("/api/admin/bank-accounts"),
|
||||||
|
staleTime: 2 * 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const supplierListOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["suppliers"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<string[]>("/api/admin/received-invoices/suppliers"),
|
||||||
|
staleTime: 2 * 60_000,
|
||||||
|
});
|
||||||
42
src/admin/lib/queries/dashboard.ts
Normal file
42
src/admin/lib/queries/dashboard.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import apiFetch from "../../utils/api";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export const dashboardOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["dashboard"],
|
||||||
|
queryFn: () => jsonQuery<Record<string, unknown>>("/api/admin/dashboard"),
|
||||||
|
staleTime: 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const require2FAOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["settings", "2fa"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<{ require_2fa: boolean }>("/api/admin/totp/required"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface Session {
|
||||||
|
id: number | string;
|
||||||
|
is_current: boolean;
|
||||||
|
device_info?: {
|
||||||
|
icon?: string;
|
||||||
|
browser?: string;
|
||||||
|
os?: string;
|
||||||
|
};
|
||||||
|
ip_address: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const sessionsOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["sessions"],
|
||||||
|
queryFn: async (): Promise<Session[]> => {
|
||||||
|
const response = await apiFetch("/api/admin/sessions");
|
||||||
|
const data = await response.json();
|
||||||
|
if (data.success) {
|
||||||
|
return Array.isArray(data.data) ? data.data : data.data?.sessions || [];
|
||||||
|
}
|
||||||
|
throw new Error(data.error || "Nepodařilo se načíst relace");
|
||||||
|
},
|
||||||
|
});
|
||||||
209
src/admin/lib/queries/invoices.ts
Normal file
209
src/admin/lib/queries/invoices.ts
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface CurrencyAmount {
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Invoice {
|
||||||
|
id: number;
|
||||||
|
invoice_number: string;
|
||||||
|
customer_name: string | null;
|
||||||
|
status: string;
|
||||||
|
issue_date: string;
|
||||||
|
due_date: string;
|
||||||
|
total: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InvoiceStats {
|
||||||
|
paid_month: CurrencyAmount[];
|
||||||
|
paid_month_czk: number;
|
||||||
|
paid_month_count: number;
|
||||||
|
awaiting: CurrencyAmount[];
|
||||||
|
awaiting_czk: number;
|
||||||
|
awaiting_count: number;
|
||||||
|
overdue: CurrencyAmount[];
|
||||||
|
overdue_czk: number;
|
||||||
|
overdue_count: number;
|
||||||
|
vat_month: CurrencyAmount[];
|
||||||
|
vat_month_czk: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InvoiceItem {
|
||||||
|
id?: number;
|
||||||
|
description: string;
|
||||||
|
item_description?: string;
|
||||||
|
quantity: number;
|
||||||
|
unit: string;
|
||||||
|
unit_price: number;
|
||||||
|
vat_rate?: number;
|
||||||
|
is_included_in_total: boolean;
|
||||||
|
position?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InvoiceDetail {
|
||||||
|
id: number;
|
||||||
|
invoice_number: string;
|
||||||
|
customer_id: number | null;
|
||||||
|
customer_name: string;
|
||||||
|
customer?: {
|
||||||
|
company_id?: string;
|
||||||
|
vat_id?: string;
|
||||||
|
};
|
||||||
|
status: string;
|
||||||
|
issue_date: string;
|
||||||
|
due_date: string;
|
||||||
|
taxable_date?: string;
|
||||||
|
tax_date?: string;
|
||||||
|
currency: string;
|
||||||
|
language: string;
|
||||||
|
vat_rate: number;
|
||||||
|
apply_vat: boolean;
|
||||||
|
exchange_rate: string;
|
||||||
|
notes?: string;
|
||||||
|
payment_method?: string;
|
||||||
|
variable_symbol?: string;
|
||||||
|
constant_symbol?: string;
|
||||||
|
issued_by?: string | null;
|
||||||
|
paid_date?: string;
|
||||||
|
billing_text?: string;
|
||||||
|
bank_name?: string;
|
||||||
|
bank_swift?: string;
|
||||||
|
bank_iban?: string;
|
||||||
|
bank_account?: string;
|
||||||
|
bank_account_id?: number | null;
|
||||||
|
items?: InvoiceItem[];
|
||||||
|
subtotal: number;
|
||||||
|
vat_amount: number;
|
||||||
|
total: number;
|
||||||
|
order?: {
|
||||||
|
id: number;
|
||||||
|
order_number: string;
|
||||||
|
status?: string;
|
||||||
|
} | null;
|
||||||
|
order_id?: number;
|
||||||
|
order_number?: string;
|
||||||
|
has_pdf?: boolean;
|
||||||
|
valid_transitions?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReceivedInvoice {
|
||||||
|
id: number;
|
||||||
|
supplier_name: string;
|
||||||
|
invoice_number: string;
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
vat_rate: number;
|
||||||
|
issue_date: string;
|
||||||
|
due_date: string;
|
||||||
|
notes: string;
|
||||||
|
status: string;
|
||||||
|
file_name?: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReceivedStats {
|
||||||
|
total_month: CurrencyAmount[];
|
||||||
|
total_month_czk: number | null;
|
||||||
|
vat_month: CurrencyAmount[];
|
||||||
|
vat_month_czk: number | null;
|
||||||
|
unpaid: CurrencyAmount[];
|
||||||
|
unpaid_czk: number | null;
|
||||||
|
unpaid_count: number;
|
||||||
|
month_count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const invoiceListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
sort?: string;
|
||||||
|
order?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
month?: number;
|
||||||
|
year?: number;
|
||||||
|
status?: string;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["invoices", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.sort) params.set("sort", filters.sort);
|
||||||
|
if (filters.order) params.set("order", filters.order);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
if (filters.month) params.set("month", String(filters.month));
|
||||||
|
if (filters.year) params.set("year", String(filters.year));
|
||||||
|
if (filters.status) params.set("status", filters.status);
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<Invoice>(
|
||||||
|
`/api/admin/invoices${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const receivedInvoiceListOptions = (filters: {
|
||||||
|
month?: number;
|
||||||
|
year?: number;
|
||||||
|
search?: string;
|
||||||
|
sort?: string;
|
||||||
|
order?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: [
|
||||||
|
"invoices",
|
||||||
|
"received",
|
||||||
|
{
|
||||||
|
month: filters.month,
|
||||||
|
year: filters.year,
|
||||||
|
search: filters.search,
|
||||||
|
sort: filters.sort,
|
||||||
|
order: filters.order,
|
||||||
|
page: filters.page,
|
||||||
|
perPage: filters.perPage,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.month) params.set("month", String(filters.month));
|
||||||
|
if (filters.year) params.set("year", String(filters.year));
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.sort) params.set("sort", filters.sort);
|
||||||
|
if (filters.order) params.set("order", filters.order);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<ReceivedInvoice>(
|
||||||
|
`/api/admin/received-invoices${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const invoiceStatsOptions = (month: number, year: number) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["invoices", "stats", month, year],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<InvoiceStats>(
|
||||||
|
`/api/admin/invoices/stats?month=${month}&year=${year}`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const receivedInvoiceStatsOptions = (month: number, year: number) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["invoices", "received", "stats", month, year],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<ReceivedStats>(
|
||||||
|
`/api/admin/received-invoices/stats?month=${month}&year=${year}`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const invoiceDetailOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["invoices", id],
|
||||||
|
queryFn: () => jsonQuery<InvoiceDetail>(`/api/admin/invoices/${id}`),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
42
src/admin/lib/queries/leave.ts
Normal file
42
src/admin/lib/queries/leave.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface LeaveRequest {
|
||||||
|
id: number;
|
||||||
|
leave_type: string;
|
||||||
|
date_from: string;
|
||||||
|
date_to: string;
|
||||||
|
total_days: number;
|
||||||
|
total_hours: number;
|
||||||
|
status: string;
|
||||||
|
notes?: string;
|
||||||
|
reviewer_note?: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const leaveRequestsOptions = (mine = true) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["leave-requests", mine ? "mine" : "all"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<LeaveRequest[]>(
|
||||||
|
`/api/admin/leave-requests${mine ? "?mine=1" : ""}`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const leavePendingOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["leave", "pending"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<Record<string, unknown>[]>(
|
||||||
|
"/api/admin/leave-requests?status=pending",
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const leaveProcessedOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["leave", "processed"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<Record<string, unknown>[]>(
|
||||||
|
"/api/admin/leave-requests?status=approved,rejected",
|
||||||
|
),
|
||||||
|
});
|
||||||
113
src/admin/lib/queries/mutations.ts
Normal file
113
src/admin/lib/queries/mutations.ts
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import {
|
||||||
|
useMutation,
|
||||||
|
useQueryClient,
|
||||||
|
type UseMutationOptions,
|
||||||
|
} from "@tanstack/react-query";
|
||||||
|
import apiFetch from "../../utils/api";
|
||||||
|
|
||||||
|
export interface ApiError extends Error {
|
||||||
|
status?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type HttpMethod = "POST" | "PUT" | "PATCH" | "DELETE";
|
||||||
|
|
||||||
|
interface ApiResponseBody<T> {
|
||||||
|
success: boolean;
|
||||||
|
data?: T;
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function performMutation<TIn, TOut>(opts: {
|
||||||
|
url: string | ((input: TIn) => string);
|
||||||
|
method: HttpMethod | ((input: TIn) => HttpMethod);
|
||||||
|
body?: TIn;
|
||||||
|
}): Promise<TOut> {
|
||||||
|
const url =
|
||||||
|
typeof opts.url === "function" ? opts.url(opts.body as TIn) : opts.url;
|
||||||
|
const method =
|
||||||
|
typeof opts.method === "function"
|
||||||
|
? opts.method(opts.body as TIn)
|
||||||
|
: opts.method;
|
||||||
|
const response = await apiFetch(url, {
|
||||||
|
method,
|
||||||
|
headers:
|
||||||
|
opts.body !== undefined
|
||||||
|
? { "Content-Type": "application/json" }
|
||||||
|
: undefined,
|
||||||
|
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
const err: ApiError = new Error("Unauthorized");
|
||||||
|
err.status = 401;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
let result: ApiResponseBody<TOut>;
|
||||||
|
try {
|
||||||
|
result = (await response.json()) as ApiResponseBody<TOut>;
|
||||||
|
} catch {
|
||||||
|
throw new Error("Invalid JSON response");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok || !result.success) {
|
||||||
|
const err: ApiError = new Error(
|
||||||
|
result.error || `Request failed (${response.status})`,
|
||||||
|
);
|
||||||
|
err.status = response.status;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.data as TOut;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiMutationOptions<TIn, TOut> {
|
||||||
|
url: string | ((input: TIn) => string);
|
||||||
|
method: HttpMethod | ((input: TIn) => HttpMethod);
|
||||||
|
/** Query-key prefixes to invalidate on success. Broad per CLAUDE.md. */
|
||||||
|
invalidate?: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook that wraps `useMutation` with `apiFetch` and broad-invalidation.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* const createCategory = useApiMutation<CategoryForm, WarehouseCategory>({
|
||||||
|
* url: "/api/admin/warehouse/categories",
|
||||||
|
* method: "POST",
|
||||||
|
* invalidate: ["warehouse"],
|
||||||
|
* });
|
||||||
|
* createCategory.mutate(form, {
|
||||||
|
* onSuccess: () => { ... },
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* The returned `data` from a successful mutation is `TOut`. Errors are thrown
|
||||||
|
* as `ApiError` (with `.status` attached) so callers can branch on HTTP code.
|
||||||
|
*/
|
||||||
|
export function useApiMutation<TIn, TOut>(
|
||||||
|
opts: ApiMutationOptions<TIn, TOut> &
|
||||||
|
Omit<UseMutationOptions<TOut, ApiError, TIn>, "mutationFn">,
|
||||||
|
) {
|
||||||
|
const { url, method, invalidate, onSuccess, ...rest } = opts;
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation<TOut, ApiError, TIn, unknown>({
|
||||||
|
mutationFn: (input: TIn) =>
|
||||||
|
performMutation<TIn, TOut>({ url, method, body: input }),
|
||||||
|
...rest,
|
||||||
|
onSuccess: (data, variables, onMutateResult, context) => {
|
||||||
|
if (invalidate) {
|
||||||
|
for (const key of invalidate) {
|
||||||
|
queryClient.invalidateQueries({ queryKey: [key] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Forward to user-provided onSuccess with the 4-arg signature expected by TanStack.
|
||||||
|
(
|
||||||
|
onSuccess as
|
||||||
|
| ((d: TOut, v: TIn, r: unknown, c: unknown) => void)
|
||||||
|
| undefined
|
||||||
|
)?.(data, variables, onMutateResult, context);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
160
src/admin/lib/queries/offers.ts
Normal file
160
src/admin/lib/queries/offers.ts
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface ItemTemplate {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
default_price: number;
|
||||||
|
category: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScopeSection {
|
||||||
|
_key: string;
|
||||||
|
title: string;
|
||||||
|
title_cz: string;
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScopeTemplate {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
|
scope_template_sections?: ScopeSection[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CustomField {
|
||||||
|
name: string;
|
||||||
|
value: string;
|
||||||
|
showLabel: boolean;
|
||||||
|
_key?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Customer {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
street?: string;
|
||||||
|
city?: string;
|
||||||
|
postal_code?: string;
|
||||||
|
country?: string;
|
||||||
|
company_id?: string;
|
||||||
|
vat_id?: string;
|
||||||
|
quotation_count: number;
|
||||||
|
custom_fields?: CustomField[];
|
||||||
|
customer_field_order?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const offerCustomersOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["offer-customers"],
|
||||||
|
queryFn: () => jsonQuery<Customer[]>("/api/admin/customers"),
|
||||||
|
staleTime: 2 * 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const itemTemplatesOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["offer-templates", "items"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<ItemTemplate[]>("/api/admin/offers-templates?action=items"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const scopeTemplatesOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["offer-templates", "scopes"],
|
||||||
|
queryFn: () => jsonQuery<ScopeTemplate[]>("/api/admin/offers-templates"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const offerListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
sort?: string;
|
||||||
|
order?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
status?: string;
|
||||||
|
customer_id?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["offers", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.sort) params.set("sort", filters.sort);
|
||||||
|
if (filters.order) params.set("order", filters.order);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
if (filters.status) params.set("status", filters.status);
|
||||||
|
if (filters.customer_id)
|
||||||
|
params.set("customer_id", String(filters.customer_id));
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery(`/api/admin/offers${qs ? `?${qs}` : ""}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface OfferItemData {
|
||||||
|
id?: number;
|
||||||
|
description: string;
|
||||||
|
item_description: string;
|
||||||
|
quantity: number;
|
||||||
|
unit: string;
|
||||||
|
unit_price: number;
|
||||||
|
is_included_in_total: boolean;
|
||||||
|
position?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OfferSectionData {
|
||||||
|
title: string;
|
||||||
|
title_cz: string;
|
||||||
|
content: string;
|
||||||
|
position?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OfferLockInfo {
|
||||||
|
user_id: number;
|
||||||
|
username: string;
|
||||||
|
full_name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OfferOrderInfo {
|
||||||
|
id: number;
|
||||||
|
order_number: string;
|
||||||
|
status?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OfferDetailData {
|
||||||
|
id: number;
|
||||||
|
quotation_number: string;
|
||||||
|
project_code: string;
|
||||||
|
customer_id: number | null;
|
||||||
|
customer_name: string;
|
||||||
|
created_at: string;
|
||||||
|
valid_until: string;
|
||||||
|
currency: string;
|
||||||
|
language: string;
|
||||||
|
vat_rate: number;
|
||||||
|
apply_vat: boolean;
|
||||||
|
items?: OfferItemData[];
|
||||||
|
sections?: OfferSectionData[];
|
||||||
|
status: string;
|
||||||
|
order: OfferOrderInfo | null;
|
||||||
|
locked_by: OfferLockInfo | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const offerDetailOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["offers", id],
|
||||||
|
queryFn: () => jsonQuery<OfferDetailData>(`/api/admin/offers/${id}`),
|
||||||
|
enabled: !!id,
|
||||||
|
// 404s (deleted/missing offers) are not transient. Retrying just spams
|
||||||
|
// GETs and fires the detail-page redirect toast repeatedly.
|
||||||
|
retry: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const offerNextNumberOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["offers", "next-number"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<{ next_number?: string; number?: string }>(
|
||||||
|
"/api/admin/offers/next-number",
|
||||||
|
),
|
||||||
|
});
|
||||||
84
src/admin/lib/queries/orders.ts
Normal file
84
src/admin/lib/queries/orders.ts
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface OrderItem {
|
||||||
|
id?: number;
|
||||||
|
description: string;
|
||||||
|
item_description?: string;
|
||||||
|
quantity: number;
|
||||||
|
unit: string;
|
||||||
|
unit_price: number;
|
||||||
|
is_included_in_total: number | boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderSection {
|
||||||
|
id?: number;
|
||||||
|
title: string;
|
||||||
|
title_cz?: string;
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderInvoice {
|
||||||
|
id: number;
|
||||||
|
invoice_number: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderProject {
|
||||||
|
id: number;
|
||||||
|
project_number: string;
|
||||||
|
name: string;
|
||||||
|
has_nas_folder?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderData {
|
||||||
|
id: number;
|
||||||
|
order_number: string;
|
||||||
|
quotation_id: number;
|
||||||
|
quotation_number: string;
|
||||||
|
project_code?: string;
|
||||||
|
customer_name: string;
|
||||||
|
customer_order_number: string;
|
||||||
|
currency: string;
|
||||||
|
created_at: string;
|
||||||
|
status: string;
|
||||||
|
notes: string;
|
||||||
|
attachment_name?: string;
|
||||||
|
apply_vat: number | boolean;
|
||||||
|
vat_rate: number;
|
||||||
|
language?: string;
|
||||||
|
items: OrderItem[];
|
||||||
|
sections: OrderSection[];
|
||||||
|
scope_title?: string;
|
||||||
|
scope_description?: string;
|
||||||
|
valid_transitions?: string[];
|
||||||
|
invoice?: OrderInvoice;
|
||||||
|
project?: OrderProject;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const orderListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
sort?: string;
|
||||||
|
order?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["orders", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.sort) params.set("sort", filters.sort);
|
||||||
|
if (filters.order) params.set("order", filters.order);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery(`/api/admin/orders${qs ? `?${qs}` : ""}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const orderDetailOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["orders", id],
|
||||||
|
queryFn: () => jsonQuery<OrderData>(`/api/admin/orders/${id}`),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
115
src/admin/lib/queries/plan.ts
Normal file
115
src/admin/lib/queries/plan.ts
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import apiFetch from "../../utils/api";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface PlanUser {
|
||||||
|
id: number;
|
||||||
|
full_name: string;
|
||||||
|
username: string;
|
||||||
|
role_name: string | null;
|
||||||
|
is_active: boolean;
|
||||||
|
has_attendance_record: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolvedCell {
|
||||||
|
source: "entry" | "override";
|
||||||
|
entryId: number | null;
|
||||||
|
overrideId: number | null;
|
||||||
|
user_id: number;
|
||||||
|
shift_date: string;
|
||||||
|
project_id: number | null;
|
||||||
|
/** Project label resolved server-side (see resolveGrid). Lets the UI show
|
||||||
|
* the project without depending on the capped/permission-gated projects
|
||||||
|
* list. Null when the cell has no project. */
|
||||||
|
project_number: string | null;
|
||||||
|
project_name: string | null;
|
||||||
|
category: string;
|
||||||
|
note: string;
|
||||||
|
rangeFrom: string | null;
|
||||||
|
rangeTo: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlanCategory {
|
||||||
|
id: number;
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
color: string;
|
||||||
|
sort_order: number;
|
||||||
|
is_active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const planCategoriesOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["plan", "categories"],
|
||||||
|
queryFn: () => jsonQuery<PlanCategory[]>("/api/admin/plan/categories"),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Build a key → category lookup from the categories list. */
|
||||||
|
export function categoryMap(
|
||||||
|
categories: PlanCategory[] | undefined,
|
||||||
|
): Record<string, PlanCategory> {
|
||||||
|
const map: Record<string, PlanCategory> = {};
|
||||||
|
for (const c of categories ?? []) map[c.key] = c;
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Czech label for a plan category key, resolved from the loaded categories
|
||||||
|
* map, falling back to the raw key. The `map` arg is optional so callers not
|
||||||
|
* yet threading categories still compile (they show the raw key until wired). */
|
||||||
|
export function planCategoryLabel(
|
||||||
|
key: string,
|
||||||
|
map?: Record<string, PlanCategory>,
|
||||||
|
): string {
|
||||||
|
return map?.[key]?.label ?? key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build the display label for a cell's project, preferring the server-
|
||||||
|
* embedded fields. Returns null when the cell has no project. */
|
||||||
|
export function cellProjectLabel(cell: {
|
||||||
|
project_number: string | null;
|
||||||
|
project_name: string | null;
|
||||||
|
}): string | null {
|
||||||
|
if (!cell.project_number && !cell.project_name) return null;
|
||||||
|
if (cell.project_number && cell.project_name) {
|
||||||
|
return `${cell.project_number} — ${cell.project_name}`;
|
||||||
|
}
|
||||||
|
return cell.project_number ?? cell.project_name;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GridData {
|
||||||
|
view: "week" | "month";
|
||||||
|
date_from: string;
|
||||||
|
date_to: string;
|
||||||
|
users: PlanUser[];
|
||||||
|
cells: Record<number, Record<string, ResolvedCell | null>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const planKeys = {
|
||||||
|
all: ["plan"] as const,
|
||||||
|
grid: (dateFrom: string, dateTo: string, view: "week" | "month") =>
|
||||||
|
["plan", "grid", { dateFrom, dateTo, view }] as const,
|
||||||
|
entries: (userId: number | null, dateFrom: string, dateTo: string) =>
|
||||||
|
["plan", "entries", { userId, dateFrom, dateTo }] as const,
|
||||||
|
overrides: (userId: number | null, dateFrom: string, dateTo: string) =>
|
||||||
|
["plan", "overrides", { userId, dateFrom, dateTo }] as const,
|
||||||
|
users: () => ["plan", "users"] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const gridQuery = (
|
||||||
|
dateFrom: string,
|
||||||
|
dateTo: string,
|
||||||
|
view: "week" | "month",
|
||||||
|
) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: planKeys.grid(dateFrom, dateTo, view),
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<GridData>(
|
||||||
|
`/api/admin/plan/grid?date_from=${dateFrom}&date_to=${dateTo}&view=${view}`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const usersQuery = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: planKeys.users(),
|
||||||
|
queryFn: () => jsonQuery<PlanUser[]>("/api/admin/plan/users"),
|
||||||
|
});
|
||||||
111
src/admin/lib/queries/projects.ts
Normal file
111
src/admin/lib/queries/projects.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";
|
||||||
|
import apiFetch from "../../utils/api";
|
||||||
|
|
||||||
|
export interface ProjectNote {
|
||||||
|
id: number;
|
||||||
|
content: string;
|
||||||
|
user_name: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectData {
|
||||||
|
id: number;
|
||||||
|
project_number: string;
|
||||||
|
name: string;
|
||||||
|
status: string;
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
customer_name: string;
|
||||||
|
responsible_user_id: string;
|
||||||
|
notes?: string;
|
||||||
|
order_id?: number;
|
||||||
|
order_number?: string;
|
||||||
|
order_status?: string;
|
||||||
|
quotation_id?: number;
|
||||||
|
quotation_number?: string;
|
||||||
|
has_nas_folder?: boolean;
|
||||||
|
project_notes?: ProjectNote[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Project {
|
||||||
|
id: number;
|
||||||
|
project_number: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const projectListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
sort?: string;
|
||||||
|
order?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["projects", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.sort) params.set("sort", filters.sort);
|
||||||
|
if (filters.order) params.set("order", filters.order);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<Project>(
|
||||||
|
`/api/admin/projects${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const projectDetailOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["projects", id],
|
||||||
|
queryFn: () => jsonQuery<ProjectData>(`/api/admin/projects/${id}`),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface ProjectFilesData {
|
||||||
|
items: Array<{
|
||||||
|
name: string;
|
||||||
|
type: "file" | "folder";
|
||||||
|
size?: number;
|
||||||
|
size_formatted?: string;
|
||||||
|
modified?: string;
|
||||||
|
extension?: string;
|
||||||
|
item_count?: number;
|
||||||
|
is_symlink?: boolean;
|
||||||
|
link_target?: string;
|
||||||
|
}>;
|
||||||
|
breadcrumb: string[];
|
||||||
|
path: string;
|
||||||
|
full_path: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const projectFilesOptions = (projectId: number, path: string) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["projects", String(projectId), "files", path],
|
||||||
|
queryFn: async (): Promise<ProjectFilesData> => {
|
||||||
|
const params = new URLSearchParams({ project_id: String(projectId) });
|
||||||
|
if (path) params.set("path", path);
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await apiFetch(`/api/admin/project-files?${params}`);
|
||||||
|
} catch {
|
||||||
|
throw new Error("Chyba připojení");
|
||||||
|
}
|
||||||
|
if (res.status === 401) throw new Error("Unauthorized");
|
||||||
|
if (res.status === 404) {
|
||||||
|
return { items: [], breadcrumb: [""], path: "", full_path: "" };
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok || !data.success) {
|
||||||
|
throw new Error(data.error || `Request failed (${res.status})`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
items: data.data.items || [],
|
||||||
|
breadcrumb: data.data.breadcrumb || [""],
|
||||||
|
path: data.data.path || "",
|
||||||
|
full_path: data.data.full_path || "",
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
87
src/admin/lib/queries/settings.ts
Normal file
87
src/admin/lib/queries/settings.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface CompanySettingsCustomField {
|
||||||
|
name: string;
|
||||||
|
value: string;
|
||||||
|
showLabel: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompanySettingsData {
|
||||||
|
// Company info
|
||||||
|
company_name?: string;
|
||||||
|
street?: string;
|
||||||
|
city?: string;
|
||||||
|
postal_code?: string;
|
||||||
|
country?: string;
|
||||||
|
company_id?: string;
|
||||||
|
vat_id?: string;
|
||||||
|
ico?: string;
|
||||||
|
dic?: string;
|
||||||
|
has_logo?: boolean;
|
||||||
|
has_logo_dark?: boolean;
|
||||||
|
custom_fields?: CompanySettingsCustomField[];
|
||||||
|
supplier_field_order?: string[];
|
||||||
|
|
||||||
|
// System settings
|
||||||
|
require_2fa?: boolean;
|
||||||
|
default_currency?: string;
|
||||||
|
default_vat_rate?: number;
|
||||||
|
available_currencies?: string[];
|
||||||
|
available_vat_rates?: number[];
|
||||||
|
break_threshold_hours?: number;
|
||||||
|
break_duration_short?: number;
|
||||||
|
break_duration_long?: number;
|
||||||
|
clock_rounding_minutes?: number;
|
||||||
|
invoice_alert_email?: string;
|
||||||
|
leave_notify_email?: string;
|
||||||
|
smtp_from?: string;
|
||||||
|
smtp_from_name?: string;
|
||||||
|
max_login_attempts?: number;
|
||||||
|
lockout_minutes?: number;
|
||||||
|
max_requests_per_minute?: number;
|
||||||
|
|
||||||
|
// Numbering
|
||||||
|
quotation_prefix?: string;
|
||||||
|
order_type_code?: string;
|
||||||
|
invoice_type_code?: string;
|
||||||
|
offer_number_pattern?: string;
|
||||||
|
order_number_pattern?: string;
|
||||||
|
invoice_number_pattern?: string;
|
||||||
|
warehouse_receipt_prefix?: string;
|
||||||
|
warehouse_receipt_number_pattern?: string;
|
||||||
|
warehouse_issue_prefix?: string;
|
||||||
|
warehouse_issue_number_pattern?: string;
|
||||||
|
warehouse_inventory_prefix?: string;
|
||||||
|
warehouse_inventory_number_pattern?: string;
|
||||||
|
|
||||||
|
// Misc
|
||||||
|
app_version?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const companySettingsOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["company-settings"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<CompanySettingsData>("/api/admin/company-settings"),
|
||||||
|
staleTime: 5 * 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const systemInfoOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["settings", "system-info"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<Record<string, unknown>>(
|
||||||
|
"/api/admin/company-settings/system-info",
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** @deprecated Use systemInfoOptions instead — this query fetches system-info, not system settings. */
|
||||||
|
export const systemSettingsOptions = systemInfoOptions;
|
||||||
|
|
||||||
|
export const require2FAOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["settings", "2fa"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<{ require_2fa: boolean }>("/api/admin/totp/required"),
|
||||||
|
});
|
||||||
104
src/admin/lib/queries/trips.ts
Normal file
104
src/admin/lib/queries/trips.ts
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface TripVehicle {
|
||||||
|
id: number;
|
||||||
|
spz: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TripUser {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackendTrip {
|
||||||
|
id: number;
|
||||||
|
vehicle_id: number;
|
||||||
|
user_id: number;
|
||||||
|
trip_date: string;
|
||||||
|
start_km: number;
|
||||||
|
end_km: number;
|
||||||
|
distance: number | null;
|
||||||
|
route_from: string;
|
||||||
|
route_to: string;
|
||||||
|
is_business: boolean;
|
||||||
|
notes: string | null;
|
||||||
|
users: { id: number; first_name: string; last_name: string };
|
||||||
|
vehicles: { id: number; name: string; spz: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const tripListOptions = (filters: {
|
||||||
|
month?: number;
|
||||||
|
year?: number;
|
||||||
|
vehicleId?: number;
|
||||||
|
userId?: number;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: [
|
||||||
|
"trips",
|
||||||
|
"list",
|
||||||
|
{
|
||||||
|
month: filters.month,
|
||||||
|
year: filters.year,
|
||||||
|
vehicleId: filters.vehicleId,
|
||||||
|
userId: filters.userId,
|
||||||
|
page: filters.page,
|
||||||
|
perPage: filters.perPage,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.month) params.set("month", String(filters.month));
|
||||||
|
if (filters.year) params.set("year", String(filters.year));
|
||||||
|
if (filters.vehicleId)
|
||||||
|
params.set("vehicle_id", String(filters.vehicleId));
|
||||||
|
if (filters.userId) params.set("user_id", String(filters.userId));
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
const qs = params.toString();
|
||||||
|
return jsonQuery<BackendTrip[]>(`/api/admin/trips${qs ? `?${qs}` : ""}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const tripVehiclesOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["trips", "vehicles"],
|
||||||
|
queryFn: () => jsonQuery<TripVehicle[]>("/api/admin/vehicles"),
|
||||||
|
staleTime: 2 * 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const tripUsersOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["trips", "users"],
|
||||||
|
queryFn: () => jsonQuery<TripUser[]>("/api/admin/trips/users"),
|
||||||
|
staleTime: 2 * 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const tripHistoryOptions = (filters: {
|
||||||
|
month?: string;
|
||||||
|
vehicleId?: number;
|
||||||
|
userId?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: [
|
||||||
|
"trips",
|
||||||
|
"history",
|
||||||
|
{
|
||||||
|
month: filters.month,
|
||||||
|
vehicleId: filters.vehicleId,
|
||||||
|
userId: filters.userId,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.month) params.set("month", filters.month);
|
||||||
|
if (filters.vehicleId)
|
||||||
|
params.set("vehicle_id", String(filters.vehicleId));
|
||||||
|
if (filters.userId) params.set("user_id", String(filters.userId));
|
||||||
|
const qs = params.toString();
|
||||||
|
return jsonQuery<BackendTrip[]>(`/api/admin/trips${qs ? `?${qs}` : ""}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
37
src/admin/lib/queries/users.ts
Normal file
37
src/admin/lib/queries/users.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
role_id: number;
|
||||||
|
roles?: { id: number; name: string; display_name: string } | null;
|
||||||
|
is_active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Role {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
display_name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const userListOptions = (permission?: string) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["users", { permission }],
|
||||||
|
queryFn: () => {
|
||||||
|
const url = permission
|
||||||
|
? `/api/admin/users?permission=${encodeURIComponent(permission)}&limit=100`
|
||||||
|
: "/api/admin/users?limit=100";
|
||||||
|
return jsonQuery<User[]>(url);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const roleListOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["roles"],
|
||||||
|
queryFn: () => jsonQuery<Role[]>("/api/admin/roles"),
|
||||||
|
staleTime: 2 * 60_000,
|
||||||
|
});
|
||||||
8
src/admin/lib/queries/vehicles.ts
Normal file
8
src/admin/lib/queries/vehicles.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
export const vehicleListOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["vehicles"],
|
||||||
|
queryFn: () => jsonQuery<Record<string, unknown>[]>("/api/admin/vehicles"),
|
||||||
|
});
|
||||||
430
src/admin/lib/queries/warehouse.ts
Normal file
430
src/admin/lib/queries/warehouse.ts
Normal file
@@ -0,0 +1,430 @@
|
|||||||
|
import { queryOptions } from "@tanstack/react-query";
|
||||||
|
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";
|
||||||
|
|
||||||
|
// --- Types ---
|
||||||
|
|
||||||
|
export interface WarehouseItem {
|
||||||
|
id: number;
|
||||||
|
item_number: string | null;
|
||||||
|
name: string;
|
||||||
|
description: string | null;
|
||||||
|
category_id: number | null;
|
||||||
|
unit: string;
|
||||||
|
min_quantity: number | null;
|
||||||
|
is_active: boolean;
|
||||||
|
notes: string | null;
|
||||||
|
category?: { id: number; name: string } | null;
|
||||||
|
total_quantity?: number;
|
||||||
|
available_quantity?: number;
|
||||||
|
stock_value?: number;
|
||||||
|
below_minimum?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseReceipt {
|
||||||
|
id: number;
|
||||||
|
receipt_number: string | null;
|
||||||
|
supplier_id: number | null;
|
||||||
|
delivery_note_number: string | null;
|
||||||
|
delivery_note_date: string | null;
|
||||||
|
received_by: number | null;
|
||||||
|
notes: string | null;
|
||||||
|
status: "DRAFT" | "CONFIRMED" | "CANCELLED";
|
||||||
|
created_at: string;
|
||||||
|
modified_at: string | null;
|
||||||
|
supplier?: { id: number; name: string } | null;
|
||||||
|
received_by_user?: {
|
||||||
|
id: number;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
} | null;
|
||||||
|
_count?: { items: number };
|
||||||
|
items?: WarehouseReceiptItem[];
|
||||||
|
attachments?: WarehouseReceiptAttachment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseReceiptItem {
|
||||||
|
id: number;
|
||||||
|
receipt_id: number;
|
||||||
|
item_id: number;
|
||||||
|
quantity: number;
|
||||||
|
unit_price: number;
|
||||||
|
location_id: number | null;
|
||||||
|
notes: string | null;
|
||||||
|
item?: WarehouseItem;
|
||||||
|
location?: { id: number; code: string; name: string } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseReceiptAttachment {
|
||||||
|
id: number;
|
||||||
|
receipt_id: number;
|
||||||
|
file_name: string;
|
||||||
|
file_mime: string;
|
||||||
|
file_size: number;
|
||||||
|
file_path: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseIssue {
|
||||||
|
id: number;
|
||||||
|
issue_number: string | null;
|
||||||
|
project_id: number;
|
||||||
|
issued_by: number | null;
|
||||||
|
notes: string | null;
|
||||||
|
status: "DRAFT" | "CONFIRMED" | "CANCELLED";
|
||||||
|
created_at: string;
|
||||||
|
modified_at: string | null;
|
||||||
|
project?: { id: number; name: string; project_number: string } | null;
|
||||||
|
issued_by_user?: { id: number; first_name: string; last_name: string } | null;
|
||||||
|
_count?: { items: number };
|
||||||
|
items?: WarehouseIssueItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseIssueItem {
|
||||||
|
id: number;
|
||||||
|
issue_id: number;
|
||||||
|
item_id: number;
|
||||||
|
batch_id: number;
|
||||||
|
quantity: number;
|
||||||
|
location_id: number | null;
|
||||||
|
reservation_id: number | null;
|
||||||
|
notes: string | null;
|
||||||
|
item?: WarehouseItem;
|
||||||
|
batch?: {
|
||||||
|
id: number;
|
||||||
|
quantity: number;
|
||||||
|
unit_price: number;
|
||||||
|
received_at: string;
|
||||||
|
} | null;
|
||||||
|
location?: { id: number; code: string; name: string } | null;
|
||||||
|
reservation?: { id: number; quantity: number; remaining_qty: number } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseReservation {
|
||||||
|
id: number;
|
||||||
|
item_id: number;
|
||||||
|
project_id: number;
|
||||||
|
quantity: number;
|
||||||
|
remaining_qty: number;
|
||||||
|
reserved_by: number | null;
|
||||||
|
notes: string | null;
|
||||||
|
status: "ACTIVE" | "FULFILLED" | "CANCELLED";
|
||||||
|
created_at: string;
|
||||||
|
modified_at: string | null;
|
||||||
|
item?: WarehouseItem;
|
||||||
|
project?: { id: number; name: string } | null;
|
||||||
|
reserved_by_user?: {
|
||||||
|
id: number;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
} | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseInventorySession {
|
||||||
|
id: number;
|
||||||
|
session_number: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
status: "DRAFT" | "CONFIRMED";
|
||||||
|
created_at: string;
|
||||||
|
modified_at: string | null;
|
||||||
|
items?: WarehouseInventoryItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseInventoryItem {
|
||||||
|
id: number;
|
||||||
|
session_id: number;
|
||||||
|
item_id: number;
|
||||||
|
location_id: number | null;
|
||||||
|
system_qty: number;
|
||||||
|
actual_qty: number;
|
||||||
|
difference: number;
|
||||||
|
notes: string | null;
|
||||||
|
item?: WarehouseItem;
|
||||||
|
location?: { id: number; code: string; name: string } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseCategory {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string | null;
|
||||||
|
sort_order: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseLocation {
|
||||||
|
id: number;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
description: string | null;
|
||||||
|
is_active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarehouseSupplier {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
ico: string | null;
|
||||||
|
dic: string | null;
|
||||||
|
contact_person: string | null;
|
||||||
|
email: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
address: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
is_active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MovementLogRow {
|
||||||
|
date: string;
|
||||||
|
type: string;
|
||||||
|
document_number: string;
|
||||||
|
item_name: string;
|
||||||
|
quantity: number;
|
||||||
|
unit_price: number;
|
||||||
|
supplier_or_project: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Query Options ---
|
||||||
|
|
||||||
|
export const warehouseItemListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
sort?: string;
|
||||||
|
order?: string;
|
||||||
|
category_id?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "items", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
if (filters.sort) params.set("sort", filters.sort);
|
||||||
|
if (filters.order) params.set("order", filters.order);
|
||||||
|
if (filters.category_id)
|
||||||
|
params.set("category_id", String(filters.category_id));
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<WarehouseItem>(
|
||||||
|
`/api/admin/warehouse/items${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseItemDetailOptions = (
|
||||||
|
id: string | undefined,
|
||||||
|
enabled?: boolean,
|
||||||
|
) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "items", id],
|
||||||
|
queryFn: () => jsonQuery<WarehouseItem>(`/api/admin/warehouse/items/${id}`),
|
||||||
|
enabled: enabled ?? !!id,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseCategoryListOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "categories"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<WarehouseCategory[]>("/api/admin/warehouse/categories"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseSupplierListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "suppliers", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<WarehouseSupplier>(
|
||||||
|
`/api/admin/warehouse/suppliers${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseLocationListOptions = (filters?: {
|
||||||
|
active?: "true" | "false" | "all";
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "locations", filters ?? { active: "true" }],
|
||||||
|
queryFn: () => {
|
||||||
|
const active = filters?.active ?? "true";
|
||||||
|
return jsonQuery<WarehouseLocation[]>(
|
||||||
|
`/api/admin/warehouse/locations?active=${active}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseReceiptListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
status?: string;
|
||||||
|
supplier_id?: number;
|
||||||
|
date_from?: string;
|
||||||
|
date_to?: string;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "receipts", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
if (filters.status) params.set("status", filters.status);
|
||||||
|
if (filters.supplier_id)
|
||||||
|
params.set("supplier_id", String(filters.supplier_id));
|
||||||
|
if (filters.date_from) params.set("date_from", filters.date_from);
|
||||||
|
if (filters.date_to) params.set("date_to", filters.date_to);
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<WarehouseReceipt>(
|
||||||
|
`/api/admin/warehouse/receipts${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseReceiptDetailOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "receipts", id],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<WarehouseReceipt>(`/api/admin/warehouse/receipts/${id}`),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseIssueListOptions = (filters: {
|
||||||
|
search?: string;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
status?: string;
|
||||||
|
project_id?: number;
|
||||||
|
date_from?: string;
|
||||||
|
date_to?: string;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "issues", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
if (filters.status) params.set("status", filters.status);
|
||||||
|
if (filters.project_id)
|
||||||
|
params.set("project_id", String(filters.project_id));
|
||||||
|
if (filters.date_from) params.set("date_from", filters.date_from);
|
||||||
|
if (filters.date_to) params.set("date_to", filters.date_to);
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<WarehouseIssue>(
|
||||||
|
`/api/admin/warehouse/issues${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseIssueDetailOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "issues", id],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<WarehouseIssue>(`/api/admin/warehouse/issues/${id}`),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseReservationListOptions = (filters: {
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
item_id?: number;
|
||||||
|
project_id?: number;
|
||||||
|
status?: string;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "reservations", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
if (filters.item_id) params.set("item_id", String(filters.item_id));
|
||||||
|
if (filters.project_id)
|
||||||
|
params.set("project_id", String(filters.project_id));
|
||||||
|
if (filters.status) params.set("status", filters.status);
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<WarehouseReservation>(
|
||||||
|
`/api/admin/warehouse/reservations${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseInventoryListOptions = (filters: {
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
status?: string;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "inventory", "list", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.page) params.set("page", String(filters.page));
|
||||||
|
if (filters.perPage) params.set("per_page", String(filters.perPage));
|
||||||
|
if (filters.status) params.set("status", filters.status);
|
||||||
|
const qs = params.toString();
|
||||||
|
return paginatedJsonQuery<WarehouseInventorySession>(
|
||||||
|
`/api/admin/warehouse/inventory-sessions${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseInventoryDetailOptions = (id: string | undefined) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "inventory", id],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<WarehouseInventorySession>(
|
||||||
|
`/api/admin/warehouse/inventory-sessions/${id}`,
|
||||||
|
),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseStockStatusOptions = (filters?: {
|
||||||
|
category_id?: number;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "stock-status", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters?.category_id)
|
||||||
|
params.set("category_id", String(filters.category_id));
|
||||||
|
const qs = params.toString();
|
||||||
|
return jsonQuery<WarehouseItem[]>(
|
||||||
|
`/api/admin/warehouse/reports/stock-status${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseBelowMinimumOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "below-minimum"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<WarehouseItem[]>("/api/admin/warehouse/reports/below-minimum"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const warehouseMovementLogOptions = (filters?: {
|
||||||
|
limit?: number;
|
||||||
|
type?: string;
|
||||||
|
project_id?: number;
|
||||||
|
date_from?: string;
|
||||||
|
date_to?: string;
|
||||||
|
}) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ["warehouse", "movement-log", filters],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters?.limit) params.set("limit", String(filters.limit));
|
||||||
|
if (filters?.type) params.set("type", filters.type);
|
||||||
|
if (filters?.project_id)
|
||||||
|
params.set("project_id", String(filters.project_id));
|
||||||
|
if (filters?.date_from) params.set("date_from", filters.date_from);
|
||||||
|
if (filters?.date_to) params.set("date_to", filters.date_to);
|
||||||
|
const qs = params.toString();
|
||||||
|
return jsonQuery<MovementLogRow[]>(
|
||||||
|
`/api/admin/warehouse/reports/movement-log${qs ? `?${qs}` : ""}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
13
src/admin/lib/queryClient.ts
Normal file
13
src/admin/lib/queryClient.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { QueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
export const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
staleTime: 30_000,
|
||||||
|
gcTime: 5 * 60_000,
|
||||||
|
refetchOnWindowFocus: true,
|
||||||
|
retry: 1,
|
||||||
|
refetchOnReconnect: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -46,33 +46,6 @@
|
|||||||
min-height: 32px;
|
min-height: 32px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Template dropdown menu */
|
|
||||||
.offers-template-menu {
|
|
||||||
position: absolute;
|
|
||||||
top: 100%;
|
|
||||||
right: 0;
|
|
||||||
z-index: 100;
|
|
||||||
min-width: 200px;
|
|
||||||
max-height: 250px;
|
|
||||||
overflow-y: auto;
|
|
||||||
background: var(--bg-primary);
|
|
||||||
border: 1px solid var(--border-color);
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
|
||||||
margin-top: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.offers-template-menu-item {
|
|
||||||
padding: 0.5rem 0.75rem;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
transition: background var(--transition);
|
|
||||||
}
|
|
||||||
|
|
||||||
.offers-template-menu-item:hover {
|
|
||||||
background: var(--bg-secondary);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Language badges */
|
/* Language badges */
|
||||||
.offers-lang-badge {
|
.offers-lang-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -491,10 +464,69 @@
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.offers-items-table .admin-table td .admin-form-input {
|
||||||
|
font-size: 16px;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 9px 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Give the description column more room by shrinking numeric columns */
|
||||||
|
.offers-col-qty {
|
||||||
|
width: 4rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-unit {
|
||||||
|
width: 4rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-price {
|
||||||
|
width: 5.5rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-included {
|
||||||
|
width: 3.5rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-total {
|
||||||
|
width: 5.5rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-del {
|
||||||
|
width: 2.5rem !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
.offers-items-table {
|
.offers-items-table {
|
||||||
margin: 0 -1rem;
|
margin: 0 -1rem;
|
||||||
width: calc(100% + 2rem);
|
width: calc(100% + 2rem);
|
||||||
|
border-radius: 0;
|
||||||
|
border-left: none;
|
||||||
|
border-right: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.offers-items-table .admin-table {
|
||||||
|
min-width: 700px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.offers-items-table .admin-table td {
|
||||||
|
padding: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.offers-items-table .admin-table th {
|
||||||
|
font-size: 10px;
|
||||||
|
padding: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Further reduce numeric columns on very small screens */
|
||||||
|
.offers-col-qty {
|
||||||
|
width: 3.5rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-unit {
|
||||||
|
width: 3.5rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-price {
|
||||||
|
width: 5rem !important;
|
||||||
|
}
|
||||||
|
.offers-col-total {
|
||||||
|
width: 5rem !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -542,6 +574,14 @@
|
|||||||
color: var(--text-muted) !important;
|
color: var(--text-muted) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Completed offer */
|
||||||
|
.offers-completed-row {
|
||||||
|
background: var(
|
||||||
|
--row-completed,
|
||||||
|
color-mix(in srgb, var(--success) 8%, transparent)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/* Read-only form (invalidated offer detail) */
|
/* Read-only form (invalidated offer detail) */
|
||||||
.offers-readonly input[readonly],
|
.offers-readonly input[readonly],
|
||||||
.offers-readonly select:disabled {
|
.offers-readonly select:disabled {
|
||||||
@@ -550,13 +590,32 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Offer draft indicator */
|
/* Offer draft indicator */
|
||||||
.offers-draft-indicator {
|
/* Filters */
|
||||||
|
.admin-filters {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
flex-wrap: wrap;
|
||||||
gap: 0.3rem;
|
gap: 1rem;
|
||||||
font-size: 0.72rem;
|
align-items: flex-start;
|
||||||
font-weight: 500;
|
}
|
||||||
color: var(--text-tertiary);
|
|
||||||
margin-top: 0.2rem;
|
.admin-filter-group {
|
||||||
opacity: 0.8;
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-filter-label {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-tertiary);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.03em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-filter-group .admin-tabs {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-filter-group .admin-form-select {
|
||||||
|
min-width: 10rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
@@ -14,6 +15,9 @@ import {
|
|||||||
import FormField from "../components/FormField";
|
import FormField from "../components/FormField";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
import apiFetch from "../utils/api";
|
import apiFetch from "../utils/api";
|
||||||
|
import { jsonQuery } from "../lib/apiAdapter";
|
||||||
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
|
import { czechPlural } from "../utils/formatters";
|
||||||
|
|
||||||
const API_BASE = "/api/admin";
|
const API_BASE = "/api/admin";
|
||||||
|
|
||||||
@@ -61,7 +65,6 @@ interface MonthlyFund {
|
|||||||
leave_hours: number;
|
leave_hours: number;
|
||||||
vacation_hours: number;
|
vacation_hours: number;
|
||||||
sick_hours: number;
|
sick_hours: number;
|
||||||
holiday_hours: number;
|
|
||||||
unpaid_hours: number;
|
unpaid_hours: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,12 +78,6 @@ interface AttendanceData {
|
|||||||
active_project_id: number | null;
|
active_project_id: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function pluralizeDays(n: number) {
|
|
||||||
if (n === 1) return "den";
|
|
||||||
if (n >= 2 && n <= 4) return "dny";
|
|
||||||
return "dnů";
|
|
||||||
}
|
|
||||||
|
|
||||||
function getFundBarBackground(fund: MonthlyFund) {
|
function getFundBarBackground(fund: MonthlyFund) {
|
||||||
if (fund.overtime > 0)
|
if (fund.overtime > 0)
|
||||||
return "linear-gradient(135deg, var(--warning), #d97706)";
|
return "linear-gradient(135deg, var(--warning), #d97706)";
|
||||||
@@ -92,22 +89,54 @@ function getFundBarBackground(fund: MonthlyFund) {
|
|||||||
export default function Attendance() {
|
export default function Attendance() {
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const { hasPermission } = useAuth();
|
const { hasPermission } = useAuth();
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const statusQuery = useQuery({
|
||||||
const [data, setData] = useState<AttendanceData>({
|
queryKey: ["attendance", "status"],
|
||||||
ongoing_shift: null,
|
queryFn: () => jsonQuery<AttendanceData>("/api/admin/attendance/status"),
|
||||||
today_shifts: [],
|
|
||||||
date: "",
|
|
||||||
leave_balance: {
|
|
||||||
vacation_total: 160,
|
|
||||||
vacation_used: 0,
|
|
||||||
vacation_remaining: 160,
|
|
||||||
sick_used: 0,
|
|
||||||
},
|
|
||||||
monthly_fund: null,
|
|
||||||
project_logs: [],
|
|
||||||
active_project_id: null,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const projectsQuery = useQuery({
|
||||||
|
queryKey: ["attendance", "projects"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<Project[]>("/api/admin/attendance?action=projects"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const punchMutation = useApiMutation<
|
||||||
|
Record<string, unknown>,
|
||||||
|
{ message?: string }
|
||||||
|
>({
|
||||||
|
url: () => `${API_BASE}/attendance`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const notesMutation = useApiMutation<{ notes: string }, { message?: string }>(
|
||||||
|
{
|
||||||
|
url: () => `${API_BASE}/attendance/notes`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance"],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const switchProjectMutation = useApiMutation<
|
||||||
|
{ project_id: number | null },
|
||||||
|
{ message?: string }
|
||||||
|
>({
|
||||||
|
url: () => `${API_BASE}/attendance/switch-project`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const leaveRequestMutation = useApiMutation<
|
||||||
|
{ leave_type: string; date_from: string; date_to: string; notes: string },
|
||||||
|
{ message?: string }
|
||||||
|
>({
|
||||||
|
url: () => `${API_BASE}/leave-requests`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance", "leave-requests", "users"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [isLeaveModalOpen, setIsLeaveModalOpen] = useState(false);
|
const [isLeaveModalOpen, setIsLeaveModalOpen] = useState(false);
|
||||||
const [leaveForm, setLeaveForm] = useState({
|
const [leaveForm, setLeaveForm] = useState({
|
||||||
leave_type: "vacation",
|
leave_type: "vacation",
|
||||||
@@ -117,10 +146,7 @@ export default function Attendance() {
|
|||||||
});
|
});
|
||||||
const [requestSubmitting, setRequestSubmitting] = useState(false);
|
const [requestSubmitting, setRequestSubmitting] = useState(false);
|
||||||
const [notes, setNotes] = useState("");
|
const [notes, setNotes] = useState("");
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
|
||||||
const [switchingProject, setSwitchingProject] = useState(false);
|
const [switchingProject, setSwitchingProject] = useState(false);
|
||||||
const [projectLogs, setProjectLogs] = useState<ProjectLog[]>([]);
|
|
||||||
const [activeProjectId, setActiveProjectId] = useState<number | null>(null);
|
|
||||||
const [gpsConfirm, setGpsConfirm] = useState<{
|
const [gpsConfirm, setGpsConfirm] = useState<{
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
action: string | null;
|
action: string | null;
|
||||||
@@ -139,45 +165,12 @@ export default function Attendance() {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
// Sync notes from query data when the shift changes
|
||||||
try {
|
useEffect(() => {
|
||||||
const response = await apiFetch(`${API_BASE}/attendance/status`);
|
if (statusQuery.data) {
|
||||||
if (response.status === 401) return;
|
setNotes(statusQuery.data.ongoing_shift?.notes || "");
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setData(result.data);
|
|
||||||
setNotes(result.data.ongoing_shift?.notes || "");
|
|
||||||
setProjectLogs(result.data.project_logs || []);
|
|
||||||
setActiveProjectId(result.data.active_project_id || null);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Nepodařilo se načíst data");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
}, [alert]);
|
}, [statusQuery.data]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchData();
|
|
||||||
}, [fetchData]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const loadProjects = async () => {
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/attendance?action=projects`,
|
|
||||||
);
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
const items = Array.isArray(result.data) ? result.data : [];
|
|
||||||
setProjects(items);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// silent - projects are supplementary
|
|
||||||
}
|
|
||||||
};
|
|
||||||
loadProjects();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useModalLock(isLeaveModalOpen);
|
useModalLock(isLeaveModalOpen);
|
||||||
|
|
||||||
@@ -266,51 +259,29 @@ export default function Attendance() {
|
|||||||
gpsData: Record<string, unknown> = {},
|
gpsData: Record<string, unknown> = {},
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/attendance`, {
|
const result = await punchMutation.mutateAsync({
|
||||||
method: "POST",
|
punch_action: action,
|
||||||
headers: { "Content-Type": "application/json" },
|
...gpsData,
|
||||||
body: JSON.stringify({ punch_action: action, ...gpsData }),
|
|
||||||
});
|
});
|
||||||
if (response.status === 401) return;
|
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
|
punchTimeoutRef.current = setTimeout(() => {
|
||||||
if (result.success) {
|
alert.success(result?.message || "Uloženo");
|
||||||
await fetchData();
|
}, 300);
|
||||||
punchTimeoutRef.current = setTimeout(() => {
|
} catch (e) {
|
||||||
alert.success(result.data?.message || result.message || "Uloženo");
|
|
||||||
}, 300);
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
alert.error("Chyba připojení");
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleBreak = async () => {
|
const handleBreak = async () => {
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/attendance`, {
|
const result = await punchMutation.mutateAsync({
|
||||||
method: "POST",
|
punch_action: "break_start",
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ punch_action: "break_start" }),
|
|
||||||
});
|
});
|
||||||
if (response.status === 401) return;
|
alert.success(result?.message || "Přestávka zaznamenána");
|
||||||
|
} catch (e) {
|
||||||
const result = await response.json();
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
if (result.success) {
|
|
||||||
await fetchData();
|
|
||||||
alert.success(
|
|
||||||
result.data?.message || result.message || "Přestávka zaznamenána",
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
@@ -318,45 +289,22 @@ export default function Attendance() {
|
|||||||
|
|
||||||
const handleSaveNotes = async () => {
|
const handleSaveNotes = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/attendance/notes`, {
|
await notesMutation.mutateAsync({ notes });
|
||||||
method: "POST",
|
alert.success("Poznámka byla uložena");
|
||||||
headers: { "Content-Type": "application/json" },
|
} catch (e) {
|
||||||
body: JSON.stringify({ notes }),
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
});
|
|
||||||
if (response.status === 401) return;
|
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
alert.success("Poznámka byla uložena");
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSwitchProject = async (newProjectId: string | null) => {
|
const handleSwitchProject = async (newProjectId: string | null) => {
|
||||||
setSwitchingProject(true);
|
setSwitchingProject(true);
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/attendance/switch-project`, {
|
const result = await switchProjectMutation.mutateAsync({
|
||||||
method: "POST",
|
project_id: newProjectId ? Number(newProjectId) : null,
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ project_id: newProjectId || null }),
|
|
||||||
});
|
});
|
||||||
if (response.status === 401) return;
|
alert.success(result?.message || "Projekt přepnut");
|
||||||
|
} catch (e) {
|
||||||
const result = await response.json();
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
if (result.success) {
|
|
||||||
await fetchData();
|
|
||||||
alert.success(
|
|
||||||
result.data?.message || result.message || "Projekt přepnut",
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
} finally {
|
||||||
setSwitchingProject(false);
|
setSwitchingProject(false);
|
||||||
}
|
}
|
||||||
@@ -380,142 +328,43 @@ export default function Attendance() {
|
|||||||
const handleRequestSubmit = async () => {
|
const handleRequestSubmit = async () => {
|
||||||
setRequestSubmitting(true);
|
setRequestSubmitting(true);
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/leave-requests`, {
|
const result = await leaveRequestMutation.mutateAsync(leaveForm);
|
||||||
method: "POST",
|
setIsLeaveModalOpen(false);
|
||||||
headers: { "Content-Type": "application/json" },
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||||
body: JSON.stringify(leaveForm),
|
alert.success(result?.message || "Žádost odeslána");
|
||||||
|
setLeaveForm({
|
||||||
|
leave_type: "vacation",
|
||||||
|
date_from: new Date().toISOString().split("T")[0],
|
||||||
|
date_to: new Date().toISOString().split("T")[0],
|
||||||
|
notes: "",
|
||||||
});
|
});
|
||||||
if (response.status === 401) return;
|
} catch (e) {
|
||||||
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setIsLeaveModalOpen(false);
|
|
||||||
await fetchData();
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
||||||
alert.success(
|
|
||||||
result.data?.message || result.message || "Žádost odeslána",
|
|
||||||
);
|
|
||||||
setLeaveForm({
|
|
||||||
leave_type: "vacation",
|
|
||||||
date_from: new Date().toISOString().split("T")[0],
|
|
||||||
date_to: new Date().toISOString().split("T")[0],
|
|
||||||
notes: "",
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
} finally {
|
||||||
setRequestSubmitting(false);
|
setRequestSubmitting(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (statusQuery.isPending) {
|
||||||
return (
|
return (
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
<div className="admin-loading">
|
||||||
<div
|
<div className="admin-spinner" />
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "200px", marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line" style={{ width: "140px" }} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div style={{ display: "flex", gap: "1.5rem" }}>
|
|
||||||
<div className="admin-card" style={{ flex: 2 }}>
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "120px", marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "180px" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-row">
|
|
||||||
<div style={{ flex: 1 }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/3"
|
|
||||||
style={{ marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/4"
|
|
||||||
style={{ height: "10px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div style={{ flex: 1 }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/3"
|
|
||||||
style={{ marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/4"
|
|
||||||
style={{ height: "10px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "100%", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
gap: "1rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/3"
|
|
||||||
style={{ marginBottom: "0.25rem" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "80px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "100%", height: "6px", borderRadius: "3px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/3"
|
|
||||||
style={{ marginBottom: "0.25rem" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "80px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "100%", height: "6px", borderRadius: "3px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (!statusQuery.data) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
ongoing_shift: ongoingShift,
|
ongoing_shift: ongoingShift,
|
||||||
today_shifts: todayShifts,
|
today_shifts: todayShifts,
|
||||||
leave_balance: leaveBalance,
|
leave_balance: leaveBalance,
|
||||||
} = data;
|
} = statusQuery.data;
|
||||||
|
const data = statusQuery.data;
|
||||||
|
const projects = projectsQuery.data ?? [];
|
||||||
|
const projectLogs = data.project_logs ?? [];
|
||||||
|
const activeProjectId = data.active_project_id ?? null;
|
||||||
const isOngoingShift = ongoingShift && !ongoingShift.departure_time;
|
const isOngoingShift = ongoingShift && !ongoingShift.departure_time;
|
||||||
const completedToday = todayShifts.filter((s) => s.departure_time);
|
const completedToday = todayShifts.filter((s) => s.departure_time);
|
||||||
const vacationDaysRemaining = Math.floor(leaveBalance.vacation_remaining / 8);
|
const vacationDaysRemaining = Math.floor(leaveBalance.vacation_remaining / 8);
|
||||||
@@ -774,7 +623,13 @@ export default function Attendance() {
|
|||||||
{formatTime(shift.departure_time)}
|
{formatTime(shift.departure_time)}
|
||||||
</td>
|
</td>
|
||||||
<td className="admin-mono">
|
<td className="admin-mono">
|
||||||
{formatMinutes(calculateWorkMinutes(shift), true)}
|
{formatMinutes(
|
||||||
|
calculateWorkMinutes({
|
||||||
|
...shift,
|
||||||
|
notes: shift.notes ?? undefined,
|
||||||
|
}),
|
||||||
|
true,
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
{projects.length > 0 && (
|
{projects.length > 0 && (
|
||||||
<td>
|
<td>
|
||||||
@@ -844,7 +699,7 @@ export default function Attendance() {
|
|||||||
{vacationDaysRemaining}
|
{vacationDaysRemaining}
|
||||||
</span>
|
</span>
|
||||||
<span className="attendance-balance-unit">
|
<span className="attendance-balance-unit">
|
||||||
{pluralizeDays(vacationDaysRemaining)}
|
{czechPlural(vacationDaysRemaining, "den", "dny", "dnů")}
|
||||||
{vacationHoursRemaining > 0 && ` ${vacationHoursRemaining}h`}
|
{vacationHoursRemaining > 0 && ` ${vacationHoursRemaining}h`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -934,8 +789,6 @@ export default function Attendance() {
|
|||||||
` + dovolená ${data.monthly_fund.vacation_hours}h`}
|
` + dovolená ${data.monthly_fund.vacation_hours}h`}
|
||||||
{data.monthly_fund.sick_hours > 0 &&
|
{data.monthly_fund.sick_hours > 0 &&
|
||||||
` + nemoc ${data.monthly_fund.sick_hours}h`}
|
` + nemoc ${data.monthly_fund.sick_hours}h`}
|
||||||
{data.monthly_fund.holiday_hours > 0 &&
|
|
||||||
` + svátek ${data.monthly_fund.holiday_hours}h`}
|
|
||||||
{data.monthly_fund.unpaid_hours > 0 &&
|
{data.monthly_fund.unpaid_hours > 0 &&
|
||||||
` + neplacené ${data.monthly_fund.unpaid_hours}h`}
|
` + neplacené ${data.monthly_fund.unpaid_hours}h`}
|
||||||
)
|
)
|
||||||
@@ -1020,7 +873,7 @@ export default function Attendance() {
|
|||||||
<path d="M9 18l6-6-6-6" />
|
<path d="M9 18l6-6-6-6" />
|
||||||
</svg>
|
</svg>
|
||||||
</Link>
|
</Link>
|
||||||
{hasPermission("attendance.admin") && (
|
{hasPermission("attendance.manage") && (
|
||||||
<Link to="/attendance/admin" className="attendance-quick-link">
|
<Link to="/attendance/admin" className="attendance-quick-link">
|
||||||
<svg
|
<svg
|
||||||
width="20"
|
width="20"
|
||||||
@@ -1172,15 +1025,15 @@ export default function Attendance() {
|
|||||||
leaveForm.date_to,
|
leaveForm.date_to,
|
||||||
)}
|
)}
|
||||||
</strong>{" "}
|
</strong>{" "}
|
||||||
{(() => {
|
{czechPlural(
|
||||||
const d = calculateBusinessDays(
|
calculateBusinessDays(
|
||||||
leaveForm.date_from,
|
leaveForm.date_from,
|
||||||
leaveForm.date_to,
|
leaveForm.date_to,
|
||||||
);
|
),
|
||||||
if (d === 1) return "pracovní den";
|
"pracovní den",
|
||||||
if (d >= 2 && d <= 4) return "pracovní dny";
|
"pracovní dny",
|
||||||
return "pracovních dnů";
|
"pracovních dnů",
|
||||||
})()}
|
)}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-muted">
|
<span className="text-muted">
|
||||||
{calculateBusinessDays(
|
{calculateBusinessDays(
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import AttendanceShiftTable from "../components/AttendanceShiftTable";
|
|||||||
import useModalLock from "../hooks/useModalLock";
|
import useModalLock from "../hooks/useModalLock";
|
||||||
import useAttendanceAdmin from "../hooks/useAttendanceAdmin";
|
import useAttendanceAdmin from "../hooks/useAttendanceAdmin";
|
||||||
import FormField from "../components/FormField";
|
import FormField from "../components/FormField";
|
||||||
import { formatMinutes } from "../utils/attendanceHelpers";
|
import { formatMinutes, formatHoursDecimal } from "../utils/attendanceHelpers";
|
||||||
|
|
||||||
interface UserTotalData {
|
interface UserTotalData {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -18,20 +18,37 @@ interface UserTotalData {
|
|||||||
working: boolean;
|
working: boolean;
|
||||||
vacation_hours: number;
|
vacation_hours: number;
|
||||||
sick_hours: number;
|
sick_hours: number;
|
||||||
holiday_hours: number;
|
|
||||||
unpaid_hours: number;
|
unpaid_hours: number;
|
||||||
fund: number | null;
|
fund: number | null;
|
||||||
worked_hours: number;
|
worked_hours: number;
|
||||||
|
// Raw worked hours incl. sub-day remainders (set by computeUserTotals in
|
||||||
|
// useAttendanceAdmin); used for the Fond "used" calculation below.
|
||||||
|
worked_hours_raw?: number;
|
||||||
covered: number;
|
covered: number;
|
||||||
missing: number;
|
missing: number;
|
||||||
overtime: number;
|
overtime: number;
|
||||||
|
// mzda-style summary fields (set by computeUserTotals in useAttendanceAdmin)
|
||||||
|
odpracovano?: number;
|
||||||
|
vcetne_svatku?: number;
|
||||||
|
prescas?: number;
|
||||||
|
svatek?: number;
|
||||||
|
worked_holiday_hours?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getFundBarBackground(data: UserTotalData) {
|
function getFundBarBackground(data: UserTotalData) {
|
||||||
if (data.overtime > 0)
|
// fondUsed mirrors the Fond "used" line in the IIFE below:
|
||||||
return "linear-gradient(135deg, var(--warning), #d97706)";
|
// real_worked + vacation + worked_holiday + free_holiday
|
||||||
if (data.covered >= (data.fund ?? 0))
|
// (delta is fondUsed - fund; 0 means exactly at the fund).
|
||||||
return "linear-gradient(135deg, var(--success), #059669)";
|
const realWorked = data.worked_hours_raw ?? data.worked_hours;
|
||||||
|
const fondUsed =
|
||||||
|
realWorked +
|
||||||
|
(data.vacation_hours ?? 0) +
|
||||||
|
(data.worked_holiday_hours ?? 0) +
|
||||||
|
(data.svatek ?? 0);
|
||||||
|
const fundVal = data.fund ?? 0;
|
||||||
|
const delta = fondUsed - fundVal;
|
||||||
|
if (delta > 0) return "linear-gradient(135deg, var(--warning), #d97706)";
|
||||||
|
if (delta >= 0) return "linear-gradient(135deg, var(--success), #059669)";
|
||||||
return "var(--gradient)";
|
return "var(--gradient)";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,9 +102,9 @@ export default function AttendanceAdmin() {
|
|||||||
useModalLock(showEditModal);
|
useModalLock(showEditModal);
|
||||||
useModalLock(showCreateModal);
|
useModalLock(showCreateModal);
|
||||||
|
|
||||||
if (!hasPermission("attendance.admin")) return <Forbidden />;
|
if (!hasPermission("attendance.manage")) return <Forbidden />;
|
||||||
|
|
||||||
// Show skeleton only on initial load (no data yet), not on filter changes
|
// Show spinner only on initial load (no data yet), not on filter changes
|
||||||
const isInitialLoad =
|
const isInitialLoad =
|
||||||
loading &&
|
loading &&
|
||||||
data.records.length === 0 &&
|
data.records.length === 0 &&
|
||||||
@@ -95,83 +112,8 @@ export default function AttendanceAdmin() {
|
|||||||
|
|
||||||
if (isInitialLoad) {
|
if (isInitialLoad) {
|
||||||
return (
|
return (
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
<div className="admin-loading">
|
||||||
<div
|
<div className="admin-spinner" />
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "200px", marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="admin-skeleton-row" style={{ gap: "0.5rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "120px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "120px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "140px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton"
|
|
||||||
style={{ gap: "0.75rem", padding: "1rem" }}
|
|
||||||
>
|
|
||||||
<div className="admin-skeleton-row">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ flex: 1, borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ flex: 1, borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="admin-grid admin-grid-3">
|
|
||||||
{[0, 1, 2].map((i) => (
|
|
||||||
<div key={i} className="admin-card">
|
|
||||||
<div className="admin-card-body">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "0.75rem" }}>
|
|
||||||
<div className="admin-skeleton-line w-1/2" />
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "80px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/3"
|
|
||||||
style={{ height: "10px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-full"
|
|
||||||
style={{ height: "4px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
|
||||||
{[0, 1, 2, 3, 4].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
<div className="admin-skeleton-line w-1/3" />
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -281,8 +223,15 @@ export default function AttendanceAdmin() {
|
|||||||
{Object.entries(data.user_totals).map(([uid, userData]) => {
|
{Object.entries(data.user_totals).map(([uid, userData]) => {
|
||||||
const ut = userData as UserTotalData;
|
const ut = userData as UserTotalData;
|
||||||
return (
|
return (
|
||||||
<div key={uid} className="admin-card">
|
<div key={uid} className="admin-card" style={{ display: "flex" }}>
|
||||||
<div className="admin-card-body">
|
<div
|
||||||
|
className="admin-card-body"
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
flex: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
<div className="flex-row gap-2 mb-2">
|
<div className="flex-row gap-2 mb-2">
|
||||||
<span style={{ fontWeight: 600 }}>{ut.name}</span>
|
<span style={{ fontWeight: 600 }}>{ut.name}</span>
|
||||||
<span
|
<span
|
||||||
@@ -298,9 +247,11 @@ export default function AttendanceAdmin() {
|
|||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
marginTop: "0.5rem",
|
marginTop: "0.5rem",
|
||||||
|
marginBottom: "0.75rem",
|
||||||
display: "flex",
|
display: "flex",
|
||||||
flexWrap: "wrap",
|
flexWrap: "wrap",
|
||||||
gap: "0.25rem",
|
gap: "0.4rem",
|
||||||
|
minHeight: "2rem",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{ut.vacation_hours > 0 && (
|
{ut.vacation_hours > 0 && (
|
||||||
@@ -313,9 +264,9 @@ export default function AttendanceAdmin() {
|
|||||||
Nem: {ut.sick_hours}h
|
Nem: {ut.sick_hours}h
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{ut.holiday_hours > 0 && (
|
{ut.svatek !== undefined && ut.svatek > 0 && (
|
||||||
<span className="attendance-leave-badge badge-holiday">
|
<span className="attendance-leave-badge badge-holiday">
|
||||||
Sv: {ut.holiday_hours}h
|
Sv: {Math.round(ut.svatek)}h
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{ut.unpaid_hours > 0 && (
|
{ut.unpaid_hours > 0 && (
|
||||||
@@ -324,62 +275,93 @@ export default function AttendanceAdmin() {
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{ut.fund !== null && (
|
{ut.fund !== null &&
|
||||||
<div className="mt-2">
|
(() => {
|
||||||
<div
|
// Fond "used" = real_worked + vacation + worked_holiday + free_holiday
|
||||||
className="text-secondary"
|
// (everything the user actually got paid for this month:
|
||||||
style={{
|
// raw worked time with sub-day remainders, plus
|
||||||
display: "flex",
|
// vacation days, plus hours worked on holidays, plus
|
||||||
justifyContent: "space-between",
|
// the 8h per unworked holiday from the fund).
|
||||||
alignItems: "center",
|
const realWorked = ut.worked_hours_raw ?? ut.worked_hours;
|
||||||
fontSize: "0.8rem",
|
const fondUsed =
|
||||||
}}
|
realWorked +
|
||||||
>
|
(ut.vacation_hours ?? 0) +
|
||||||
<span>
|
(ut.worked_holiday_hours ?? 0) +
|
||||||
Fond: {ut.worked_hours}h / {ut.fund}h
|
(ut.svatek ?? 0);
|
||||||
</span>
|
const fundVal = ut.fund ?? 0;
|
||||||
{ut.overtime > 0 && (
|
const delta = fondUsed - fundVal;
|
||||||
<span className="text-warning fw-600">
|
return (
|
||||||
+{ut.overtime}h
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{ut.overtime <= 0 && ut.missing > 0 && (
|
|
||||||
<span className="text-danger fw-600">
|
|
||||||
-{ut.missing}h
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
marginTop: "0.375rem",
|
|
||||||
height: "4px",
|
|
||||||
background: "var(--bg-tertiary)",
|
|
||||||
borderRadius: "2px",
|
|
||||||
overflow: "hidden",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
|
className="kpi-card-footer"
|
||||||
style={{
|
style={{
|
||||||
height: "100%",
|
marginTop: "auto",
|
||||||
width: `${Math.min(100, (ut.covered / (ut.fund || 1)) * 100)}%`,
|
paddingTop: "0.75rem",
|
||||||
background: getFundBarBackground(ut),
|
borderTop: "1px solid var(--border-color)",
|
||||||
borderRadius: "2px",
|
|
||||||
transition: "width 0.3s ease",
|
|
||||||
}}
|
}}
|
||||||
/>
|
>
|
||||||
</div>
|
<div
|
||||||
</div>
|
className="text-secondary"
|
||||||
)}
|
style={{
|
||||||
{data.leave_balances[uid] && (
|
display: "flex",
|
||||||
<div
|
justifyContent: "space-between",
|
||||||
className="text-secondary"
|
alignItems: "center",
|
||||||
style={{ marginTop: "0.5rem", fontSize: "0.8rem" }}
|
fontSize: "0.8rem",
|
||||||
>
|
}}
|
||||||
Zbývá dovolené:{" "}
|
>
|
||||||
{data.leave_balances[uid].vacation_remaining.toFixed(1)}h
|
<span>
|
||||||
/ {data.leave_balances[uid].vacation_total}h
|
Fond: {formatHoursDecimal(fondUsed * 60)}h /{" "}
|
||||||
</div>
|
{formatHoursDecimal(fundVal * 60)}h
|
||||||
)}
|
</span>
|
||||||
|
{delta > 0 && (
|
||||||
|
<span className="text-warning fw-600">
|
||||||
|
+{formatHoursDecimal(delta * 60)}h
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{delta <= 0 && delta < 0 && (
|
||||||
|
<span className="text-danger fw-600">
|
||||||
|
-{formatHoursDecimal(Math.abs(delta) * 60)}h
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginTop: "0.375rem",
|
||||||
|
height: "4px",
|
||||||
|
background: "var(--bg-tertiary)",
|
||||||
|
borderRadius: "2px",
|
||||||
|
overflow: "hidden",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: "100%",
|
||||||
|
width: `${Math.min(
|
||||||
|
100,
|
||||||
|
(fondUsed / (ut.fund || 1)) * 100,
|
||||||
|
)}%`,
|
||||||
|
background: getFundBarBackground(ut),
|
||||||
|
borderRadius: "2px",
|
||||||
|
transition: "width 0.3s ease",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
<div
|
||||||
|
className="text-secondary"
|
||||||
|
style={{ marginTop: "0.75rem", fontSize: "0.8rem" }}
|
||||||
|
>
|
||||||
|
{data.leave_balances[uid] ? (
|
||||||
|
<>
|
||||||
|
Zbývá dovolené:{" "}
|
||||||
|
{data.leave_balances[uid].vacation_remaining.toFixed(1)}
|
||||||
|
h / {data.leave_balances[uid].vacation_total}h
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span style={{ visibility: "hidden" }}>—</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -443,7 +425,14 @@ export default function AttendanceAdmin() {
|
|||||||
projectList={projectList}
|
projectList={projectList}
|
||||||
users={data.users}
|
users={data.users}
|
||||||
onShiftDateChange={handleCreateShiftDateChange}
|
onShiftDateChange={handleCreateShiftDateChange}
|
||||||
editingRecord={editingRecord}
|
editingRecord={
|
||||||
|
editingRecord
|
||||||
|
? {
|
||||||
|
user_name: editingRecord.user_name ?? "",
|
||||||
|
shift_date: editingRecord.shift_date,
|
||||||
|
}
|
||||||
|
: null
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ConfirmModal
|
<ConfirmModal
|
||||||
|
|||||||
@@ -1,79 +1,29 @@
|
|||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState } from "react";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
import { motion, AnimatePresence } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import ConfirmModal from "../components/ConfirmModal";
|
import ConfirmModal from "../components/ConfirmModal";
|
||||||
import useModalLock from "../hooks/useModalLock";
|
import FormModal from "../components/FormModal";
|
||||||
import FormField from "../components/FormField";
|
import FormField from "../components/FormField";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
attendanceBalancesOptions,
|
||||||
|
attendanceWorkFundOptions,
|
||||||
|
attendanceProjectReportOptions,
|
||||||
|
type BalanceEntry,
|
||||||
|
type BalancesData,
|
||||||
|
type FundData,
|
||||||
|
type FundUserData,
|
||||||
|
type MonthFundData,
|
||||||
|
type ProjectData,
|
||||||
|
type UserShort,
|
||||||
|
} from "../lib/queries/attendance";
|
||||||
|
|
||||||
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
|
|
||||||
import apiFetch from "../utils/api";
|
|
||||||
const API_BASE = "/api/admin";
|
const API_BASE = "/api/admin";
|
||||||
|
|
||||||
interface BalanceEntry {
|
|
||||||
name: string;
|
|
||||||
vacation_total: number;
|
|
||||||
vacation_used: number;
|
|
||||||
vacation_remaining: number;
|
|
||||||
sick_used: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UserShort {
|
|
||||||
id: number | string;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FundUserData {
|
|
||||||
name: string;
|
|
||||||
worked: number;
|
|
||||||
covered: number;
|
|
||||||
overtime: number;
|
|
||||||
missing: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MonthFundData {
|
|
||||||
month_name: string;
|
|
||||||
fund: number;
|
|
||||||
fund_to_date: number;
|
|
||||||
business_days: number;
|
|
||||||
users?: Record<string, FundUserData>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProjectUser {
|
|
||||||
user_id: number;
|
|
||||||
user_name: string;
|
|
||||||
hours: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProjectEntry {
|
|
||||||
project_id: number | null;
|
|
||||||
project_number?: string;
|
|
||||||
project_name?: string;
|
|
||||||
hours: number;
|
|
||||||
users: ProjectUser[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MonthProjectData {
|
|
||||||
month_name: string;
|
|
||||||
projects: ProjectEntry[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BalancesData {
|
|
||||||
users: UserShort[];
|
|
||||||
balances: Record<string, BalanceEntry>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FundData {
|
|
||||||
months: Record<string, MonthFundData>;
|
|
||||||
holidays: unknown[];
|
|
||||||
users: UserShort[];
|
|
||||||
balances: Record<string, unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProjectData {
|
|
||||||
months: Record<string, MonthProjectData>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const getVacationClass = (remaining: number): string => {
|
const getVacationClass = (remaining: number): string => {
|
||||||
if (remaining <= 0) return "text-danger";
|
if (remaining <= 0) return "text-danger";
|
||||||
if (remaining < 20) return "text-warning";
|
if (remaining < 20) return "text-warning";
|
||||||
@@ -134,23 +84,16 @@ const getProgressBackground = (
|
|||||||
export default function AttendanceBalances() {
|
export default function AttendanceBalances() {
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const { hasPermission } = useAuth();
|
const { hasPermission } = useAuth();
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [year, setYear] = useState(new Date().getFullYear());
|
const [year, setYear] = useState(new Date().getFullYear());
|
||||||
const [data, setData] = useState<BalancesData>({
|
const { data: balancesData, isPending: balancesPending } = useQuery(
|
||||||
users: [],
|
attendanceBalancesOptions(year),
|
||||||
balances: {},
|
);
|
||||||
});
|
const { data: fundData, isPending: fundPending } = useQuery(
|
||||||
|
attendanceWorkFundOptions(year),
|
||||||
const [fundLoading, setFundLoading] = useState(true);
|
);
|
||||||
const [fundData, setFundData] = useState<FundData>({
|
const { data: projectData, isPending: projectPending } = useQuery(
|
||||||
months: {},
|
attendanceProjectReportOptions(year),
|
||||||
holidays: [],
|
);
|
||||||
users: [],
|
|
||||||
balances: {},
|
|
||||||
});
|
|
||||||
|
|
||||||
const [projectLoading, setProjectLoading] = useState(true);
|
|
||||||
const [projectData, setProjectData] = useState<ProjectData>({ months: {} });
|
|
||||||
|
|
||||||
const [showEditModal, setShowEditModal] = useState(false);
|
const [showEditModal, setShowEditModal] = useState(false);
|
||||||
const [editingUser, setEditingUser] = useState<{
|
const [editingUser, setEditingUser] = useState<{
|
||||||
@@ -169,71 +112,37 @@ export default function AttendanceBalances() {
|
|||||||
userName: string;
|
userName: string;
|
||||||
}>({ show: false, userId: null, userName: "" });
|
}>({ show: false, userId: null, userName: "" });
|
||||||
|
|
||||||
const fetchData = useCallback(
|
|
||||||
async (showLoading = true) => {
|
|
||||||
if (showLoading) setLoading(true);
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/attendance?action=balances&year=${year}`,
|
|
||||||
);
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setData(result.data);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Nepodařilo se načíst data");
|
|
||||||
} finally {
|
|
||||||
if (showLoading) setLoading(false);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[year, alert],
|
|
||||||
);
|
|
||||||
|
|
||||||
const fetchFundData = useCallback(async () => {
|
|
||||||
setFundLoading(true);
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/attendance?action=workfund&year=${year}`,
|
|
||||||
);
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setFundData(result.data);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// silent - fund data is supplementary
|
|
||||||
} finally {
|
|
||||||
setFundLoading(false);
|
|
||||||
}
|
|
||||||
}, [year]);
|
|
||||||
|
|
||||||
const fetchProjectData = useCallback(async () => {
|
|
||||||
setProjectLoading(true);
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/attendance?action=project_report&year=${year}`,
|
|
||||||
);
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setProjectData(result.data);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// silent - project data is supplementary
|
|
||||||
} finally {
|
|
||||||
setProjectLoading(false);
|
|
||||||
}
|
|
||||||
}, [year]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const loadAll = async () => {
|
|
||||||
await Promise.all([fetchData(), fetchFundData(), fetchProjectData()]);
|
|
||||||
};
|
|
||||||
loadAll();
|
|
||||||
}, [fetchData, fetchFundData, fetchProjectData]);
|
|
||||||
|
|
||||||
useModalLock(showEditModal);
|
|
||||||
|
|
||||||
if (!hasPermission("attendance.balances")) return <Forbidden />;
|
if (!hasPermission("attendance.balances")) return <Forbidden />;
|
||||||
|
|
||||||
|
const editMutation = useApiMutation<
|
||||||
|
{
|
||||||
|
user_id: string;
|
||||||
|
year: number;
|
||||||
|
action_type: "edit";
|
||||||
|
vacation_total: number;
|
||||||
|
vacation_used: number;
|
||||||
|
sick_used: number;
|
||||||
|
},
|
||||||
|
{ message?: string; error?: string }
|
||||||
|
>({
|
||||||
|
url: () => `${API_BASE}/attendance?action=balances`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance", "users"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const resetMutation = useApiMutation<
|
||||||
|
{ user_id: string; year: number; action_type: "reset" },
|
||||||
|
{ message?: string; error?: string }
|
||||||
|
>({
|
||||||
|
url: () => `${API_BASE}/attendance?action=balances`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance", "users"],
|
||||||
|
onSuccess: (data) => {
|
||||||
|
setResetConfirm({ show: false, userId: null, userName: "" });
|
||||||
|
alert.success(data?.message || "Operace dokončena");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const openEditModal = (userId: string, balance: BalanceEntry) => {
|
const openEditModal = (userId: string, balance: BalanceEntry) => {
|
||||||
setEditingUser({ id: userId, name: balance.name });
|
setEditingUser({ id: userId, name: balance.name });
|
||||||
setEditForm({
|
setEditForm({
|
||||||
@@ -247,63 +156,29 @@ export default function AttendanceBalances() {
|
|||||||
const handleEditSubmit = async () => {
|
const handleEditSubmit = async () => {
|
||||||
if (!editingUser) return;
|
if (!editingUser) return;
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(
|
const result = await editMutation.mutateAsync({
|
||||||
`${API_BASE}/attendance?action=balances`,
|
user_id: editingUser.id,
|
||||||
{
|
year,
|
||||||
method: "POST",
|
action_type: "edit",
|
||||||
headers: { "Content-Type": "application/json" },
|
...editForm,
|
||||||
body: JSON.stringify({
|
});
|
||||||
user_id: editingUser.id,
|
setShowEditModal(false);
|
||||||
year,
|
alert.success(result?.message || "Upraveno");
|
||||||
action_type: "edit",
|
} catch (e) {
|
||||||
...editForm,
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
setShowEditModal(false);
|
|
||||||
await fetchData(false);
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
||||||
alert.success(result.message);
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleReset = async () => {
|
const handleReset = async () => {
|
||||||
if (!resetConfirm.userId) return;
|
if (!resetConfirm.userId) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(
|
await resetMutation.mutateAsync({
|
||||||
`${API_BASE}/attendance?action=balances`,
|
user_id: resetConfirm.userId,
|
||||||
{
|
year,
|
||||||
method: "POST",
|
action_type: "reset",
|
||||||
headers: { "Content-Type": "application/json" },
|
});
|
||||||
body: JSON.stringify({
|
} catch (e) {
|
||||||
user_id: resetConfirm.userId,
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
year,
|
|
||||||
action_type: "reset",
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
setResetConfirm({ show: false, userId: null, userName: "" });
|
|
||||||
await fetchData(false);
|
|
||||||
alert.success(result.message);
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -315,7 +190,7 @@ export default function AttendanceBalances() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getYearFundTotals = (userId: string) => {
|
const getYearFundTotals = (userId: string) => {
|
||||||
if (!fundData.months || Object.keys(fundData.months).length === 0)
|
if (!fundData?.months || Object.keys(fundData.months).length === 0)
|
||||||
return null;
|
return null;
|
||||||
let totalFund = 0;
|
let totalFund = 0;
|
||||||
let totalWorked = 0;
|
let totalWorked = 0;
|
||||||
@@ -380,132 +255,137 @@ export default function AttendanceBalances() {
|
|||||||
transition={{ duration: 0.25, delay: 0.06 }}
|
transition={{ duration: 0.25, delay: 0.06 }}
|
||||||
>
|
>
|
||||||
<div className="admin-card-body">
|
<div className="admin-card-body">
|
||||||
{loading && (
|
{balancesPending ? (
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
<div className="admin-loading">
|
||||||
{[0, 1, 2, 3, 4].map((i) => (
|
<div className="admin-spinner" />
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
<div className="admin-skeleton-line w-1/3" />
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!loading && Object.keys(data.balances).length === 0 && (
|
|
||||||
<div className="admin-empty-state">
|
|
||||||
<p>Žádní uživatelé k zobrazení.</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!loading && Object.keys(data.balances).length > 0 && (
|
|
||||||
<div className="admin-table-responsive">
|
|
||||||
<table className="admin-table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Zaměstnanec</th>
|
|
||||||
<th>Nárok (h)</th>
|
|
||||||
<th>Čerpáno (h)</th>
|
|
||||||
<th>Zbývá (h)</th>
|
|
||||||
<th>Nemoc (h)</th>
|
|
||||||
<th>Fond roku</th>
|
|
||||||
<th>Pokryto</th>
|
|
||||||
<th>+/−</th>
|
|
||||||
<th>Akce</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{Object.entries(data.balances).map(([userId, balance]) => {
|
|
||||||
const yf = getYearFundTotals(userId);
|
|
||||||
return (
|
|
||||||
<tr key={userId}>
|
|
||||||
<td className="fw-500">{balance.name}</td>
|
|
||||||
<td className="admin-mono">{balance.vacation_total}</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{balance.vacation_used.toFixed(1)}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
<span
|
|
||||||
className={getVacationClass(
|
|
||||||
balance.vacation_remaining,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{balance.vacation_remaining.toFixed(1)}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{balance.sick_used.toFixed(1)}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{yf ? `${yf.fund}h` : "—"}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{yf ? `${yf.covered}h` : "—"}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{yf ? renderFundDiff(yf) : "—"}
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<div className="admin-table-actions">
|
|
||||||
<button
|
|
||||||
onClick={() => openEditModal(userId, balance)}
|
|
||||||
className="admin-btn-icon"
|
|
||||||
title="Upravit"
|
|
||||||
aria-label="Upravit"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
width="18"
|
|
||||||
height="18"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
>
|
|
||||||
<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.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() =>
|
|
||||||
setResetConfirm({
|
|
||||||
show: true,
|
|
||||||
userId,
|
|
||||||
userName: balance.name,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="admin-btn-icon danger"
|
|
||||||
title="Resetovat"
|
|
||||||
aria-label="Resetovat"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
width="18"
|
|
||||||
height="18"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
>
|
|
||||||
<polyline points="3 6 5 6 21 6" />
|
|
||||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{balancesData &&
|
||||||
|
Object.keys(balancesData.balances).length === 0 && (
|
||||||
|
<div className="admin-empty-state">
|
||||||
|
<p>Žádní uživatelé k zobrazení.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{balancesData &&
|
||||||
|
Object.keys(balancesData.balances).length > 0 && (
|
||||||
|
<div className="admin-table-responsive">
|
||||||
|
<table className="admin-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Zaměstnanec</th>
|
||||||
|
<th>Nárok (h)</th>
|
||||||
|
<th>Čerpáno (h)</th>
|
||||||
|
<th>Zbývá (h)</th>
|
||||||
|
<th>Nemoc (h)</th>
|
||||||
|
<th>Fond roku</th>
|
||||||
|
<th>Pokryto</th>
|
||||||
|
<th>+/−</th>
|
||||||
|
<th>Akce</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{Object.entries(balancesData.balances).map(
|
||||||
|
([userId, balance]) => {
|
||||||
|
const yf = getYearFundTotals(userId);
|
||||||
|
return (
|
||||||
|
<tr key={userId}>
|
||||||
|
<td className="fw-500">{balance.name}</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{balance.vacation_total}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{balance.vacation_used.toFixed(1)}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
<span
|
||||||
|
className={getVacationClass(
|
||||||
|
balance.vacation_remaining,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{balance.vacation_remaining.toFixed(1)}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{balance.sick_used.toFixed(1)}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{yf ? `${yf.fund}h` : "—"}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{yf ? `${yf.covered}h` : "—"}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{yf ? renderFundDiff(yf) : "—"}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div className="admin-table-actions">
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
openEditModal(userId, balance)
|
||||||
|
}
|
||||||
|
className="admin-btn-icon"
|
||||||
|
title="Upravit"
|
||||||
|
aria-label="Upravit"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
>
|
||||||
|
<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.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
setResetConfirm({
|
||||||
|
show: true,
|
||||||
|
userId,
|
||||||
|
userName: balance.name,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="admin-btn-icon danger"
|
||||||
|
title="Resetovat"
|
||||||
|
aria-label="Resetovat"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
>
|
||||||
|
<polyline points="3 6 5 6 21 6" />
|
||||||
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
{/* Monthly Fund Overview */}
|
{/* Monthly Fund Overview */}
|
||||||
{!fundLoading &&
|
{!fundPending &&
|
||||||
fundData.months &&
|
fundData?.months &&
|
||||||
Object.keys(fundData.months).length > 0 && (
|
Object.keys(fundData.months).length > 0 && (
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, y: 12 }}
|
initial={{ opacity: 0, y: 12 }}
|
||||||
@@ -587,7 +467,7 @@ export default function AttendanceBalances() {
|
|||||||
gap: "0.375rem",
|
gap: "0.375rem",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{fundData.users &&
|
{fundData?.users &&
|
||||||
fundData.users.map((user) => {
|
fundData.users.map((user) => {
|
||||||
const us = monthData.users?.[String(user.id)];
|
const us = monthData.users?.[String(user.id)];
|
||||||
if (!us) return null;
|
if (!us) return null;
|
||||||
@@ -668,23 +548,15 @@ export default function AttendanceBalances() {
|
|||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{fundLoading && (
|
{fundPending && (
|
||||||
<div className="mt-6">
|
<div className="admin-loading">
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
<div className="admin-spinner" />
|
||||||
{[0, 1, 2].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
<div className="admin-skeleton-line w-1/3" />
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Monthly Project Overview */}
|
{/* Monthly Project Overview */}
|
||||||
{!projectLoading &&
|
{!projectPending &&
|
||||||
projectData.months &&
|
projectData?.months &&
|
||||||
Object.keys(projectData.months).length > 0 && (
|
Object.keys(projectData.months).length > 0 && (
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, y: 12 }}
|
initial={{ opacity: 0, y: 12 }}
|
||||||
@@ -876,123 +748,83 @@ export default function AttendanceBalances() {
|
|||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{projectLoading && (
|
{projectPending && (
|
||||||
<div className="mt-6">
|
<div className="admin-loading">
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
<div className="admin-spinner" />
|
||||||
{[0, 1, 2].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
<div className="admin-skeleton-line w-1/3" />
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Edit Modal */}
|
{/* Edit Modal */}
|
||||||
<AnimatePresence>
|
<FormModal
|
||||||
{showEditModal && editingUser && (
|
isOpen={showEditModal && !!editingUser}
|
||||||
<motion.div
|
onClose={() => setShowEditModal(false)}
|
||||||
className="admin-modal-overlay"
|
onSubmit={handleEditSubmit}
|
||||||
initial={{ opacity: 0 }}
|
title="Upravit dovolenou"
|
||||||
animate={{ opacity: 1 }}
|
loading={editMutation.isPending}
|
||||||
exit={{ opacity: 0 }}
|
>
|
||||||
transition={{ duration: 0.2 }}
|
{editingUser && (
|
||||||
>
|
<>
|
||||||
<div
|
<p
|
||||||
className="admin-modal-backdrop"
|
className="text-secondary"
|
||||||
onClick={() => setShowEditModal(false)}
|
style={{ marginTop: "0", marginBottom: "0.75rem" }}
|
||||||
/>
|
|
||||||
<motion.div
|
|
||||||
className="admin-modal"
|
|
||||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
|
||||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
|
||||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
|
||||||
transition={{ duration: 0.2 }}
|
|
||||||
>
|
>
|
||||||
<div className="admin-modal-header">
|
{editingUser.name}
|
||||||
<h2 className="admin-modal-title">Upravit dovolenou</h2>
|
</p>
|
||||||
<p className="text-secondary" style={{ marginTop: "0.25rem" }}>
|
<div className="admin-form">
|
||||||
{editingUser.name}
|
<FormField label="Nárok na dovolenou (hodiny)">
|
||||||
</p>
|
<input
|
||||||
</div>
|
type="number"
|
||||||
|
value={editForm.vacation_total}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditForm({
|
||||||
|
...editForm,
|
||||||
|
vacation_total: parseFloat(e.target.value),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
min="0"
|
||||||
|
max="500"
|
||||||
|
step="1"
|
||||||
|
className="admin-form-input"
|
||||||
|
/>
|
||||||
|
</FormField>
|
||||||
|
|
||||||
<div className="admin-modal-body">
|
<FormField label="Čerpáno dovolené (hodiny)">
|
||||||
<div className="admin-form">
|
<input
|
||||||
<FormField label="Nárok na dovolenou (hodiny)">
|
type="number"
|
||||||
<input
|
value={editForm.vacation_used}
|
||||||
type="number"
|
onChange={(e) =>
|
||||||
value={editForm.vacation_total}
|
setEditForm({
|
||||||
onChange={(e) =>
|
...editForm,
|
||||||
setEditForm({
|
vacation_used: parseFloat(e.target.value),
|
||||||
...editForm,
|
})
|
||||||
vacation_total: parseFloat(e.target.value),
|
}
|
||||||
})
|
min="0"
|
||||||
}
|
max="500"
|
||||||
min="0"
|
step="0.5"
|
||||||
max="500"
|
className="admin-form-input"
|
||||||
step="1"
|
/>
|
||||||
className="admin-form-input"
|
</FormField>
|
||||||
/>
|
|
||||||
</FormField>
|
|
||||||
|
|
||||||
<FormField label="Čerpáno dovolené (hodiny)">
|
<FormField label="Čerpáno nemocenské (hodiny)">
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
value={editForm.vacation_used}
|
value={editForm.sick_used}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setEditForm({
|
setEditForm({
|
||||||
...editForm,
|
...editForm,
|
||||||
vacation_used: parseFloat(e.target.value),
|
sick_used: parseFloat(e.target.value),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
min="0"
|
min="0"
|
||||||
max="500"
|
max="500"
|
||||||
step="0.5"
|
step="0.5"
|
||||||
className="admin-form-input"
|
className="admin-form-input"
|
||||||
/>
|
/>
|
||||||
</FormField>
|
</FormField>
|
||||||
|
</div>
|
||||||
<FormField label="Čerpáno nemocenské (hodiny)">
|
</>
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
value={editForm.sick_used}
|
|
||||||
onChange={(e) =>
|
|
||||||
setEditForm({
|
|
||||||
...editForm,
|
|
||||||
sick_used: parseFloat(e.target.value),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
min="0"
|
|
||||||
max="500"
|
|
||||||
step="0.5"
|
|
||||||
className="admin-form-input"
|
|
||||||
/>
|
|
||||||
</FormField>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="admin-modal-footer">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowEditModal(false)}
|
|
||||||
className="admin-btn admin-btn-secondary"
|
|
||||||
>
|
|
||||||
Zrušit
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleEditSubmit}
|
|
||||||
className="admin-btn admin-btn-primary"
|
|
||||||
>
|
|
||||||
Uložit
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</motion.div>
|
|
||||||
</motion.div>
|
|
||||||
)}
|
)}
|
||||||
</AnimatePresence>
|
</FormModal>
|
||||||
|
|
||||||
{/* Reset Confirmation */}
|
{/* Reset Confirmation */}
|
||||||
<ConfirmModal
|
<ConfirmModal
|
||||||
@@ -1005,6 +837,7 @@ export default function AttendanceBalances() {
|
|||||||
message={`Opravdu chcete vynulovat čerpání dovolené a nemocenské pro ${resetConfirm.userName} za rok ${year}?`}
|
message={`Opravdu chcete vynulovat čerpání dovolené a nemocenské pro ${resetConfirm.userName} za rok ${year}?`}
|
||||||
confirmText="Resetovat"
|
confirmText="Resetovat"
|
||||||
confirmVariant="danger"
|
confirmVariant="danger"
|
||||||
|
loading={resetMutation.isPending}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { userListOptions } from "../lib/queries/users";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
@@ -7,14 +9,9 @@ import { motion } from "framer-motion";
|
|||||||
|
|
||||||
import AdminDatePicker from "../components/AdminDatePicker";
|
import AdminDatePicker from "../components/AdminDatePicker";
|
||||||
import FormField from "../components/FormField";
|
import FormField from "../components/FormField";
|
||||||
import apiFetch from "../utils/api";
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
const API_BASE = "/api/admin";
|
const API_BASE = "/api/admin";
|
||||||
|
|
||||||
interface User {
|
|
||||||
id: number | string;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CreateForm {
|
interface CreateForm {
|
||||||
user_id: string;
|
user_id: string;
|
||||||
shift_date: string;
|
shift_date: string;
|
||||||
@@ -35,9 +32,18 @@ export default function AttendanceCreate() {
|
|||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const { hasPermission } = useAuth();
|
const { hasPermission } = useAuth();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [loading, setLoading] = useState(true);
|
const { data: usersData, isPending: loading } = useQuery(userListOptions());
|
||||||
|
const users = (usersData ?? []).map((u) => ({
|
||||||
|
id: u.id,
|
||||||
|
name: `${u.first_name} ${u.last_name}`.trim() || u.username,
|
||||||
|
}));
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [users, setUsers] = useState<User[]>([]);
|
|
||||||
|
const createMutation = useApiMutation<CreateForm, { message?: string }>({
|
||||||
|
url: () => `${API_BASE}/attendance`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance", "users"],
|
||||||
|
});
|
||||||
|
|
||||||
const [form, setForm] = useState<CreateForm>(() => {
|
const [form, setForm] = useState<CreateForm>(() => {
|
||||||
const today = new Date().toISOString().split("T")[0];
|
const today = new Date().toISOString().split("T")[0];
|
||||||
@@ -58,26 +64,6 @@ export default function AttendanceCreate() {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchUsers = async () => {
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(`${API_BASE}/users`);
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setUsers(
|
|
||||||
Array.isArray(result.data) ? result.data : result.data?.items || [],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Nepodařilo se načíst uživatele");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchUsers();
|
|
||||||
}, [alert]);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
@@ -89,22 +75,11 @@ export default function AttendanceCreate() {
|
|||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/attendance`, {
|
const result = await createMutation.mutateAsync(form);
|
||||||
method: "POST",
|
alert.success(result?.message || "Uloženo");
|
||||||
headers: { "Content-Type": "application/json" },
|
navigate(`/attendance/admin?month=${form.shift_date.substring(0, 7)}`);
|
||||||
body: JSON.stringify(form),
|
} catch (e) {
|
||||||
});
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
|
|
||||||
if (result.success) {
|
|
||||||
alert.success(result.message);
|
|
||||||
navigate(`/attendance/admin?month=${form.shift_date.substring(0, 7)}`);
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
@@ -123,34 +98,12 @@ export default function AttendanceCreate() {
|
|||||||
|
|
||||||
const isWorkType = form.leave_type === "work";
|
const isWorkType = form.leave_type === "work";
|
||||||
|
|
||||||
if (!hasPermission("attendance.admin")) return <Forbidden />;
|
if (!hasPermission("attendance.manage")) return <Forbidden />;
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
<div className="admin-loading">
|
||||||
<div
|
<div className="admin-spinner" />
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div className="admin-skeleton-line h-8" style={{ width: "200px" }} />
|
|
||||||
</div>
|
|
||||||
<div className="admin-card" style={{ maxWidth: "600px" }}>
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
|
||||||
{[0, 1, 2, 3, 4].map((i) => (
|
|
||||||
<div key={i}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/4"
|
|
||||||
style={{ marginBottom: "0.5rem", height: "10px" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line w-full h-10" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "120px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -224,7 +177,6 @@ export default function AttendanceCreate() {
|
|||||||
<option value="work">Práce</option>
|
<option value="work">Práce</option>
|
||||||
<option value="vacation">Dovolená</option>
|
<option value="vacation">Dovolená</option>
|
||||||
<option value="sick">Nemoc</option>
|
<option value="sick">Nemoc</option>
|
||||||
<option value="holiday">Svátek</option>
|
|
||||||
<option value="unpaid">Neplacené volno</option>
|
<option value="unpaid">Neplacené volno</option>
|
||||||
</select>
|
</select>
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
|
import { useState, useMemo, useRef } from "react";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import AdminDatePicker from "../components/AdminDatePicker";
|
import AdminDatePicker from "../components/AdminDatePicker";
|
||||||
|
import { companySettingsOptions } from "../lib/queries/settings";
|
||||||
|
import {
|
||||||
|
attendanceHistoryOptions,
|
||||||
|
type AttendanceRecord,
|
||||||
|
type ProjectLogEntry,
|
||||||
|
} from "../lib/queries/attendance";
|
||||||
import {
|
import {
|
||||||
formatDate,
|
formatDate,
|
||||||
formatDatetime,
|
formatDatetime,
|
||||||
@@ -14,35 +20,12 @@ import {
|
|||||||
getLeaveTypeBadgeClass,
|
getLeaveTypeBadgeClass,
|
||||||
calculateWorkMinutesPrint,
|
calculateWorkMinutesPrint,
|
||||||
formatTimeOrDatetimePrint,
|
formatTimeOrDatetimePrint,
|
||||||
|
calculateFreeHolidayHours,
|
||||||
|
holidaysInMonth,
|
||||||
|
normalizeDateStr,
|
||||||
|
formatHoursDecimal,
|
||||||
} from "../utils/attendanceHelpers";
|
} from "../utils/attendanceHelpers";
|
||||||
import FormField from "../components/FormField";
|
import FormField from "../components/FormField";
|
||||||
import apiFetch from "../utils/api";
|
|
||||||
|
|
||||||
const API_BASE = "/api/admin";
|
|
||||||
|
|
||||||
interface ProjectLog {
|
|
||||||
id?: number;
|
|
||||||
project_id?: number;
|
|
||||||
project_name?: string;
|
|
||||||
started_at?: string;
|
|
||||||
ended_at?: string | null;
|
|
||||||
hours?: string | number | null;
|
|
||||||
minutes?: string | number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AttendanceRecord {
|
|
||||||
id: number;
|
|
||||||
shift_date: string;
|
|
||||||
leave_type?: string;
|
|
||||||
leave_hours?: number;
|
|
||||||
arrival_time?: string | null;
|
|
||||||
departure_time?: string | null;
|
|
||||||
break_start?: string | null;
|
|
||||||
break_end?: string | null;
|
|
||||||
notes?: string;
|
|
||||||
project_name?: string;
|
|
||||||
project_logs?: ProjectLog[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const MONTH_NAMES = [
|
const MONTH_NAMES = [
|
||||||
"Leden",
|
"Leden",
|
||||||
@@ -193,48 +176,19 @@ const renderProjectCell = (record: AttendanceRecord) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function AttendanceHistory() {
|
export default function AttendanceHistory() {
|
||||||
const alert = useAlert();
|
|
||||||
const { user, hasPermission } = useAuth();
|
const { user, hasPermission } = useAuth();
|
||||||
const [loading, setLoading] = useState(true);
|
const queryClient = useQueryClient();
|
||||||
const [companyName, setCompanyName] = useState("");
|
const { data: companySettings } = useQuery(companySettingsOptions());
|
||||||
|
const companyName = companySettings?.company_name || "";
|
||||||
const printRef = useRef<HTMLDivElement>(null);
|
const printRef = useRef<HTMLDivElement>(null);
|
||||||
const [month, setMonth] = useState(() => {
|
const [month, setMonth] = useState(() => {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
|
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
|
||||||
});
|
});
|
||||||
const [records, setRecords] = useState<AttendanceRecord[]>([]);
|
const { data, isPending } = useQuery(
|
||||||
|
attendanceHistoryOptions({ month, userId: user?.id }),
|
||||||
const fetchData = useCallback(async () => {
|
);
|
||||||
setLoading(true);
|
const records = data ?? [];
|
||||||
try {
|
|
||||||
const [yearStr, monthStr] = month.split("-");
|
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/attendance?year=${yearStr}&month=${monthStr}&limit=1000&user_id=${user?.id || ""}`,
|
|
||||||
);
|
|
||||||
if (response.status === 401) return;
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setRecords(result.data);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Nepodařilo se načíst data");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}, [month, alert, user?.id]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchData();
|
|
||||||
}, [fetchData]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
apiFetch(`${API_BASE}/company-settings`)
|
|
||||||
.then((r) => r.json())
|
|
||||||
.then((d) => {
|
|
||||||
if (d.success) setCompanyName(d.data.company_name || "");
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const computed = useMemo(() => {
|
const computed = useMemo(() => {
|
||||||
const [yearStr, monthStr] = month.split("-");
|
const [yearStr, monthStr] = month.split("-");
|
||||||
@@ -244,7 +198,6 @@ export default function AttendanceHistory() {
|
|||||||
let totalMinutes = 0;
|
let totalMinutes = 0;
|
||||||
let vacationHours = 0;
|
let vacationHours = 0;
|
||||||
let sickHours = 0;
|
let sickHours = 0;
|
||||||
let holidayHours = 0;
|
|
||||||
let unpaidHours = 0;
|
let unpaidHours = 0;
|
||||||
|
|
||||||
for (const record of records) {
|
for (const record of records) {
|
||||||
@@ -256,26 +209,51 @@ export default function AttendanceHistory() {
|
|||||||
record.leave_hours != null ? Number(record.leave_hours) : 8;
|
record.leave_hours != null ? Number(record.leave_hours) : 8;
|
||||||
if (leaveType === "vacation") vacationHours += hours;
|
if (leaveType === "vacation") vacationHours += hours;
|
||||||
else if (leaveType === "sick") sickHours += hours;
|
else if (leaveType === "sick") sickHours += hours;
|
||||||
else if (leaveType === "holiday") holidayHours += hours;
|
|
||||||
else if (leaveType === "unpaid") unpaidHours += hours;
|
else if (leaveType === "unpaid") unpaidHours += hours;
|
||||||
|
// "holiday" is no longer a user-selectable leave_type — it is
|
||||||
|
// auto-computed from Czech public holidays by the print/KPI code.
|
||||||
|
// Old records may still exist; skip so they don't double-count.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const yr = parseInt(yearStr, 10);
|
const yr = parseInt(yearStr, 10);
|
||||||
const mo = parseInt(monthStr, 10) - 1;
|
const mo = parseInt(monthStr, 10) - 1;
|
||||||
const businessDays = getBusinessDaysInMonth(yr, mo);
|
const businessDays = getBusinessDaysInMonth(yr, mo);
|
||||||
const fund = businessDays * 8;
|
// Fund counts Mon-Fri + holidays (holidays are paid via the fond).
|
||||||
|
const holidayDates = holidaysInMonth(yr, mo + 1);
|
||||||
|
const holidayCount = holidayDates.length;
|
||||||
|
const fund = (businessDays + holidayCount) * 8;
|
||||||
const worked = Math.round((totalMinutes / 60) * 100) / 100;
|
const worked = Math.round((totalMinutes / 60) * 100) / 100;
|
||||||
// Covered = worked + vacation + sick (NOT holiday/unpaid — holiday is excluded from fund, unpaid is voluntary)
|
// Covered = worked + vacation + sick (NOT unpaid — unpaid is voluntary).
|
||||||
const leaveHours = vacationHours + sickHours;
|
const leaveHours = vacationHours + sickHours;
|
||||||
const covered = Math.round((worked + leaveHours) * 100) / 100;
|
const covered = Math.round((worked + leaveHours) * 100) / 100;
|
||||||
const remaining = Math.max(0, Math.round((fund - covered) * 100) / 100);
|
|
||||||
const overtime = Math.max(0, Math.round((covered - fund) * 100) / 100);
|
// fondUsed = real_worked + vacation + worked_holiday + free_holiday.
|
||||||
|
// (the all-in number: everything the user got paid for this month).
|
||||||
|
const realWorked = totalMinutes / 60;
|
||||||
|
const freeHolidayHours = calculateFreeHolidayHours(
|
||||||
|
records as unknown as Parameters<typeof calculateFreeHolidayHours>[0],
|
||||||
|
holidayDates,
|
||||||
|
);
|
||||||
|
const workedHolidayHours = records
|
||||||
|
.filter(
|
||||||
|
(r) =>
|
||||||
|
(r.leave_type || "work") === "work" &&
|
||||||
|
holidayDates.includes(normalizeDateStr(r.shift_date)),
|
||||||
|
)
|
||||||
|
.reduce((sum, r) => sum + calculateWorkMinutesPrint(r) / 60, 0);
|
||||||
|
const fondUsed =
|
||||||
|
realWorked + vacationHours + workedHolidayHours + freeHolidayHours;
|
||||||
|
const delta = fondUsed - fund;
|
||||||
|
const missing = Math.max(0, Math.round(-delta * 100) / 100);
|
||||||
|
const overtime = Math.max(0, Math.round(delta * 100) / 100);
|
||||||
|
const remaining = missing;
|
||||||
|
|
||||||
const monthlyFund = {
|
const monthlyFund = {
|
||||||
fund,
|
fund,
|
||||||
business_days: businessDays,
|
business_days: businessDays,
|
||||||
worked,
|
holiday_count: holidayCount,
|
||||||
|
worked: Math.round(fondUsed * 100) / 100,
|
||||||
covered,
|
covered,
|
||||||
remaining,
|
remaining,
|
||||||
overtime,
|
overtime,
|
||||||
@@ -286,9 +264,12 @@ export default function AttendanceHistory() {
|
|||||||
totalMinutes,
|
totalMinutes,
|
||||||
vacationHours,
|
vacationHours,
|
||||||
sickHours,
|
sickHours,
|
||||||
holidayHours,
|
|
||||||
unpaidHours,
|
unpaidHours,
|
||||||
monthlyFund,
|
monthlyFund,
|
||||||
|
fondUsed,
|
||||||
|
freeHolidayHours,
|
||||||
|
workedHolidayHours,
|
||||||
|
delta,
|
||||||
};
|
};
|
||||||
}, [records, month]);
|
}, [records, month]);
|
||||||
|
|
||||||
@@ -372,7 +353,6 @@ export default function AttendanceHistory() {
|
|||||||
}
|
}
|
||||||
.badge-vacation { background: #dbeafe; color: #1d4ed8; }
|
.badge-vacation { background: #dbeafe; color: #1d4ed8; }
|
||||||
.badge-sick { background: #fee2e2; color: #dc2626; }
|
.badge-sick { background: #fee2e2; color: #dc2626; }
|
||||||
.badge-holiday { background: #dcfce7; color: #16a34a; }
|
|
||||||
.badge-unpaid { background: #f3f4f6; color: #6b7280; }
|
.badge-unpaid { background: #f3f4f6; color: #6b7280; }
|
||||||
.badge-overtime { background: #fef3c7; color: #d97706; }
|
.badge-overtime { background: #fef3c7; color: #d97706; }
|
||||||
@media print {
|
@media print {
|
||||||
@@ -459,143 +439,161 @@ export default function AttendanceHistory() {
|
|||||||
transition={{ duration: 0.25, delay: 0.08 }}
|
transition={{ duration: 0.25, delay: 0.08 }}
|
||||||
>
|
>
|
||||||
<div className="admin-card-body">
|
<div className="admin-card-body">
|
||||||
{loading && (
|
{isPending ? (
|
||||||
<div className="admin-skeleton" style={{ gap: "0.5rem" }}>
|
<div className="admin-loading">
|
||||||
<div className="admin-skeleton-row" style={{ gap: "1rem" }}>
|
<div className="admin-spinner" />
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "48px",
|
|
||||||
height: "48px",
|
|
||||||
borderRadius: "12px",
|
|
||||||
flexShrink: 0,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div className="flex-1">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/2"
|
|
||||||
style={{ marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-full"
|
|
||||||
style={{ height: "6px", borderRadius: "3px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/3"
|
|
||||||
style={{ height: "10px", marginTop: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
) : (
|
||||||
{!loading && computed.monthlyFund && (
|
<>
|
||||||
<div
|
{computed.monthlyFund && (
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "1rem",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="admin-stat-icon info">
|
|
||||||
<svg
|
|
||||||
width="24"
|
|
||||||
height="24"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
>
|
|
||||||
<rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
|
|
||||||
<line x1="16" y1="2" x2="16" y2="6" />
|
|
||||||
<line x1="8" y1="2" x2="8" y2="6" />
|
|
||||||
<line x1="3" y1="10" x2="21" y2="10" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<div style={{ flex: 1, minWidth: "200px" }}>
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: "flex",
|
display: "flex",
|
||||||
justifyContent: "space-between",
|
alignItems: "center",
|
||||||
alignItems: "baseline",
|
gap: "1rem",
|
||||||
marginBottom: "0.375rem",
|
flexWrap: "wrap",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span
|
<div className="admin-stat-icon info">
|
||||||
style={{
|
<svg
|
||||||
fontWeight: 600,
|
width="24"
|
||||||
fontSize: "1rem",
|
height="24"
|
||||||
color: "var(--text-primary)",
|
viewBox="0 0 24 24"
|
||||||
}}
|
fill="none"
|
||||||
>
|
stroke="currentColor"
|
||||||
Fond: {computed.monthlyFund.worked}h /{" "}
|
strokeWidth="2"
|
||||||
{computed.monthlyFund.fund}h
|
>
|
||||||
</span>
|
<rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
|
||||||
<span
|
<line x1="16" y1="2" x2="16" y2="6" />
|
||||||
className="text-secondary"
|
<line x1="8" y1="2" x2="8" y2="6" />
|
||||||
style={{ fontSize: "0.8125rem" }}
|
<line x1="3" y1="10" x2="21" y2="10" />
|
||||||
>
|
</svg>
|
||||||
{computed.monthlyFund.business_days} prac. dnů
|
</div>
|
||||||
</span>
|
<div style={{ flex: 1, minWidth: "200px" }}>
|
||||||
</div>
|
<div
|
||||||
<div className="attendance-balance-bar">
|
style={{
|
||||||
<div
|
display: "flex",
|
||||||
className="attendance-balance-progress"
|
justifyContent: "space-between",
|
||||||
style={{
|
alignItems: "baseline",
|
||||||
width: `${Math.min(100, computed.monthlyFund.fund > 0 ? (computed.monthlyFund.covered / computed.monthlyFund.fund) * 100 : 0)}%`,
|
marginBottom: "0.375rem",
|
||||||
background:
|
}}
|
||||||
computed.monthlyFund.covered >=
|
>
|
||||||
computed.monthlyFund.fund
|
<span
|
||||||
? "linear-gradient(135deg, var(--success), #059669)"
|
style={{
|
||||||
: "var(--gradient)",
|
fontWeight: 600,
|
||||||
}}
|
fontSize: "1rem",
|
||||||
/>
|
color: "var(--text-primary)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Fond: {computed.monthlyFund.worked}h /{" "}
|
||||||
|
{computed.monthlyFund.fund}h
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="text-secondary"
|
||||||
|
style={{ fontSize: "0.8125rem" }}
|
||||||
|
>
|
||||||
|
{computed.monthlyFund.business_days} prac. dnů
|
||||||
|
{computed.monthlyFund.holiday_count > 0 &&
|
||||||
|
` + ${computed.monthlyFund.holiday_count} svátky`}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="attendance-balance-bar">
|
||||||
|
<div
|
||||||
|
className="attendance-balance-progress"
|
||||||
|
style={{
|
||||||
|
width: `${Math.min(100, computed.monthlyFund.fund > 0 ? (computed.monthlyFund.worked / computed.monthlyFund.fund) * 100 : 0)}%`,
|
||||||
|
background:
|
||||||
|
computed.delta > 0
|
||||||
|
? "linear-gradient(135deg, var(--warning), #d97706)"
|
||||||
|
: computed.delta >= 0
|
||||||
|
? "linear-gradient(135deg, var(--success), #059669)"
|
||||||
|
: "var(--gradient)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexWrap: "wrap",
|
||||||
|
gap: "0.4rem",
|
||||||
|
marginTop: "0.5rem",
|
||||||
|
minHeight: "1.5rem",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexWrap: "wrap",
|
||||||
|
gap: "0.4rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{computed.totalMinutes > 0 && (
|
||||||
|
<span
|
||||||
|
className="attendance-leave-badge"
|
||||||
|
title="Odpracováno (reálně)"
|
||||||
|
>
|
||||||
|
Práce: {formatHoursDecimal(computed.totalMinutes)}h
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{computed.vacationHours > 0 && (
|
||||||
|
<span className="attendance-leave-badge badge-vacation">
|
||||||
|
Dov: {computed.vacationHours}h
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{computed.sickHours > 0 && (
|
||||||
|
<span className="attendance-leave-badge badge-sick">
|
||||||
|
Nem: {computed.sickHours}h
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{computed.freeHolidayHours > 0 && (
|
||||||
|
<span className="attendance-leave-badge badge-holiday">
|
||||||
|
Sv: {Math.round(computed.freeHolidayHours)}h
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{computed.unpaidHours > 0 && (
|
||||||
|
<span className="attendance-leave-badge badge-unpaid">
|
||||||
|
Nep: {computed.unpaidHours}h
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
color: "var(--text-muted)",
|
||||||
|
}}
|
||||||
|
className={
|
||||||
|
computed.delta > 0
|
||||||
|
? "text-warning fw-600"
|
||||||
|
: computed.delta < 0
|
||||||
|
? "text-danger fw-600"
|
||||||
|
: "text-success fw-600"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{computed.delta > 0
|
||||||
|
? `Přesčas: +${formatHoursDecimal(computed.delta * 60)}h`
|
||||||
|
: computed.delta < 0
|
||||||
|
? `Zbývá: ${formatHoursDecimal(-computed.delta * 60)}h`
|
||||||
|
: "Fond splněn"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{!computed.monthlyFund && (
|
||||||
<div
|
<div
|
||||||
className="text-muted"
|
className="text-muted"
|
||||||
style={{
|
style={{
|
||||||
display: "flex",
|
fontSize: "0.875rem",
|
||||||
justifyContent: "space-between",
|
textAlign: "center",
|
||||||
fontSize: "0.75rem",
|
padding: "0.5rem 0",
|
||||||
marginTop: "0.375rem",
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span>
|
Fond měsíce není k dispozici
|
||||||
{"Pokryto: "}
|
|
||||||
{computed.monthlyFund.covered}h (práce{" "}
|
|
||||||
{computed.monthlyFund.worked}h
|
|
||||||
{computed.vacationHours > 0 &&
|
|
||||||
` + dovolená ${computed.vacationHours}h`}
|
|
||||||
{computed.sickHours > 0 &&
|
|
||||||
` + nemoc ${computed.sickHours}h`}
|
|
||||||
{computed.holidayHours > 0 &&
|
|
||||||
` + svátek ${computed.holidayHours}h`}
|
|
||||||
{computed.unpaidHours > 0 &&
|
|
||||||
` + neplacené ${computed.unpaidHours}h`}
|
|
||||||
)
|
|
||||||
</span>
|
|
||||||
{computed.monthlyFund.overtime > 0 ? (
|
|
||||||
<span className="text-warning fw-600">
|
|
||||||
Přesčas: +{computed.monthlyFund.overtime}h
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<span>Zbývá: {computed.monthlyFund.remaining}h</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</div>
|
</>
|
||||||
)}
|
|
||||||
{!loading && !computed.monthlyFund && (
|
|
||||||
<div
|
|
||||||
className="text-muted"
|
|
||||||
style={{
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
textAlign: "center",
|
|
||||||
padding: "0.5rem 0",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Fond měsíce není k dispozici
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
@@ -608,90 +606,89 @@ export default function AttendanceHistory() {
|
|||||||
transition={{ duration: 0.25, delay: 0.12 }}
|
transition={{ duration: 0.25, delay: 0.12 }}
|
||||||
>
|
>
|
||||||
<div className="admin-card-body">
|
<div className="admin-card-body">
|
||||||
{loading && (
|
{isPending ? (
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
<div className="admin-loading">
|
||||||
{[0, 1, 2, 3, 4].map((i) => (
|
<div className="admin-spinner" />
|
||||||
<div key={i} className="admin-skeleton-row">
|
</div>
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
) : (
|
||||||
<div className="admin-skeleton-line w-1/3" />
|
<>
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
{records.length === 0 && (
|
||||||
|
<div className="admin-empty-state">
|
||||||
|
<p>Za tento měsíc nejsou žádné záznamy.</p>
|
||||||
</div>
|
</div>
|
||||||
))}
|
)}
|
||||||
</div>
|
{records.length > 0 && (
|
||||||
)}
|
<div className="admin-table-responsive">
|
||||||
{!loading && records.length === 0 && (
|
<table className="admin-table">
|
||||||
<div className="admin-empty-state">
|
<thead>
|
||||||
<p>Za tento měsíc nejsou žádné záznamy.</p>
|
<tr>
|
||||||
</div>
|
<th>Datum</th>
|
||||||
)}
|
<th>Typ</th>
|
||||||
{!loading && records.length > 0 && (
|
<th>Příchod</th>
|
||||||
<div className="admin-table-responsive">
|
<th>Pauza</th>
|
||||||
<table className="admin-table">
|
<th>Odchod</th>
|
||||||
<thead>
|
<th>Hodiny</th>
|
||||||
<tr>
|
<th>Projekty</th>
|
||||||
<th>Datum</th>
|
<th>Poznámka</th>
|
||||||
<th>Typ</th>
|
|
||||||
<th>Příchod</th>
|
|
||||||
<th>Pauza</th>
|
|
||||||
<th>Odchod</th>
|
|
||||||
<th>Hodiny</th>
|
|
||||||
<th>Projekty</th>
|
|
||||||
<th>Poznámka</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{records.map((record) => {
|
|
||||||
const leaveType = record.leave_type || "work";
|
|
||||||
const isLeave = leaveType !== "work";
|
|
||||||
const workMinutes = isLeave
|
|
||||||
? (Number(record.leave_hours) || 8) * 60
|
|
||||||
: calculateWorkMinutes(record);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<tr key={record.id}>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{formatDate(record.shift_date)}
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span
|
|
||||||
className={`attendance-leave-badge ${getLeaveTypeBadgeClass(leaveType)}`}
|
|
||||||
>
|
|
||||||
{getLeaveTypeName(leaveType)}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{isLeave ? "—" : formatDatetime(record.arrival_time)}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{isLeave ? "—" : formatBreakRange(record)}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{isLeave
|
|
||||||
? "—"
|
|
||||||
: formatDatetime(record.departure_time)}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{workMinutes > 0
|
|
||||||
? formatMinutes(workMinutes, true)
|
|
||||||
: "—"}
|
|
||||||
</td>
|
|
||||||
<td>{renderProjectCell(record)}</td>
|
|
||||||
<td
|
|
||||||
style={{
|
|
||||||
maxWidth: "150px",
|
|
||||||
overflow: "hidden",
|
|
||||||
textOverflow: "ellipsis",
|
|
||||||
whiteSpace: "nowrap",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{record.notes || ""}
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
);
|
</thead>
|
||||||
})}
|
<tbody>
|
||||||
</tbody>
|
{records.map((record) => {
|
||||||
</table>
|
const leaveType = record.leave_type || "work";
|
||||||
</div>
|
const isLeave = leaveType !== "work";
|
||||||
|
const workMinutes = isLeave
|
||||||
|
? (Number(record.leave_hours) || 8) * 60
|
||||||
|
: calculateWorkMinutes(record);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr key={record.id}>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{formatDate(record.shift_date)}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span
|
||||||
|
className={`attendance-leave-badge ${getLeaveTypeBadgeClass(leaveType)}`}
|
||||||
|
>
|
||||||
|
{getLeaveTypeName(leaveType)}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{isLeave
|
||||||
|
? "—"
|
||||||
|
: formatDatetime(record.arrival_time)}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{isLeave ? "—" : formatBreakRange(record)}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{isLeave
|
||||||
|
? "—"
|
||||||
|
: formatDatetime(record.departure_time)}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{workMinutes > 0
|
||||||
|
? formatMinutes(workMinutes, true)
|
||||||
|
: "—"}
|
||||||
|
</td>
|
||||||
|
<td>{renderProjectCell(record)}</td>
|
||||||
|
<td
|
||||||
|
style={{
|
||||||
|
maxWidth: "150px",
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{record.notes || ""}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
@@ -740,9 +737,7 @@ export default function AttendanceHistory() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(computed.vacationHours > 0 ||
|
{(computed.vacationHours > 0 || computed.sickHours > 0) && (
|
||||||
computed.sickHours > 0 ||
|
|
||||||
computed.holidayHours > 0) && (
|
|
||||||
<div className="leave-summary">
|
<div className="leave-summary">
|
||||||
{computed.vacationHours > 0 && (
|
{computed.vacationHours > 0 && (
|
||||||
<>
|
<>
|
||||||
@@ -758,13 +753,6 @@ export default function AttendanceHistory() {
|
|||||||
</span>{" "}
|
</span>{" "}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{computed.holidayHours > 0 && (
|
|
||||||
<>
|
|
||||||
<span className="leave-badge badge-holiday">
|
|
||||||
Svátek: {computed.holidayHours}h
|
|
||||||
</span>{" "}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useState, useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
@@ -9,65 +10,33 @@ import L from "leaflet";
|
|||||||
import "leaflet/dist/leaflet.css";
|
import "leaflet/dist/leaflet.css";
|
||||||
|
|
||||||
import { formatDate, formatTime } from "../utils/attendanceHelpers";
|
import { formatDate, formatTime } from "../utils/attendanceHelpers";
|
||||||
import apiFetch from "../utils/api";
|
import {
|
||||||
const API_BASE = "/api/admin";
|
attendanceLocationOptions,
|
||||||
|
type LocationRecord,
|
||||||
interface LocationRecord {
|
} from "../lib/queries/attendance";
|
||||||
user_name: string;
|
|
||||||
shift_date: string;
|
|
||||||
arrival_time?: string | null;
|
|
||||||
departure_time?: string | null;
|
|
||||||
arrival_lat?: string | number | null;
|
|
||||||
arrival_lng?: string | number | null;
|
|
||||||
arrival_accuracy?: number | null;
|
|
||||||
arrival_address?: string | null;
|
|
||||||
departure_lat?: string | number | null;
|
|
||||||
departure_lng?: string | number | null;
|
|
||||||
departure_accuracy?: number | null;
|
|
||||||
departure_address?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function AttendanceLocation() {
|
export default function AttendanceLocation() {
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const { hasPermission } = useAuth();
|
const { hasPermission } = useAuth();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [record, setRecord] = useState<LocationRecord | null>(null);
|
|
||||||
const mapRef = useRef<HTMLDivElement>(null);
|
const mapRef = useRef<HTMLDivElement>(null);
|
||||||
const mapInstanceRef = useRef<unknown>(null);
|
const mapInstanceRef = useRef<unknown>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
const locationQuery = useQuery(attendanceLocationOptions(id));
|
||||||
const fetchData = async () => {
|
const record = locationQuery.data ?? null;
|
||||||
try {
|
const isPending = locationQuery.isPending;
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/attendance?action=location&id=${id}`,
|
|
||||||
);
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
const raw = result.data.record || result.data;
|
|
||||||
// Enrich with user_name from nested users relation
|
|
||||||
const userName = raw.users
|
|
||||||
? `${raw.users.first_name} ${raw.users.last_name}`.trim()
|
|
||||||
: raw.user_name || "";
|
|
||||||
setRecord({ ...raw, user_name: userName });
|
|
||||||
} else {
|
|
||||||
alert.error("Záznam nebyl nalezen");
|
|
||||||
navigate("/attendance/admin");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Nepodařilo se načíst data");
|
|
||||||
navigate("/attendance/admin");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchData();
|
// Navigate away on fetch error
|
||||||
}, [id, alert, navigate]);
|
useEffect(() => {
|
||||||
|
if (locationQuery.error) {
|
||||||
|
alert.error("Nepodařilo se načíst data");
|
||||||
|
navigate("/attendance/admin");
|
||||||
|
}
|
||||||
|
}, [locationQuery.error]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!record || loading) return;
|
if (!record || isPending) return;
|
||||||
|
|
||||||
const hasArrivalLocation = record.arrival_lat && record.arrival_lng;
|
const hasArrivalLocation = record.arrival_lat && record.arrival_lng;
|
||||||
const hasDepartureLocation = record.departure_lat && record.departure_lng;
|
const hasDepartureLocation = record.departure_lat && record.departure_lng;
|
||||||
@@ -175,7 +144,7 @@ export default function AttendanceLocation() {
|
|||||||
mapInstanceRef.current = null;
|
mapInstanceRef.current = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, [record, loading]);
|
}, [record, isPending]);
|
||||||
|
|
||||||
const formatDatetimeLocal = (datetime: string | null | undefined): string => {
|
const formatDatetimeLocal = (datetime: string | null | undefined): string => {
|
||||||
if (!datetime) return "—";
|
if (!datetime) return "—";
|
||||||
@@ -183,57 +152,7 @@ export default function AttendanceLocation() {
|
|||||||
return `${d.getDate()}.${d.getMonth() + 1}.${d.getFullYear()} ${formatTime(datetime)}`;
|
return `${d.getDate()}.${d.getMonth() + 1}.${d.getFullYear()} ${formatTime(datetime)}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!hasPermission("attendance.admin")) return <Forbidden />;
|
if (!hasPermission("attendance.manage")) return <Forbidden />;
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "32px", height: "32px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "200px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "100%", height: "300px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "grid",
|
|
||||||
gridTemplateColumns: "1fr 1fr",
|
|
||||||
gap: "1.25rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{[0, 1].map((i) => (
|
|
||||||
<div key={i} className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "50%" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line w-full" />
|
|
||||||
<div className="admin-skeleton-line w-3/4" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!record) {
|
if (!record) {
|
||||||
return null;
|
return null;
|
||||||
@@ -247,6 +166,14 @@ export default function AttendanceLocation() {
|
|||||||
: record.shift_date;
|
: record.shift_date;
|
||||||
const month = shiftDateStr.substring(0, 7);
|
const month = shiftDateStr.substring(0, 7);
|
||||||
|
|
||||||
|
if (isPending) {
|
||||||
|
return (
|
||||||
|
<div className="admin-loading">
|
||||||
|
<div className="admin-spinner" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<motion.div
|
<motion.div
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
import Pagination from "../components/Pagination";
|
import Pagination from "../components/Pagination";
|
||||||
import FormField from "../components/FormField";
|
import FormField from "../components/FormField";
|
||||||
|
import FormModal from "../components/FormModal";
|
||||||
import AdminDatePicker from "../components/AdminDatePicker";
|
import AdminDatePicker from "../components/AdminDatePicker";
|
||||||
import { czechPlural } from "../utils/formatters";
|
import { czechPlural } from "../utils/formatters";
|
||||||
import apiFetch from "../utils/api";
|
import apiFetch from "../utils/api";
|
||||||
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
|
|
||||||
const API_BASE = "/api/admin";
|
const API_BASE = "/api/admin";
|
||||||
|
|
||||||
@@ -57,6 +60,9 @@ const ENTITY_TYPE_LABELS: Record<string, string> = {
|
|||||||
trips: "Jízda",
|
trips: "Jízda",
|
||||||
vehicles: "Vozidlo",
|
vehicles: "Vozidlo",
|
||||||
bank_account: "Bankovní účet",
|
bank_account: "Bankovní účet",
|
||||||
|
work_plan_entry: "Plán prací – záznam",
|
||||||
|
work_plan_override: "Plán prací – přepsání dne",
|
||||||
|
plan_category: "Plán prací – kategorie",
|
||||||
};
|
};
|
||||||
|
|
||||||
const ACTION_OPTIONS = Object.entries(ACTION_LABELS).map(([value, label]) => ({
|
const ACTION_OPTIONS = Object.entries(ACTION_LABELS).map(([value, label]) => ({
|
||||||
@@ -77,13 +83,6 @@ interface AuditLogEntry {
|
|||||||
user_ip: string | null;
|
user_ip: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PaginationData {
|
|
||||||
total: number;
|
|
||||||
page: number;
|
|
||||||
per_page: number;
|
|
||||||
total_pages: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Filters {
|
interface Filters {
|
||||||
search: string;
|
search: string;
|
||||||
action: string;
|
action: string;
|
||||||
@@ -95,9 +94,6 @@ interface Filters {
|
|||||||
export default function AuditLog() {
|
export default function AuditLog() {
|
||||||
const { hasPermission } = useAuth();
|
const { hasPermission } = useAuth();
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const [logs, setLogs] = useState<AuditLogEntry[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [pagination, setPagination] = useState<PaginationData | null>(null);
|
|
||||||
const [filters, setFilters] = useState<Filters>({
|
const [filters, setFilters] = useState<Filters>({
|
||||||
search: "",
|
search: "",
|
||||||
action: "",
|
action: "",
|
||||||
@@ -105,90 +101,97 @@ export default function AuditLog() {
|
|||||||
date_from: "",
|
date_from: "",
|
||||||
date_to: "",
|
date_to: "",
|
||||||
});
|
});
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [perPage, setPerPage] = useState(50);
|
||||||
const [showCleanup, setShowCleanup] = useState(false);
|
const [showCleanup, setShowCleanup] = useState(false);
|
||||||
const [cleanupDays, setCleanupDays] = useState(90);
|
const [cleanupDays, setCleanupDays] = useState(90);
|
||||||
const [cleaning, setCleaning] = useState(false);
|
|
||||||
|
|
||||||
const fetchLogs = useCallback(
|
const { data: logsData, isPending } = useQuery({
|
||||||
async (page = 1, perPage = 50) => {
|
queryKey: [
|
||||||
setLoading(true);
|
"audit-log",
|
||||||
try {
|
{
|
||||||
const params = new URLSearchParams({
|
search: filters.search,
|
||||||
page: String(page),
|
action: filters.action,
|
||||||
per_page: String(perPage),
|
entityType: filters.entity_type,
|
||||||
});
|
dateFrom: filters.date_from,
|
||||||
|
dateTo: filters.date_to,
|
||||||
|
page,
|
||||||
|
perPage,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
queryFn: async () => {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
page: String(page),
|
||||||
|
per_page: String(perPage),
|
||||||
|
});
|
||||||
|
if (filters.search) params.set("search", filters.search);
|
||||||
|
if (filters.action) params.set("action", filters.action);
|
||||||
|
if (filters.entity_type) params.set("entity_type", filters.entity_type);
|
||||||
|
if (filters.date_from) params.set("date_from", filters.date_from);
|
||||||
|
if (filters.date_to) params.set("date_to", filters.date_to);
|
||||||
|
|
||||||
if (filters.search) params.set("search", filters.search);
|
const response = await apiFetch(
|
||||||
if (filters.action) params.set("action", filters.action);
|
`${API_BASE}/audit-log?${params.toString()}`,
|
||||||
if (filters.entity_type) params.set("entity_type", filters.entity_type);
|
);
|
||||||
if (filters.date_from) params.set("date_from", filters.date_from);
|
if (response.status === 401) throw new Error("Unauthorized");
|
||||||
if (filters.date_to) params.set("date_to", filters.date_to);
|
const result = await response.json();
|
||||||
|
if (!result.success)
|
||||||
const response = await apiFetch(
|
throw new Error(result.error || "Nepodařilo se načíst audit log");
|
||||||
`${API_BASE}/audit-log?${params.toString()}`,
|
return {
|
||||||
);
|
data: Array.isArray(result.data) ? result.data : [],
|
||||||
const data = await response.json();
|
pagination: {
|
||||||
|
total: result.pagination?.total ?? 0,
|
||||||
if (data.success) {
|
page: result.pagination?.page ?? 1,
|
||||||
setLogs(Array.isArray(data.data) ? data.data : []);
|
per_page: result.pagination?.limit ?? perPage,
|
||||||
setPagination({
|
total_pages: result.pagination?.total_pages ?? 1,
|
||||||
total: data.pagination?.total ?? 0,
|
},
|
||||||
page: data.pagination?.page ?? 1,
|
};
|
||||||
per_page: data.pagination?.limit ?? 50,
|
|
||||||
total_pages: data.pagination?.total_pages ?? 1,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
alert.error(data.error || "Nepodařilo se načíst audit log");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
[filters, alert],
|
});
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
const logs: AuditLogEntry[] = logsData?.data ?? [];
|
||||||
fetchLogs();
|
const pagination = logsData?.pagination ?? null;
|
||||||
}, [fetchLogs]);
|
|
||||||
|
|
||||||
if (!hasPermission("settings.audit")) {
|
if (!hasPermission("settings.audit")) {
|
||||||
return <Forbidden />;
|
return <Forbidden />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const cleanupMutation = useApiMutation<
|
||||||
|
{ days: number; confirm?: string },
|
||||||
|
{ message?: string; error?: string }
|
||||||
|
>({
|
||||||
|
url: () => `${API_BASE}/audit-log/cleanup`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["audit-log"],
|
||||||
|
onSuccess: (data) => {
|
||||||
|
alert.success(data?.message || "Hotovo");
|
||||||
|
setShowCleanup(false);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const handleFilterChange = (key: keyof Filters, value: string) => {
|
const handleFilterChange = (key: keyof Filters, value: string) => {
|
||||||
setFilters((prev) => ({ ...prev, [key]: value }));
|
setFilters((prev) => ({ ...prev, [key]: value }));
|
||||||
|
setPage(1);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePageChange = (newPage: number) => {
|
const handlePageChange = (newPage: number) => {
|
||||||
fetchLogs(newPage, pagination?.per_page || 50);
|
setPage(newPage);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePerPageChange = (newPerPage: number) => {
|
const handlePerPageChange = (newPerPage: number) => {
|
||||||
fetchLogs(1, newPerPage);
|
setPage(1);
|
||||||
|
setPerPage(newPerPage);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCleanup = async () => {
|
const handleCleanup = async () => {
|
||||||
setCleaning(true);
|
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/audit-log/cleanup`, {
|
// Backend requires this literal confirmation token when wiping everything.
|
||||||
method: "POST",
|
await cleanupMutation.mutateAsync({
|
||||||
headers: { "Content-Type": "application/json" },
|
days: cleanupDays,
|
||||||
body: JSON.stringify({ days: cleanupDays }),
|
...(cleanupDays === 0 ? { confirm: "DELETE_ALL_AUDIT" } : {}),
|
||||||
});
|
});
|
||||||
const data = await response.json();
|
} catch (e) {
|
||||||
if (data.success) {
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
alert.success(data.message);
|
|
||||||
setShowCleanup(false);
|
|
||||||
fetchLogs();
|
|
||||||
} else {
|
|
||||||
alert.error(data.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
|
||||||
setCleaning(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -197,65 +200,10 @@ export default function AuditLog() {
|
|||||||
return new Date(dateString).toLocaleString("cs-CZ");
|
return new Date(dateString).toLocaleString("cs-CZ");
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading && logs.length === 0) {
|
if (isPending && logs.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
<div className="admin-loading">
|
||||||
<div
|
<div className="admin-spinner" />
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "160px", marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line" style={{ width: "100px" }} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton"
|
|
||||||
style={{ gap: "0.75rem", padding: "1rem" }}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "100%", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "100%", borderRadius: "4px" }}
|
|
||||||
/>
|
|
||||||
{Array.from({ length: 8 }, (_, i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "120px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "80px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "70px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "80px" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line flex-1" />
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "90px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -296,78 +244,36 @@ export default function AuditLog() {
|
|||||||
</button>
|
</button>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
{showCleanup && (
|
<FormModal
|
||||||
<div className="admin-modal-overlay" style={{ opacity: 1 }}>
|
isOpen={showCleanup}
|
||||||
<div
|
onClose={() => !cleanupMutation.isPending && setShowCleanup(false)}
|
||||||
className="admin-modal-backdrop"
|
onSubmit={handleCleanup}
|
||||||
onClick={() => !cleaning && setShowCleanup(false)}
|
title="Vyčistit audit log"
|
||||||
/>
|
submitLabel="Smazat"
|
||||||
<motion.div
|
loading={cleanupMutation.isPending}
|
||||||
className="admin-modal admin-confirm-modal"
|
>
|
||||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
<p className="admin-confirm-message">Smazat záznamy starší než:</p>
|
||||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
<div style={{ margin: "0.75rem 0", maxWidth: "200px" }}>
|
||||||
transition={{ duration: 0.2 }}
|
<select
|
||||||
|
className="admin-form-select"
|
||||||
|
value={cleanupDays}
|
||||||
|
onChange={(e) => setCleanupDays(parseInt(e.target.value))}
|
||||||
>
|
>
|
||||||
<div className="admin-modal-body admin-confirm-content">
|
<option value={30}>30 dní</option>
|
||||||
<div className="admin-confirm-icon admin-confirm-icon-danger">
|
<option value={60}>60 dní</option>
|
||||||
<svg
|
<option value={90}>90 dní</option>
|
||||||
width="24"
|
<option value={180}>180 dní</option>
|
||||||
height="24"
|
<option value={365}>1 rok</option>
|
||||||
viewBox="0 0 24 24"
|
<option value={0}>Vše</option>
|
||||||
fill="none"
|
</select>
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
>
|
|
||||||
<polyline points="3 6 5 6 21 6" />
|
|
||||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<h2 className="admin-confirm-title">Vyčistit audit log</h2>
|
|
||||||
<p className="admin-confirm-message">
|
|
||||||
Smazat záznamy starší než:
|
|
||||||
</p>
|
|
||||||
<div style={{ margin: "0.75rem auto", maxWidth: "200px" }}>
|
|
||||||
<select
|
|
||||||
className="admin-form-select"
|
|
||||||
value={cleanupDays}
|
|
||||||
onChange={(e) => setCleanupDays(parseInt(e.target.value))}
|
|
||||||
>
|
|
||||||
<option value={30}>30 dní</option>
|
|
||||||
<option value={60}>60 dní</option>
|
|
||||||
<option value={90}>90 dní</option>
|
|
||||||
<option value={180}>180 dní</option>
|
|
||||||
<option value={365}>1 rok</option>
|
|
||||||
<option value={0}>Vše</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<p
|
|
||||||
className="admin-confirm-message"
|
|
||||||
style={{ fontSize: "12px", opacity: 0.6 }}
|
|
||||||
>
|
|
||||||
Tato akce je nevratná.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="admin-modal-footer">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowCleanup(false)}
|
|
||||||
className="admin-btn admin-btn-secondary"
|
|
||||||
disabled={cleaning}
|
|
||||||
>
|
|
||||||
Zrušit
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleCleanup}
|
|
||||||
className="admin-btn admin-btn-primary"
|
|
||||||
disabled={cleaning}
|
|
||||||
>
|
|
||||||
{cleaning ? "Mažu..." : "Smazat"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</motion.div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
<p
|
||||||
|
className="admin-confirm-message"
|
||||||
|
style={{ fontSize: "12px", opacity: 0.6 }}
|
||||||
|
>
|
||||||
|
Tato akce je nevratná.
|
||||||
|
</p>
|
||||||
|
</FormModal>
|
||||||
|
|
||||||
<motion.div
|
<motion.div
|
||||||
className="admin-card mb-4"
|
className="admin-card mb-4"
|
||||||
@@ -442,112 +348,73 @@ export default function AuditLog() {
|
|||||||
>
|
>
|
||||||
<div className="admin-card-body">
|
<div className="admin-card-body">
|
||||||
<div className="admin-table-responsive">
|
<div className="admin-table-responsive">
|
||||||
<table className="admin-table">
|
{isPending ? (
|
||||||
<thead>
|
<div className="admin-loading">
|
||||||
<tr>
|
<div className="admin-spinner" />
|
||||||
<th>Čas</th>
|
</div>
|
||||||
<th>Uživatel</th>
|
) : (
|
||||||
<th>Akce</th>
|
<table className="admin-table">
|
||||||
<th>Typ entity</th>
|
<thead>
|
||||||
<th>Popis</th>
|
|
||||||
<th>IP</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{loading &&
|
|
||||||
Array.from({ length: 10 }, (_, i) => (
|
|
||||||
<tr key={`skeleton-${i}`}>
|
|
||||||
<td>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "110px", height: "14px" }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "80px", height: "14px" }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "70px",
|
|
||||||
height: "22px",
|
|
||||||
borderRadius: "10px",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "80px", height: "14px" }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "60%", height: "14px" }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "90px", height: "14px" }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
{!loading && logs.length === 0 && (
|
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={6}>
|
<th>Čas</th>
|
||||||
<div className="admin-empty-state">
|
<th>Uživatel</th>
|
||||||
<div className="admin-empty-icon">
|
<th>Akce</th>
|
||||||
<svg
|
<th>Typ entity</th>
|
||||||
width="28"
|
<th>Popis</th>
|
||||||
height="28"
|
<th>IP</th>
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
>
|
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
|
||||||
<polyline points="14 2 14 8 20 8" />
|
|
||||||
<line x1="16" y1="13" x2="8" y2="13" />
|
|
||||||
<line x1="16" y1="17" x2="8" y2="17" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<p>Žádné záznamy k zobrazení</p>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
)}
|
</thead>
|
||||||
{!loading &&
|
<tbody>
|
||||||
logs.map((log) => (
|
{logs.length === 0 && (
|
||||||
<tr key={log.id}>
|
<tr>
|
||||||
<td className="admin-mono">
|
<td colSpan={6}>
|
||||||
{formatDatetime(log.created_at)}
|
<div className="admin-empty-state">
|
||||||
|
<div className="admin-empty-icon">
|
||||||
|
<svg
|
||||||
|
width="28"
|
||||||
|
height="28"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
>
|
||||||
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||||
|
<polyline points="14 2 14 8 20 8" />
|
||||||
|
<line x1="16" y1="13" x2="8" y2="13" />
|
||||||
|
<line x1="16" y1="17" x2="8" y2="17" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<p>Žádné záznamy k zobrazení</p>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="fw-500">{log.username || "-"}</td>
|
|
||||||
<td>
|
|
||||||
<span
|
|
||||||
className={`admin-badge ${ACTION_BADGE_CLASS[log.action] || "admin-badge-secondary"}`}
|
|
||||||
>
|
|
||||||
{ACTION_LABELS[log.action] || log.action}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
{ENTITY_TYPE_LABELS[log.entity_type || ""] ||
|
|
||||||
log.entity_type ||
|
|
||||||
"-"}
|
|
||||||
</td>
|
|
||||||
<td>{log.description || "-"}</td>
|
|
||||||
<td className="admin-mono">{log.user_ip || "-"}</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
)}
|
||||||
</tbody>
|
{logs.length > 0 &&
|
||||||
</table>
|
logs.map((log) => (
|
||||||
|
<tr key={log.id}>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{formatDatetime(log.created_at)}
|
||||||
|
</td>
|
||||||
|
<td className="fw-500">{log.username || "-"}</td>
|
||||||
|
<td>
|
||||||
|
<span
|
||||||
|
className={`admin-badge ${ACTION_BADGE_CLASS[log.action] || "admin-badge-secondary"}`}
|
||||||
|
>
|
||||||
|
{ACTION_LABELS[log.action] || log.action}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{ENTITY_TYPE_LABELS[log.entity_type || ""] ||
|
||||||
|
log.entity_type ||
|
||||||
|
"-"}
|
||||||
|
</td>
|
||||||
|
<td>{log.description || "-"}</td>
|
||||||
|
<td className="admin-mono">{log.user_ip || "-"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Pagination
|
<Pagination
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,15 @@
|
|||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState, useCallback } from "react";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import useModalLock from "../hooks/useModalLock";
|
import useModalLock from "../hooks/useModalLock";
|
||||||
import apiFetch from "../utils/api";
|
import apiFetch from "../utils/api";
|
||||||
|
import { dashboardOptions } from "../lib/queries/dashboard";
|
||||||
|
import { require2FAOptions } from "../lib/queries/settings";
|
||||||
import { getCzechDate } from "../utils/dashboardHelpers";
|
import { getCzechDate } from "../utils/dashboardHelpers";
|
||||||
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
import DashKpiCards from "../components/dashboard/DashKpiCards";
|
import DashKpiCards from "../components/dashboard/DashKpiCards";
|
||||||
import DashQuickActions from "../components/dashboard/DashQuickActions";
|
import DashQuickActions from "../components/dashboard/DashQuickActions";
|
||||||
import DashActivityFeed from "../components/dashboard/DashActivityFeed";
|
import DashActivityFeed from "../components/dashboard/DashActivityFeed";
|
||||||
@@ -69,13 +73,26 @@ export default function Dashboard() {
|
|||||||
const { user, updateUser, hasPermission } = useAuth();
|
const { user, updateUser, hasPermission } = useAuth();
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
|
|
||||||
const [dashData, setDashData] = useState<DashData | null>(null);
|
|
||||||
const [dashLoading, setDashLoading] = useState(true);
|
|
||||||
const [punching, setPunching] = useState(false);
|
const [punching, setPunching] = useState(false);
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { data: dashDataRaw, isPending: dashLoading } =
|
||||||
|
useQuery(dashboardOptions());
|
||||||
|
const dashData = dashDataRaw as DashData | undefined;
|
||||||
|
const { data: totpData, isPending: totpLoading } =
|
||||||
|
useQuery(require2FAOptions());
|
||||||
|
const totpEnabled = totpData?.require_2fa ?? !!user?.totpEnabled;
|
||||||
|
|
||||||
|
const punchMutation = useApiMutation<
|
||||||
|
Record<string, unknown>,
|
||||||
|
{ message?: string }
|
||||||
|
>({
|
||||||
|
url: () => `${API_BASE}/attendance`,
|
||||||
|
method: () => "POST",
|
||||||
|
invalidate: ["attendance", "dashboard"],
|
||||||
|
});
|
||||||
|
|
||||||
// 2FA state - sdileny mezi profilem a bannerem
|
// 2FA state - sdileny mezi profilem a bannerem
|
||||||
const [totpEnabled, setTotpEnabled] = useState(false);
|
|
||||||
const [totpLoading, setTotpLoading] = useState(true);
|
|
||||||
const [show2FASetup, setShow2FASetup] = useState(false);
|
const [show2FASetup, setShow2FASetup] = useState(false);
|
||||||
const [show2FADisable, setShow2FADisable] = useState(false);
|
const [show2FADisable, setShow2FADisable] = useState(false);
|
||||||
const [totpSecret, setTotpSecret] = useState<string | null>(null);
|
const [totpSecret, setTotpSecret] = useState<string | null>(null);
|
||||||
@@ -88,46 +105,6 @@ export default function Dashboard() {
|
|||||||
useModalLock(show2FASetup);
|
useModalLock(show2FASetup);
|
||||||
useModalLock(show2FADisable);
|
useModalLock(show2FADisable);
|
||||||
|
|
||||||
const fetchDashboard = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(`${API_BASE}/dashboard`);
|
|
||||||
const data = await response.json();
|
|
||||||
if (data.success !== false) {
|
|
||||||
setDashData(data.data || data);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
if (import.meta.env.DEV) {
|
|
||||||
console.error("Dashboard fetch error:", err);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setDashLoading(false);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchDashboard();
|
|
||||||
}, [fetchDashboard]);
|
|
||||||
|
|
||||||
// 2FA status fetch
|
|
||||||
const fetch2FAStatus = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(`${API_BASE}/totp/setup`);
|
|
||||||
const data = await response.json();
|
|
||||||
if (data.success) {
|
|
||||||
setTotpEnabled(!!user?.totpEnabled);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// 2FA status fetch failed silently
|
|
||||||
setTotpEnabled(!!user?.totpEnabled);
|
|
||||||
} finally {
|
|
||||||
setTotpLoading(false);
|
|
||||||
}
|
|
||||||
}, [user?.totpEnabled]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetch2FAStatus();
|
|
||||||
}, [fetch2FAStatus]);
|
|
||||||
|
|
||||||
// Punch (prichod/odchod) primo z dashboardu
|
// Punch (prichod/odchod) primo z dashboardu
|
||||||
const handleQuickPunch = useCallback(() => {
|
const handleQuickPunch = useCallback(() => {
|
||||||
const action = dashData?.my_shift?.has_ongoing ? "departure" : "arrival";
|
const action = dashData?.my_shift?.has_ongoing ? "departure" : "arrival";
|
||||||
@@ -135,20 +112,13 @@ export default function Dashboard() {
|
|||||||
|
|
||||||
const submitPunch = async (gpsData: Record<string, unknown> = {}) => {
|
const submitPunch = async (gpsData: Record<string, unknown> = {}) => {
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/attendance`, {
|
const result = await punchMutation.mutateAsync({
|
||||||
method: "POST",
|
punch_action: action,
|
||||||
headers: { "Content-Type": "application/json" },
|
...gpsData,
|
||||||
body: JSON.stringify({ punch_action: action, ...gpsData }),
|
|
||||||
});
|
});
|
||||||
const result = await response.json();
|
alert.success(result?.message || "Docházka zaznamenána");
|
||||||
if (result.success) {
|
} catch (e) {
|
||||||
alert.success(result.data?.message || "Docházka zaznamenána");
|
alert.error(e instanceof Error ? e.message : "Chyba pripojeni");
|
||||||
fetchDashboard();
|
|
||||||
} else {
|
|
||||||
alert.error(result.error || "Chyba při záznamu docházky");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba pripojeni");
|
|
||||||
} finally {
|
} finally {
|
||||||
setPunching(false);
|
setPunching(false);
|
||||||
}
|
}
|
||||||
@@ -167,7 +137,7 @@ export default function Dashboard() {
|
|||||||
() => submitPunch({}),
|
() => submitPunch({}),
|
||||||
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 },
|
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 },
|
||||||
);
|
);
|
||||||
}, [dashData, alert, fetchDashboard]);
|
}, [dashData, alert, punchMutation]);
|
||||||
|
|
||||||
// 2FA handlery
|
// 2FA handlery
|
||||||
const handleStart2FASetup = async () => {
|
const handleStart2FASetup = async () => {
|
||||||
@@ -202,7 +172,9 @@ export default function Dashboard() {
|
|||||||
});
|
});
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setTotpEnabled(true);
|
queryClient.invalidateQueries({ queryKey: ["settings"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||||
setBackupCodes(data.data?.backup_codes || null);
|
setBackupCodes(data.data?.backup_codes || null);
|
||||||
setTotpSecret(null);
|
setTotpSecret(null);
|
||||||
setTotpQrUri(null);
|
setTotpQrUri(null);
|
||||||
@@ -230,7 +202,9 @@ export default function Dashboard() {
|
|||||||
});
|
});
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setTotpEnabled(false);
|
queryClient.invalidateQueries({ queryKey: ["settings"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||||
setShow2FADisable(false);
|
setShow2FADisable(false);
|
||||||
setDisableCode("");
|
setDisableCode("");
|
||||||
updateUser({ totpEnabled: false });
|
updateUser({ totpEnabled: false });
|
||||||
@@ -335,63 +309,10 @@ export default function Dashboard() {
|
|||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Skeleton loading */}
|
{/* Loading spinner */}
|
||||||
{dashLoading && (
|
{dashLoading && (
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.25rem" }}>
|
<div className="admin-loading">
|
||||||
<div className="admin-kpi-grid admin-kpi-4">
|
<div className="admin-spinner" />
|
||||||
{[0, 1, 2, 3].map((i) => (
|
|
||||||
<div
|
|
||||||
key={i}
|
|
||||||
className="admin-skeleton-line h-24"
|
|
||||||
style={{ borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="dash-quick-actions">
|
|
||||||
{[0, 1, 2, 3].map((i) => (
|
|
||||||
<div
|
|
||||||
key={i}
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ height: "52px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="dash-main-grid">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ height: "320px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ height: "320px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
gap: "1.25rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ height: "150px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ height: "150px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="dash-bottom">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ height: "200px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ height: "200px", borderRadius: "10px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -400,12 +321,14 @@ export default function Dashboard() {
|
|||||||
(hasPermission("offers.view") ||
|
(hasPermission("offers.view") ||
|
||||||
hasPermission("invoices.view") ||
|
hasPermission("invoices.view") ||
|
||||||
hasPermission("projects.view") ||
|
hasPermission("projects.view") ||
|
||||||
hasPermission("orders.view")) && <DashKpiCards dashData={dashData} />}
|
hasPermission("orders.view")) && (
|
||||||
|
<DashKpiCards dashData={dashData ?? null} />
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Quick actions */}
|
{/* Quick actions */}
|
||||||
{!dashLoading && (
|
{!dashLoading && (
|
||||||
<DashQuickActions
|
<DashQuickActions
|
||||||
dashData={dashData}
|
dashData={dashData ?? null}
|
||||||
punching={punching}
|
punching={punching}
|
||||||
onPunch={handleQuickPunch}
|
onPunch={handleQuickPunch}
|
||||||
/>
|
/>
|
||||||
@@ -423,7 +346,7 @@ export default function Dashboard() {
|
|||||||
<DashActivityFeed activities={dashData?.recent_activity ?? null} />
|
<DashActivityFeed activities={dashData?.recent_activity ?? null} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{hasPermission("attendance.admin") && (
|
{hasPermission("attendance.manage") && (
|
||||||
<DashAttendanceToday attendance={dashData?.attendance ?? null} />
|
<DashAttendanceToday attendance={dashData?.attendance ?? null} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import {
|
|||||||
useParams,
|
useParams,
|
||||||
Link,
|
Link,
|
||||||
} from "react-router-dom";
|
} from "react-router-dom";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import DOMPurify from "dompurify";
|
import DOMPurify from "dompurify";
|
||||||
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
@@ -35,6 +37,17 @@ import {
|
|||||||
} from "@dnd-kit/modifiers";
|
} from "@dnd-kit/modifiers";
|
||||||
import { CSS } from "@dnd-kit/utilities";
|
import { CSS } from "@dnd-kit/utilities";
|
||||||
import apiFetch from "../utils/api";
|
import apiFetch from "../utils/api";
|
||||||
|
import {
|
||||||
|
companySettingsOptions,
|
||||||
|
type CompanySettingsData,
|
||||||
|
} from "../lib/queries/settings";
|
||||||
|
import {
|
||||||
|
invoiceDetailOptions,
|
||||||
|
type InvoiceDetail,
|
||||||
|
} from "../lib/queries/invoices";
|
||||||
|
import { offerCustomersOptions, type Customer } from "../lib/queries/offers";
|
||||||
|
import { bankAccountsOptions, type BankAccount } from "../lib/queries/common";
|
||||||
|
import { jsonQuery } from "../lib/apiAdapter";
|
||||||
import { formatCurrency, formatDate } from "../utils/formatters";
|
import { formatCurrency, formatDate } from "../utils/formatters";
|
||||||
|
|
||||||
const API_BASE = "/api/admin";
|
const API_BASE = "/api/admin";
|
||||||
@@ -60,29 +73,13 @@ interface InvoiceItem {
|
|||||||
id?: number;
|
id?: number;
|
||||||
_key: string;
|
_key: string;
|
||||||
description: string;
|
description: string;
|
||||||
|
item_description: string;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
unit: string;
|
unit: string;
|
||||||
unit_price: number;
|
unit_price: number;
|
||||||
vat_rate: number;
|
vat_rate: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Customer {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
company_id?: string;
|
|
||||||
city?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BankAccount {
|
|
||||||
id: number;
|
|
||||||
account_name: string;
|
|
||||||
account_number?: string;
|
|
||||||
bank_name?: string;
|
|
||||||
bic?: string;
|
|
||||||
iban?: string;
|
|
||||||
is_default?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InvoiceForm {
|
interface InvoiceForm {
|
||||||
customer_id: number | null;
|
customer_id: number | null;
|
||||||
customer_name: string;
|
customer_name: string;
|
||||||
@@ -106,42 +103,6 @@ interface InvoiceForm {
|
|||||||
bank_account: string;
|
bank_account: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface InvoiceCustomer {
|
|
||||||
company_id?: string;
|
|
||||||
vat_id?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Invoice {
|
|
||||||
id: number;
|
|
||||||
invoice_number: string;
|
|
||||||
customer_id?: number | null;
|
|
||||||
customer_name: string | null;
|
|
||||||
customer?: InvoiceCustomer;
|
|
||||||
order_id?: number;
|
|
||||||
order_number?: string;
|
|
||||||
currency: string;
|
|
||||||
status: string;
|
|
||||||
issue_date: string;
|
|
||||||
due_date: string;
|
|
||||||
tax_date: string;
|
|
||||||
payment_method: string;
|
|
||||||
constant_symbol?: string;
|
|
||||||
issued_by: string | null;
|
|
||||||
paid_date?: string;
|
|
||||||
notes: string;
|
|
||||||
language: string;
|
|
||||||
apply_vat: number | string;
|
|
||||||
vat_rate?: number;
|
|
||||||
billing_text?: string;
|
|
||||||
bank_name?: string;
|
|
||||||
bank_swift?: string;
|
|
||||||
bank_iban?: string;
|
|
||||||
bank_account?: string;
|
|
||||||
bank_account_id?: number | null;
|
|
||||||
items: Omit<InvoiceItem, "_key">[];
|
|
||||||
valid_transitions?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sortable row for create mode
|
// Sortable row for create mode
|
||||||
function SortableInvoiceRow({
|
function SortableInvoiceRow({
|
||||||
item,
|
item,
|
||||||
@@ -205,20 +166,34 @@ function SortableInvoiceRow({
|
|||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
<td className="text-tertiary text-center fw-500">{index + 1}</td>
|
<td className="text-tertiary text-center fw-500">{index + 1}</td>
|
||||||
<td>
|
<td style={{ verticalAlign: "top" }}>
|
||||||
<input
|
<div
|
||||||
type="text"
|
style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}
|
||||||
value={item.description}
|
>
|
||||||
onChange={(e) => onUpdate(index, "description", e.target.value)}
|
<input
|
||||||
className="admin-form-input fw-500"
|
type="text"
|
||||||
placeholder="Popis položky..."
|
value={item.description}
|
||||||
/>
|
onChange={(e) => onUpdate(index, "description", e.target.value)}
|
||||||
|
className="admin-form-input fw-500"
|
||||||
|
placeholder="Popis položky..."
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={item.item_description}
|
||||||
|
onChange={(e) =>
|
||||||
|
onUpdate(index, "item_description", e.target.value)
|
||||||
|
}
|
||||||
|
className="admin-form-input"
|
||||||
|
placeholder="Podrobný popis (volitelný)"
|
||||||
|
style={{ fontSize: "0.8rem", opacity: 0.8 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
value={item.quantity}
|
value={item.quantity}
|
||||||
onChange={(e) => onUpdate(index, "quantity", e.target.value)}
|
onChange={(e) => onUpdate(index, "quantity", Number(e.target.value))}
|
||||||
className="admin-form-input"
|
className="admin-form-input"
|
||||||
min="0"
|
min="0"
|
||||||
step="any"
|
step="any"
|
||||||
@@ -247,7 +222,9 @@ function SortableInvoiceRow({
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
value={item.unit_price}
|
value={item.unit_price}
|
||||||
onChange={(e) => onUpdate(index, "unit_price", e.target.value)}
|
onChange={(e) =>
|
||||||
|
onUpdate(index, "unit_price", Number(e.target.value))
|
||||||
|
}
|
||||||
className="admin-form-input"
|
className="admin-form-input"
|
||||||
step="any"
|
step="any"
|
||||||
style={{
|
style={{
|
||||||
@@ -318,6 +295,7 @@ export default function InvoiceDetail() {
|
|||||||
(): InvoiceItem => ({
|
(): InvoiceItem => ({
|
||||||
_key: `inv-${++keyCounterRef.current}`,
|
_key: `inv-${++keyCounterRef.current}`,
|
||||||
description: "",
|
description: "",
|
||||||
|
item_description: "",
|
||||||
quantity: 1,
|
quantity: 1,
|
||||||
unit: "ks",
|
unit: "ks",
|
||||||
unit_price: 0,
|
unit_price: 0,
|
||||||
@@ -367,12 +345,12 @@ export default function InvoiceDetail() {
|
|||||||
bank_account: "",
|
bank_account: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
const [bankAccounts, setBankAccounts] = useState<BankAccount[]>([]);
|
|
||||||
const [dueDays, setDueDays] = useState(14);
|
const [dueDays, setDueDays] = useState(14);
|
||||||
const [items, setItems] = useState<InvoiceItem[]>([
|
const [items, setItems] = useState<InvoiceItem[]>([
|
||||||
{
|
{
|
||||||
_key: "inv-1",
|
_key: "inv-1",
|
||||||
description: "",
|
description: "",
|
||||||
|
item_description: "",
|
||||||
quantity: 1,
|
quantity: 1,
|
||||||
unit: "ks",
|
unit: "ks",
|
||||||
unit_price: 0,
|
unit_price: 0,
|
||||||
@@ -381,44 +359,30 @@ export default function InvoiceDetail() {
|
|||||||
]);
|
]);
|
||||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [loading, setLoading] = useState(true);
|
const [dataReady, setDataReady] = useState(false);
|
||||||
const [invoiceNumber, setInvoiceNumber] = useState("");
|
const [invoiceNumber, setInvoiceNumber] = useState("");
|
||||||
const initialSnapshotRef = useRef<string | null>(null);
|
const initialSnapshotRef = useRef<string | null>(null);
|
||||||
|
|
||||||
const [customers, setCustomers] = useState<Customer[]>([]);
|
|
||||||
const [customerSearch, setCustomerSearch] = useState("");
|
const [customerSearch, setCustomerSearch] = useState("");
|
||||||
const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
|
const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
|
||||||
|
|
||||||
const [companySettings, setCompanySettings] = useState<{
|
const companySettings = useQuery(companySettingsOptions()).data;
|
||||||
default_currency: string;
|
|
||||||
default_vat_rate: number;
|
|
||||||
available_currencies: string[];
|
|
||||||
available_vat_rates: number[];
|
|
||||||
} | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
apiFetch(`${API_BASE}/company-settings`)
|
if (companySettings && !isEdit) {
|
||||||
.then((r) => r.json())
|
setForm((prev) => ({
|
||||||
.then((d) => {
|
...prev,
|
||||||
if (d.success) {
|
currency:
|
||||||
setCompanySettings(d.data);
|
prev.currency === "CZK"
|
||||||
if (!isEdit) {
|
? companySettings.default_currency || "CZK"
|
||||||
setForm((prev) => ({
|
: prev.currency,
|
||||||
...prev,
|
vat_rate:
|
||||||
currency:
|
prev.vat_rate === 21
|
||||||
prev.currency === "CZK"
|
? (companySettings.default_vat_rate ?? 21)
|
||||||
? d.data.default_currency || "CZK"
|
: prev.vat_rate,
|
||||||
: prev.currency,
|
}));
|
||||||
vat_rate:
|
}
|
||||||
prev.vat_rate === 21
|
}, [companySettings, isEdit]);
|
||||||
? (d.data.default_vat_rate ?? 21)
|
|
||||||
: prev.vat_rate,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const vatOptions = (
|
const vatOptions = (
|
||||||
companySettings?.available_vat_rates || [0, 10, 12, 15, 21]
|
companySettings?.available_vat_rates || [0, 10, 12, 15, 21]
|
||||||
@@ -437,8 +401,36 @@ export default function InvoiceDetail() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// ─── TanStack Query ───
|
||||||
|
|
||||||
|
const customersQuery = useQuery(offerCustomersOptions());
|
||||||
|
const customers = customersQuery.data ?? [];
|
||||||
|
|
||||||
|
const bankAccountsQuery = useQuery(bankAccountsOptions());
|
||||||
|
const bankAccounts = bankAccountsQuery.data ?? [];
|
||||||
|
|
||||||
|
const invoiceQuery = useQuery(invoiceDetailOptions(id));
|
||||||
|
const invoice = invoiceQuery.data ?? null;
|
||||||
|
|
||||||
|
const nextNumberQuery = useQuery({
|
||||||
|
queryKey: ["invoices", "next-number"],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<{ next_number?: string; number?: string }>(
|
||||||
|
`${API_BASE}/invoices/next-number`,
|
||||||
|
).then((d) => d?.next_number || d?.number || ""),
|
||||||
|
enabled: !isEdit,
|
||||||
|
});
|
||||||
|
|
||||||
|
const orderDataQuery = useQuery({
|
||||||
|
queryKey: ["invoices", "order-data", fromOrderId],
|
||||||
|
queryFn: () =>
|
||||||
|
jsonQuery<Record<string, unknown>>(
|
||||||
|
`${API_BASE}/invoices/order-data/${fromOrderId}`,
|
||||||
|
),
|
||||||
|
enabled: !!fromOrderId,
|
||||||
|
});
|
||||||
|
|
||||||
// ─── Edit mode state ───
|
// ─── Edit mode state ───
|
||||||
const [invoice, setInvoice] = useState<Invoice | null>(null);
|
|
||||||
const [notes, setNotes] = useState("");
|
const [notes, setNotes] = useState("");
|
||||||
const [statusChanging, setStatusChanging] = useState<string | null>(null);
|
const [statusChanging, setStatusChanging] = useState<string | null>(null);
|
||||||
const [statusConfirm, setStatusConfirm] = useState<{
|
const [statusConfirm, setStatusConfirm] = useState<{
|
||||||
@@ -456,234 +448,191 @@ export default function InvoiceDetail() {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// ─── Data loading ───
|
// ─── Sync query data to form state ───
|
||||||
|
|
||||||
|
// Edit mode: populate form from invoice data
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isEdit) return;
|
if (!isEdit || dataReady) return;
|
||||||
const load = async () => {
|
if (
|
||||||
try {
|
invoiceQuery.isLoading ||
|
||||||
const promises = [
|
bankAccountsQuery.isLoading ||
|
||||||
apiFetch(`${API_BASE}/invoices/next-number`),
|
customersQuery.isLoading
|
||||||
apiFetch(`${API_BASE}/customers`),
|
)
|
||||||
apiFetch(`${API_BASE}/bank-accounts`),
|
return;
|
||||||
];
|
if (!invoiceQuery.data) return;
|
||||||
if (fromOrderId) {
|
|
||||||
promises.push(
|
|
||||||
apiFetch(`${API_BASE}/invoices/order-data/${fromOrderId}`),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const results = await Promise.all(promises);
|
const inv = invoiceQuery.data;
|
||||||
|
|
||||||
const numRes = results[0];
|
// Match bank account from invoice's bank details
|
||||||
if (numRes.ok) {
|
let matchedBankId: number | string = "";
|
||||||
const numData = await numRes.json();
|
const bankData = bankAccountsQuery.data ?? [];
|
||||||
if (numData.success)
|
const match = bankData.find(
|
||||||
setInvoiceNumber(
|
(b) =>
|
||||||
numData.data?.next_number || numData.data?.number || "",
|
(inv.bank_iban && b.iban === inv.bank_iban) ||
|
||||||
);
|
(inv.bank_account && b.account_number === inv.bank_account),
|
||||||
}
|
);
|
||||||
|
if (match) matchedBankId = match.id;
|
||||||
|
|
||||||
const custRes = results[1];
|
const formData: InvoiceForm = {
|
||||||
if (custRes.ok) {
|
customer_id: inv.customer_id || null,
|
||||||
const custData = await custRes.json();
|
customer_name: inv.customer_name || "",
|
||||||
if (custData.success)
|
order_id: inv.order_id || null,
|
||||||
setCustomers(
|
issue_date: inv.issue_date
|
||||||
Array.isArray(custData.data)
|
? new Date(inv.issue_date).toISOString().split("T")[0]
|
||||||
? custData.data
|
: "",
|
||||||
: custData.data?.customers || [],
|
due_date: inv.due_date
|
||||||
);
|
? new Date(inv.due_date).toISOString().split("T")[0]
|
||||||
}
|
: "",
|
||||||
|
tax_date: inv.tax_date
|
||||||
const bankRes = results[2];
|
? new Date(inv.tax_date).toISOString().split("T")[0]
|
||||||
if (bankRes.ok) {
|
: "",
|
||||||
const bankData = await bankRes.json();
|
currency: inv.currency || "CZK",
|
||||||
if (bankData.success && Array.isArray(bankData.data)) {
|
apply_vat: Number(inv.apply_vat) ? 1 : 0,
|
||||||
setBankAccounts(bankData.data);
|
vat_rate: Number(inv.vat_rate) || 21,
|
||||||
const defaultAcc = bankData.data.find(
|
payment_method: inv.payment_method || "Příkazem",
|
||||||
(a: BankAccount) => a.is_default,
|
constant_symbol: inv.constant_symbol || "0308",
|
||||||
);
|
issued_by: inv.issued_by || "",
|
||||||
if (defaultAcc) {
|
billing_text: inv.billing_text || "",
|
||||||
setForm((prev) => ({
|
notes: inv.notes || "",
|
||||||
...prev,
|
language: inv.language || "cs",
|
||||||
bank_account_id: defaultAcc.id,
|
bank_account_id: matchedBankId,
|
||||||
bank_name: defaultAcc.bank_name || "",
|
bank_name: inv.bank_name || "",
|
||||||
bank_swift: defaultAcc.bic || "",
|
bank_swift: inv.bank_swift || "",
|
||||||
bank_iban: defaultAcc.iban || "",
|
bank_iban: inv.bank_iban || "",
|
||||||
bank_account: defaultAcc.account_number || "",
|
bank_account: inv.bank_account || "",
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pre-fill from order
|
|
||||||
if (fromOrderId && results[3]?.ok) {
|
|
||||||
const orderData = await results[3].json();
|
|
||||||
if (orderData.success) {
|
|
||||||
const order = orderData.data;
|
|
||||||
const vatRate =
|
|
||||||
Number(order.vat_rate) ||
|
|
||||||
(companySettings?.default_vat_rate ?? 21);
|
|
||||||
setForm((prev) => ({
|
|
||||||
...prev,
|
|
||||||
customer_id: order.customer_id,
|
|
||||||
customer_name: order.customer_name || "",
|
|
||||||
order_id: order.id,
|
|
||||||
currency:
|
|
||||||
order.currency || companySettings?.default_currency || "CZK",
|
|
||||||
apply_vat: Number(order.apply_vat) || 0,
|
|
||||||
vat_rate: vatRate,
|
|
||||||
}));
|
|
||||||
if (order.items?.length > 0) {
|
|
||||||
setItems(
|
|
||||||
order.items.map((item: Record<string, unknown>) => ({
|
|
||||||
_key: `inv-${++keyCounterRef.current}`,
|
|
||||||
description: (item.description as string) || "",
|
|
||||||
quantity: Number(item.quantity) || 1,
|
|
||||||
unit: (item.unit as string) || "",
|
|
||||||
unit_price: Number(item.unit_price) || 0,
|
|
||||||
vat_rate: vatRate,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba při načítání dat");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
load();
|
setForm(formData);
|
||||||
}, [isEdit, fromOrderId, alert]);
|
setNotes(inv.notes || "");
|
||||||
|
setInvoiceNumber(inv.invoice_number || "");
|
||||||
|
|
||||||
// Edit mode: load existing invoice
|
// Calculate dueDays from existing dates
|
||||||
const fetchDetail = useCallback(async () => {
|
if (inv.issue_date && inv.due_date) {
|
||||||
if (!id) return;
|
const issue = new Date(inv.issue_date);
|
||||||
try {
|
const due = new Date(inv.due_date);
|
||||||
const [response, custRes, bankRes] = await Promise.all([
|
const diffDays = Math.round(
|
||||||
apiFetch(`${API_BASE}/invoices/${id}`),
|
(due.getTime() - issue.getTime()) / (1000 * 60 * 60 * 24),
|
||||||
apiFetch(`${API_BASE}/customers`),
|
);
|
||||||
apiFetch(`${API_BASE}/bank-accounts`),
|
if (diffDays > 0 && diffDays <= 60) setDueDays(diffDays);
|
||||||
]);
|
|
||||||
if (response.status === 401) return;
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
const inv = result.data;
|
|
||||||
setInvoice(inv);
|
|
||||||
setNotes(inv.notes || "");
|
|
||||||
setInvoiceNumber(inv.invoice_number || "");
|
|
||||||
|
|
||||||
// Populate customers list
|
|
||||||
if (custRes.ok) {
|
|
||||||
const custData = await custRes.json();
|
|
||||||
if (custData.success)
|
|
||||||
setCustomers(
|
|
||||||
Array.isArray(custData.data)
|
|
||||||
? custData.data
|
|
||||||
: custData.data?.customers || [],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Populate bank accounts and match existing
|
|
||||||
let matchedBankId: number | string = "";
|
|
||||||
if (bankRes.ok) {
|
|
||||||
const bankData = await bankRes.json();
|
|
||||||
if (bankData.success && Array.isArray(bankData.data)) {
|
|
||||||
setBankAccounts(bankData.data);
|
|
||||||
// Match by IBAN or account number
|
|
||||||
const match = bankData.data.find(
|
|
||||||
(b: BankAccount) =>
|
|
||||||
(inv.bank_iban && b.iban === inv.bank_iban) ||
|
|
||||||
(inv.bank_account && b.account_number === inv.bank_account),
|
|
||||||
);
|
|
||||||
if (match) matchedBankId = match.id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Populate form state from existing invoice
|
|
||||||
const formData = {
|
|
||||||
customer_id: inv.customer_id || null,
|
|
||||||
customer_name: inv.customer_name || "",
|
|
||||||
order_id: inv.order_id || null,
|
|
||||||
issue_date: inv.issue_date
|
|
||||||
? new Date(inv.issue_date).toISOString().split("T")[0]
|
|
||||||
: "",
|
|
||||||
due_date: inv.due_date
|
|
||||||
? new Date(inv.due_date).toISOString().split("T")[0]
|
|
||||||
: "",
|
|
||||||
tax_date: inv.tax_date
|
|
||||||
? new Date(inv.tax_date).toISOString().split("T")[0]
|
|
||||||
: "",
|
|
||||||
currency: inv.currency || "CZK",
|
|
||||||
apply_vat: Number(inv.apply_vat) ? 1 : 0,
|
|
||||||
vat_rate: Number(inv.vat_rate) || 21,
|
|
||||||
payment_method: inv.payment_method || "Příkazem",
|
|
||||||
constant_symbol: inv.constant_symbol || "0308",
|
|
||||||
issued_by: inv.issued_by || "",
|
|
||||||
billing_text: inv.billing_text || "",
|
|
||||||
notes: inv.notes || "",
|
|
||||||
language: inv.language || "cs",
|
|
||||||
bank_account_id: matchedBankId,
|
|
||||||
bank_name: inv.bank_name || "",
|
|
||||||
bank_swift: inv.bank_swift || "",
|
|
||||||
bank_iban: inv.bank_iban || "",
|
|
||||||
bank_account: inv.bank_account || "",
|
|
||||||
};
|
|
||||||
setForm(formData);
|
|
||||||
|
|
||||||
// Calculate dueDays from existing dates
|
|
||||||
if (inv.issue_date && inv.due_date) {
|
|
||||||
const issue = new Date(inv.issue_date);
|
|
||||||
const due = new Date(inv.due_date);
|
|
||||||
const diffDays = Math.round(
|
|
||||||
(due.getTime() - issue.getTime()) / (1000 * 60 * 60 * 24),
|
|
||||||
);
|
|
||||||
if (diffDays > 0 && diffDays <= 60) setDueDays(diffDays);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Populate items from existing invoice
|
|
||||||
const mappedItems =
|
|
||||||
inv.items?.length > 0
|
|
||||||
? inv.items.map((item: Record<string, unknown>) => ({
|
|
||||||
_key: `inv-${++keyCounterRef.current}`,
|
|
||||||
id: item.id as number | undefined,
|
|
||||||
description: (item.description as string) || "",
|
|
||||||
quantity: Number(item.quantity) || 1,
|
|
||||||
unit: (item.unit as string) || "",
|
|
||||||
unit_price: Number(item.unit_price) || 0,
|
|
||||||
vat_rate: Number(item.vat_rate) || Number(inv.vat_rate) || 21,
|
|
||||||
}))
|
|
||||||
: [];
|
|
||||||
if (mappedItems.length > 0) {
|
|
||||||
setItems(mappedItems);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Capture initial snapshot for dirty-checking
|
|
||||||
initialSnapshotRef.current = JSON.stringify({
|
|
||||||
form: formData,
|
|
||||||
items: mappedItems,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
alert.error(result.error || "Nepodařilo se načíst fakturu");
|
|
||||||
navigate("/invoices");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
navigate("/invoices");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
}, [id, alert, navigate]);
|
|
||||||
|
|
||||||
|
// Populate items from existing invoice
|
||||||
|
const invItems = inv.items;
|
||||||
|
const mappedItems =
|
||||||
|
invItems && invItems.length > 0
|
||||||
|
? invItems.map((item) => ({
|
||||||
|
_key: `inv-${++keyCounterRef.current}`,
|
||||||
|
id: item.id,
|
||||||
|
description: item.description || "",
|
||||||
|
item_description: item.item_description || "",
|
||||||
|
quantity: Number(item.quantity) || 1,
|
||||||
|
unit: item.unit || "",
|
||||||
|
unit_price: Number(item.unit_price) || 0,
|
||||||
|
vat_rate: Number(inv.vat_rate) || 21,
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
if (mappedItems.length > 0) {
|
||||||
|
setItems(mappedItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture initial snapshot for dirty-checking
|
||||||
|
initialSnapshotRef.current = JSON.stringify({
|
||||||
|
form: formData,
|
||||||
|
items: mappedItems,
|
||||||
|
});
|
||||||
|
|
||||||
|
setDataReady(true);
|
||||||
|
}, [
|
||||||
|
isEdit,
|
||||||
|
dataReady,
|
||||||
|
invoiceQuery.isLoading,
|
||||||
|
invoiceQuery.data,
|
||||||
|
bankAccountsQuery.isLoading,
|
||||||
|
bankAccountsQuery.data,
|
||||||
|
customersQuery.isLoading,
|
||||||
|
]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
// Create mode: populate form from query data
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isEdit) fetchDetail();
|
if (isEdit || dataReady) return;
|
||||||
}, [isEdit, fetchDetail]);
|
if (
|
||||||
|
nextNumberQuery.isLoading ||
|
||||||
|
bankAccountsQuery.isLoading ||
|
||||||
|
customersQuery.isLoading
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
if (fromOrderId && orderDataQuery.isLoading) return;
|
||||||
|
|
||||||
// Capture initial snapshot for dirty-checking once data finishes loading.
|
// Set invoice number
|
||||||
// Edit mode: captured inside fetchDetail from raw API data.
|
if (nextNumberQuery.data) {
|
||||||
// Create mode: captured on first stable render after loading completes.
|
setInvoiceNumber(nextNumberQuery.data);
|
||||||
if (!loading && !initialSnapshotRef.current) {
|
}
|
||||||
|
|
||||||
|
// Set default bank account
|
||||||
|
const defaultAcc = bankAccounts.find((a) => a.is_default);
|
||||||
|
if (defaultAcc) {
|
||||||
|
setForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
bank_account_id: defaultAcc.id,
|
||||||
|
bank_name: defaultAcc.bank_name || "",
|
||||||
|
bank_swift: defaultAcc.bic || "",
|
||||||
|
bank_iban: defaultAcc.iban || "",
|
||||||
|
bank_account: defaultAcc.account_number || "",
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-fill from order
|
||||||
|
if (fromOrderId && orderDataQuery.data) {
|
||||||
|
const order = orderDataQuery.data;
|
||||||
|
const vatRate =
|
||||||
|
Number(order.vat_rate) || (companySettings?.default_vat_rate ?? 21);
|
||||||
|
setForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
customer_id: order.customer_id as number,
|
||||||
|
customer_name: (order.customer_name as string) || "",
|
||||||
|
order_id: order.id as number,
|
||||||
|
currency:
|
||||||
|
(order.currency as string) ||
|
||||||
|
companySettings?.default_currency ||
|
||||||
|
"CZK",
|
||||||
|
apply_vat: Number(order.apply_vat) || 0,
|
||||||
|
vat_rate: vatRate,
|
||||||
|
}));
|
||||||
|
const orderItems = order.items as Record<string, unknown>[] | undefined;
|
||||||
|
if (orderItems && orderItems.length > 0) {
|
||||||
|
setItems(
|
||||||
|
orderItems.map((item) => ({
|
||||||
|
_key: `inv-${++keyCounterRef.current}`,
|
||||||
|
description: (item.description as string) || "",
|
||||||
|
item_description: (item.item_description as string) || "",
|
||||||
|
quantity: Number(item.quantity) || 1,
|
||||||
|
unit: (item.unit as string) || "",
|
||||||
|
unit_price: Number(item.unit_price) || 0,
|
||||||
|
vat_rate: vatRate,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setDataReady(true);
|
||||||
|
}, [
|
||||||
|
isEdit,
|
||||||
|
dataReady,
|
||||||
|
nextNumberQuery.isLoading,
|
||||||
|
nextNumberQuery.data,
|
||||||
|
bankAccountsQuery.isLoading,
|
||||||
|
bankAccountsQuery.data,
|
||||||
|
customersQuery.isLoading,
|
||||||
|
fromOrderId,
|
||||||
|
orderDataQuery.isLoading,
|
||||||
|
orderDataQuery.data,
|
||||||
|
companySettings,
|
||||||
|
bankAccounts,
|
||||||
|
]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
// Capture initial snapshot for dirty-checking once data sync completes.
|
||||||
|
// Edit mode: captured inside the sync effect from raw query data.
|
||||||
|
// Create mode: captured on the first render after sync effects populate the form.
|
||||||
|
if (dataReady && !initialSnapshotRef.current) {
|
||||||
initialSnapshotRef.current = JSON.stringify({ form, items });
|
initialSnapshotRef.current = JSON.stringify({ form, items });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -814,6 +763,34 @@ export default function InvoiceDetail() {
|
|||||||
}, [items, form.apply_vat]);
|
}, [items, form.apply_vat]);
|
||||||
|
|
||||||
// ─── Create/Edit mode: submit ───
|
// ─── Create/Edit mode: submit ───
|
||||||
|
const saveMutation = useApiMutation<
|
||||||
|
Record<string, unknown>,
|
||||||
|
{ invoice_id: number }
|
||||||
|
>({
|
||||||
|
url: () => (isEdit ? `${API_BASE}/invoices/${id}` : `${API_BASE}/invoices`),
|
||||||
|
method: () => (isEdit ? "PUT" : "POST"),
|
||||||
|
invalidate: ["invoices", "orders"],
|
||||||
|
onSuccess: (data) => {
|
||||||
|
const invoiceId = isEdit ? Number(id) : data.invoice_id;
|
||||||
|
// PDF binary generation — KEEP as raw apiFetch
|
||||||
|
void apiFetch(
|
||||||
|
`${API_BASE}/invoices-pdf/${invoiceId}?lang=${form.language}&save=1`,
|
||||||
|
).catch(() => {});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const statusMutation = useApiMutation<{ status: string }, unknown>({
|
||||||
|
url: () => `${API_BASE}/invoices/${id}`,
|
||||||
|
method: () => "PUT",
|
||||||
|
invalidate: ["invoices", "orders"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const invoiceDeleteMutation = useApiMutation<void, unknown>({
|
||||||
|
url: () => `${API_BASE}/invoices/${id}`,
|
||||||
|
method: () => "DELETE",
|
||||||
|
invalidate: ["invoices", "orders"],
|
||||||
|
});
|
||||||
|
|
||||||
const handleCreateSubmit = async (e?: React.FormEvent) => {
|
const handleCreateSubmit = async (e?: React.FormEvent) => {
|
||||||
e?.preventDefault();
|
e?.preventDefault();
|
||||||
|
|
||||||
@@ -831,7 +808,7 @@ export default function InvoiceDetail() {
|
|||||||
|
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const payload: any = {
|
const payload: Record<string, unknown> = {
|
||||||
...form,
|
...form,
|
||||||
due_date: computedDueDate || form.due_date,
|
due_date: computedDueDate || form.due_date,
|
||||||
items: items
|
items: items
|
||||||
@@ -843,43 +820,21 @@ export default function InvoiceDetail() {
|
|||||||
};
|
};
|
||||||
if (isEdit) payload.invoice_number = invoiceNumber;
|
if (isEdit) payload.invoice_number = invoiceNumber;
|
||||||
|
|
||||||
const url = isEdit
|
const data = await saveMutation.mutateAsync(payload);
|
||||||
? `${API_BASE}/invoices/${id}`
|
if (!isEdit) clearDraft();
|
||||||
: `${API_BASE}/invoices`;
|
alert.success(isEdit ? "Faktura byla uložena" : "Faktura byla vytvořena");
|
||||||
const method = isEdit ? "PUT" : "POST";
|
initialSnapshotRef.current = JSON.stringify({ form, items });
|
||||||
|
if (!isEdit) {
|
||||||
const response = await apiFetch(url, {
|
navigate(`/invoices/${data.invoice_id}`);
|
||||||
method,
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
});
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
if (!isEdit) clearDraft();
|
|
||||||
const invoiceId = isEdit ? id : result.data.invoice_id;
|
|
||||||
await apiFetch(
|
|
||||||
`${API_BASE}/invoices-pdf/${invoiceId}?lang=${form.language}&save=1`,
|
|
||||||
).catch(() => {});
|
|
||||||
alert.success(
|
|
||||||
result.message ||
|
|
||||||
(isEdit ? "Faktura byla uložena" : "Faktura byla vytvořena"),
|
|
||||||
);
|
|
||||||
initialSnapshotRef.current = JSON.stringify({ form, items });
|
|
||||||
if (isEdit) {
|
|
||||||
fetchDetail();
|
|
||||||
} else {
|
|
||||||
navigate(`/invoices/${result.data.invoice_id}`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
alert.error(
|
|
||||||
result.error ||
|
|
||||||
(isEdit
|
|
||||||
? "Nepodařilo se uložit fakturu"
|
|
||||||
: "Nepodařilo se vytvořit fakturu"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (e) {
|
||||||
alert.error("Chyba připojení");
|
alert.error(
|
||||||
|
e instanceof Error
|
||||||
|
? e.message
|
||||||
|
: isEdit
|
||||||
|
? "Nepodařilo se uložit fakturu"
|
||||||
|
: "Nepodařilo se vytvořit fakturu",
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
@@ -888,23 +843,14 @@ export default function InvoiceDetail() {
|
|||||||
// ─── Edit mode: status change ───
|
// ─── Edit mode: status change ───
|
||||||
const handleStatusChange = async () => {
|
const handleStatusChange = async () => {
|
||||||
if (!statusConfirm.status) return;
|
if (!statusConfirm.status) return;
|
||||||
setStatusChanging(statusConfirm.status);
|
const newStatus = statusConfirm.status;
|
||||||
|
setStatusChanging(newStatus);
|
||||||
setStatusConfirm({ show: false, status: null });
|
setStatusConfirm({ show: false, status: null });
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/invoices/${id}`, {
|
await statusMutation.mutateAsync({ status: newStatus });
|
||||||
method: "PUT",
|
alert.success("Stav byl změněn");
|
||||||
headers: { "Content-Type": "application/json" },
|
} catch (e) {
|
||||||
body: JSON.stringify({ status: statusConfirm.status }),
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
});
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
alert.success(result.message || "Stav byl změněn");
|
|
||||||
fetchDetail();
|
|
||||||
} else {
|
|
||||||
alert.error(result.error || "Nepodařilo se změnit stav");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
} finally {
|
||||||
setStatusChanging(null);
|
setStatusChanging(null);
|
||||||
}
|
}
|
||||||
@@ -938,18 +884,11 @@ export default function InvoiceDetail() {
|
|||||||
const handleDelete = async () => {
|
const handleDelete = async () => {
|
||||||
setDeleting(true);
|
setDeleting(true);
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(`${API_BASE}/invoices/${id}`, {
|
await invoiceDeleteMutation.mutateAsync(undefined);
|
||||||
method: "DELETE",
|
alert.success("Faktura byla smazána");
|
||||||
});
|
navigate("/invoices");
|
||||||
const result = await response.json();
|
} catch (e) {
|
||||||
if (result.success) {
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
alert.success(result.message || "Faktura byla smazána");
|
|
||||||
navigate("/invoices");
|
|
||||||
} else {
|
|
||||||
alert.error(result.error || "Nepodařilo se smazat fakturu");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
} finally {
|
||||||
setDeleting(false);
|
setDeleting(false);
|
||||||
setDeleteConfirm(false);
|
setDeleteConfirm(false);
|
||||||
@@ -960,53 +899,6 @@ export default function InvoiceDetail() {
|
|||||||
if (!isEdit && !hasPermission("invoices.create")) return <Forbidden />;
|
if (!isEdit && !hasPermission("invoices.create")) return <Forbidden />;
|
||||||
if (isEdit && !hasPermission("invoices.view")) return <Forbidden />;
|
if (isEdit && !hasPermission("invoices.view")) return <Forbidden />;
|
||||||
|
|
||||||
// ─── Loading skeleton ───
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div className="flex-row-gap">
|
|
||||||
{isEdit && (
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "32px", height: "32px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "200px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{isEdit && (
|
|
||||||
<div className="admin-skeleton-row gap-2">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "100px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "100px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
|
||||||
{[0, 1, 2, 3].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
<div className="admin-skeleton-line w-1/2" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ═══════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════
|
||||||
// PAID INVOICE — read-only view
|
// PAID INVOICE — read-only view
|
||||||
// ═══════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════
|
||||||
@@ -1015,6 +907,13 @@ export default function InvoiceDetail() {
|
|||||||
if (isEdit && !invoice) return null;
|
if (isEdit && !invoice) return null;
|
||||||
|
|
||||||
if (isPaid && invoice) {
|
if (isPaid && invoice) {
|
||||||
|
if (!dataReady) {
|
||||||
|
return (
|
||||||
|
<div className="admin-loading">
|
||||||
|
<div className="admin-spinner" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -1183,7 +1082,7 @@ export default function InvoiceDetail() {
|
|||||||
<div className="admin-card-header flex-between">
|
<div className="admin-card-header flex-between">
|
||||||
<h3 className="admin-card-title">Položky</h3>
|
<h3 className="admin-card-title">Položky</h3>
|
||||||
</div>
|
</div>
|
||||||
{invoice.items?.length > 0 ? (
|
{invoice.items && invoice.items.length > 0 ? (
|
||||||
<div className="admin-table-responsive">
|
<div className="admin-table-responsive">
|
||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
@@ -1224,6 +1123,17 @@ export default function InvoiceDetail() {
|
|||||||
</td>
|
</td>
|
||||||
<td className="fw-500">
|
<td className="fw-500">
|
||||||
{item.description || "\u2014"}
|
{item.description || "\u2014"}
|
||||||
|
{item.item_description && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: "0.8rem",
|
||||||
|
opacity: 0.8,
|
||||||
|
marginTop: 2,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{item.item_description}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="text-center">
|
<td className="text-center">
|
||||||
{item.quantity}{" "}
|
{item.quantity}{" "}
|
||||||
@@ -1319,6 +1229,13 @@ export default function InvoiceDetail() {
|
|||||||
// ═══════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════
|
||||||
// CREATE MODE + EDIT (not paid) — shared form
|
// CREATE MODE + EDIT (not paid) — shared form
|
||||||
// ═══════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════
|
||||||
|
if (!dataReady) {
|
||||||
|
return (
|
||||||
|
<div className="admin-loading">
|
||||||
|
<div className="admin-spinner" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<motion.div
|
<motion.div
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
import {
|
import { useState, useEffect, useRef, lazy, Suspense } from "react";
|
||||||
useState,
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
useEffect,
|
|
||||||
useCallback,
|
|
||||||
useRef,
|
|
||||||
lazy,
|
|
||||||
Suspense,
|
|
||||||
} from "react";
|
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { Link, useSearchParams } from "react-router-dom";
|
import { Link, useSearchParams } from "react-router-dom";
|
||||||
@@ -17,7 +11,14 @@ import apiFetch from "../utils/api";
|
|||||||
import { formatCurrency, formatDate, czechPlural } from "../utils/formatters";
|
import { formatCurrency, formatDate, czechPlural } from "../utils/formatters";
|
||||||
import SortIcon from "../components/SortIcon";
|
import SortIcon from "../components/SortIcon";
|
||||||
import useTableSort from "../hooks/useTableSort";
|
import useTableSort from "../hooks/useTableSort";
|
||||||
import useListData from "../hooks/useListData";
|
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
|
||||||
|
import {
|
||||||
|
invoiceListOptions,
|
||||||
|
invoiceStatsOptions,
|
||||||
|
type Invoice,
|
||||||
|
type InvoiceStats,
|
||||||
|
type CurrencyAmount,
|
||||||
|
} from "../lib/queries/invoices";
|
||||||
import Pagination from "../components/Pagination";
|
import Pagination from "../components/Pagination";
|
||||||
|
|
||||||
const ReceivedInvoices = lazy(() => import("./ReceivedInvoices"));
|
const ReceivedInvoices = lazy(() => import("./ReceivedInvoices"));
|
||||||
@@ -39,11 +40,6 @@ const MONTH_NAMES = [
|
|||||||
"prosinec",
|
"prosinec",
|
||||||
];
|
];
|
||||||
|
|
||||||
interface CurrencyAmount {
|
|
||||||
amount: number;
|
|
||||||
currency: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatMultiCurrency(amounts: CurrencyAmount[]): string {
|
function formatMultiCurrency(amounts: CurrencyAmount[]): string {
|
||||||
if (!Array.isArray(amounts) || amounts.length === 0) return "0 Kč";
|
if (!Array.isArray(amounts) || amounts.length === 0) return "0 Kč";
|
||||||
return amounts.map((a) => formatCurrency(a.amount, a.currency)).join(" · ");
|
return amounts.map((a) => formatCurrency(a.amount, a.currency)).join(" · ");
|
||||||
@@ -84,31 +80,6 @@ const STATUS_FILTERS = [
|
|||||||
{ value: "overdue", label: "Po splatnosti" },
|
{ value: "overdue", label: "Po splatnosti" },
|
||||||
];
|
];
|
||||||
|
|
||||||
interface Invoice {
|
|
||||||
id: number;
|
|
||||||
invoice_number: string;
|
|
||||||
customer_name: string | null;
|
|
||||||
status: string;
|
|
||||||
issue_date: string;
|
|
||||||
due_date: string;
|
|
||||||
total: number;
|
|
||||||
currency: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InvoiceStats {
|
|
||||||
paid_month: CurrencyAmount[];
|
|
||||||
paid_month_czk: number;
|
|
||||||
paid_month_count: number;
|
|
||||||
awaiting: CurrencyAmount[];
|
|
||||||
awaiting_czk: number;
|
|
||||||
awaiting_count: number;
|
|
||||||
overdue: CurrencyAmount[];
|
|
||||||
overdue_czk: number;
|
|
||||||
overdue_count: number;
|
|
||||||
vat_month: CurrencyAmount[];
|
|
||||||
vat_month_czk: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DraftData {
|
interface DraftData {
|
||||||
form: Record<string, unknown>;
|
form: Record<string, unknown>;
|
||||||
items: Record<string, unknown>[];
|
items: Record<string, unknown>[];
|
||||||
@@ -134,8 +105,6 @@ export default function Invoices() {
|
|||||||
const now = new Date();
|
const now = new Date();
|
||||||
const [statsMonth, setStatsMonth] = useState(now.getMonth() + 1);
|
const [statsMonth, setStatsMonth] = useState(now.getMonth() + 1);
|
||||||
const [statsYear, setStatsYear] = useState(now.getFullYear());
|
const [statsYear, setStatsYear] = useState(now.getFullYear());
|
||||||
const [stats, setStats] = useState<InvoiceStats | null>(null);
|
|
||||||
const [statsLoading, setStatsLoading] = useState(true);
|
|
||||||
const hasLoadedOnce = useRef(false);
|
const hasLoadedOnce = useRef(false);
|
||||||
const slideDirection = useRef(0);
|
const slideDirection = useRef(0);
|
||||||
const blobUrlRef = useRef<string | null>(null);
|
const blobUrlRef = useRef<string | null>(null);
|
||||||
@@ -154,28 +123,15 @@ export default function Invoices() {
|
|||||||
statsMonth === now.getMonth() + 1 && statsYear === now.getFullYear();
|
statsMonth === now.getMonth() + 1 && statsYear === now.getFullYear();
|
||||||
const monthLabel = `${MONTH_NAMES[statsMonth - 1]} ${statsYear}`;
|
const monthLabel = `${MONTH_NAMES[statsMonth - 1]} ${statsYear}`;
|
||||||
|
|
||||||
const fetchStats = useCallback(async () => {
|
const statsQuery = useQuery(invoiceStatsOptions(statsMonth, statsYear));
|
||||||
setStatsLoading(true);
|
const stats = statsQuery.data ?? null;
|
||||||
try {
|
|
||||||
const res = await apiFetch(
|
|
||||||
`${API_BASE}/invoices/stats?month=${statsMonth}&year=${statsYear}`,
|
|
||||||
);
|
|
||||||
const data = await res.json();
|
|
||||||
if (data.success) {
|
|
||||||
setStats(data.data);
|
|
||||||
hasLoadedOnce.current = true;
|
|
||||||
setSlideKey((k) => k + 1);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
} finally {
|
|
||||||
setStatsLoading(false);
|
|
||||||
}
|
|
||||||
}, [statsMonth, statsYear]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchStats();
|
if (statsQuery.data) {
|
||||||
}, [fetchStats]);
|
hasLoadedOnce.current = true;
|
||||||
|
setSlideKey((k) => k + 1);
|
||||||
|
}
|
||||||
|
}, [statsQuery.data]);
|
||||||
|
|
||||||
const prevMonth = () => {
|
const prevMonth = () => {
|
||||||
slideDirection.current = -1;
|
slideDirection.current = -1;
|
||||||
@@ -225,24 +181,23 @@ export default function Invoices() {
|
|||||||
setDraft(null);
|
setDraft(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const {
|
const {
|
||||||
items: invoices,
|
items: invoices,
|
||||||
loading,
|
|
||||||
initialLoad,
|
|
||||||
pagination,
|
pagination,
|
||||||
refetch: fetchData,
|
isPending: initialLoad,
|
||||||
} = useListData<Invoice>("invoices", {
|
isFetching: loading,
|
||||||
search,
|
} = usePaginatedQuery<Invoice>(
|
||||||
sort,
|
invoiceListOptions({
|
||||||
order,
|
search,
|
||||||
page,
|
sort,
|
||||||
extraParams: {
|
order,
|
||||||
month: String(statsMonth),
|
page,
|
||||||
year: String(statsYear),
|
month: statsMonth,
|
||||||
...(statusFilter ? { status: statusFilter } : {}),
|
year: statsYear,
|
||||||
},
|
status: statusFilter || undefined,
|
||||||
errorMsg: "Nepodařilo se načíst faktury",
|
}),
|
||||||
});
|
);
|
||||||
|
|
||||||
if (!hasPermission("invoices.view")) return <Forbidden />;
|
if (!hasPermission("invoices.view")) return <Forbidden />;
|
||||||
|
|
||||||
@@ -260,8 +215,9 @@ export default function Invoices() {
|
|||||||
if (result.success) {
|
if (result.success) {
|
||||||
setDeleteConfirm({ show: false, invoice: null });
|
setDeleteConfirm({ show: false, invoice: null });
|
||||||
alert.success(result.message || "Faktura byla smazána");
|
alert.success(result.message || "Faktura byla smazána");
|
||||||
fetchData();
|
queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||||
fetchStats();
|
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||||
} else {
|
} else {
|
||||||
alert.error(result.error || "Nepodařilo se smazat fakturu");
|
alert.error(result.error || "Nepodařilo se smazat fakturu");
|
||||||
}
|
}
|
||||||
@@ -283,8 +239,9 @@ export default function Invoices() {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
alert.success("Faktura označena jako zaplacená");
|
alert.success("Faktura označena jako zaplacená");
|
||||||
fetchData();
|
queryClient.invalidateQueries({ queryKey: ["invoices"] });
|
||||||
fetchStats();
|
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["projects"] });
|
||||||
} else {
|
} else {
|
||||||
alert.error(data.error || "Nepodařilo se změnit stav");
|
alert.error(data.error || "Nepodařilo se změnit stav");
|
||||||
}
|
}
|
||||||
@@ -323,80 +280,8 @@ export default function Invoices() {
|
|||||||
|
|
||||||
if (initialLoad) {
|
if (initialLoad) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="admin-loading">
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
<div className="admin-spinner" />
|
||||||
<div
|
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "200px", marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line" style={{ width: "140px" }} />
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-10"
|
|
||||||
style={{ width: "140px", borderRadius: "8px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="admin-kpi-grid admin-kpi-4">
|
|
||||||
{[0, 1, 2, 3].map((i) => (
|
|
||||||
<div key={i} className="admin-stat-card">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "60%",
|
|
||||||
height: "11px",
|
|
||||||
marginBottom: "0.5rem",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "40%",
|
|
||||||
height: "28px",
|
|
||||||
marginBottom: "0.5rem",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "50%", height: "12px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1rem" }}>
|
|
||||||
{[0, 1, 2, 3, 4].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "80px" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "70px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "90px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "90px" }}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "100px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -528,34 +413,8 @@ export default function Invoices() {
|
|||||||
>
|
>
|
||||||
<Suspense
|
<Suspense
|
||||||
fallback={
|
fallback={
|
||||||
<div
|
<div className="admin-loading">
|
||||||
className="admin-kpi-grid admin-kpi-4"
|
<div className="admin-spinner" />
|
||||||
style={{ marginBottom: "1.5rem" }}
|
|
||||||
>
|
|
||||||
{[0, 1, 2, 3].map((i) => (
|
|
||||||
<div key={i} className="admin-stat-card">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "60%",
|
|
||||||
height: "11px",
|
|
||||||
marginBottom: "0.5rem",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "40%",
|
|
||||||
height: "28px",
|
|
||||||
marginBottom: "0.5rem",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "50%", height: "12px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -574,35 +433,9 @@ export default function Invoices() {
|
|||||||
animate={{ opacity: 1, y: 0 }}
|
animate={{ opacity: 1, y: 0 }}
|
||||||
transition={{ duration: 0.25, delay: 0.1 }}
|
transition={{ duration: 0.25, delay: 0.1 }}
|
||||||
>
|
>
|
||||||
{!hasLoadedOnce.current && statsLoading ? (
|
{statsQuery.isPending && !hasLoadedOnce.current ? (
|
||||||
<div
|
<div className="admin-loading">
|
||||||
className="admin-kpi-grid admin-kpi-4"
|
<div className="admin-spinner" />
|
||||||
style={{ marginBottom: "1.5rem" }}
|
|
||||||
>
|
|
||||||
{[0, 1, 2, 3].map((i) => (
|
|
||||||
<div key={i} className="admin-stat-card">
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "60%",
|
|
||||||
height: "11px",
|
|
||||||
marginBottom: "0.5rem",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{
|
|
||||||
width: "40%",
|
|
||||||
height: "28px",
|
|
||||||
marginBottom: "0.5rem",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line"
|
|
||||||
style={{ width: "50%", height: "12px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
stats && (
|
stats && (
|
||||||
@@ -784,245 +617,143 @@ export default function Invoices() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{invoices.length === 0 && !(draft && !statusFilter) ? (
|
<AnimatePresence mode="wait">
|
||||||
<div className="admin-empty-state">
|
<motion.div
|
||||||
<div className="admin-empty-icon">
|
key={`${statusFilter}-${search}-${statsMonth}-${statsYear}-${page}-${invoices.length}`}
|
||||||
<svg
|
initial={{ opacity: 0, y: 6 }}
|
||||||
width="28"
|
animate={{ opacity: 1, y: 0 }}
|
||||||
height="28"
|
exit={{ opacity: 0 }}
|
||||||
viewBox="0 0 24 24"
|
transition={{ duration: 0.15 }}
|
||||||
fill="none"
|
>
|
||||||
stroke="currentColor"
|
{invoices.length === 0 && !(draft && !statusFilter) ? (
|
||||||
strokeWidth="1.5"
|
<div className="admin-empty-state">
|
||||||
strokeLinecap="round"
|
<div className="admin-empty-icon">
|
||||||
strokeLinejoin="round"
|
<svg
|
||||||
>
|
width="28"
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
height="28"
|
||||||
<polyline points="14 2 14 8 20 8" />
|
viewBox="0 0 24 24"
|
||||||
<line x1="16" y1="13" x2="8" y2="13" />
|
fill="none"
|
||||||
<line x1="16" y1="17" x2="8" y2="17" />
|
stroke="currentColor"
|
||||||
<polyline points="10 9 9 9 8 9" />
|
strokeWidth="1.5"
|
||||||
</svg>
|
strokeLinecap="round"
|
||||||
</div>
|
strokeLinejoin="round"
|
||||||
<p>Zatím nejsou žádné faktury.</p>
|
|
||||||
{hasPermission("invoices.create") && (
|
|
||||||
<p
|
|
||||||
className="text-tertiary"
|
|
||||||
style={{ fontSize: "0.875rem" }}
|
|
||||||
>
|
|
||||||
Vytvořte první fakturu tlačítkem výše.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="admin-table-responsive">
|
|
||||||
<table className="admin-table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th
|
|
||||||
style={{ cursor: "pointer" }}
|
|
||||||
onClick={() => handleSort("invoice_number")}
|
|
||||||
>
|
>
|
||||||
Číslo{" "}
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||||
<SortIcon
|
<polyline points="14 2 14 8 20 8" />
|
||||||
column="invoice_number"
|
<line x1="16" y1="13" x2="8" y2="13" />
|
||||||
sort={activeSort}
|
<line x1="16" y1="17" x2="8" y2="17" />
|
||||||
order={order}
|
<polyline points="10 9 9 9 8 9" />
|
||||||
/>
|
</svg>
|
||||||
</th>
|
</div>
|
||||||
<th>Zákazník</th>
|
<p>Zatím nejsou žádné faktury.</p>
|
||||||
<th
|
{hasPermission("invoices.create") && (
|
||||||
style={{ cursor: "pointer" }}
|
<p
|
||||||
onClick={() => handleSort("status")}
|
className="text-tertiary"
|
||||||
|
style={{ fontSize: "0.875rem" }}
|
||||||
>
|
>
|
||||||
Stav{" "}
|
Vytvořte první fakturu tlačítkem výše.
|
||||||
<SortIcon
|
</p>
|
||||||
column="status"
|
)}
|
||||||
sort={activeSort}
|
</div>
|
||||||
order={order}
|
) : (
|
||||||
/>
|
<div className="admin-table-responsive">
|
||||||
</th>
|
<table className="admin-table">
|
||||||
<th
|
<thead>
|
||||||
style={{ cursor: "pointer" }}
|
<tr>
|
||||||
onClick={() => handleSort("issue_date")}
|
<th
|
||||||
>
|
style={{ cursor: "pointer" }}
|
||||||
Vystaveno{" "}
|
onClick={() => handleSort("invoice_number")}
|
||||||
<SortIcon
|
>
|
||||||
column="issue_date"
|
Číslo{" "}
|
||||||
sort={activeSort}
|
<SortIcon
|
||||||
order={order}
|
column="invoice_number"
|
||||||
/>
|
sort={activeSort}
|
||||||
</th>
|
order={order}
|
||||||
<th
|
/>
|
||||||
style={{ cursor: "pointer" }}
|
</th>
|
||||||
onClick={() => handleSort("due_date")}
|
<th>Zákazník</th>
|
||||||
>
|
<th
|
||||||
Splatnost{" "}
|
style={{ cursor: "pointer" }}
|
||||||
<SortIcon
|
onClick={() => handleSort("status")}
|
||||||
column="due_date"
|
>
|
||||||
sort={activeSort}
|
Stav{" "}
|
||||||
order={order}
|
<SortIcon
|
||||||
/>
|
column="status"
|
||||||
</th>
|
sort={activeSort}
|
||||||
<th className="text-right">Celkem</th>
|
order={order}
|
||||||
<th>Akce</th>
|
/>
|
||||||
</tr>
|
</th>
|
||||||
</thead>
|
<th
|
||||||
<tbody>
|
style={{ cursor: "pointer" }}
|
||||||
{draft && !search && !statusFilter && (
|
onClick={() => handleSort("issue_date")}
|
||||||
<tr className="offers-draft-row">
|
>
|
||||||
<td>
|
Vystaveno{" "}
|
||||||
<span className="offers-draft-row-label">
|
<SortIcon
|
||||||
Koncept
|
column="issue_date"
|
||||||
{draft.savedAt && (
|
sort={activeSort}
|
||||||
<span style={{ fontWeight: 400, opacity: 0.8 }}>
|
order={order}
|
||||||
{" · "}
|
/>
|
||||||
{new Date(draft.savedAt).toLocaleTimeString(
|
</th>
|
||||||
"cs-CZ",
|
<th
|
||||||
{ hour: "2-digit", minute: "2-digit" },
|
style={{ cursor: "pointer" }}
|
||||||
|
onClick={() => handleSort("due_date")}
|
||||||
|
>
|
||||||
|
Splatnost{" "}
|
||||||
|
<SortIcon
|
||||||
|
column="due_date"
|
||||||
|
sort={activeSort}
|
||||||
|
order={order}
|
||||||
|
/>
|
||||||
|
</th>
|
||||||
|
<th className="text-right">Celkem</th>
|
||||||
|
<th>Akce</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{draft && !search && !statusFilter && (
|
||||||
|
<tr className="offers-draft-row">
|
||||||
|
<td>
|
||||||
|
<span className="offers-draft-row-label">
|
||||||
|
Koncept
|
||||||
|
{draft.savedAt && (
|
||||||
|
<span
|
||||||
|
style={{ fontWeight: 400, opacity: 0.8 }}
|
||||||
|
>
|
||||||
|
{" · "}
|
||||||
|
{new Date(
|
||||||
|
draft.savedAt,
|
||||||
|
).toLocaleTimeString("cs-CZ", {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
)}
|
</td>
|
||||||
</span>
|
<td>
|
||||||
</td>
|
{(draft.form.customer_name as string) ||
|
||||||
<td>
|
"\u2014"}
|
||||||
{(draft.form.customer_name as string) || "\u2014"}
|
</td>
|
||||||
</td>
|
<td>{"\u2014"}</td>
|
||||||
<td>{"\u2014"}</td>
|
<td className="admin-mono">
|
||||||
<td className="admin-mono">
|
{draft.form.issue_date
|
||||||
{draft.form.issue_date
|
? formatDate(draft.form.issue_date as string)
|
||||||
? formatDate(draft.form.issue_date as string)
|
: "\u2014"}
|
||||||
: "\u2014"}
|
</td>
|
||||||
</td>
|
<td className="admin-mono">
|
||||||
<td className="admin-mono">
|
{draft.form.due_date
|
||||||
{draft.form.due_date
|
? formatDate(draft.form.due_date as string)
|
||||||
? formatDate(draft.form.due_date as string)
|
: "\u2014"}
|
||||||
: "\u2014"}
|
</td>
|
||||||
</td>
|
<td />
|
||||||
<td />
|
<td>
|
||||||
<td>
|
<div className="admin-table-actions">
|
||||||
<div className="admin-table-actions">
|
<Link
|
||||||
<Link
|
to="/invoices/new"
|
||||||
to="/invoices/new"
|
className="admin-btn-icon"
|
||||||
className="admin-btn-icon"
|
title="Pokračovat v konceptu"
|
||||||
title="Pokračovat v konceptu"
|
aria-label="Pokračovat v konceptu"
|
||||||
aria-label="Pokračovat v konceptu"
|
>
|
||||||
>
|
|
||||||
<svg
|
|
||||||
width="18"
|
|
||||||
height="18"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
>
|
|
||||||
<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.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
|
||||||
</svg>
|
|
||||||
</Link>
|
|
||||||
<button
|
|
||||||
onClick={discardDraft}
|
|
||||||
className="admin-btn-icon danger"
|
|
||||||
title="Zahodit koncept"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
width="18"
|
|
||||||
height="18"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
>
|
|
||||||
<polyline points="3 6 5 6 21 6" />
|
|
||||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
)}
|
|
||||||
{invoices.map((inv) => {
|
|
||||||
const isOverdue =
|
|
||||||
inv.status === "overdue" ||
|
|
||||||
(inv.status === "issued" &&
|
|
||||||
inv.due_date &&
|
|
||||||
new Date(inv.due_date) <
|
|
||||||
new Date(new Date().toDateString()));
|
|
||||||
return (
|
|
||||||
<tr
|
|
||||||
key={inv.id}
|
|
||||||
className={isOverdue ? "offers-expired-row" : ""}
|
|
||||||
>
|
|
||||||
<td className="admin-mono">
|
|
||||||
<Link
|
|
||||||
to={`/invoices/${inv.id}`}
|
|
||||||
className="link-accent"
|
|
||||||
>
|
|
||||||
{inv.invoice_number}
|
|
||||||
</Link>
|
|
||||||
</td>
|
|
||||||
<td>{inv.customer_name || "\u2014"}</td>
|
|
||||||
<td>
|
|
||||||
{inv.status === "paid" ? (
|
|
||||||
<span
|
|
||||||
className={`admin-badge ${STATUS_CLASSES[inv.status]}`}
|
|
||||||
>
|
|
||||||
{STATUS_LABELS[inv.status]}
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
onClick={() => toggleStatus(inv)}
|
|
||||||
className={`admin-badge ${STATUS_CLASSES[inv.status] || ""}`}
|
|
||||||
style={{ cursor: "pointer" }}
|
|
||||||
>
|
|
||||||
{STATUS_LABELS[inv.status] || inv.status}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="admin-mono">
|
|
||||||
{formatDate(inv.issue_date)}
|
|
||||||
</td>
|
|
||||||
<td
|
|
||||||
className="admin-mono"
|
|
||||||
style={
|
|
||||||
inv.status === "overdue"
|
|
||||||
? { color: "var(--danger)", fontWeight: 600 }
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{formatDate(inv.due_date)}
|
|
||||||
</td>
|
|
||||||
<td
|
|
||||||
className="admin-mono"
|
|
||||||
style={{ textAlign: "right", fontWeight: 500 }}
|
|
||||||
>
|
|
||||||
{formatCurrency(inv.total, inv.currency)}
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<div className="admin-table-actions">
|
|
||||||
<Link
|
|
||||||
to={`/invoices/${inv.id}`}
|
|
||||||
className="admin-btn-icon"
|
|
||||||
title={
|
|
||||||
inv.status === "paid" ? "Detail" : "Upravit"
|
|
||||||
}
|
|
||||||
aria-label={
|
|
||||||
inv.status === "paid" ? "Detail" : "Upravit"
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{inv.status === "paid" ? (
|
|
||||||
<svg
|
|
||||||
width="18"
|
|
||||||
height="18"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
>
|
|
||||||
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
|
|
||||||
<circle cx="12" cy="12" r="3" />
|
|
||||||
</svg>
|
|
||||||
) : (
|
|
||||||
<svg
|
<svg
|
||||||
width="18"
|
width="18"
|
||||||
height="18"
|
height="18"
|
||||||
@@ -1034,51 +765,11 @@ export default function Invoices() {
|
|||||||
<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="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.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||||
</svg>
|
</svg>
|
||||||
)}
|
</Link>
|
||||||
</Link>
|
|
||||||
{hasPermission("invoices.export") && (
|
|
||||||
<button
|
<button
|
||||||
onClick={() => handlePdf(inv)}
|
onClick={discardDraft}
|
||||||
className="admin-btn-icon"
|
|
||||||
title="Zobrazit fakturu"
|
|
||||||
disabled={pdfLoading === inv.id}
|
|
||||||
>
|
|
||||||
{pdfLoading === inv.id ? (
|
|
||||||
<div
|
|
||||||
className="admin-spinner"
|
|
||||||
style={{
|
|
||||||
width: 18,
|
|
||||||
height: 18,
|
|
||||||
borderWidth: 2,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<svg
|
|
||||||
width="18"
|
|
||||||
height="18"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="2"
|
|
||||||
>
|
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
|
||||||
<polyline points="14 2 14 8 20 8" />
|
|
||||||
<line x1="16" y1="13" x2="8" y2="13" />
|
|
||||||
<line x1="16" y1="17" x2="8" y2="17" />
|
|
||||||
</svg>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{hasPermission("invoices.delete") && (
|
|
||||||
<button
|
|
||||||
onClick={() =>
|
|
||||||
setDeleteConfirm({
|
|
||||||
show: true,
|
|
||||||
invoice: inv,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="admin-btn-icon danger"
|
className="admin-btn-icon danger"
|
||||||
title="Smazat"
|
title="Zahodit koncept"
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
width="18"
|
width="18"
|
||||||
@@ -1092,16 +783,195 @@ export default function Invoices() {
|
|||||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
)}
|
</div>
|
||||||
</div>
|
</td>
|
||||||
</td>
|
</tr>
|
||||||
</tr>
|
)}
|
||||||
);
|
{invoices.map((inv) => {
|
||||||
})}
|
const isOverdue =
|
||||||
</tbody>
|
inv.status === "overdue" ||
|
||||||
</table>
|
(inv.status === "issued" &&
|
||||||
</div>
|
inv.due_date &&
|
||||||
)}
|
new Date(inv.due_date) <
|
||||||
|
new Date(new Date().toDateString()));
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
key={inv.id}
|
||||||
|
className={
|
||||||
|
isOverdue ? "offers-expired-row" : ""
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<td className="admin-mono">
|
||||||
|
<Link
|
||||||
|
to={`/invoices/${inv.id}`}
|
||||||
|
className="link-accent"
|
||||||
|
>
|
||||||
|
{inv.invoice_number}
|
||||||
|
</Link>
|
||||||
|
</td>
|
||||||
|
<td>{inv.customer_name || "\u2014"}</td>
|
||||||
|
<td>
|
||||||
|
{inv.status === "paid" ? (
|
||||||
|
<span
|
||||||
|
className={`admin-badge ${STATUS_CLASSES[inv.status]}`}
|
||||||
|
>
|
||||||
|
{STATUS_LABELS[inv.status]}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => toggleStatus(inv)}
|
||||||
|
className={`admin-badge ${STATUS_CLASSES[inv.status] || ""}`}
|
||||||
|
style={{ cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
{STATUS_LABELS[inv.status] || inv.status}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="admin-mono">
|
||||||
|
{formatDate(inv.issue_date)}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
className="admin-mono"
|
||||||
|
style={
|
||||||
|
inv.status === "overdue"
|
||||||
|
? {
|
||||||
|
color: "var(--danger)",
|
||||||
|
fontWeight: 600,
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{formatDate(inv.due_date)}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
className="admin-mono"
|
||||||
|
style={{
|
||||||
|
textAlign: "right",
|
||||||
|
fontWeight: 500,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{formatCurrency(inv.total, inv.currency)}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div className="admin-table-actions">
|
||||||
|
<Link
|
||||||
|
to={`/invoices/${inv.id}`}
|
||||||
|
className="admin-btn-icon"
|
||||||
|
title={
|
||||||
|
inv.status === "paid"
|
||||||
|
? "Detail"
|
||||||
|
: "Upravit"
|
||||||
|
}
|
||||||
|
aria-label={
|
||||||
|
inv.status === "paid"
|
||||||
|
? "Detail"
|
||||||
|
: "Upravit"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{inv.status === "paid" ? (
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
|
||||||
|
<circle cx="12" cy="12" r="3" />
|
||||||
|
</svg>
|
||||||
|
) : (
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<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.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
</Link>
|
||||||
|
{hasPermission("invoices.export") && (
|
||||||
|
<button
|
||||||
|
onClick={() => handlePdf(inv)}
|
||||||
|
className="admin-btn-icon"
|
||||||
|
title="Zobrazit fakturu"
|
||||||
|
disabled={pdfLoading === inv.id}
|
||||||
|
>
|
||||||
|
{pdfLoading === inv.id ? (
|
||||||
|
<div
|
||||||
|
className="admin-spinner"
|
||||||
|
style={{
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
borderWidth: 2,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||||
|
<polyline points="14 2 14 8 20 8" />
|
||||||
|
<line
|
||||||
|
x1="16"
|
||||||
|
y1="13"
|
||||||
|
x2="8"
|
||||||
|
y2="13"
|
||||||
|
/>
|
||||||
|
<line
|
||||||
|
x1="16"
|
||||||
|
y1="17"
|
||||||
|
x2="8"
|
||||||
|
y2="17"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{hasPermission("invoices.delete") && (
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
setDeleteConfirm({
|
||||||
|
show: true,
|
||||||
|
invoice: inv,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="admin-btn-icon danger"
|
||||||
|
title="Smazat"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<polyline points="3 6 5 6 21 6" />
|
||||||
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</motion.div>
|
||||||
|
</AnimatePresence>
|
||||||
<Pagination pagination={pagination} onPageChange={setPage} />
|
<Pagination pagination={pagination} onPageChange={setPage} />
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useAuth } from "../context/AuthContext";
|
import { useAuth } from "../context/AuthContext";
|
||||||
import { useAlert } from "../context/AlertContext";
|
import { useAlert } from "../context/AlertContext";
|
||||||
import { motion, AnimatePresence } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import { formatDate, formatDatetime } from "../utils/attendanceHelpers";
|
import { formatDate, formatDatetime } from "../utils/attendanceHelpers";
|
||||||
import apiFetch from "../utils/api";
|
|
||||||
import { czechPlural } from "../utils/formatters";
|
import { czechPlural } from "../utils/formatters";
|
||||||
|
import {
|
||||||
|
leavePendingOptions,
|
||||||
|
leaveProcessedOptions,
|
||||||
|
} from "../lib/queries/leave";
|
||||||
import ConfirmModal from "../components/ConfirmModal";
|
import ConfirmModal from "../components/ConfirmModal";
|
||||||
import Forbidden from "../components/Forbidden";
|
import Forbidden from "../components/Forbidden";
|
||||||
import useModalLock from "../hooks/useModalLock";
|
import FormModal from "../components/FormModal";
|
||||||
import FormField from "../components/FormField";
|
import FormField from "../components/FormField";
|
||||||
|
import { useApiMutation } from "../lib/queries/mutations";
|
||||||
|
|
||||||
const API_BASE = "/api/admin";
|
const API_BASE = "/api/admin";
|
||||||
|
|
||||||
@@ -101,15 +106,23 @@ function mapLeaveRequest(raw: RawLeaveRequest): LeaveRequest {
|
|||||||
export default function LeaveApproval() {
|
export default function LeaveApproval() {
|
||||||
const { hasPermission } = useAuth();
|
const { hasPermission } = useAuth();
|
||||||
const alert = useAlert();
|
const alert = useAlert();
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [activeTab, setActiveTab] = useState<"pending" | "processed">(
|
const [activeTab, setActiveTab] = useState<"pending" | "processed">(
|
||||||
"pending",
|
"pending",
|
||||||
);
|
);
|
||||||
const [pendingRequests, setPendingRequests] = useState<LeaveRequest[]>([]);
|
const { data: pendingData, isPending: loading } = useQuery(
|
||||||
const [pendingCount, setPendingCount] = useState(0);
|
leavePendingOptions(),
|
||||||
const [processedRequests, setProcessedRequests] = useState<LeaveRequest[]>(
|
|
||||||
[],
|
|
||||||
);
|
);
|
||||||
|
const { data: processedData } = useQuery({
|
||||||
|
...leaveProcessedOptions(),
|
||||||
|
enabled: activeTab === "processed",
|
||||||
|
});
|
||||||
|
const pendingRequests =
|
||||||
|
(pendingData as RawLeaveRequest[] | undefined)?.map(mapLeaveRequest) ?? [];
|
||||||
|
const pendingCount = pendingRequests.length;
|
||||||
|
const processedRequests =
|
||||||
|
(processedData as RawLeaveRequest[] | undefined)?.map(mapLeaveRequest) ??
|
||||||
|
[];
|
||||||
|
|
||||||
const [approveModal, setApproveModal] = useState<{
|
const [approveModal, setApproveModal] = useState<{
|
||||||
open: boolean;
|
open: boolean;
|
||||||
request: LeaveRequest | null;
|
request: LeaveRequest | null;
|
||||||
@@ -119,99 +132,45 @@ export default function LeaveApproval() {
|
|||||||
request: LeaveRequest | null;
|
request: LeaveRequest | null;
|
||||||
}>({ open: false, request: null });
|
}>({ open: false, request: null });
|
||||||
const [rejectNote, setRejectNote] = useState("");
|
const [rejectNote, setRejectNote] = useState("");
|
||||||
const [processing, setProcessing] = useState(false);
|
|
||||||
|
|
||||||
useModalLock(rejectModal.open);
|
|
||||||
|
|
||||||
const fetchPending = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/leave-requests?status=pending`,
|
|
||||||
);
|
|
||||||
if (response.status === 401) return;
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
const mapped = (result.data as RawLeaveRequest[]).map(mapLeaveRequest);
|
|
||||||
setPendingRequests(mapped);
|
|
||||||
setPendingCount(result.pagination?.total ?? mapped.length);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Nepodařilo se načíst žádosti");
|
|
||||||
}
|
|
||||||
}, [alert]);
|
|
||||||
|
|
||||||
const fetchProcessed = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const response = await apiFetch(
|
|
||||||
`${API_BASE}/leave-requests?status=approved`,
|
|
||||||
);
|
|
||||||
if (response.status === 401) return;
|
|
||||||
const resultApproved = await response.json();
|
|
||||||
|
|
||||||
const response2 = await apiFetch(
|
|
||||||
`${API_BASE}/leave-requests?status=rejected`,
|
|
||||||
);
|
|
||||||
if (response2.status === 401) return;
|
|
||||||
const resultRejected = await response2.json();
|
|
||||||
|
|
||||||
const all = [
|
|
||||||
...(resultApproved.success
|
|
||||||
? (resultApproved.data as RawLeaveRequest[]).map(mapLeaveRequest)
|
|
||||||
: []),
|
|
||||||
...(resultRejected.success
|
|
||||||
? (resultRejected.data as RawLeaveRequest[]).map(mapLeaveRequest)
|
|
||||||
: []),
|
|
||||||
].sort(
|
|
||||||
(a: LeaveRequest, b: LeaveRequest) =>
|
|
||||||
(b.reviewed_at ? new Date(b.reviewed_at).getTime() : 0) -
|
|
||||||
(a.reviewed_at ? new Date(a.reviewed_at).getTime() : 0),
|
|
||||||
);
|
|
||||||
|
|
||||||
setProcessedRequests(all);
|
|
||||||
} catch {
|
|
||||||
alert.error("Nepodařilo se načíst vyřízené žádosti");
|
|
||||||
}
|
|
||||||
}, [alert]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setLoading(true);
|
|
||||||
fetchPending().finally(() => setLoading(false));
|
|
||||||
}, [fetchPending]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (activeTab === "processed" && processedRequests.length === 0) {
|
|
||||||
fetchProcessed();
|
|
||||||
}
|
|
||||||
}, [activeTab, processedRequests.length, fetchProcessed]);
|
|
||||||
|
|
||||||
if (!hasPermission("attendance.approve")) return <Forbidden />;
|
if (!hasPermission("attendance.approve")) return <Forbidden />;
|
||||||
|
|
||||||
const handleApprove = async () => {
|
const approveMutation = useApiMutation<
|
||||||
setProcessing(true);
|
{ id: number; status: "approved" },
|
||||||
try {
|
unknown
|
||||||
const response = await apiFetch(
|
>({
|
||||||
`${API_BASE}/leave-requests/${approveModal.request!.id}`,
|
url: ({ id }) => `${API_BASE}/leave-requests/${id}`,
|
||||||
{
|
method: () => "PUT",
|
||||||
method: "PUT",
|
invalidate: ["leave-requests", "leave", "attendance", "users"],
|
||||||
headers: { "Content-Type": "application/json" },
|
onSuccess: () => {
|
||||||
body: JSON.stringify({ status: "approved" }),
|
setApproveModal({ open: false, request: null });
|
||||||
},
|
alert.success("Žádost byla schválena");
|
||||||
);
|
},
|
||||||
if (response.status === 401) return;
|
});
|
||||||
|
|
||||||
const result = await response.json();
|
const rejectMutation = useApiMutation<
|
||||||
if (result.success) {
|
{ id: number; status: "rejected"; reviewer_note: string },
|
||||||
setApproveModal({ open: false, request: null });
|
unknown
|
||||||
await fetchPending();
|
>({
|
||||||
setProcessedRequests([]);
|
url: ({ id }) => `${API_BASE}/leave-requests/${id}`,
|
||||||
alert.success("Žádost byla schválena");
|
method: () => "PUT",
|
||||||
} else {
|
invalidate: ["leave-requests", "leave", "attendance", "users"],
|
||||||
alert.error(result.error);
|
onSuccess: () => {
|
||||||
}
|
setRejectModal({ open: false, request: null });
|
||||||
} catch {
|
setRejectNote("");
|
||||||
alert.error("Chyba připojení");
|
alert.success("Žádost byla zamítnuta");
|
||||||
} finally {
|
},
|
||||||
setProcessing(false);
|
});
|
||||||
|
|
||||||
|
const handleApprove = async () => {
|
||||||
|
if (!approveModal.request) return;
|
||||||
|
try {
|
||||||
|
await approveMutation.mutateAsync({
|
||||||
|
id: approveModal.request.id,
|
||||||
|
status: "approved",
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -220,71 +179,22 @@ export default function LeaveApproval() {
|
|||||||
alert.error("Důvod zamítnutí je povinný");
|
alert.error("Důvod zamítnutí je povinný");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!rejectModal.request) return;
|
||||||
setProcessing(true);
|
|
||||||
try {
|
try {
|
||||||
const response = await apiFetch(
|
await rejectMutation.mutateAsync({
|
||||||
`${API_BASE}/leave-requests/${rejectModal.request!.id}`,
|
id: rejectModal.request.id,
|
||||||
{
|
status: "rejected",
|
||||||
method: "PUT",
|
reviewer_note: rejectNote,
|
||||||
headers: { "Content-Type": "application/json" },
|
});
|
||||||
body: JSON.stringify({
|
} catch (e) {
|
||||||
status: "rejected",
|
alert.error(e instanceof Error ? e.message : "Chyba připojení");
|
||||||
reviewer_note: rejectNote,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (response.status === 401) return;
|
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
setRejectModal({ open: false, request: null });
|
|
||||||
setRejectNote("");
|
|
||||||
await fetchPending();
|
|
||||||
setProcessedRequests([]);
|
|
||||||
alert.success("Žádost byla zamítnuta");
|
|
||||||
} else {
|
|
||||||
alert.error(result.error);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
alert.error("Chyba připojení");
|
|
||||||
} finally {
|
|
||||||
setProcessing(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
|
<div className="admin-loading">
|
||||||
<div
|
<div className="admin-spinner" />
|
||||||
className="admin-skeleton-row"
|
|
||||||
style={{ justifyContent: "space-between" }}
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line h-8"
|
|
||||||
style={{ width: "200px", marginBottom: "0.5rem" }}
|
|
||||||
/>
|
|
||||||
<div className="admin-skeleton-line" style={{ width: "140px" }} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="admin-card">
|
|
||||||
<div className="admin-skeleton" style={{ gap: "1.25rem" }}>
|
|
||||||
{[0, 1, 2, 3, 4].map((i) => (
|
|
||||||
<div key={i} className="admin-skeleton-row">
|
|
||||||
<div className="admin-skeleton-line circle" />
|
|
||||||
<div className="flex-1">
|
|
||||||
<div className="admin-skeleton-line w-1/3 mb-2" />
|
|
||||||
<div
|
|
||||||
className="admin-skeleton-line w-1/4"
|
|
||||||
style={{ height: "10px" }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="admin-skeleton-line w-1/4" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -370,7 +280,11 @@ export default function LeaveApproval() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
style={{ display: "flex", flexDirection: "column", gap: "1rem" }}
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: "1rem",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{pendingRequests.map((req) => (
|
{pendingRequests.map((req) => (
|
||||||
<div key={req.id} className="admin-card">
|
<div key={req.id} className="admin-card">
|
||||||
@@ -573,82 +487,43 @@ export default function LeaveApproval() {
|
|||||||
}
|
}
|
||||||
confirmText="Schválit"
|
confirmText="Schválit"
|
||||||
type="info"
|
type="info"
|
||||||
loading={processing}
|
loading={approveMutation.isPending}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Reject Modal */}
|
{/* Reject Modal */}
|
||||||
<AnimatePresence>
|
<FormModal
|
||||||
{rejectModal.open && (
|
isOpen={rejectModal.open && !!rejectModal.request}
|
||||||
<motion.div
|
onClose={() => {
|
||||||
className="admin-modal-overlay"
|
setRejectModal({ open: false, request: null });
|
||||||
initial={{ opacity: 0 }}
|
setRejectNote("");
|
||||||
animate={{ opacity: 1 }}
|
}}
|
||||||
exit={{ opacity: 0 }}
|
onSubmit={handleReject}
|
||||||
transition={{ duration: 0.2 }}
|
title="Zamítnout žádost"
|
||||||
>
|
submitLabel="Zamítnout"
|
||||||
<div
|
loading={rejectMutation.isPending}
|
||||||
className="admin-modal-backdrop"
|
>
|
||||||
onClick={() => {
|
{rejectModal.request && (
|
||||||
setRejectModal({ open: false, request: null });
|
<>
|
||||||
setRejectNote("");
|
<p className="text-secondary mb-4">
|
||||||
}}
|
{rejectModal.request.employee_name} —{" "}
|
||||||
/>
|
{leaveTypeLabels[rejectModal.request.leave_type]},{" "}
|
||||||
<motion.div
|
{formatDate(rejectModal.request.date_from)} —{" "}
|
||||||
className="admin-modal"
|
{formatDate(rejectModal.request.date_to)} (
|
||||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
{rejectModal.request.total_days} dnů)
|
||||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
</p>
|
||||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
<FormField label="Důvod zamítnutí" required>
|
||||||
transition={{ duration: 0.2 }}
|
<textarea
|
||||||
>
|
value={rejectNote}
|
||||||
<div className="admin-modal-header">
|
onChange={(e) => setRejectNote(e.target.value)}
|
||||||
<h2 className="admin-modal-title">Zamítnout žádost</h2>
|
placeholder="Uveďte důvod zamítnutí..."
|
||||||
</div>
|
className="admin-form-textarea"
|
||||||
<div className="admin-modal-body">
|
rows={3}
|
||||||
{rejectModal.request && (
|
autoFocus
|
||||||
<p className="text-secondary mb-4">
|
/>
|
||||||
{rejectModal.request.employee_name} —{" "}
|
</FormField>
|
||||||
{leaveTypeLabels[rejectModal.request.leave_type]},{" "}
|
</>
|
||||||
{formatDate(rejectModal.request.date_from)} —{" "}
|
|
||||||
{formatDate(rejectModal.request.date_to)} (
|
|
||||||
{rejectModal.request.total_days} dnů)
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
<FormField label="Důvod zamítnutí" required>
|
|
||||||
<textarea
|
|
||||||
value={rejectNote}
|
|
||||||
onChange={(e) => setRejectNote(e.target.value)}
|
|
||||||
placeholder="Uveďte důvod zamítnutí..."
|
|
||||||
className="admin-form-textarea"
|
|
||||||
rows={3}
|
|
||||||
autoFocus
|
|
||||||
/>
|
|
||||||
</FormField>
|
|
||||||
</div>
|
|
||||||
<div className="admin-modal-footer">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
setRejectModal({ open: false, request: null });
|
|
||||||
setRejectNote("");
|
|
||||||
}}
|
|
||||||
className="admin-btn admin-btn-secondary"
|
|
||||||
disabled={processing}
|
|
||||||
>
|
|
||||||
Zrušit
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleReject}
|
|
||||||
disabled={processing || !rejectNote.trim()}
|
|
||||||
className="admin-btn admin-btn-primary"
|
|
||||||
>
|
|
||||||
{processing ? "Zpracování..." : "Zamítnout"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</motion.div>
|
|
||||||
</motion.div>
|
|
||||||
)}
|
)}
|
||||||
</AnimatePresence>
|
</FormModal>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user