Compare commits
225 Commits
v2.0.7
...
3530dd247c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3530dd247c | ||
|
|
996012e3d3 | ||
|
|
3cd7cfcc34 | ||
|
|
68d9c224bc | ||
|
|
200aa0e1a8 | ||
|
|
e3b414d22c | ||
|
|
89656ac2c6 | ||
|
|
94030230e7 | ||
|
|
d859b5bbf7 | ||
|
|
5683912b76 | ||
|
|
3ec512faf1 | ||
|
|
9f9f359acb | ||
|
|
593dfc356d | ||
|
|
0172c9a442 | ||
|
|
81b4cb51e7 | ||
|
|
a274a49e90 | ||
|
|
9c192e79e7 | ||
|
|
4d0ec53514 | ||
|
|
87e644eef8 | ||
|
|
6428044624 | ||
|
|
67ddfb2d5d | ||
|
|
81293ae543 | ||
|
|
237ebf3ef8 | ||
|
|
983a1408f1 | ||
|
|
ae4a51bf7d | ||
|
|
fb480d886d | ||
|
|
59f555059b | ||
|
|
3d784adf5d | ||
|
|
44cfea22ca | ||
|
|
bce0280846 | ||
|
|
0d9b5e9570 | ||
|
|
2b3266a1cc | ||
|
|
2f084174df | ||
|
|
5551786da2 | ||
|
|
09f8dc63bf | ||
|
|
8dec785d13 | ||
|
|
4674ff3389 | ||
|
|
4bb7de7247 | ||
|
|
719d1f2659 | ||
|
|
3787cc4dd0 | ||
|
|
1ee59b54bc | ||
|
|
907ee574e6 | ||
|
|
b51ea2505e | ||
|
|
fd2e613aa5 | ||
|
|
1f2aff8325 | ||
|
|
e11765bf0e | ||
|
|
8f74efba97 | ||
|
|
b9103c59f0 | ||
|
|
bf33d0a543 | ||
|
|
64bb7f9c37 | ||
|
|
6f3f1c40e7 | ||
|
|
164ce54adf | ||
|
|
6877919133 | ||
|
|
5ec70599aa | ||
|
|
7e4469b29a | ||
|
|
08af4cd0ae | ||
|
|
eb279a87a9 | ||
|
|
ea3b595b32 | ||
|
|
e9b432bec6 | ||
|
|
741c8109fa | ||
|
|
07d9c8d9f7 | ||
|
|
0928b3636e | ||
|
|
738f852168 | ||
|
|
aa7b97689b | ||
|
|
5cd5a9e37d | ||
|
|
27b734f6d0 | ||
|
|
91072548d4 | ||
|
|
5b380863cf | ||
|
|
1293da7f25 | ||
|
|
d9cf8f53e8 | ||
|
|
f509e24942 | ||
|
|
4159ae57a4 | ||
|
|
4c8ed39d85 | ||
|
|
06519d521f | ||
|
|
3c6d175857 | ||
|
|
7582cf88f3 | ||
|
|
4deabbfcc0 | ||
|
|
302a0f8b3f | ||
|
|
78f39e9f82 | ||
|
|
949bf6c86f | ||
|
|
c8fc662552 | ||
|
|
10c8454c9b | ||
|
|
9496944ad2 | ||
|
|
608ebb02bd | ||
|
|
3a3485d029 | ||
|
|
674b44d047 | ||
|
|
2dbacc3bec | ||
|
|
c21f02e5d1 | ||
|
|
f87e110359 | ||
|
|
f1b1329c1b | ||
|
|
88d5d43448 | ||
|
|
4745af3639 | ||
|
|
4258699b73 | ||
|
|
bfd2c59ad3 | ||
|
|
0b69dbfde0 | ||
|
|
db7a5c3d15 | ||
|
|
f1ce76d21d | ||
|
|
575c07aac8 | ||
|
|
4bf245d35c | ||
|
|
79d026e756 | ||
|
|
40a859f5e1 | ||
|
|
ffae1a4e74 | ||
|
|
5c9ebddf50 | ||
|
|
f268907848 | ||
|
|
dd8c699420 | ||
|
|
268a947c85 | ||
|
|
75dc97516e | ||
|
|
d1533ffc4d | ||
|
|
1c1b9dca17 | ||
|
|
7b20c47937 | ||
|
|
7398cad466 | ||
|
|
396a1d37ec | ||
|
|
ca1f07671f | ||
|
|
638264fc7c | ||
|
|
f68a4dafc4 | ||
|
|
700fb47bbc | ||
|
|
c2746d78c9 | ||
|
|
4e534471d9 | ||
|
|
975a555af5 | ||
|
|
6a22195c7d | ||
|
|
74ce24e3fa | ||
|
|
8ee5a443ef | ||
|
|
b3e2abf9b2 | ||
|
|
1826fc7976 | ||
|
|
d08e55a41a | ||
|
|
97101c4db7 | ||
|
|
1e4dd1fbcc | ||
|
|
5462fcf944 | ||
|
|
78cd7cf2d8 | ||
|
|
cb82349c86 | ||
|
|
d445384408 | ||
|
|
3268cf2100 | ||
|
|
841ab676ec | ||
|
|
313d9218c1 | ||
|
|
c270cb22e9 | ||
|
|
113edd9a0d | ||
|
|
753c16423c | ||
|
|
11b71501ee | ||
|
|
5c03570f07 | ||
|
|
ed9ea52a44 | ||
|
|
9e9aacdf0b | ||
|
|
52ff0a6ffa | ||
|
|
a15fa68c3b | ||
|
|
e86c2e9a80 | ||
|
|
ce636215dc | ||
|
|
473f7c4a8c | ||
|
|
28186397a0 | ||
|
|
a3948c7da1 | ||
|
|
53c8359acc | ||
|
|
c2d7a96718 | ||
|
|
61673247bf | ||
|
|
9fe5113c5b | ||
|
|
e868ecf769 | ||
|
|
20177e8f87 | ||
|
|
39565767ef | ||
|
|
c4668357aa | ||
|
|
b4f1b6ce2b | ||
|
|
66235ff567 | ||
|
|
d341db2e51 | ||
|
|
430ec3e76b | ||
|
|
f295af4a14 | ||
|
|
db11999c85 | ||
|
|
afef0e6759 | ||
|
|
62f50d31af | ||
|
|
3d3df6db85 | ||
|
|
162f9b9fdf | ||
|
|
3b48bd0523 | ||
|
|
2b7b480144 | ||
|
|
e26fce092a | ||
|
|
d7e0ba933d | ||
|
|
8b90cfed1f | ||
|
|
8476ffebd6 | ||
|
|
63ccf8fda7 | ||
|
|
9f4b8a897a | ||
|
|
2a3df15565 | ||
|
|
b1f48df30c | ||
|
|
f00fcf95fd | ||
|
|
4093664936 | ||
|
|
ecb83d4654 | ||
|
|
a06ea2e1cd | ||
|
|
15a2da38cc | ||
|
|
4072197f4a | ||
|
|
1914fddb4d | ||
|
|
63192dc781 | ||
|
|
6147131aad | ||
|
|
b4f859ea6e | ||
|
|
519edce373 | ||
|
|
c454d1a3fc | ||
|
|
b1f21a1f48 | ||
|
|
b6cd5046d5 | ||
|
|
25c8c39ba6 | ||
|
|
4b2770a000 | ||
|
|
434a12b4a8 | ||
|
|
28fb399217 | ||
|
|
c0ff7b4549 | ||
|
|
1e21c12f33 | ||
|
|
ab12f9d791 | ||
|
|
cf442b9a99 | ||
|
|
2e7caea5a6 | ||
|
|
702a4984ee | ||
|
|
769767c33d | ||
|
|
f18e2e0f2c | ||
|
|
d62abe81fd | ||
|
|
ac7c220bb1 | ||
|
|
b7ebf04001 | ||
|
|
441f46a471 | ||
|
|
f011a67ff3 | ||
|
|
92594f89c3 | ||
|
|
6664e3bc4d | ||
|
|
c5cfd855ba | ||
|
|
2565e0de21 | ||
|
|
817f0b2f00 | ||
|
|
e4ec08a5ef | ||
|
|
049ee492c0 | ||
|
|
f4bc038f8b | ||
|
|
58e5fd2b1d | ||
|
|
0226cdd52b | ||
|
|
b665ea1d9b | ||
|
|
ec74ded953 | ||
|
|
bcf63d00d1 | ||
|
|
096784768f | ||
|
|
3623b441ce | ||
|
|
4bf7bf4ed6 | ||
|
|
92252382ac | ||
|
|
8bed920de1 |
@@ -1,14 +1,23 @@
|
||||
// Block direct .env file edits (not .env.example, .env.production, .env.test)
|
||||
let data = '';
|
||||
process.stdin.on('data', chunk => data += chunk);
|
||||
process.stdin.on('end', () => {
|
||||
//
|
||||
// Hook exit-code contract (Claude Code PreToolUse):
|
||||
// exit 0 = allow (stdout JSON is only parsed on exit 0)
|
||||
// exit 2 = BLOCK — the reason must be written to STDERR
|
||||
// any other exit code = non-blocking error (the tool call proceeds)
|
||||
// So to actually block, we must print to stderr and exit 2.
|
||||
let data = "";
|
||||
process.stdin.on("data", (chunk) => (data += chunk));
|
||||
process.stdin.on("end", () => {
|
||||
try {
|
||||
const input = JSON.parse(data);
|
||||
const filePath = input.tool_input?.file_path || '';
|
||||
const basename = filePath.split('/').pop().split('\\').pop();
|
||||
if (basename === '.env') {
|
||||
console.log(JSON.stringify({ decision: 'block', reason: 'Direct .env edits are blocked. Use .env.example instead.' }));
|
||||
process.exit(1);
|
||||
const filePath = input.tool_input?.file_path || "";
|
||||
const basename = filePath.split("/").pop().split("\\").pop();
|
||||
if (basename === ".env") {
|
||||
console.error("Direct .env edits are blocked. Use .env.example instead.");
|
||||
process.exit(2);
|
||||
}
|
||||
} catch {}
|
||||
} catch {
|
||||
// Deliberate fail-open: on unparseable input exit 0 (allow). Exiting 2
|
||||
// here would block EVERY Edit/Write if the hook payload format changed.
|
||||
}
|
||||
});
|
||||
|
||||
63
.env.example
63
.env.example
@@ -1,32 +1,63 @@
|
||||
# Database
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# boha-app-ts environment template. Copy to `.env` (dev) / `.env.test` (tests).
|
||||
# Required vars throw at boot if missing; optional vars show their defaults.
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# ── Required ──────────────────────────────────────────────────────────────
|
||||
DATABASE_URL=mysql://user:password@localhost:3306/app
|
||||
|
||||
# Server
|
||||
PORT=3001
|
||||
HOST=127.0.0.1
|
||||
APP_ENV=local
|
||||
|
||||
# Auth — MUST regenerate for production: openssl rand -hex 32
|
||||
JWT_SECRET=REPLACE_WITH_64_CHAR_HEX_STRING_RUN_openssl_rand_hex_32
|
||||
# TOTP — MUST regenerate for production: openssl rand -hex 32
|
||||
TOTP_ENCRYPTION_KEY=REPLACE_WITH_64_CHAR_HEX_STRING_RUN_openssl_rand_hex_32
|
||||
|
||||
# ── Server ────────────────────────────────────────────────────────────────
|
||||
PORT=3001 # production port (dev is hardcoded to 3050)
|
||||
HOST=127.0.0.1
|
||||
APP_ENV=local # local | production — controls CSP/CORS/HSTS
|
||||
APP_URL= # base URL used in email links
|
||||
# TRUST_PROXY=127.0.0.1,::1 # comma-separated trusted proxy IPs
|
||||
|
||||
# ── Tokens (seconds) ──────────────────────────────────────────────────────
|
||||
ACCESS_TOKEN_EXPIRY=900
|
||||
REFRESH_TOKEN_SESSION_EXPIRY=3600
|
||||
REFRESH_TOKEN_REMEMBER_EXPIRY=2592000
|
||||
|
||||
# TOTP — MUST regenerate for production: openssl rand -hex 32
|
||||
TOTP_ENCRYPTION_KEY=REPLACE_WITH_64_CHAR_HEX_STRING_RUN_openssl_rand_hex_32
|
||||
# ── TOTP / 2FA (optional, sensible defaults) ──────────────────────────────
|
||||
# TOTP_ALGORITHM=SHA1
|
||||
# TOTP_DIGITS=6
|
||||
# TOTP_PERIOD=30
|
||||
# LOGIN_TOKEN_EXPIRY_MINUTES=5
|
||||
|
||||
# File storage
|
||||
# ── Rate limiting (optional) ──────────────────────────────────────────────
|
||||
# RATE_LIMIT_MAX=300
|
||||
# RATE_LIMIT_WINDOW=1 minute
|
||||
# RATE_LIMIT_LOGIN=20
|
||||
# RATE_LIMIT_TOTP=5
|
||||
# RATE_LIMIT_REFRESH=10
|
||||
|
||||
# ── File storage (NAS network shares) ─────────────────────────────────────
|
||||
NAS_PATH=Z:/02_PROJEKTY
|
||||
MAX_UPLOAD_SIZE=52428800
|
||||
# NAS_INVOICES= # invoice PDFs — {base}/Vydané|Přijaté/YYYY/MM/ (falls back to NAS_FINANCIALS_PATH if unset)
|
||||
# NAS_ORDERS= # issued-order PDF archival — {base}/Vydané/YYYY/MM/ (off until set)
|
||||
# NAS_OFFERS_PATH=
|
||||
MAX_UPLOAD_SIZE=52428800 # 50 MB
|
||||
|
||||
# Email
|
||||
# ── Email ─────────────────────────────────────────────────────────────────
|
||||
CONTACT_EMAIL_TO=
|
||||
CONTACT_EMAIL_FROM=
|
||||
SMTP_FROM=
|
||||
# SMTP_FROM_NAME=
|
||||
LEAVE_NOTIFY_EMAIL=
|
||||
# INVOICE_ALERT_EMAIL= # set to enable the daily 08:00 invoice-alert cron
|
||||
# Optional SMTP transport (defaults to local sendmail when SMTP_HOST is unset):
|
||||
# SMTP_HOST=
|
||||
# SMTP_PORT=587
|
||||
# SMTP_SECURE=false
|
||||
# SMTP_USER=
|
||||
# SMTP_PASS=
|
||||
|
||||
# App URL (for email links)
|
||||
APP_URL=
|
||||
|
||||
# CORS (production only, comma-separated)
|
||||
# ── CORS (production only, comma-separated) ───────────────────────────────
|
||||
CORS_ORIGINS=
|
||||
|
||||
# ── AI assistant "Odin" (optional; feature self-hides when unset) ─────────
|
||||
# ANTHROPIC_API_KEY=
|
||||
|
||||
16
.gitignore
vendored
16
.gitignore
vendored
@@ -7,6 +7,13 @@ dist/
|
||||
dist-client/
|
||||
*.css.map
|
||||
|
||||
# Build / tooling artifacts
|
||||
*.tsbuildinfo
|
||||
*.bak
|
||||
|
||||
# Local scratch
|
||||
.playwright-mcp/
|
||||
|
||||
# Release archives
|
||||
*.tar.gz
|
||||
|
||||
@@ -14,5 +21,14 @@ dist-client/
|
||||
.claude/worktrees/
|
||||
.claude/settings.local.json
|
||||
|
||||
# Local Claude tooling (personal, not shared)
|
||||
.claude/commands/
|
||||
.claude/skills/
|
||||
.claude/workflows/
|
||||
CLAUDE-FABLE-5.md
|
||||
|
||||
# Personal scratch (planning docs, etc.)
|
||||
simon/
|
||||
|
||||
# Superpowers brainstorm mockups
|
||||
.superpowers/
|
||||
|
||||
7
.prettierignore
Normal file
7
.prettierignore
Normal file
@@ -0,0 +1,7 @@
|
||||
dist/
|
||||
dist-client/
|
||||
node_modules/
|
||||
prisma/migrations/
|
||||
src/admin/bones/
|
||||
*.tsbuildinfo
|
||||
package-lock.json
|
||||
7
.prettierrc.json
Normal file
7
.prettierrc.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": false,
|
||||
"trailingComma": "all",
|
||||
"tabWidth": 2,
|
||||
"printWidth": 80
|
||||
}
|
||||
334
AUDIT-2026-06-12.md
Normal file
334
AUDIT-2026-06-12.md
Normal file
@@ -0,0 +1,334 @@
|
||||
# Codebase Audit — boha-app-ts — 2026-06-12
|
||||
|
||||
## Summary
|
||||
|
||||
| Severity | Count |
|
||||
| ------------ | ----: |
|
||||
| **Critical** | 3 |
|
||||
| **High** | 6 |
|
||||
| **Medium** | 11 |
|
||||
| **Low** | 8 |
|
||||
| **Total** | 28 |
|
||||
|
||||
> 2026-06-12: M3 (offer PDF footer) withdrawn as a false positive after user
|
||||
> verification — see the struck section below. Counts updated 12→11 / 29→28.
|
||||
|
||||
## Methodology
|
||||
|
||||
- **Fan-out discovery:** 27 independent finder passes swept the codebase across domain modules (auth/sessions, attendance/leave, documents — offers/orders/issued-orders/invoices, warehouse, projects, trips/vehicles, plan, users/roles, AI/Odin, settings) and cross-cutting dimensions (Zod-cap-vs-DB-column alignment, date/timezone boundaries, pagination determinism, React Query cache invalidation, transaction atomicity, FK-error→4xx mapping, privilege boundaries).
|
||||
- **Dedupe vs prior backlog:** candidate findings were de-duplicated against the existing audit backlog (`docs/codebase-audit-findings-2026-06-06.md`, `docs/cross-module-consistency-audit-2026-06-09.md`, `REVIEW_FINDINGS.md`). Already-fixed items (e.g. the 2026-06-06 sessions audit-logging finding) and already-tracked duplicates were dropped; only net-new defects survived.
|
||||
- **3-lens adversarial verification:** every surviving finding was independently re-checked through three lenses — (1) **trace-to-refute** (follow the full code path end-to-end and try to break each step), (2) **convention veto** (confirm it genuinely VIOLATES a documented `CLAUDE.md` convention and is NOT one of the deliberate "looks-like-a-bug" decisions: local-time `toJSON`, local-noon `@db.Date` writes, lenient date schemas, net-only documents, gross `received_invoices.amount`, shared `orders.*` permission family), and (3) **executable repro** (a concrete, developer-runnable reproduction with observable wrong output). A finding ships only with three independent `real` verdicts. Findings the convention lens vetoed (e.g. one warehouse over-issue variant whose exact numbers are blocked by an upstream aggregate guard — kept only after a corrected, reachable repro was supplied) were re-scoped, not waved through.
|
||||
|
||||
Order below is by severity, then by blast radius within a severity.
|
||||
|
||||
---
|
||||
|
||||
## CRITICAL
|
||||
|
||||
### C1. Deleting a vacation/sick attendance record never restores the leave balance — `vacation_used` stays permanently inflated
|
||||
|
||||
- **Severity:** Critical
|
||||
- **File:** `src/services/attendance.service.ts:1751`
|
||||
- **Failure scenario:** `createLeave` increments `leave_balances.vacation_used`/`sick_used` when booking leave (lines 1304–1331), but `deleteAttendance` (1751–1772) only runs `prisma.attendance.delete` — it never decrements the balance. `getStatus` (line 246) and `getBalances` (line 530) derive `vacation_remaining = vacation_total - vacation_used` from the stored counter, so cancelling a booked leave by deleting its rows permanently removes entitlement the employee never actually took. The leave-request approval path (`leave-requests.ts`) has the identical asymmetric increment-on-approve / no-decrement-on-delete.
|
||||
- **Repro:**
|
||||
1. As an admin (`attendance.manage`), `POST /api/admin/attendance?action=leave` for user 5, `date_from=2026-07-06`, `date_to=2026-07-10`, `leave_type=vacation`, `leave_hours=8` → creates 5 rows and adds 40h to `vacation_used`.
|
||||
2. Read balances: `vacation_used=40`, `vacation_remaining = total-40`.
|
||||
3. `DELETE /api/admin/attendance/:id` for each of the 5 rows.
|
||||
4. Read balances again: rows are gone but `vacation_used` is still 40 and `vacation_remaining` is still down 40h. Only a manual admin `handleBalances` reset fixes it.
|
||||
- **Pinning test:** Book a 5-day vacation, assert `vacation_used` rose by 40h, delete all 5 attendance rows, then assert `vacation_used` returned to its pre-booking value (fails today: stays 40).
|
||||
|
||||
### C2. `confirmIssue`: duplicate issue lines on the same batch pass per-line validation but decrement cumulatively, driving batch quantity negative (silent over-issue)
|
||||
|
||||
- **Severity:** Critical
|
||||
- **File:** `src/services/warehouse.service.ts:626`
|
||||
- **Failure scenario:** The confirm path validates and decrements stock **per line**, re-reading the batch fresh each iteration with no cross-line running tally and no `if (newBatchQty < 0) throw` guard. Two issue lines for the same item that resolve to the same batch each pass the independent `batch.quantity >= line.quantity` check, then the decrement loop accumulates: line A leaves the batch at 3, line B re-reads 3 and writes `3-5 = -2`, flagging `is_consumed=true`. The negative/consumed batch drops out of `getItemTotalStock` (`is_consumed:false` filter), so the over-issue is silently hidden from all stock totals. No `(issue_id, batch_id)` unique constraint exists on `sklad_issue_lines`.
|
||||
- **Repro (corrected — the single-batch case is blocked by the per-item aggregate guard in `validateIssueReservationRules`; use two batches so the per-item total check passes while one batch still goes negative):**
|
||||
1. Seed item X with two unconsumed batches B1(qty 8, older) and B2(qty 8). Total stock = 16.
|
||||
2. `POST /issues` with two lines, both `item_id=X`, no `batch_id`, each `quantity=5`. `selectFifoBatches` is called once per line against the live DB with nothing persisted, so both resolve to B1; the per-item availability check (16 < 10 is false) passes. Draft stores two lines both `batch_id=B1`.
|
||||
3. `POST /issues/:id/confirm` → 200. B1 validated 8≥5 twice (both see original 8), then decremented to 3, then to `-2` with `is_consumed=true`.
|
||||
4. 10 units issued from a batch that held 8; B1 persists at `quantity=-2`, drops from stock totals — 2 units leave with no accounting trail and FIFO is broken, with no error raised.
|
||||
- **Pinning test:** Confirm an issue containing two same-item lines whose combined quantity exceeds a single resolved batch; assert the confirm is rejected (400) and no batch row is left with `quantity < 0`.
|
||||
|
||||
### C3. `confirmInventorySession` swallows an in-transaction throw with `return` instead of `throw`, committing partial stock writes the route reports as failed
|
||||
|
||||
- **Severity:** Critical
|
||||
- **File:** `src/services/warehouse.service.ts:1275`
|
||||
- **Failure scenario:** The function body is `return prisma.$transaction(async (tx) => { ... })` (line 1108). A single loop over `session.items` interleaves real writes with a throwing op: the surplus branch (diff>0) creates a corrective receipt, receipt line, batch, and upserts `sklad_item_locations`; a later deficit line makes `selectFifoBatches` throw. The catch at line 1275 **returns** `{ error, status: 400 }` from inside the transaction callback. In an interactive Prisma transaction, returning a value (rather than throwing) **commits** — so the surplus item's writes persist while the session→CONFIRMED update (line 1293) is skipped, leaving the session DRAFT. The route sees `"error" in result` and returns HTTP 400 ("nothing changed"). Re-confirming the still-DRAFT session re-runs the loop and re-creates the same surplus batch — repeatable phantom inventory and corrupted valuation on every retry.
|
||||
- **Repro:**
|
||||
1. ItemA exists; ItemB has a location row `quantity=10` but fewer unconsumed batches (documented location/batch drift at lines 1244–1250 — also reproducible by consuming batches between session create and confirm).
|
||||
2. `POST /admin/inventory-sessions` with items ordered `[{ItemA surplus, actual_qty 5}, {ItemB deficit, actual_qty 0}]` (ItemA's line gets the lower id, processed first).
|
||||
3. `POST /admin/inventory-sessions/<id>/confirm` → HTTP 400 "Nedostatečné množství na skladě", BUT ItemA now has a permanent +5 corrective batch + bumped `item_location`, and the session is still DRAFT.
|
||||
4. Re-confirm → another +5 for ItemA, fails on ItemB again. Each retry adds +5 phantom stock while the API reports failure.
|
||||
- **Pinning test:** Confirm an inventory session whose item list has a valid surplus line before an over-deficit line; assert the response is an error AND no `sklad_receipts`/`sklad_batches` rows were created (transaction rolled back) and the session is unchanged.
|
||||
|
||||
---
|
||||
|
||||
## HIGH
|
||||
|
||||
### H1. Terminating one session force-logs-out ALL of the user's sessions on the terminated device's next refresh
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/services/auth.ts:280`
|
||||
- **Failure scenario:** Session termination (`sessions.ts:94-97` DELETE `/:id`, `sessions.ts:124-131` action=all, `profile.ts:98-101` password-change) sets ONLY `replaced_at` (no `replaced_by_hash`, row not deleted). Legitimate rotation (`auth.ts:315-318`) sets BOTH. The reuse-detection condition at `auth.ts:280-282` is `storedToken.replaced_at || storedToken.replaced_by_hash`, evaluated BEFORE the expiry check at line 292 — so a manually-terminated token presented on a later refresh is misclassified as theft and runs `tx.refresh_tokens.deleteMany({ where: { user_id } })` (line 285), wiping every session for that user, including the laptop the user is actively on, plus a false "reuse detected" warning.
|
||||
- **Repro:**
|
||||
1. Log in from two devices → Session A (laptop), Session B (phone), both `replaced_at=null`.
|
||||
2. From the laptop, `DELETE /api/admin/sessions/<B.id>` → B gets `replaced_at` set only.
|
||||
3. After B's access token expires (~15 min), the phone calls `POST /api/admin/refresh` with B's still-present cookie.
|
||||
4. `refreshAccessToken` hits the reuse branch (B's `replaced_at` truthy), deletes ALL of the user's tokens including A. Laptop is silently logged out on its next refresh.
|
||||
- **Pinning test:** Create two refresh-token sessions, terminate one via the sessions DELETE route, present the terminated token to `refreshAccessToken`; assert the OTHER session's row still exists (fails today: it is deleted).
|
||||
|
||||
### H2. `order_items.description` Zod cap (8000) far exceeds DB column `VarChar(500)` → Prisma 500 on long descriptions
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/schemas/orders.schema.ts:12`
|
||||
- **Failure scenario:** `OrderItemSchema.description = z.string().max(8000)` but `order_items.description` is `@db.VarChar(500)` (`schema.prisma:327`). `createOrder`/`updateOrder` map the value straight into `tx.order_items.createMany` with no truncation. A 501–8000 char description passes Zod, overflows the column under MySQL strict mode (P2000), and `createOrder`'s catch only re-maps errors carrying a `status` property — so it surfaces as HTTP 500 "Interní chyba serveru" instead of a clean Czech 400, with the whole order transaction rolled back.
|
||||
- **Repro:** `POST /api/admin/orders` (Content-Type application/json so the manual-JSON branch runs), `items:[{ description: "x".repeat(600), quantity:1, unit_price:100 }]` → HTTP 500 instead of 400; no order persisted. Same on `PUT /api/admin/orders/:id` for an order in `prijata`/`v_realizaci`.
|
||||
- **Pinning test:** `parseBody(OrderItemSchema, { description: "x".repeat(600), ... })` should fail Zod with a 400-class error (fails today: passes, then 500s at Prisma). Fix: `.max(500)`.
|
||||
|
||||
### H3. Issued-order status transition silently discards unsaved item/section edits and marks them clean
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/admin/pages/IssuedOrderDetail.tsx:524`
|
||||
- **Failure scenario:** A `sent` issued order is both editable AND has valid transitions. `handleStatusChange` (line 516) sends ONLY `{ status: newStatus }`; the server's `replaceItems = editable && Array.isArray(body.items)` is false for a status-only payload, so edited items/sections are never persisted. Worse, line 524 calls `markClean({ form, items, sections })` with the in-memory UNSAVED edits, re-baselining the unsaved-changes guard so `isDirty` flips false and the `beforeunload` warning never fires. After the transition the order is `confirmed` → read-only, so the lost edits cannot be re-applied. (Contrast: `OfferDetail`/`InvoiceDetail` do NOT call `markClean` on transition.)
|
||||
- **Repro:** Open a `sent` issued order with `orders.edit`, edit a line item / section / supplier (form dirty), click "Potvrdit" and confirm. The transition succeeds, the edits are silently dropped, and on refetch the items/sections revert to stored values with no warning.
|
||||
- **Pinning test:** Render `IssuedOrderDetail` for a `sent` order, mutate an item, invoke a status transition; assert the PUT payload includes the edited `items` (or that the guard stays dirty / a warning is shown) — fails today.
|
||||
|
||||
### H4. Received-invoices list is paginated server-side (25/page) but the UI sends no `page` param and renders no Pagination control — rows 26+ are permanently hidden
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/admin/pages/ReceivedInvoices.tsx:265`
|
||||
- **Failure scenario:** `receivedInvoiceListOptions` hits `/received-invoices`, which applies `skip`/`take` with `parsePagination`'s default limit of 25. The component builds the query with no `page`/`perPage`, reads only `listQuery.data?.data` (the first 25 rows), and renders NO `<Pagination>`. The "Celkem" footer is sourced from the separate `/received-invoices/list-totals` over the FULL filtered set, so with 26+ rows the displayed total visibly disagrees with the on-screen rows. The sibling issued-invoices tab (`Invoices.tsx`) correctly uses `usePaginatedQuery` + `<Pagination>`.
|
||||
- **Repro:** Seed 26 CZK received invoices in one month. `GET /received-invoices?month=6&year=2026` returns `data.length=25`, `pagination.total=26`; `GET /received-invoices/list-totals?...` returns 26000 CZK. In the UI (Faktury → Přijaté, June 2026) the table shows 25 rows summing to 25000 while the footer shows 26000 — and the 26th invoice is unreachable.
|
||||
- **Pinning test:** With 26 received invoices in a month, assert the page requests page 2 (or renders a pager) and that all 26 are reachable — fails today.
|
||||
|
||||
### H5. Odin invoice import: Czech-format dates silently corrupt month/year (wrong month or NaN) in `received_invoices`
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/admin/components/odin/InvoiceReviewCard.tsx:79`
|
||||
- **Failure scenario:** The review card exposes "Datum vystavení"/"Datum splatnosti" as free-text fields; `OdinChat.saveInvoice` sends the raw string. The multipart schema validates `issue_date` only as `z.string().max(255).nullish()`, so it passes. The route derives `invoiceMonth = new Date(issue_date).getMonth()+1` / `getFullYear()` with no validity guard. `new Date("15.03.2026")` → Invalid Date → `NaN` (day>12); `new Date("12.6.2026")` → December 2026 (wrong month). NAS save (line 410) runs BEFORE the DB create (line 420), so for the NaN case Prisma rejects into the `UnsignedTinyInt`/`UnsignedSmallInt` columns → HTTP 500 with an orphaned NAS file; for day≤12 it silently files under the wrong month/year.
|
||||
- **Repro:** In Odin, edit an extracted invoice's issue date to `15.03.2026` and Save → 500 + orphaned NAS file. Use `12.6.2026` → invoice silently filed under month 12. Equivalent: `POST /api/admin/received-invoices` (multipart) with `issue_date:"15.03.2026"`.
|
||||
- **Pinning test:** `POST /received-invoices` with `issue_date="15.03.2026"` should return a 400 (or normalize) — fails today (500 + NaN write). Fix: use `isoDateString` coercion / validity guard.
|
||||
|
||||
### H6. Leave-request approval charges vacation/sick balance for Czech public holidays that fall inside the range
|
||||
|
||||
- **Severity:** High
|
||||
- **File:** `src/routes/admin/leave-requests.ts:222`
|
||||
- **Failure scenario:** Both the request-creation loop (lines 90–97) and the approval loop (lines 222–244) count business days with a weekend-only filter (`dow !== 0 && dow !== 6`); the file never imports `isHoliday`. So weekday Czech public holidays inside the range are counted as charged leave days, and approval increments `vacation_used`/`sick_used` by `totalBusinessDays * 8` including them. The sibling `attendance.service.createLeave` (line 1270) correctly skips `isHoliday(...)`, and `getBusinessDaysInMonth` excludes holidays from the work fund — so the deduction is a double charge for a day already paid/free.
|
||||
- **Repro:** Employee `POST /api/admin/leave-requests` `{leave_type:"vacation", date_from:"2026-05-01", date_to:"2026-05-09"}` (1.5. and 8.5. are weekday holidays in 2026) → `total_hours=48`. Approver `PUT /.../{id}` `{status:"approved"}` → `vacation_used` grows by 48h instead of 32h; holiday dates are recorded as consumed vacation in `attendance`.
|
||||
- **Pinning test:** Approve a vacation request spanning a weekday public holiday; assert `vacation_used` increased only by the non-holiday business hours (fails today: includes the holiday).
|
||||
|
||||
---
|
||||
|
||||
## MEDIUM
|
||||
|
||||
### M1. Invoice date fields accept arbitrary strings and write a day early to `@db.Date` when a datetime value is submitted
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/services/invoices.service.ts:533`
|
||||
- **Failure scenario:** `CreateInvoiceSchema`/`UpdateInvoiceSchema` type `issue_date`/`due_date`/`tax_date`/`paid_date` as plain `z.string().max(255).nullish()` (not `isoDateString`). `createInvoice`/`updateInvoice` do `new Date(String(...))` straight into the `@db.Date` columns. A round-tripped API value like `"2025-03-15T00:00:00"` (the `toJSON` override emits local time, no `Z`) parses as local Prague → `2025-03-14 22:00 UTC` → Prisma truncates to `2025-03-14`. The invoice then also lands in the wrong month bucket in `getInvoiceStats`/`buildInvoiceWhere`. Every other `@db.Date`-writing module uses `isoDateString` (which slices the time off); invoices is the lone outlier.
|
||||
- **Repro:** `POST /api/admin/invoices` with `issue_date:"2025-03-01T00:00:00"` → DB stores `2025-02-28`; `GET .../stats?month=3&year=2025` excludes it and inflates February.
|
||||
- **Pinning test:** Create an invoice with `issue_date="2025-03-01T00:00:00"`; assert the stored date is `2025-03-01` (fails today: `2025-02-28`). Fix: `isoDateString.nullish()`.
|
||||
|
||||
### M2. `order_items.unit` Zod cap (255) exceeds DB column `VarChar(20)` → Prisma 500 on long unit strings
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/schemas/orders.schema.ts:15`
|
||||
- **Failure scenario:** `unit: z.string().max(255)` vs `order_items.unit @db.VarChar(20)` (`schema.prisma:330`). A 21–255 char unit passes Zod, overflows the column (P2000), and surfaces as 500 (the create catch only re-maps `status`-bearing errors; update has no try/catch). The sibling offers/issued-orders schemas correctly use `.max(20)`.
|
||||
- **Repro:** `POST /api/admin/orders` (JSON) `items:[{ description:"Test", quantity:1, unit_price:100, unit:"abcdefghijklmnopqrstuvwxyz" }]` → HTTP 500 instead of 400. (The MUI form enforces `maxLength:20` client-side, so this is an API/non-browser vector.)
|
||||
- **Pinning test:** `parseBody(OrderItemSchema, { unit: "x".repeat(21), ... })` should 400 at Zod — fails today. Fix: `.max(20)`.
|
||||
|
||||
### ~~M3. Offer PDF page footer ("Strana X z Y") never renders~~ — WITHDRAWN 2026-06-12 (false positive)
|
||||
|
||||
- **Status:** **Withdrawn** — user verified the footer DOES render in production.
|
||||
- **Why the audit got it wrong:** the finding (and all three verification lenses) trusted the repo's own documentation — the `html-to-pdf.ts:68-74` comment and the CLAUDE.md line "Chromium has no CSS margin-box footers". That fact has been stale since **Chrome 131 (Nov 2024), which implemented CSS `@page` margin boxes**; the project runs Puppeteer 24.40 (bundled Chrome 146 locally) and prod renders with system Chromium 149, both far past 131, so the offer's `@bottom-center { counter(page) }` footer renders fine. No lens rendered an actual PDF — documentation poisoning, not a code bug.
|
||||
- **Real follow-up (doc-only, Low):** correct the outdated claim in `html-to-pdf.ts` and CLAUDE.md so future work doesn't repeat this; the `footerTemplate` mechanism and the CSS margin-box mechanism are now BOTH valid, coexisting approaches.
|
||||
|
||||
### M4. `customer_order_number` Zod cap (255) exceeds DB column `VarChar(100)` → Prisma 500
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/schemas/orders.schema.ts:54`
|
||||
- **Failure scenario:** `customer_order_number: z.string().max(255)` vs `orders.customer_order_number @db.VarChar(100)` (`schema.prisma:356`). A 101–255 char value passes Zod, overflows the column (P2000 under strict mode), and surfaces as 500 instead of 400 (no P2003/P2000 mapping; create catch only handles `status`-bearing errors).
|
||||
- **Repro:** `POST /api/admin/orders` (JSON) `{ customer_order_number: "A".repeat(150), currency:"CZK", language:"cs", status:"prijata" }` → HTTP 500; no order created. Same on `PUT /api/admin/orders/:id`.
|
||||
- **Pinning test:** `parseBody(CreateOrderSchema, { customer_order_number: "A".repeat(150), ... })` should 400 — fails today. Fix: `.max(100)` on both schemas.
|
||||
|
||||
### M5. Foreign-currency invoice PDF returns HTTP 500 (and fails to archive) when the CNB rate lookup throws
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/invoices-pdf.ts:411`
|
||||
- **Failure scenario:** For a EUR invoice, `const cnbRate = isForeign ? await getRate(currency, issueDateStr) : 1.0` is unguarded. When CNB is unreachable and no cached entry exists for the issue date, `getRate` throws "Nepodařilo se získat aktuální kurzy z ČNB", which propagates to the route's catch and returns the 500 error page — blocking BOTH preview and NAS archival, even though the rate only feeds the cosmetic CZK-conversion footnote. Sibling consumers (`received-invoices` stats, `ai-tools`) wrap `toCzk` and degrade per-row; the PDF path has no fallback.
|
||||
- **Repro:** EUR invoice with a back-dated/never-fetched issue date, CNB unreachable → `GET /api/admin/invoices-pdf/:id` (preview) or `?save=1` (archive) returns 500; the `save=1` archival is silently swallowed client-side, leaving no NAS copy.
|
||||
- **Pinning test:** Mock `getRate` to throw, render a foreign-currency invoice PDF; assert a non-error response (PDF rendered with the conversion line omitted) — fails today (500).
|
||||
|
||||
### M6. `updateProject` sets FK fields with no existence check → FK violation 500
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/services/projects.service.ts:115`
|
||||
- **Failure scenario:** `updateProject` writes `customer_id`/`responsible_user_id`/`quotation_id`/`order_id` straight into `prisma.projects.update` with only int coercion and no `findUnique`. The FKs are `onDelete: Restrict`, so a non-existent id raises P2003 → generic 500. `createProject` validates `customer_id`/`responsible_user_id` and returns clean Czech 400s; the update path is the inconsistent gap.
|
||||
- **Repro:** `PUT /api/admin/projects/1` `{ "customer_id": 999999 }` → HTTP 500 "Interní chyba serveru" instead of "Zákazník nenalezen" 400. Same for the other three FK fields.
|
||||
- **Pinning test:** `PUT /projects/:id` with a non-existent `customer_id`; assert a 400 with a Czech "nenalezen" message — fails today (500). Fix: mirror `createProject`'s existence checks.
|
||||
|
||||
### M7. Date-range filters/reports exclude the whole `date_to` day (`lte` against UTC-midnight) — inclusive end date silently drops same-day records
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/warehouse.ts:1038`
|
||||
- **Failure scenario:** Receipts/issues filters and the project-consumption / movement-log reports build `created_at: { lte: new Date(date_to) }`. `new Date("2026-06-12")` parses as UTC midnight = 02:00 Prague; `created_at` is `@db.DateTime(0)` storing local-time instants, so a receipt at 09:00 Prague (07:00Z) is `> 00:00Z` and excluded. The entire requested end day disappears from filtered lists and report totals.
|
||||
- **Repro:** Confirm a receipt today at 09:00 Prague. `GET /admin/warehouse/receipts?date_from=2026-06-12&date_to=2026-06-12` returns zero rows. Reports for a period ending 2026-06-12 under-report the last day.
|
||||
- **Pinning test:** Create a same-day receipt at 09:00 local, filter `date_to` = that date; assert the receipt is returned — fails today. Fix: half-open `lt utcMidnightOfLocalDay(date_to + 1 day)`.
|
||||
|
||||
### M8. POST/PUT receipts & issues 500 on nonexistent or deleted FK ids instead of a clean Czech 400
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/warehouse.ts:1117`
|
||||
- **Failure scenario:** The receipts/issues create+update handlers write rows directly with no FK-existence pre-check and no try/catch; schemas only int-coerce ids. A deleted/nonexistent `supplier_id`/`location_id`/`item_id`/`project_id`/`batch_id` raises P2003/P2025 → generic 500. The document modules (offers/orders/issued-orders) and `trips.ts` all pre-validate FK existence precisely to avoid this; warehouse omits the guard.
|
||||
- **Repro:** `POST /receipts` `{ items:[{ item_id: 99999999, quantity:1, unit_price:10 }] }` → 500. `POST /issues` `{ project_id: 99999999, items:[{ item_id:<in-stock>, quantity:1 }] }` → 500. `POST /issues` with a valid item + nonexistent explicit `batch_id` → 500.
|
||||
- **Pinning test:** `POST /receipts` with a nonexistent `item_id`; assert a 400 ("Položka nenalezena") — fails today (500).
|
||||
|
||||
### M9. `updateEntry` never re-checks the per-cell cap, so expanding an entry's range pushes a day past `MAX_RECORDS_PER_CELL` and silently hides existing records
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/services/plan.service.ts:597`
|
||||
- **Failure scenario:** `createEntry`/`bulkCreateEntries`/`createOverride` all guard the per-cell cap of 3 via `assertEntryCapAvailable`, but `updateEntry` does not. Expanding an entry's `date_from`/`date_to` onto a day that already holds 3 active entries succeeds, producing 4. `resolveCell`/`resolveGrid` cap display at 3 (newest-first), so the oldest entry silently vanishes from the grid while remaining active in the DB.
|
||||
- **Repro:** Create 3 active entries on 2099-07-01 for user 5; create a 4th on 2099-07-02; `PATCH /plan/entries/<4th>` `{ date_from:"2099-07-01", date_to:"2099-07-01" }` → 200; the grid for that day now shows only 3 of the 4 entries.
|
||||
- **Pinning test:** Fill a day to the cap, then `PATCH` another entry to overlap that day; assert the update is rejected with the cap error — fails today.
|
||||
|
||||
### M10. `POST /users` does not strip `role_id` for non-admins — a `users.create` holder can grant any non-admin role
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/routes/admin/users.ts:63`
|
||||
- **Failure scenario:** The POST handler forwards `role_id` straight to `createUser`; `createUser` only rejects the literal `admin` role. The PUT handler explicitly strips `role_id`/`is_active` for non-admin callers ("Privilege-escalation guard"), so create is an inconsistent escalation surface: a `users.create` holder can mint an account on any high-privilege non-admin role (e.g. one bundling `settings.roles` or `users.edit`) the caller itself lacks. Violates the documented "Role-management writes are admin-only and re-checked" rule.
|
||||
- **Repro:** As account M with only `users.create`, `POST /api/admin/users` `{ ..., role_id: N }` where N is a non-admin role bundling `settings.roles`/`users.edit` → 201; the new account holds permissions M never had.
|
||||
- **Pinning test:** As a non-admin `users.create` caller, POST a user with a privileged `role_id`; assert the created user's role is NOT the privileged one (role stripped, as on PUT) — fails today.
|
||||
|
||||
### M11. `route_from`/`route_to` Zod cap (255) exceeds DB column `VarChar(100)` — 500 or silent truncation
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/schemas/trips.schema.ts:17`
|
||||
- **Failure scenario:** `route_from`/`route_to` cap at `.max(255)` (create lines 17–18, update 29–30) vs `trips.route_from/route_to @db.VarChar(100)` (`schema.prisma:668-669`). The route writes `String(body.route_from)` directly. A 101–255 char route passes Zod, then either 500s (P2000 strict mode, no global Prisma mapping) or silently truncates to 100 chars (data loss). The frontend TextFields have no `maxLength`, so the UI triggers it too.
|
||||
- **Repro:** `POST /api/admin/trips` with a 150-char `route_from` → 500 (or truncated 201). Same on `PUT`.
|
||||
- **Pinning test:** `parseBody(CreateTripSchema, { route_from: "x".repeat(101), ... })` should 400 — fails today. Fix: `.max(100)`.
|
||||
|
||||
### M12. Shared Puppeteer browser disconnecting mid-render fails concurrent PDF requests (no re-acquire/retry)
|
||||
|
||||
- **Severity:** Medium
|
||||
- **File:** `src/utils/html-to-pdf.ts:92`
|
||||
- **Failure scenario:** `getBrowser()` returns the cached module-level browser after a point-in-time `connected` check; `htmlToPdf` immediately does `b.newPage()` with no re-check. Two concurrent renders capture the same handle; if Chromium crashes (OOM/killed) after the guard, both reject. A's finally nulls the shared handle out from under B. Both return 500 even though an immediate retry would relaunch and succeed — there is no re-acquire/retry wrapper.
|
||||
- **Repro:** Fire two simultaneous `GET /api/admin/orders-pdf/5` (always renders, no NAS short-circuit), then `pkill -9 chrome` during the render window → both requests 500; the next request succeeds.
|
||||
- **Pinning test:** Stub the cached browser so `connected` is true at guard time and false at `newPage` time; assert `htmlToPdf` re-acquires and resolves (or both concurrent calls succeed on retry) — fails today.
|
||||
|
||||
---
|
||||
|
||||
## LOW
|
||||
|
||||
### L1. Client-supplied TOTP secret up to 255 chars overflows `VarChar(255)` after encryption, yielding a 500 instead of a 400
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/schemas/auth.schema.ts:30`
|
||||
- **Failure scenario:** `TotpEnableSchema.secret` caps at `.max(255)` on the plaintext, but the stored value is the AES-256-GCM ciphertext (`base64(IV[12] + ciphertext + tag[16])`), which exceeds 255 chars for any plaintext over ~164 chars. `users.totp_secret` is `@db.VarChar(255)`. The pre-write `totp.validate` does not bound secret length, and the attacker controls both `secret` and `code`, so a long secret reaches the write → P2000 → 500 (strict mode) or silent ciphertext truncation that permanently locks the account out.
|
||||
- **Repro:** Authenticated, 2FA-not-enabled user: generate a 250-char base32 secret + matching TOTP code, `POST /api/admin/totp/enable` with the correct password → 500 (or corrupted secret).
|
||||
- **Pinning test:** Enable TOTP with a 250-char secret; assert a 400 (not 500) — fails today. Fix: `.max(64)` (real secrets are 16–32 chars).
|
||||
|
||||
### L2. Offer number sequence is never released on delete when created and finalized in different calendar years
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/services/offers.service.ts:522`
|
||||
- **Failure scenario:** `generateOfferNumber` keys on `new Date().getFullYear()` (finalize year), assigning e.g. `2026/NA/001`. `deleteOffer` derives the release year from `existing.created_at.getFullYear()` (2025) and calls `releaseOfferNumber(2025, "2026/NA/001")`; `releaseSequence` reconstructs the highest as `2025/NA/<n>`, which never equals `2026/NA/001`, so the `deletedNumber === highestNumber` guard is false and the 2026 counter keeps a permanent gap. `invoices.service.ts` solves the same problem correctly by parsing the year out of the document number.
|
||||
- **Repro:** Create a draft `2025-12-30`, finalize it `2026-01-02` → `2026/NA/001`. Delete it → next finalized 2026 offer is `2026/NA/002` (gap; no `2026/NA/001`).
|
||||
- **Pinning test:** Create a draft in year Y, finalize+delete it in year Y+1; assert the Y+1 sequence counter was released — fails today. Fix: parse the year from the assigned number.
|
||||
|
||||
### L3. `customers` list paginates with non-unique sort columns and no `id` tiebreak → unstable pagination
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/routes/admin/customers.ts:54`
|
||||
- **Failure scenario:** `orderBy: { [sortField]: order }` over allow-listed fields (`name`/`city`/`country`/`company_id`, all non-unique) with no `{ id }` tiebreak, used with offset pagination. Rows sharing a sort-key value that straddle a page boundary can reorder between the page-1 and page-2 queries, duplicating one and skipping another. Violates the documented determinism rule; siblings (`issued-orders.ts`, `trips.ts`) use compound `[..., { id }]` orderings. (The same defect exists at `received-invoices.ts:144`.)
|
||||
- **Repro:** Seed customers with a shared `city` straddling a `limit=2` boundary; page through `?sort=city` and observe a customer appearing on two pages while another is skipped.
|
||||
- **Pinning test:** Paginate a sort over duplicate-`city` customers; assert the concatenated pages contain every customer exactly once — fails today. Fix: `orderBy: [{ [sortField]: order }, { id: order }]`.
|
||||
|
||||
### L4. Invoice month navigation does not reset the page index → switching to a sparser month shows an empty table
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/admin/pages/Invoices.tsx:244`
|
||||
- **Failure scenario:** `prevMonth`/`nextMonth` mutate `statsMonth`/`statsYear` but never `setPage(1)` (unlike the status/search handlers). The list query keys on `page` + month, and the server never clamps page to `total_pages`, so paging to page 3 of a busy month then switching to a 1-page month requests `?page=3&month=...` and gets an empty `data` array — empty table for a populated month, with the pager reading "3 of 1".
|
||||
- **Repro:** Open a month with 60+ invoices, go to page 3, click the previous-month chevron to a month with a handful → empty "Zatím nejsou žádné faktury" table. API: `GET /api/admin/invoices?page=3&month=<sparse>&year=<y>` returns `data:[]` with non-zero `total`.
|
||||
- **Pinning test (component):** With `page=3`, fire `nextMonth`; assert `page` resets to 1 — fails today.
|
||||
|
||||
### L5. Issued-orders sub-list keeps its page index when the parent Orders page changes month → empty list for sparser months
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/admin/pages/IssuedOrders.tsx:135`
|
||||
- **Failure scenario:** `IssuedOrders` receives `month`/`year` as props and holds `page` in local state with no effect/key resetting it on prop change (the child is not keyed by month/year, so it doesn't remount). Paging to page 2 of a busy month then moving the parent to a sparse month requests page 2 of the new month → empty `data` → "Zatím žádné vydané objednávky." for a month that has orders on page 1.
|
||||
- **Repro:** Objednávky → Vydané: navigate to a month with ≥26 issued orders, click page 2, then use the parent month chevron to a month with 1–25 orders → empty sub-list. API equivalent: `GET /api/admin/issued-orders?page=2&month=<1..25 orders>&year=<y>` → `data:[]` with non-zero `total`.
|
||||
- **Pinning test (component):** With `page=2`, change the `month` prop; assert `page` resets to 1 (or is clamped to `total_pages`) — fails today.
|
||||
|
||||
### L6. Settings "System" tab save clobbers freshly-saved "Firma" numbering patterns with stale values
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/admin/pages/Settings.tsx:297`
|
||||
- **Failure scenario:** Both tabs edit the same singleton `company_settings` row via `PUT /company-settings`. `sysForm` carries `offer_number_pattern`/`order_number_pattern`/`invoice_number_pattern` (populated once, gated by a never-reset `sysFormInitialized` flag). After editing numbering in the Firma tab (which invalidates `["company-settings"]`), `sysForm` stays stale; saving the System tab sends the whole stale form, and the backend applies every `!== undefined` field, silently reverting the Firma-tab change.
|
||||
- **Repro:** Init the System tab; in the Firma tab change `offer_number_pattern` and save; return to System and save any unrelated field → `offer_number_pattern` reverts to its pre-edit value, with a success toast.
|
||||
- **Pinning test:** PUT the offer pattern, then PUT a stale sysForm carrying the old pattern; assert the offer pattern is NOT reverted (or that System-tab saves omit the numbering fields) — fails today.
|
||||
|
||||
### L7. `start_km`/`end_km` accept decimals but DB columns are `Int` — non-integer odometer reading errors or truncates
|
||||
|
||||
- **Severity:** Low
|
||||
- **File:** `src/schemas/trips.schema.ts:15`
|
||||
- **Failure scenario:** `start_km`/`end_km` use `nonNegativeNumberFromForm` (only `Number.isFinite && >=0`, no integer refine), but the columns are `Int`. A decimal passes Zod, reaches the `Int` column → Prisma validation 500 or MySQL truncation (corrupting the reading and derived distance, propagated into `vehicles.actual_km`). Same mismatch for `vehicles.initial_km`/`actual_km`. The UI's `parseInt` is used only for the distance widget, not the submitted payload, so the browser is vulnerable too.
|
||||
- **Repro:** `POST /api/admin/trips` `{ vehicle_id, trip_date:"2098-01-15", start_km:100.5, end_km:1200.7, route_from:"A", route_to:"B" }` → 500 (or truncated values).
|
||||
- **Pinning test:** `parseBody(CreateTripSchema, { start_km: 100.5, ... })` should 400 — fails today. Fix: `nonNegativeIntFromForm` for the four km fields.
|
||||
|
||||
### L8. AI monthly budget control: severity-mismatched permission, date asymmetry, dead UI button, currency overflow, audit-log boundary (grouped low-severity cluster)
|
||||
|
||||
These five independently-confirmed low-severity findings share the "minor blast radius / narrow trigger" profile. Each is real and pinnable.
|
||||
|
||||
- **L8a. Company-wide AI monthly budget is mutable by any `ai.use` holder (not admin/settings).** `src/routes/admin/ai.ts:58`. `PUT /api/admin/ai/budget` is gated only by `requirePermission("ai.use")`, an ordinary grantable permission. Setting `budget_usd=0` makes `assertBudgetAvailable` return 402 for everyone (admins included) → company-wide AI DoS; setting `1000000` removes the cost cap. The parallel `company-settings` writes are gated behind `settings.company`/`settings.system`.
|
||||
- **Repro:** As any `ai.use` holder, `PUT /api/admin/ai/budget {"budget_usd":0}` → all `ai/chat` and `extract-invoices` calls 402.
|
||||
- **Pinning test:** Call `PUT /ai/budget` as a non-admin `ai.use`-only user; assert 403 — fails today. Fix: gate behind `settings.company`/admin.
|
||||
|
||||
- **L8b. Audit-log `date_from` filter boundary shifted ~2h vs `date_to` (UTC vs local parsing).** `src/routes/admin/audit-log.ts:46`. `from = new Date(date_from)` parses as UTC midnight (02:00 Prague), while `to = new Date(date_to + "T23:59:59")` parses as local — so events between 00:00 and 02:00 Prague on the from-date are silently excluded.
|
||||
- **Repro:** `GET /api/admin/audit-log?date_from=2026-06-12&date_to=2026-06-12` omits a row logged at 01:30 Prague that day.
|
||||
- **Pinning test:** Insert an audit row at 01:30 local, filter for that day; assert it's returned — fails today.
|
||||
|
||||
- **L8c. Draft invoice shows a non-functional "Zobrazit fakturu" PDF button that always errors.** `src/admin/pages/InvoiceDetail.tsx:1805`. The button render guard lacks the `status !== "draft"` check that `OfferDetail`/`IssuedOrderDetail` have; clicking it on a draft opens a blank tab, 404s `/file`, closes the tab, and toasts an error.
|
||||
- **Repro:** Open a draft invoice, click "Zobrazit fakturu" → blank tab flash + "PDF soubor nenalezen" toast.
|
||||
- **Pinning test:** Render `InvoiceDetail` for a draft; assert the PDF button is not rendered — fails today. Fix: add `&& invoice.invoice_number` (or non-draft) to the guard.
|
||||
|
||||
- **L8d. Odin "Měna" / received-invoice currency over 3 chars 500s the save (`VarChar(3)` vs schema `max(20)`).** `src/components/odin/InvoiceReviewCard.tsx:67` / `src/schemas/received-invoices.schema.ts:11`. A free-text currency like "Koruna" passes Zod (`max(20)`) but overflows `received_invoices.currency @db.VarChar(3)` (P2000 → 500), AND because the NAS write precedes the DB create, the uploaded file is orphaned. The same module's `description` (`max(8000)` vs `VarChar(500)`) and `invoice_number` (`max(255)` vs `VarChar(100)`) are also misaligned.
|
||||
- **Repro:** Save an Odin invoice with `currency:"Koruna"` → 500 + orphaned NAS file. Equivalent: `POST /received-invoices` multipart with `currency:"Koruna"`.
|
||||
- **Pinning test:** `parseBody(CreateReceivedInvoiceSchema, { currency:"Koruna", ... })` should 400 — fails today. Fix: `currency .max(3)`, `description .max(500)`, `invoice_number .max(100)`.
|
||||
|
||||
- **L8e. Warehouse supplier `ico`/`dic` Zod caps (255) exceed `VarChar(20)` columns.** `src/schemas/warehouse.schema.ts:34`. A >20-char `ico`/`dic` (bad paste) passes Zod and 500s at Prisma. Low realism (real IČO=8 digits) but a genuine 500-vs-400 defect; the customers schema (`company_id`/`vat_id`) shares it.
|
||||
- **Repro:** `POST /api/admin/warehouse/suppliers` `{ name:"Test", ico:"123456789012345678901" }` → 500.
|
||||
- **Pinning test:** `parseBody(CreateSupplierSchema, { ico:"x".repeat(21), ... })` should 400 — fails today. Fix: `.max(20)`.
|
||||
|
||||
> **Adjacent uncited Zod-cap mismatches confirmed during verification** (same bug class, fix alongside the above so the gap is closed once): invoice line-item `description` (`max(8000)` vs `VarChar(500)`) and `unit` (`max(255)` vs `VarChar(20)`) — `src/schemas/invoices.schema.ts:13,16`, **High** blast radius (whole invoice save rolls back); invoice bank/payment fields `payment_method`/`constant_symbol`/`bank_swift`/`bank_iban`/`bank_account` (caps 255 vs `VarChar(50)/VarChar(20)`) — `src/schemas/invoices.schema.ts:30-35`, **Medium**; warehouse `/items` list ignores the client `sort` param and sorts by non-unique `name` with no `id` tiebreak — `src/routes/admin/warehouse.ts:662`, **Low**; year-spanning leave request books all hours against the start year's balance only — `src/routes/admin/leave-requests.ts:195`, **Medium**; Dashboard "Přidat jízdu" quick action omits `["vehicles"]` invalidation — `src/admin/components/dashboard/DashQuickActions.tsx:184`, **Low**. These were verified `real` but fall outside the 29-item cited set; treat them as a fast-follow batch.
|
||||
|
||||
---
|
||||
|
||||
## Recommended Fix Order (dependencies considered)
|
||||
|
||||
**Phase 0 — Data-integrity criticals first (financial/stock corruption, silent & cumulative).** These corrupt persisted state and worsen on retry; fix before anything cosmetic.
|
||||
|
||||
1. **C3** `confirmInventorySession` `return`→`throw` (one-line change; stops repeatable phantom inventory). Trivial, highest leverage.
|
||||
2. **C2** `confirmIssue` cross-line over-issue guard (add a running per-batch tally / up-front availability pass, mirroring the existing `confirmIssue` validation-first pattern; consider a `(issue_id, batch_id)` unique constraint as a backstop).
|
||||
3. **C1** leave-balance restore on attendance delete — but **do C1 together with H6 and the year-spanning leave finding**, since all three live in the leave/attendance balance code and a single corrected helper (per-day, holiday-aware, per-year accumulation, with an inverse on delete) resolves them coherently. Fix the holiday-counting (H6) and per-year split first, then route delete through the same helper.
|
||||
|
||||
**Phase 1 — Security / privilege & session correctness.** 4. **H1** session-reuse misclassification (gate the reuse branch on `replaced_by_hash` alone; reorder vs the expiry check). Self-contained; high user impact. 5. **M10** `POST /users` role-strip for non-admins; **L8a** AI budget permission gate. Both are permission-boundary one-liners.
|
||||
|
||||
**Phase 2 — The Zod-cap-vs-DB-column batch (single coordinated sweep).** All of **H2, M2, M4, M11, L1, L8d, L8e** plus the adjacent invoice item/bank caps share one mechanism and one fix shape (`.max()` alignment + optionally a global P2000→400 mapping in `server.ts`). Do them in one pass with a shared "cap-must-fit-column" test helper so the class is closed, not whacked one at a time. Highest blast radius within the batch (whole-save rollback): invoice item caps, then H2.
|
||||
|
||||
> **Phase 2 follow-ups (2026-06-12, deliberately deferred):** (1) the optional
|
||||
> global P2000→400 mapping in the `server.ts` error handler was NOT added —
|
||||
> `server.ts` exports no app builder, so the mapping would be untestable
|
||||
> without first extracting an exported `buildApp()`; do the refactor + backstop
|
||||
> together. (2) Frontend `maxLength` attributes on the trips (odkud/kam) and
|
||||
> invoice bank/payment form fields — pure UX polish now that Zod 400s
|
||||
> over-length input with a Czech message; add when next touching those forms.
|
||||
|
||||
**Phase 3 — FK-existence & error-mapping consistency.** **M6** (projects update), **M8** (warehouse receipts/issues), **M5** (CNB graceful degradation). These align the lagging modules with the established offers/orders pre-validation pattern; a shared P2003→Czech-400 mapping (added in Phase 2 if you choose the global-handler route) reduces the per-site work.
|
||||
|
||||
**Phase 4 — Date/timezone boundaries.** **M1** (invoice date `isoDateString`), **M7** (warehouse `date_to` half-open), **H5** (Odin Czech-date), **L8b** (audit-log `from`). Group because they share the documented date-boundary helpers (`isoDateString`, `utcMidnightOfLocalDay`); fixing M1/H5 also removes a day-shift class.
|
||||
|
||||
**Phase 5 — Pagination determinism & frontend state.** **H4** (received-invoices pager — add the missing `usePaginatedQuery`/`<Pagination>`), **L3** (customers + received-invoices `id` tiebreak), **L4/L5** (page-reset on month change), **M9** (plan update cap), **H3** (issued-order transition flush edits + don't `markClean` stale state). H4 is the largest UI change; the rest are small, independent guards.
|
||||
|
||||
**Phase 6 — Cosmetic / low-blast cleanup (parallelizable, no dependencies).** ~~M3~~ (withdrawn; only the stale Chromium-footer comment in `html-to-pdf.ts`/CLAUDE.md remains as a doc fix), **M12** (Puppeteer re-acquire/retry), **L2** (offer number release year), **L6** (Settings System/Firma clobber), **L7** (km integer coercion), **L8c** (draft PDF button guard), warehouse `/items` sort param + tiebreak, and the Dashboard `["vehicles"]` invalidation.
|
||||
|
||||
Rationale for ordering: persisted-data corruption (Phase 0) cannot be allowed to accumulate; security boundaries (Phase 1) are cheap and high-impact; the cap batch (Phase 2) and FK/error mapping (Phase 3) are most efficient done as coordinated sweeps that share a fix shape and tests; date boundaries (Phase 4) share helpers; UI/pagination (Phase 5) depend on nothing earlier but benefit from the cleaner backend; everything in Phase 6 is independent and can be parallelized across contributors.
|
||||
714
CLAUDE.md
714
CLAUDE.md
@@ -1,24 +1,26 @@
|
||||
# CLAUDE.md — boha-app-ts
|
||||
|
||||
Business management system for a Czech company, rewritten from PHP to TypeScript/Node.js.
|
||||
Handles attendance, invoicing, leave/trips, projects, vehicles, and HR operations.
|
||||
Handles attendance, invoicing, offers/orders, leave/trips, projects, warehouse, vehicles, and HR operations.
|
||||
|
||||
---
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
| -------------- | ------------------------------------------------------------- |
|
||||
| Runtime | Node.js, TypeScript 5.9.3 (strict) |
|
||||
| HTTP Framework | Fastify 5.8.2 |
|
||||
| ORM | Prisma 6.19.2 → MySQL |
|
||||
| Auth | JWT (HS256, 15 min) + TOTP 2FA (RFC 6238, otpauth) + bcryptjs |
|
||||
| Validation | Zod 4.3.6 |
|
||||
| Frontend | React 18.3.1 + Vite 8.0.0 + Material UI v7 (Emotion) |
|
||||
| Testing | Vitest 4.1.0 + Supertest |
|
||||
| PDF | Puppeteer 24.x |
|
||||
| Email | nodemailer 8.x |
|
||||
| Cron | node-cron 4.x |
|
||||
| Layer | Technology |
|
||||
| -------------- | ----------------------------------------------------------------------------------------------------- |
|
||||
| Runtime | Node.js, TypeScript (strict, all tsconfigs) |
|
||||
| HTTP Framework | Fastify 5 |
|
||||
| ORM | Prisma 7 (Rust-free client + @prisma/adapter-mariadb; datasource lives in `prisma.config.ts`) → MySQL |
|
||||
| Auth | JWT (HS256, 15 min) + TOTP 2FA (RFC 6238, otpauth) + bcryptjs |
|
||||
| Validation | Zod 4 |
|
||||
| Frontend | React 19 + Vite + Material UI v7 (Emotion) + React Query |
|
||||
| Testing | Vitest + Supertest against a real `app_test` DB |
|
||||
| PDF | Puppeteer (stay on 24.x — v25 is ESM-only, conflicts with the CJS server build) |
|
||||
| Email / Cron | nodemailer / node-cron |
|
||||
| AI | @anthropic-ai/sdk → claude-sonnet-4-6 ("Odin" assistant) |
|
||||
|
||||
(Exact versions live in `package.json` — don't trust any pinned here.)
|
||||
|
||||
---
|
||||
|
||||
@@ -26,34 +28,28 @@ Handles attendance, invoicing, leave/trips, projects, vehicles, and HR operation
|
||||
|
||||
```
|
||||
src/
|
||||
├── server.ts # Fastify server entry point — plugins, routes, error handler
|
||||
├── server.ts # Fastify entry — plugins, routes, error handler
|
||||
├── routes/admin/ # HTTP route handlers (one file per entity)
|
||||
├── services/ # Business logic (no classes, exported functions, uses Prisma directly)
|
||||
├── schemas/ # Zod validation schemas (one file per entity)
|
||||
├── middleware/ # auth.ts (requireAuth, requirePermission, optionalAuth)
|
||||
│ # security.ts (CSP, HSTS, security headers)
|
||||
├── utils/ # totp.ts, pdf.ts, email.ts, audit.ts, formatters, etc.
|
||||
├── config/ # env.ts (config singleton, Date.toJSON override)
|
||||
├── types/ # index.ts (AuthData, JwtPayload, ApiResponse, re-exports from Prisma)
|
||||
├── admin/ # React 18 + Material UI frontend (~105 .tsx files)
|
||||
├── services/ # Business logic (no classes, exported functions, own Prisma)
|
||||
├── schemas/ # Zod validation schemas (one file per entity; shared coercers in common.ts)
|
||||
├── middleware/ # auth.ts (requireAuth/requirePermission), security.ts (CSP, HSTS)
|
||||
├── utils/ # totp, email, audit, date, pdf-shared, content-disposition, html-to-pdf, …
|
||||
├── config/ # env.ts (config singleton, TZ + Date.toJSON override)
|
||||
├── types/ # AuthData, JwtPayload, ApiResponse, Prisma re-exports
|
||||
├── admin/ # React 19 + MUI v7 frontend
|
||||
│ ├── AdminApp.tsx # Router + lazy-loaded pages
|
||||
│ ├── theme.ts # MUI theme — light/dark color schemes, tokens, component defaults
|
||||
│ ├── GlobalStyles.tsx # App-wide global styles via MUI <GlobalStyles> (reset, typography, utilities)
|
||||
│ ├── ui/ # MUI component kit (AppShell, Button, DataTable, Modal, …) — pages import from here
|
||||
│ ├── context/ # AuthContext, AlertContext (ThemeContext lives in src/context/)
|
||||
│ ├── components/ # Non-page components: RichEditor (Quill), PlanGrid, file manager, dashboard/ + warehouse/ widgets
|
||||
│ ├── theme.ts / GlobalStyles.tsx
|
||||
│ ├── ui/ # MUI component kit — pages import from here
|
||||
│ ├── components/ # Non-page components incl. document/ (shared doc editors), odin/, warehouse/
|
||||
│ ├── context/ # AuthContext, AlertContext (ThemeContext lives in src/context/)
|
||||
│ ├── pages/ # One file per page/feature
|
||||
│ ├── lib/ # React Query options & mutations (queries/) + shared label maps
|
||||
│ ├── hooks/ # usePaginatedQuery, useTableSort, useDebounce, useReducedMotion, …
|
||||
│ └── utils/ # api.ts (fetch wrapper with token refresh), formatters, helpers
|
||||
└── __tests__/ # Vitest tests (~14 files: auth, numbering, warehouse, plan, invoices, …)
|
||||
│ ├── lib/queries/ # React Query options + useApiMutation
|
||||
│ ├── hooks/ # usePaginatedQuery, useDocumentLock, useUnsavedChangesGuard, useDocumentPdf, …
|
||||
│ └── utils/ # api.ts (apiFetch with token refresh), formatters
|
||||
└── __tests__/ # Vitest suites (server-side only; real app_test DB)
|
||||
|
||||
prisma/
|
||||
├── schema.prisma # 49 models, MySQL, snake_case columns
|
||||
└── migrations/ # Applied migrations
|
||||
|
||||
dist/ # Compiled server (CommonJS, ES2022)
|
||||
dist-client/ # Built frontend (Vite, ES2020)
|
||||
prisma/ # schema.prisma (snake_case columns) + migrations/
|
||||
dist/ dist-client/ # Compiled server (CommonJS) / built frontend (Vite)
|
||||
```
|
||||
|
||||
---
|
||||
@@ -61,448 +57,380 @@ dist-client/ # Built frontend (Vite, ES2020)
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev # Starts server in watch mode (manage frontend separately)
|
||||
npm run dev:server # tsx watch src/server.ts
|
||||
npm run dev:client # Vite dev server
|
||||
|
||||
# Build
|
||||
npm run build # Build server + client
|
||||
npm run build:server # tsc -p tsconfig.server.json → dist/
|
||||
npm run build:client # vite build → dist-client/
|
||||
|
||||
# Run (production)
|
||||
npm start # node dist/server.js
|
||||
|
||||
# Tests
|
||||
npm test # vitest run (single pass)
|
||||
npm run test:watch # vitest watch
|
||||
|
||||
# Database
|
||||
npx prisma migrate dev # Create migration from schema changes + apply to dev
|
||||
npx prisma migrate dev --name <descriptive_name> # Named migration
|
||||
npx prisma migrate deploy # Apply pending migrations to production
|
||||
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
|
||||
npm run dev:server # tsx watch src/server.ts (frontend: npm run dev:client)
|
||||
npm run build # server + client
|
||||
npm test # vitest run — against app_test via .env.test
|
||||
npm run typecheck # tsc -b --noEmit (NOT -p tsconfig.json — that solution file checks nothing)
|
||||
npm run lint # eslint . — react-hooks/rules-of-hooks is an ERROR; keep 0 errors
|
||||
npm run format # prettier --write .
|
||||
npx prisma generate # after every schema change (client is not committed)
|
||||
npx prisma studio # DB browser
|
||||
```
|
||||
|
||||
**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.
|
||||
**Before any migration, ask the user to stop their dev server and wait for
|
||||
confirmation** (the running server holds DB connections).
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Required:
|
||||
Required: `DATABASE_URL`, `JWT_SECRET`, `TOTP_ENCRYPTION_KEY` (64-char hex).
|
||||
|
||||
```
|
||||
DATABASE_URL=mysql://user:pass@host:3306/dbname
|
||||
JWT_SECRET=<64-char hex string>
|
||||
TOTP_ENCRYPTION_KEY=<64-char hex string>
|
||||
```
|
||||
Optional (defaults in `src/config/env.ts`): `PORT` (prod 3001; dev default 3050
|
||||
hardcoded), `HOST`, `APP_ENV=local|production` (controls CSP/CORS/HSTS),
|
||||
`ACCESS_TOKEN_EXPIRY`, `REFRESH_TOKEN_SESSION_EXPIRY`,
|
||||
`REFRESH_TOKEN_REMEMBER_EXPIRY`, `NAS_PATH` (project files),
|
||||
`NAS_INVOICES` + `NAS_ORDERS` (document PDF archives — split trees),
|
||||
`MAX_UPLOAD_SIZE`, `CONTACT_EMAIL_TO/FROM`, `SMTP_FROM`, `LEAVE_NOTIFY_EMAIL`,
|
||||
`APP_URL`, `CORS_ORIGINS`, `ANTHROPIC_API_KEY` (Odin self-hides without it).
|
||||
|
||||
Optional (with defaults):
|
||||
|
||||
```
|
||||
PORT=3001 # Production port (dev default: 3050, hardcoded in server.ts)
|
||||
HOST=127.0.0.1
|
||||
APP_ENV=local|production # Default: local. Controls CSP, CORS, HSTS
|
||||
ACCESS_TOKEN_EXPIRY=900 # 15 minutes
|
||||
REFRESH_TOKEN_SESSION_EXPIRY=3600 # 1 hour
|
||||
REFRESH_TOKEN_REMEMBER_EXPIRY=2592000 # 30 days
|
||||
NAS_PATH=Z:/02_PROJEKTY # Network share for project files
|
||||
MAX_UPLOAD_SIZE=52428800 # 50MB
|
||||
CONTACT_EMAIL_TO=
|
||||
CONTACT_EMAIL_FROM=
|
||||
SMTP_FROM=
|
||||
LEAVE_NOTIFY_EMAIL=
|
||||
APP_URL= # Used in email links
|
||||
CORS_ORIGINS= # Comma-separated, production only
|
||||
```
|
||||
|
||||
Use `.env` for dev, `.env.test` for tests.
|
||||
`.env` for dev, `.env.test` for tests (both gitignored — **never edit env
|
||||
files; the user manages them**).
|
||||
|
||||
---
|
||||
|
||||
## Architecture & Key Patterns
|
||||
|
||||
### Request Flow
|
||||
### Request flow
|
||||
|
||||
```
|
||||
Request → CORS → Cookie → Rate-limit → Security headers
|
||||
→ requirePermission() or requireAuth()
|
||||
→ Zod schema validation (parseBody helper)
|
||||
→ Route handler
|
||||
→ Service function
|
||||
→ Prisma
|
||||
→ success(reply, data) or error(reply, message, status)
|
||||
→ requirePermission() / requireAnyPermission()
|
||||
→ parseBody(Schema) / parseId(param)
|
||||
→ Route handler → Service function → Prisma
|
||||
→ success(reply, data) | error(reply, czechMessage, status)
|
||||
```
|
||||
|
||||
### Response Format
|
||||
### Response format
|
||||
|
||||
All responses use this shape:
|
||||
`{ success: true, data, message?, pagination? }` on success,
|
||||
`{ success: false, error }` on failure. Always the `success()`/`error()`/
|
||||
paginated helpers — never raw `reply.send()`.
|
||||
|
||||
```typescript
|
||||
// Success
|
||||
{ success: true, data: T, message?: string, pagination?: {...} }
|
||||
### Services
|
||||
|
||||
// Error
|
||||
{ success: false, error: string }
|
||||
```
|
||||
|
||||
Use the `success()` and `error()` helpers in routes — never write raw `reply.send()`.
|
||||
|
||||
### Service Pattern
|
||||
|
||||
Services are plain exported async functions, no classes:
|
||||
|
||||
```typescript
|
||||
// src/services/foo.service.ts
|
||||
export async function getFoo(id: number) {
|
||||
const result = await prisma.foo.findUnique({ where: { id } });
|
||||
if (!result) return { error: "Not found", status: 404 };
|
||||
return { data: result };
|
||||
}
|
||||
|
||||
// src/routes/admin/foo.ts
|
||||
const result = await getFoo(id);
|
||||
if ("error" in result) return error(reply, result.error, result.status ?? 400);
|
||||
return success(reply, result.data);
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Routes map service errors to HTTP responses using the pattern above.
|
||||
- Global error handler in `server.ts` catches all unhandled exceptions; returns 500 with Czech message.
|
||||
- **Never silently swallow errors.** Even if a failure is non-fatal, log it: `app.log.error(e, 'context')`.
|
||||
- Error messages are in Czech (this is intentional — user-facing messages, Czech company).
|
||||
Plain exported async functions; services own Prisma, routes stay thin.
|
||||
Preferred error shape: return **token literals** (`"not_found"`,
|
||||
`"invalid_transition"`, `"supplier_not_found"`, …) and let the ROUTE map
|
||||
tokens to Czech messages + HTTP codes (the offers/issued-orders modules are
|
||||
the reference). Legacy services return `{ error: czech, status }` — fine to
|
||||
keep until touched; never the discriminated-union style. Respect soft-delete
|
||||
(`is_deleted: false`) in reads where the model has it.
|
||||
|
||||
### Permissions
|
||||
|
||||
```typescript
|
||||
// Route-level guard
|
||||
fastify.addHook("preHandler", requirePermission("invoices.view"));
|
||||
// or multiple
|
||||
fastify.addHook(
|
||||
"preHandler",
|
||||
requirePermission("invoices.view", "invoices.edit"),
|
||||
);
|
||||
`requirePermission("entity.action")` / `requireAnyPermission(…)`. The admin
|
||||
role bypasses checks (shortcut: `authData.roleName === "admin"` —
|
||||
⚠️ `AuthData` has **`roleName`**, not `role`; don't type `authData` as `any`).
|
||||
GET list/detail endpoints need a permission guard too, NOT bare `requireAuth`
|
||||
(bare-auth reads leak data to any logged-in user). Frontend rule: a _view_
|
||||
permission opens pages read-only; an _edit_ permission unlocks fields and
|
||||
save buttons.
|
||||
|
||||
// Admin role bypasses all permission checks
|
||||
// Permissions follow the pattern: "entity.action" (e.g., "users.create", "invoices.delete")
|
||||
```
|
||||
### Audit
|
||||
|
||||
### Audit Logging
|
||||
|
||||
Call `logAudit()` from `src/utils/audit.ts` whenever data is created/updated/deleted.
|
||||
Pass `oldData` and `newData` so the diff is stored. Audit failures are non-fatal.
|
||||
|
||||
### Validation
|
||||
|
||||
Use Zod schemas from `src/schemas/`. All route bodies must be validated:
|
||||
|
||||
```typescript
|
||||
const body = parseBody(FooSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
```
|
||||
`logAudit()` on every create/update/delete (and security-relevant actions)
|
||||
with `oldValues`/`newValues`. Use a `"(koncept)"`-style fallback in
|
||||
descriptions for unnumbered drafts. Audit failures are non-fatal.
|
||||
|
||||
---
|
||||
|
||||
## Date & Timezone Handling (Critical Gotcha)
|
||||
## Dates & Timezones (Critical — three rules)
|
||||
|
||||
`src/config/env.ts` sets `process.env.TZ = 'Europe/Prague'` and overrides
|
||||
`Date.prototype.toJSON()` to return local time (not UTC). This means:
|
||||
1. **Global override:** `src/config/env.ts` sets `TZ=Europe/Prague` and
|
||||
monkey-patches `Date.prototype.toJSON()` to emit LOCAL time (PHP-migration
|
||||
parity). All API date strings are local. Never assume UTC; never manually
|
||||
offset. Do not remove the override.
|
||||
2. **`@db.Date` columns — Prisma truncates filter Dates to the UTC date
|
||||
part.** A local-midnight boundary (`new Date(y, m, d)` = 22:00/23:00 UTC of
|
||||
the _previous_ day) silently shifts the queried window a day back — this was
|
||||
a 14-site production bug class. Build `@db.Date` filter boundaries and
|
||||
"today" writes as UTC-midnight instants of the LOCAL calendar day:
|
||||
`new Date(Date.UTC(y, m, d))` or `utcMidnightOfLocalDay()` from
|
||||
`src/utils/date.ts`; use half-open `gte`/`lt` ranges; never write a bare
|
||||
`new Date()` into a `@db.Date` column (stores yesterday between 00:00–02:00
|
||||
Prague).
|
||||
3. **Two deliberate write regimes — don't "fix" either:** the plan module
|
||||
does date-only math in UTC; attendance/leave writes `@db.Date` at **local
|
||||
noon** (`new Date(y, m, d, 12, 0, 0)`). Frontend "today" comes from
|
||||
`localDateStr` (server) / `normalizeDateStr`/`todayLocalStr` (client) —
|
||||
**never** `new Date().toISOString().split("T")[0]` (UTC date, a day early
|
||||
in the Prague evening).
|
||||
|
||||
- `JSON.stringify(new Date())` returns local Czech time, not UTC.
|
||||
- All API responses with Date fields will contain local time strings.
|
||||
- Prisma stores dates as UTC internally, but they read back as local due to the TZ setting.
|
||||
- **Never assume UTC** when working with Date objects in this codebase.
|
||||
- When writing new date comparisons or DB queries, use `new Date()` (already local) — do not manually offset.
|
||||
- The override exists for PHP migration compatibility and Czech date display.
|
||||
---
|
||||
|
||||
## Document Modules (offers · orders · issued orders · invoices)
|
||||
|
||||
**Business rules (user/accountant decisions — do not revert):**
|
||||
|
||||
- **VAT exists ONLY on invoices and received invoices.** Offers, order
|
||||
confirmations and issued orders are NOT tax documents: net prices only, one
|
||||
total labeled "Celkem bez DPH" / "Total excl. VAT", no VAT columns, no
|
||||
explanatory VAT notice. Their VAT DB columns were dropped. Invoices created
|
||||
from an order prefill the company default VAT rate.
|
||||
- **Issued orders (objednávky vydané) take suppliers** (`sklad_suppliers`,
|
||||
picker lookup at `GET /issued-orders/suppliers` under orders._ perms);
|
||||
offers take customers. Issued orders share the `orders._` permission family
|
||||
(deliberate).
|
||||
- **PDF families:** the offer PDF keeps its own monochrome customer-facing
|
||||
design; invoices + issued orders share the red-accent (#de3a3a) family.
|
||||
- **Free-form PO content lives in the rich-text sections** ("Obsah" on issued
|
||||
orders, "Rozsah projektu" on offers — CZ/EN titles, Quill content). Issued
|
||||
orders deliberately have NO scope-template picker, NO item templates, NO
|
||||
duplicate action.
|
||||
|
||||
**Platform conventions:**
|
||||
|
||||
- **Deferred numbering:** drafts carry a NULL document number
|
||||
(nullable-unique column); the sequence number is consumed in-transaction on
|
||||
finalize (draft→active / draft→sent) via `numbering.service.ts`, and
|
||||
released-if-highest on delete. Never hardcode numbering; previews use the
|
||||
collision-advancing helpers.
|
||||
- **Status machines:** `VALID_TRANSITIONS` maps in the services; detail
|
||||
responses return `valid_transitions` and the UI renders transition buttons
|
||||
from it. Field edits outside the editable states (offers: draft/active;
|
||||
issued: draft/sent) are rejected with an explicit Czech 400 — status-only
|
||||
payloads still pass.
|
||||
- **Edit locking:** lock/heartbeat/unlock route trio on both offers and
|
||||
issued orders (30 s server TTL = 3 missed 10 s client heartbeats); detail
|
||||
enriches `locked_by {user_id, username, full_name}` only when fresh and
|
||||
held by another user; client side is the shared `useDocumentLock` hook +
|
||||
`LockBanner`.
|
||||
- **PDF serving:** `GET …/:id/file` serves the archived NAS copy and falls
|
||||
back to a live render (re-archiving it) on a miss; drafts 404 (no number),
|
||||
so the UI hides PDF buttons on drafts. Numbered-document archives write to
|
||||
a deterministic path and **overwrite in place** — never uniquePath `_N`
|
||||
suffixes. The issued-order PDF gets language from the document's `language`
|
||||
column and carries a Puppeteer `footerTemplate` footer on every page
|
||||
("Vystavil" left, "Strana X z Y"/"Page X of Y" centered). Two repeating-
|
||||
footer mechanisms coexist and BOTH work: Puppeteer `footerTemplate`
|
||||
(invoices + issued orders — `htmlToPdf(html, { footerTemplate })`) and CSS
|
||||
`@page` margin boxes (`@bottom-center` + `counter(page)`, offer PDF —
|
||||
supported since Chrome 131, Nov 2024). Don't migrate one to the other.
|
||||
- **Shared modules — extend, never fork local copies:**
|
||||
`src/admin/components/document/` (DocumentItemsEditor, SectionsEditor,
|
||||
LockBanner), hooks `useDocumentLock` / `useUnsavedChangesGuard` /
|
||||
`useDocumentPdf` (+ list variant), `src/admin/lib/documentStatus.ts`,
|
||||
CustomerPicker/SupplierPicker, `src/utils/pdf-shared.ts` (escapeHtml,
|
||||
strict cleanQuillHtml, formatNum NBSP, formatCurrency, formatDate),
|
||||
`src/utils/content-disposition.ts` (RFC 5987 — raw filenames with
|
||||
diacritics in headers make Node throw 500s).
|
||||
|
||||
---
|
||||
|
||||
## TOTP / 2FA
|
||||
|
||||
- Secret stored AES-256-GCM encrypted in `users.totp_secret`.
|
||||
- Supports two encoding formats: PHP legacy (base64 iv+cipher+tag) and TS (hex).
|
||||
- Backup codes stored as encrypted JSON array in `users.totp_backup_codes`.
|
||||
- When `company_settings.require_2fa = true`, all users must enroll before accessing the app.
|
||||
- Login flow: password → if 2FA enabled → issue `loginToken` (5 min, single-use) → TOTP verify → issue access + refresh tokens.
|
||||
Secret AES-256-GCM encrypted in `users.totp_secret` (PHP-legacy base64 and TS
|
||||
hex formats both supported); encrypted backup codes with their own
|
||||
`/totp/backup-verify` login endpoint. `company_settings.require_2fa` forces
|
||||
enrollment. Login flow: password → (if enrolled) single-use 5-min
|
||||
`loginToken` → TOTP/backup verify → access + refresh tokens. The enrollment
|
||||
QR is generated locally with the `qrcode` package (never an external QR URL —
|
||||
CSP blocks it and it would leak the secret).
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
Tests live in `src/__tests__/`. They use Vitest + Supertest against a real test database (`.env.test`).
|
||||
|
||||
- The suite spans ~14 files / 152 tests — auth, numbering, warehouse, plan, invoices, exchange-rates, schema coercion, NAS file manager, env, manual-create. Server-side only (no component tests yet).
|
||||
- Use `buildApp()` helper to spin up the Fastify instance for tests.
|
||||
- Tests use `vitest.config.ts` with `environment: 'node'` and 15s timeout.
|
||||
- **Do not mock Prisma** — tests hit a real database to catch schema/query bugs.
|
||||
|
||||
When adding new features, add tests in `src/__tests__/`. Name test files `<feature>.test.ts`.
|
||||
- The suite MUTATES a real MySQL DB → it runs against **`app_test`** (never
|
||||
dev `app`), configured in `.env.test`; `src/__tests__/setup.ts` hard-throws
|
||||
unless `DATABASE_URL` names a `*test*` database.
|
||||
- **After any schema change, apply migrations to the test DB too** or the
|
||||
suite fails: set `DATABASE_URL` to the app_test URL and run
|
||||
`npx prisma migrate deploy`.
|
||||
- To (re)create it: `CREATE DATABASE app_test;` → copy `.env` to `.env.test`
|
||||
with the DB name swapped + `ANTHROPIC_API_KEY=` blanked → migrate deploy →
|
||||
`npx tsx prisma/seed.ts`.
|
||||
- **Do not mock Prisma** — real DB catches schema/query bugs. Mock only true
|
||||
externals (Puppeteer via `vi.mock("../utils/html-to-pdf")`, NAS reads via
|
||||
`vi.spyOn`). Files run serialized (`fileParallelism: false`) to avoid
|
||||
sequence deadlocks. Tests are type-checked by `tsc -b`.
|
||||
- Fixture hygiene: far-future dates (year 2098) or unique prefixes + full
|
||||
cleanup; FK-safe deletion order. New features get tests in
|
||||
`src/__tests__/<feature>.test.ts`.
|
||||
|
||||
---
|
||||
|
||||
## Frontend Conventions
|
||||
|
||||
- Pages are lazy-loaded via `React.lazy()` in `AdminApp.tsx`.
|
||||
- Auth state lives in `AuthContext`; use `useAuth()` hook to access it.
|
||||
- Alerts/toasts use `AlertContext`; use `useAlert()` to show them.
|
||||
- Data fetching uses **React Query** (query options + mutations in `src/admin/lib/queries/`); `src/admin/utils/api.ts` (`apiFetch`) handles token refresh automatically — dedupes concurrent refreshes, and token responses carry `expires_in` so the client refreshes BEFORE expiry (no reactive 401 churn).
|
||||
- Custom hooks: `usePaginatedQuery`, `useTableSort`, `useDebounce`, `useModalLock`, `useReducedMotion`.
|
||||
- Styling: **Material UI v7** (Emotion) — theme in `src/admin/theme.ts`, `sx`/`styled()` in components, app-wide rules in `GlobalStyles.tsx`. **No hand-written `.css` files, no Tailwind.** Use `theme.vars` for colours so light/dark resolve automatically.
|
||||
- Pages lazy-load via `React.lazy()` in `AdminApp.tsx`; auth via `useAuth()`,
|
||||
toasts via `useAlert()`.
|
||||
- **React Query for all fetching** (query options live in
|
||||
`src/admin/lib/queries/`; no fetch-in-useEffect; prefer deriving state over
|
||||
effects). Mutations via `useApiMutation` (opt-in `envelope` mode passes the
|
||||
server message through). `apiFetch` refreshes tokens proactively.
|
||||
- **Rules of Hooks:** every hook runs BEFORE any early return — the
|
||||
`<Forbidden/>` guard goes after all hooks. Lint enforces this as an error.
|
||||
- **Invalidation:** broad domain keys (`["offers"]`, not `["offers","list"]`
|
||||
— prefix matching covers sub-queries), and a mutation invalidates every
|
||||
domain that embeds its data (user CRUD → trips+attendance; vehicle → trips;
|
||||
invoice → orders; attendance/leave → **`["dashboard"]`**). The dashboard
|
||||
also uses `refetchOnMount: "always"` as a backstop. Raw-`apiFetch` writes
|
||||
still must invalidate their domains.
|
||||
- Single sources of truth: status chips/labels in `lib/documentStatus.ts`;
|
||||
audit entity labels in `lib/entityTypeLabels.ts`; plan categories from the
|
||||
DB. Don't duplicate label maps.
|
||||
|
||||
### Query Invalidation Convention
|
||||
### Styling (MUI v7 — no custom .css, no Tailwind)
|
||||
|
||||
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)
|
||||
- Theme in `src/admin/theme.ts` (cssVariables, light+dark schemes); global
|
||||
rules in `GlobalStyles.tsx`; pages compose the kit in `src/admin/ui/` —
|
||||
reach for raw `@mui/material` only for one-off layout/infra.
|
||||
- Colours via **`theme.vars!.palette.*`**; alpha via channel tokens
|
||||
(`rgba(${theme.vars!.palette.primary.mainChannel} / 0.12)`); per-scheme
|
||||
one-offs via `theme.applyStyles("dark", …)`. No hardcoded hex.
|
||||
- Don't regress: status row tints are channel-alpha washes (never `.light`
|
||||
fills — invisible text in dark mode); icon badges are solid `X.main` +
|
||||
white glyph; the theme persists ONLY under MUI's `mui-mode` localStorage
|
||||
key (ThemeContext owns `<html data-theme>`); dialogs lock `<html>` via
|
||||
`useDialogScrollLock`; Modal/ConfirmDialog freeze content through the close
|
||||
fade; ConfirmDialogs stay open with `loading` during their request.
|
||||
- When refactoring pages, **preserve ALL data logic verbatim** (hooks,
|
||||
mutations, invalidate arrays, validation, permissions).
|
||||
|
||||
---
|
||||
|
||||
## Frontend — Styling & MUI (migration complete, shipped in v2.0.0)
|
||||
## AI Assistant — "Odin"
|
||||
|
||||
The admin frontend is **fully on Material UI v7** (Emotion). The old ~7,100 lines of hand-written CSS are gone — **there are no custom `.css` files in `src/admin`**; the only stylesheets imported anywhere are the two third-party libs (`react-quill-new/dist/quill.snow.css`, `leaflet/dist/leaflet.css`). Look-and-feel is "Soft-SaaS shell + dense tables", dark/light preserved. Full history/decisions/gotchas live in agent memory (`project_mui_migration.md`); the original spec/plans are under `docs/superpowers/`.
|
||||
`ai.use`-gated Claude assistant at `/odin` (granted to admin). **Phase 2a:
|
||||
read-only agentic assistant** — chat turns run an agentic loop
|
||||
(`agenticChat` in `src/services/ai.service.ts`, max 6 round-trips, budget
|
||||
re-checked between iterations) over the read-only tools in
|
||||
`src/services/ai-tools.ts` (invoices, offers, orders, projects, customers,
|
||||
warehouse, attendance).
|
||||
|
||||
**Where styling lives**
|
||||
**Security model (do not weaken):** Odin is the **user's delegate** — the
|
||||
tool list is pre-filtered by the caller's permissions AND every handler
|
||||
re-checks them (`ctxCan`); there are **NO write tools** (writes come in
|
||||
Phase 2b as propose→confirm action cards, never autonomous). Tool handlers
|
||||
call the same service functions the routes use. Assistant turns persist
|
||||
their tool trace in `ai_chat_messages.content_json` (plain `content` stays
|
||||
the display text); the UI shows consulted-tool chips. The system prompt
|
||||
enforces plain-text replies (the chat renders pre-wrap text, no Markdown).
|
||||
|
||||
- **Theme — `src/admin/theme.ts`:** `cssVariables` with `colorSchemeSelector: "[data-theme='%s']"`, light + dark `colorSchemes`, tokens, component defaults. Use **`theme.vars!.palette.*`** (the `vars` field is typed optional → `!`) so colours resolve per scheme; for alpha use the channel tokens — `rgba(${theme.vars!.palette.primary.mainChannel} / 0.12)`; for per-scheme one-offs use `theme.applyStyles("dark", { … })`.
|
||||
- **Global rules — `src/admin/GlobalStyles.tsx`:** reset, typography, scrollbar, `::selection`, view-transition timing, and the utility classes (`.text-*`, `.flex-*`, `.mb-*`, …), all theme-aware. (The pre-React bootstrap spinner is inlined in `src/App.tsx` because it mounts before MUI.)
|
||||
- **Component kit — `src/admin/ui/`:** AppShell, Button, Card, TextField, Select (string-based — convert ids at the boundary), DateField/MonthField/TimeField (date-fns v4, cs), Modal, ConfirmDialog (optional `children` + content freeze), DataTable (sortable + mobile card layout + `rowSx`/`rowDanger`/`rowInactive`), Pagination, Tabs/TabPanel, StatusChip, CheckboxField/SwitchField, Field, Alert, PageHeader, FilterBar, StatCard, ProgressBar, FileUpload, EmptyState, LoadingState, ThemeToggle, PageEnter (staggered page entrance), RichEditorRoot/RichTextView (Quill). Dev-only `/ui-kit` showcase route.
|
||||
|
||||
**Building / editing pages**
|
||||
|
||||
- Pages import from the **kit** (`src/admin/ui/`); reach for `@mui/material` (`styled`/`sx`) directly only for one-off layout or infra (theme, GlobalStyles, the Quill/Leaflet wrappers).
|
||||
- Wrap a page's top-level sections in `<PageEnter>`. Filters go in `<FilterBar>` with **bare** controls (no `<Field>` label) at the standard widths.
|
||||
- When refactoring, **preserve ALL data logic verbatim** (hooks, mutations, `invalidate` arrays, validation, permissions); change only presentation.
|
||||
|
||||
**Conventions learned — don't regress**
|
||||
|
||||
- **Status row tints** = subtle channel-alpha washes (`rgba(var(--mui-palette-X-mainChannel) / 0.12)`), NEVER a solid `.light` fill: `.light` is a light colour in BOTH schemes, so white dark-mode text on it is invisible. Voided/disabled rows = `opacity` + muted text.
|
||||
- **Icon badges** = solid `X.main` tile + **white** glyph (not an `X.light` tile + `X.main` glyph — that's low-contrast).
|
||||
- **Theme is single-source:** `src/context/ThemeContext.tsx` owns the `<html data-theme>` attribute + the View-Transitions cross-fade, and persists under MUI's **`mui-mode`** localStorage key (the same key MUI reads on mount). Do NOT add a second theme key — that desyncs page vs toggle on refresh.
|
||||
- **Dialogs** lock `<html>` via `useDialogScrollLock` (MUI only locks `<body>`, and `html{overflow-x:hidden}` makes `<html>` the scroller); Modal/ConfirmDialog freeze title/label/loading through the close fade so nothing flashes. Login renders OUTSIDE AppShell.
|
||||
|
||||
**Gates every change:** `npx tsc -b --noEmit` (NOT `-p tsconfig.json` — a vacuous solution file that checks nothing), `npm run build`, `npx vitest run`.
|
||||
Per-call cost ledger in `ai_usage` with a monthly budget cap (402 when
|
||||
exceeded). Invoice flow unchanged: PDF → `extract-invoices` (structured
|
||||
output) → review cards → existing `POST /received-invoices`.
|
||||
**`received_invoices.amount` is GROSS (VAT-inclusive)** — VAT is
|
||||
back-calculated (`vatFromGross`). Phase-2 design notes live in
|
||||
`docs/superpowers/specs/`.
|
||||
|
||||
---
|
||||
|
||||
## Database Conventions
|
||||
## Database & Migrations
|
||||
|
||||
- All models use `snake_case` column names; Prisma maps to camelCase in TypeScript.
|
||||
- Soft-delete via `is_deleted` boolean (not all tables, check schema).
|
||||
- Timestamps: `created_at`, `updated_at` (auto-managed by Prisma).
|
||||
- Number sequences (`number_sequences` table) manage invoice/quotation numbering — never hardcode numbering logic.
|
||||
- All significant tables have audit log entries. Check `audit_logs` model for the schema.
|
||||
Conventions: snake_case columns; `created_at`/`updated_at` timestamps;
|
||||
soft-delete via `is_deleted` where present; `number_sequences` owns all
|
||||
document numbering.
|
||||
|
||||
---
|
||||
**Golden rules:**
|
||||
|
||||
## Database Migrations (Critical Workflow)
|
||||
- **NEVER `prisma db push`** — it bypasses migration history and causes drift.
|
||||
- **Every DB change is a tracked migration** — schema, permission/seed rows,
|
||||
backfills, one-shot fixes. A migration's `migration.sql` may contain plain
|
||||
`INSERT/UPDATE/DELETE`. No raw SQL against production, ever; `prisma db
|
||||
seed` is dev-only convenience (`prisma/seed.ts` refuses to run with
|
||||
`APP_ENV=production`) — prod baselines belong in migrations.
|
||||
|
||||
**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
|
||||
**Making a schema change (this shell is non-interactive — `prisma migrate
|
||||
dev` will refuse to run; use this recipe):**
|
||||
|
||||
```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.
|
||||
# 1. Edit prisma/schema.prisma (ask the user to stop their dev server first!)
|
||||
# 2. Generate the migration SQL into a new folder:
|
||||
mkdir prisma/migrations/<yyyyMMddHHmmss>_<name>
|
||||
npx prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script \
|
||||
> prisma/migrations/<...>/migration.sql # strip the BOM if written via PowerShell Out-File!
|
||||
# 3. Review the SQL, then apply + regenerate:
|
||||
npx prisma migrate deploy
|
||||
npx prisma generate
|
||||
# 4. Apply to the test DB as well (suite breaks otherwise):
|
||||
# DATABASE_URL=<app_test url> npx prisma migrate deploy
|
||||
# 5. Commit schema.prisma AND the migration folder together.
|
||||
```
|
||||
|
||||
### 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>
|
||||
```
|
||||
Deployment, drift checks, hotfix-migration shipping and baselining:
|
||||
see **`docs/release.md`**.
|
||||
|
||||
---
|
||||
|
||||
## Conventions (enforced — verified by the 2026-06-06 audit)
|
||||
|
||||
These are the unified rules across the codebase. Follow them for new code; the
|
||||
audit found and fixed the deviations. Full report: `docs/codebase-audit-2026-06-06.md`.
|
||||
## Enforced Conventions (single source — merged 2026-06 audits)
|
||||
|
||||
**Routes**
|
||||
|
||||
- **Responses:** always `success(reply, data[, status, message])` / `error(reply, msg, status)` / the paginated helper. Never raw `reply.send({ success: true, ... })`. (Some legacy files still do — convert when you touch them.)
|
||||
- **Route ids:** parse numeric params with `parseId((request.params as any).id, reply)` then `if (id === null) return;`. Do not use raw `parseInt` (it yields `NaN`, not a 400).
|
||||
- **Bodies:** validate every body with `parseBody(Schema, request.body)` → `if ("error" in body) return error(reply, body.error, 400)`.
|
||||
- **Permissions:** guard with `requirePermission` / `requireAnyPermission`. The admin shortcut is `authData.roleName === "admin"`. ⚠️ `AuthData` has **`roleName`**, not `role` (`role` only exists on `JwtPayload`). Don't type `authData` as `any` — it hides exactly this bug.
|
||||
- **Audit:** call `logAudit` on every create/update/delete (and on security-relevant actions like session/token termination) with `oldValues`/`newValues`.
|
||||
|
||||
**Services**
|
||||
|
||||
- Plain exported async functions; return `{ data }` or `{ error, status }` (preferred over discriminated unions). Services own Prisma; routes stay thin.
|
||||
- Respect soft-delete (`is_deleted: false`) in reads where the model has it.
|
||||
- `success()`/`error()`/paginated helpers only; `parseId` for numeric params
|
||||
(`if (id === null) return;`); `parseBody` for every body; permission guards
|
||||
on reads AND writes; `logAudit` with old/new values on every mutation.
|
||||
- Role-management writes are admin-only and re-checked (no creating or
|
||||
rewriting the `admin` role).
|
||||
|
||||
**Schemas (Zod 4)**
|
||||
|
||||
- Use Zod 4 idioms: `z.strictObject({...})` / `z.looseObject({...})` (not deprecated `.strict()` / `.passthrough()`).
|
||||
- Shared coercion helpers (number-from-form, nullable-number, boolean-from-form) belong in `src/schemas/common.ts` — don't copy-paste the `z.union([z.number(), z.string()]).transform(Number)` idiom (it's duplicated ~150× today; consolidating is a tracked follow-up). New number coercions should guard against `NaN`.
|
||||
- User-facing messages in **Czech**; identifiers/keys in English.
|
||||
- `z.strictObject`/`z.looseObject` (not deprecated `.strict()`/`.passthrough()`).
|
||||
- **Shared coercion helpers in `src/schemas/common.ts` are MANDATORY** for
|
||||
form-coerced fields: `numberFromForm`, `numberInRange`,
|
||||
`nonNegativeNumberFromForm`, `positiveNumberFromForm`,
|
||||
`intIdFromForm`/`nullableIntIdFromForm`, `nonNegativeIntFromForm`,
|
||||
`booleanFromForm`, `isoDateString`, `dateTimeString`/`nullableDateTimeString`,
|
||||
`timeString`, `emailOrEmpty`, `DocumentSectionSchema`. NEVER the raw
|
||||
`z.union([z.number(), z.string()]).transform(Number)` idiom (silent NaN —
|
||||
the single biggest historical bug class). FK ids → intIdFromForm;
|
||||
quantities/prices → nonNegative/positive; bounded → numberInRange.
|
||||
- The date/time helpers are deliberately **lenient** (strip trailing time
|
||||
components) because edit forms re-submit `toJSON`-serialized values.
|
||||
Optional emails: `emailOrEmpty.nullish()` (a bare `.email()` 400s the form).
|
||||
- Align `max()` caps with the DB column widths (an over-cap string 500s at
|
||||
Prisma instead of 400ing at Zod). Update schemas derive via
|
||||
`.partial()` (+ `.omit()` for immutable fields like document numbers) —
|
||||
and therefore must NOT carry top-level `.default()`s (Zod 4 `.partial()`
|
||||
still injects field defaults into partial payloads).
|
||||
- User-facing messages in **Czech**; identifiers/tokens in English.
|
||||
|
||||
**Frontend**
|
||||
**Determinism & concurrency**
|
||||
|
||||
- **Query invalidation:** invalidate the **broad domain key** (`["offers"]`, not `["offers","list"]`). Prefix-matching covers sub-queries.
|
||||
- **Single source of truth for shared maps:** audit `entity_type` → Czech label lives in `src/admin/lib/entityTypeLabels.ts` and MUST be keyed to the server's `EntityType` values (add the new key there when you add an entity type). Plan categories come from the DB via `lib/queries/plan.ts`. Don't duplicate label maps across files or across server/client.
|
||||
- Prefer deriving state over `useEffect`; use React Query for fetching, not effects.
|
||||
- Timestamp/date-only sorts ALWAYS get an `{ id }` tiebreak (second-precision
|
||||
columns make single-key sorts non-deterministic).
|
||||
- Read-modify-write of shared rows (stock, balances, sequences) runs inside
|
||||
`prisma.$transaction` with `SELECT … FOR UPDATE` via **`tx.$queryRaw`**
|
||||
(not `$executeRaw`), locking in global ascending-id order. Multi-statement
|
||||
writes (header + items + sections) belong in ONE transaction.
|
||||
- Uniqueness checks go INSIDE the create transaction (pass the `tx` client to
|
||||
the checker) and catch `P2002` → 409 as backstop.
|
||||
|
||||
**Dates (two deliberate regimes — don't "fix" either)**
|
||||
**Errors**
|
||||
|
||||
- **Plan module** does all date-only math in **UTC** (`setUTCDate`, `toISOString().slice(0,10)`) because its columns are `@db.Date` (UTC-midnight). Correct and stable.
|
||||
- **Attendance/leave** writes `@db.Date` at **local noon** (`new Date(y, m, d, 12, 0, 0)`).
|
||||
- **Frontend "today" / date-string round-trips:** use `utils/date.ts` `localDateStr` (server) / `normalizeDateStr` (client). **Never** use `new Date().toISOString().split("T")[0]` for "today" — it's the UTC date and is a day early during the late-evening Prague window.
|
||||
- Never silently swallow — every catch logs (`console.*` in services; there
|
||||
is no request-scoped logger there). The only allowed silent catch is an
|
||||
_expected_ condition (e.g. ENOENT-as-existence-check) **with a comment**.
|
||||
- Prefer explicit Czech 4xx over silently ignoring submitted fields.
|
||||
|
||||
---
|
||||
|
||||
## Known Issues & Gotchas
|
||||
## Known 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.
|
||||
|
||||
2. **CJS/ESM mismatch in tests** — Server compiles to CommonJS (`tsconfig.server.json`), but Vitest runs in ESM by default. The `vitest.config.ts` resolves this, but be careful when adding dependencies that only support ESM.
|
||||
|
||||
3. **Mixed error patterns** — Some services return `{ error, status }`, others return discriminated unions `{ type: 'success' | 'error' }`. Prefer `{ error, status }` for consistency with existing routes.
|
||||
|
||||
4. **Never swallow errors** — log at minimum; never use empty `catch` blocks. The service layer logs via `console.*` (there is no request-scoped pino logger in services). The NAS managers' previously-silent filesystem catches are now logged. One exception: a `catch` that handles an _expected_ condition (e.g. `ENOENT` used as an existence check) may stay silent **only with a comment** saying so.
|
||||
|
||||
5. **HTML sanitization is in place — keep applying it** — Rich-text fields (invoice notes, quotation scope, order notes) ARE sanitized: server-side DOMPurify (jsdom) plus a `cleanQuillHtml` regex pass at all three PDF routes, and the frontend sanitizes before every `dangerouslySetInnerHTML` (InvoiceDetail, OrderDetail). (The old "sanitization gap" note was stale — verified by the 2026-06-06 audit.) When you add ANY new rich-text/HTML field, apply the same sanitization on BOTH the PDF path and the render path.
|
||||
|
||||
6. **Puppeteer PDF generation** — Runs a headless browser. Input to the HTML template must be sanitized. Do not pass unsanitized user data into PDF templates.
|
||||
|
||||
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 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.
|
||||
|
||||
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.
|
||||
1. **CJS/ESM:** the server compiles to CommonJS; Vitest runs ESM
|
||||
(`vitest.config.ts` bridges it). Beware ESM-only dependencies.
|
||||
2. **Rich text / PDF security:** every rich-text/HTML field gets server-side
|
||||
DOMPurify + the strict `cleanQuillHtml` from `src/utils/pdf-shared.ts` on
|
||||
the PDF path AND sanitization before any `dangerouslySetInnerHTML`. Never
|
||||
pass unsanitized user data into Puppeteer templates; string-built HTML
|
||||
(print views, PDF templates) must `escapeHtml` every interpolation.
|
||||
3. **NAS paths** may be unmounted in dev (`Z:`) — NAS features must degrade
|
||||
with logged errors, and tests stub NAS reads.
|
||||
4. **Prisma client**: regenerate after every schema change; it is not
|
||||
committed. (On prod this is a mandatory deploy step — see docs/release.md.)
|
||||
5. **No CSRF tokens** by design (SameSite=Strict + CORS) — do not weaken CORS.
|
||||
6. **Czech locale hardcoded** in messages/month names — intentional.
|
||||
7. **Cross-login caches:** React Query keys are user-agnostic; the query
|
||||
cache is cleared on login/logout in AuthContext — keep it that way.
|
||||
|
||||
---
|
||||
|
||||
## Release Process
|
||||
## Release
|
||||
|
||||
1. Bump version in `package.json`
|
||||
2. `npm run build`
|
||||
3. Commit and tag (`git tag -a vX.Y.Z`)
|
||||
4. Push to Gitea (`git push origin master && git push origin vX.Y.Z`)
|
||||
5. Create tarball: `tar -czf app-ts-X.Y.Z.tar.gz dist dist-client prisma package.json package-lock.json scripts`
|
||||
6. Deploy via SSH to production server (`boha_admin@192.168.50.100`):
|
||||
- Path: `/var/www/app-ts`
|
||||
- Remove old files: `rm -rf dist dist-client prisma scripts package.json package-lock.json`
|
||||
- Copy tarball to server: `scp app-ts-X.Y.Z.tar.gz boha_admin@192.168.50.100:/tmp/`
|
||||
- Extract tarball: `tar -xzf /tmp/app-ts-X.Y.Z.tar.gz`
|
||||
- Install dependencies: `npm install --omit=dev`
|
||||
- Apply Prisma migrations: `npx prisma migrate deploy`
|
||||
- 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.
|
||||
Process, deployment commands, hotfix-migration shipping and verification
|
||||
checklist: **`docs/release.md`**. Run the full test suite before tagging; the
|
||||
user picks version numbers. **Never push to production or restart services
|
||||
without explicit confirmation.**
|
||||
|
||||
407
POSSIBLE_IMPROVEMENTS.md
Normal file
407
POSSIBLE_IMPROVEMENTS.md
Normal file
@@ -0,0 +1,407 @@
|
||||
# Possible Improvements — UX & Consistency Review
|
||||
|
||||
_A prioritized UX review of boha-app, grounded in 104 verified, code-referenced findings._
|
||||
|
||||
> **How this was produced (2026-06-24):** a multi-agent audit fanned out 16 independent
|
||||
> reviewers across 5 feature domains and 11 cross-cutting UX dimensions (155 raw findings),
|
||||
> deduplicated them into 118 unique items, then **adversarially re-checked every finding
|
||||
> against the actual code** — dropping 14 that didn't hold up or contradicted a deliberate
|
||||
> documented decision (CLAUDE.md). What remains are 104 findings each confirmed in the
|
||||
> source, with file references kept intact so they can be acted on directly. Read §1–§3 for
|
||||
> the opinion and the plan; §4 is the full catalogue by theme; §5 is suggested sequencing.
|
||||
>
|
||||
> **Independently re-verified (2026-06-24):** a second adversarial pass (9 parallel
|
||||
> verifiers, different model) re-checked all 104 findings against the source:
|
||||
> **100 confirmed, 4 partial, 0 refuted.** The partials were factual nits (a couple of
|
||||
> miscounts, one wrong fix target, one mis-cited import), corrected inline in this
|
||||
> document. The pass also surfaced one new backend finding (trips create authz — see §4.9)
|
||||
> and upgraded confidence on the AttendanceAdmin and warehouse-models findings.
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
boha-app is a **mature, broad, and genuinely well-built** back-office system. The bones are excellent: there is a real component kit (`src/admin/ui/`), shared document modules, a single-source-of-truth status module (`documentStatus.ts`), a global React Query cache with disciplined invalidation conventions, timezone-safe date handling, edit-locking on documents, and an accessibility-aware theme. Most of the "hard" platform work is done and done well. This is not a rescue job — it is a **polish-and-converge job**.
|
||||
|
||||
That said, the owner asked the right question. The single dominant theme across these findings is **consistency debt: the app does the same thing several different ways, and the variants disagree in ways the daily user feels.** Almost every cluster below is a story of "module A got it right, module B is an older or forked copy that drifted." The codebase even documents this pattern against itself — `documentStatus.ts` exists _because_ per-page status maps drifted; `useUnsavedChangesGuard` exists _because_ the dirty-check was copy-pasted; CLAUDE.md explicitly says "extend, never fork." The findings show those rules are followed in the newest modules (offers, issued orders) and quietly violated in the older twins (invoices, orders, attendance-admin, projects, warehouse).
|
||||
|
||||
Why this matters: the user's mental model breaks at the seams. Marking an invoice paid from the **detail** page leaves a project's order-status label stale, but doing it from the **list** page refreshes it. The "create" button **navigates to a page** on one Orders tab and **opens a modal** on the other. A failed list fetch shows "no records yet" — which can convince a user a customer has zero invoices when the server actually errored. Validation errors appear **inline under the field** on the supplier modal but **as a 4-second toast** on its mirror-image customer modal. None of these is catastrophic alone; collectively they make a strong app feel "not quite finished" and erode trust in what's on screen.
|
||||
|
||||
**The five highest-leverage moves, in order:**
|
||||
|
||||
1. **Stop showing stale data after writes.** Define one canonical React Query invalidation set per document family and apply it to _both_ list and detail mutations. Today detail-page edits invalidate fewer domains than their list twins (`OrderDetail`, `InvoiceDetail`, `DashProfile`, leave-cancel). Small effort, removes a whole class of "why is this number wrong" confusion. _(Cluster: data-freshness)_
|
||||
|
||||
2. **Guard the irreversible actions that currently aren't.** Marking an invoice **"Zaplaceno"** is a single unconfirmed chip click and is _terminal_ — the one truly irreversible document transition with **no** confirm, while every reversible status change has one. Same inversion in the warehouse: **"Potvrdit"** (posts stock) has no confirm but its **undo** does. And the **Aktivní/Neaktivní** chips are secret one-click toggles that fail silently on error. _(Cluster: destructive actions)_
|
||||
|
||||
3. **Fix list-page failure and loading states.** No list page reads `isError`, and there is no global `QueryCache.onError`, so failed fetches fall through to the **empty state** — actively misleading. Add a global error toast plus a distinct inline error. _(Cluster: loading/empty/error)_
|
||||
|
||||
4. **Make the app usable on a phone.** The shared `Tabs` uses MUI's non-scrolling `variant="standard"`, so the 5 status-filter tabs on Offers/Invoices simply **clip off-screen and become unreachable** at ~360px — a one-prop fix that touches every status filter. Modals never go full-screen on phones. _(Cluster: mobile)_
|
||||
|
||||
5. **Converge the shared primitives the app already owns.** Route the forked dirty-guards, status maps, empty states, page headers, save buttons, and PDF openers back through their canonical implementations. This is the structural fix that prevents the other four from re-drifting. _(Cluster: forked modules)_
|
||||
|
||||
The rest of this report groups all findings by theme, gives a prioritized action table, and then lists every finding with its file references intact so they can be acted on directly.
|
||||
|
||||
---
|
||||
|
||||
## 2. Top Themes
|
||||
|
||||
### Theme A — Data-freshness drift (the trust killer)
|
||||
|
||||
React Query invalidation is the app's nervous system, and CLAUDE.md lays out clear rules ("invalidate every domain that embeds the data"). The newest modules obey; older and raw-`apiFetch` paths don't. **List pages and their own detail pages invalidate different domain sets** because list pages use manual `invalidate` arrays while detail pages use `useApiMutation` arrays, and the two drifted independently. The result is subtle: a value that is correct after editing it one way is stale after editing it the identical other way. Converge on **one named invalidation constant per family** and reuse it on both surfaces. The dashboard already solved the "many domains feed me" case with `refetchOnMount: "always"` — apply the same backstop to the audit log.
|
||||
|
||||
### Theme B — Destructive & risky actions are gated by consequence-inverted logic
|
||||
|
||||
The pattern across the app is sound — `ConfirmDialog` everywhere — but the gating is **inversely correlated with actual consequence** in the few places it matters most. The _irreversible_ transitions (invoice→paid, warehouse "Potvrdit" posts stock) have **no** guard, while their _reversible_ counterparts (cancel document) get a full danger confirm. Several state changes hide as **chip toggles with no affordance** and **no `onError`**, so a rejected toggle silently reverts with zero feedback. And the "wipe the entire audit log" case uses the same low-key modal as "trim 30-day rows." Converge on: irreversibility → stronger friction, never weaker; every mutating control announces itself and reports its errors.
|
||||
|
||||
### Theme C — Forms & save UX speak three dialects
|
||||
|
||||
Validation is **inline-under-field** in some forms and **transient toast** in others — and _mirrored screens disagree_ (supplier modal inline vs customer modal toast; trip editor inline vs admin-trip editor toast; received-invoice bulk-review inline vs its single-edit toast). Enter submits page forms but **never** submits a shared-`Modal` form. Save buttons **spin** in document pages but only **swap text** elsewhere, and dual-save warehouse forms can't tell you which action is running. Failed validation never **moves focus** to the bad field. Converge on: inline `<Field error>` for validation, toasts only for transport/server failures, `<form onSubmit>` in the shared Modal, one save affordance, and focus-the-first-error.
|
||||
|
||||
### Theme D — Unsaved-work protection is partial and fork-ridden
|
||||
|
||||
The shared `useUnsavedChangesGuard` is used by exactly two pages; `OrderDetail` and `InvoiceDetail` **re-implement it inline**, and `ProjectDetail`, `CompanySettings`, all three warehouse forms, and `AttendanceCreate` have **no guard at all** — a refresh discards a 15-line receipt silently. Worse, _every_ guard only catches `beforeunload`, so clicking the in-app **"Zpět"** or a sidebar link — the most common way to leave — discards edits with no prompt (this one needs a router upgrade). And `InvoiceDetail` has **no edit-lock** while its siblings do, so two users can clobber each other's invoice line items.
|
||||
|
||||
### Theme E — Loading, empty & error states have no single grammar
|
||||
|
||||
Three different loading behaviors for the _same_ "change the month" action (dim / nothing / flash). Empty states built two ways (`<EmptyState>` vs hand-rolled `Box+Typography`). 40 pages **blank the whole page to a centered spinner** (layout shift) instead of keeping chrome; there are **zero** real MUI `<Skeleton>`s despite identifiers literally named `showListSkeleton`. The dashboard hand-rolls its own spinner. And the big one: **failed fetches render as empty**, not as errors.
|
||||
|
||||
### Theme F — Navigation & information architecture has thin orientation
|
||||
|
||||
Every browser tab reads **"Admin"** (no per-page title), there are no breadcrumbs, the back control is built **four different ways**, and `Received-order` detail sends you back to the **wrong Orders tab**. Master data is scattered across four nav sections; "Zákazníci" lives at the misleading URL `/offers/customers`; `settings.templates` opens the gear then **bounces you to the dashboard**; and there are three different "access denied" experiences. None blocks work, but together they make deep pages feel un-anchored.
|
||||
|
||||
### Theme G — Mobile is a second-class citizen in specific, fixable spots
|
||||
|
||||
Status-filter tabs **clip and become unreachable** on phones. Modals never go full-screen. Long full-page editors keep **Save only at the top**, so phone users scroll all the way back up to save. Warehouse line-items lose the labeled card-per-row layout the document editor has — worst exactly where shop-floor mobile use is likely. `FilterBar` children mix fixed and growing flex bases, leaving dead space.
|
||||
|
||||
### Theme H — Microcopy & localization inconsistency
|
||||
|
||||
The goods-receipt module is named **four ways** (Příjmy / Nový příjem / Příjmové doklady / Příjemka) and "Příjmy" also means _financial income_. "Cancelled" is spelled two ways in the same status file. Create verbs split three ways. The busy label has five competing forms plus a `"Chyba pripojeni"` diacritics typo. Autocompletes leak English **"No options"** in an otherwise fully-Czech app. Several prices bypass cs-CZ formatting (period decimals, no currency).
|
||||
|
||||
### Theme I — Accessibility gaps in the hot paths
|
||||
|
||||
Clickable table rows aren't keyboard-operable (warehouse records literally can't be opened by keyboard). Search boxes are placeholder-only with no accessible name across ~13 pages. The desktop line-item grid is unlabeled while the mobile card is fully labeled. No skip-to-content link, so keyboard users tab the whole sidebar on every navigation.
|
||||
|
||||
### Theme J — Bundle & performance
|
||||
|
||||
MUI + Emotion sit in the **781 kB entry chunk**, so every patch release busts the cached UI vendor code and daily users re-download ~232 kB gzip of unchanged MUI. The Dashboard and its 7 subcomponents are bundled into the entry chunk and downloaded **on the Login screen**. No route-transition progress bar, no link prefetch.
|
||||
|
||||
---
|
||||
|
||||
## 3. Prioritized Recommendations
|
||||
|
||||
Effort: **S** = hours · **M** = a focused day or two · **L** = multi-day / structural.
|
||||
|
||||
### Quick wins — high impact, low effort
|
||||
|
||||
| # | Change | Where | Impact | Effort |
|
||||
| --- | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------ | ------ |
|
||||
| 1 | Make status-filter `Tabs` scrollable so they stop clipping off-screen on phones | `src/admin/ui/Tabs.tsx:28-49` (one prop fixes all) | High | S |
|
||||
| 2 | Add a confirm (or undo toast) + hover affordance to the **"mark invoice paid"** chip — the only unguarded irreversible transition | `Invoices.tsx:339-359,550-562`, `ReceivedInvoices.tsx:668-680` | High | S |
|
||||
| 3 | Converge detail-page invalidation sets onto the list-page (full) sets | `OrderDetail.tsx:162,168,177`; `InvoiceDetail.tsx:1054,1067,1073`; `DashProfile.tsx:225-226`; `LeaveRequests.tsx:90` | Medium | S |
|
||||
| 4 | Gate the Invoices **list** PDF icon on `invoice_number` so drafts stop dead-ending in a 404 | `Invoices.tsx:616-626` | Medium | S |
|
||||
| 5 | Point `Received-order` detail Zpět / redirects at `/orders?tab=prijate` | `OrderDetail.tsx:116-121,275-287,397-405` | Medium | S |
|
||||
| 6 | Add a global `QueryCache.onError` toast so failed fetches stop masquerading as empty | `src/admin/lib/queryClient.ts` | High | S |
|
||||
| 7 | Debounce search on Invoices / ReceivedInvoices / AuditLog (reuse `useDebounce`) | `Invoices.tsx:282`, `ReceivedInvoices.tsx:250`, `AuditLog.tsx:202` | Medium | S |
|
||||
| 8 | Add global MUI `csCZ` `localeText` (kills English "No options" everywhere) | `src/admin/ui/MuiProvider.tsx:15`; pickers `CustomerPicker.tsx:49`, `SupplierPicker.tsx:49` | Medium | S |
|
||||
| 9 | Add `onError` toast to Vehicles/Users active-toggle mutations (silent failure today) | `Vehicles.tsx:146-160`, `Users.tsx:162-171` | Medium | S |
|
||||
| 10 | Add a per-page `document.title` (`<TitleSync>`) so tabs/bookmarks aren't all "Admin" | `index.html:22`, `AppShell`, `navData.tsx` | Medium | S |
|
||||
| 11 | Use `PROJECT_STATUS`/`ORDER_STATUS` maps for project + linked-order chips (currently wrong colors / raw DB tokens) | `Projects.tsx:50`, `ProjectDetail.tsx:43,577`, `documentStatus.ts` | Medium | S |
|
||||
| 12 | Fix `"Chyba pripojeni"` diacritics typo; unify cancelled-label spelling | `Dashboard.tsx:127`, `AuthContext.tsx:256,314`; `documentStatus.ts:49,58` | Low | S |
|
||||
| 13 | Add a skip-to-content link + `id="main-content"` on `<main>` | `AppShell.tsx:130-145,210-223` | Medium | S |
|
||||
| 14 | Lazy-load Dashboard so its 7 subcomponents leave the Login critical path | `AdminApp.tsx:14-15`, `Dashboard.tsx:16` | Medium | S |
|
||||
| 15 | Relabel the two Orders-tab "Vytvořit objednávku" buttons (identical for two doc types) | `Orders.tsx:125,129` | Medium | S |
|
||||
|
||||
### High-impact — worth a focused effort
|
||||
|
||||
| # | Change | Where | Impact | Effort |
|
||||
| --- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------ | ------ |
|
||||
| 16 | Add unsaved-changes guards to the heavy editors that have none; de-fork `OrderDetail`/`InvoiceDetail` onto the shared hook | `ProjectDetail`, `CompanySettings`, `Warehouse*Form`, `AttendanceCreate`; `useUnsavedChangesGuard.ts` | High | M |
|
||||
| 17 | Render an inline error (distinct from empty) when `isError`, with retry | `usePaginatedQuery.ts:47`, all list pages | High | M |
|
||||
| 18 | Standardize validation on inline `<Field error>`; fix the mirrored screens that disagree | `WarehouseSuppliers` vs `OffersCustomers`; `Trips` vs `TripsAdmin`; `ReceivedInvoices` bulk vs single | Medium | M |
|
||||
| 19 | Wrap shared `Modal` in `<form onSubmit>` so Enter submits every dialog | `src/admin/ui/Modal.tsx:84,92` | Medium | M |
|
||||
| 20 | Route the three forked invoice PDF openers through `useDocumentPdf`/`useDocumentListPdf` | `Invoices.tsx:361`, `InvoiceDetail.tsx:1175`, `ReceivedInvoices.tsx:561` | Medium | M |
|
||||
| 21 | Replace inline English/technical error strings with `apiErrorMessage(...)` across ~32 pages | `mutations.ts:30-36`; per-page catch blocks | Medium | M |
|
||||
| 22 | Make `Modal` full-screen on phones; fix leave-modal hardcoded 2-col date grid | `Modal.tsx:67-75`, `Attendance.tsx:1195-1199` | Medium | S |
|
||||
| 23 | Give warehouse line-items the labeled card-per-row mobile layout the document editor has | `WarehouseIssueForm.tsx:513-567` vs `DocumentItemsEditor.tsx:170-342` | Medium | M |
|
||||
| 24 | Add keyboard semantics to `DataTable` clickable rows (role/tabindex/Enter-Space) | `DataTable.tsx:285-303,137-161` | Medium | M |
|
||||
| 25 | Add a "Nová žádost" create action to "Moje žádosti" (lift the leave modal out of Attendance) | `LeaveRequests.tsx:241`, `Attendance.tsx:936,978` | Medium | M |
|
||||
| 26 | Route hand-rolled headers through `PageHeader`/`headerActionsSx` (~20 pages) so mobile buttons stack | `PageHeader.tsx:19`; `Projects`, `Users`, `Vehicles`, `TripsAdmin`, `AttendanceAdmin`, `Settings`, `CompanySettings` | Medium | M |
|
||||
| 27 | Confirm before warehouse **"Potvrdit"** / **"Uložit a potvrdit"** (posts stock irreversibly) | `WarehouseReceiptDetail.tsx:354-356`, `WarehouseReceiptForm.tsx:445` | Medium | S |
|
||||
| 28 | Split `@mui/*`+`@emotion/*`(+quill) into a long-lived `vendor-mui` chunk | `vite.config.ts` | Medium | M |
|
||||
| 29 | Give list-page search inputs an accessible name + `type="search"` (shared `SearchField`) | `Offers.tsx:787`, `Invoices.tsx:741`, +11 pages | Medium | S |
|
||||
|
||||
### Strategic — larger bets
|
||||
|
||||
| # | Change | Where | Impact | Effort |
|
||||
| --- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- | ------ | ------ |
|
||||
| 30 | Add edit-locking (migration + route trio) to `InvoiceDetail` (and order notes) to stop multi-user clobbering | `invoices.ts`, `orders.ts`, schema; wire `useDocumentLock`/`LockBanner` | High | L |
|
||||
| 31 | Migrate `InvoiceDetail` off its fork onto shared `DocumentItemsEditor`/`useDocumentPdf`/dirty-guard (add `showVat` flag) | `InvoiceDetail.tsx:241-541`, `DocumentItemsEditor.tsx` | Medium | L |
|
||||
| 32 | Block dirty in-app navigation (requires `createBrowserRouter`/`RouterProvider` migration, then centralize in the guard) | `main.tsx`, `useUnsavedChangesGuard.ts` | Medium | L |
|
||||
| 33 | Move `AttendanceAdmin` reads off raw `apiFetch` onto React Query (kills the `setTimeout(300)` refetch dance) | `useAttendanceAdmin.ts:823,871,1057` | Medium | L |
|
||||
| 34 | Real skeleton/page-shell first paint instead of full-page spinner on 40 pages | `LoadingState.tsx`, list pages; `skeleton-boha` skill exists | Medium | L |
|
||||
| 35 | Route-transition top progress bar + sidebar link prefetch | `AppShell.tsx:222`, `AdminApp.tsx` | Medium | M |
|
||||
| 36 | Consolidate duplicated status/label maps into `documentStatus.ts` (warehouse/projects/leave) | `documentStatus.ts`; 6 warehouse files, `Projects`, `Leave*` | Medium | M |
|
||||
|
||||
---
|
||||
|
||||
## 4. Detailed Findings by Area
|
||||
|
||||
### 4.1 Data-freshness — stale data after mutations
|
||||
|
||||
- **Detail-page mutations invalidate fewer domains than their list twins.** `OrderDetail` status/notes/delete (`OrderDetail.tsx:162,168,177`) invalidate only `[orders,invoices]` while the `ReceivedOrders` list delete (`ReceivedOrders.tsx:175`) uses `[orders,offers,projects,invoices]`. `InvoiceDetail` save/status/delete (`InvoiceDetail.tsx:1054,1067,1073`) use `[invoices,orders]` while the `Invoices` list adds `projects` (`Invoices.tsx:328,352`). **Why it matters:** marking an invoice paid or changing an order status from the _detail_ page leaves `ProjectDetail`'s `order_status` label (`ProjectDetail.tsx:571`) and the source offer stale until staleTime/refocus. **Fix:** define one canonical set per family (e.g. `[offers,orders,issued-orders,projects,invoices]`) and apply to both surfaces; `OfferDetail`/`Offers` are the consistent reference to copy.
|
||||
|
||||
- **Self-profile edit refreshes fewer domains than an admin editing the same user.** `DashProfile` (`DashProfile.tsx:225-226`) invalidates only `[dashboard,users]`, but admin Users edit uses `USER_INVALIDATE=[users,trips,attendance,leave-requests,leave,projects]` (`Users.tsx:117-124`). **Why:** your display name is embedded in trips/attendance/leave/projects (none keyed under `[users]`), so renaming yourself leaves it stale there. **Fix:** export `USER_INVALIDATE` from a shared module and reuse it in `DashProfile`.
|
||||
|
||||
- **Cancelling a leave request omits the `[users]` balance invalidation that create/approve include.** Cancel (`LeaveRequests.tsx:90`) invalidates `[leave-requests,leave,attendance]`; create (`Attendance.tsx:305`) and approve/reject (`LeaveApproval.tsx:164,177`) add `users,dashboard`. **Why:** the genuinely-stale gap is `[users]` balance/history when an approved future request is cancelled (the `[dashboard]` part self-heals via `refetchOnMount`). **Fix:** hoist a shared `LEAVE_INVALIDATE` set across all three flows.
|
||||
|
||||
- **Audit Log is never invalidated by the mutations that write audit rows.** `logAudit()` runs on every mutation, but `[audit-log]` is invalidated only by plan flows (`usePlanWork.ts:167`) and the page's own cleanup (`AuditLog.tsx:191`). **Why:** recent actions don't appear within the 30s default staleTime. **Fix:** add `refetchOnMount:'always'` (and `staleTime:0`) to the AuditLog page's inline `useQuery` (`AuditLog.tsx:135`), mirroring `dashboardOptions` — don't sprinkle `[audit-log]` into dozens of arrays. _(Verification note: `auditLogOptions` in `auditLog.ts` is dead code — nothing imports it; either delete it or wire the page onto it and put the option there.)_
|
||||
|
||||
- **Odin invoice import invalidates only `[invoices]`, not `[suppliers]`/`[company-settings]`.** `OdinChat.tsx:362` vs manual `[invoices,suppliers,company-settings]` (`ReceivedInvoices.tsx:331,341`). **Why:** an Odin import that introduces a new vendor name won't appear in the `[suppliers]`-keyed autocomplete until staleTime expires. **Fix:** use the same set on both paths (they POST to the same endpoint).
|
||||
|
||||
- **Received-invoice supplier picker is disjoint from the warehouse/issued-order supplier registry.** Received invoices use a free-text `string[]` under `[suppliers]` → `/received-invoices/suppliers` (`common.ts:22-28`); issued orders/warehouse use the structured `sklad_suppliers` table (`issued-orders.ts:76`, `warehouse.ts:241`). **Why:** a vendor added in Warehouse→Suppliers never shows when entering a received invoice, and vice-versa — same conceptual entity, two disjoint stores. **Fix:** don't force an FK (keep one-off vendors as quick free-text), but **union** `sklad_suppliers` names into the received-invoice autocomplete source.
|
||||
|
||||
### 4.2 Destructive & risky actions — confirmation and undo
|
||||
|
||||
- **Marking an invoice "Zaplaceno" is a single unconfirmed chip click — the only irreversible transition with no guard.** In both invoice lists the chip instantly PUTs `status=paid` with no confirm and no undo (`Invoices.tsx:339-359,550-562`, `ReceivedInvoices.tsx:668-680`); for issued invoices "paid" is terminal (detail goes read-only, row undeletable, `InvoiceDetail.tsx:1220-1314`). Every _detail_ page gates status changes behind a `ConfirmDialog`, but this one doesn't, and the chip only differs from a static one by a pointer cursor. **Fix:** route the chip click through a `ConfirmDialog` ("Označit fakturu … jako zaplacenou?") or an undo toast, and add a hover/tooltip affordance.
|
||||
|
||||
- **Aktivní/Neaktivní chips are hidden one-click toggles with no affordance, and fail silently.** On Vehicles, Users, Warehouse Locations and Suppliers the `StatusChip` is secretly an `onClick` toggle with no tooltip/label (`Vehicles.tsx:263`, `Users.tsx:288`). Deactivation fires on one click while the less-destructive delete gets a full `ConfirmDialog`. The Vehicles/Users toggle mutations declare only `onSuccess`, **no `onError`** and no try/catch (`Vehicles.tsx:146-160`, `Users.tsx:162-171`), so a rejected toggle gives zero feedback and the chip silently reverts. **Fix:** make activation an explicit labelled control (switch/menu action) with a tooltip; add a deactivation confirm for user/vehicle; add `onError` toasts. (`WarehouseLocations`/`WarehouseSuppliers` already toast via try/catch — copy them.)
|
||||
|
||||
- **`ConfirmDialog` in-flight `loading` is applied inconsistently — some dialogs allow duplicate submits.** `IssuedOrderDetail` passes `loading` to both status and delete dialogs (`:958`); `OrderDetail`/`InvoiceDetail` pass it to delete but not status (`OrderDetail.tsx:780-790`, `InvoiceDetail.tsx:2453-2463`); Vehicles delete (`:417-429`), `AttendanceAdmin` delete (raw `apiFetch`, no `isPending`, `useAttendanceAdmin.ts:1293-1320`) and CompanySettings bank delete omit it entirely → a second click fires a duplicate request. **Fix:** pass `loading={mutation.isPending}` to every `ConfirmDialog`; convert `AttendanceAdmin`'s raw delete to `useApiMutation`; standardize on `IssuedOrderDetail`'s keep-open "Zpracovávám…" convention.
|
||||
|
||||
- **Irreversible "Potvrdit" (posts stock) has no confirm, while its reversible "Zrušit doklad" undo does.** `WarehouseReceiptDetail.tsx:354-356` commits stock movements on one click; `:508-517` requires a danger confirm to reverse it. Same single-click commit in the form's "Uložit a potvrdit" (`WarehouseReceiptForm.tsx:445`). **Why:** the gating is inverted relative to consequence; a misclick commits stock. **Fix:** add a `ConfirmDialog` before "Potvrdit" (and ideally the form's commit).
|
||||
|
||||
- **Cancellation confirms show two near-identical "Zrušit" buttons.** When the confirmed action is itself a cancellation, both the dismiss and the confirm start with "Zrušit" (`WarehouseReceiptDetail.tsx:508-516`, `LeaveRequests.tsx:260-268`) — same leading word, opposite meanings (the buttons do differ visually: contained vs text). **Fix:** relabel the dismiss to "Zpět"/"Ne" via `cancelText` (`ConfirmDialog.tsx:31-33`).
|
||||
|
||||
- **Wiping the ENTIRE audit log uses the same low-key modal as trimming old rows.** "Vše" sits in the same dropdown as "30 dní"/"90 dní" and the only warning is a 0.6-opacity caption (`AuditLog.tsx:297-319,207-218`). The backend deliberately requires a special literal to wipe everything (`routes/admin/audit-log.ts:92-109`), but the UI auto-supplies it with no extra friction. **Fix:** when "Vše" is selected, switch to danger styling, show a prominent warning, ideally require typing a confirmation word.
|
||||
|
||||
- **Error toasts auto-dismiss after 4s identically to successes, with no history.** `AlertContext.tsx:53-70` defaults every severity to 4000ms; a long Czech validation message vanishes as fast as "Uloženo," with no toast history (`AlertContainer.tsx:20-27`). **Fix:** key the default off severity — error/warning longer or sticky-until-dismissed, success ~4s.
|
||||
|
||||
### 4.3 Error & message feedback fidelity
|
||||
|
||||
- **Raw English/technical error strings leak into Czech toasts on ~30 pages.** A helper `apiErrorMessage(err, fallback)` converts client-generated English ("Unauthorized", "Failed to fetch", "Invalid JSON response", "Request failed (NNN)") into a Czech fallback (`mutations.ts:30-36,69-84`), but only `OfferDetail`/`IssuedOrderDetail` use it. ~30 pages do `alert.error(e instanceof Error ? e.message : "Chyba připojení")` (`Vehicles.tsx:203`, `OrderDetail.tsx:191`), passing the raw English through on dropped connections / non-JSON 500s / 401s. **Fix:** replace the inline pattern with `apiErrorMessage(e, "<Czech fallback>")` across the ~32 files. **Do not** add a blanket `useApiMutation` default `onError` — pages call `mutateAsync` inside try/catch and also reset local state there, so a default handler would double-toast.
|
||||
|
||||
### 4.4 Unsaved-changes & data-loss protection
|
||||
|
||||
- **The dirty guard is absent on heavy editors and forked twice.** Shared `useUnsavedChangesGuard` is used only by `OfferDetail`/`IssuedOrderDetail`; `OrderDetail` (`:130-143`) and `InvoiceDetail` (`:942-958`) re-implement `isDirty`+`beforeunload` inline; `ProjectDetail`, `CompanySettings`, `WarehouseIssueForm/ReceiptForm/InventoryForm` and `AttendanceCreate` register **no guard at all** — a refresh discards everything typed. **Fix:** route the two forks through the shared hook and add it to the six unguarded editors.
|
||||
|
||||
- **Dirty guards block only tab-close, not in-app navigation.** Every guard registers only `beforeunload` (`useUnsavedChangesGuard.ts:25-33`), which doesn't fire on React-Router navigation — so the in-app "Zpět" or a sidebar link discards edits silently. **Fix (structural):** the app uses classic `<BrowserRouter>` (react-router 6.30.3) where `useBlocker`/`usePrompt` aren't available — this needs a migration to `createBrowserRouter`/`RouterProvider` (or a custom nav-intercept context), then centralize the blocker inside the shared hook.
|
||||
|
||||
- **Always-editable page forms offer no explicit Discard.** Modals have "Zrušit" and `WarehouseItemDetail` has an edit/cancel toggle that restores the snapshot (`:247-269`), but `ProjectDetail` (only Uložit+Smazat, `:343`) and `CompanySettings` (only Uložit, `:647`) give no way to abandon edits — you must reload (and they don't even warn). **Fix:** add a "Zrušit změny" button that restores the loaded snapshot from query cache.
|
||||
|
||||
- **Invoices have no edit-lock while offers and issued orders do (multi-user clobbering).** `OfferDetail`/`IssuedOrderDetail` acquire a server lock, heartbeat, render `LockBanner` and force read-only when another user holds it; `InvoiceDetail` imports none of it (`:22-88`), so two users can clobber each other's line items (last-save-wins). Same gap for received-order notes on `OrderDetail`. **Fix (structural):** the _client_ pieces exist (`useDocumentLock`+`LockBanner`) but the _server_ trio does **not** — needs a migration adding `locked_by`/`locked_at` to invoices (and orders), a lock/heartbeat/unlock route trio + `locked_by` enrichment in the detail endpoint (mirror `issued-orders.ts:138-245`), then wire the existing hook + banner.
|
||||
|
||||
### 4.5 Form validation & submission
|
||||
|
||||
- **Validation is inline in some forms, transient toasts in others — and mirrored screens disagree.** Inline `<Field error>` camp: Trips, Users, Vehicles, WarehouseSuppliers, OfferDetail. Toast camp: ProjectDetail, AttendanceCreate, CompanySettings, OffersCustomers, TripsAdmin, ReceivedInvoices-edit. The disagreements: supplier modal inline (`WarehouseSuppliers.tsx:266-270`) vs its mirror customer modal toast (`OffersCustomers.tsx:338-341`); regular trip editor inline `end_km>start_km` (`Trips.tsx:294-300`) vs admin trip editor toast (`TripsAdmin.tsx:485-490`); received-invoice bulk-review inline per-row (`:431-446`) vs single-edit toast (`:508-519`). **Fix:** standardize on inline `<Field error>`; reserve toasts for server/transport failures.
|
||||
|
||||
- **Enter submits page forms but never any shared-Modal form.** `Modal` renders children in `DialogContent` with an `onClick` button (default `type=button`) and no surrounding `<form>` (`Modal.tsx:84,92`), so Enter never submits a modal. `OfferDetail` even hand-rolled an `onKeyDown` Enter workaround (`:1059-1061`). **Fix:** wrap `DialogContent`+`DialogActions` in `<form onSubmit>`, make the primary action `type=submit`, mark secondary/in-content buttons `type=button`, and remove the workaround.
|
||||
|
||||
- **Failed validation doesn't move focus to the first invalid field nor announce to AT.** Handlers just `setErrors` and return (`Vehicles.tsx:192-197`); the `Field` error is a plain caption wired via `aria-describedby`/`aria-invalid`, not `aria-live`/`role=alert` (`Field.tsx:81-89`). In a long modal the error can be off-screen. **Fix:** after `setErrors`, focus+`scrollIntoView` the first errored field and render the inline error with `role=alert`; centralize in `Field.tsx`/`Modal.tsx`.
|
||||
|
||||
- **Required-asterisk marking is inconsistent with what's validated; DateField/TimeField can't show an error border.** `Field` paints the asterisk only when `required` is passed (`Field.tsx:74`), but it's applied unevenly: `WarehouseIssueForm` validates Projekt-required with no asterisk (`:474` vs `:328-329`); `ProjectDetail` validates Název-required with no asterisk (`:377` vs `:192`); `DateField`/`TimeField` take no `error` prop so a failed required date only reddens helper text, not the border. **Fix:** make `required` the single source of truth (drives asterisk + ideally validation); thread an `error` prop through `DateField`/`TimeField`.
|
||||
|
||||
- **Save-button feedback differs (spinner vs text swap); dual-save warehouse forms don't show which action is running.** Document pages render a `CircularProgress` and track `savingAction` so only the clicked button spins (`OfferDetail.tsx:764`); most other forms just swap to text (`ProjectDetail.tsx:346`). On `WarehouseIssueForm` both save buttons swap to identical "Ukládání..." and disable (`:455-465`) — you can't tell which is in flight. **Fix:** adopt one affordance app-wide (spinner+disabled with per-action targeting); spin only the clicked warehouse action.
|
||||
|
||||
- **Note typed in the create-project modal is saved to the legacy column and shown as non-editable.** The "Přidat projekt" modal's Poznámka writes `projects.notes` (`Projects.tsx:164`, `projects.service.ts:222`), but `ProjectDetail` renders that column read-only under "Starší poznámka (před zavedením systému)" (`:477,491`). So a note typed at creation is instantly mislabeled as legacy and uneditable, while the real editable `project_notes` system lives only on the detail page. **Fix:** drop the Poznámka field from the create modal, or route the create-time note through `createProjectNote`.
|
||||
|
||||
### 4.6 Loading, empty & error states
|
||||
|
||||
- **Failed list fetches silently render the empty state.** `usePaginatedQuery` exposes `isError`/`error` (`:47-48`) but no list page reads them, and `queryClient.ts` has no `QueryCache.onError`. So a 500/network drop falls through to the `DataTable` empty slot — Projects shows "Zatím nejsou žádné projekty" (`:480`). Detail pages handle errors loudly; `WarehouseReports.tsx:350` shows an inline `<Alert severity=error>`. **Fix:** add a `QueryCache.onError` toast and/or render an inline error distinct from empty when `isError`, with retry wired to `refetch`.
|
||||
|
||||
- **Empty states built two ways, and clickable-CTA vs text-only split.** Shared `<EmptyState>` is used by document/warehouse lists, but Projects/Vehicles/Users hand-roll `Box(textAlign,py:6)+Typography+Button` (`Projects.tsx:471/480`, `Vehicles.tsx:323`, `Users.tsx:350`), reinventing the `action` prop. Offers renders a clickable "Vytvořit první nabídku" (`:835`) while Invoices/ReceivedInvoices only name the button in description text (`Invoices.tsx:770`). **Fix:** migrate hand-rolled empties to `<EmptyState title description action>` and standardize the clickable-create-CTA convention.
|
||||
|
||||
- **Empty-state microcopy is inconsistent** (fragments vs sentences, trailing-period split, three filtered-empty phrasings, 2nd person). Fragments with no period (`AuditLog.tsx:368`, `WarehouseReports.tsx:223,364`) vs full sentences (`AttendanceHistory.tsx:653`). Filtered-empty worded three ways: "neodpovídají filtru" (`Offers.tsx:827`) / "neodpovídají filtru." (`Projects.tsx:473`) / "neodpovídají hledání." (`ReceivedInvoices.tsx:859`). Nothing-yet mixes "Zatím nejsou žádné X." with 2nd-person "Zatím nemáte žádné žádosti" (`LeaveRequests.tsx:253`). **Fix:** adopt one canonical filtered-empty string, one unfiltered-empty string, one trailing-period rule.
|
||||
|
||||
- **Changing a month/filter gives three different loading behaviors.** Document/warehouse lists dim the card via `isFetching` opacity (`Offers.tsx:815`). `TripsHistory`/`TripsAdmin` keep stale data with NO feedback (`:304-306`/`:810-812`). `AttendanceHistory` uses plain `useQuery` with no `placeholderData`, so a month change flips `isPending` and swaps the whole table for a centered spinner (`:523,646`). **Fix:** standardize on the `isFetching` card-dim; give Trips screens the dim and `AttendanceHistory` `keepPreviousData`.
|
||||
|
||||
- **No real skeletons; 40 list pages blank the whole page to a centered spinner (layout shift); "skeleton" identifiers are misnamed.** The only first-paint affordance is `LoadingState` (centered spinner, `LoadingState.tsx:10-22`); 40 pages early-return it before rendering chrome (`Projects.tsx:267`, `Offers.tsx:492`), so title/tabs/filter bar vanish then snap in. There are zero MUI `<Skeleton>`s despite identifiers like `showListSkeleton` (`ReceivedInvoices.tsx:357`). **Fix:** render `PageHeader`+`FilterBar` immediately and confine the spinner (or a real DataTable skeleton — the `skeleton-boha` skill exists) to the table area; at minimum rename the misleading identifiers.
|
||||
|
||||
- **Redundant sequential/stacked spinners.** First visit to a lazy section shows the Suspense fallback spinner (chunk download, `AdminApp.tsx:112`), then the page's own `isPending` shows a SECOND centered spinner. Separately `ReceivedInvoices` never early-returns: `renderKpi` shows `<LoadingState/>` (`:752`) AND the list shows one (`:846`) — two stacked spinners on cold load, where sibling `Invoices` shows one. **Fix:** render a single unified loading state per page (have lazy pages supply their own shell as the Suspense fallback).
|
||||
|
||||
- **Dashboard hand-rolls its loading spinner and mixes empty-state styles.** `Dashboard.tsx:313-316` and `DashSessions.tsx:161-164` inline `Box+CircularProgress` (different padding/size, no aria-label) vs the shared `<LoadingState/>`. `DashTodayPlan`/`DashSessions` hand-roll Typography empties while `DashActivityFeed`/`DashAttendanceToday` use `<EmptyState>`. On the most-visited page. **Fix:** use `<LoadingState/>` and standardize card empties on `<EmptyState>`.
|
||||
|
||||
- **Profile, 2FA and active sessions are gated behind the heavy dashboard aggregate query.** `DashProfile` and `DashSessions` render only inside `{!dashLoading && (...)}` (`Dashboard.tsx:505`), where `dashLoading` is the multi-domain aggregate (attendance+offers+invoices+orders+projects+leave). Neither block depends on that data — `DashProfile`'s 2FA comes from `totpStatusOptions`, `DashSessions` has its own query (`:74`). **Fix:** render `DashProfile`/`DashSessions` independently; gate only the data-dependent cards.
|
||||
|
||||
- **Autocomplete pickers show English "No options."** `MuiProvider` sets only the date-picker locale, no global `csCZ` `localeText` (`:15-22`); `CustomerPicker.tsx:49`/`SupplierPicker.tsx:49` omit `noOptionsText`, so empty search shows MUI's built-in English. `ItemPicker.tsx:61` correctly sets "Žádné položky." **Fix:** add MUI `csCZ` component `localeText` (fixes every Autocomplete/pagination at once) or at minimum `noOptionsText` on the two pickers.
|
||||
|
||||
### 4.7 List-page consistency
|
||||
|
||||
- **Invoices/ReceivedInvoices/AuditLog search fires a query per keystroke (no debounce).** Offers/IssuedOrders/ReceivedOrders/Projects/Warehouse use `useDebounce(value,300)`, but `Invoices.tsx:282`, `ReceivedInvoices.tsx:250` and `AuditLog.tsx:202` feed the raw value into the query key — laggier and hammering the API on the busiest financial screens. **Fix:** wrap in `useDebounce` (or a shared `SearchField`).
|
||||
|
||||
- **DataTable `onRowClick` rows aren't keyboard-operable; row-click only exists on warehouse lists.** Warehouse Items/Issues/Inventory/Receipts open via clicking the row (their _only_ entry), but Offers/Invoices/Orders/Projects/Users/Vehicles don't set `onRowClick`. Worse, the clickable `TableRow` has no `tabIndex`/`role`/`onKeyDown` (`DataTable.tsx:285-303,137-161`), so a keyboard user **cannot** open a warehouse record. `OdinSidebar` already has the correct pattern (`:126-140`). **Fix:** add `role="button"`, `tabIndex=0`, Enter/Space handling when `onRowClick` is set; then pick one row convention.
|
||||
|
||||
- **Column sorting absent on warehouse-document, audit-log and trips tables that look sortable.** `DataTable` renders sort headers only when columns carry `sortKey` and the page wires `onSort`. Offers/Invoices/Orders/Projects/WarehouseItems do; `WarehouseIssues.tsx:258`, `AuditLog.tsx:364`, `TripsAdmin.tsx:815` and WarehouseReceipts don't — you can't reorder warehouse docs by date/status nor the audit log by user, with no cue distinguishing a sortable header from a dead one. **Fix:** wire `useTableSort`+`sortKey`+`onSort` into the large paginated tables.
|
||||
|
||||
- **Sibling Order tabs disagree on the "all" status label.** `IssuedOrders` uses "Všechny" (`:60`), `ReceivedOrders` "Všechny stavy" (`:54`) under the same parent Orders tabs. **Fix:** unify the label (don't force the Tabs-vs-Select control change — IssuedOrders deliberately keeps a Select).
|
||||
|
||||
- **Filter baseline diverges: search/date/reset missing where needed.** WarehouseIssues/Receipts have search+status+date-range+reset; `WarehouseInventory.tsx:149` has only a status dropdown (no search despite `session_number`); `WarehouseReservations.tsx:354` has no text search or date filter; `AuditLog.tsx:321` (5 filters) and `TripsAdmin.tsx:734` (3 filters) have **no reset**. **Fix:** standardize a list-filter baseline; add the missing search/date/reset.
|
||||
|
||||
- **Offers/IssuedOrders filter by customer/supplier but the Invoices list cannot.** Offers has a customer Select (`:797-812`), IssuedOrders a supplier Select (`:400-415`), but the equally customer-centric Invoices list offers only free-text search (`:739-751`). **Fix:** add a customer Select (load via `offerCustomersOptions`, wire `customer_id` into list+totals; may need a small backend add).
|
||||
|
||||
- **Count subtitle missing on Projects/Users/Vehicles/Customers and the Přijaté tab; count copy splits `czechPlural` vs hand-rolled ternary.** Projects/Users/Vehicles show a bare title (`Projects.tsx:427`, `Users.tsx:338`, `Vehicles.tsx:311`), Customers a static description (`:492`), and Vydané shows a count line but Přijaté doesn't. The plural is hand-rolled five times (`WarehouseIssues.tsx:112-114`) where `czechPlural()` exists (`formatters.ts:69`). **Fix:** add a result-count subtitle via `PageHeader`; replace the hand-rolled ternaries with `czechPlural()`.
|
||||
|
||||
- **Many pages hand-roll the title bar instead of `PageHeader`, so multi-button headers wrap raggedly on mobile.** `PageHeader`'s `headerActionsSx` makes header buttons stack full-width on phones (`PageHeader.tsx:19-30`), but ~20 pages hand-roll `Box+Typography h4 + raw action Box` (Projects, Users, Vehicles, TripsAdmin, Attendance, AttendanceAdmin, Settings, CompanySettings). The multi-button ones (AttendanceAdmin Tisk/Vyplnit/Přidat `:179-198`; TripsAdmin Tisk/Vozidla `:699-731`) wrap into a ragged half-width grid on phones. **Fix:** route through `<PageHeader>` or wrap the action Box in `headerActionsSx`.
|
||||
|
||||
- **Three forked invoice PDF openers → inconsistent feedback and different error copy.** Shared `useDocumentListPdf`/`useDocumentPdf` pre-opens the tab, shows a per-row spinner, guards double-clicks, handles 401 and revokes the blob URL (`useDocumentPdf.ts:37-86`); Offers/IssuedOrders use it. But Invoices reimplements it inline (`:361`), ReceivedInvoices reimplements with **no** loading state (`:561`), and InvoiceDetail forks its own (`:1175`). Same failure yields three different sentences. **Fix:** route all three through the shared hook (make the error string a parameter — received-invoice `openFile` streams a stored upload, not a generated PDF).
|
||||
|
||||
- **Invoices LIST shows a PDF button on draft invoices, dead-ending in a 404.** Offers/IssuedOrders hide the PDF icon for drafts and InvoiceDetail's own header hides it on drafts (`:1890`), but the Invoices list renders it for every invoice gated only on permission (`:616-626`). **Fix:** gate on `inv.invoice_number` too, matching `Offers.tsx:660`/`IssuedOrders.tsx:303`.
|
||||
|
||||
- **Customers and Suppliers directories use opposite data/search/pagination models.** Built as mirrors, but `OffersCustomers` fetches the entire list once and filters client-side with no debounce/pagination (`:159,380`), while `WarehouseSuppliers` is server-paginated, debounced, page-sized with real Pagination (`:139,449`). **Fix:** align Customers on the Suppliers model (server pagination/search), preserving instant responsiveness via `keepPreviousData`/quick debounce.
|
||||
|
||||
### 4.8 Navigation & information architecture
|
||||
|
||||
- **Received-order detail returns you to the wrong Orders tab.** Received orders live under Orders→"Přijaté", but `OrderDetail`'s Zpět/post-delete/fetch-error redirects all go to `/orders` with no tab, and Orders defaults to "vydane" (`Orders.tsx:78-79`) — so you land on the issued-orders list (a different doc type). IssuedOrderDetail does it right with `/orders?tab=vydane`. **Fix:** point `OrderDetail`'s links (`:116,280,399`) at `/orders?tab=prijate`.
|
||||
|
||||
- **The "Zpět" back control is built four different ways.** No shared back primitive: document detail puts a labeled outlined Zpět on the LEFT (`OfferDetail.tsx:643`); warehouse detail puts it on the RIGHT inside PageHeader (`WarehouseItemDetail.tsx:372`); warehouse forms use an icon-only IconButton on the left (`WarehouseReceiptForm.tsx:423`); `AttendanceCreate` uses a text "← Zpět na správu" on the right (`:173`). All hardcode the list route. **Fix:** add an optional `back={{to,label}}`/`onBack` prop to `PageHeader` rendering one canonical left-aligned icon+label control.
|
||||
|
||||
- **No per-page browser title — every tab/bookmark/history entry reads "Admin."** `index.html:22` hardcodes `<title>Admin</title>` and nothing updates it (zero `document.title` refs). With multiple tabs open (common here), the tab strip/history/bookmarks all read "Admin." **Fix:** add a `<TitleSync>` setting `document.title` per route from `navData.tsx` labels (`+ " · BOHA"`).
|
||||
|
||||
- **No route breadcrumbs on deep detail/form pages.** Deep destinations (`/warehouse/items/:id`, `/warehouse/receipts/:id/edit`, `/orders/issued/:id`) give only one back link to a single hardcoded list, with no "Sklad › Položky › <item>" trail. Combined with the missing title, deep-page orientation is thin. **Fix:** add a lightweight section › list › record breadcrumb derived from route + `navData` metadata.
|
||||
|
||||
- **`settings.templates` gates the Nastavení nav item but Settings bounces such users to the dashboard.** The gear shows if the user holds any of five permissions including `settings.templates`, but `canAccessSettings` checks only roles/company/system/banking and `Navigate`-to-`/` otherwise (`Settings.tsx:199-200,421-423`). So a templates-only user sees the gear, clicks, and is teleported away. Meanwhile the offer-templates editor (`/offers/templates`, `OffersTemplates.tsx:137`) has **no** nav entry — only a "Šablony" button buried in the Offers header (`Offers.tsx:750`). **Fix:** drop `settings.templates` from the Nastavení gate (`navData.tsx:486-492`) and give the templates editor a discoverable home.
|
||||
|
||||
- **Three different "access denied" experiences.** ~40 pages render the polished `<Forbidden/>` (403 + explanation + "Zpět na Dashboard"); Settings silently `Navigate`-to-`/` (`:421-423`); Odin shows a bare unstyled line of text (`Odin.tsx:9-17`). **Fix:** standardize on `<Forbidden/>` everywhere.
|
||||
|
||||
- **"Zákazníci" master data sits under the misleading URL `/offers/customers`.** Customers are a top-level entity referenced by offers, orders and invoices, yet the route implies a sub-resource of offers — visible in code as the `matchExclude:['/offers/customers','/offers/templates']` hack the Nabídky nav item needs (`navData.tsx:250`). **Fix:** move customers to a top-level `/customers` (redirect from the old URL), removing the hack.
|
||||
|
||||
- **Master-data lists are scattered across four nav sections with no cross-links.** Zákazníci under Administrativa, Dodavatelé under Sklad, Vozidla under Kniha jízd, Uživatelé under Systém (`navData.tsx:226,297,448,470`). Salient consequence: issued orders (Administrativa) pull suppliers from `sklad_suppliers` (Sklad), so fixing a supplier means jumping to Sklad. **Fix:** at minimum add cross-links (e.g. "spravovat dodavatele" from the issued-order supplier picker → `/warehouse/suppliers`).
|
||||
|
||||
- **Sklad nav is a flat 10-item list mixing daily ops with one-time config.** Ten ungrouped items (`navData.tsx:314-463`) intermix `warehouse.operate` daily drivers with rarely-touched `warehouse.manage` config (Kategorie/Lokace/Dodavatelé). **Fix:** split into operations vs "nastavení skladu" subgroups (or move the three config screens behind one entry).
|
||||
|
||||
- **One "Vytvořit objednávku" button navigates to a page on one tab and opens a modal on the other.** On Objednávky: Vydané routes to `/orders/issued/new`, Přijaté opens a modal (`Orders.tsx:119-132`, `ReceivedOrders.tsx:606`). Across modules, offers/invoices/issued orders use routed full-page forms while received orders create in a modal. **Fix:** pick one pattern per tier or split into two distinct labelled actions.
|
||||
|
||||
- **No skip-to-content link — keyboard users tab the whole sidebar on every page.** A permanent 248px sidebar with many links renders before `<main>` (`AppShell.tsx:130-145,210-223`), with no skip link and no id on `<main>`. **Fix:** add a visually-hidden "Přeskočit na obsah" link (visible on focus) targeting `id="main-content"`.
|
||||
|
||||
### 4.9 Discoverability & workflow friction
|
||||
|
||||
- **"Moje žádosti" has no create action.** Its header has no actions and its empty state literally instructs filing on the Docházka page (`LeaveRequests.tsx:241,254`); the only way to open the leave form is a button buried on the punch screen (`Attendance.tsx:936,978`). **Fix:** add a "Nová žádost" button to `LeaveRequests` opening the same modal; lift the modal into a shared component.
|
||||
|
||||
- **Dashboard "Vaše dnešní zařazení" card shows the project as plain text — every other dash card links onward.** `DashTodayPlan` renders `projectLabel` as plain text (`:69`) while other cards link "Vše →"/"Detail →." **Fix:** wrap `projectLabel` in a `RouterLink` to `/projects/:id` (id is already in `TodayPlan`); optionally add a "Plán prací →" header button.
|
||||
|
||||
- **Issue detail shows the consumed reservation as a raw "ID: n" database identifier** (`WarehouseIssueDetail.tsx:204`), unlike the project reference beside it (a real link). **Fix:** at minimum render "R{id}" to match `ReservationPicker`'s own label (`:65`).
|
||||
|
||||
- **`ReservationPicker` is dead code — a manual Výdejka can't draw down an existing reservation.** A ready-made picker exists (`ReservationPicker.tsx:14`) but is imported nowhere; the issue form only sets `reservation_id` from router prefill (`WarehouseIssueForm.tsx:183`). **Fix:** render it in the issue-form line (gated on item_id+project_id, mirroring `BatchSelect`) — or delete the unused component.
|
||||
|
||||
- **Audit log surfaces only the one-line description — the stored old/new values are on the wire but never shown.** `audit_logs` stores `old_values`/`new_values` and the route returns full rows (`routes/admin/audit-log.ts:64-74`), but the page's row type omits them and rows aren't expandable (`AuditLog.tsx:97-105,229-275`). The most valuable part of an audit trail is invisible. **Fix:** add the fields to the type and open a detail modal rendering old→new.
|
||||
|
||||
- **Odin's empty state never hints it can query real system data.** The landing hero only says "Zeptejte se na cokoli, nebo přiložte fakturu…" (`OdinThread.tsx:82-149`), giving no hint Odin can query invoices/offers/orders/projects/warehouse via its read-only tools. **Fix:** add 3-4 clickable example-prompt chips that prefill the composer (`OdinChat.tsx:218-219`).
|
||||
|
||||
- **Keyboard shortcuts ship undiscoverable; `ShortcutsHelp` is a permanent no-op.** `ShortcutsHelp` is mounted but returns null (`:1-7`, `AppShell.tsx:226`), while Ctrl+Enter (note save), Enter (Odin send), Enter (plan category) ship with no help. **Fix:** build the "?"-opens-cheat-sheet overlay, or as a cheap first step add `title` hints (copy `OdinComposer`'s `title="Odeslat (Enter)"` onto `NoteCard`'s Ctrl+Enter).
|
||||
|
||||
- **Plan grid resets to the current week on every remount.** `usePlanWork` inits view/anchor to `new Date()` with no persistence (`:112-113`), so leaving and returning to `/plan` loses your scroll position. **Fix:** persist view+anchor (URL query or localStorage).
|
||||
|
||||
- **"Zpět na správu" / post-save links pass `?month=YYYY-MM` but AttendanceAdmin ignores it.** `AttendanceCreate` (`:141`) and `AttendanceLocation` (`:211`) link to `/attendance/admin?month=…`, but `useAttendanceAdmin` never reads the URL (hard-inits month to current). **Fix:** seed the initial month from `useSearchParams()` and keep it synced.
|
||||
|
||||
- **Receipt/Issue details never show a document-level total.** They compute per-line "Celkem" but the `DataTable` has no footer/sum (`WarehouseReceiptDetail.tsx:250`, `WarehouseIssueDetail.tsx:182`); forms show no running total. Every other money-bearing document leads with a prominent total. **Fix:** add a summary line (sum of qty×unit_price via `formatCurrency`) under the Položky table and a live running total in the forms.
|
||||
|
||||
- **Inventory form only creates a draft; Receipt/Issue forms offer "Uložit a potvrdit" in one action.** `WarehouseInventoryForm` offers only "Vytvořit inventuru" (`:204`); to post you must go to the detail and click "Potvrdit inventuru" (`:209`). **Fix:** add a "Vytvořit a potvrdit" button (the form already collects `actual_qty`), OR surface a hint explaining the deliberate two-step variance-review flow.
|
||||
|
||||
- **Trips admin can't enter a trip on behalf of a driver, though attendance admin can create for any employee.** `TripsAdmin` offers only Tisk + a Vozidla link (`:710`), no "add trip," and its edit modal has no driver picker. The `/trips` POST already accepts `body.user_id` (`trips.ts:341`). **Fix:** add an "Přidat jízdu" action with a driver selector, mirroring `AttendanceAdmin`.
|
||||
|
||||
- **⚠ Found during verification (backend, not UX): `POST /trips` accepts `body.user_id` without a `trips.manage` check.** Any user holding only `trips.record` can create a trip attributed to another user's id (`src/routes/admin/trips.ts:341`, `trips.schema.ts:13`) — reads are correctly scoped (`buildTripsWhere` limits non-managers to their own trips) but the create path is not. Minor impersonation-on-create authz gap. **Fix:** ignore `body.user_id` (force `authData.userId`) unless the caller holds `trips.manage`.
|
||||
|
||||
- **Personal Trips "Záznam" shows company-wide trips/stats for managers.** Unlike "Moje historie" (filters by `userId`), the personal Trips page calls `tripListOptions`/`tripStatsOptions` with no `userId` and renders a "Řidič" column (`Trips.tsx:166,359`) — surfacing all drivers' trips and company-wide totals, unlike the strictly-personal attendance punch screen. **Fix:** pass `userId` (matching `TripsHistory`), or relabel/drop the Řidič column. Keep list and stats on one scope.
|
||||
|
||||
### 4.10 Forked/duplicated shared modules & code drift
|
||||
|
||||
- **`InvoiceDetail` forks the shared document editor (and drops the item-description maxLength cap).** Offers/issued orders compose shared `DocumentItemsEditor`/`useDocumentPdf`/`useUnsavedChangesGuard`; `InvoiceDetail` reimplements all three (`:241-541,1175-1196,942-958`). Divergence: the invoice item description textarea has **no maxLength** while the shared editor caps it (`DocumentItemsEditor.tsx:390`) — an over-long description 500s at Prisma instead of capping client-side. **Fix:** add a `showVat`/`vatOptions` flag to `DocumentItemsEditor` (respecting "VAT only on invoices") and migrate `InvoiceDetail` onto it plus the shared hooks.
|
||||
|
||||
- **Status label/color maps duplicated across warehouse, projects and leave.** `documentStatus.ts` exists specifically to kill per-page maps, yet DRAFT/CONFIRMED/CANCELLED recur across 6 warehouse files (`WarehouseIssues.tsx:35-48`), `Projects.tsx:44-57`/`ProjectDetail.tsx:37-50` are byte-identical, and `LeaveRequests.tsx:25-55`/`LeaveApproval.tsx:36-66` are byte-identical. **Fix:** add `WAREHOUSE_DOC_STATUS`, `MOVEMENT_TYPE`, `RESERVATION_STATUS`, `PROJECT_STATUS`, `LEAVE_STATUS`/`LEAVE_TYPE` to `documentStatus.ts` and import them.
|
||||
|
||||
- **`AttendanceAdmin` fetches outside React Query (raw `apiFetch` in `useEffect` + manual refetch dance).** `useAttendanceAdmin` loads projects/users/records via raw `apiFetch` with its own `setData`/`setLoading` (`:823,871`), so it doesn't participate in `['attendance']` invalidations — each mutation must invalidate AND manually re-run `fetchData` with a `setTimeout(300)` (`:1057-1063`). The single biggest structural inconsistency and a latent stale-data risk. **Fix:** migrate reads to React Query options.
|
||||
|
||||
- **Orphaned standalone attendance-create page diverges from the admin modal (no project logs).** Adding a record exists twice: a standalone full-page form at `/attendance/create` AND `ShiftFormModal` (`AttendanceAdmin.tsx:194`). The modal supports per-shift project-time logs; the standalone page can't (`AttendanceCreate.tsx:63-147`), and nothing navigates to it. **Fix:** delete `AttendanceCreate.tsx` and its route — the modal is the live superset.
|
||||
|
||||
- **"Vytvořit objednávku" modal uses two different file pickers.** The Offers-list version uses the shared `FileUpload`; the Offer-detail version reimplements it with a raw `<input type=file>` + manual readout + custom remove button (`OfferDetail.tsx:1066-1112` vs `Offers.tsx:894-929`). Same dialog, two attachment UIs. **Fix:** replace the raw input with `FileUpload` (gains drag-drop/validation).
|
||||
|
||||
- **Warehouse entities use three different create/edit interaction models.** Items edit inline on the detail page via a toggle (`WarehouseItemDetail.tsx:112`); Receipts/Issues use a full-page Form + read-only Detail; Inventory has a Form for creation only; Reservations/Categories/Locations/Suppliers use a list-page Modal. Items (a flat record like Suppliers) using inline edit is the main outlier. **Fix:** document one convention (line-item records = Form+Detail; flat lookups = list modal) and reconcile the Items outlier — treat as a documented rule, not a forced risky migration.
|
||||
|
||||
- **Inconsistent "record not found": Item detail redirects away, siblings keep a stable URL.** `WarehouseItemDetail` toasts + `navigate('/warehouse/items')` (`:153-158`); `WarehouseIssueDetail`/`ReceiptDetail`/`InventoryDetail` render an in-place "nebyla nalezena" EmptyState with a Back button and keep the URL (`:122`/`:200`/`:99`). **Fix:** align Item detail to the in-place EmptyState pattern.
|
||||
|
||||
- **Settings save model is inconsistent.** The System tab has **two** "Uložit" buttons doing the same thing (`Settings.tsx:997-1007,1193-1199`); other cards have no save; 2FA saves instantly; on Firma, bank accounts/logo apply instantly while company info/numbering/currency need the bottom save (`CompanySettings.tsx:990-1013,1457-1461`). The user can't predict whether a change is live or pending. **Fix:** drop one duplicate System Save; visually distinguish auto-apply vs pending controls.
|
||||
|
||||
- **Attendance location page formats datetime with `new Date()` instead of the timezone-safe shared helper.** `AttendanceLocation` defines a local `formatDatetimeLocal` parsing with `new Date()` (`:176`); the rest of attendance uses the timezone-safe `formatDatetime` (`attendanceHelpers.ts:42`), so the same timestamp renders differently. **Fix:** build a regex-based timezone-safe formatter that keeps the year (the location detail legitimately wants the year, which `formatDatetime` omits).
|
||||
|
||||
- **Document editor uses two reorder gestures side by side.** Line items reorder via a drag handle (`DocumentItemsEditor.tsx:350-364`), but sections (`SectionsEditor.tsx:200-219`) and company custom fields (`CompanySettings.tsx:1049-1067`) use up/down arrows — on the same page. The drag-only items are also less keyboard-discoverable. **Fix:** add up/down arrow buttons alongside the line-item drag handle (matching SectionsEditor) — also fixes the keyboard-affordance gap.
|
||||
|
||||
- **Login re-implements the theme toggle.** The shell uses shared `<ThemeToggle/>` (animated crossfade, title + aria-label); Login builds its own IconButton with hand-duplicated SVGs, only a title, no aria-label, no animation (`Login.tsx:264-313` vs `ThemeToggle.tsx:36-57`). The first screen every user sees is less accessible. **Fix:** reuse the shared `<ThemeToggle/>`.
|
||||
|
||||
### 4.11 Visual & theming consistency
|
||||
|
||||
- **Projects status-chip colors diverge from the app-wide convention (and duplicate the label map).** `documentStatus.ts` establishes success=done/paid, error=cancelled, info=open. Projects breaks all three — ACTIVE=green, COMPLETED=**blue**, CANCELLED=**grey** (`Projects.tsx:50`, `ProjectDetail.tsx:43`). So a finished project shows blue while a finished order shows green. **Fix:** add a `PROJECT_STATUS` map (aktivni→info, dokonceny→success, zruseny→error) and consume via `statusLabel`/`statusColor`.
|
||||
|
||||
- **Linked order status on Project detail renders as a raw untranslated token.** `ProjectDetail` shows `STATUS_LABELS[project.order_status]` but `STATUS_LABELS` is the _project_ map while `order_status` is `prijata`/`v_realizaci`/… — zero key overlap (`:577`), so a completed order shows "(dokoncena)" lowercase plain text. **Fix:** render via `statusLabel(ORDER_STATUS, project.order_status)` (ideally a `StatusChip`).
|
||||
|
||||
- **Settings admin-role callout uses a solid `info.light`/`info.dark` fill (the forbidden .light-fill anti-pattern).** The "Administrátor má vždy plný přístup" box is hand-styled with `bgcolor:'info.light'`/`color:'info.dark'` (`Settings.tsx:1228-1229`) — the single solid palette-.light fill in the admin, violating the documented channel-alpha rule; in dark mode it's garish low-contrast blue-on-blue. **Fix:** use the kit `<Alert severity='info'>` (`Alert.tsx:8`), or a channel-alpha wash.
|
||||
|
||||
- **Dashboard "Vystavit fakturu" quick action reuses the destructive error/red palette.** `DashQuickActions` sets color `'danger'` → MUI error (`:296`,`:59`), the same red as every Delete button, so "Issue invoice" reads as destructive beside green/blue/orange create actions. _(Caveat: red is also the invoice PDF brand family (#de3a3a), and "Odchod" uses `danger` too — this may be deliberate branding; treat as optional.)_ **Fix:** if not intentional, change to a non-destructive color (info/primary); reserve error/red for deletes.
|
||||
|
||||
- **Plan `DayInRangeModal` shows raw ISO dates while the rest of the plan dialogs format cs-CZ.** It prints "2026-06-28 – 2026-07-02" (`PlanCellModal.tsx:466,474,495`) while ViewModal/DayPanel format "28. 6. 2026." **Fix:** wrap the dates in `formatDate()`.
|
||||
|
||||
- **Project delete confirm differs between list and detail.** The list ConfirmDialog always renders the "Smazat i soubory na disku" checkbox even for projects with no NAS folder, with terse copy, no name, no irreversibility warning (`Projects.tsx:508,516`); the detail gates the checkbox on `has_nas_folder` and uses richer copy + "Tato akce je nevratná." (`ProjectDetail.tsx:621,626`). **Fix:** gate the list checkbox on `has_nas_folder` and use the same copy (name + warning).
|
||||
|
||||
### 4.12 Microcopy & localization
|
||||
|
||||
- **Goods-receipt module named four ways; "Příjmy" also reads as financial income.** Nav "Příjmy" (`navData.tsx:348`), overview button "Nový příjem" (`Warehouse.tsx:203`), list title "Příjmové doklady" + "Nový doklad" (`WarehouseReceipts.tsx:170,178`), detail/audit "Příjemka" (`WarehouseReceiptDetail.tsx:204`, `entityTypeLabels.ts:29`). Issues mirror this (Výdeje/Výdejky/Výdejka). "Příjmy" is the standard Czech word for _income_, so the nav label is actively misleading. **Fix:** settle on "Příjemka"/"Výdejka" everywhere.
|
||||
|
||||
- **Saving/busy labels inconsistent; one "Chyba pripojeni" diacritics typo; Modal overrides caller `submitText` mid-save.** Competing forms: "Ukládám…" (Modal, AttendanceCreate, NoteCard, DashProfile), "Ukládání..." (most pages), "Zpracovávám…" vs "Zpracovávám...", plus "Vytváření..."/"Odesílám..."; ellipsis sometimes "…" sometimes three dots. The connection-error fallback is "Chyba pripojeni" (no diacritics) on the dashboard (`Dashboard.tsx:127`, `AuthContext.tsx:256,314`) vs "Chyba připojení" elsewhere. Modal hardcodes `loading?'Ukládám…':submitText` (`:96`), overriding "Vytvořit uživatele" mid-save. **Fix:** fix the typo (outlier vs ~90 sites); standardize the busy label + Unicode ellipsis; the Modal hardcoding is acceptable for save forms (lower priority).
|
||||
|
||||
- **"Cancelled" order status spelled two ways in `documentStatus.ts`.** Received orders use `stornovana`→"Stornována" (`:49`); issued orders use `cancelled`→"Stornovaná" (`:58`) — side-by-side under the same `/orders` page. These are display labels (safe to change). **Fix:** pick one Czech form for both.
|
||||
|
||||
- **Add-line button uses literal "+ Přidat položku" in document editors vs icon + "Přidat položku" in warehouse forms.** `DocumentItemsEditor.tsx:596` (literal plus, no startIcon) vs warehouse forms with `startIcon={PlusIcon}` (`WarehouseIssueForm.tsx:601` etc.). **Fix:** standardize the affordance and label.
|
||||
|
||||
- **Create/edit modal submit labels mix entity-specific, bare, and default wording.** "Vytvořit zákazníka"/"Uložit změny" (`OffersCustomers.tsx:543`), "Vytvořit uživatele" (`Users.tsx:369`), bare "Vytvořit"/"Uložit" (`OffersTemplates.tsx:361`), and Vehicles falls back to the Modal default "Uložit" (`Modal.tsx:36`). **Fix:** adopt one rule (create="Vytvořit", edit="Uložit změny") and set it as the Modal default.
|
||||
|
||||
- **Create-action verb differs across analogous list pages; both Orders tabs share the identical "Vytvořit objednávku" label.** Imperative "Přidat X" (master data) vs "Nový/Nová X" (documents) vs "Vytvořit objednávku" (Orders, identical on both tabs for two different doc types, `Orders.tsx:125,129`); the empty-state CTA verb mirrors and compounds this. **Fix:** disambiguate the two Orders tabs first ("Nová vydaná/přijatá objednávka"), then pick one verb convention and align the empty-state CTA.
|
||||
|
||||
- **Several numbers/prices bypass cs-CZ formatting; file-size unit casing disagrees (kB vs KB).** Offers item-template price uses `Number().toFixed(2)`→"1234.50" (period, no separator/currency, `OffersTemplates.tsx:287`); warehouse batch picker builds "…toFixed(2) Kč" (`WarehouseIssueForm.tsx:160`); vacation/sick hour balances use `.toFixed(1)`→"12.5" (`AttendanceBalances.tsx:307`); zeros render "0 Kč" vs "0,00 Kč." File-size helper duplicated with "kB" (`FileUpload.tsx:9`) vs "KB" (`OfferDetail.tsx:1072`). **Fix:** route money through `formatCurrency` and decimals through cs-CZ/Intl; extract one `formatFileSize()` with one unit casing.
|
||||
|
||||
- **Leave-request modal day/hour estimate ignores public holidays.** The modal previews "X pracovních dnů" using `calculateBusinessDays` (Mon–Fri only, `Attendance.tsx:498,1242`), but the rest of the system is holiday-aware (server `leave-requests.ts:99` excludes weekends AND holidays). A vacation spanning e.g. 1 May over-counts vs the stored `total_days`/`total_hours`. **Fix:** make the modal estimate holiday-aware (reuse the holiday helper).
|
||||
|
||||
### 4.13 Mobile / responsive
|
||||
|
||||
- **Status-filter tab bars clip on phones — shared `Tabs` has no scrollable variant.** `Tabs.tsx:28-49` uses MUI's default `variant="standard"` (overflow hidden, no scroll). At ~360px the 5 offer/invoice tabs and 4 project tabs overflow the centered Box and get clipped with no scroll affordance — effectively unreachable. **Fix:** set `variant="scrollable"`, `scrollButtons="auto"`, `allowScrollButtonsMobile` — one change fixes every status filter and the issued/received toggle.
|
||||
|
||||
- **Shared Modal never goes full-screen on phones; leave date grid is hardcoded two-column.** `Modal` renders a plain `fullWidth+maxWidth` Dialog with no responsive `fullScreen` (`:67-75`), so the ~9-field Trip form, the admin shift form and the leave form become a narrow scrolling box at 360px. The leave modal's Od/Do grid is hardcoded `minmax(0,1fr) minmax(0,1fr)` (`Attendance.tsx:1195-1199`) while every other date-pair grid is responsive `{xs:'1fr',sm:'1fr 1fr'}` (`ShiftFormModal.tsx:254`, `Trips.tsx:528-535`). **Fix:** add `fullScreen={useMediaQuery(down('sm'))}` to Modal; fix the leave grid.
|
||||
|
||||
- **Long full-page editors keep Save only in the top header (no sticky save); placement differs page-to-page.** Document detail editors place all Save/Create/Activate in the top `headerActionsSx` slot (`OfferDetail.tsx:688-828`), so after scrolling through header fields/picker/line-items/rich-text/notes a phone user must scroll back to the top to save. `AttendanceCreate` pins Zrušit/Uložit at the **bottom** (`:362-374`); modals pin submit in DialogActions — three placements. **Fix:** add a sticky action bar to long editors and standardize placement.
|
||||
|
||||
- **Warehouse issue/receipt line items lack the labeled card-per-row mobile layout the document editor has.** `DocumentItemsEditor` has a dedicated `isMobile` branch — a bordered card per row with "Položka N" index, labeled fields, per-row total, drag/remove (`:170-342`). `WarehouseIssueForm.tsx:513-567` just collapses a grid to `xs:'1fr'` with placeholder-only fields, no border/labels/separator — once a value is typed the placeholder vanishes and rows blur together. Worst exactly where shop-floor mobile use is likely. **Fix:** reuse the card-per-row pattern (ideally a shared mobile line-item card).
|
||||
|
||||
- **FilterBar children mix fixed-vs-grow flex bases, leaving dead space on mobile.** `AttendanceAdmin.tsx:202,205` use `flex:'0 0 180px'`/`'0 0 220px'` and `AttendanceHistory.tsx:516` uses `flex:'0 0 180px'` (fixed, never grow), so on a phone they sit narrow with dead space beside them, while `Offers.tsx:786` uses `flex:'1 1 320px'` which fills the row. **Fix:** adopt one convention (e.g. `flex:'1 1 <min>px'`) or have `FilterBar` stretch children full-width below `sm`.
|
||||
|
||||
### 4.14 Accessibility
|
||||
|
||||
- **Desktop document line-item grid inputs are unlabeled while the mobile card layout labels every field.** The mobile branch passes explicit labels (Popis, Množství, Jednotka, Jedn. cena, Sleva %); the desktop table renders the same TextFields with **no** label/aria-label, relying on visual `<th>` headers not programmatically associated with the inputs; the desktop "V ceně" Checkbox is unnamed (`DocumentItemsEditor.tsx:374-440,445-450`). A screen-reader user editing an offer on desktop hears a column of unlabeled "edit text" boxes. **Fix:** add an `aria-label` to each desktop cell control (e.g. `Množství, položka ${index+1}`).
|
||||
|
||||
- **List-page search boxes are placeholder-only inputs with no accessible name.** Raw TextFields with only a placeholder (not an accessible name) across ~13 pages (`Offers.tsx:787`, `Invoices.tsx:741`, `WarehouseItems.tsx:180`, `Projects.tsx:454`, `IssuedOrders.tsx:386`). **Fix:** add `aria-label="Hledat"` + `type="search"` — best via a shared `SearchField` (also adds the native clear button and mobile search keyboard).
|
||||
|
||||
- **(Cross-listed) DataTable clickable rows aren't keyboard-operable; no skip-to-content link.** See §4.7 (row semantics) and §4.8 (skip link).
|
||||
|
||||
### 4.15 Performance & bundle
|
||||
|
||||
- **MUI + Emotion live in the 781 kB entry chunk, so every deploy busts the cached UI vendor code.** `vite.config.ts` `manualChunks` only carves out react/react-dom/react-router (436 kB) and framer-motion (147 kB); the entire MUI library + Emotion fall into the entry chunk (781 kB raw / 232 kB gzip). With frequent same-day patch releases, daily users re-download ~232 kB gzip of unchanged MUI every deploy. **Fix:** split `@mui/*`+`@emotion/*`(+quill) into a long-lived `vendor-mui` chunk.
|
||||
|
||||
- **framer-motion (147 kB) is a static dependency of the eager AppShell, loading on first paint incl. Login.** `AppShell`/`PageEnter`/`ThemeToggle` statically import framer-motion (`PageHeader` deliberately does not); `AppShell` is eagerly imported by `AdminApp` (`:8`, `AppShell.tsx:101`). Login pays for it too. **Fix:** migrate to `LazyMotion` + the lightweight `m` component (`domAnimation`) — note Login and the Dash\* components import framer-motion directly, so lazy-gating only `PageEnter` won't remove it from the login critical path.
|
||||
|
||||
- **Dashboard + its 7 Dash\* subcomponents are bundled into the entry chunk, downloaded on the Login screen.** Dashboard and Login are statically imported in `AdminApp` (`:14-15`), so an unauthenticated user hitting `/login` downloads the entire authenticated dashboard's code before typing a password. **Fix:** lazy-load Dashboard via `lazyWithReload` like every other route; keep Login eager.
|
||||
|
||||
- **No route-transition progress indicator and no link prefetch — heavy pages blank to a spinner on click.** Clicking a sidebar item blanks main content to a centered spinner while the chunk downloads (PlanWork 44 kB, InvoiceDetail 35 kB, AttendanceLocation 155 kB with Leaflet), with no top progress bar and no prefetch (zero `prefetchQuery`/`onMouseEnter`/`preload` hits). A `ProgressBar` exists but is reused only as an attendance-fund meter. **Fix:** add an unobtrusive top `LinearProgress` during route transitions and prefetch the lazy chunk (+ primary query) on sidebar link hover/focus.
|
||||
|
||||
---
|
||||
|
||||
## 5. Suggested Sequencing
|
||||
|
||||
**Sprint 1 — "Stop lying to the user" (mostly Quick Wins, ~2-3 days).**
|
||||
Ship the data-freshness convergence (one invalidation set per family), the global `QueryCache.onError` so failed fetches stop showing as empty, the scrollable mobile tabs, the invoice-paid confirm, the silent-toggle `onError` toasts, the draft-PDF 404 gate, the wrong-Orders-tab redirect, the search debounces, the `csCZ` localeText, the `document.title`, the project/order status-color fixes, and the diacritics/label typos. These are individually small, collectively high-trust, and low-risk. Pair each with a quick Playwright check on the dev server (the user runs it).
|
||||
|
||||
**Sprint 2 — "Converge the primitives" (the structural anti-drift work, ~1 week).**
|
||||
De-fork the dirty-guards and add them to the six unguarded editors; route the invoice PDF openers through `useDocumentPdf`; consolidate the status maps into `documentStatus.ts`; standardize validation on inline `<Field error>` (starting with the mirrored screens); add `<form onSubmit>` to Modal; migrate hand-rolled headers to `PageHeader`; replace inline English errors with `apiErrorMessage`. This is where you stop the Sprint-1 fixes from re-drifting, and it's the cleanest fit for the codebase's "extend, never fork" rule.
|
||||
|
||||
**Sprint 3 — "Mobile + a11y + warehouse parity" (~1 week).**
|
||||
Full-screen modals, sticky save bars, warehouse card-per-row line items, keyboard-operable rows, skip link, search-field accessible names, warehouse document totals, the leave "Nová žádost" action, and the warehouse "Potvrdit" confirm.
|
||||
|
||||
**Strategic backlog (schedule deliberately, each is multi-day and one needs a migration).**
|
||||
Invoice edit-locking (DB migration + route trio — coordinate the migration per CLAUDE.md: ask the user to stop the dev server, apply to `app_test` too). The router upgrade for in-app dirty-nav blocking. `AttendanceAdmin` onto React Query. `InvoiceDetail` onto the shared editor. Real skeletons. Bundle splitting + route prefetch. Treat the navigation/IA items (breadcrumbs, master-data nav grouping, `/customers` move) as a focused IA pass once the above settle.
|
||||
|
||||
A note on scope discipline: nearly every item here is "make B match the already-correct A," so the safest pattern is to **read the reference implementation first** (offers/issued orders for documents, `WarehouseSuppliers` for lists, `documentStatus.ts` for status) and converge onto it — rather than inventing new patterns. That keeps the diff small and the regression surface low, which matches the user's same-day-patch-release rhythm.
|
||||
73
README.md
Normal file
73
README.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# boha-app-ts
|
||||
|
||||
Internal business-management system for a Czech company (attendance, invoicing,
|
||||
leave/trips, projects, vehicles, warehouse, HR) — a TypeScript/Node.js rewrite
|
||||
of the legacy PHP app. User-facing text is Czech by design.
|
||||
|
||||
> For full architecture, conventions, and gotchas, see **[CLAUDE.md](./CLAUDE.md)**.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Backend:** Fastify 5 · Prisma 6 → MySQL · Zod 4 · JWT (HS256) + TOTP 2FA
|
||||
- **Frontend:** React 18 · Vite · Material UI v7 (Emotion) · TanStack Query — an
|
||||
SPA in `src/admin/`, served by the same Fastify process (Vite middleware in
|
||||
dev, static files in prod)
|
||||
- **Other:** Puppeteer (PDF) · nodemailer · node-cron · `@anthropic-ai/sdk` (the
|
||||
admins-only "Odin" assistant)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js (LTS) and a MySQL database
|
||||
- Copy `.env.example` → `.env` and fill in the **required** vars (`DATABASE_URL`,
|
||||
`JWT_SECRET`, `TOTP_ENCRYPTION_KEY` — generate the keys with `openssl rand -hex 32`)
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npx prisma generate
|
||||
npx prisma migrate dev # apply migrations to your dev DB
|
||||
npx prisma db seed # optional: dev-only sample data (NEVER on prod)
|
||||
```
|
||||
|
||||
## Develop
|
||||
|
||||
```bash
|
||||
npm run dev:server # API (tsx watch) on http://127.0.0.1:3050
|
||||
npm run dev:client # Vite dev server (manage separately)
|
||||
```
|
||||
|
||||
## Build & run
|
||||
|
||||
```bash
|
||||
npm run build # tsc server → dist/ + vite client → dist-client/
|
||||
npm start # node dist/server.js
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
npm test # vitest run — hits a real test DB (.env.test); no Prisma mocks
|
||||
```
|
||||
|
||||
## Quality gates
|
||||
|
||||
Before committing, all of these must pass:
|
||||
|
||||
```bash
|
||||
npx tsc -b --noEmit # typecheck (NOT `tsc -p tsconfig.json`)
|
||||
npm run build
|
||||
npx vitest run
|
||||
npm run lint # ESLint (incl. react-hooks) — see eslint.config.js
|
||||
```
|
||||
|
||||
## Database migrations
|
||||
|
||||
Every schema/data change is a tracked Prisma migration — **never** `prisma db push`
|
||||
or raw SQL on production. Stop the dev server before running `prisma migrate dev`.
|
||||
See CLAUDE.md → _Database Migrations_ for the full workflow and the production
|
||||
deploy/hotfix process.
|
||||
|
||||
## License
|
||||
|
||||
ISC
|
||||
393
REVIEW.md
Normal file
393
REVIEW.md
Normal file
@@ -0,0 +1,393 @@
|
||||
# Codebase Audit Checklist
|
||||
|
||||
**Date:** 2026-06-09 | **Total files:** 304 | Scope: full project (source + config). Excluded: docs/*.md, prisma/migrations/*.sql (generated SQL), package-lock.json, binaries.
|
||||
|
||||
## (root)
|
||||
|
||||
- [x] .env.example
|
||||
- [x] .gitignore
|
||||
- [x] .prettierignore
|
||||
- [x] .prettierrc.json
|
||||
- [x] boneyard.config.json
|
||||
- [x] CLAUDE.md
|
||||
- [x] eslint.config.mjs
|
||||
- [x] index.html
|
||||
- [x] package.json
|
||||
- [x] prisma.config.ts
|
||||
- [x] tsconfig.app.json
|
||||
- [x] tsconfig.json
|
||||
- [x] tsconfig.server.json
|
||||
- [x] tsconfig.test.json
|
||||
- [x] vite.config.ts
|
||||
- [x] vitest.config.ts
|
||||
|
||||
## .claude
|
||||
|
||||
- [x] .claude/hooks/block-env.js
|
||||
- [x] .claude/hooks/format-on-save.js
|
||||
- [x] .claude/settings.json
|
||||
- [x] .claude/settings.local.json
|
||||
|
||||
## prisma
|
||||
|
||||
- [x] prisma/seed.ts
|
||||
- [x] prisma/schema.prisma
|
||||
|
||||
## scripts
|
||||
|
||||
- [x] scripts/check-roles.mjs
|
||||
- [x] scripts/migrate-received-invoices-to-nas.ts
|
||||
- [x] scripts/rotate-totp-key.ts
|
||||
- [x] scripts/seed-test-users.mjs
|
||||
|
||||
## src/__tests__
|
||||
|
||||
- [x] src/__tests__/ai.test.ts
|
||||
- [x] src/__tests__/auth.service.test.ts
|
||||
- [x] src/__tests__/auth.test.ts
|
||||
- [x] src/__tests__/bank-accounts.test.ts
|
||||
- [x] src/__tests__/company-settings-numbering.test.ts
|
||||
- [x] src/__tests__/customers.schema.test.ts
|
||||
- [x] src/__tests__/drafts-aggregation.test.ts
|
||||
- [x] src/__tests__/drafts-deferred-numbering.test.ts
|
||||
- [x] src/__tests__/env.test.ts
|
||||
- [x] src/__tests__/exchange-rates.test.ts
|
||||
- [x] src/__tests__/helpers.ts
|
||||
- [x] src/__tests__/invoices.service.test.ts
|
||||
- [x] src/__tests__/issued-orders.test.ts
|
||||
- [x] src/__tests__/manual-create.test.ts
|
||||
- [x] src/__tests__/nas-document-manager.test.ts
|
||||
- [x] src/__tests__/nas-file-manager.test.ts
|
||||
- [x] src/__tests__/nas-project-folder.test.ts
|
||||
- [x] src/__tests__/numbering.test.ts
|
||||
- [x] src/__tests__/offer-invoice-totals.test.ts
|
||||
- [x] src/__tests__/orders-list.test.ts
|
||||
- [x] src/__tests__/order-totals.test.ts
|
||||
- [x] src/__tests__/plan.test.ts
|
||||
- [x] src/__tests__/planAuditDescription.test.ts
|
||||
- [x] src/__tests__/planCategory.test.ts
|
||||
- [x] src/__tests__/received-invoices-vat.test.ts
|
||||
- [x] src/__tests__/setup.ts
|
||||
- [x] src/__tests__/schema-nan.test.ts
|
||||
- [x] src/__tests__/warehouse.test.ts
|
||||
|
||||
## src/admin (AdminApp.tsx)
|
||||
|
||||
- [x] src/admin/AdminApp.tsx
|
||||
|
||||
## src/admin (components)
|
||||
|
||||
- [x] src/admin/components/AlertContainer.tsx
|
||||
- [x] src/admin/components/AttendanceShiftTable.tsx
|
||||
- [x] src/admin/components/BulkAttendanceModal.tsx
|
||||
- [x] src/admin/components/BulkPlanModal.tsx
|
||||
- [x] src/admin/components/dashboard/DashActivityFeed.tsx
|
||||
- [x] src/admin/components/dashboard/DashAttendanceToday.tsx
|
||||
- [x] src/admin/components/dashboard/DashKpiCards.tsx
|
||||
- [x] src/admin/components/dashboard/DashProfile.tsx
|
||||
- [x] src/admin/components/dashboard/DashQuickActions.tsx
|
||||
- [x] src/admin/components/dashboard/DashSessions.tsx
|
||||
- [x] src/admin/components/dashboard/DashTodayPlan.tsx
|
||||
- [x] src/admin/components/ErrorBoundary.tsx
|
||||
- [x] src/admin/components/Forbidden.tsx
|
||||
- [x] src/admin/components/odin/InvoiceReviewCard.tsx
|
||||
- [x] src/admin/components/odin/OdinComposer.tsx
|
||||
- [x] src/admin/components/odin/OdinChat.tsx
|
||||
- [x] src/admin/components/odin/OdinMark.tsx
|
||||
- [x] src/admin/components/odin/OdinSidebar.tsx
|
||||
- [x] src/admin/components/odin/OdinThread.tsx
|
||||
- [x] src/admin/components/odin/types.ts
|
||||
- [x] src/admin/components/OrderConfirmationModal.tsx
|
||||
- [x] src/admin/components/PlanCategoriesModal.tsx
|
||||
- [x] src/admin/components/PlanCellModal.tsx
|
||||
- [x] src/admin/components/PlanGrid.tsx
|
||||
- [x] src/admin/components/PlanRangeChips.tsx
|
||||
- [x] src/admin/components/ProjectFileManager.tsx
|
||||
- [x] src/admin/components/RichEditor.tsx
|
||||
- [x] src/admin/components/ShiftFormModal.tsx
|
||||
- [x] src/admin/components/ShortcutsHelp.tsx
|
||||
- [x] src/admin/components/warehouse/ItemPicker.tsx
|
||||
- [x] src/admin/components/warehouse/ReservationPicker.tsx
|
||||
|
||||
## src/admin (context)
|
||||
|
||||
- [x] src/admin/context/AlertContext.tsx
|
||||
- [x] src/admin/context/AuthContext.tsx
|
||||
|
||||
## src/admin (GlobalStyles.tsx)
|
||||
|
||||
- [x] src/admin/GlobalStyles.tsx
|
||||
|
||||
## src/admin (hooks)
|
||||
|
||||
- [x] src/admin/hooks/useAttendanceAdmin.ts
|
||||
- [x] src/admin/hooks/useDebounce.ts
|
||||
- [x] src/admin/hooks/useModalLock.ts
|
||||
- [x] src/admin/hooks/usePaginatedQuery.ts
|
||||
- [x] src/admin/hooks/usePlanWork.ts
|
||||
- [x] src/admin/hooks/useReducedMotion.ts
|
||||
- [x] src/admin/hooks/useTableSort.ts
|
||||
|
||||
## src/admin (lib)
|
||||
|
||||
- [x] src/admin/lib/apiAdapter.ts
|
||||
- [x] src/admin/lib/documentStatus.ts
|
||||
- [x] src/admin/lib/entityTypeLabels.ts
|
||||
- [x] src/admin/lib/queries/ai.ts
|
||||
- [x] src/admin/lib/queries/attendance.ts
|
||||
- [x] src/admin/lib/queries/auditLog.ts
|
||||
- [x] src/admin/lib/queries/common.ts
|
||||
- [x] src/admin/lib/queries/dashboard.ts
|
||||
- [x] src/admin/lib/queries/invoices.ts
|
||||
- [x] src/admin/lib/queries/issued-orders.ts
|
||||
- [x] src/admin/lib/queries/leave.ts
|
||||
- [x] src/admin/lib/queries/mutations.ts
|
||||
- [x] src/admin/lib/queries/offers.ts
|
||||
- [x] src/admin/lib/queries/orders.ts
|
||||
- [x] src/admin/lib/queries/plan.ts
|
||||
- [x] src/admin/lib/queries/projects.ts
|
||||
- [x] src/admin/lib/queries/settings.ts
|
||||
- [x] src/admin/lib/queries/trips.ts
|
||||
- [x] src/admin/lib/queries/users.ts
|
||||
- [x] src/admin/lib/queries/vehicles.ts
|
||||
- [x] src/admin/lib/queries/warehouse.ts
|
||||
- [x] src/admin/lib/queryClient.ts
|
||||
|
||||
## src/admin (pages)
|
||||
|
||||
- [x] src/admin/pages/Attendance.tsx
|
||||
- [x] src/admin/pages/AttendanceAdmin.tsx
|
||||
- [x] src/admin/pages/AttendanceBalances.tsx
|
||||
- [x] src/admin/pages/AttendanceCreate.tsx
|
||||
- [x] src/admin/pages/AttendanceHistory.tsx
|
||||
- [x] src/admin/pages/AttendanceLocation.tsx
|
||||
- [x] src/admin/pages/AuditLog.tsx
|
||||
- [x] src/admin/pages/CompanySettings.tsx
|
||||
- [x] src/admin/pages/Dashboard.tsx
|
||||
- [x] src/admin/pages/InvoiceDetail.tsx
|
||||
- [x] src/admin/pages/Invoices.tsx
|
||||
- [x] src/admin/pages/IssuedOrderDetail.tsx
|
||||
- [x] src/admin/pages/IssuedOrders.tsx
|
||||
- [x] src/admin/pages/LeaveApproval.tsx
|
||||
- [x] src/admin/pages/LeaveRequests.tsx
|
||||
- [x] src/admin/pages/Login.tsx
|
||||
- [x] src/admin/pages/NotFound.tsx
|
||||
- [x] src/admin/pages/Odin.tsx
|
||||
- [x] src/admin/pages/OfferDetail.tsx
|
||||
- [x] src/admin/pages/Offers.tsx
|
||||
- [x] src/admin/pages/OffersCustomers.tsx
|
||||
- [x] src/admin/pages/OffersTemplates.tsx
|
||||
- [x] src/admin/pages/OrderDetail.tsx
|
||||
- [x] src/admin/pages/Orders.tsx
|
||||
- [x] src/admin/pages/PlanWork.tsx
|
||||
- [x] src/admin/pages/ProjectDetail.tsx
|
||||
- [x] src/admin/pages/Projects.tsx
|
||||
- [x] src/admin/pages/ReceivedInvoices.tsx
|
||||
- [x] src/admin/pages/ReceivedOrders.tsx
|
||||
- [x] src/admin/pages/Settings.tsx
|
||||
- [x] src/admin/pages/Trips.tsx
|
||||
- [x] src/admin/pages/TripsAdmin.tsx
|
||||
- [x] src/admin/pages/TripsHistory.tsx
|
||||
- [x] src/admin/pages/UiKit.tsx
|
||||
- [x] src/admin/pages/Users.tsx
|
||||
- [x] src/admin/pages/Vehicles.tsx
|
||||
- [x] src/admin/pages/Warehouse.tsx
|
||||
- [x] src/admin/pages/WarehouseCategories.tsx
|
||||
- [x] src/admin/pages/WarehouseInventory.tsx
|
||||
- [x] src/admin/pages/WarehouseInventoryDetail.tsx
|
||||
- [x] src/admin/pages/WarehouseInventoryForm.tsx
|
||||
- [x] src/admin/pages/WarehouseIssueDetail.tsx
|
||||
- [x] src/admin/pages/WarehouseIssueForm.tsx
|
||||
- [x] src/admin/pages/WarehouseIssues.tsx
|
||||
- [x] src/admin/pages/WarehouseItemDetail.tsx
|
||||
- [x] src/admin/pages/WarehouseItems.tsx
|
||||
- [x] src/admin/pages/WarehouseLocations.tsx
|
||||
- [x] src/admin/pages/WarehouseReceiptDetail.tsx
|
||||
- [x] src/admin/pages/WarehouseReceiptForm.tsx
|
||||
- [x] src/admin/pages/WarehouseReceipts.tsx
|
||||
- [x] src/admin/pages/WarehouseReports.tsx
|
||||
- [x] src/admin/pages/WarehouseReservations.tsx
|
||||
- [x] src/admin/pages/WarehouseSuppliers.tsx
|
||||
|
||||
## src/admin (theme.test.ts)
|
||||
|
||||
- [x] src/admin/theme.test.ts
|
||||
|
||||
## src/admin (theme.ts)
|
||||
|
||||
- [x] src/admin/theme.ts
|
||||
|
||||
## src/admin (ui)
|
||||
|
||||
- [x] src/admin/ui/Alert.tsx
|
||||
- [x] src/admin/ui/AppShell.tsx
|
||||
- [x] src/admin/ui/Button.tsx
|
||||
- [x] src/admin/ui/Card.tsx
|
||||
- [x] src/admin/ui/ConfirmDialog.tsx
|
||||
- [x] src/admin/ui/CustomerPicker.tsx
|
||||
- [x] src/admin/ui/DataTable.tsx
|
||||
- [x] src/admin/ui/DateField.tsx
|
||||
- [x] src/admin/ui/EmptyState.tsx
|
||||
- [x] src/admin/ui/Field.tsx
|
||||
- [x] src/admin/ui/FileUpload.tsx
|
||||
- [x] src/admin/ui/FilterBar.tsx
|
||||
- [x] src/admin/ui/Checkbox.tsx
|
||||
- [x] src/admin/ui/index.ts
|
||||
- [x] src/admin/ui/LoadingState.tsx
|
||||
- [x] src/admin/ui/Modal.tsx
|
||||
- [x] src/admin/ui/MonthField.tsx
|
||||
- [x] src/admin/ui/MuiProvider.tsx
|
||||
- [x] src/admin/ui/navData.tsx
|
||||
- [x] src/admin/ui/PageEnter.tsx
|
||||
- [x] src/admin/ui/PageHeader.tsx
|
||||
- [x] src/admin/ui/Pagination.tsx
|
||||
- [x] src/admin/ui/ProgressBar.tsx
|
||||
- [x] src/admin/ui/RichText.tsx
|
||||
- [x] src/admin/ui/Select.tsx
|
||||
- [x] src/admin/ui/SidebarNav.tsx
|
||||
- [x] src/admin/ui/StatCard.tsx
|
||||
- [x] src/admin/ui/StatusChip.tsx
|
||||
- [x] src/admin/ui/Tabs.tsx
|
||||
- [x] src/admin/ui/TextField.tsx
|
||||
- [x] src/admin/ui/ThemeToggle.tsx
|
||||
- [x] src/admin/ui/TimeField.tsx
|
||||
- [x] src/admin/ui/useDialogScrollLock.ts
|
||||
|
||||
## src/admin (utils)
|
||||
|
||||
- [x] src/admin/utils/api.ts
|
||||
- [x] src/admin/utils/attendanceHelpers.ts
|
||||
- [x] src/admin/utils/dashboardHelpers.ts
|
||||
- [x] src/admin/utils/formatters.ts
|
||||
|
||||
## src/App.tsx
|
||||
|
||||
- [x] src/App.tsx
|
||||
|
||||
## src/config
|
||||
|
||||
- [x] src/config/database.ts
|
||||
- [x] src/config/env.ts
|
||||
|
||||
## src/context
|
||||
|
||||
- [x] src/context/ThemeContext.tsx
|
||||
|
||||
## src/main.tsx
|
||||
|
||||
- [x] src/main.tsx
|
||||
|
||||
## src/middleware
|
||||
|
||||
- [x] src/middleware/auth.ts
|
||||
- [x] src/middleware/security.ts
|
||||
|
||||
## src/routes
|
||||
|
||||
- [x] src/routes/admin/ai.ts
|
||||
- [x] src/routes/admin/attendance.ts
|
||||
- [x] src/routes/admin/audit-log.ts
|
||||
- [x] src/routes/admin/auth.ts
|
||||
- [x] src/routes/admin/bank-accounts.ts
|
||||
- [x] src/routes/admin/company-settings.ts
|
||||
- [x] src/routes/admin/customers.ts
|
||||
- [x] src/routes/admin/dashboard.ts
|
||||
- [x] src/routes/admin/invoices.ts
|
||||
- [x] src/routes/admin/invoices-pdf.ts
|
||||
- [x] src/routes/admin/issued-orders.ts
|
||||
- [x] src/routes/admin/issued-orders-pdf.ts
|
||||
- [x] src/routes/admin/leave-requests.ts
|
||||
- [x] src/routes/admin/offers-pdf.ts
|
||||
- [x] src/routes/admin/orders.ts
|
||||
- [x] src/routes/admin/orders-pdf.ts
|
||||
- [x] src/routes/admin/plan.ts
|
||||
- [x] src/routes/admin/profile.ts
|
||||
- [x] src/routes/admin/project-files.ts
|
||||
- [x] src/routes/admin/projects.ts
|
||||
- [x] src/routes/admin/quotations.ts
|
||||
- [x] src/routes/admin/received-invoices.ts
|
||||
- [x] src/routes/admin/roles.ts
|
||||
- [x] src/routes/admin/scope-templates.ts
|
||||
- [x] src/routes/admin/sessions.ts
|
||||
- [x] src/routes/admin/totp.ts
|
||||
- [x] src/routes/admin/trips.ts
|
||||
- [x] src/routes/admin/users.ts
|
||||
- [x] src/routes/admin/vehicles.ts
|
||||
- [x] src/routes/admin/warehouse.ts
|
||||
|
||||
## src/server.ts
|
||||
|
||||
- [x] src/server.ts
|
||||
|
||||
## src/services
|
||||
|
||||
- [x] src/services/ai.service.ts
|
||||
- [x] src/services/attendance.service.ts
|
||||
- [x] src/services/audit.ts
|
||||
- [x] src/services/auth.ts
|
||||
- [x] src/services/exchange-rates.ts
|
||||
- [x] src/services/invoice-alerts.ts
|
||||
- [x] src/services/invoices.service.ts
|
||||
- [x] src/services/issued-orders.service.ts
|
||||
- [x] src/services/leave-notification.ts
|
||||
- [x] src/services/mailer.ts
|
||||
- [x] src/services/nas-file-manager.ts
|
||||
- [x] src/services/nas-financials-manager.ts
|
||||
- [x] src/services/nas-offers-manager.ts
|
||||
- [x] src/services/numbering.service.ts
|
||||
- [x] src/services/offers.service.ts
|
||||
- [x] src/services/orders.service.ts
|
||||
- [x] src/services/plan.service.ts
|
||||
- [x] src/services/planCategory.service.ts
|
||||
- [x] src/services/projects.service.ts
|
||||
- [x] src/services/system-settings.ts
|
||||
- [x] src/services/users.service.ts
|
||||
- [x] src/services/warehouse.service.ts
|
||||
|
||||
## src/schemas
|
||||
|
||||
- [x] src/schemas/ai.schema.ts
|
||||
- [x] src/schemas/attendance.schema.ts
|
||||
- [x] src/schemas/auth.schema.ts
|
||||
- [x] src/schemas/bank-accounts.schema.ts
|
||||
- [x] src/schemas/common.ts
|
||||
- [x] src/schemas/customers.schema.ts
|
||||
- [x] src/schemas/invoices.schema.ts
|
||||
- [x] src/schemas/issued-orders.schema.ts
|
||||
- [x] src/schemas/leave-requests.schema.ts
|
||||
- [x] src/schemas/offers.schema.ts
|
||||
- [x] src/schemas/orders.schema.ts
|
||||
- [x] src/schemas/plan.schema.ts
|
||||
- [x] src/schemas/planCategory.schema.ts
|
||||
- [x] src/schemas/profile.schema.ts
|
||||
- [x] src/schemas/projects.schema.ts
|
||||
- [x] src/schemas/received-invoices.schema.ts
|
||||
- [x] src/schemas/roles.schema.ts
|
||||
- [x] src/schemas/scope-templates.schema.ts
|
||||
- [x] src/schemas/settings.schema.ts
|
||||
- [x] src/schemas/trips.schema.ts
|
||||
- [x] src/schemas/users.schema.ts
|
||||
- [x] src/schemas/vehicles.schema.ts
|
||||
- [x] src/schemas/warehouse.schema.ts
|
||||
|
||||
## src/types
|
||||
|
||||
- [x] src/types/fastify.d.ts
|
||||
- [x] src/types/index.ts
|
||||
|
||||
## src/utils
|
||||
|
||||
- [x] src/utils/czech-holidays.ts
|
||||
- [x] src/utils/date.ts
|
||||
- [x] src/utils/encryption.ts
|
||||
- [x] src/utils/html-to-pdf.ts
|
||||
- [x] src/utils/pagination.ts
|
||||
- [x] src/utils/planAuditDescription.ts
|
||||
- [x] src/utils/response.ts
|
||||
- [x] src/utils/totp.ts
|
||||
|
||||
## src/vite-env.d.ts
|
||||
|
||||
- [x] src/vite-env.d.ts
|
||||
|
||||
|
||||
1580
REVIEW_FINDINGS.md
Normal file
1580
REVIEW_FINDINGS.md
Normal file
File diff suppressed because it is too large
Load Diff
180
docs/cross-module-consistency-audit-2026-06-09.md
Normal file
180
docs/cross-module-consistency-audit-2026-06-09.md
Normal file
@@ -0,0 +1,180 @@
|
||||
# Cross-Module Consistency Report: Offers, Invoices, Orders
|
||||
|
||||
> Generated 2026-06-09 by a multi-agent UI/UX audit (4 by-dimension examiners + synthesis)
|
||||
> across the Offers (nabídky), Invoices (faktury), and Orders (objednávky) modules.
|
||||
> Examination only — no code was changed. File:line refs are at the time of the audit.
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
The three document modules (Offers, Invoices, Orders) share a strong common foundation — `PageEnter`/`PageHeader`/`Card`/`FilterBar`/`DataTable`/`StatusChip`/`Pagination`, a near-identical line-item editor (dnd-kit drag, mobile cards, monospace per-row totals, per-rate VAT breakdown), and a uniform totals layout — so the divergences are concentrated in a handful of presentational and behavioral details rather than the architecture. **No single module is canonical across the board:** Invoices is the most mature on list-level intelligence (KPI StatCards, overdue row tinting) and is the only one with a polished load pattern (ReceivedInvoices' `hasLoadedOnce` skeleton suppression); Issued Orders is the cleanest detail-page reference (single editable form with a `readOnly` prop, semantically correct status-transition button colors); and Offers is the best on list-level state richness (three-tier `rowSx` tinting, search-aware empty states) but the worst on detail-form fidelity (raw HTML checkboxes, action-icon overload). The highest-value work clusters into four buckets: bring Orders up to Invoices' list intelligence (KPIs, filters, row tinting), converge the three detail forms on shared MUI kit components (Autocomplete customer picker, MUI Checkbox, RichEditor notes), fix two genuine safety/feature bugs (delete-button guards and Orders' missing delete), and a long tail of cheap label/width/alignment unifications in the line-item tables.
|
||||
|
||||
## 2. Recommended Canonical Patterns
|
||||
|
||||
| Dimension | Standardize on | Why |
|
||||
| ------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| List KPI cards | **Invoices** (`Invoices.tsx:420-505`) | Only module with a 4-card metrics grid; gives business context Orders/Offers lack |
|
||||
| List load/skeleton | **ReceivedInvoices** (`hasLoadedOnce` ref, lines 325/688/784) | Skeleton only on first mount, suppressed on refetch — no full-page blocking jank |
|
||||
| List row state tinting | **Offers** (`Offers.tsx:650-684`) three-tier `rowSx` | Richest at-a-glance lifecycle signal; Invoices' single overdue tint is the minimal version |
|
||||
| List status filter | **Tabs** for ≤4 states (Offers/Invoices), **Select** for ≥5 (IssuedOrders) | Tabs show all options inline; Select scales — choose by option count |
|
||||
| Search-aware empty state | **Offers** (`Offers.tsx:840-855`) | Distinguishes search-empty (no CTA) from list-empty (with CTA) |
|
||||
| Detail read-only mode | **IssuedOrderDetail** (single form + `readOnly` prop, `:638`) | DRY; avoids InvoiceDetail's duplicate read-only JSX branch that must be hand-synced |
|
||||
| Status-transition button colors | **IssuedOrderDetail** (`:903-917`) | Destructive = `outlined`+`error`, positive = `contained`+`primary` (semantically correct) |
|
||||
| Save-button loading | **Invoice/Order** (CircularProgress + text) | Clearer visual signal than Offers' text-only swap |
|
||||
| Detail guard placement | **OfferDetail** (all guards top-level, `:1087-1091`) | Flattest; no `if (!dataReady)` buried inside render branches |
|
||||
| Customer/supplier picker | **MUI Autocomplete freeSolo** (as in `ReceivedInvoices.tsx:914-929`) | Keyboard-accessible, searchable, Material-standard |
|
||||
| Boolean fields | **MUI `CheckboxField` kit** (as in OrdersReceived modal) | Themed, accessible; replaces raw `<input type=checkbox>` |
|
||||
| Notes fields | **RichEditor** (Offers/Orders already) | Uniform editing; future-proof for formatting |
|
||||
| `issued_by` | **Read-only, auto-filled** (Invoices, `:1881-1885`) | Immutable provenance tied to the issuing user |
|
||||
| Currency options | **Company settings** (Offers/Invoices) | Admin-configurable without code change |
|
||||
| Line-item labels/widths | **Invoices+Orders majority** ("Jedn. cena", qty `5.5rem`, remove `2.5rem`, `align="center"`) | 2-of-3 already agree; Offers is the lone outlier |
|
||||
| Amount column header | **"Celkem"** (all but ReceivedInvoices' "Částka") | Single label for the same concept |
|
||||
|
||||
## 3. Inconsistencies by Dimension
|
||||
|
||||
### A. Tables & Lists
|
||||
|
||||
**HIGH — Orders lack KPI StatCards.** Invoices renders a 4-card metrics grid (`Invoices.tsx:420-505`; ReceivedInvoices `:687-761`); IssuedOrders, OrdersReceived, and Offers render none. Orders users lose pipeline visibility (count by status, total value). Fix: add a 4-StatCard grid to IssuedOrders/OrdersReceived mirroring the Invoices layout. Decide whether Offers warrants its own. Effort: **M**.
|
||||
|
||||
**HIGH — Offers row-action overload (6-7 icons vs 3).** `Offers.tsx:540-641` renders View/Edit, Duplicate, Show/Create Order, Invalidate, PDF, Delete; Invoices/IssuedOrders/OrdersReceived keep 3. Fix: reduce Offers to 4 (View/Edit, Order toggle, PDF, Delete); move Duplicate/Invalidate into a row overflow menu or the detail page. Effort: **M**.
|
||||
|
||||
**MED — Orders missing list features that Invoices/Offers have.**
|
||||
|
||||
- _Row state tinting:_ Offers 3-tier (`:650-684`), Invoices 1-tier overdue (`:510-526`), all three Orders modules + ReceivedInvoices = none. Add `rowSx` (completed→success wash, overdue/expired→warning, voided→opacity) using the channel-alpha convention. Effort: **S** each.
|
||||
- _Status filter:_ OrdersReceived has none; add a Select like IssuedOrders (`:305-313`, `STATUS_OPTIONS` `:53`). Effort: **S**.
|
||||
- _Sortable columns:_ IssuedOrders/OrdersReceived expose only 3 `sortKey`s vs 5-6 in Invoices/Offers; add customer_name, total, status. Effort: **S**.
|
||||
|
||||
**MED — Load pattern blocks the page on refetch.** Offers (`:453`), Invoices (`:402`), IssuedOrders (`:189`), OrdersReceived (`:328`) return a full `<LoadingState/>` whenever `isPending`; only ReceivedInvoices suppresses the skeleton after first load (`hasLoadedOnce`, `:325/688/784`). Adopt the `hasLoadedOnce` ref pattern everywhere. Effort: **S-M**.
|
||||
|
||||
**MED — Amount column label split.** ReceivedInvoices uses "Částka"; everyone else "Celkem". Rename "Částka"→"Celkem". (supplier-vs-customer terminology "Dodavatel"/"Zákazník" is correctly domain-specific — leave it.) Effort: **S**.
|
||||
|
||||
**LOW — Offers tabs not centered.** Invoices/Orders wrap Tabs in a centered Box (`Invoices.tsx:712-721`, `Orders.tsx:161-170`); Offers (`:717-726`) left-aligns. Effort: **S**.
|
||||
|
||||
**LOW — Empty-state copy not search-aware.** Offers distinguishes search-empty vs list-empty (`:840-855`); the others show one message (+ stale CTA when filtered to empty). Effort: **S**.
|
||||
|
||||
_Already fine: PageHeader, FilterBar layout, Pagination placement, StatusChip colors, search-placeholder copy, draft-banner presence (Offers/Invoices by design)._
|
||||
|
||||
### B. Detail Buttons & Layout
|
||||
|
||||
**HIGH — Delete-button safety bugs + Orders feature gap.**
|
||||
|
||||
- OfferDetail (`:1191-1199`) allows delete even when invalidated/locked/completed.
|
||||
- InvoiceDetail (`:1167-1175`, `:1734-1742`) allows delete even when `paid`.
|
||||
- IssuedOrderDetail has **no delete at all** (no button/mutation/handler).
|
||||
Fix: add `!readOnly`/status guards to Offers and Invoices; add a guarded delete to IssuedOrderDetail for parity. Effort: **M**.
|
||||
|
||||
**HIGH — Detail read-only handling diverges.** IssuedOrderDetail uses one form with a `readOnly`/`editable` flag (`:638`); InvoiceDetail forks a whole separate read-only JSX branch for paid invoices (`:1104-1615`) that must be hand-synced; OfferDetail is always editable. Fix: refactor InvoiceDetail's paid view to the single-form-`readOnly`-prop model. Effort: **L**.
|
||||
|
||||
**MED — Status-transition button styling inverted.** InvoiceDetail emphasizes positive ("paid"→`contained`+`primary`, `:1719-1733`); IssuedOrderDetail emphasizes danger ("cancelled"→`outlined`+`error`, `:903-917`). Standardize on the Order rule. Effort: **S**.
|
||||
|
||||
**MED — Back-button target inconsistent.** OfferDetail→`/offers` (`:1108`), InvoiceDetail→`/invoices` (`:1124`/`:1639`), IssuedOrderDetail→`/orders?tab=vydane` (`:836`). Make tabbed-landing modules carry the tab param: Invoices→`/invoices?tab=issued`. Effort: **S**.
|
||||
|
||||
**LOW — Save-button loading style.** Offers text-only (`:1187`); Invoice/Order spinner+text. Switch Offers to spinner+text. Effort: **S**.
|
||||
|
||||
**LOW — Create-success invalidation scope.** OfferDetail invalidates `["offers","orders","projects","invoices"]` (`:927`); Invoice/Order invalidate only their own domain. Verify Invoice/Order touch no foreign domains, else widen. Effort: **S**.
|
||||
|
||||
**LOW — Guard placement.** Hoist Invoice/Order `if (!dataReady)` guards to OfferDetail's top-level pattern when touching those files. Effort: **S**.
|
||||
|
||||
_Already fine: PageEnter wrapper, header layout + `headerActionsSx`, StatusChip-in-header, mobile breakpoints, Card sectioning, items-table structure, totals block, permission guards._
|
||||
|
||||
### C. Forms & Fields
|
||||
|
||||
**HIGH — Customer/supplier picker: 3 different widgets.** Offers (`OfferDetail.tsx:1307-1373`) and Invoices (`InvoiceDetail.tsx:1816-1876`) use a hand-rolled searchable dropdown; IssuedOrders (`:935-948`) uses a plain non-searchable `<Select>`; ReceivedInvoices (`:914-929`) uses MUI `Autocomplete freeSolo`. Standardize all on `Autocomplete freeSolo`. Effort: **M**.
|
||||
|
||||
**HIGH — `apply_vat` boolean: MUI Checkbox vs raw `<input>`.** Offers uses MUI `Checkbox` (`:1482-1488`); InvoiceDetail (`:2008-2017`) and IssuedOrderDetail (`:1023-1035`) use raw `<input type="checkbox">`. Standardize on the kit `CheckboxField`. Effort: **S**.
|
||||
|
||||
**HIGH — Notes field: TextField vs RichEditor.** Offers (`:1953-1966`) and Orders (`:1257-1272`) use RichEditor; Invoices (`:2232-2240`) and ReceivedInvoices modal (`:1214-1225`) use plain multiline TextField. Move Invoices notes to RichEditor — and per CLAUDE.md gotcha #5, apply DOMPurify + `cleanQuillHtml` sanitization on both the PDF and render paths. Effort: **M**.
|
||||
|
||||
**MED — `issued_by` editable in Orders, read-only in Invoices.** Make Orders read-only + auto-filled from auth. Effort: **S**.
|
||||
|
||||
**MED — VAT rate/toggle layout differs.** Adopt Offers' dual-field (rate Select + toggle) where a per-document rate applies. Effort: **M**.
|
||||
|
||||
**LOW — Currency options hard-coded in Orders.** IssuedOrders (`:96-99,985`) and OrdersReceived modal (`:575-580`) hard-code; point at company settings. Effort: **S**.
|
||||
|
||||
_Already fine: `<Field>` wrapper + error display, DateField usage, totals footer, Card grouping, basic-info grid, delivery/payment terms being Orders-only (domain-justified)._
|
||||
|
||||
### D. Line-Item Editors
|
||||
|
||||
Offers is the consistent outlier; Invoices+Orders already agree — canonicalize on them. Cheap, mostly-mechanical edits in `OfferDetail.tsx` (plus one internal Invoices fix).
|
||||
|
||||
**MED — Unit-price label.** Offers "Cena/ks" (`:336`, `:1625`) → "Jedn. cena". Effort: **S**.
|
||||
**MED — Unit-price + quantity header alignment/width.** Offers default-left, qty `5rem` → `align="center"`, qty `5.5rem`. Also InvoiceDetail's paid read-only header uses `align="right"` (`:1429`) — switch to `center`. Effort: **S**.
|
||||
**MED — Grand-total label.** Invoices "Celkem k úhradě:" is domain-appropriate (payment context) — **keep, intentional.**
|
||||
**MED — Editable VAT-column header.** Unify the two editable forms on "DPH"; align Invoices' paid-view header. Effort: **S**.
|
||||
**LOW — Remove-button cell width.** Offers `3rem` → `2.5rem`. Effort: **S**.
|
||||
|
||||
_Already fine: description/detail multiline fields (rows=2, vertical resize), unit-price column width `8rem`, per-row monospace total, mobile card metrics, dnd-kit drag config, totals area layout, per-rate VAT breakdown._
|
||||
|
||||
## 4. Suggested Fix Order
|
||||
|
||||
**Batch 1 — Mechanical quick wins (low judgment, low risk).**
|
||||
|
||||
1. Line-item unifications in `OfferDetail.tsx`: "Cena/ks"→"Jedn. cena", qty width `5rem`→`5.5rem`, `align="center"` on qty/unit-price headers, remove-button cell `3rem`→`2.5rem`. Plus in-Invoices fixes (paid-view unit-price `right`→`center`; "%DPH"→"DPH").
|
||||
2. List: "Částka"→"Celkem" (ReceivedInvoices); center Offers tabs.
|
||||
3. Detail: Offers save button → spinner+text; standardize status-transition button colors (Order rule); back-button tab params (Invoices→`?tab=issued`).
|
||||
4. Forms: `apply_vat` raw `<input>` → kit `CheckboxField` in Invoice/Order; Orders currency Select → company settings; Orders `issued_by` read-only+auto-filled.
|
||||
|
||||
**Batch 2 — Small behavioral additions (per-file logic, light judgment).** 5. Add `rowSx` state tinting to the three Orders modules (+ optionally ReceivedInvoices). 6. Add OrdersReceived status-filter Select; widen IssuedOrders/OrdersReceived `sortKey` coverage. 7. Adopt `hasLoadedOnce` skeleton-suppression in Offers/Invoices/IssuedOrders/OrdersReceived. 8. Search-aware empty states (Offers pattern) in Invoices/IssuedOrders/OrdersReceived.
|
||||
|
||||
**Batch 3 — Safety/feature bug fixes (need judgment, preserve data logic).** 9. Delete-button guards: add `!readOnly`/status checks to Offers + Invoices; add a guarded delete to IssuedOrderDetail for parity. 10. Verify create-success invalidation scope for Invoice/Order; widen only if they touch foreign domains.
|
||||
|
||||
**Batch 4 — Shared-component & layout refactors (largest, most judgment).** 11. Replace the three customer/supplier pickers with one `Autocomplete freeSolo` (consider a shared `CustomerPicker` kit component). 12. Move Invoices notes to RichEditor + wire DOMPurify/`cleanQuillHtml` on PDF + render paths. 13. Unify VAT rate/toggle layout on Offers' dual-field pattern. 14. Add KPI StatCard grids to IssuedOrders/OrdersReceived (decide metrics; consider an Offers variant). 15. Refactor InvoiceDetail's separate paid read-only branch into the single-form-`readOnly`-prop model; hoist guards to top-level. 16. Reduce Offers row actions to 4 (move Duplicate/Invalidate to overflow menu/detail).
|
||||
|
||||
## 5. Already Consistent — Do Not Touch
|
||||
|
||||
- **Shell & layout:** `PageEnter`, `PageHeader`, `Card` sectioning, `FilterBar`, header layout + `headerActionsSx`, StatusChip-in-header, mobile breakpoints.
|
||||
- **Lists:** DataTable rendering, Pagination placement, StatusChip semantic colors, search-placeholder copy, draft-banner presence (by design).
|
||||
- **Forms:** `<Field>` wrapper + error display, DateField, totals footer, basic-info grid, delivery/payment terms being Orders-only.
|
||||
- **Line items:** description/detail multiline (rows=2, vertical resize), unit-price width `8rem`, per-row monospace total, mobile card metrics, dnd-kit drag, totals layout, per-rate VAT breakdown.
|
||||
- **Cross-cutting:** success/error handling, `formatCurrency`, permission guards.
|
||||
|
||||
**Intentional differences to preserve:** Invoices' "Celkem k úhradě:" grand-total wording (payment context) and the supplier-vs-customer ("Dodavatel"/"Zákazník") terminology.
|
||||
|
||||
---
|
||||
|
||||
# Part 2 — Status/State Models + Draft Persistence (follow-up audit)
|
||||
|
||||
> Generated 2026-06-09 by a second multi-agent audit (status models + draft persistence).
|
||||
|
||||
## Summary
|
||||
|
||||
The five document types share the same conceptual lifecycle (draft → active → terminal/paid) but agree on almost nothing in implementation. State is stored two ways (raw `String(30)` vs Prisma enum), keyed in two languages (Czech for customer-orders, English for everything else), enforced with three transition styles, and rendered through **six separately-maintained label/color maps that have already drifted** (the same `issued` status is amber in the list, blue in the detail). Draft persistence works end-to-end only for Offers, is **half-wired for Issued Invoices (a banner promises a draft that is never written)**, and is absent everywhere else. The theme is **copy-paste divergence with no shared source of truth**.
|
||||
|
||||
## State-model comparison
|
||||
|
||||
| Document | Storage | Key language | #States | Transitions | Auto-transitions | Edit-lock | Color consistency |
|
||||
| ------------------------------------ | -------------------------- | ------------------------------------------------------------ | ------- | -------------------------------- | ---------------------------------------- | -------------------------------------- | ------------------------------------------------------ |
|
||||
| Offer (quotations) | `String(30)` def `active` | mixed (`active`/`ordered`/`invalidated`) | 3 | none (manual; `invalidateOffer`) | none | locked only when `invalidated` | **no label/color map** (tabs only) |
|
||||
| Customer Order (orders) | `String(30)` def `prijata` | **Czech** (`prijata`/`v_realizaci`/`dokoncena`/`stornovana`) | 4 | `VALID_TRANSITIONS` | → project status sync | items lock in `dokoncena`/`stornovana` | consistent list↔detail |
|
||||
| Issued Order (issued_orders) | **enum** def `draft` | English (`draft`/`sent`/`confirmed`/`completed`/`cancelled`) | 5 | `VALID_TRANSITIONS` | none | full lock outside `draft`/`sent` | consistent |
|
||||
| Issued Invoice (invoices) | `String(30)` def `issued` | English (`issued`/`overdue`/`paid`) | 3 | `VALID_TRANSITIONS` | `markOverdueInvoices()` + auto paid_date | full lock in `paid` | **DRIFTED**: `issued`=warning in list, =info in detail |
|
||||
| Received Invoice (received_invoices) | **enum** def `unpaid` | English (`unpaid`/`paid`) | 2 | implicit (no revert) | auto paid_date, month/year | locks in `paid` | consistent (list only) |
|
||||
|
||||
## Intentional (KEEP) vs Accidental (FIX)
|
||||
|
||||
**Domain-justified — keep:** different state counts per document (orders need 5, received invoices need 2); Offers' transition-free lifecycle (document it); the customer-order→project sync and invoice auto-overdue business rules; stricter edit-lock on terminal states.
|
||||
|
||||
**Accidental — fix:**
|
||||
|
||||
- Czech vs English status keys (customer-orders are the lone Czech holdout — legacy-PHP carryover).
|
||||
- String vs enum storage (orders/quotations/invoices loose `String`; issued_orders/received_invoices typed enums).
|
||||
- Divergent semantic color for the same status (`issued` = warning vs info).
|
||||
- Six duplicated, drifting `STATUS_LABELS`/`STATUS_COLORS` maps; Offers has none.
|
||||
- Duplicated draft-key constants (`boha_offer_draft` defined in two files).
|
||||
- **Half-wired issued-invoice draft** (banner reads a key that's never written; `clearDraft` is dead code) — a live user-facing bug.
|
||||
- Cross-record draft leakage (`boha_offer_draft` not record-scoped).
|
||||
- Auto-transition logic placed in three different homes (service vs scheduled fn vs route handler).
|
||||
- Arbitrary draft-banner visibility heuristics.
|
||||
|
||||
## Recommendations
|
||||
|
||||
- **Status keys → English** (4/5 already English; matches CLAUDE.md identifier convention). Rename customer-order DB values (`prijata`→`received`, `v_realizaci`→`in_progress`, `dokoncena`→`completed`, `stornovana`→`cancelled`) + the `ORDER_TO_PROJECT_STATUS` keys. **Needs DB migration + backfill.**
|
||||
- **Storage → Prisma enums** for invoices/orders/quotations (match the other two). **Migration**, mechanical; do in the same migration as the rename.
|
||||
- **One shared `src/admin/lib/documentStatus.ts`** exporting per-document `STATUS_LABELS` + `STATUS_COLORS` (Czech labels, MUI colors), consumed everywhere — kills all six duplicates, fixes the `issued` color drift in one place (→ `warning`), gives Offers a chip. Fold draft-key constants into a shared `DRAFT_KEYS`. **Frontend-only.**
|
||||
- **Drafts → uniform or removed; never half-wired.** Recommended: a reusable `useDocumentDraft(key, { recordId })` hook (record-scoped, debounced autosave, restore-on-init, unified banner) applied to all create/edit forms; finish the stubbed invoice banner. Acceptable cheaper alternative: delete drafts entirely. Either way, fix the half-wired invoice banner. **Frontend-only.**
|
||||
- **Transition placement → one home** (service layer, never the route). **Backend-only, no migration.**
|
||||
|
||||
## Effort + risk
|
||||
|
||||
- **Frontend-only (cheap, safe, do now):** shared `documentStatus.ts` (+ fix `issued` color drift, + Offers chip), fix the half-wired invoice draft, record-scoped `useDocumentDraft` hook + leakage guard + banner unification.
|
||||
- **Backend, no migration (low risk, opportunistic):** centralize auto-transition logic into services; document Offers' transition-free lifecycle.
|
||||
- **Backend + DB migration (higher risk, deferrable, do as ONE planned tested change):** Czech→English customer-order status rename (DB values + transition map + project-sync keys + frontend maps in lockstep, with `UPDATE` backfill); String→enum conversion for invoices/orders/quotations. **Not correctness blockers** (the String columns work today) — schedule deliberately.
|
||||
@@ -1,385 +0,0 @@
|
||||
# Deployment Guide — boha-app-ts (Ubuntu Server)
|
||||
|
||||
Migration from PHP boha-app to TypeScript boha-app-ts on the same Ubuntu server.
|
||||
Both apps share the same MySQL database. The PHP app stays running during migration.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Ubuntu server with the PHP boha-app already running
|
||||
- nginx with SSL (Let's Encrypt) already configured
|
||||
- MySQL database already running with production data
|
||||
- NAS storage mounted (e.g., `/mnt/nas/02_PROJEKTY`)
|
||||
- SSH access to the server
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Prepare on Dev Machine (Windows)
|
||||
|
||||
### 1.1 Create Prisma migration baseline
|
||||
|
||||
```bash
|
||||
cd D:\cortex\boha-app-ts
|
||||
mkdir -p prisma/migrations/0_init
|
||||
npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
|
||||
npx prisma migrate resolve --applied 0_init
|
||||
git add prisma/migrations/
|
||||
git commit -m "chore: create Prisma migration baseline"
|
||||
```
|
||||
|
||||
### 1.2 Build the application
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
This creates:
|
||||
- `dist/` — compiled server (Node.js)
|
||||
- `dist-client/` — compiled frontend (static files)
|
||||
|
||||
### 1.3 Generate new production secrets
|
||||
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
# Save this as JWT_SECRET
|
||||
|
||||
openssl rand -hex 32
|
||||
# Save this as TOTP_ENCRYPTION_KEY (only if you want a new key)
|
||||
```
|
||||
|
||||
### 1.4 Test the production build locally (optional)
|
||||
|
||||
```bash
|
||||
APP_ENV=production JWT_SECRET=<your-dev-key> TOTP_ENCRYPTION_KEY=<your-dev-key> DATABASE_URL=<your-dev-db> node dist/server.js
|
||||
```
|
||||
|
||||
Verify it starts and responds at `http://localhost:3001/api/health`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Prepare Ubuntu Server
|
||||
|
||||
### 2.1 Install Node.js 22
|
||||
|
||||
```bash
|
||||
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
|
||||
sudo apt-get install -y nodejs
|
||||
node -v
|
||||
npm -v
|
||||
```
|
||||
|
||||
### 2.2 Install PM2
|
||||
|
||||
```bash
|
||||
sudo npm install -g pm2
|
||||
```
|
||||
|
||||
### 2.3 Create application directory
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /var/www/boha-app-ts
|
||||
sudo chown $USER:$USER /var/www/boha-app-ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Transfer Files to Server
|
||||
|
||||
### 3.1 Copy built files
|
||||
|
||||
From your Windows machine (Git Bash or PowerShell with SCP):
|
||||
|
||||
```bash
|
||||
scp -r dist/ dist-client/ package.json package-lock.json prisma/ scripts/ .env.example user@server:/var/www/boha-app-ts/
|
||||
```
|
||||
|
||||
Or use rsync if available:
|
||||
|
||||
```bash
|
||||
rsync -avz --exclude node_modules --exclude .env dist/ dist-client/ package.json package-lock.json prisma/ scripts/ .env.example user@server:/var/www/boha-app-ts/
|
||||
```
|
||||
|
||||
### 3.2 Install production dependencies on server
|
||||
|
||||
```bash
|
||||
ssh user@server
|
||||
cd /var/www/boha-app-ts
|
||||
npm install --production
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Configure Environment
|
||||
|
||||
### 4.1 Create production .env
|
||||
|
||||
```bash
|
||||
cd /var/www/boha-app-ts
|
||||
cp .env.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
Fill in:
|
||||
|
||||
```env
|
||||
# Database — same as the PHP app
|
||||
DATABASE_URL=mysql://user:password@localhost:3306/your_db_name
|
||||
|
||||
# Server
|
||||
PORT=3001
|
||||
HOST=127.0.0.1
|
||||
APP_ENV=production
|
||||
|
||||
# Auth — use the NEW secrets generated in step 1.3
|
||||
JWT_SECRET=<paste-new-jwt-secret>
|
||||
ACCESS_TOKEN_EXPIRY=900
|
||||
REFRESH_TOKEN_SESSION_EXPIRY=3600
|
||||
REFRESH_TOKEN_REMEMBER_EXPIRY=2592000
|
||||
|
||||
# TOTP — use SAME key as PHP app (unless you want to re-encrypt)
|
||||
TOTP_ENCRYPTION_KEY=<same-key-as-php-app>
|
||||
|
||||
# NAS — Linux mount point
|
||||
NAS_PATH=/mnt/nas/02_PROJEKTY
|
||||
MAX_UPLOAD_SIZE=52428800
|
||||
|
||||
# Email
|
||||
CONTACT_EMAIL_TO=manager@boha-automation.cz
|
||||
CONTACT_EMAIL_FROM=web@boha-automation.cz
|
||||
SMTP_FROM=noreply@boha-automation.cz
|
||||
|
||||
# CORS — your production domain(s)
|
||||
CORS_ORIGINS=https://app.boha-automation.cz,https://www.boha-automation.cz
|
||||
```
|
||||
|
||||
**Important decisions:**
|
||||
|
||||
| Setting | Recommendation |
|
||||
|---------|---------------|
|
||||
| `JWT_SECRET` | **New key.** All PHP sessions will be invalid — users re-login. This is expected. |
|
||||
| `TOTP_ENCRYPTION_KEY` | **Same key as PHP app.** Avoids re-encrypting all TOTP secrets. |
|
||||
| `DATABASE_URL` | **Same database as PHP app.** Both apps share it. |
|
||||
| `NAS_PATH` | **Linux mount point** instead of Windows drive letter. |
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Database Setup
|
||||
|
||||
### 5.1 Mark Prisma baseline as applied
|
||||
|
||||
```bash
|
||||
cd /var/www/boha-app-ts
|
||||
npx prisma migrate resolve --applied 0_init
|
||||
```
|
||||
|
||||
This tells Prisma the database already has all tables. No SQL is executed.
|
||||
|
||||
### 5.2 Verify database connection
|
||||
|
||||
```bash
|
||||
npx prisma db pull --print | head -20
|
||||
```
|
||||
|
||||
Should show your existing tables.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: TOTP Key Rotation (only if using new encryption key)
|
||||
|
||||
**Skip this section if you're using the same `TOTP_ENCRYPTION_KEY` as the PHP app.**
|
||||
|
||||
If you generated a new encryption key:
|
||||
|
||||
```bash
|
||||
cd /var/www/boha-app-ts
|
||||
|
||||
# Dry run — verify all secrets can be decrypted and re-encrypted
|
||||
npx tsx scripts/rotate-totp-key.ts <old-key> <new-key> --dry-run
|
||||
|
||||
# If all [OK], run for real
|
||||
npx tsx scripts/rotate-totp-key.ts <old-key> <new-key>
|
||||
```
|
||||
|
||||
After this, the PHP app's TOTP verification will break (secrets are now encrypted with the new key). Only do this when you're ready to cut over.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: Start Application with PM2
|
||||
|
||||
### 7.1 Create PM2 config
|
||||
|
||||
```bash
|
||||
cd /var/www/boha-app-ts
|
||||
cat > ecosystem.config.js << 'EOF'
|
||||
module.exports = {
|
||||
apps: [{
|
||||
name: 'boha-app-ts',
|
||||
script: 'dist/server.js',
|
||||
cwd: '/var/www/boha-app-ts',
|
||||
instances: 1,
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
},
|
||||
}]
|
||||
};
|
||||
EOF
|
||||
```
|
||||
|
||||
### 7.2 Start the app
|
||||
|
||||
```bash
|
||||
pm2 start ecosystem.config.js
|
||||
pm2 save
|
||||
pm2 startup
|
||||
# Follow the printed command to enable auto-start on boot
|
||||
```
|
||||
|
||||
### 7.3 Verify
|
||||
|
||||
```bash
|
||||
pm2 status
|
||||
pm2 logs boha-app-ts --lines 20
|
||||
curl http://localhost:3001/api/health
|
||||
```
|
||||
|
||||
Expected: `{"status":"ok","timestamp":"..."}`
|
||||
|
||||
---
|
||||
|
||||
## Phase 8: Nginx Configuration
|
||||
|
||||
### 8.1 Create nginx config
|
||||
|
||||
```bash
|
||||
sudo nano /etc/nginx/sites-available/boha-app-ts
|
||||
```
|
||||
|
||||
Paste:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name app.boha-automation.cz;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/app.boha-automation.cz/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/app.boha-automation.cz/privkey.pem;
|
||||
|
||||
client_max_body_size 55M;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name app.boha-automation.cz;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
```
|
||||
|
||||
Adjust `server_name` and SSL paths to match your setup.
|
||||
|
||||
### 8.2 Enable and reload
|
||||
|
||||
```bash
|
||||
sudo ln -s /etc/nginx/sites-available/boha-app-ts /etc/nginx/sites-enabled/
|
||||
sudo nginx -t
|
||||
sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 9: Testing
|
||||
|
||||
### 9.1 Verify in browser
|
||||
|
||||
Open `https://app.boha-automation.cz` and test:
|
||||
|
||||
- [ ] Login page loads
|
||||
- [ ] Login works (users will need to re-login due to new JWT_SECRET)
|
||||
- [ ] TOTP verification works (if using same encryption key)
|
||||
- [ ] Dashboard loads with data
|
||||
- [ ] Offers — list, create, edit, PDF export
|
||||
- [ ] Orders — list, create from offer, status transitions
|
||||
- [ ] Invoices — list, create, PDF with QR code
|
||||
- [ ] Projects — list, create, file manager (upload/download)
|
||||
- [ ] Attendance — clock in/out, admin view, print
|
||||
- [ ] Trips — list, history
|
||||
- [ ] Settings — company settings, users, roles
|
||||
|
||||
### 9.2 Check logs for errors
|
||||
|
||||
```bash
|
||||
pm2 logs boha-app-ts --lines 50
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 10: Cutover Strategy
|
||||
|
||||
Both apps run simultaneously on the same database. Recommended approach:
|
||||
|
||||
1. **Week 1:** Run both apps. Use the TS app for daily work. Fall back to PHP if issues arise.
|
||||
2. **Week 2:** If stable, redirect the main domain to the TS app.
|
||||
3. **Week 3:** Stop the PHP app.
|
||||
|
||||
To redirect the PHP domain to the TS app, update the nginx config for the PHP domain to proxy to port 3001 instead.
|
||||
|
||||
---
|
||||
|
||||
## Future Updates
|
||||
|
||||
When you push code changes:
|
||||
|
||||
```bash
|
||||
# On dev machine
|
||||
npm run build
|
||||
git push
|
||||
|
||||
# On server
|
||||
cd /var/www/boha-app-ts
|
||||
git pull
|
||||
npm install --production
|
||||
npx prisma generate
|
||||
npx prisma migrate deploy # runs any new migrations
|
||||
pm2 restart boha-app-ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| `EADDRINUSE: port 3001` | `pm2 stop boha-app-ts` then `pm2 start` |
|
||||
| Prisma connection error | Check `DATABASE_URL` in `.env` |
|
||||
| TOTP verification fails | Verify `TOTP_ENCRYPTION_KEY` matches the key used to encrypt secrets |
|
||||
| NAS files not accessible | Check mount: `ls /mnt/nas/02_PROJEKTY`, verify permissions |
|
||||
| 502 Bad Gateway | App not running: `pm2 status`, check logs: `pm2 logs` |
|
||||
| CSS/JS not loading | Verify `dist-client/` was copied, check `APP_ENV=production` |
|
||||
| CORS errors | Check `CORS_ORIGINS` in `.env` matches your domain exactly |
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `pm2 start ecosystem.config.js` | Start the app |
|
||||
| `pm2 restart boha-app-ts` | Restart after update |
|
||||
| `pm2 stop boha-app-ts` | Stop the app |
|
||||
| `pm2 logs boha-app-ts` | View logs |
|
||||
| `pm2 monit` | Live monitoring |
|
||||
| `npx prisma migrate deploy` | Apply database migrations |
|
||||
| `npx prisma studio` | Database GUI (dev only) |
|
||||
107
docs/release.md
Normal file
107
docs/release.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# Release & deployment runbook — boha-app-ts
|
||||
|
||||
Referenced from CLAUDE.md. **Never deploy to production or restart services
|
||||
without explicit user confirmation.**
|
||||
|
||||
## Standard release
|
||||
|
||||
1. Run the full gates locally: `npx vitest run` (all green), `npx tsc -b --noEmit`,
|
||||
`npm run lint` (0 errors).
|
||||
2. Bump version: `npm version X.Y.Z --no-git-tag-version` (the user picks the number).
|
||||
3. `npm run build`
|
||||
4. Commit and tag: `git tag -a vX.Y.Z`
|
||||
5. Push to Gitea: `git push origin master && git push origin vX.Y.Z`
|
||||
6. Create tarball:
|
||||
|
||||
```bash
|
||||
tar -czf app-ts-X.Y.Z.tar.gz dist dist-client prisma prisma.config.ts package.json package-lock.json scripts
|
||||
```
|
||||
|
||||
⚠️ `prisma.config.ts` is REQUIRED — Prisma 7 keeps the datasource URL there;
|
||||
without it, `prisma generate`/`migrate deploy` on prod have no datasource.
|
||||
|
||||
7. Deploy via SSH to production (`boha_admin@192.168.50.100`, path `/var/www/app-ts`):
|
||||
|
||||
```bash
|
||||
scp app-ts-X.Y.Z.tar.gz boha_admin@192.168.50.100:/tmp/
|
||||
ssh boha_admin@192.168.50.100
|
||||
cd /var/www/app-ts
|
||||
rm -rf dist dist-client prisma prisma.config.ts scripts package.json package-lock.json
|
||||
tar -xzf /tmp/app-ts-X.Y.Z.tar.gz
|
||||
npm install --omit=dev
|
||||
npx prisma generate # MANDATORY — see below
|
||||
npx prisma migrate deploy
|
||||
pm2 restart app-ts --update-env
|
||||
```
|
||||
|
||||
**`npx prisma generate` is mandatory.** `npm install` skips client
|
||||
regeneration when dependencies didn't change, leaving a stale client that
|
||||
still selects dropped/renamed columns → P2022 500s in prod (this caused
|
||||
the v2.4.0 incident: every issued-orders query failed until generate ran).
|
||||
|
||||
8. Verify: `pm2 list` (status online, correct version, restart counter not
|
||||
climbing), `npx prisma migrate status` ("up to date"),
|
||||
`curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:3001/` → 200,
|
||||
and grep logs for errors from the CURRENT pid only (the out log keeps old
|
||||
errors from prior pids).
|
||||
9. Clean up tarballs locally and in `/tmp/` on the server.
|
||||
|
||||
**nginx is NOT part of a normal release.** nginx is only a reverse proxy in
|
||||
front of the pm2 app (`proxy_pass` → `127.0.0.1:3001`); a code release changes
|
||||
app code, which `pm2 restart app-ts` picks up — nginx has nothing new to read.
|
||||
Do **not** run `sudo nginx -t && sudo systemctl reload nginx` every deploy. Run
|
||||
it ONLY when you actually edit nginx config (`/etc/nginx/…` — `server_name`,
|
||||
ports, `proxy_pass` upstream, TLS cert paths, locations/redirects/headers,
|
||||
`client_max_body_size`, rate limits, etc.). When you do change it, always
|
||||
`nginx -t` first (validates syntax, changes nothing) THEN `systemctl reload
|
||||
nginx` (graceful re-read, keeps active connections; a bad config on reload is
|
||||
rejected and the old one keeps running).
|
||||
|
||||
Risky releases (framework jumps, FK/constraint-altering migrations) get a
|
||||
read-only pre-flight first: `prisma migrate status` on prod, verify FK
|
||||
constraint names the migration DROPs, check no data violates new
|
||||
UNIQUE/RESTRICT constraints — and confirm with the user before the
|
||||
irreversible steps. The prod DB is backed up by a cron job (no manual
|
||||
mysqldump needed).
|
||||
|
||||
## Hotfixing a migration added after the tarball was built
|
||||
|
||||
A migration folder created after the release tarball shipped is not on prod,
|
||||
so `prisma migrate deploy` reports "No pending migrations". Ship just the
|
||||
migration folder (still tracked in git — this is NOT raw SQL on prod):
|
||||
|
||||
```bash
|
||||
# Local
|
||||
cd prisma/migrations
|
||||
tar -czf /tmp/<name>_migration.tar.gz <timestamp>_<name>/
|
||||
scp /tmp/<name>_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
|
||||
tar -xzf /tmp/<name>_migration.tar.gz
|
||||
cd /var/www/app-ts
|
||||
npx prisma migrate deploy
|
||||
pm2 restart app-ts --update-env
|
||||
```
|
||||
|
||||
## Drift check / preview before deploy
|
||||
|
||||
```bash
|
||||
# Preview what SQL would bring the dev DB (per prisma.config.ts) to the local schema
|
||||
npx prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script
|
||||
```
|
||||
|
||||
Empty output = no diff. (Prisma 7 removed `--from-url`; diffs against another
|
||||
DB need its URL in a config/env override.) If drift includes DROPs,
|
||||
investigate before touching production.
|
||||
|
||||
## Baselining a database that has no migrations
|
||||
|
||||
If a database was synced without migration history (no `_prisma_migrations`
|
||||
table): create the initial migration locally, copy `prisma/migrations` to the
|
||||
server, then mark it applied without running SQL:
|
||||
|
||||
```bash
|
||||
npx prisma migrate resolve --applied <migration_name>
|
||||
```
|
||||
3874
docs/superpowers/plans/2026-05-29-warehouse-module.md
Normal file
3874
docs/superpowers/plans/2026-05-29-warehouse-module.md
Normal file
File diff suppressed because it is too large
Load Diff
124
docs/superpowers/plans/2026-06-03-deferred-high-issues.md
Normal file
124
docs/superpowers/plans/2026-06-03-deferred-high-issues.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# Deferred HIGH issues — performance & UX sprint
|
||||
|
||||
**Created:** 2026-06-03
|
||||
**Source audit:** Parallel 5-agent production risk audit (2026-06-03)
|
||||
**Context:** All 8 CRITICAL and 3 of 8 HIGH issues were fixed in the same session.
|
||||
The 5 items below were intentionally deferred — they are not data-integrity or
|
||||
auth risks, but they are real production pain that should be addressed in a
|
||||
dedicated performance / UX sprint before the user base notices.
|
||||
|
||||
---
|
||||
|
||||
## #9 — N+1 queries in warehouse list/detail/report
|
||||
|
||||
**Files:**
|
||||
|
||||
- `src/services/warehouse.service.ts:184-199` (getBelowMinimumItems)
|
||||
- `src/services/warehouse.service.ts:629-646` (somewhere in items list)
|
||||
- `src/services/warehouse.service.ts:681-683`
|
||||
- `src/services/warehouse.service.ts:2182-2203` (report)
|
||||
|
||||
**Pattern:** `items.map(async (i) => { const stock = await getStock(i.id); const available = await getAvailable(i.id); const value = await getValue(i.id); })` — fires N+1 round-trips per item. For a list of 50 items, that's 150 sequential queries.
|
||||
|
||||
**Production impact:** Slow page loads (1-3s on 50 items, scales linearly). Users already complain about the items page; this is the root cause for the warehouse report being the slowest page in the app.
|
||||
|
||||
**Fix sketch:**
|
||||
|
||||
- Replace the `for` loop with a single grouped query: `prisma.sklad_batches.groupBy({ by: ['item_id'], _sum: { quantity: true }, where: { item_id: { in: itemIds } } })` for stocks, similar aggregates for reservations.
|
||||
- Map the grouped results back to items in JS. One query instead of N.
|
||||
- For the report view, do the same — group all batches and reservations by item_id in a single round-trip, then join with items in memory.
|
||||
- Estimated effort: M (4-6 hours including testing).
|
||||
|
||||
---
|
||||
|
||||
## #10 — Missing FK indexes on hot warehouse tables
|
||||
|
||||
**File:** `prisma/schema.prisma` (no `@@index` directives on the new warehouse tables)
|
||||
|
||||
**Missing indexes (verify against `prisma/schema.prisma` and add to a new migration):**
|
||||
|
||||
- `sklad_receipt_lines.item_id` — every `confirmReceipt` reads/writes this
|
||||
- `sklad_issue_lines.batch_id` — every `confirmIssue` reads/writes this
|
||||
- `sklad_issue_lines.item_id`
|
||||
- `sklad_reservations.project_id` — reservation list per project
|
||||
- `sklad_reservations.item_id`
|
||||
- `sklad_item_locations.item_id`
|
||||
- `sklad_item_locations.location_id`
|
||||
- `sklad_batches.receipt_line_id` (if nullable FK)
|
||||
- `sklad_inventory_lines.item_id`
|
||||
- `sklad_inventory_lines.session_id`
|
||||
|
||||
**Production impact:** MySQL currently does table scans for these joins. With even 10k batch rows, the receipts/issues/reservations pages will start to crawl. On production data (likely already 50k+ batches), this is a real performance cliff.
|
||||
|
||||
**Fix sketch:**
|
||||
|
||||
- Add `@@index([item_id])`, `@@index([batch_id])` etc. to each model in `prisma/schema.prisma`.
|
||||
- Run `npx prisma migrate dev --name warehouse_fk_indexes` (after asking user to stop dev server per CLAUDE.md).
|
||||
- Run `npx prisma generate`.
|
||||
- Verify with `EXPLAIN` on the slow queries after deploy.
|
||||
- Estimated effort: S (1-2 hours).
|
||||
|
||||
**CLAUDE.md note:** Before running `prisma migrate dev`, the user must stop the dev server.
|
||||
|
||||
---
|
||||
|
||||
## #13 — Pagination does not auto-adjust after delete
|
||||
|
||||
**Files:** All list pages (Invoices, Offers, Projects, Orders, WarehouseXxx)
|
||||
|
||||
**Pattern:** User is on page 5 (e.g. 10 items per page, 47 total, pages 1-5). They delete the last item on page 5. Total becomes 46, but the page param is still 5. The list endpoint returns 0 results, the user sees an empty table, and the "next" button is disabled but there's no automatic jump back to page 4.
|
||||
|
||||
**Production impact:** Confusing UX. Users have to manually click "previous" or reset filters. Doesn't cause data loss but is a small papercut that erodes trust.
|
||||
|
||||
**Fix sketch:**
|
||||
|
||||
- In each list page's `useQuery` error/empty handler, detect `pagination.total === 0 && page > 1` and call `setPage(page - 1)`.
|
||||
- Or more cleanly: have the API include `pagination.total_pages` and the frontend clamp `page` to `min(page, total_pages)` after each refetch.
|
||||
- Estimated effort: S (2-3 hours; touches ~10-12 pages).
|
||||
|
||||
---
|
||||
|
||||
## #14 — Offer lock lifecycle has multiple silent failures
|
||||
|
||||
**File:** `src/admin/pages/OfferDetail.tsx:472-516`
|
||||
|
||||
**Pattern:** Lock acquire, heartbeat (interval), and unlock all use `.catch(() => {})`. If any of them silently fails, the user thinks they have the lock but actually don't — or worse, the lock is held by a tab that's already closed because the unload handler also swallowed the error.
|
||||
|
||||
**Production impact:** Two users editing the same offer can both see "You have the lock" and clobber each other's changes. Data loss in a real, low-probability but high-impact scenario.
|
||||
|
||||
**Fix sketch:**
|
||||
|
||||
- Replace `.catch(() => {})` with `.catch((err) => console.error("Offer lock error:", err))` at minimum.
|
||||
- Better: surface lock acquisition failures via a toast (`alert.error("Nepodařilo se získat zámek, stránka bude pouze pro čtení.")`).
|
||||
- For the unlock on unmount: best-effort `navigator.sendBeacon` or a synchronous fallback so the lock is released even if the page is closing.
|
||||
- Estimated effort: S (1-2 hours).
|
||||
|
||||
---
|
||||
|
||||
## #11 (audit item, not a real bug) — TOTP replay counter rewind
|
||||
|
||||
**File investigated:** `src/utils/totp.ts:5-30`, `src/routes/admin/auth.ts:165-184`
|
||||
|
||||
**Status:** False positive. The audit suggested `verifyResult.counter` could be lower than the actual step used. After reading the implementation:
|
||||
|
||||
```ts
|
||||
const delta = totp.validate({ token: code, window: 1 });
|
||||
// ...
|
||||
const counterDelta = Math.min(delta, 0); // -1 or 0, never +1
|
||||
const counter = currentCounter + counterDelta;
|
||||
```
|
||||
|
||||
`Math.min(delta, 0)` clamps to ≤ 0, so `counter` is always the **current** step or **one step in the past** — never a future step. The `counter <= lastCounter` check in the route is correct and complete. No fix needed.
|
||||
|
||||
If anyone revisits this in the future, this analysis is the basis for closing the ticket.
|
||||
|
||||
---
|
||||
|
||||
## Suggested order for the next sprint
|
||||
|
||||
1. **#10 (indexes)** — cheap, high impact, addresses a growing data cliff. Do first.
|
||||
2. **#9 (N+1)** — bigger effort but the same root cause family. Tackle after indexes.
|
||||
3. **#14 (offer lock)** — small but prevents data loss; fits in a single PR.
|
||||
4. **#13 (pagination)** — UX polish; do last, batch with other UX cleanup.
|
||||
|
||||
Estimated total: 1-2 days of focused work.
|
||||
3597
docs/superpowers/plans/2026-06-05-plan-praci.md
Normal file
3597
docs/superpowers/plans/2026-06-05-plan-praci.md
Normal file
File diff suppressed because it is too large
Load Diff
1154
docs/superpowers/plans/2026-06-06-manual-project-order-creation.md
Normal file
1154
docs/superpowers/plans/2026-06-06-manual-project-order-creation.md
Normal file
File diff suppressed because it is too large
Load Diff
1406
docs/superpowers/plans/2026-06-06-plan-categories-management.md
Normal file
1406
docs/superpowers/plans/2026-06-06-plan-categories-management.md
Normal file
File diff suppressed because it is too large
Load Diff
1274
docs/superpowers/plans/2026-06-08-ai-assistant-phase1.md
Normal file
1274
docs/superpowers/plans/2026-06-08-ai-assistant-phase1.md
Normal file
File diff suppressed because it is too large
Load Diff
792
docs/superpowers/plans/2026-06-08-odin-conversations.md
Normal file
792
docs/superpowers/plans/2026-06-08-odin-conversations.md
Normal file
@@ -0,0 +1,792 @@
|
||||
# Odin Multi-Conversation Chat — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Turn the single-thread Odin assistant into a multi-conversation chat (top-tabs, rename/delete, auto-title) on the `/odin` page.
|
||||
|
||||
**Architecture:** New `ai_conversations` table; `ai_chat_messages` gains `conversation_id` (FK, cascade). Conversation-scoped service + routes replace the single `/history` endpoints. A new `OdinChat` component (+ focused sub-components) replaces `DashAssistant`, keeping all proven chat/extract/save logic but scoped to the active conversation.
|
||||
|
||||
**Tech Stack:** Fastify 5, Prisma 6 (MySQL), Zod 4, React 18 + MUI v7, TanStack Query, Vitest (real DB).
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-06-08-odin-conversations-design.md`.
|
||||
|
||||
---
|
||||
|
||||
## File map
|
||||
|
||||
| File | Responsibility |
|
||||
| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
|
||||
| `prisma/schema.prisma` | + `ai_conversations`; `ai_chat_messages.conversation_id` + relation + index swap |
|
||||
| `prisma/migrations/20260608140000_add_ai_conversations/migration.sql` | create table, add column, backfill, enforce FK |
|
||||
| `src/services/ai.service.ts` | replace `getChatHistory/appendChatMessages/clearChatHistory` with conversation-scoped fns |
|
||||
| `src/schemas/ai.schema.ts` | + `AiCreateConversationSchema`, `AiRenameConversationSchema`; keep `AiHistoryAppendSchema` (reused for append) |
|
||||
| `src/routes/admin/ai.ts` | replace `/history` routes with `/conversations*` routes |
|
||||
| `src/__tests__/ai.test.ts` | replace history tests with conversation tests |
|
||||
| `src/admin/lib/queries/ai.ts` | + conversation query options/types; remove `aiHistoryOptions` |
|
||||
| `src/admin/components/odin/OdinTabs.tsx` | conversation tabs + new + rename/delete menu |
|
||||
| `src/admin/components/odin/OdinThread.tsx` | message list + avatar + empty/busy states |
|
||||
| `src/admin/components/odin/InvoiceReviewCard.tsx` | editable extracted-invoice card |
|
||||
| `src/admin/components/odin/OdinComposer.tsx` | staged chips + attach + input + send |
|
||||
| `src/admin/components/odin/OdinChat.tsx` | orchestrator: queries, state, the ported logic |
|
||||
| `src/admin/pages/Odin.tsx` | render `OdinChat` (was `DashAssistant`) |
|
||||
| `src/admin/components/dashboard/DashAssistant.tsx` | **deleted** |
|
||||
|
||||
**Controller note (migration):** Tasks that touch the DB require the dev server stopped. After Task 1's files are written, the **controller** runs: ask user to stop dev server → `npx prisma generate` → `npx prisma migrate deploy` (applies to dev `app` DB) → resume. Backend tsc is red between Task 1 and Task 2 (data model changes before the service is updated) — that is expected; Task 2 restores green.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Data model + migration
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `prisma/schema.prisma`
|
||||
- Create: `prisma/migrations/20260608140000_add_ai_conversations/migration.sql`
|
||||
|
||||
- [ ] **Step 1: Edit `prisma/schema.prisma`** — replace the existing `ai_chat_messages` model and add `ai_conversations` above it:
|
||||
|
||||
```prisma
|
||||
model ai_conversations {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
title String @db.VarChar(255)
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime @default(now()) @updatedAt @db.Timestamp(0)
|
||||
messages ai_chat_messages[]
|
||||
|
||||
@@index([user_id, id], map: "idx_ai_conv_user")
|
||||
}
|
||||
|
||||
model ai_chat_messages {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
conversation_id Int
|
||||
role String @db.VarChar(20)
|
||||
content String @db.Text
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
conversation ai_conversations @relation(fields: [conversation_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([conversation_id, id], map: "idx_ai_chat_conv")
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write the migration SQL** at `prisma/migrations/20260608140000_add_ai_conversations/migration.sql`:
|
||||
|
||||
```sql
|
||||
-- Multi-conversation Odin: conversations table + conversation_id on messages.
|
||||
|
||||
CREATE TABLE `ai_conversations` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`user_id` INTEGER NOT NULL,
|
||||
`title` VARCHAR(255) NOT NULL,
|
||||
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
PRIMARY KEY (`id`),
|
||||
INDEX `idx_ai_conv_user` (`user_id`, `id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `ai_chat_messages`
|
||||
ADD COLUMN `conversation_id` INTEGER NULL AFTER `user_id`;
|
||||
|
||||
-- Backfill: one conversation per user who has messages ("keep as first conversation").
|
||||
INSERT INTO `ai_conversations` (`user_id`, `title`, `created_at`, `updated_at`)
|
||||
SELECT `user_id`, 'Konverzace', NOW(), NOW()
|
||||
FROM `ai_chat_messages`
|
||||
GROUP BY `user_id`;
|
||||
|
||||
UPDATE `ai_chat_messages` m
|
||||
JOIN `ai_conversations` c ON c.`user_id` = m.`user_id`
|
||||
SET m.`conversation_id` = c.`id`;
|
||||
|
||||
-- Enforce: drop old per-user index, NOT NULL, FK (cascade), per-conversation index.
|
||||
ALTER TABLE `ai_chat_messages`
|
||||
DROP INDEX `idx_ai_chat_user`,
|
||||
MODIFY `conversation_id` INTEGER NOT NULL,
|
||||
ADD CONSTRAINT `fk_ai_chat_conv` FOREIGN KEY (`conversation_id`)
|
||||
REFERENCES `ai_conversations`(`id`) ON DELETE CASCADE,
|
||||
ADD INDEX `idx_ai_chat_conv` (`conversation_id`, `id`);
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Controller applies the migration** (not the implementer):
|
||||
- Ask user to stop the dev server (Prisma engine DLL is locked on Windows otherwise).
|
||||
- `npx prisma generate` — expect "Generated Prisma Client".
|
||||
- `npx prisma migrate deploy` — expect "Applying migration `20260608140000_add_ai_conversations`" → "successfully applied".
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add prisma/schema.prisma prisma/migrations/20260608140000_add_ai_conversations
|
||||
git commit -m "feat(odin): ai_conversations table + conversation_id on messages"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Backend — conversation service, schemas, routes
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/services/ai.service.ts`
|
||||
- Modify: `src/schemas/ai.schema.ts`
|
||||
- Modify: `src/routes/admin/ai.ts`
|
||||
|
||||
- [ ] **Step 1: Replace the chat-history block in `ai.service.ts`.** Delete `getChatHistory`, `appendChatMessages`, `clearChatHistory` and the `HISTORY_LIMIT` const, and put this in their place (keep the `StoredChatMessage` interface):
|
||||
|
||||
```ts
|
||||
// ── Conversations (server-side, per user) ─────────────────────────────────
|
||||
export interface StoredChatMessage {
|
||||
role: string;
|
||||
content: string;
|
||||
created_at: Date;
|
||||
}
|
||||
export interface ConversationSummary {
|
||||
id: number;
|
||||
title: string;
|
||||
updated_at: Date;
|
||||
}
|
||||
|
||||
const DEFAULT_CONVERSATION_TITLE = "Nová konverzace";
|
||||
const MESSAGE_LIMIT = 200; // cap a single thread read
|
||||
|
||||
export async function listConversations(
|
||||
userId: number,
|
||||
): Promise<ConversationSummary[]> {
|
||||
return prisma.ai_conversations.findMany({
|
||||
where: { user_id: userId },
|
||||
orderBy: { id: "asc" }, // stable tab order
|
||||
select: { id: true, title: true, updated_at: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createConversation(
|
||||
userId: number,
|
||||
title?: string,
|
||||
): Promise<ConversationSummary> {
|
||||
return prisma.ai_conversations.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
title: title?.trim() || DEFAULT_CONVERSATION_TITLE,
|
||||
},
|
||||
select: { id: true, title: true, updated_at: true },
|
||||
});
|
||||
}
|
||||
|
||||
/** Ownership-checked fetch; null when not found / not owned. */
|
||||
async function ownConversation(userId: number, convId: number) {
|
||||
return prisma.ai_conversations.findFirst({
|
||||
where: { id: convId, user_id: userId },
|
||||
select: { id: true, title: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getConversationMessages(
|
||||
userId: number,
|
||||
convId: number,
|
||||
): Promise<{ data: StoredChatMessage[] } | { error: string; status: number }> {
|
||||
if (!(await ownConversation(userId, convId)))
|
||||
return { error: "Konverzace nenalezena", status: 404 };
|
||||
const rows = await prisma.ai_chat_messages.findMany({
|
||||
where: { conversation_id: convId },
|
||||
orderBy: { id: "desc" },
|
||||
take: MESSAGE_LIMIT,
|
||||
select: { role: true, content: true, created_at: true },
|
||||
});
|
||||
return { data: rows.reverse() };
|
||||
}
|
||||
|
||||
export async function appendConversationMessages(
|
||||
userId: number,
|
||||
convId: number,
|
||||
messages: { role: string; content: string }[],
|
||||
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
|
||||
const conv = await ownConversation(userId, convId);
|
||||
if (!conv) return { error: "Konverzace nenalezena", status: 404 };
|
||||
if (messages.length > 0) {
|
||||
await prisma.ai_chat_messages.createMany({
|
||||
data: messages.map((m) => ({
|
||||
user_id: userId,
|
||||
conversation_id: convId,
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
})),
|
||||
});
|
||||
}
|
||||
// Auto-title from the first user message (only while still the default), and
|
||||
// always bump updated_at.
|
||||
const firstUser = messages.find((m) => m.role === "user");
|
||||
const data: { updated_at: Date; title?: string } = { updated_at: new Date() };
|
||||
if (conv.title === DEFAULT_CONVERSATION_TITLE && firstUser) {
|
||||
const t = firstUser.content.replace(/\s+/g, " ").trim().slice(0, 60);
|
||||
if (t) data.title = t;
|
||||
}
|
||||
await prisma.ai_conversations.update({ where: { id: convId }, data });
|
||||
return { data: { ok: true } };
|
||||
}
|
||||
|
||||
export async function renameConversation(
|
||||
userId: number,
|
||||
convId: number,
|
||||
title: string,
|
||||
): Promise<{ data: ConversationSummary } | { error: string; status: number }> {
|
||||
if (!(await ownConversation(userId, convId)))
|
||||
return { error: "Konverzace nenalezena", status: 404 };
|
||||
const updated = await prisma.ai_conversations.update({
|
||||
where: { id: convId },
|
||||
data: { title: title.trim() || DEFAULT_CONVERSATION_TITLE },
|
||||
select: { id: true, title: true, updated_at: true },
|
||||
});
|
||||
return { data: updated };
|
||||
}
|
||||
|
||||
export async function deleteConversation(
|
||||
userId: number,
|
||||
convId: number,
|
||||
): Promise<{ data: { ok: true } } | { error: string; status: number }> {
|
||||
if (!(await ownConversation(userId, convId)))
|
||||
return { error: "Konverzace nenalezena", status: 404 };
|
||||
await prisma.ai_conversations.delete({ where: { id: convId } }); // cascade
|
||||
return { data: { ok: true } };
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Schemas** — in `src/schemas/ai.schema.ts`, keep `AiHistoryAppendSchema` (reused for append) and add:
|
||||
|
||||
```ts
|
||||
export const AiCreateConversationSchema = z.object({
|
||||
title: z.string().max(255).optional(),
|
||||
});
|
||||
|
||||
export const AiRenameConversationSchema = z.object({
|
||||
title: z.string().min(1, "Název je povinný").max(255),
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Routes** — in `src/routes/admin/ai.ts`: update imports (drop `getChatHistory/appendChatMessages/clearChatHistory`, add the new fns; add `AiCreateConversationSchema, AiRenameConversationSchema`; import `parseId` from `"../../schemas/common"`). Delete the three `/history` route blocks and append these (all `requirePermission("ai.use")`):
|
||||
|
||||
```ts
|
||||
// GET /conversations — this user's conversations (stable order)
|
||||
app.get(
|
||||
"/conversations",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const conversations = await listConversations(request.authData!.userId);
|
||||
return success(reply, { conversations });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /conversations — create
|
||||
app.post(
|
||||
"/conversations",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const body = parseBody(AiCreateConversationSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const conversation = await createConversation(
|
||||
request.authData!.userId,
|
||||
body.data.title,
|
||||
);
|
||||
return success(reply, { conversation });
|
||||
},
|
||||
);
|
||||
|
||||
// GET /conversations/:id/messages
|
||||
app.get(
|
||||
"/conversations/:id/messages",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const result = await getConversationMessages(request.authData!.userId, id);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, { messages: result.data });
|
||||
},
|
||||
);
|
||||
|
||||
// POST /conversations/:id/messages — append turns
|
||||
app.post(
|
||||
"/conversations/:id/messages",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const body = parseBody(AiHistoryAppendSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const result = await appendConversationMessages(
|
||||
request.authData!.userId,
|
||||
id,
|
||||
body.data.messages,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, result.data);
|
||||
},
|
||||
);
|
||||
|
||||
// PATCH /conversations/:id — rename
|
||||
app.patch(
|
||||
"/conversations/:id",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const body = parseBody(AiRenameConversationSchema, request.body);
|
||||
if ("error" in body) return error(reply, body.error, 400);
|
||||
const result = await renameConversation(
|
||||
request.authData!.userId,
|
||||
id,
|
||||
body.data.title,
|
||||
);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, { conversation: result.data });
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /conversations/:id
|
||||
app.delete(
|
||||
"/conversations/:id",
|
||||
{ preHandler: requirePermission("ai.use") },
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = parseId((request.params as { id: string }).id, reply);
|
||||
if (id === null) return;
|
||||
const result = await deleteConversation(request.authData!.userId, id);
|
||||
if ("error" in result) return error(reply, result.error, result.status);
|
||||
return success(reply, result.data);
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Gate**
|
||||
|
||||
Run: `npx tsc -b --noEmit` — expect exit 0. Run: `npm run build` — expect success.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/services/ai.service.ts src/schemas/ai.schema.ts src/routes/admin/ai.ts
|
||||
git commit -m "feat(odin): conversation-scoped service + routes (replace /history)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Backend tests
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/__tests__/ai.test.ts`
|
||||
|
||||
- [ ] **Step 1: Replace the imports + cleanup markers.** Swap the history-fn imports for the conversation fns, and update the top-of-file constants/cleanup:
|
||||
|
||||
```ts
|
||||
import {
|
||||
computeCostUsd,
|
||||
recordUsage,
|
||||
getMonthSpendUsd,
|
||||
getBudgetUsd,
|
||||
assertBudgetAvailable,
|
||||
isConfigured,
|
||||
listConversations,
|
||||
createConversation,
|
||||
getConversationMessages,
|
||||
appendConversationMessages,
|
||||
renameConversation,
|
||||
deleteConversation,
|
||||
} from "../services/ai.service";
|
||||
|
||||
const KIND = "test_ai";
|
||||
const CONV_UID_A = 999999991; // synthetic, FK-free owner ids
|
||||
const CONV_UID_B = 999999992;
|
||||
const HIST_MARKER = "「test-conv」"; // marks HTTP-test conversations on real users
|
||||
```
|
||||
|
||||
Update the top-level cleanup (`afterAll` and the conversation `beforeEach`) to delete by these. Deleting a conversation cascades its messages:
|
||||
|
||||
```ts
|
||||
afterAll(async () => {
|
||||
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
|
||||
});
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { title: { contains: HIST_MARKER } },
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace the `describe("ai.service chat history", …)` block** with conversation service tests:
|
||||
|
||||
```ts
|
||||
describe("ai.service conversations", () => {
|
||||
beforeEach(async () => {
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("creates, lists, appends (auto-title), and reads oldest→newest", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
expect(conv.title).toBe("Nová konverzace");
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "Kolik je hodin v Praze?" },
|
||||
{ role: "assistant", content: "Nevím, ale…" },
|
||||
]);
|
||||
const list = await listConversations(CONV_UID_A);
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].title).toBe("Kolik je hodin v Praze?"); // auto-titled
|
||||
const msgs = await getConversationMessages(CONV_UID_A, conv.id);
|
||||
expect("data" in msgs && msgs.data.map((m) => m.content)).toEqual([
|
||||
"Kolik je hodin v Praze?",
|
||||
"Nevím, ale…",
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not overwrite a renamed title on later appends", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
await renameConversation(CONV_UID_A, conv.id, "Moje téma");
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "tohle by nemělo přepsat název" },
|
||||
]);
|
||||
const list = await listConversations(CONV_UID_A);
|
||||
expect(list[0].title).toBe("Moje téma");
|
||||
});
|
||||
|
||||
it("isolates conversations per user (404 across owners)", async () => {
|
||||
const a = await createConversation(CONV_UID_A);
|
||||
expect(await listConversations(CONV_UID_B)).toHaveLength(0);
|
||||
const read = await getConversationMessages(CONV_UID_B, a.id);
|
||||
expect("error" in read && read.status).toBe(404);
|
||||
const ren = await renameConversation(CONV_UID_B, a.id, "hack");
|
||||
expect("error" in ren && ren.status).toBe(404);
|
||||
const del = await deleteConversation(CONV_UID_B, a.id);
|
||||
expect("error" in del && del.status).toBe(404);
|
||||
});
|
||||
|
||||
it("cascade-deletes messages with the conversation", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "x" },
|
||||
]);
|
||||
await deleteConversation(CONV_UID_A, conv.id);
|
||||
const remaining = await prisma.ai_chat_messages.count({
|
||||
where: { conversation_id: conv.id },
|
||||
});
|
||||
expect(remaining).toBe(0);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Replace the HTTP history tests** (the `/history` `it(...)` blocks) with conversation HTTP tests inside the existing `describe("HTTP /api/admin/ai", …)`:
|
||||
|
||||
```ts
|
||||
it("GET /conversations requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: { Authorization: `Bearer ${noPermToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("conversation lifecycle over HTTP (create → append → list → rename → delete)", async () => {
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} t` },
|
||||
});
|
||||
expect(created.statusCode).toBe(200);
|
||||
const id = created.json().data.conversation.id as number;
|
||||
|
||||
const app2 = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/admin/ai/conversations/${id}/messages`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [{ role: "user", content: "ahoj" }] },
|
||||
});
|
||||
expect(app2.statusCode).toBe(200);
|
||||
|
||||
const msgs = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/ai/conversations/${id}/messages`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(
|
||||
msgs.json().data.messages.map((m: { content: string }) => m.content),
|
||||
).toContain("ahoj");
|
||||
|
||||
const renamed = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/admin/ai/conversations/${id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} renamed` },
|
||||
});
|
||||
expect(renamed.json().data.conversation.title).toBe(`${HIST_MARKER} renamed`);
|
||||
|
||||
const del = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/admin/ai/conversations/${id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(del.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("GET messages of a non-existent conversation → 404", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations/999999000/messages",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Gate**
|
||||
|
||||
Run: `npx vitest run src/__tests__/ai.test.ts` — expect all passing. Then `npx vitest run` — expect the whole suite green.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/__tests__/ai.test.ts
|
||||
git commit -m "test(odin): conversation CRUD, isolation, auto-title, cascade"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Frontend queries + types
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/admin/lib/queries/ai.ts`
|
||||
|
||||
- [ ] **Step 1: Add conversation options.** Keep everything (incl. `aiHistoryOptions` for now — it's removed in Task 6 alongside its only consumer `DashAssistant.tsx`, so every task stays green). Add:
|
||||
|
||||
```ts
|
||||
export interface Conversation {
|
||||
id: number;
|
||||
title: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export const aiConversationsOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ["ai", "conversations"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ conversations: Conversation[] }>(
|
||||
"/api/admin/ai/conversations",
|
||||
),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
export const aiConversationMessagesOptions = (id: number) =>
|
||||
queryOptions({
|
||||
queryKey: ["ai", "conversation", id, "messages"],
|
||||
queryFn: () =>
|
||||
jsonQuery<{ messages: StoredChatMessage[] }>(
|
||||
`/api/admin/ai/conversations/${id}/messages`,
|
||||
),
|
||||
// Re-read the DB on each mount/selection (no stale-cache resurrection).
|
||||
staleTime: Infinity,
|
||||
gcTime: 0,
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Gate**
|
||||
|
||||
Run: `npx tsc -p tsconfig.app.json --noEmit` — expect exit 0 (we kept `aiHistoryOptions`, so `DashAssistant.tsx` still compiles).
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/admin/lib/queries/ai.ts
|
||||
git commit -m "feat(odin): conversation query options"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Frontend presentational components
|
||||
|
||||
**Files:**
|
||||
|
||||
- Create: `src/admin/components/odin/OdinTabs.tsx`
|
||||
- Create: `src/admin/components/odin/OdinThread.tsx`
|
||||
- Create: `src/admin/components/odin/InvoiceReviewCard.tsx`
|
||||
- Create: `src/admin/components/odin/OdinComposer.tsx`
|
||||
|
||||
These are **props-driven** (no data fetching). Port presentational details (bubble styling, the `Typography`-color fix, review-card fields, staged chips) from the current `src/admin/components/dashboard/DashAssistant.tsx`, which the implementer should read first.
|
||||
|
||||
- [ ] **Step 1: Shared types** — define at the top of `OdinChat.tsx` (Task 6) and import where needed, OR duplicate the tiny `ChatTurn` shape. Use these exact shapes across files:
|
||||
|
||||
```ts
|
||||
export interface ChatTurn {
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
}
|
||||
export interface ReviewInvoice {
|
||||
uid: string;
|
||||
supplier_name: string;
|
||||
invoice_number: string;
|
||||
amount: string;
|
||||
currency: string;
|
||||
vat_rate: string;
|
||||
issue_date: string;
|
||||
due_date: string;
|
||||
description: string;
|
||||
file_name: string;
|
||||
file: File;
|
||||
}
|
||||
export type EditableField =
|
||||
| "supplier_name"
|
||||
| "invoice_number"
|
||||
| "amount"
|
||||
| "currency"
|
||||
| "vat_rate"
|
||||
| "issue_date"
|
||||
| "due_date"
|
||||
| "description";
|
||||
export interface StagedFile {
|
||||
id: string;
|
||||
file: File;
|
||||
}
|
||||
```
|
||||
|
||||
Put these in a new `src/admin/components/odin/types.ts` and import from there in every odin file.
|
||||
|
||||
- [ ] **Step 2: `OdinTabs.tsx`** — props and behavior:
|
||||
|
||||
```tsx
|
||||
interface OdinTabsProps {
|
||||
conversations: { id: number; title: string }[];
|
||||
activeId: number | null;
|
||||
busy: boolean;
|
||||
onSelect: (id: number) => void;
|
||||
onNew: () => void;
|
||||
onRename: (id: number, title: string) => void;
|
||||
onDelete: (id: number) => void;
|
||||
}
|
||||
```
|
||||
|
||||
Render a horizontally-scrollable row (`Box` with `overflowX: "auto"`, `display: flex`, `gap`). Each conversation is a clickable pill (`Button` size small; active = `contained`, else `outlined color="inherit"`). After the pills, a `+` `Button` calls `onNew`. The **active** pill shows a small `⋮` `IconButton` opening an `@mui/material` `Menu` with "Přejmenovat" and "Smazat". "Přejmenovat" opens the kit `Modal` containing a `TextField` (prefilled with current title) → on submit calls `onRename`. "Smazat" opens the kit `ConfirmDialog` → on confirm calls `onDelete`. All actions disabled while `busy`.
|
||||
|
||||
- [ ] **Step 3: `OdinThread.tsx`** — props:
|
||||
|
||||
```tsx
|
||||
interface OdinThreadProps {
|
||||
turns: ChatTurn[];
|
||||
busy: boolean;
|
||||
loading: boolean;
|
||||
threadRef: React.RefObject<HTMLDivElement>;
|
||||
}
|
||||
```
|
||||
|
||||
Render the scrolling message area (`flex: 1, minHeight: 0, overflowY: "auto"`). Assistant turns left with a small circular Odin avatar (`Box` 28px, `borderRadius: "50%"`, `bgcolor: "primary.main"`, white "O"); user turns right-aligned `primary.main` bubble. **Message colour MUST be on the `Typography`** (`color: user ? "common.white" : "text.primary"`) — GlobalStyles pins `p` to text.secondary. Empty state (no turns, not busy, not loading): centered Odin avatar + "Dobrý den, jsem Odin. Zeptejte se, nebo přiložte fakturu (PDF) k importu." When `loading`: "Načítám…". When `busy`: a `CircularProgress size={14}` + "Pracuji…" row.
|
||||
|
||||
- [ ] **Step 4: `InvoiceReviewCard.tsx`** — props:
|
||||
|
||||
```tsx
|
||||
interface InvoiceReviewCardProps {
|
||||
inv: ReviewInvoice;
|
||||
busy: boolean;
|
||||
onChange: (uid: string, field: EditableField, value: string) => void;
|
||||
onSave: (inv: ReviewInvoice) => void;
|
||||
onDiscard: (uid: string) => void;
|
||||
}
|
||||
```
|
||||
|
||||
Port the card body from `DashAssistant.tsx` verbatim (the `Chip "Faktura"` + filename header, the 2-col grid of `TextField`s including **"Částka s DPH"**, "Datum splatnosti", "Popis", and the Uložit / Zahodit buttons). Replace `patch(...)`→`onChange(...)`, `saveInvoice`→`onSave`, the discard filter→`onDiscard(inv.uid)`.
|
||||
|
||||
- [ ] **Step 5: `OdinComposer.tsx`** — props:
|
||||
|
||||
```tsx
|
||||
interface OdinComposerProps {
|
||||
input: string;
|
||||
attachments: StagedFile[];
|
||||
busy: boolean;
|
||||
canSubmit: boolean;
|
||||
fileRef: React.RefObject<HTMLInputElement>;
|
||||
onInput: (v: string) => void;
|
||||
onFiles: (files: FileList | null) => void;
|
||||
onRemoveAttachment: (id: string) => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
```
|
||||
|
||||
Port the staged-attachment chips + the composer row (hidden file `input`, "Přiložit" button, `TextField` with Enter-to-submit, "Odeslat" button) from `DashAssistant.tsx`. Disable per `busy` / `!canSubmit`.
|
||||
|
||||
- [ ] **Step 6: Gate**
|
||||
|
||||
Run: `npx tsc -p tsconfig.app.json --noEmit` — expect exit 0 (these compile independently of the orchestrator). If a component is unused at this point, that is fine — Task 6 wires them.
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/admin/components/odin
|
||||
git commit -m "feat(odin): tabs, thread, review-card, composer components"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: OdinChat orchestrator + page + delete DashAssistant
|
||||
|
||||
**Files:**
|
||||
|
||||
- Create: `src/admin/components/odin/OdinChat.tsx`
|
||||
- Modify: `src/admin/pages/Odin.tsx`
|
||||
- Modify: `src/admin/lib/queries/ai.ts` (remove `aiHistoryOptions`)
|
||||
- Delete: `src/admin/components/dashboard/DashAssistant.tsx`
|
||||
|
||||
- [ ] **Step 1: Write `OdinChat.tsx`.** It owns all state + queries + the ported submit/extract/save logic, scoped to the active conversation. Port the helper fns (`summaryNote`, `nextUid`, `plural`, `MODEL_CONTEXT`, `MAX_STORE`) and the **submit / saveInvoice / onFiles / persist** logic from `DashAssistant.tsx` with these adaptations:
|
||||
- **Queries:** `usage` (unchanged), `aiConversationsOptions()`, and `aiConversationMessagesOptions(activeId)` (enabled when `activeId != null`).
|
||||
- **State:** `activeId: number | null`, plus `input`, `busy`, `turns`, `review`, `attachments`, `fileRef`, `threadRef`.
|
||||
- **Ensure a conversation exists:** when the conversations query resolves: if empty, `POST /conversations` to create a default and `setActiveId(new.id)` + invalidate `["ai","conversations"]`; else if `activeId == null`, `setActiveId(list[0].id)`.
|
||||
- **Seed per conversation:** a `seededId = useRef<number|null>(null)`. Effect keyed on `[activeId, messagesData]`: when `messagesData` for the active id arrives and `seededId.current !== activeId`, set `seededId.current = activeId`, `setTurns(messagesData.messages.map(m => ({role:m.role, content:m.content})))`, `setReview([])`.
|
||||
- **Switch tab (`onSelect`):** `setActiveId(id); setTurns([]); setReview([]); seededId.current = null;` (force re-seed; the messages query for the new id loads and seeds).
|
||||
- **`persist(msgs)`** posts to `/api/admin/ai/conversations/${activeId}/messages` (was `/history`); best-effort + `console.error` on failure.
|
||||
- **`submit`:** identical to `DashAssistant.submit` EXCEPT it first ensures `activeId` (if null, await-create one and use it); marks `seededId.current = activeId`; on success persists via the conversation endpoint; on error rolls back + keeps input/attachments. Gate `canSubmit` on `!conversationsPending && activeId != null && !busy && (input.trim() || attachments.length)`.
|
||||
- **`onNew`:** `POST /conversations` → select it (`setActiveId`, clear turns/review, `seededId.current=null`) + invalidate `["ai","conversations"]`.
|
||||
- **`onRename(id, title)`:** `PATCH /conversations/:id` → invalidate `["ai","conversations"]`.
|
||||
- **`onDelete(id)`:** `DELETE /conversations/:id` → invalidate `["ai","conversations"]`; if `id === activeId`, pick another conversation from the (refetched) list or null.
|
||||
- **Layout:** a full-height shell — `Box sx={{ height: "calc(100dvh - 140px)", display: "flex", flexDirection: "column" }}` containing: header (`Odin` + budget `Utraceno: $x / $y`), `<OdinTabs … />`, `<OdinThread … />` (flex 1), the review list (`review.map(inv => <InvoiceReviewCard … />)` in a bounded `maxHeight: "35vh", overflowY: "auto"` box), and `<OdinComposer … />`.
|
||||
- **Self-hide:** keep `if (usage && usage.configured === false) return null;`.
|
||||
|
||||
Reference the exact bodies of `submit`, `saveInvoice`, `onFiles`, `summaryNote`, `nextUid` in the current `DashAssistant.tsx` (lines ~52–333) — copy them, applying only the adaptations above.
|
||||
|
||||
- [ ] **Step 2: Update `src/admin/pages/Odin.tsx`** — swap the import and render:
|
||||
|
||||
```tsx
|
||||
import OdinChat from "../components/odin/OdinChat";
|
||||
// …
|
||||
<Box sx={{ maxWidth: 1100, mx: "auto" }}>
|
||||
<OdinChat />
|
||||
</Box>;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Delete `src/admin/components/dashboard/DashAssistant.tsx`** and remove the now-orphaned `aiHistoryOptions` from `src/admin/lib/queries/ai.ts` (DashAssistant was its only consumer).
|
||||
|
||||
```bash
|
||||
git rm src/admin/components/dashboard/DashAssistant.tsx
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Gate**
|
||||
|
||||
Run: `npx tsc -b --noEmit` — expect exit 0. Run: `npm run build` — expect success. Run: `npx vitest run` — expect the full suite green.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/admin/components/odin/OdinChat.tsx src/admin/pages/Odin.tsx src/admin/lib/queries/ai.ts
|
||||
git commit -m "feat(odin): OdinChat orchestrator; render on /odin; remove DashAssistant"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Final verification (controller)
|
||||
|
||||
- `npx tsc -b --noEmit` = 0, `npm run build` = success, `npx vitest run` = all green.
|
||||
- Manual (user/controller): create a conversation, send a chat, attach a PDF → review → save, rename a tab, delete a tab, reload (history persists per conversation), switch tabs (each keeps its own thread).
|
||||
- Adversarial review pass (workflow) before merge/release.
|
||||
2445
docs/superpowers/plans/2026-06-09-issued-orders.md
Normal file
2445
docs/superpowers/plans/2026-06-09-issued-orders.md
Normal file
File diff suppressed because it is too large
Load Diff
188
docs/superpowers/plans/2026-06-10-audit-high-fix-pass.md
Normal file
188
docs/superpowers/plans/2026-06-10-audit-high-fix-pass.md
Normal file
@@ -0,0 +1,188 @@
|
||||
# 2026-06-10 — Audit fix pass #1: all verified CRITICAL/HIGH findings
|
||||
|
||||
Source: `REVIEW_FINDINGS.md` (2026-06-09 full audit, 304 files). Scope of this pass:
|
||||
the 19 verified per-file **HIGH** findings + the project-level **CRITICAL** dependency
|
||||
finding. The two project-level HIGH _structural refactors_ (service-layer extraction for
|
||||
6 route files; PDF template dedup) are explicitly **out of scope** — they are
|
||||
multi-thousand-line refactors that deserve their own pass.
|
||||
|
||||
Execution: subagent-driven development — one implementer per task (sequential, shared
|
||||
test DB forbids parallel test runs), spec-compliance review then code-quality review
|
||||
after each. No commits until the user asks. Final full gates:
|
||||
`npx tsc -b --noEmit` · `npx vitest run` · `npm run lint` · `npm run build`.
|
||||
|
||||
---
|
||||
|
||||
## Task H — Dependencies (project-level CRITICAL) — done inline by controller
|
||||
|
||||
- Remove `concurrently` from devDependencies (unused; carries both critical advisories
|
||||
GHSA-w7jw-789q-3m8p / shell-quote CVSS 8.1).
|
||||
- Add `"overrides": { "@hono/node-server": "^1.19.13" }` (clears the 3 moderate
|
||||
advisories from the prisma → @prisma/dev chain; do NOT take npm's Prisma 6 downgrade).
|
||||
- Remove deprecated stub types `@types/dompurify`, `@types/bcryptjs`; move `@types/jsdom`
|
||||
to devDependencies.
|
||||
- Add `qrcode` + `@types/qrcode` (needed by Task B to replace the CSP-blocked external
|
||||
QR service).
|
||||
- `npm install`, verify `npm audit` (criticals+moderates gone), typecheck.
|
||||
|
||||
## Task A — Attendance create/edit broken since 519edce (top-5 #1)
|
||||
|
||||
Findings (both verified HIGH):
|
||||
|
||||
- `src/admin/pages/AttendanceCreate.tsx:80-99` — handleSubmit posts the raw form whose
|
||||
shape the API does not accept: `arrival_date`/`break_start_date`/`break_start_time`/
|
||||
`break_end_*`/`departure_date` are not in CreateAttendanceSchema (silently stripped —
|
||||
breaks and overnight dates never save); times are never combined with dates (unlike
|
||||
useAttendanceAdmin's combineDatetime), so a validated "HH:MM" would reach
|
||||
createAttendance which does `new Date('08:00')` → Invalid Date → 500; and since commit
|
||||
519edce the always-sent empty-string time fields (`arrival_time: ""`) fail timeString
|
||||
validation, so EVERY submit from this page — including leave records — returns 400.
|
||||
- `src/admin/pages/AttendanceAdmin.tsx:407-442` (logic in `useAttendanceAdmin.ts`) —
|
||||
create/edit modal submits send combined `YYYY-MM-DDTHH:MM:00` datetimes for
|
||||
arrival/departure/break, but since 519edce CreateAttendanceSchema/UpdateAttendanceSchema
|
||||
validate them with `timeString` (HH:MM only) — every create/edit containing a time is
|
||||
rejected 400 "Čas musí být ve formátu HH:MM" (and the service itself expects full
|
||||
datetimes via `new Date(...)`); additionally `break_start`/`break_end` are absent from
|
||||
CreateAttendanceSchema, so breaks are silently stripped on create.
|
||||
|
||||
Direction: first `git show 519edce` to understand the intent; the schema contradicts
|
||||
both client and service, so the fix is to make the schemas validate the combined
|
||||
local-datetime wire format the client sends and the service consumes (lenient helper in
|
||||
`src/schemas/common.ts` per repo convention), add `break_start`/`break_end` to the create
|
||||
schema, and rewrite AttendanceCreate.tsx's submit to combine date+time and omit empty
|
||||
optionals. TDD: route-level regression tests (work record with times+breaks, overnight,
|
||||
leave record without times, update) in `src/__tests__/`.
|
||||
|
||||
## Task B — 2FA: backup-code login, enrollment QR, dashboard status (top-5 #2)
|
||||
|
||||
Findings (all verified HIGH):
|
||||
|
||||
- `src/admin/context/AuthContext.tsx:263-272` — backup-code login broken: verify2FA
|
||||
always POSTs to /login/totp with the code as totp_code plus an isBackup flag the server
|
||||
ignores; TotpVerifySchema requires exactly 6 digits so 8-char backup codes always 400.
|
||||
The real endpoint POST /api/admin/totp/backup-verify (expects backup_code) is never
|
||||
called anywhere in the frontend — lockout for any user who lost their authenticator.
|
||||
- `src/admin/components/dashboard/DashProfile.tsx:556` — QR `<img>` from api.qrserver.com
|
||||
is blocked by the production CSP (img-src 'self' data: blob: + osm tiles), so prod 2FA
|
||||
enrollment shows a broken image. (Also a privacy bug: the TOTP secret is sent to a
|
||||
third-party URL.) Fix: generate the QR locally with the `qrcode` package
|
||||
(`QRCode.toDataURL(otpauthUrl)`) — data: is already CSP-allowed.
|
||||
- `src/admin/pages/Dashboard.tsx:89-91` — totpEnabled derived from require2FAOptions()
|
||||
which returns the COMPANY-WIDE require_2fa policy flag, not the user's enrollment; the
|
||||
per-user endpoint (totp.ts:190-197) is never queried. Wrong "2FA Aktivní/Neaktivní" and
|
||||
wrong button shown.
|
||||
|
||||
Direction: read `src/routes/admin/totp.ts` first; wire Login/AuthContext so a backup code
|
||||
goes to backup-verify and completes the login-token flow. If the server endpoint doesn't
|
||||
fit the loginToken flow, extend it minimally (single-use code consumption + logAudit
|
||||
preserved). Server test for backup-verify login path if server is touched.
|
||||
|
||||
## Task C — Invoice/issued-order edit integrity (top-5 #3)
|
||||
|
||||
Findings (all verified HIGH):
|
||||
|
||||
- `src/admin/pages/InvoiceDetail.tsx:728` — edit hydration overwrites each item's
|
||||
persisted per-line VAT with the invoice-level rate (`vat_rate: Number(inv.vat_rate) || 21`)
|
||||
though invoice_items.vat_rate is a real per-item column — re-saving a mixed-rate invoice
|
||||
silently corrupts per-line VAT in the DB; `|| 21` also turns legitimate 0% into 21%
|
||||
(same falsy-zero at line 689).
|
||||
- `src/admin/pages/InvoiceDetail.tsx:1891-1902` — editing "Text fakturace (na PDF)" is
|
||||
silently lost: payload includes billing_text but UpdateInvoiceSchema
|
||||
(src/schemas/invoices.schema.ts:46-67) has no billing_text field, so Zod strips it
|
||||
(updateInvoice supports it via strFields). Add the field to the schema + server test.
|
||||
- `src/admin/pages/IssuedOrderDetail.tsx:606-611` — hydration falsy-fallbacks:
|
||||
`quantity: Number(it.quantity) || 1` turns saved 0 into 1; `vat_rate: Number(it.vat_rate)
|
||||
|| Number(d.vat_rate) || 21` turns a saved 0% line into 21% — displayed wrong and
|
||||
silently persisted on next save.
|
||||
- `src/admin/pages/IssuedOrderDetail.tsx:826-839` — handleStatusChange never mirrors the
|
||||
new status into form.status, so StatusChip, the `editable` flag and the delete-button
|
||||
gate use the stale status after every transition.
|
||||
|
||||
Use Number.isFinite-style coercion that respects 0 (e.g. `const n = Number(x);
|
||||
Number.isFinite(n) ? n : fallback`).
|
||||
|
||||
## Task D — Trips: truncated lists/totals + dropped vehicle edit (top-5 #4a)
|
||||
|
||||
Findings (all verified HIGH):
|
||||
|
||||
- `src/admin/lib/queries/trips.ts:52-63` — tripListOptions consumes the paginated
|
||||
endpoint via plain jsonQuery, discarding pagination meta; Trips.tsx uses default limit
|
||||
25 and TripsAdmin perPage:100 (server hard cap) — both silently truncate with no
|
||||
pagination controls.
|
||||
- `src/admin/lib/queries/trips.ts:95-103` — tripHistoryOptions sends no page/per_page →
|
||||
25 rows; TripsHistory.tsx computes monthly km/business totals from the truncated rows.
|
||||
- `src/admin/pages/Trips.tsx:324-336` — stat cards computed from the 25-row page;
|
||||
header labels stats "current month" though the query has no month filter.
|
||||
- `src/admin/pages/TripsAdmin.tsx:295,665-676` — edit modal sends vehicle_id but
|
||||
UpdateTripSchema (src/schemas/trips.schema.ts:23-31) has no vehicle_id and the PUT
|
||||
handler never applies it — vehicle change silently dropped. Add to schema
|
||||
(nullableIntIdFromForm) + apply in route + audit + server test.
|
||||
- `src/admin/pages/TripsHistory.tsx:98-104,121-128` — same 25-row truncation for the
|
||||
month view and its stat cards.
|
||||
|
||||
Direction for totals: prefer a server-side aggregate (the repo already has per-currency
|
||||
totals endpoints for invoices/orders as the pattern) over fetching all pages client-side;
|
||||
lists get real pagination using the existing `usePaginatedQuery`/`Pagination` kit pieces
|
||||
used elsewhere. Keep the month-filter semantics of TripsHistory correct (totals must
|
||||
cover the WHOLE month, not one page).
|
||||
|
||||
## Task E — orders.service.ts: PDF blob in every response (top-5 #4b)
|
||||
|
||||
Finding (verified HIGH): `src/services/orders.service.ts:154-176,196-216,228-263,570,683`
|
||||
— attachment_data (full PDF blob, Bytes) is fetched on every query with no select/omit
|
||||
and spread into API responses by enrichOrder/getOrder; getOrderTotals loads every blob
|
||||
for the whole filtered set just to sum totals; updateOrder/deleteOrder pre-reads pull the
|
||||
blob to check status/number. A dedicated /:id/attachment endpoint already exists.
|
||||
Exclude the blob from list/detail/totals/pre-reads (keep has_attachment-style boolean if
|
||||
the FE needs it — check FE usage), keep the attachment endpoint working, extend
|
||||
`src/__tests__/orders-list.test.ts` to assert attachment_data is absent.
|
||||
|
||||
## Task F — Warehouse: unit enum 400s + dead attachment download
|
||||
|
||||
Findings (both verified HIGH):
|
||||
|
||||
- `src/admin/pages/WarehouseItemDetail.tsx:451-462` — "Jednotka" is free-text but the
|
||||
server requires UnitEnum ("ks","m","kg","bal","sada","m2","m3","l") — any other value
|
||||
400s create/update. Make it a Select over the enum values (single source: mirror the
|
||||
server enum list).
|
||||
- `src/admin/pages/WarehouseReceiptDetail.tsx:251-259` — attachment link targets
|
||||
GET /warehouse/receipts/:id/attachments/:attachmentId which does not exist (only POST
|
||||
upload + DELETE are registered in warehouse.ts), and a plain <a href> sends no
|
||||
Authorization header anyway. Add the GET download route (requirePermission, correct
|
||||
content-type/disposition) + authenticated blob download in the UI (fetch via apiFetch →
|
||||
object URL, like other binary downloads in the repo). Server test for the new route.
|
||||
|
||||
## Task G — Small fixes
|
||||
|
||||
- `.claude/hooks/block-env.js:10-11` (verified HIGH) — block decision never takes
|
||||
effect: prints {decision:'block'} JSON to stdout then exits 1; Claude Code only parses
|
||||
stdout JSON on exit 0 and only blocks on exit 2 (reason on stderr). Fix: exit 2 with the
|
||||
reason on stderr.
|
||||
- `src/admin/pages/Projects.tsx:153-154` (verified HIGH) — create modal submits
|
||||
start_date/end_date initialized to "" which isoDateString.nullish() rejects → creating
|
||||
a project without filling BOTH dates always 400s. Send null/omit when empty.
|
||||
|
||||
---
|
||||
|
||||
## Status
|
||||
|
||||
- [x] H — dependencies (controller, inline) — criticals+moderates cleared; only the
|
||||
2 known-mitigated quill lows remain
|
||||
- [x] A — attendance create/edit — dateTimeString helpers, break fields, rewritten
|
||||
AttendanceCreate payload; 6 regression tests
|
||||
- [x] B — 2FA — backup-verify wired (+ remember-me parity server-side), local QR via
|
||||
qrcode lib, per-user totp status; 6 tests
|
||||
- [x] C — invoice/issued-order edit integrity — numberOr (shared in formatters.ts),
|
||||
billing_text in UpdateInvoiceSchema, status mirror; 2 tests
|
||||
- [x] D — trips — paginated queries + Pagination UI on 3 pages, GET /trips/stats
|
||||
(buildTripsWhere shared), vehicle_id on PUT + both-vehicle odometer recompute,
|
||||
print rebuilt (sync window.open, escaped string template); 7 tests
|
||||
- [x] E — orders attachment_data excluded from all non-binary reads (incl.
|
||||
numbering/invoices/orders-pdf callers); 4 tests
|
||||
- [x] F — warehouse unit Select + GET receipt attachment route + authenticated blob
|
||||
download; RFC 5987 content-disposition helper (also fixes received-invoices +
|
||||
orders Czech-filename 500); 6 tests
|
||||
- [x] G — block-env hook exit 2/stderr (verified empirically), Projects empty dates
|
||||
→ null
|
||||
- [x] Final gates: tsc -b clean · vitest 30 files / 342 tests green · lint 0 errors ·
|
||||
build OK. Whole-diff 3-lens review: see final report.
|
||||
@@ -0,0 +1,789 @@
|
||||
# Per-document custom-field print selection — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Let each offer, issued order, and invoice choose — on its detail page — which company custom fields print in its PDF sender block; default none selected.
|
||||
|
||||
**Architecture:** A new nullable `selected_custom_fields` column (JSON-array-in-VARCHAR) on `quotations`, `issued_orders`, `invoices`. A shared backend util encodes/decodes the index array. Create/update services persist it; detail services decode it to `number[]`. The PDF `buildAddressLines()` company-block builder gains an optional selected-indices filter. A shared React picker reused by the three detail pages drives the selection.
|
||||
|
||||
**Tech Stack:** Prisma 7 / MySQL, Fastify 5, Zod 4, Vitest (real `app_test` DB), React 19 + MUI v7 + React Query.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-06-16-per-document-custom-field-selection-design.md`
|
||||
|
||||
---
|
||||
|
||||
## Conventions for this plan
|
||||
|
||||
- This shell is non-interactive — `prisma migrate dev` is forbidden. Use the `migrate diff` recipe (Task 1).
|
||||
- **Before the migration, ask the user to stop their dev server and wait for confirmation** (it holds DB connections). Do not run the migration until they confirm.
|
||||
- Server tests run against `app_test` via `.env.test` (`npm test`). Apply the migration to `app_test` too or the suite breaks.
|
||||
- `npm run typecheck` = `tsc -b --noEmit`. `npm run lint` must stay at 0 errors.
|
||||
- Selection semantics in `buildAddressLines`: param **omitted/`undefined`** ⇒ show ALL custom fields (unchanged behavior — used for customer/supplier blocks). Param is an **array** (possibly empty) ⇒ show ONLY those indices (used for the company/sender block; empty ⇒ none).
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- **Modify** `prisma/schema.prisma` — add `selected_custom_fields String?` to `quotations`, `issued_orders`, `invoices`.
|
||||
- **Create** `prisma/migrations/<ts>_add_selected_custom_fields/migration.sql`.
|
||||
- **Modify** `src/utils/custom-fields.ts` — add `encodeSelectedCustomFields` / `parseSelectedCustomFields`.
|
||||
- **Create** `src/__tests__/selected-custom-fields.test.ts` — util + integration coverage.
|
||||
- **Modify** `src/schemas/offers.schema.ts`, `issued-orders.schema.ts`, `invoices.schema.ts` — new optional array field.
|
||||
- **Modify** `src/services/offers.service.ts`, `issued-orders.service.ts`, `invoices.service.ts` — persist on create/update, decode in detail.
|
||||
- **Modify** `src/routes/admin/offers-pdf.ts`, `issued-orders-pdf.ts`, `invoices-pdf.ts` — filter company custom lines.
|
||||
- **Modify** `src/admin/lib/queries/offers.ts`, `issued-orders.ts`, `invoices.ts` — add `selected_custom_fields: number[]` to detail interfaces.
|
||||
- **Create** `src/admin/components/document/CustomFieldsPrintPicker.tsx` — shared picker.
|
||||
- **Modify** `src/admin/pages/OfferDetail.tsx`, `IssuedOrderDetail.tsx`, `InvoiceDetail.tsx` — render picker, wire into save payload.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Schema column + migration
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `prisma/schema.prisma` (models `quotations`, `issued_orders`, `invoices`)
|
||||
- Create: `prisma/migrations/<yyyyMMddHHmmss>_add_selected_custom_fields/migration.sql`
|
||||
|
||||
- [ ] **Step 1: Ask the user to stop their dev server**
|
||||
|
||||
Post: "Please stop your dev server so I can apply a migration, and tell me when it's stopped." Wait for confirmation before any later `migrate deploy` step.
|
||||
|
||||
- [ ] **Step 2: Add the column to each model in `prisma/schema.prisma`**
|
||||
|
||||
Add this line to the `quotations` model (near other scalar columns, e.g. after `language`):
|
||||
|
||||
```prisma
|
||||
selected_custom_fields String? @db.VarChar(255)
|
||||
```
|
||||
|
||||
Add the identical line to the `issued_orders` model and to the `invoices` model.
|
||||
|
||||
- [ ] **Step 3: Generate the migration SQL**
|
||||
|
||||
Run (Git Bash):
|
||||
|
||||
```bash
|
||||
cd /d/cortex/boha-app-ts
|
||||
TS=$(date +%Y%m%d%H%M%S)
|
||||
mkdir -p "prisma/migrations/${TS}_add_selected_custom_fields"
|
||||
npx prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script \
|
||||
> "prisma/migrations/${TS}_add_selected_custom_fields/migration.sql"
|
||||
```
|
||||
|
||||
Expected: a `migration.sql` containing three `ALTER TABLE … ADD COLUMN selected_custom_fields VARCHAR(255) NULL` statements (one per table). Open it and confirm it touches ONLY `quotations`, `issued_orders`, `invoices` and adds nothing else (no BOM — if it was written via PowerShell, strip the BOM).
|
||||
|
||||
- [ ] **Step 4: Apply to dev DB + regenerate client (after user confirmed server stopped)**
|
||||
|
||||
```bash
|
||||
npx prisma migrate deploy
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
Expected: "All migrations have been applied" and a regenerated client.
|
||||
|
||||
- [ ] **Step 5: Apply to the test DB**
|
||||
|
||||
```bash
|
||||
DATABASE_URL="$(grep -m1 '^DATABASE_URL' .env.test | cut -d= -f2- | tr -d '"')" npx prisma migrate deploy
|
||||
```
|
||||
|
||||
Expected: the same migration applied to `app_test`. (If the env parsing is awkward on this shell, temporarily set `DATABASE_URL` to the app_test URL from `.env.test` and run `npx prisma migrate deploy`.)
|
||||
|
||||
- [ ] **Step 6: Typecheck**
|
||||
|
||||
Run: `npm run typecheck`
|
||||
Expected: PASS (the new Prisma field is now known to the client).
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add prisma/schema.prisma prisma/migrations
|
||||
git commit -m "feat(documents): add selected_custom_fields column to quotations/issued_orders/invoices"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Backend encode/decode util (TDD)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/utils/custom-fields.ts`
|
||||
- Test: `src/__tests__/selected-custom-fields.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Create `src/__tests__/selected-custom-fields.test.ts`:
|
||||
|
||||
```ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
encodeSelectedCustomFields,
|
||||
parseSelectedCustomFields,
|
||||
} from "../utils/custom-fields";
|
||||
|
||||
describe("selected custom fields encode/decode", () => {
|
||||
it("encodes a non-empty index array to a JSON string", () => {
|
||||
expect(encodeSelectedCustomFields([0, 2])).toBe("[0,2]");
|
||||
});
|
||||
|
||||
it("encodes empty / non-array to null", () => {
|
||||
expect(encodeSelectedCustomFields([])).toBeNull();
|
||||
expect(encodeSelectedCustomFields(undefined)).toBeNull();
|
||||
expect(encodeSelectedCustomFields("nope")).toBeNull();
|
||||
});
|
||||
|
||||
it("dedupes, sorts, and drops invalid entries before encoding", () => {
|
||||
expect(encodeSelectedCustomFields([2, 0, 2, -1, 1.5, 3])).toBe("[0,2,3]");
|
||||
});
|
||||
|
||||
it("parses a stored string back to a number array", () => {
|
||||
expect(parseSelectedCustomFields("[0,2]")).toEqual([0, 2]);
|
||||
});
|
||||
|
||||
it("parses null / malformed to an empty array", () => {
|
||||
expect(parseSelectedCustomFields(null)).toEqual([]);
|
||||
expect(parseSelectedCustomFields("")).toEqual([]);
|
||||
expect(parseSelectedCustomFields("{garbage")).toEqual([]);
|
||||
expect(parseSelectedCustomFields('"x"')).toEqual([]);
|
||||
});
|
||||
|
||||
it("parses already-array input (defensive) and filters invalid", () => {
|
||||
expect(parseSelectedCustomFields([0, "1", 2, -3] as unknown)).toEqual([
|
||||
0, 2,
|
||||
]);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run it to confirm failure**
|
||||
|
||||
Run: `npm test -- selected-custom-fields`
|
||||
Expected: FAIL — `encodeSelectedCustomFields is not a function`.
|
||||
|
||||
- [ ] **Step 3: Implement the helpers**
|
||||
|
||||
Append to `src/utils/custom-fields.ts`:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* Per-document selection of which COMPANY custom fields print on a PDF.
|
||||
* Stored positionally (matching the `custom_<i>` keys the PDF builder emits)
|
||||
* as a JSON array string, e.g. "[0,2]". Null/empty means "none selected".
|
||||
*/
|
||||
export function encodeSelectedCustomFields(indices: unknown): string | null {
|
||||
const clean = normalizeIndices(indices);
|
||||
return clean.length > 0 ? JSON.stringify(clean) : null;
|
||||
}
|
||||
|
||||
/** Decode the stored selection (string OR defensive array) into a clean number[]. */
|
||||
export function parseSelectedCustomFields(raw: unknown): number[] {
|
||||
if (raw == null) return [];
|
||||
if (Array.isArray(raw)) return normalizeIndices(raw);
|
||||
if (typeof raw !== "string" || raw.trim() === "") return [];
|
||||
try {
|
||||
return normalizeIndices(JSON.parse(raw));
|
||||
} catch {
|
||||
// Malformed JSON in a selection column degrades to "none" (expected
|
||||
// condition — a hand-edited/legacy row should never 500 a PDF render).
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeIndices(input: unknown): number[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const set = new Set<number>();
|
||||
for (const v of input) {
|
||||
if (typeof v === "number" && Number.isInteger(v) && v >= 0) set.add(v);
|
||||
}
|
||||
return [...set].sort((a, b) => a - b);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the test to confirm it passes**
|
||||
|
||||
Run: `npm test -- selected-custom-fields`
|
||||
Expected: PASS (all util cases).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/utils/custom-fields.ts src/__tests__/selected-custom-fields.test.ts
|
||||
git commit -m "feat(documents): selected-custom-fields encode/decode helpers"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Zod schemas
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/schemas/offers.schema.ts`
|
||||
- Modify: `src/schemas/issued-orders.schema.ts`
|
||||
- Modify: `src/schemas/invoices.schema.ts`
|
||||
|
||||
- [ ] **Step 1: Offers schema**
|
||||
|
||||
In `src/schemas/offers.schema.ts`, inside `CreateQuotationSchema`, add after the `sections` line (line 50):
|
||||
|
||||
```ts
|
||||
// Positional indices of company custom fields to print on this document's
|
||||
// PDF. Omitted/empty ⇒ none. Update schema derives via .partial().
|
||||
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
|
||||
```
|
||||
|
||||
(`UpdateQuotationSchema` already derives from this via `.partial().omit({ quotation_number: true })` — no change needed there.)
|
||||
|
||||
- [ ] **Step 2: Issued-orders schema**
|
||||
|
||||
In `src/schemas/issued-orders.schema.ts`, inside `CreateIssuedOrderSchema`, add after the `sections` field:
|
||||
|
||||
```ts
|
||||
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
|
||||
```
|
||||
|
||||
(`UpdateIssuedOrderSchema` derives via `.partial()` — no change.)
|
||||
|
||||
- [ ] **Step 3: Invoices schema**
|
||||
|
||||
In `src/schemas/invoices.schema.ts`, add the same line to BOTH `CreateInvoiceSchema` (after its `sections` field) and `UpdateInvoiceSchema` (after its `sections` field — invoices define the two schemas separately, so it must be added in both):
|
||||
|
||||
```ts
|
||||
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Typecheck**
|
||||
|
||||
Run: `npm run typecheck`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/schemas/offers.schema.ts src/schemas/issued-orders.schema.ts src/schemas/invoices.schema.ts
|
||||
git commit -m "feat(documents): accept selected_custom_fields in document schemas"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Services — persist on write, decode in detail (TDD)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/services/offers.service.ts`
|
||||
- Modify: `src/services/issued-orders.service.ts`
|
||||
- Modify: `src/services/invoices.service.ts`
|
||||
- Test: `src/__tests__/selected-custom-fields.test.ts` (extend)
|
||||
|
||||
- [ ] **Step 1: Add the import to all three services**
|
||||
|
||||
At the top of each of the three service files, add (or extend the existing import from `../utils/custom-fields`):
|
||||
|
||||
```ts
|
||||
import {
|
||||
encodeSelectedCustomFields,
|
||||
parseSelectedCustomFields,
|
||||
} from "../utils/custom-fields";
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Offers — persist on create**
|
||||
|
||||
In `createOffer` (`src/services/offers.service.ts`), inside `tx.quotations.create({ data: { … } })`, add after `scope_description`:
|
||||
|
||||
```ts
|
||||
selected_custom_fields: encodeSelectedCustomFields(
|
||||
body.selected_custom_fields,
|
||||
),
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Offers — persist on update**
|
||||
|
||||
In `updateOffer`, inside the `const data = { … }` object (after `scope_description`, before `modified_at`), add:
|
||||
|
||||
```ts
|
||||
selected_custom_fields:
|
||||
body.selected_custom_fields !== undefined
|
||||
? encodeSelectedCustomFields(body.selected_custom_fields)
|
||||
: undefined,
|
||||
```
|
||||
|
||||
(`undefined` = "key absent in payload, leave column untouched" — matches the sibling header fields.)
|
||||
|
||||
- [ ] **Step 4: Offers — decode in detail**
|
||||
|
||||
In `getOffer`, in the returned object (after `valid_transitions`), add:
|
||||
|
||||
```ts
|
||||
selected_custom_fields: parseSelectedCustomFields(rest.selected_custom_fields),
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Issued orders — persist + decode**
|
||||
|
||||
In `src/services/issued-orders.service.ts`:
|
||||
|
||||
- In `createIssuedOrder`, inside `tx.issued_orders.create({ data: { … } })`, add:
|
||||
```ts
|
||||
selected_custom_fields: encodeSelectedCustomFields(
|
||||
body.selected_custom_fields,
|
||||
),
|
||||
```
|
||||
- In `updateIssuedOrder`, inside the header `data` object passed to `issued_orders.update`, add:
|
||||
```ts
|
||||
selected_custom_fields:
|
||||
body.selected_custom_fields !== undefined
|
||||
? encodeSelectedCustomFields(body.selected_custom_fields)
|
||||
: undefined,
|
||||
```
|
||||
- In `getIssuedOrder`, in the returned object (after `valid_transitions`), add:
|
||||
|
||||
```ts
|
||||
selected_custom_fields: parseSelectedCustomFields(rest.selected_custom_fields),
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Invoices — persist + decode**
|
||||
|
||||
In `src/services/invoices.service.ts`:
|
||||
|
||||
- In `createInvoice`, inside `tx.invoices.create({ data: { … } })`, add after `internal_notes`:
|
||||
```ts
|
||||
selected_custom_fields: encodeSelectedCustomFields(
|
||||
body.selected_custom_fields,
|
||||
),
|
||||
```
|
||||
- In `updateInvoice`, inside the first `if (editable) { … }` block (after the `tax_date` handling, still inside the block), add:
|
||||
```ts
|
||||
if (body.selected_custom_fields !== undefined)
|
||||
data.selected_custom_fields = encodeSelectedCustomFields(
|
||||
body.selected_custom_fields,
|
||||
);
|
||||
```
|
||||
- In `getInvoice`, in the returned object (after `valid_transitions`), add:
|
||||
|
||||
```ts
|
||||
selected_custom_fields: parseSelectedCustomFields(rest.selected_custom_fields),
|
||||
```
|
||||
|
||||
- [ ] **Step 7: Extend the test with an offers round-trip (real DB)**
|
||||
|
||||
Append to `src/__tests__/selected-custom-fields.test.ts`. Match the existing suite's fixture style — import the offers service directly and clean up. Use a far-future placeholder where the suite does; if an existing offers test helper exists, prefer it. Minimal version:
|
||||
|
||||
```ts
|
||||
import { createOffer, getOffer } from "../services/offers.service";
|
||||
import { prisma } from "../config/prisma"; // adjust to the project's prisma export path
|
||||
|
||||
describe("offers selected_custom_fields round-trip", () => {
|
||||
const created: number[] = [];
|
||||
afterAll(async () => {
|
||||
if (created.length)
|
||||
await prisma.quotations.deleteMany({ where: { id: { in: created } } });
|
||||
});
|
||||
|
||||
it("persists selection on create and decodes it on detail", async () => {
|
||||
const res = (await createOffer({
|
||||
status: "draft",
|
||||
selected_custom_fields: [2, 0, 0],
|
||||
})) as { id: number };
|
||||
created.push(res.id);
|
||||
|
||||
const row = await prisma.quotations.findUnique({ where: { id: res.id } });
|
||||
expect(row?.selected_custom_fields).toBe("[0,2]");
|
||||
|
||||
const detail = await getOffer(res.id);
|
||||
expect(detail?.selected_custom_fields).toEqual([0, 2]);
|
||||
});
|
||||
|
||||
it("stores null when selection is empty", async () => {
|
||||
const res = (await createOffer({
|
||||
status: "draft",
|
||||
selected_custom_fields: [],
|
||||
})) as { id: number };
|
||||
created.push(res.id);
|
||||
const row = await prisma.quotations.findUnique({ where: { id: res.id } });
|
||||
expect(row?.selected_custom_fields).toBeNull();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
> Before running: confirm the prisma import path (`../config/prisma` vs `../config/db` — grep an existing test). Adjust the import to match.
|
||||
|
||||
- [ ] **Step 8: Run tests**
|
||||
|
||||
Run: `npm test -- selected-custom-fields`
|
||||
Expected: PASS (util + offers round-trip). If FK constraints require a customer, the `customer_id`-less draft path above avoids them.
|
||||
|
||||
- [ ] **Step 9: Typecheck + commit**
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
git add src/services/offers.service.ts src/services/issued-orders.service.ts src/services/invoices.service.ts src/__tests__/selected-custom-fields.test.ts
|
||||
git commit -m "feat(documents): persist & expose selected_custom_fields in services"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: PDF rendering — filter company custom lines (TDD)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/routes/admin/offers-pdf.ts`
|
||||
- Modify: `src/routes/admin/issued-orders-pdf.ts`
|
||||
- Modify: `src/routes/admin/invoices-pdf.ts`
|
||||
- Test: `src/__tests__/selected-custom-fields.test.ts` (extend, if a PDF render is unit-testable; otherwise assert via the helper — see Step 6)
|
||||
|
||||
- [ ] **Step 1: Offers PDF — add the filter param to `buildAddressLines`**
|
||||
|
||||
In `src/routes/admin/offers-pdf.ts`, change the signature (line 28-32):
|
||||
|
||||
```ts
|
||||
function buildAddressLines(
|
||||
entity: Record<string, unknown> | null,
|
||||
isSupplier: boolean,
|
||||
t: (key: string) => string,
|
||||
selectedCustomFields?: number[],
|
||||
): AddressResult {
|
||||
```
|
||||
|
||||
Then change the custom-field loop (lines 88-96) to skip non-selected indices when a selection array is provided:
|
||||
|
||||
```ts
|
||||
const filterCustom = Array.isArray(selectedCustomFields);
|
||||
cfData.forEach((cf, i) => {
|
||||
if (filterCustom && !selectedCustomFields!.includes(i)) return;
|
||||
const cfName = (cf.name || "").trim();
|
||||
const cfValue = (cf.value || "").trim();
|
||||
const showLabel = cf.showLabel !== false;
|
||||
if (cfValue) {
|
||||
fieldMap[`custom_${i}`] =
|
||||
showLabel && cfName ? `${cfName}: ${cfValue}` : cfValue;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Offers PDF — pass the document's selection into the COMPANY call**
|
||||
|
||||
The offer's sender/company block is `supp` (`isSupplier: true` on `settings`). Update that call (lines 209-213) to pass the parsed selection; leave the customer call (`cust`) unchanged so customer custom fields still show in full:
|
||||
|
||||
```ts
|
||||
const supp = buildAddressLines(
|
||||
settings as unknown as Record<string, unknown>,
|
||||
true,
|
||||
t,
|
||||
parseSelectedCustomFields(
|
||||
(quotation as { selected_custom_fields?: unknown }).selected_custom_fields,
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
Add the import at the top of the file:
|
||||
|
||||
```ts
|
||||
import { parseSelectedCustomFields } from "../../utils/custom-fields";
|
||||
```
|
||||
|
||||
> Confirm `quotation` (the `OfferForPdf` payload the render function receives) is selected with the default field set so `selected_custom_fields` is present. It's a scalar column on `quotations`, so the default `findUnique`/`include` returns it — no `select` narrowing to adjust here.
|
||||
|
||||
- [ ] **Step 3: Issued-orders PDF — same change on the COMPANY (buyer) block**
|
||||
|
||||
In `src/routes/admin/issued-orders-pdf.ts`:
|
||||
|
||||
- Add `selectedCustomFields?: number[]` as the last param of `buildAddressLines` and apply the identical `filterCustom` guard in its custom-field loop.
|
||||
- The company block is `buyer = buildAddressLines(settings, true, t)` (line 316). Change to:
|
||||
```ts
|
||||
const buyer = buildAddressLines(
|
||||
settings,
|
||||
true,
|
||||
t,
|
||||
parseSelectedCustomFields(
|
||||
(order as { selected_custom_fields?: unknown }).selected_custom_fields,
|
||||
),
|
||||
);
|
||||
```
|
||||
- Leave `buildSupplierLines(...)` untouched (supplier fields keep showing in full).
|
||||
- Add `import { parseSelectedCustomFields } from "../../utils/custom-fields";`.
|
||||
|
||||
> Confirm the render function's `order` param carries `selected_custom_fields`. If the route fetches the order via a narrow `select`, add `selected_custom_fields: true` to it; if it uses `include`/default scalars, it's already present. Grep the route's `issued_orders.findUnique`/`findFirst` before assuming.
|
||||
|
||||
- [ ] **Step 4: Invoices PDF — same change on the COMPANY (supplier-of-invoice) block**
|
||||
|
||||
In `src/routes/admin/invoices-pdf.ts`:
|
||||
|
||||
- Add `selectedCustomFields?: number[]` as the last param of `buildAddressLines` and apply the identical `filterCustom` guard.
|
||||
- The company block is `supp = buildAddressLines(settings, true, t)` (line 457). Change to:
|
||||
```ts
|
||||
const supp = buildAddressLines(
|
||||
settings,
|
||||
true,
|
||||
t,
|
||||
parseSelectedCustomFields(
|
||||
(invoice as { selected_custom_fields?: unknown }).selected_custom_fields,
|
||||
),
|
||||
);
|
||||
```
|
||||
- Leave `cust = buildAddressLines(customer, false, t)` untouched.
|
||||
- Note the separate `settings.custom_fields` read lower down (the "supplier email/web" extraction near line 469) is a DIFFERENT concern (pulls an email for a header line) — **do not** filter that; leave it as-is.
|
||||
- Add `import { parseSelectedCustomFields } from "../../utils/custom-fields";`.
|
||||
|
||||
> Confirm `invoice` is fetched with default scalars (it is — `prisma.invoices.findUnique` without a narrowing `select` in this route), so `selected_custom_fields` is present.
|
||||
|
||||
- [ ] **Step 5: Typecheck + lint**
|
||||
|
||||
Run: `npm run typecheck && npm run lint`
|
||||
Expected: PASS, 0 lint errors.
|
||||
|
||||
- [ ] **Step 6: Add a focused render assertion (extend the test file)**
|
||||
|
||||
If the three PDF modules export their HTML render function (e.g. offers exports `renderOfferHtml`), add a test that renders with a stubbed settings object carrying two company custom fields and asserts only the selected one appears. Mock `html-to-pdf` per the suite convention; you're asserting on the returned HTML string, not a real PDF. Example for offers (adapt names to the actual export):
|
||||
|
||||
```ts
|
||||
import { renderOfferHtml } from "../routes/admin/offers-pdf"; // confirm export name
|
||||
|
||||
it("offer PDF prints only selected company custom fields", () => {
|
||||
const settings = {
|
||||
name: "Naše Firma s.r.o.",
|
||||
custom_fields: JSON.stringify({
|
||||
fields: [
|
||||
{ name: "Tel.", value: "123", showLabel: true },
|
||||
{ name: "Web", value: "example.cz", showLabel: true },
|
||||
],
|
||||
field_order: [],
|
||||
}),
|
||||
};
|
||||
const quotation = {
|
||||
customers: null,
|
||||
quotation_items: [],
|
||||
scope_sections: [],
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
selected_custom_fields: "[0]",
|
||||
};
|
||||
const html = renderOfferHtml(quotation as never, settings as never);
|
||||
expect(html).toContain("Tel.: 123");
|
||||
expect(html).not.toContain("example.cz");
|
||||
});
|
||||
```
|
||||
|
||||
If the render function is NOT exported / not unit-testable without a DB, SKIP this step rather than forcing it — the util test (Task 2) plus the service round-trip (Task 4) already cover the data path; note in the commit that PDF filtering was verified manually. Do not export internals solely to test them if that breaks the module's encapsulation; prefer a manual verification note.
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/routes/admin/offers-pdf.ts src/routes/admin/issued-orders-pdf.ts src/routes/admin/invoices-pdf.ts src/__tests__/selected-custom-fields.test.ts
|
||||
git commit -m "feat(documents): PDF prints only the document's selected company custom fields"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Frontend — detail query types + shared picker
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/admin/lib/queries/offers.ts`, `issued-orders.ts`, `invoices.ts`
|
||||
- Create: `src/admin/components/document/CustomFieldsPrintPicker.tsx`
|
||||
|
||||
- [ ] **Step 1: Add the field to the three detail interfaces**
|
||||
|
||||
- `src/admin/lib/queries/offers.ts` — add to `OfferDetailData`:
|
||||
```ts
|
||||
selected_custom_fields: number[];
|
||||
```
|
||||
- `src/admin/lib/queries/issued-orders.ts` — add to `IssuedOrderDetail`:
|
||||
```ts
|
||||
selected_custom_fields: number[];
|
||||
```
|
||||
- `src/admin/lib/queries/invoices.ts` — add to `InvoiceDetail`:
|
||||
|
||||
```ts
|
||||
selected_custom_fields?: number[];
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create the shared picker component**
|
||||
|
||||
Create `src/admin/components/document/CustomFieldsPrintPicker.tsx`:
|
||||
|
||||
```tsx
|
||||
import { FormControlLabel, Checkbox, Box, Typography } from "@mui/material";
|
||||
import type { CompanySettingsCustomField } from "../../lib/queries/settings";
|
||||
|
||||
interface Props {
|
||||
/** Company custom field definitions, in positional order (index = print key). */
|
||||
fields: CompanySettingsCustomField[];
|
||||
/** Currently selected positional indices. */
|
||||
selected: number[];
|
||||
/** Read-only (document not editable / locked by another user). */
|
||||
disabled?: boolean;
|
||||
onChange: (next: number[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-document picker: choose which COMPANY custom fields print on this
|
||||
* document's PDF. Selection is positional (matches the PDF `custom_<i>` keys).
|
||||
* Renders nothing when the company has defined no custom fields.
|
||||
*/
|
||||
export default function CustomFieldsPrintPicker({
|
||||
fields,
|
||||
selected,
|
||||
disabled = false,
|
||||
onChange,
|
||||
}: Props) {
|
||||
const printable = fields.filter((f) => (f.value || "").trim());
|
||||
if (printable.length === 0) return null;
|
||||
|
||||
const toggle = (idx: number, checked: boolean) => {
|
||||
const set = new Set(selected);
|
||||
if (checked) set.add(idx);
|
||||
else set.delete(idx);
|
||||
onChange([...set].sort((a, b) => a - b));
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
|
||||
Vlastní pole na PDF
|
||||
</Typography>
|
||||
{fields.map((f, idx) => {
|
||||
if (!(f.value || "").trim()) return null;
|
||||
const label = (f.name || "").trim() ? `${f.name}: ${f.value}` : f.value;
|
||||
return (
|
||||
<FormControlLabel
|
||||
key={idx}
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={selected.includes(idx)}
|
||||
disabled={disabled}
|
||||
onChange={(e) => toggle(idx, e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">{label}</Typography>}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
> Note: indices are keyed off the FULL `fields` array (not the filtered `printable`) so they stay aligned with the PDF's `custom_<i>`, which also enumerates the full array. Empty-value fields are skipped visually but still consume their index.
|
||||
|
||||
- [ ] **Step 3: Typecheck**
|
||||
|
||||
Run: `npm run typecheck`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/admin/lib/queries/offers.ts src/admin/lib/queries/issued-orders.ts src/admin/lib/queries/invoices.ts src/admin/components/document/CustomFieldsPrintPicker.tsx
|
||||
git commit -m "feat(documents): shared CustomFieldsPrintPicker + detail query types"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Frontend — wire the picker into the three detail pages
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: `src/admin/pages/OfferDetail.tsx`
|
||||
- Modify: `src/admin/pages/IssuedOrderDetail.tsx`
|
||||
- Modify: `src/admin/pages/InvoiceDetail.tsx`
|
||||
|
||||
For EACH page, the same four edits. Detail below uses OfferDetail; repeat the pattern for the other two (their company-settings query and edit-lock/editable flags already exist on the page — reuse them; do not add new queries).
|
||||
|
||||
- [ ] **Step 1: Import the picker (all three pages)**
|
||||
|
||||
```ts
|
||||
import CustomFieldsPrintPicker from "../components/document/CustomFieldsPrintPicker";
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Seed local state from the loaded document**
|
||||
|
||||
Add state near the page's other editable-field state, and seed it when the document loads (follow the page's existing seeding pattern — if it copies server data into state in an effect or on query success, add this alongside; if it derives form state via `useState` initializers keyed on the query, match that):
|
||||
|
||||
```ts
|
||||
const [selectedCustomFields, setSelectedCustomFields] = useState<number[]>([]);
|
||||
// when the detail query resolves (same place other fields are seeded):
|
||||
// setSelectedCustomFields(data.selected_custom_fields ?? []);
|
||||
```
|
||||
|
||||
Respect Rules of Hooks: declare this `useState` with the other hooks, before any early `return`.
|
||||
|
||||
- [ ] **Step 3: Render the picker in the editable header/meta area**
|
||||
|
||||
Place near the other document-level settings (currency/language). `companySettings` is already loaded on the page via `companySettingsOptions()`. Use the page's existing "is this document editable / not locked by another user" boolean for `disabled` (e.g. `!canEdit` or the locked flag the page already computes):
|
||||
|
||||
```tsx
|
||||
<CustomFieldsPrintPicker
|
||||
fields={companySettings?.custom_fields ?? []}
|
||||
selected={selectedCustomFields}
|
||||
disabled={!canEdit}
|
||||
onChange={setSelectedCustomFields}
|
||||
/>
|
||||
```
|
||||
|
||||
> Use whatever the page already calls its edit-gate (e.g. `canEdit`, `editable`, `isLockedByOther`). Do NOT invent a new permission — reuse the page's existing flag so the picker locks exactly when the rest of the form does.
|
||||
|
||||
- [ ] **Step 4: Include the selection in the save payload**
|
||||
|
||||
Find where the page builds its update/create payload (the object passed to the save mutation) and add:
|
||||
|
||||
```ts
|
||||
selected_custom_fields: selectedCustomFields,
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Repeat Steps 1-4 for `IssuedOrderDetail.tsx` and `InvoiceDetail.tsx`**
|
||||
|
||||
Same edits; the company-settings query, edit-gate flag, and save payload all already exist on each page.
|
||||
|
||||
- [ ] **Step 6: Typecheck + lint**
|
||||
|
||||
Run: `npm run typecheck && npm run lint`
|
||||
Expected: PASS, 0 lint errors (watch `react-hooks/rules-of-hooks` — the new `useState` must precede any early return).
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/admin/pages/OfferDetail.tsx src/admin/pages/IssuedOrderDetail.tsx src/admin/pages/InvoiceDetail.tsx
|
||||
git commit -m "feat(documents): per-document custom-field print picker on offer/issued-order/invoice detail"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Full verification
|
||||
|
||||
- [ ] **Step 1: Run the whole server suite**
|
||||
|
||||
Run: `npm test`
|
||||
Expected: PASS (no regressions; new selected-custom-fields cases green).
|
||||
|
||||
- [ ] **Step 2: Typecheck + lint + build**
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
npm run lint
|
||||
npm run build
|
||||
```
|
||||
|
||||
Expected: all PASS; client builds.
|
||||
|
||||
- [ ] **Step 3: Manual smoke (user-driven, dev server is theirs)**
|
||||
|
||||
Ask the user to: open an offer detail with company custom fields defined → tick one field → save → open its PDF and confirm only that field prints in the company block; confirm an untouched/older document prints no custom fields. Repeat for an issued order and an invoice.
|
||||
|
||||
- [ ] **Step 4: Final state check**
|
||||
|
||||
```bash
|
||||
git status
|
||||
git log --oneline -8
|
||||
```
|
||||
|
||||
Expected: clean tree, the feature commits present.
|
||||
|
||||
---
|
||||
|
||||
## Self-review notes (addressed)
|
||||
|
||||
- **Spec coverage:** storage column (T1), encode/decode (T2), schemas (T3), service persist+decode (T4), PDF filter (T5), frontend types+picker (T6), detail-page wiring (T7), tests throughout + full verify (T8). Order confirmations deliberately untouched. ✅
|
||||
- **Default = none:** `buildAddressLines` filters only when passed an array; the company call always passes the parsed selection (default `[]`), so nothing prints until ticked. Customer/supplier calls omit the param ⇒ unchanged. ✅
|
||||
- **Positional identity:** indices key off the full `fields` array on both render and picker sides (T5 note, T6 Step 2 note). ✅
|
||||
- **Type consistency:** `encodeSelectedCustomFields` / `parseSelectedCustomFields` used with identical signatures across services and PDF routes; detail interfaces expose `number[]`. ✅
|
||||
- **Open confirmations flagged inline** (prisma import path in tests; whether each PDF route narrows its document `select`) — each has a grep-first instruction rather than an assumption.
|
||||
770
docs/superpowers/specs/2026-05-29-warehouse-module-design.md
Normal file
770
docs/superpowers/specs/2026-05-29-warehouse-module-design.md
Normal file
@@ -0,0 +1,770 @@
|
||||
# Warehouse (Sklad) Module Design
|
||||
|
||||
**Date:** 2026-05-29
|
||||
**Status:** Approved
|
||||
**Module:** Warehouse/Inventory management for boha-app-ts
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Full warehouse management module under the Administration section. Tracks material receiving, issuing, reservations, inventory, and project assignment. Uses true FIFO with batch-level tracking, document-driven architecture (header + lines), and integrates with existing projects, number sequences, and NAS file storage.
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
### Movements
|
||||
|
||||
- **Receipt (Prijem):** Material enters warehouse. Multi-item document with delivery note attachment.
|
||||
- **Issue (Vydej):** Material leaves warehouse, mandatory project assignment. Multi-item document.
|
||||
- **Reservation:** Virtual hold on stock before issue. Reduces available qty but not physical stock. Issue consumes reservation.
|
||||
- **Inventory (Inventura):** Corrective movements based on physical count vs system count.
|
||||
- **Storno:** Cancel a confirmed receipt or issue. Creates opposite corrective movements, preserves audit trail.
|
||||
|
||||
### Catalog
|
||||
|
||||
- Each material has: catalog number, name, description, category, unit, min quantity.
|
||||
- Categories are user-defined (CRUD).
|
||||
- Units are fixed list: ks, m, kg, bal, sada, m2, m3, l.
|
||||
- Items can be soft-deactivated (is_active=false).
|
||||
|
||||
### Pricing
|
||||
|
||||
- Purchase price per unit, recorded bez DPH.
|
||||
- True FIFO: each receipt line creates a batch. Issues consume oldest batches first.
|
||||
- Batch-level tracking with remaining quantity.
|
||||
|
||||
### Delivery Notes
|
||||
|
||||
- File attachment (PDF/image) uploaded to NAS.
|
||||
- Delivery note number and date stored as metadata on receipt header.
|
||||
|
||||
### Suppliers
|
||||
|
||||
- Separate `sklad_suppliers` table (ICO, DIC, contact info).
|
||||
- Not shared with customers table.
|
||||
|
||||
### Locations
|
||||
|
||||
- Warehouse has named locations/shelves (code + name, e.g. "A1 - Regal A, police 1").
|
||||
- Junction table tracks qty per item per location.
|
||||
|
||||
### Projects
|
||||
|
||||
- Every issue is mandatory FK to `projects` table.
|
||||
- No free/issues without project assignment.
|
||||
|
||||
### Min Stock Alerts
|
||||
|
||||
- Each item has optional `min_quantity`.
|
||||
- Dashboard highlights items below minimum.
|
||||
- No email notification (UI alert only).
|
||||
|
||||
### Immutability
|
||||
|
||||
- All movements are immutable once confirmed.
|
||||
- Corrections via storno (cancel receipt/issue) which creates opposite movements.
|
||||
- Draft movements can be edited freely.
|
||||
|
||||
### Numbering
|
||||
|
||||
- Auto-numbering via `number_sequences` on confirm.
|
||||
- Types: `warehouse_receipt` (e.g. PRI-2026-001), `warehouse_issue` (e.g. VYD-2026-001).
|
||||
|
||||
### Issue Documents
|
||||
|
||||
- No PDF generation for issues. Record only in system.
|
||||
|
||||
### Reports
|
||||
|
||||
- Stock status: all items with qty, min_qty, value, below-min flag.
|
||||
- Project consumption: material consumed per project (filter by project, date range).
|
||||
- Movement log: all receipts + issues with filters.
|
||||
- Below minimum: items under min_quantity.
|
||||
|
||||
---
|
||||
|
||||
## Architecture: Document-Driven
|
||||
|
||||
Each movement type is a document (header + lines), matching the existing invoice/offer pattern.
|
||||
|
||||
### Document Flow
|
||||
|
||||
```
|
||||
DRAFT → CONFIRMED (affects stock)
|
||||
DRAFT → CANCELLED (no stock effect)
|
||||
CONFIRMED → CANCELLED (storno: reverses stock changes)
|
||||
```
|
||||
|
||||
Only CONFIRMED documents affect `sklad_batches`, `sklad_item_locations`, and reservations.
|
||||
|
||||
---
|
||||
|
||||
## Database Schema
|
||||
|
||||
### Enums
|
||||
|
||||
```prisma
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
### Master Data
|
||||
|
||||
```prisma
|
||||
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[]
|
||||
|
||||
@@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[]
|
||||
|
||||
@@index([category_id], map: "sklad_items_category_id")
|
||||
@@map("sklad_items")
|
||||
}
|
||||
```
|
||||
|
||||
### FIFO Batches & Location Tracking
|
||||
|
||||
```prisma
|
||||
model sklad_batches {
|
||||
id Int @id @default(autoincrement())
|
||||
item_id Int
|
||||
receipt_line_id Int
|
||||
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])
|
||||
|
||||
@@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")
|
||||
}
|
||||
```
|
||||
|
||||
### Receipts
|
||||
|
||||
```prisma
|
||||
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(fields: [received_by], references: [id])
|
||||
lines 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")
|
||||
}
|
||||
```
|
||||
|
||||
### Issues
|
||||
|
||||
```prisma
|
||||
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(fields: [issued_by], references: [id])
|
||||
lines 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")
|
||||
}
|
||||
```
|
||||
|
||||
### Reservations
|
||||
|
||||
```prisma
|
||||
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(fields: [reserved_by], references: [id])
|
||||
issue_lines sklad_issue_lines[]
|
||||
|
||||
@@index([item_id, status], map: "sklad_reservations_item_status")
|
||||
@@map("sklad_reservations")
|
||||
}
|
||||
```
|
||||
|
||||
### Inventory
|
||||
|
||||
```prisma
|
||||
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)
|
||||
|
||||
lines 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")
|
||||
}
|
||||
```
|
||||
|
||||
**Total: 13 models + 5 enums**
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
All under prefix `/api/admin/warehouse`.
|
||||
|
||||
### Items (warehouse.manage)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | ------------ | ------------------------------------------------------------- |
|
||||
| GET | `/items` | List items (paginated, filter by category, search, below-min) |
|
||||
| GET | `/items/:id` | Item detail with batches, locations, reservations |
|
||||
| POST | `/items` | Create item |
|
||||
| PUT | `/items/:id` | Update item |
|
||||
| DELETE | `/items/:id` | Soft-delete (is_active=false) |
|
||||
|
||||
### Categories (warehouse.manage)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | ----------------- | ------------------------- |
|
||||
| GET | `/categories` | List all |
|
||||
| POST | `/categories` | Create |
|
||||
| PUT | `/categories/:id` | Update |
|
||||
| DELETE | `/categories/:id` | Delete (only if no items) |
|
||||
|
||||
### Suppliers (warehouse.manage)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | ---------------- | ----------------------------- |
|
||||
| GET | `/suppliers` | List (paginated, search) |
|
||||
| GET | `/suppliers/:id` | Detail |
|
||||
| POST | `/suppliers` | Create |
|
||||
| PUT | `/suppliers/:id` | Update |
|
||||
| DELETE | `/suppliers/:id` | Soft-delete (is_active=false) |
|
||||
|
||||
### Locations (warehouse.manage)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | ---------------- | ------------------------------------- |
|
||||
| GET | `/locations` | List all |
|
||||
| POST | `/locations` | Create |
|
||||
| PUT | `/locations/:id` | Update |
|
||||
| DELETE | `/locations/:id` | Delete (only if no items at location) |
|
||||
|
||||
### Receipts (warehouse.operate)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | ----------------------------------------- | ------------------------------------------------------------- |
|
||||
| GET | `/receipts` | List (paginated, filter by status/supplier/date) |
|
||||
| GET | `/receipts/:id` | Detail with lines + attachments |
|
||||
| POST | `/receipts` | Create receipt (DRAFT, with lines) |
|
||||
| PUT | `/receipts/:id` | Update receipt + lines (DRAFT only) |
|
||||
| POST | `/receipts/:id/confirm` | Confirm: creates batches, updates locations, generates number |
|
||||
| POST | `/receipts/:id/cancel` | Cancel: storno batches if confirmed |
|
||||
| POST | `/receipts/:id/attachments` | Upload delivery note (multipart) |
|
||||
| DELETE | `/receipts/:id/attachments/:attachmentId` | Delete attachment |
|
||||
|
||||
### Issues (warehouse.operate)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | --------------------- | --------------------------------------------------------------------------------------- |
|
||||
| GET | `/issues` | List (paginated, filter by status/project/date) |
|
||||
| GET | `/issues/:id` | Detail with lines |
|
||||
| POST | `/issues` | Create issue (DRAFT, with lines) |
|
||||
| PUT | `/issues/:id` | Update issue + lines (DRAFT only) |
|
||||
| POST | `/issues/:id/confirm` | Confirm: decrements batches, updates locations, fulfills reservations, generates number |
|
||||
| POST | `/issues/:id/cancel` | Cancel: restores batch quantities if confirmed |
|
||||
|
||||
### Reservations (warehouse.operate)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | -------------------------- | ------------------------------------ |
|
||||
| GET | `/reservations` | List (filter by item/project/status) |
|
||||
| POST | `/reservations` | Create reservation |
|
||||
| POST | `/reservations/:id/cancel` | Cancel reservation |
|
||||
|
||||
### Inventory (warehouse.inventory)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | --------------------------------- | --------------------------------------- |
|
||||
| GET | `/inventory-sessions` | List sessions |
|
||||
| GET | `/inventory-sessions/:id` | Detail with lines |
|
||||
| POST | `/inventory-sessions` | Create session (system_qty auto-filled) |
|
||||
| PUT | `/inventory-sessions/:id` | Update lines (DRAFT only) |
|
||||
| POST | `/inventory-sessions/:id/confirm` | Confirm: creates corrective movements |
|
||||
|
||||
### Reports (warehouse.view)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | ------------------------------ | ---------------------------------------------------- |
|
||||
| GET | `/reports/stock-status` | All items with qty, min_qty, value, below-min flag |
|
||||
| GET | `/reports/project-consumption` | Material per project (filter by project, date range) |
|
||||
| GET | `/reports/movement-log` | All movements with filters |
|
||||
| GET | `/reports/below-minimum` | Items below min_quantity |
|
||||
|
||||
### Utility (warehouse.view)
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | -------------------------- | -------------------------------------- |
|
||||
| GET | `/items/:id/available-qty` | Available qty (total stock - reserved) |
|
||||
| GET | `/items/:id/batches` | FIFO batch queue for item |
|
||||
|
||||
---
|
||||
|
||||
## Business Logic
|
||||
|
||||
### Receipt Confirm (single Prisma transaction)
|
||||
|
||||
1. Validate status is DRAFT
|
||||
2. Generate `receipt_number` via `number_sequences` (type: `warehouse_receipt`)
|
||||
3. For each receipt line:
|
||||
- Create `sklad_batches` row (quantity = original_qty = line qty, unit_price from line, received_at = now)
|
||||
- Upsert `sklad_item_locations` (add qty to specified location)
|
||||
4. Update receipt status to CONFIRMED
|
||||
5. Log audit
|
||||
|
||||
### Receipt Cancel
|
||||
|
||||
**If DRAFT:** Set status to CANCELLED. No stock changes.
|
||||
|
||||
**If CONFIRMED (storno):**
|
||||
|
||||
1. Validate no issue lines have consumed batches from this receipt
|
||||
2. For each receipt line / batch:
|
||||
- If batch is fully consumed (is_consumed=true), reject cancellation
|
||||
- Decrement `sklad_item_locations` by batch remaining quantity
|
||||
- Delete the batch row
|
||||
3. Set receipt status to CANCELLED
|
||||
4. Log audit
|
||||
|
||||
### Issue Confirm (single Prisma transaction)
|
||||
|
||||
1. Validate status is DRAFT
|
||||
2. For each issue line, validate: batch has enough remaining quantity
|
||||
3. Generate `issue_number` via `number_sequences` (type: `warehouse_issue`)
|
||||
4. For each issue line:
|
||||
- Decrement `sklad_batches.quantity`, set `is_consumed=true` if 0
|
||||
- Decrement `sklad_item_locations.quantity`
|
||||
- If `reservation_id` set, decrement `sklad_reservations.remaining_qty`
|
||||
5. Check reservations: if remaining_qty = 0, set status to FULFILLED
|
||||
6. Update issue status to CONFIRMED
|
||||
7. Log audit
|
||||
|
||||
### Issue Cancel
|
||||
|
||||
**If DRAFT:** Set status to CANCELLED. No stock changes.
|
||||
|
||||
**If CONFIRMED (storno):**
|
||||
|
||||
1. For each issue line:
|
||||
- Increment `sklad_batches.quantity`, set `is_consumed=false` if was true
|
||||
- Increment `sklad_item_locations.quantity`
|
||||
- If `reservation_id` set, increment `sklad_reservations.remaining_qty`, set status back to ACTIVE if was FULFILLED
|
||||
2. Set issue status to CANCELLED
|
||||
3. Log audit
|
||||
|
||||
### Auto-FIFO on Issue Creation
|
||||
|
||||
When creating an issue line, if user doesn't pick a specific batch:
|
||||
|
||||
- Service selects oldest unconsumed batches for the item (via `sklad_batches_fifo` index)
|
||||
- May span multiple batches if quantity exceeds one batch's remaining qty
|
||||
- Frontend shows available batches for manual override
|
||||
|
||||
### Reservation Creation
|
||||
|
||||
1. Validate item exists and is_active
|
||||
2. Calculate available_qty = total stock qty - sum of active reservation quantities for this item
|
||||
3. Validate available_qty >= requested quantity
|
||||
4. Create reservation with quantity = remaining_qty
|
||||
5. Does NOT modify `sklad_batches` or `sklad_item_locations`
|
||||
|
||||
### Inventory Confirm (single Prisma transaction)
|
||||
|
||||
1. Validate status is DRAFT
|
||||
2. For each inventory line where difference != 0:
|
||||
- If difference > 0 (more stock than system): create a corrective receipt (type: inventory, auto-confirmed)
|
||||
- If difference < 0 (less stock than system): create a corrective issue (type: inventory, auto-confirmed)
|
||||
3. Generate `session_number` via `number_sequences` (type: `warehouse_inventory`)
|
||||
4. Set status to CONFIRMED
|
||||
5. Log audit
|
||||
|
||||
---
|
||||
|
||||
## Frontend
|
||||
|
||||
### Sidebar
|
||||
|
||||
Entry in `Sidebar.tsx` with permission `warehouse.view`:
|
||||
|
||||
- Icon: package/box icon
|
||||
- Label: "Sklad"
|
||||
- Path: `/warehouse`
|
||||
|
||||
### Pages (lazy-loaded)
|
||||
|
||||
| Route | Component | Permission |
|
||||
| ------------------------------ | ------------------------ | ------------------- |
|
||||
| `/warehouse` | Warehouse | warehouse.view |
|
||||
| `/warehouse/items` | WarehouseItems | warehouse.view |
|
||||
| `/warehouse/items/:id` | WarehouseItemDetail | warehouse.view |
|
||||
| `/warehouse/receipts` | WarehouseReceipts | warehouse.view |
|
||||
| `/warehouse/receipts/new` | WarehouseReceiptForm | warehouse.operate |
|
||||
| `/warehouse/receipts/:id` | WarehouseReceiptDetail | warehouse.view |
|
||||
| `/warehouse/receipts/:id/edit` | WarehouseReceiptForm | warehouse.operate |
|
||||
| `/warehouse/issues` | WarehouseIssues | warehouse.view |
|
||||
| `/warehouse/issues/new` | WarehouseIssueForm | warehouse.operate |
|
||||
| `/warehouse/issues/:id` | WarehouseIssueDetail | warehouse.view |
|
||||
| `/warehouse/issues/:id/edit` | WarehouseIssueForm | warehouse.operate |
|
||||
| `/warehouse/reservations` | WarehouseReservations | warehouse.view |
|
||||
| `/warehouse/inventory` | WarehouseInventory | warehouse.inventory |
|
||||
| `/warehouse/inventory/new` | WarehouseInventoryForm | warehouse.inventory |
|
||||
| `/warehouse/inventory/:id` | WarehouseInventoryDetail | warehouse.inventory |
|
||||
| `/warehouse/reports` | WarehouseReports | warehouse.view |
|
||||
| `/warehouse/suppliers` | WarehouseSuppliers | warehouse.manage |
|
||||
| `/warehouse/locations` | WarehouseLocations | warehouse.manage |
|
||||
| `/warehouse/categories` | WarehouseCategories | warehouse.manage |
|
||||
|
||||
### Warehouse Dashboard
|
||||
|
||||
- Summary cards: total items, total stock value, below-minimum count, active reservations
|
||||
- Below-minimum alert section (highlighted)
|
||||
- Recent movements (last 10)
|
||||
|
||||
### WarehouseReports
|
||||
|
||||
- Tab-based: Stock Status | Project Consumption | Movement Log | Below Minimum
|
||||
- Each tab has filters (date range, project, category, supplier)
|
||||
- Paginated data tables with sorting
|
||||
|
||||
### Key Shared Components
|
||||
|
||||
| Component | Purpose |
|
||||
| ---------------------- | ----------------------------------------------------------------------------- |
|
||||
| ItemPicker | Searchable item selector (name + catalog number), used in receipt/issue forms |
|
||||
| BatchPicker | FIFO batch selector for issue lines, shows available qty per batch |
|
||||
| LocationSelect | Location dropdown |
|
||||
| SupplierSelect | Supplier dropdown |
|
||||
| WarehouseMovementTable | Reusable multi-line editor for receipt/issue lines |
|
||||
|
||||
### Query Keys
|
||||
|
||||
```
|
||||
["warehouse"] -> invalidates all
|
||||
["warehouse", "items", filters] -> item list
|
||||
["warehouse", "items", id] -> item detail
|
||||
["warehouse", "receipts", filters] -> receipt list
|
||||
["warehouse", "receipts", id] -> receipt detail
|
||||
["warehouse", "issues", filters] -> issue list
|
||||
["warehouse", "issues", id] -> issue detail
|
||||
["warehouse", "reservations", filters] -> reservation list
|
||||
["warehouse", "inventory", filters] -> inventory sessions
|
||||
["warehouse", "inventory", id] -> inventory detail
|
||||
["warehouse", "suppliers", filters] -> supplier list
|
||||
["warehouse", "locations"] -> location list
|
||||
["warehouse", "categories"] -> category list
|
||||
["warehouse", "reports", type, filters] -> report data
|
||||
```
|
||||
|
||||
Mutation invalidation: broad `["warehouse"]` for any create/update/delete.
|
||||
|
||||
---
|
||||
|
||||
## Permissions
|
||||
|
||||
| Permission | Display Name | Module | Description |
|
||||
| --------------------- | -------------- | ------ | ------------------------------------------------------ |
|
||||
| `warehouse.view` | Zobrazit sklad | sklad | View stock status, items, reports, movement history |
|
||||
| `warehouse.operate` | Prijem a vydej | sklad | Create/confirm receipts, issues, reservations |
|
||||
| `warehouse.manage` | Sprava skladu | sklad | Manage items catalog, suppliers, locations, categories |
|
||||
| `warehouse.inventory` | Inventura | sklad | Create/confirm inventory sessions |
|
||||
|
||||
---
|
||||
|
||||
## Number Sequences
|
||||
|
||||
Three new types registered in `number_sequences`:
|
||||
|
||||
- `warehouse_receipt` - generated on receipt confirm
|
||||
- `warehouse_issue` - generated on issue confirm
|
||||
- `warehouse_inventory` - generated on inventory session confirm
|
||||
|
||||
Pattern configurable via `company_settings`, same as invoices.
|
||||
|
||||
---
|
||||
|
||||
## File Storage
|
||||
|
||||
Receipt attachments use existing `NasFinancialsManager`:
|
||||
|
||||
- Stored under `warehouse/YYYY/MM/` on NAS
|
||||
- DB metadata in `sklad_receipt_attachments` (file_name, file_mime, file_size, file_path)
|
||||
- Upload via `@fastify/multipart`
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
### New Files
|
||||
|
||||
```
|
||||
src/
|
||||
routes/admin/warehouse.ts
|
||||
services/warehouse.service.ts
|
||||
schemas/warehouse.schema.ts
|
||||
admin/
|
||||
pages/
|
||||
Warehouse.tsx
|
||||
WarehouseItems.tsx
|
||||
WarehouseItemDetail.tsx
|
||||
WarehouseReceipts.tsx
|
||||
WarehouseReceiptDetail.tsx
|
||||
WarehouseReceiptForm.tsx
|
||||
WarehouseIssues.tsx
|
||||
WarehouseIssueDetail.tsx
|
||||
WarehouseIssueForm.tsx
|
||||
WarehouseReservations.tsx
|
||||
WarehouseInventory.tsx
|
||||
WarehouseInventoryDetail.tsx
|
||||
WarehouseInventoryForm.tsx
|
||||
WarehouseReports.tsx
|
||||
WarehouseSuppliers.tsx
|
||||
WarehouseLocations.tsx
|
||||
WarehouseCategories.tsx
|
||||
lib/queries/warehouse.ts
|
||||
components/warehouse/
|
||||
ItemPicker.tsx
|
||||
BatchPicker.tsx
|
||||
LocationSelect.tsx
|
||||
SupplierSelect.tsx
|
||||
WarehouseMovementTable.tsx
|
||||
```
|
||||
|
||||
### Modified Files
|
||||
|
||||
| File | Change |
|
||||
| ---------------------------------- | ---------------------------------- |
|
||||
| `src/server.ts` | Import + register warehouse routes |
|
||||
| `src/types/index.ts` | Add 8 EntityType values |
|
||||
| `src/admin/AdminApp.tsx` | Lazy imports + routes |
|
||||
| `src/admin/components/Sidebar.tsx` | Add warehouse menu entry |
|
||||
| `prisma/schema.prisma` | Add 13 models + 5 enums |
|
||||
| `prisma/seed.ts` | Add 4 permissions |
|
||||
|
||||
---
|
||||
|
||||
## Audit Entity Types
|
||||
|
||||
New values added to `EntityType` union in `src/types/index.ts`:
|
||||
|
||||
- `warehouse_item`
|
||||
- `warehouse_receipt`
|
||||
- `warehouse_issue`
|
||||
- `warehouse_reservation`
|
||||
- `warehouse_inventory`
|
||||
- `warehouse_supplier`
|
||||
- `warehouse_category`
|
||||
- `warehouse_location`
|
||||
|
||||
---
|
||||
|
||||
## Constraints & Edge Cases
|
||||
|
||||
1. **Batch consumption on cancel:** If any batch from a receipt has been partially or fully consumed by an issue, the receipt cannot be cancelled. User must first cancel the consuming issues.
|
||||
|
||||
2. **Reservation availability:** Available qty = sum of active batch quantities - sum of active reservation quantities. Reservation creation validates available_qty >= requested.
|
||||
|
||||
3. **Location qty consistency:** `sklad_item_locations` is a denormalized cache for quick lookups. It must always stay in sync with `sklad_batches`. The confirm/cancel transactions maintain this.
|
||||
|
||||
4. **FIFO spanning batches:** When auto-FIFO selects batches for an issue line and the quantity spans multiple batches, the service creates **multiple issue lines** (one per batch consumed), all under the same issue document. The user's original requested quantity is preserved across the split lines. This works because each `sklad_issue_lines` row has exactly one `batch_id`.
|
||||
|
||||
5. **Inventory corrective movements:** On confirm, each line with a difference creates an auto-confirmed receipt or issue. The `notes` field of these corrective documents references the inventory session ID and line, so they can be traced back. These corrective documents are fully audited like manual receipts/issues.
|
||||
|
||||
6. **Unit consistency:** Once an item is created with a unit, it cannot be changed if any movements exist. This prevents unit mismatches in stock calculations.
|
||||
@@ -0,0 +1,191 @@
|
||||
# Manual project & order creation — design
|
||||
|
||||
Date: 2026-06-06
|
||||
Status: approved (pending spec review)
|
||||
Author: Claude + BOHA
|
||||
|
||||
## Problem
|
||||
|
||||
Today both entities are only ever _derived_ from a parent:
|
||||
|
||||
- A **project** is created solely as a side-effect of `createOrderFromQuotation`
|
||||
(`orders.service.ts`). There is **no** `POST /projects`, no `createProject`
|
||||
service, no `CreateProjectSchema`. A manual-create feature existed but was
|
||||
**removed in commit `82919d3`** (2026-04-28) — the note: _"Projects can only
|
||||
be created through orders (shared numbering sequence)."_ The old code pulled
|
||||
`project_number` from the shared order/project pool, which consumed an order
|
||||
number and left **gaps in order numbering**. That is the bug we must not repeat.
|
||||
- An **order** is normally created from an offer. A manual `createOrder`
|
||||
(`orders.service.ts`, offer-less) **already exists** and the route already
|
||||
dispatches to it, but there is **no UI**, and it does not create a project.
|
||||
|
||||
We want: (1) manually create projects on `/projects`, (2) manually create
|
||||
orders without an offer on `/orders`.
|
||||
|
||||
## Decisions (locked with the user)
|
||||
|
||||
1. **Project numbering: shared pool, _with_ proper tracking.** Standalone
|
||||
projects take the next **shared** number via `generateSharedNumber()` — the
|
||||
same pool as orders — but we add the tracking/transparency that was missing
|
||||
before (see "Tracking" below). Auto-assigned; no manual number entry.
|
||||
2. **Manual order → project: optional checkbox, default ON.** The order form
|
||||
has a pre-checked "Vytvořit propojený projekt"; when set, the order and its
|
||||
project share the order number (identical to the from-offer flow → no gap).
|
||||
3. **Order form scope: header only.** Customer, customer order number,
|
||||
currency/VAT, scope title/description, notes. No line-item editor.
|
||||
4. **Customer: optional** on both forms (matches the existing nullable schema).
|
||||
5. **Match existing house design** — `FormModal` + `FormField`, the
|
||||
`Vehicles.tsx` create/edit-modal pattern, the `OffersCustomers.tsx`
|
||||
header-button + customer-selector pattern, existing list/badge styling.
|
||||
|
||||
## Why the shared pool is safe here (the tracking)
|
||||
|
||||
The shared sequence is effectively a single "zakázkové číslo" pool. An order and
|
||||
its project share one number; a standalone project simply takes the next number
|
||||
in that pool and has no order. The mechanics that make this coherent:
|
||||
|
||||
- **Collision-safe:** `isSharedNumberTaken()` already checks **both**
|
||||
`orders.order_number` and `projects.project_number`, so the same number can
|
||||
never be issued twice across the pool (`numbering.service.ts:161-167`).
|
||||
- **Atomic:** `createProject` wraps `generateSharedNumber(tx)` in
|
||||
`prisma.$transaction` — the existing `SELECT … FOR UPDATE` lock
|
||||
(`getNextSequence`) serialises concurrent consumers.
|
||||
- **Release on delete:** `deleteProject` already calls `releaseSharedNumber`,
|
||||
which decrements the sequence only if the deleted number is the current
|
||||
highest — so deleting a standalone project doesn't leave a permanent tail-gap
|
||||
(`numbering.service.ts:116-158, 319-328`).
|
||||
- **Audit trail:** `logAudit` on create/delete records the number in
|
||||
`newValues`/`oldValues`, so every consumed pool number has a "who/when/what"
|
||||
trail showing it went to a project (not a lost order).
|
||||
- **UI transparency:** the Projects list shows a badge — **"z objednávky"**
|
||||
(order-linked, `order_id != null`) vs **"samostatný"** (standalone) — so a
|
||||
pool number with no order reads as intentional. The create form previews the
|
||||
number it is about to assign (`previewSharedNumber()`).
|
||||
|
||||
## Part A — Manual projects
|
||||
|
||||
### Backend
|
||||
|
||||
- **`src/schemas/projects.schema.ts`** — add `CreateProjectSchema`
|
||||
(`z.strictObject`, shared coercers from `schemas/common.ts`, Czech messages):
|
||||
- `name` — required, `z.string().min(1)`.
|
||||
- `customer_id` — optional number (coerced, NaN-guarded).
|
||||
- `responsible_user_id` — optional number.
|
||||
- `status` — optional, default `"aktivni"`.
|
||||
- `start_date`, `end_date` — optional date strings.
|
||||
- `notes` — optional string.
|
||||
- **No** `project_number` field (auto-assigned from the pool).
|
||||
- **`src/services/projects.service.ts`** — add `createProject(data)`:
|
||||
- `prisma.$transaction(async (tx) => …)`: `project_number = await
|
||||
generateSharedNumber(tx)`; `tx.projects.create({ … order_id: null,
|
||||
quotation_id: null, status: data.status ?? "aktivni", … })`.
|
||||
- Validate `customer_id` / `responsible_user_id` exist (when provided) →
|
||||
return `{ error, status: 400 }` (Czech) if not.
|
||||
- After commit: `nasFileManager.createProjectFolder(number, name)` when
|
||||
`isConfigured()` — non-fatal, logged on failure (mirrors the old code).
|
||||
- Return `{ data: project }` (or `{ error, status }`).
|
||||
- **`src/routes/admin/projects.ts`**:
|
||||
- `POST /` guarded by `requirePermission("projects.create")` →
|
||||
`parseBody(CreateProjectSchema, …)` → `createProject` → `logAudit`
|
||||
(`action: "create"`, `entityType: "project"`, `newValues`) →
|
||||
`success(reply, project, 201, "Projekt vytvořen")`.
|
||||
- `GET /next-number` guarded by `projects.create` → `previewSharedNumber()` →
|
||||
`success(reply, { number })`. (Preview only; does not consume.)
|
||||
|
||||
### Frontend (`src/admin/pages/Projects.tsx` + new modal)
|
||||
|
||||
- Header **"Přidat projekt"** button, gated on `hasPermission("projects.create")`,
|
||||
matching the `OffersCustomers.tsx` "Přidat zákazníka" header-button pattern.
|
||||
- A project create `FormModal` (house pattern from `Vehicles.tsx`): `FormField`
|
||||
rows for name (required), customer (select from customers list), responsible
|
||||
user (select from `userListOptions`), status, start/end dates, notes, plus a
|
||||
read-only "Číslo projektu: `<preview>` (přiděleno automaticky)" line fetched
|
||||
from `GET /projects/next-number` when the modal opens.
|
||||
- `useApiMutation` POST `/api/admin/projects`; on success invalidate
|
||||
**`["projects"]`** (broad domain key, per the invalidation convention) and
|
||||
close modal; surface server errors via `useAlert`.
|
||||
- List: add the **"z objednávky" / "samostatný"** badge (derive from
|
||||
`order_id`). Update the empty-state text (currently "Projekt se vytvoří
|
||||
automaticky při vytvoření objednávky") to mention manual creation.
|
||||
|
||||
## Part B — Manual orders (header only, optional project)
|
||||
|
||||
### Backend
|
||||
|
||||
- **`src/schemas/orders.schema.ts`** — add `create_project` to
|
||||
`CreateOrderSchema`: boolean via the existing `preprocess(v => v === true || v
|
||||
=== 1 || v === "1")` idiom, `.optional().default(true)`. (Only the manual path
|
||||
uses this schema; the from-quotation path uses `CreateOrderFromQuotationSchema`.)
|
||||
- **`src/services/orders.service.ts` `createOrder`** — inside the existing
|
||||
transaction, after the order is created, when `body.create_project` is true and
|
||||
there is no quotation link: `tx.projects.create({ project_number: orderNumber,
|
||||
order_id: order.id, customer_id: order.customer_id, name: scope_title ??
|
||||
customer_order_number ?? orderNumber, status: "aktivni" })` — mirrors
|
||||
`createOrderFromQuotation`'s project block, so order + project share the number.
|
||||
Return the project id so the route can audit it.
|
||||
- **`src/routes/admin/orders.ts`** — the manual `POST /` branch already exists
|
||||
(`orders.create`); add a second `logAudit` for the created project when present.
|
||||
|
||||
### Frontend (`src/admin/pages/Orders.tsx` + new modal)
|
||||
|
||||
- Header **"Vytvořit objednávku"** button, gated on `orders.create`.
|
||||
- Header-only `FormModal`: customer (select), customer order number, currency,
|
||||
VAT rate + apply-VAT, language, scope title, scope description, notes, and a
|
||||
pre-checked **"Vytvořit propojený projekt"** checkbox. Read-only next
|
||||
order-number preview via the existing `GET /api/admin/orders/next-number`.
|
||||
- POST `/api/admin/orders` (no `quotationId`); on success invalidate
|
||||
**`["orders"]`** and **`["projects"]`**; errors via `useAlert`.
|
||||
|
||||
## Part C — Permissions
|
||||
|
||||
`projects.create` was removed from the permission set and must come back the
|
||||
**migration** way (per CLAUDE.md — never seed-only for prod data):
|
||||
|
||||
- New migration `prisma/migrations/<ts>_add_projects_create_permission/` that
|
||||
`INSERT`s the `projects.create` permission row and grants it to the **admin**
|
||||
role (mirror `20260603230000_add_warehouse_permissions/migration.sql`). Use
|
||||
`INSERT … ON DUPLICATE KEY UPDATE` / `INSERT IGNORE` style so re-runs are safe.
|
||||
- Add `projects.create` to the `PERMISSIONS` array in `prisma/seed.ts` (dev).
|
||||
- `orders.create` already exists — no change.
|
||||
|
||||
## Part D — Tests (`src/__tests__/`)
|
||||
|
||||
Real-DB Vitest (no Prisma mocks), following `numbering.test.ts` style:
|
||||
|
||||
- `createProject` assigns the next shared number, increments the `shared`
|
||||
sequence by exactly 1, sets `order_id = null`, writes an audit row.
|
||||
- `createOrder` with `create_project: true` creates an order **and** a project
|
||||
sharing one `order_number`/`project_number`.
|
||||
- Interleaved coherence: order → standalone project → order produces three
|
||||
consecutive shared numbers with no duplicates (the tracking guarantee).
|
||||
- `createOrder` with `create_project: false` creates only the order.
|
||||
|
||||
## Error handling
|
||||
|
||||
- Service returns `{ error, status }` (Czech) for bad customer/user FK and
|
||||
numbering exhaustion (the `generateSharedNumber` 100-retry throw → mapped to a
|
||||
500 with a Czech message by the route, logged via `app.log.error`).
|
||||
- NAS folder creation is non-fatal and logged (never blocks creation).
|
||||
|
||||
## Out of scope (v1) — noted for later
|
||||
|
||||
- Editing order line-items after creation.
|
||||
- Attaching a standalone project to an order later (conflicts with current
|
||||
`order_id` immutability + the `has_order` delete guard).
|
||||
- Manual project-number override (user chose auto-from-pool).
|
||||
- A unified order+project number lookup/search.
|
||||
|
||||
## Affected files (summary)
|
||||
|
||||
- `src/schemas/projects.schema.ts` (add `CreateProjectSchema`)
|
||||
- `src/schemas/orders.schema.ts` (add `create_project`)
|
||||
- `src/services/projects.service.ts` (add `createProject`)
|
||||
- `src/services/orders.service.ts` (`createOrder` optional project)
|
||||
- `src/routes/admin/projects.ts` (`POST /`, `GET /next-number`)
|
||||
- `src/routes/admin/orders.ts` (audit project on manual order)
|
||||
- `src/admin/pages/Projects.tsx` (+ create modal, badge, empty-state)
|
||||
- `src/admin/pages/Orders.tsx` (+ create modal)
|
||||
- `src/admin/lib/queries/projects.ts`, `orders.ts` (mutations/preview queries)
|
||||
- `prisma/migrations/<ts>_add_projects_create_permission/migration.sql`
|
||||
- `prisma/seed.ts` (+ `projects.create`)
|
||||
- `src/__tests__/manual-create.test.ts` (new)
|
||||
@@ -0,0 +1,191 @@
|
||||
# Plan Categories Management — Design Spec
|
||||
|
||||
Date: 2026-06-06
|
||||
Status: Approved (approach A)
|
||||
Area: Work Plan (`/plan-work`)
|
||||
|
||||
## Goal
|
||||
|
||||
Let managers (`attendance.manage`) **create, rename, recolor, and retire** the
|
||||
categories used by the work plan, via a "Správa kategorií" button above the
|
||||
calendar that opens a form modal with a per-category color picker. Categories
|
||||
become data, not a hardcoded enum.
|
||||
|
||||
## Current state (what's hardcoded today)
|
||||
|
||||
- DB: `plan_category` **enum** (`work, preparation, travel, leave, sick,
|
||||
training, other`) used by `work_plan_entries.category` and
|
||||
`work_plan_overrides.category` (both `NOT NULL`).
|
||||
- Validation: `planCategoryEnum` in `src/schemas/plan.schema.ts`.
|
||||
- Frontend labels: `PLAN_CATEGORIES` / `planCategoryLabel` in
|
||||
`src/admin/lib/queries/plan.ts`.
|
||||
- Colors: per-category CSS variables `--plan-tape-<key>` in `src/admin/plan.css`,
|
||||
applied via `.plan-cell:has(.plan-chip--<key>)::before` (left "tape" bar) and
|
||||
`.plan-chip--<key>` (chip text/border/background via `color-mix`). 14 rules.
|
||||
- Server audit: `PLAN_CATEGORY_LABELS_CS` in `src/utils/planAuditDescription.ts`.
|
||||
- A decorative paper-grain gradient (`plan.css` ~lines 102–107) tints the page
|
||||
background with `--plan-tape-work` / `--plan-tape-training` at 5%. This is
|
||||
cosmetic and **not** category-semantic.
|
||||
|
||||
## Approach (A)
|
||||
|
||||
Introduce a `plan_categories` table. Keep the entry/override `category` column
|
||||
as a **string key** (slug) referencing `plan_categories.key`. Change the column
|
||||
type from the enum to `VARCHAR(50)`; existing values are preserved verbatim.
|
||||
"Remove" means **deactivate** (`is_active = false`), never hard-delete, so
|
||||
historical entries keep resolving their label and color.
|
||||
|
||||
Rejected: a real FK `category_id` (needs per-row backfill + read/write churn for
|
||||
no user-visible benefit); keeping the enum (can't add categories).
|
||||
|
||||
## Data model
|
||||
|
||||
New table `plan_categories`:
|
||||
|
||||
| column | type | notes |
|
||||
| ---------- | ------------ | -------------------------------------------- |
|
||||
| id | INT PK AI | |
|
||||
| key | VARCHAR(50) | UNIQUE, slug, immutable after create |
|
||||
| label | VARCHAR(100) | Czech display name, editable |
|
||||
| color | VARCHAR(7) | `#RRGGBB` |
|
||||
| sort_order | INT | display order; new categories append (max+1) |
|
||||
| is_active | BOOLEAN | default true; false = retired |
|
||||
| created_at | DATETIME | default now |
|
||||
| updated_at | DATETIME | auto |
|
||||
|
||||
Column change: `work_plan_entries.category` and `work_plan_overrides.category`
|
||||
`plan_category` → `VARCHAR(50) NOT NULL`. Drop the `plan_category` enum from the
|
||||
Prisma schema once no column uses it.
|
||||
|
||||
## Migration (one tracked Prisma migration)
|
||||
|
||||
`npx prisma migrate dev --name plan_categories` (requires dev server stopped —
|
||||
ask the user first per CLAUDE.md). The generated `migration.sql` will:
|
||||
|
||||
1. `CREATE TABLE plan_categories (...)`.
|
||||
2. `ALTER` the two `category` columns enum → `VARCHAR(50)`.
|
||||
3. `INSERT` the 7 seed rows (so production gets them — not seed-only, per the
|
||||
migration policy). Seed values (key, label, color, sort_order):
|
||||
|
||||
| key | label | color | sort |
|
||||
| ----------- | -------------- | ------- | ---- |
|
||||
| work | Práce | #2563eb | 1 |
|
||||
| preparation | Příprava | #0d9488 | 2 |
|
||||
| travel | Cesta / Montáž | #ca8a04 | 3 |
|
||||
| leave | Dovolená | #16a34a | 4 |
|
||||
| sick | Nemoc | #dc2626 | 5 |
|
||||
| training | Školení | #7c3aed | 6 |
|
||||
| other | Jiné | #6b7280 | 7 |
|
||||
|
||||
After: `npx prisma generate`, commit schema + migration folder.
|
||||
|
||||
## API — `/api/admin/plan/categories`
|
||||
|
||||
All under the existing plan route file group.
|
||||
|
||||
- `GET /` — returns **all** categories (active + inactive), ordered by
|
||||
`sort_order, id`. Readable by `attendance.record` OR `attendance.manage`
|
||||
(every grid viewer needs labels/colors, including for retired categories on
|
||||
historical entries).
|
||||
- `POST /` — create. `attendance.manage`. Body: `{ label, color }`. `key` is
|
||||
auto-slugged from `label` (ASCII, lowercased, deduped); `sort_order = max+1`.
|
||||
- `PATCH /:id` — update `label` / `color` / `is_active`. `attendance.manage`.
|
||||
`key` is immutable.
|
||||
- `DELETE /:id` — deactivate (`is_active = false`). `attendance.manage`.
|
||||
|
||||
Service layer: `src/services/planCategory.service.ts` (plain async functions,
|
||||
`{ data }` / `{ error, status }` envelope). Audit-logged via `logAudit` with a
|
||||
new entity type `plan_category` (add to `EntityType` and the AuditLog +
|
||||
dashboard `ENTITY_TYPE_LABELS` maps, e.g. "Plán prací – kategorie").
|
||||
|
||||
Validation (`src/schemas/plan.schema.ts` or a new `planCategory.schema.ts`):
|
||||
|
||||
- `label`: required, 1–100 chars, trimmed.
|
||||
- `color`: regex `^#[0-9a-fA-F]{6}$`.
|
||||
- `is_active`: boolean (PATCH only).
|
||||
- Entry/override create/update: `category` becomes `z.string().min(1)`; the
|
||||
**service** validates the key exists and `is_active` (reject unknown/inactive
|
||||
with a Czech 400).
|
||||
|
||||
## Validation rules / edge cases
|
||||
|
||||
- **Slug collision:** if the slug derived from a new label already exists,
|
||||
append `-2`, `-3`, … Keys are never shown to users.
|
||||
- **At least one active category:** deactivating the last active category is
|
||||
rejected (Czech 400) so the create form is never empty.
|
||||
- **Deactivate in use:** allowed. Existing entries keep their key; the category
|
||||
still renders (GET returns inactive ones) but is hidden from the create
|
||||
`<select>`.
|
||||
- **Rename/recolor:** applies to all entries with that key (reference is by
|
||||
key) — this is the desired "recolor everywhere" behavior.
|
||||
- **No hard delete** in this iteration (deactivate only). Possible later
|
||||
enhancement: allow hard-delete when zero entries reference the key.
|
||||
|
||||
## Frontend
|
||||
|
||||
- **Button** "Správa kategorií" in `PlanWork.tsx` header, rendered only when
|
||||
`hasPermission("attendance.manage")`.
|
||||
- **Modal** (`PlanCategoriesModal.tsx`, uses `FormModal`): a row per category =
|
||||
`label` text input + native `<input type="color">` swatch + active toggle (or
|
||||
a "retire/restore" control), plus an "add category" row (label + color +
|
||||
add). Mutations invalidate `["plan", "categories"]` **and** `["plan"]` (so the
|
||||
grid recolors) and `["dashboard"]`/`["audit-log"]` (audit feed).
|
||||
- **Category query** `["plan","categories"]` loaded in `PlanWork`, passed to the
|
||||
grid and cell modal. The create/edit plan `<select>` lists **active**
|
||||
categories from this query (replacing hardcoded `PLAN_CATEGORIES`); display
|
||||
uses the **full** map (so retired categories still render).
|
||||
- `planCategoryLabel` becomes a lookup into the categories map (with raw-key
|
||||
fallback). `PLAN_CATEGORIES` constant is removed.
|
||||
|
||||
## Color rendering (the notable refactor)
|
||||
|
||||
Replace the 14 hardcoded per-key rules with a generic, custom-property-driven
|
||||
treatment:
|
||||
|
||||
- `PlanGrid` sets `style={{ "--cat-color": color }}` on the `.plan-cell`
|
||||
`<button>` when the cell has a category (`color` from the categories map). The
|
||||
custom property cascades to the chip and is available to the cell's `::before`
|
||||
tape.
|
||||
- `plan.css`:
|
||||
- `.plan-cell::before` tape uses
|
||||
`background: var(--cat-color, var(--plan-tape-other))` — the graphite
|
||||
`#6b7280` is the defensive neutral fallback when a cell has no category
|
||||
color (replaces the seven `:has(.plan-chip--<key>)::before` rules).
|
||||
- `.plan-chip` (generic) uses `color: var(--cat-color)`,
|
||||
`border-color: color-mix(in srgb, var(--cat-color) 35%, transparent)`,
|
||||
`background: color-mix(in srgb, var(--cat-color) 10%, var(--plan-paper))`
|
||||
(replaces the seven `.plan-chip--<key>` rules).
|
||||
- Visual output is identical for the existing 7; new categories work with no CSS
|
||||
changes.
|
||||
- The decorative paper-grain gradient stays static (keep two literal colors or
|
||||
the two `--plan-tape-*` vars it needs); it is not category-semantic.
|
||||
|
||||
## Audit description
|
||||
|
||||
`src/services/plan.service.ts` builds the audit description with the category
|
||||
label. Since labels now live in the DB, resolve the label from `plan_categories`
|
||||
by key (alongside the existing `resolvePlanLabels` lookups) and pass the plain
|
||||
label into `buildPlanAuditDescription`. `src/utils/planAuditDescription.ts`'s
|
||||
`buildPlanAuditDescription` stays pure (receives the resolved label);
|
||||
`PLAN_CATEGORY_LABELS_CS`/`planCategoryLabel` there are removed or reduced to a
|
||||
fallback.
|
||||
|
||||
## Testing
|
||||
|
||||
Vitest (real DB, per project convention):
|
||||
|
||||
- `planCategory.service` CRUD: create (slug generation, sort_order), update
|
||||
(label/color/active), deactivate, and the "last active category" guard.
|
||||
- Color/label validation rejects bad hex and empty label.
|
||||
- Entry create accepts an active key and rejects an unknown/inactive key.
|
||||
|
||||
## Out of scope (YAGNI)
|
||||
|
||||
- Per-category icons.
|
||||
- Drag-to-reorder (order by `sort_order, id`; new categories append).
|
||||
- Hard delete of unused categories (deactivate only).
|
||||
|
||||
## Assumptions to confirm
|
||||
|
||||
- "Remove" = deactivate (history preserved). ✅ implied by approach A.
|
||||
- Native browser color picker (`<input type="color">`), not a custom palette.
|
||||
190
docs/superpowers/specs/2026-06-08-ai-assistant-phase1-design.md
Normal file
190
docs/superpowers/specs/2026-06-08-ai-assistant-phase1-design.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# Design — AI assistant, Phase 1 (chat + invoice import + budget cap)
|
||||
|
||||
**Date:** 2026-06-08
|
||||
**Status:** Approved (brainstorming) — ready for implementation plan
|
||||
**Phase 1 of 2.** Phase 2 (the AI querying system data via read-tools) is a separate later cycle — see "Deferred: Phase 2" at the end.
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Add the app's first AI capability: an **admin-only chat assistant embedded on the
|
||||
dashboard** where you can talk to Claude and, crucially, **attach received-invoice
|
||||
PDFs that the AI reads and imports into Přijaté faktury** (extract → you confirm →
|
||||
save). All AI usage is bounded by an **admin-editable monthly budget (default
|
||||
$50)** that hard-stops calls when exhausted.
|
||||
|
||||
## Decisions (locked in brainstorming)
|
||||
|
||||
- **Scope (Phase 1):** chat + invoice import + budget cap. **No system-data
|
||||
access** (the AI cannot query your invoices/projects/attendance — that's Phase 2).
|
||||
- **Placement:** a `DashAssistant` widget on the **dashboard, at the top under the
|
||||
welcome text** — not a separate page, not a floating bubble.
|
||||
- **Access:** **admins only**, via a new `ai.use` permission.
|
||||
- **Model:** **Claude Sonnet 4.6** (strong vision, low cost).
|
||||
- **Save flow:** extract → **you confirm/edit → save** (never silent auto-save).
|
||||
- **Budget:** **$50/month**, resets each calendar month, **admin-editable in
|
||||
Settings**; AI calls are **blocked** once the month's spend reaches the budget.
|
||||
- **Chat:** **non-streaming** (request → full reply) and **in-browser history
|
||||
only** (not persisted server-side) for v1 — both are easy later upgrades.
|
||||
|
||||
## Non-goals / out of scope (Phase 1)
|
||||
|
||||
- No system-data query tools / function-calling (Phase 2).
|
||||
- No server-side conversation persistence, no streaming.
|
||||
- No new invoice storage path — reuses `POST /received-invoices` verbatim.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
Greenfield AI integration; the rest of the app is unaffected and works unchanged
|
||||
if `ANTHROPIC_API_KEY` is absent (the assistant widget simply doesn't render and
|
||||
the AI routes return a clear "not configured" error).
|
||||
|
||||
- **Dependency:** `@anthropic-ai/sdk`.
|
||||
- **Env:** `ANTHROPIC_API_KEY` (required for the feature). Optional
|
||||
`AI_MONTHLY_BUDGET_USD` default seed (the live value lives in the DB, below).
|
||||
- **`src/services/ai.service.ts`** — wraps the SDK, owns the model choice + system
|
||||
prompt + cost accounting. Two operations:
|
||||
- `chat(messages)` → `client.messages.create({ model: "claude-sonnet-4-6", … })`,
|
||||
non-streaming, returns `{ reply: string, usage }`.
|
||||
- `extractInvoice(pdfBuffer, fileName)` → `client.messages.create` with the PDF as
|
||||
a `document` content block + `output_config.format` JSON-schema for the
|
||||
received-invoice fields, returns `{ fields, usage }`.
|
||||
- Both call the spend tracker to record usage **and** are gated by the budget
|
||||
guard (below) BEFORE the API call.
|
||||
- Isolated so tests can stub the Anthropic call (no real API in CI).
|
||||
|
||||
## Spend cap (the $50/month budget)
|
||||
|
||||
- **New table `ai_usage`** (migration): `id`, `user_id?`, `kind` ("chat" |
|
||||
"extract"), `model`, `input_tokens`, `output_tokens`, `cost_usd`
|
||||
`@db.Decimal(10,6)`, `created_at @db.Timestamp(0)`, with an index on
|
||||
`created_at`.
|
||||
- **Cost map** (in `ai.service.ts`): model → `{ inputPerToken, outputPerToken }`.
|
||||
Sonnet 4.6 = $3 / $15 per 1M → `0.000003` / `0.000015` per token. `cost_usd =
|
||||
in*inP + out*outP`.
|
||||
- **Budget value:** a new `ai_monthly_budget_usd Decimal @default(50)` column on
|
||||
`company_settings` (the existing app-config singleton). Admin-editable in
|
||||
Settings.
|
||||
- **Budget guard `assertBudgetAvailable()`:** sum `cost_usd` for rows where
|
||||
`created_at >= startOfMonth(now)`; if `>= ai_monthly_budget_usd`, return
|
||||
`{ error: "Měsíční rozpočet AI byl vyčerpán", status: 402 }`. Called at the top
|
||||
of every AI route BEFORE the Claude call.
|
||||
- **Usage read:** `GET /api/admin/ai/usage` → `{ month_spend_usd, budget_usd,
|
||||
remaining_usd }` for the chat's budget indicator and the Settings page.
|
||||
|
||||
## Backend routes — `src/routes/admin/ai.ts`
|
||||
|
||||
All guarded by `requirePermission("ai.use")`.
|
||||
|
||||
- `POST /api/admin/ai/chat` — body `{ messages: {role, content}[] }`. Budget guard →
|
||||
`ai.service.chat` → log usage → `success(reply: string, remaining_usd)`.
|
||||
- `POST /api/admin/ai/extract-invoices` — multipart PDF files (≤ `MAX_UPLOAD_SIZE`,
|
||||
PDF/image only). Budget guard → `extractInvoice` per file → returns the extracted
|
||||
fields per file (NOT saved) + usage. The files are **not** persisted here.
|
||||
- `GET /api/admin/ai/usage` — current-month spend + budget + remaining.
|
||||
|
||||
If `ANTHROPIC_API_KEY` is unset, the POST routes return
|
||||
`{ error: "AI není nakonfigurováno", status: 503 }`.
|
||||
|
||||
## Invoice import flow (extract → confirm → save)
|
||||
|
||||
1. Admin attaches one or more invoice PDFs in the dashboard chat (optionally with a
|
||||
text note).
|
||||
2. Frontend posts the files to `POST /ai/extract-invoices`; the AI returns the
|
||||
extracted fields for each.
|
||||
3. The chat renders an **editable review card per invoice** (dodavatel, číslo
|
||||
faktury, částka, měna, sazba DPH, datum vystavení/splatnosti, poznámka),
|
||||
pre-filled with the AI's values, plus a duplicate hint if `invoice_number` +
|
||||
`supplier_name` already exists.
|
||||
4. Admin glances/edits → **"Uložit"** (per card) or **"Uložit vše"**.
|
||||
5. The frontend submits **the original File + the confirmed metadata** to the
|
||||
**existing `POST /api/admin/received-invoices`** (multipart) — same NAS storage,
|
||||
same server-side VAT recompute, same audit. The AI never writes invoices
|
||||
directly. (The PDF is uploaded twice — once to extract, once to save — which is
|
||||
fine for invoice-sized files and avoids any server-side temp-file handling.)
|
||||
|
||||
## Frontend
|
||||
|
||||
- **`src/admin/components/dashboard/DashAssistant.tsx`** — the chat widget:
|
||||
message list, input box, attach-file button, and a small budget indicator
|
||||
("Rozpočet: $X.XX / $50"). Non-streaming; conversation in component state only.
|
||||
Renders the invoice review cards inline (reusing the received-invoice field
|
||||
inputs / kit components).
|
||||
- **`src/admin/pages/Dashboard.tsx`** — render `<DashAssistant />` at the top,
|
||||
directly under the welcome text, **only when** the user is admin / has `ai.use`
|
||||
(and only when AI is configured — a `GET /ai/usage` 503 hides it gracefully).
|
||||
- **`src/admin/lib/queries/ai.ts`** — React Query options/mutations for chat,
|
||||
extract, and usage. On a successful invoice save, invalidate `["received-invoices"]`.
|
||||
- **Settings** — an admin field to set the monthly budget (writes
|
||||
`company_settings.ai_monthly_budget_usd`).
|
||||
|
||||
## Permissions & migration
|
||||
|
||||
One Prisma migration:
|
||||
|
||||
- Create `ai_usage` table.
|
||||
- Add `ai_monthly_budget_usd` to `company_settings` (default 50).
|
||||
- Insert the `ai.use` permission and grant it to the **admin** role (explicit
|
||||
`INSERT`s in `migration.sql`, per the project's migration policy).
|
||||
|
||||
(The admin role bypasses permission checks via `roleName === "admin"`, but the
|
||||
explicit `ai.use` permission lets the access be widened later without code changes
|
||||
and documents intent.)
|
||||
|
||||
## Security / privacy
|
||||
|
||||
- **Phase 1 has no tools**, so the AI cannot take actions on your data — its only
|
||||
effect is the human-confirmed invoice save. A malicious/auto-generated invoice
|
||||
PDF therefore can't trigger anything (the injection-to-action surface arrives in
|
||||
Phase 2 and is designed there).
|
||||
- Attached PDFs are sent to the Anthropic API to be read. The API key lives in
|
||||
`.env` (server-side only), never exposed to the browser.
|
||||
- Standard sanitization already applies on the received-invoice render/PDF paths;
|
||||
AI-extracted text flows through the same validated `received_invoices` create.
|
||||
|
||||
## Testing
|
||||
|
||||
Server-side, real test DB, **Anthropic call stubbed** (no real API in CI):
|
||||
|
||||
- **Spend tracker:** `cost_usd` computed correctly from tokens for Sonnet 4.6;
|
||||
monthly sum only counts the current month.
|
||||
- **Budget guard:** under budget → allowed; at/over budget → `402` with the Czech
|
||||
message; the guard reads the DB budget value.
|
||||
- **Permissions:** all `/ai/*` routes return `403` without `ai.use`.
|
||||
- **Not-configured:** with no `ANTHROPIC_API_KEY`, POST routes return `503`.
|
||||
- **extract field-mapping:** given a stubbed AI response, the route returns the
|
||||
expected `received_invoices` field shape (and computes nothing that the existing
|
||||
create doesn't already).
|
||||
|
||||
Frontend has no component-test harness → gated by `tsc -b` + `build` + a manual
|
||||
check (the dashboard widget renders for admins, hidden otherwise).
|
||||
|
||||
Gates: `npx tsc -b --noEmit`, `npm run build`, `npx vitest run`.
|
||||
|
||||
## Rollout
|
||||
|
||||
Ships as **v2.1.0** (notable new capability) via the standard process. **Requires a
|
||||
migration**, so the dev server must be stopped for `prisma migrate dev` (ask first),
|
||||
and the release runs `prisma migrate deploy` on prod. `ANTHROPIC_API_KEY` must be
|
||||
set in the production `.env` before the feature works.
|
||||
|
||||
---
|
||||
|
||||
## Deferred: Phase 2 (system-data access) — captured
|
||||
|
||||
A later, separate spec + cycle. The AI gains **read-only tools** (function calling)
|
||||
to answer questions about your data — e.g. "co je po splatnosti?", "kolik jsme
|
||||
fakturovali v květnu?". Key design work for Phase 2:
|
||||
|
||||
- A curated set of **read tools** (search invoices, overdue list, project lookup,
|
||||
attendance summary, …), each **scoped to the calling user's permissions** so the
|
||||
AI never returns data the user can't see.
|
||||
- The **agentic tool-loop** (Claude requests a tool → app executes against Prisma →
|
||||
returns results → Claude continues), with a per-conversation tool-call cap to
|
||||
bound cost (within the same monthly budget).
|
||||
- **Prompt-injection hardening:** because the AI will both read untrusted invoice
|
||||
content _and_ hold tools, tools stay **read-only**, results are treated as data,
|
||||
and any state-changing action remains human-confirmed.
|
||||
218
docs/superpowers/specs/2026-06-08-odin-conversations-design.md
Normal file
218
docs/superpowers/specs/2026-06-08-odin-conversations-design.md
Normal file
@@ -0,0 +1,218 @@
|
||||
# Odin — Multi-Conversation AI Chat — Design
|
||||
|
||||
**Date:** 2026-06-08
|
||||
**Status:** Approved (design), pending spec review
|
||||
|
||||
## Goal
|
||||
|
||||
Replace the single-thread Odin assistant with a multi-conversation chat: a
|
||||
purpose-built UI on the `/odin` page where the user keeps several named
|
||||
conversations (like topics), switches between them via top tabs, and can
|
||||
rename or delete them. All existing assistant capabilities (chat, PDF invoice
|
||||
extraction → review → save, monthly budget) carry over unchanged.
|
||||
|
||||
## Background (current state)
|
||||
|
||||
- `ai_chat_messages` is a single rolling thread per user (`user_id, role,
|
||||
content, created_at`). Endpoints `GET/POST/DELETE /api/admin/ai/history`
|
||||
read/append/clear that one thread.
|
||||
- The chat lives in `DashAssistant.tsx`, rendered on the `/odin` page (moved
|
||||
off the dashboard in the prior change, branch `feat/odin-page`).
|
||||
- Stateless AI endpoints (`/chat`, `/extract-invoices`, `/usage`, `/budget`)
|
||||
are unaffected by conversations — they don't persist anything themselves.
|
||||
|
||||
## Decisions (from brainstorming)
|
||||
|
||||
- **Titling:** new conversation auto-titles from its first user message; user
|
||||
can rename.
|
||||
- **Per-conversation actions:** rename + delete.
|
||||
- **Existing history:** migrate the current single thread into one conversation
|
||||
per user ("keep as first conversation"); nothing is lost.
|
||||
- **Layout:** top tabs + chat (not a left sidebar).
|
||||
|
||||
## Data model
|
||||
|
||||
### `ai_conversations` (new)
|
||||
|
||||
| column | type | notes |
|
||||
| ---------- | --------------------- | ----------------------------------- |
|
||||
| id | INT PK AUTO_INCREMENT | |
|
||||
| user_id | INT NOT NULL | owner; isolation key |
|
||||
| title | VARCHAR(255) NOT NULL | default "Nová konverzace" |
|
||||
| created_at | TIMESTAMP(0) NOT NULL | default CURRENT_TIMESTAMP |
|
||||
| updated_at | TIMESTAMP(0) NOT NULL | bumped on each append; sort/recency |
|
||||
|
||||
Index: `idx_ai_conv_user (user_id, id)`.
|
||||
|
||||
### `ai_chat_messages` (modified)
|
||||
|
||||
- Add `conversation_id INT NOT NULL` (FK → `ai_conversations(id)` `ON DELETE
|
||||
CASCADE`). Keep `user_id` (denormalized, harmless; simplifies cleanup).
|
||||
- Replace index `idx_ai_chat_user (user_id, id)` with
|
||||
`idx_ai_chat_conv (conversation_id, id)` (messages are read per conversation).
|
||||
|
||||
### Prisma
|
||||
|
||||
```prisma
|
||||
model ai_conversations {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
title String @db.VarChar(255)
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime @default(now()) @updatedAt @db.Timestamp(0)
|
||||
messages ai_chat_messages[]
|
||||
|
||||
@@index([user_id, id], map: "idx_ai_conv_user")
|
||||
}
|
||||
|
||||
model ai_chat_messages {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
conversation_id Int
|
||||
role String @db.VarChar(20)
|
||||
content String @db.Text
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
conversation ai_conversations @relation(fields: [conversation_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([conversation_id, id], map: "idx_ai_chat_conv")
|
||||
}
|
||||
```
|
||||
|
||||
### Migration (hand-written SQL; one tracked migration)
|
||||
|
||||
1. `CREATE TABLE ai_conversations (...)`.
|
||||
2. `ALTER TABLE ai_chat_messages ADD COLUMN conversation_id INT NULL AFTER user_id`.
|
||||
3. Backfill one conversation per user who has messages:
|
||||
`INSERT INTO ai_conversations (user_id, title, created_at, updated_at)
|
||||
SELECT user_id, 'Konverzace', NOW(), NOW() FROM ai_chat_messages GROUP BY user_id;`
|
||||
4. Point messages at it:
|
||||
`UPDATE ai_chat_messages m JOIN ai_conversations c ON c.user_id = m.user_id
|
||||
SET m.conversation_id = c.id;`
|
||||
5. Drop the old index, enforce NOT NULL, add the FK + new index:
|
||||
`ALTER TABLE ai_chat_messages DROP INDEX idx_ai_chat_user,
|
||||
MODIFY conversation_id INT NOT NULL,
|
||||
ADD CONSTRAINT fk_ai_chat_conv FOREIGN KEY (conversation_id)
|
||||
REFERENCES ai_conversations(id) ON DELETE CASCADE,
|
||||
ADD INDEX idx_ai_chat_conv (conversation_id, id);`
|
||||
|
||||
The backfill is a no-op when `ai_chat_messages` is empty (prod today), and
|
||||
preserves the dev thread.
|
||||
|
||||
## Service layer (`ai.service.ts`)
|
||||
|
||||
Replace the single-thread helpers (`getChatHistory` / `appendChatMessages` /
|
||||
`clearChatHistory`) with conversation-scoped ones. Every function takes
|
||||
`userId` and verifies the conversation belongs to the user.
|
||||
|
||||
- `listConversations(userId)` → `{id, title, updated_at}[]`, ordered by `id` asc
|
||||
(stable tab order).
|
||||
- `createConversation(userId, title?)` → the new conversation (default title
|
||||
"Nová konverzace").
|
||||
- `getConversation(userId, id)` → conversation or null (ownership check helper).
|
||||
- `getConversationMessages(userId, id)` → `StoredChatMessage[]` oldest→newest,
|
||||
or `{ error, status }` if not owned/found.
|
||||
- `appendConversationMessages(userId, id, msgs)` → append; **bump `updated_at`**;
|
||||
**auto-title**: if the conversation's title is still the default and this batch
|
||||
has a user message, set `title` = first ~60 chars of that user message.
|
||||
- `renameConversation(userId, id, title)` / `deleteConversation(userId, id)` —
|
||||
ownership-checked; delete cascades messages.
|
||||
|
||||
Auto-title keeps titling server-side and robust (no client title logic).
|
||||
|
||||
## Routes (`routes/admin/ai.ts`, all `requirePermission("ai.use")`)
|
||||
|
||||
| Method | Path | Body / result |
|
||||
| ------ | ----------------------------- | ------------------------------------------ |
|
||||
| GET | `/conversations` | → `{ conversations: [...] }` |
|
||||
| POST | `/conversations` | `{ title? }` → `{ conversation }` |
|
||||
| GET | `/conversations/:id/messages` | → `{ messages: [...] }` (404 if not owned) |
|
||||
| POST | `/conversations/:id/messages` | `{ messages:[{role,content}] }` (1..20) |
|
||||
| PATCH | `/conversations/:id` | `{ title }` (1..255) |
|
||||
| DELETE | `/conversations/:id` | → `{ ok: true }` |
|
||||
|
||||
`:id` parsed via `parseId`; bodies via `parseBody`; ownership 404 from the
|
||||
service surfaced with `error(reply, ...)`. The old `/history` routes are removed.
|
||||
`/chat`, `/extract-invoices`, `/usage`, `/budget` are unchanged.
|
||||
|
||||
## Frontend
|
||||
|
||||
### Queries (`lib/queries/ai.ts`)
|
||||
|
||||
- `aiConversationsOptions()` → `["ai","conversations"]`, `GET /conversations`.
|
||||
- `aiConversationMessagesOptions(id)` → `["ai","conversation",id,"messages"]`,
|
||||
`GET /conversations/:id/messages`, `gcTime: 0` (each mount re-reads the DB,
|
||||
same rationale as today: no stale-cache resurrection).
|
||||
- Types: `Conversation { id, title, updated_at }`, reuse `StoredChatMessage`.
|
||||
|
||||
### Components (`src/admin/components/odin/`)
|
||||
|
||||
- **`OdinChat.tsx`** — orchestrator. Owns: active conversation id, input, busy,
|
||||
staged attachments, review list. Loads the conversation list; ensures one
|
||||
exists (creates a default if the user has none); loads the active thread;
|
||||
routes send/extract/save through the active conversation. Full-height flex
|
||||
layout: header → tabs → thread (flex-grow, scroll) → review → composer.
|
||||
- **`OdinTabs.tsx`** — horizontally-scrollable tabs (one per conversation) +
|
||||
a "+" new-chat button + a ⋮ menu on the active tab (Přejmenovat / Smazat).
|
||||
Rename uses a small Modal with a text field; delete uses ConfirmDialog.
|
||||
- **`OdinThread.tsx`** — message list with an Odin avatar on assistant turns,
|
||||
user turns right-aligned; the "Pracuji…" indicator; empty-state greeting.
|
||||
(Message text colour set on the `Typography` — GlobalStyles pins `p` to
|
||||
text.secondary.)
|
||||
- **`InvoiceReviewCard.tsx`** — the editable extract card (supplier, number,
|
||||
Částka s DPH, měna, sazba, dates, popis) + Uložit / Zahodit.
|
||||
- **`OdinComposer.tsx`** — staged-attachment chips + attach button + message
|
||||
field (Enter to send) + send button; disabled until the active thread loads.
|
||||
|
||||
`DashAssistant.tsx` is deleted; `pages/Odin.tsx` renders `OdinChat`.
|
||||
|
||||
### Data flow
|
||||
|
||||
1. Mount → load `aiConversationsOptions`. If empty, `POST /conversations` to
|
||||
create a default and select it; else select the first (or last-active).
|
||||
2. Selecting a tab sets the active id → `aiConversationMessagesOptions(id)`
|
||||
loads that thread into the displayed turns (seed-once per id; submit marks
|
||||
the thread live so a late load can't clobber — same guard as today).
|
||||
3. **Send (chat):** optimistic user turn → `POST /chat` → append assistant
|
||||
reply → `POST /conversations/:id/messages` persists both → bump usage. On
|
||||
error: roll back, keep input.
|
||||
4. **Send (attachments):** `POST /extract-invoices` → review cards →
|
||||
client-side summary turn → persist the user+summary turns. Save a card →
|
||||
`POST /received-invoices` (gross/VAT-inclusive, unchanged).
|
||||
5. **New / rename / delete** → mutations that invalidate `["ai","conversations"]`
|
||||
(and reset the active id appropriately on delete).
|
||||
|
||||
### Reuse
|
||||
|
||||
All proven logic carries over verbatim: staged-attach (no auto-send), the three
|
||||
bug fixes (no clear-on-error, rollback dangling turn, stable ids — `nextUid`,
|
||||
NOT `crypto.randomUUID`), the model-context trimming (last 20, leading-user),
|
||||
budget indicator, gross/VAT save. The only structural change is "one thread" →
|
||||
"active conversation thread", plus the tab/CRUD shell.
|
||||
|
||||
## Error handling
|
||||
|
||||
- Ownership: service returns `{ error: "Konverzace nenalezena", status: 404 }`
|
||||
for a conversation the user doesn't own; routes surface it. No cross-user read
|
||||
or write is possible (every query filters by `user_id`).
|
||||
- Persistence is best-effort and logged (never swallowed), as today.
|
||||
- Auto-create-default and create/rename/delete failures surface a Czech toast.
|
||||
|
||||
## Testing
|
||||
|
||||
Backend (Vitest, real DB):
|
||||
|
||||
- Conversation CRUD: create → list → rename → delete (cascade removes messages).
|
||||
- **Isolation:** user A cannot read/append/rename/delete user B's conversation
|
||||
(404), and `listConversations(A)` excludes B's.
|
||||
- Append: ordering oldest→newest; `updated_at` bumps; **auto-title** sets the
|
||||
title from the first user message and does not overwrite a renamed title.
|
||||
- HTTP: routes 403 without `ai.use`; 404 for a foreign/:id; 400 on bad body.
|
||||
|
||||
Frontend: no component tests (consistent with the codebase); gated by
|
||||
`tsc -b` + `npm run build`. Live verification by the user/controller.
|
||||
|
||||
## Out of scope (Phase 2+)
|
||||
|
||||
- Querying system data inside chat (the original deferred Phase-2 scope).
|
||||
- Conversation search, pinning, folders, sharing.
|
||||
- Streaming responses.
|
||||
@@ -0,0 +1,49 @@
|
||||
# Odin → General Assistant (Phase 2+) — Forward-Looking Notes
|
||||
|
||||
**Date:** 2026-06-08 · **Status:** NOT scheduled — design notes only, recorded so Phase 1 choices don't box us in.
|
||||
|
||||
The vision: Odin grows from "chat + invoice import" into a **general assistant** that can **query system data** (invoices, projects, attendance, vehicles…) and **take actions** (create an order, mark paid, draft a quote…). This note assesses whether the Phase-1 architecture supports that, and what to carry forward deliberately.
|
||||
|
||||
## Bottom line
|
||||
|
||||
Phase 1 sets us up well; it does **not** box us in. Two things to carry forward on purpose:
|
||||
|
||||
1. **Structured message storage** (content blocks, not a plain string) — cheap to plan now, costly to retrofit later.
|
||||
2. **The assistant acts strictly as the authenticated user** — every tool runs through the existing permission/ownership layer.
|
||||
|
||||
Everything else (conversations, budget/usage, thin services) is already pointing the right way.
|
||||
|
||||
## What Phase 1 already gets right
|
||||
|
||||
- **Conversations** — multi-turn, persisted, per-user, isolated. Exactly the context substrate an agent needs.
|
||||
- **Budget + usage tracking + `ai.use` gate** — the cost/access spine. Tool loops spend more, so this matters _more_, not less.
|
||||
- **Thin service layer** (`{ data } | { error, status }`, ownership-checked) — ideal to wrap as tools without rewriting business logic.
|
||||
- **The extract → review → save flow** — a perfect template for "propose action → human confirms → execute." The `canSave`/`invoices.create` gate added in Phase 1 is the one-tool version of per-action authorization.
|
||||
|
||||
## The one schema thing to note now
|
||||
|
||||
`ai_chat_messages.content` is a **plain string**. Tool use requires persisting **content blocks** (`text` + `tool_use` + `tool_result`), because the model must see the full tool-call history to continue. When Phase 2 lands, store the **raw content-block array** (JSON column, e.g. `content_json`/`blocks`) and keep a derived plain-text for display/search. Don't change it now — just design Phase 2 persistence as "store the blocks," treating the current string as a lossy projection.
|
||||
|
||||
## The core shift (Phase 2)
|
||||
|
||||
1. **Tool use over the existing services.** Define tools (`list_invoices`, `get_project`, `create_order`, …) whose handlers call the **same service functions the routes use**. The SDK tool-runner loops; we execute. Reuses all validation/business logic and — critically — permissions.
|
||||
2. **Authorization is the hard part.** Every tool MUST run **as the user**, through `requirePermission` / service ownership checks. The assistant must never do what the user can't. It is the user's _delegate_, not a privileged actor.
|
||||
3. **Read vs write.** Read/query tools may run autonomously. Write/destructive tools **propose → confirm → execute** (generalize the invoice review card into a generic "action card"). Aligns with the assistant safety rules (confirm side-effecting actions).
|
||||
4. **Audit.** Every action the assistant takes should `logAudit` like a manual action, attributed to the user with a marker (e.g. `via: "odin"`), for a real trail.
|
||||
5. **Cost.** Tool loops are multi-round-trip → 3–10× the tokens of a chat turn. The $50 cap bites faster; consider per-conversation cost display and per-action budget re-checks (the inter-file budget re-check in `extract-invoices` is the pattern).
|
||||
|
||||
## Data access: tools-over-services, NOT RAG
|
||||
|
||||
Recommendation: **function-calling against the real services**, not embeddings/RAG. The data is structured, live, and permissioned — tools give correct, current, authorized answers. RAG over a snapshot would be stale, would leak across permission boundaries, and would duplicate logic. Reserve embeddings for genuinely unstructured document search if it ever comes up.
|
||||
|
||||
## Other forward notes
|
||||
|
||||
- **Model / effort:** a true agentic assistant wants a stronger model and possibly `effort` tuning; Phase-1 Sonnet single-shot is right for now.
|
||||
- **Streaming:** multi-step tool use feels slow without it — add SSE when Phase 2 lands.
|
||||
- **System prompt:** describe the user's role + available tools + the confirm-before-write rule.
|
||||
- **Managed Agents vs self-hosted loop:** Anthropic's Managed Agents host the loop, but for a self-hosted business app with our own services + permissions, **Claude API + tool use with a self-hosted loop** is the better fit — authorization stays in our stack.
|
||||
|
||||
## What NOT to do prematurely
|
||||
|
||||
- Don't add a tool framework, embeddings, or streaming now — Phase 1 is plain chat + a fixed-prompt extractor, and that's the right scope.
|
||||
- Don't widen `ai.use` to non-admins until the per-action authorization story (point 2) is in place.
|
||||
383
docs/superpowers/specs/2026-06-09-issued-orders-design.md
Normal file
383
docs/superpowers/specs/2026-06-09-issued-orders-design.md
Normal file
@@ -0,0 +1,383 @@
|
||||
# Objednávky vydané (Issued Purchase Orders) — Design Spec
|
||||
|
||||
**Date:** 2026-06-09
|
||||
**Status:** Approved (brainstorm) → ready for implementation plan
|
||||
**Author:** brainstorm session
|
||||
|
||||
> **Updated 2026-06-09 (as-built):** Shipped with three deviations from this
|
||||
> brainstorm — **Vydané-first tabs** (Vydané | Přijaté, mirroring Invoices), a
|
||||
> **shared chevron month/year filter** above the tabs that filters both lists,
|
||||
> and a PDF **rebuilt on the shared invoice/order-confirmation template** rather
|
||||
> than the custom layout sketched below. See the affected sections (UI placement,
|
||||
> PDF export, Frontend) and the plan's "Post-plan consistency pass" note.
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Add a new document type — **objednávky vydané** (purchase orders you issue to a
|
||||
supplier) — alongside the existing customer orders. You author the PO with line
|
||||
items, it gets an auto-generated number, you track its status, and you export it
|
||||
to PDF to send to the supplier. The existing orders module becomes the
|
||||
**přijaté** (customer-order) side of a two-tab UI, mirroring how the Invoices
|
||||
page already splits **Vydané | Přijaté**.
|
||||
|
||||
## Non-goals (v1)
|
||||
|
||||
- **No cross-module wiring.** A PO does **not** link to warehouse goods receipts
|
||||
(`sklad_receipts`) or to received invoices (`faktury přijaté`). The full
|
||||
procurement loop (ordered → received → invoiced) is a deliberate later phase.
|
||||
- **No new supplier master.** POs reuse the existing `customers` table as generic
|
||||
business partners.
|
||||
- **No NAS persistence of the PO PDF** in v1 (generated on demand only).
|
||||
- **No "scope sections"** (the CZ/EN rich-text blocks orders/quotations carry).
|
||||
- **No AI/Odin authoring.** POs are authored by hand; Odin extraction is a
|
||||
received-document concept and does not apply to documents you create.
|
||||
|
||||
---
|
||||
|
||||
## Decisions log (resolved during brainstorm)
|
||||
|
||||
1. **Direction mapping.** Today's `orders` (status default `prijata`, flowing
|
||||
quotation → order → project → invoice) stay as the **Přijaté** side, largely
|
||||
unchanged — only surfaced under a new tab. The new **Vydané** side is a
|
||||
brand-new document type. _(Not a `direction` flag on the existing table.)_
|
||||
2. **Supplier source.** A PO references the existing **`customers`** table (FK),
|
||||
used as a generic business partner. No new supplier/vendor master.
|
||||
3. **Linkage.** **Standalone document** in v1. No automatic links to warehouse or
|
||||
received invoices.
|
||||
4. **UI placement.** **Tabs on the Orders page**, mirroring the Invoices page.
|
||||
_(As-built: **Vydané first / Přijaté second** — `Vydané | Přijaté`, tab values
|
||||
`vydane`/`prijate`, persisted in `?tab=` — matching the Invoices page order. A
|
||||
shared **chevron month/year selector** sits above the tabs and filters BOTH
|
||||
lists: Vydané by `order_date`, Přijaté by `created_at`. The pre-existing Přijaté
|
||||
search bug — search term sent but ignored by the backend — was also fixed.)_
|
||||
5. **Model shape.** A **dedicated `issued_orders` + `issued_order_items`** pair,
|
||||
mirroring `invoices`/`invoice_items` — _not_ an extension of `orders` and _not_
|
||||
an upload-only record like `received_invoices`.
|
||||
6. **VAT regime.** **NET base + VAT-on-top** (the _issued-invoice_ convention),
|
||||
the **opposite** of `received_invoices` (which are gross/VAT-inclusive). Totals
|
||||
use the same per-line-rounded math as `computeInvoiceTotals`.
|
||||
7. **Numbering.** A **dedicated** `number_sequences` type (`"issued_order"`),
|
||||
separate from the `"shared"` orders/projects pool and from `"invoice"`. Number
|
||||
assigned **at creation** (even for a `draft`), with release-on-delete.
|
||||
8. **Permissions.** **Reuse the existing `orders.*` set** (`view`/`create`/`edit`/
|
||||
`delete`) plus `orders.export` for the PDF — mirrors invoices sharing one
|
||||
permission set across both tabs; **no permission migration needed**.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
A self-contained vertical slice following the codebase's established document
|
||||
pattern (the same shape `invoices` uses):
|
||||
|
||||
```
|
||||
prisma/schema.prisma → models issued_orders, issued_order_items + enum
|
||||
src/schemas/issued-orders.schema.ts
|
||||
src/services/issued-orders.service.ts
|
||||
src/services/numbering.service.ts (extend: issued-order number fns)
|
||||
src/routes/admin/issued-orders.ts (register in routes/admin/index.ts)
|
||||
src/routes/admin/issued-orders-pdf.ts (PDF route, modeled on invoices-pdf.ts)
|
||||
src/admin/pages/Orders.tsx (add Přijaté | Vydané tabs)
|
||||
src/admin/pages/IssuedOrderDetail.tsx (create/edit form + PDF export)
|
||||
src/admin/lib/queries/issued-orders.ts
|
||||
src/admin/lib/entityTypeLabels.ts (add "issued_order" Czech label)
|
||||
src/admin/AdminApp.tsx (lazy routes for detail/new)
|
||||
src/__tests__/issued-orders.test.ts
|
||||
```
|
||||
|
||||
**Tech stack:** Fastify 5, Prisma 7 (MySQL), Zod 4, React 19 + MUI v7, React
|
||||
Query, Puppeteer (PDF), Vitest. All new code follows the audited conventions
|
||||
(success/error helpers, `parseBody`/`parseId`, shared Zod coercers, broad query
|
||||
invalidation, deterministic ordering with an `id` tiebreak, locked
|
||||
read-modify-write for numbering).
|
||||
|
||||
---
|
||||
|
||||
## Data model
|
||||
|
||||
### `issued_orders` (parallels `invoices`)
|
||||
|
||||
| Field | Type | Notes |
|
||||
| ---------------- | -------------------------------------------------- | ------------------------------------------- |
|
||||
| `id` | Int PK autoincrement | |
|
||||
| `po_number` | VARCHAR(50) unique | auto-assigned (see Numbering) |
|
||||
| `customer_id` | Int FK → `customers` (onDelete Restrict, nullable) | the **supplier/partner** being ordered from |
|
||||
| `status` | enum `issued_orders_status` | default `draft` |
|
||||
| `currency` | VARCHAR(10) default `"CZK"` | |
|
||||
| `vat_rate` | Decimal(5,2) default `21.00` | doc-level default rate |
|
||||
| `apply_vat` | Boolean default `true` | |
|
||||
| `exchange_rate` | Decimal(12,4) nullable | foreign-currency, like orders |
|
||||
| `order_date` | Date | date the PO is issued |
|
||||
| `delivery_date` | Date nullable | requested delivery / required-by |
|
||||
| `language` | VARCHAR(5) default `"cs"` | drives PDF language |
|
||||
| `delivery_terms` | VARCHAR(500) nullable | optional, shown on PDF |
|
||||
| `payment_terms` | VARCHAR(500) nullable | optional, shown on PDF |
|
||||
| `issued_by` | VARCHAR(255) nullable | signatory name |
|
||||
| `notes` | Text nullable | rich text, **rendered on PDF** (sanitized) |
|
||||
| `internal_notes` | Text nullable | private, **not** on PDF |
|
||||
| `created_at` | DateTime default now | |
|
||||
| `modified_at` | DateTime @updatedAt | |
|
||||
|
||||
**Relations:** `issued_order_items[]`, `customers?`.
|
||||
**Indexes:** `(customer_id)`, `(status, order_date)`.
|
||||
|
||||
### `issued_order_items` (parallels `invoice_items`)
|
||||
|
||||
| Field | Type | Notes |
|
||||
| ------------------ | ------------------------------------------- | ------------------------------- |
|
||||
| `id` | Int PK | |
|
||||
| `issued_order_id` | Int FK → `issued_orders` (onDelete Cascade) | |
|
||||
| `description` | VARCHAR(500) | main line text |
|
||||
| `item_description` | Text nullable | optional long detail |
|
||||
| `quantity` | Decimal(12,3) default `1.000` | |
|
||||
| `unit` | VARCHAR(20) nullable | e.g. ks, hod, kg |
|
||||
| `unit_price` | Decimal(12,2) default `0.00` | **NET** unit price |
|
||||
| `vat_rate` | Decimal(5,2) default `21.00` | per-line; overrides doc default |
|
||||
| `position` | Int default `0` | ordering |
|
||||
|
||||
**Index:** `(issued_order_id)`.
|
||||
|
||||
### `issued_orders_status` enum
|
||||
|
||||
`draft`, `sent`, `confirmed`, `completed`, `cancelled`
|
||||
(Czech labels: _Koncept · Odeslaná · Potvrzená · Dokončená · Stornovaná_.)
|
||||
|
||||
---
|
||||
|
||||
## Numbering
|
||||
|
||||
A dedicated sequence, exactly like invoices:
|
||||
|
||||
- New `number_sequences` type string `"issued_order"` (unique on `(type, year)`,
|
||||
as the table already enforces). Separate from `"shared"` and `"invoice"`.
|
||||
- New `company_settings` columns:
|
||||
- `issued_order_number_pattern` VARCHAR default `"{YY}{CODE}{NNNN}"`
|
||||
- `issued_order_type_code` VARCHAR default `"72"` (orders use `71`, invoices
|
||||
`81`; `72` is free and configurable).
|
||||
- New functions in `src/services/numbering.service.ts`, reusing the existing
|
||||
`applyPattern` + `getNextSequence` (`SELECT … FOR UPDATE` lock, P2002
|
||||
first-of-year retry):
|
||||
- `generateIssuedOrderNumber(tx)` — atomically consumes the next number.
|
||||
- `previewIssuedOrderNumber()` — non-consuming peek (for the create form).
|
||||
- `releaseIssuedOrderNumber(year, number)` — decrement only if the deleted PO
|
||||
held the current highest number that year (gap prevention), mirroring
|
||||
`releaseInvoiceNumber`.
|
||||
- The number is **assigned at creation**, including for a `draft`. Deleting a PO
|
||||
releases the number per the rule above.
|
||||
|
||||
---
|
||||
|
||||
## Backend API
|
||||
|
||||
### Schema — `src/schemas/issued-orders.schema.ts`
|
||||
|
||||
`CreateIssuedOrderSchema`, `UpdateIssuedOrderSchema`, `IssuedOrderItemSchema`,
|
||||
built **only** from the shared coercers in `src/schemas/common.ts`:
|
||||
|
||||
- `customer_id` → `nullableIntIdFromForm`
|
||||
- `quantity` → `positiveNumberFromForm`; `unit_price` → `nonNegativeNumberFromForm`
|
||||
- `vat_rate` → `numberInRange(0, 100)`
|
||||
- `order_date` / `delivery_date` → `isoDateString` (lenient)
|
||||
- text fields → `z.string().max(...)`; optional email-like none here
|
||||
- Czech user-facing messages; English identifiers.
|
||||
|
||||
**No** raw `z.union([z.number(), z.string()]).transform(Number)` — that idiom is
|
||||
banned (silent `NaN`).
|
||||
|
||||
### Service — `src/services/issued-orders.service.ts`
|
||||
|
||||
Plain exported async functions returning `{ data }` or `{ error, status }`:
|
||||
|
||||
- `listIssuedOrders(params)` — paginated; filters `status`, `customer_id`,
|
||||
`search` (po_number / supplier name); whitelist sort
|
||||
(`id`/`po_number`/`status`/`order_date`/`created_at`) with a deterministic
|
||||
**`{ id }` tiebreak**; each row enriched via `computeIssuedOrderTotals`.
|
||||
- `getIssuedOrder(id)` — full detail with items, supplier name, and
|
||||
`valid_transitions`.
|
||||
- `createIssuedOrder(body)` — inside `prisma.$transaction`:
|
||||
`generateIssuedOrderNumber(tx)` → insert header → batch-insert items.
|
||||
- `updateIssuedOrder(id, body)` — validates the status transition against
|
||||
`VALID_TRANSITIONS`; replaces items (delete-all + recreate) only while the doc
|
||||
is editable (`draft`/`sent`); blocks any `po_number` change.
|
||||
- `deleteIssuedOrder(id)` — delete (items cascade) then
|
||||
`releaseIssuedOrderNumber(year, po_number)`.
|
||||
- `computeIssuedOrderTotals(items, applyVat, docRate)` — **NET + VAT-on-top,
|
||||
rounded per line before accumulation** (same shape as `computeInvoiceTotals`):
|
||||
`base = qty × unit_price`; `lineVat = round(base × rate/100)` when
|
||||
`applyVat`; `subtotal = Σ base`, `vat = Σ lineVat`, `total = subtotal + vat`.
|
||||
Falls back line `vat_rate` → doc `vat_rate` → 21.
|
||||
- `getNextIssuedOrderNumber()` — proxies `previewIssuedOrderNumber()`.
|
||||
|
||||
`VALID_TRANSITIONS`:
|
||||
|
||||
```
|
||||
draft → [sent, cancelled]
|
||||
sent → [confirmed, cancelled]
|
||||
confirmed → [completed, cancelled]
|
||||
completed → [] // terminal
|
||||
cancelled → [] // terminal
|
||||
```
|
||||
|
||||
### Routes — `src/routes/admin/issued-orders.ts`
|
||||
|
||||
Registered in `src/routes/admin/index.ts`. Every handler uses `success()`/
|
||||
`error()`, `parseBody(Schema, …)`, `parseId((request.params as any).id, reply)`,
|
||||
and `logAudit` with a **new** entity type `"issued_order"` (create/update/delete,
|
||||
with `oldValues`/`newValues`). Adding this entity type requires also registering
|
||||
its Czech label in `src/admin/lib/entityTypeLabels.ts` (keyed to the server's
|
||||
`EntityType` value), per the single-source-of-truth convention.
|
||||
|
||||
| Method · Path | Guard | Purpose |
|
||||
| ------------------------------------------ | --------------- | -------------------------- |
|
||||
| GET `/api/admin/issued-orders` | `orders.view` | list (paginated, filtered) |
|
||||
| GET `/api/admin/issued-orders/next-number` | `orders.create` | preview next PO number |
|
||||
| GET `/api/admin/issued-orders/:id` | `orders.view` | detail |
|
||||
| POST `/api/admin/issued-orders` | `orders.create` | create |
|
||||
| PUT `/api/admin/issued-orders/:id` | `orders.edit` | update |
|
||||
| DELETE `/api/admin/issued-orders/:id` | `orders.delete` | delete |
|
||||
| GET `/api/admin/issued-orders/:id/pdf` | `orders.export` | render + stream PDF |
|
||||
|
||||
---
|
||||
|
||||
## PDF export
|
||||
|
||||
> **As-built (2026-06-09):** rather than the custom/compact layout this section
|
||||
> originally sketched, the issued-order PDF was **rebuilt on the shared
|
||||
> invoice / order-confirmation red-accent (#de3a3a) template** (`src/routes/admin/issued-orders-pdf.ts`),
|
||||
> titled **OBJEDNÁVKA**, for visual consistency with the rest of the document
|
||||
> suite. Because a PO is a buying document, the direction is **flipped vs an
|
||||
> invoice**: the selected **customer record renders as "Dodavatel" (supplier)**
|
||||
> and **your company as "Odběratel" (buyer)**. It is generated **on demand** and
|
||||
> streamed as `application/pdf` — **no NAS persistence**. Sanitization,
|
||||
> on-demand/no-NAS behavior, and the NET+VAT-on-top totals below are unchanged.
|
||||
|
||||
New route + template `src/routes/admin/issued-orders-pdf.ts`, reusing
|
||||
`htmlToPdf` (Puppeteer) from `src/utils/pdf.ts`:
|
||||
|
||||
- **Dodavatel (supplier) block** = the selected `customers` record (name,
|
||||
IČO/`company_id`, DIČ/`vat_id`, address). **Odběratel (buyer) block** = your
|
||||
company (`company_settings`: name, IČO, DIČ, address, logo as base64).
|
||||
- Body: items table → VAT recap grouped by rate → **NET total + VAT + gross**.
|
||||
- `cs` / `en` strings selected by `language`. Czech date/currency via the
|
||||
existing formatters.
|
||||
- `notes` passed through the **same** `cleanQuillHtml` + DOMPurify sanitization
|
||||
used by invoices/orders before going into the template (mandatory for any new
|
||||
rich-text-on-PDF field).
|
||||
- **v1 behavior:** generate on demand and stream `application/pdf` with
|
||||
`Content-Disposition` filename `{po_number}.pdf`. **No NAS write.** (A future
|
||||
`?save=1 → Objednávky vydané/YYYY/MM/{po_number}.pdf` add-on is a small,
|
||||
isolated follow-up.)
|
||||
|
||||
---
|
||||
|
||||
## Frontend
|
||||
|
||||
- **`src/admin/pages/Orders.tsx` — add `Vydané | Přijaté` tabs** using the same
|
||||
MUI Tabs pattern as `Invoices.tsx`. The current orders list moves **verbatim**
|
||||
into the **Přijaté** tab — every hook, mutation, `invalidate` array, validation,
|
||||
and permission check preserved unchanged; only presentation is reorganized. The
|
||||
**Vydané** tab renders the new list.
|
||||
_(As-built: `Orders.tsx` became a **parent shell** that owns the `PageHeader` +
|
||||
the shared month/year selector + the tabs; `IssuedOrders.tsx` (Vydané) and
|
||||
`OrdersReceived.tsx` (Přijaté) are **content-only children** receiving `month`/`year`
|
||||
props. `OrdersReceived`'s create modal is **hoisted** to the shell via
|
||||
`createOpen`/`setCreateOpen`, the ReceivedInvoices pattern. **No KPI/stat cards**
|
||||
on the Orders landing — deliberate, since orders have no paid/overdue semantics.)_
|
||||
- **Vydané list** — `DataTable` columns: `po_number`, supplier (customer name),
|
||||
status chip (color per status), `order_date`, total (currency), actions (open,
|
||||
**Export PDF**, delete). `FilterBar` with status + customer `Select`s and search
|
||||
at standard widths; pagination + sortable headers; an "Vytvořit objednávku
|
||||
vydanou" button gated on `orders.create`.
|
||||
- **`src/admin/pages/IssuedOrderDetail.tsx`** (lazy routes `/orders/issued/new`
|
||||
and `/orders/issued/:id` in `AdminApp.tsx`): supplier `Select`, `order_date` /
|
||||
`delivery_date` `DateField`s, currency / VAT rate / `apply_vat`, a **line-items
|
||||
table** (add/remove rows + `@dnd-kit` reorder, like `InvoiceDetail`), `RichEditor`
|
||||
notes, internal notes, `delivery_terms` / `payment_terms`, `issued_by`, **live
|
||||
totals** (net / VAT / gross), status-transition buttons, and an **Export PDF**
|
||||
button gated on `orders.export`. Top-level sections wrapped in `<PageEnter>`;
|
||||
imports come from the `ui/` kit.
|
||||
- **Queries** `src/admin/lib/queries/issued-orders.ts` — `issuedOrderListOptions`,
|
||||
`issuedOrderDetailOptions`, `issuedOrderNextNumberOptions`. All mutations
|
||||
invalidate the **broad `["issued-orders"]`** domain key.
|
||||
- **Rules of Hooks:** all hooks run before any early permission `return`
|
||||
(`<Forbidden/>`/`<Navigate/>` go after every hook) — `npm run lint` enforces
|
||||
`react-hooks/rules-of-hooks` as an error.
|
||||
- Sidebar nav unchanged — one "Objednávky" item; the split lives in the tabs.
|
||||
|
||||
---
|
||||
|
||||
## Permissions
|
||||
|
||||
Reuse the existing `orders.*` set for the Vydané tab:
|
||||
|
||||
- `orders.view` — list + detail + PDF view
|
||||
- `orders.create` — create + next-number preview
|
||||
- `orders.edit` — update
|
||||
- `orders.delete` — delete
|
||||
- `orders.export` — PDF export (already seeded)
|
||||
|
||||
This mirrors invoices (issued + received share one `invoices.*` set) and needs
|
||||
**no permission migration**. _(Future option, out of scope for v1: a dedicated
|
||||
`purchase-orders._` set via a seed + migration if purchasing must be locked down
|
||||
separately from sales orders.)\*
|
||||
|
||||
---
|
||||
|
||||
## Status lifecycle
|
||||
|
||||
`draft → sent → confirmed → completed`, plus any non-terminal → `cancelled`.
|
||||
|
||||
- **Editable** (header + items): `draft`, `sent`.
|
||||
- **Read-only except a permitted status change**: `confirmed`, `completed`,
|
||||
`cancelled`.
|
||||
- Enforced server-side by the `VALID_TRANSITIONS` guard in the service; the detail
|
||||
page only renders buttons for valid next states.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
`src/__tests__/issued-orders.test.ts`, against the real **`app_test`** DB via
|
||||
`buildApp()` (no Prisma mocks):
|
||||
|
||||
- **Numbering:** sequential allocation; release-only-if-highest on delete; the
|
||||
generated number matches the configured pattern.
|
||||
- **Create + totals:** create with multiple items, assert NET+VAT-on-top totals
|
||||
with **per-line rounding pinned to exact 2-decimal values**; mixed per-line VAT
|
||||
rates; `apply_vat=false` zeroes VAT but preserves the NET subtotal.
|
||||
- **Status transitions:** every valid transition succeeds; invalid transitions
|
||||
return the proper error; items become read-only after `confirmed`.
|
||||
- **Permissions:** each endpoint rejects a caller lacking the required `orders.*`
|
||||
permission (not bare auth).
|
||||
- **PDF:** `GET /:id/pdf` returns `200` with `content-type: application/pdf`.
|
||||
|
||||
---
|
||||
|
||||
## Migration
|
||||
|
||||
A single `prisma migrate dev --name issued_orders`:
|
||||
|
||||
1. Creates `issued_orders` and `issued_order_items` tables + the
|
||||
`issued_orders_status` enum.
|
||||
2. Adds `issued_order_number_pattern` and `issued_order_type_code` columns to
|
||||
`company_settings` with SQL defaults (`"{YY}{CODE}{NNNN}"`, `"72"`).
|
||||
|
||||
Per project rules: **ask the user to stop the dev server first**; commit both
|
||||
`schema.prisma` and the generated migration folder; run `prisma generate`. No raw
|
||||
SQL on prod — the column defaults ship inside the migration's `migration.sql`.
|
||||
|
||||
**Quality gates before "done":** `npx tsc -b --noEmit`, `npm run build`,
|
||||
`npx vitest run`, `npm run lint` (0 errors).
|
||||
|
||||
---
|
||||
|
||||
## Future phases (explicitly out of scope for v1)
|
||||
|
||||
- **Procurement links:** PO ↔ warehouse goods receipt (`sklad_receipts`) and
|
||||
PO ↔ received invoice matching (ordered → received → invoiced rollups), with
|
||||
Odin pre-filling a received invoice from a PO.
|
||||
- **NAS persistence** of the generated PO PDF (`?save=1`).
|
||||
- **Dedicated `purchase-orders.*` permission set.**
|
||||
- **Scope sections** (CZ/EN rich-text blocks) if POs ever need narrative content.
|
||||
52
docs/superpowers/specs/2026-06-12-sidebar-icons-design.md
Normal file
52
docs/superpowers/specs/2026-06-12-sidebar-icons-design.md
Normal file
@@ -0,0 +1,52 @@
|
||||
# Sidebar icon refresh — design
|
||||
|
||||
**Date:** 2026-06-12 · **Status:** approved (visual companion session, 3 screens)
|
||||
|
||||
## Problem
|
||||
|
||||
All 31 sidebar items have icons, but 13 share a glyph with another item
|
||||
(3× "people", 3× "sliders", 2× grid/bar-chart/box/history-clock) and Faktury
|
||||
uses a dollar sign in an app that bills in Kč/EUR. Duplicated glyphs defeat
|
||||
the purpose of icons as unique visual anchors.
|
||||
|
||||
## Decisions (user-approved)
|
||||
|
||||
1. **Full refresh** of all items (option B over targeted fix).
|
||||
2. **Tile language (option B of 3 rendered directions):** every item's glyph
|
||||
sits in a rounded-square tile (border-radius 32%, echoing OdinMark), as a
|
||||
**soft color wash — one muted hue per menu section**:
|
||||
Přehled `primary` (red) · Docházka `info` (blue) · Kniha jízd `teal` ·
|
||||
Administrativa `warning` (amber) · Sklad `violet` · Systém `slate`.
|
||||
3. **Odin stays unique:** the only **solid** (gradient) tile and the only
|
||||
animated icon. No animation anywhere else. Red stays reserved for
|
||||
Odin/primary.
|
||||
4. **Glyph set** approved on the full-set screen: receipt for Faktury,
|
||||
business card for Zákazníci, truck for Dodavatelé, stamp for Schvalování,
|
||||
ledger ± for Správa bilancí, route/pin/car for Kniha jízd, barcode for
|
||||
Inventura, shelf rack for Lokace, arrows into/out of a box for
|
||||
Příjmy/Výdeje, warehouse hall for Sklad přehled, tag/cart/folder for
|
||||
Nabídky/Objednávky/Projekty, gauge for Přehled, paper plane for Žádosti,
|
||||
timesheet for Moje historie (docházka), shapes for Kategorie, chart frame
|
||||
for Reporty, magnifier-over-list for Audit log. Kept concepts (now unique
|
||||
in the set): clock (Záznam docházky), calendar (Plán prací), people
|
||||
(Uživatelé), gear (Nastavení), box (Položky).
|
||||
|
||||
## Implementation
|
||||
|
||||
- `theme.ts`: add `teal`, `violet`, `slate` palette entries (light + dark
|
||||
mains, full main/light/dark/contrastText so cssVariables emits `*Channel`
|
||||
tokens) + TS module augmentation.
|
||||
- `navData.tsx`: `MenuSection.hue` (palette key), new glyph SVGs
|
||||
(stroke, 24-viewBox, width 2, round caps), `MenuItem.rawIcon` flag for
|
||||
Odin (its icon ships its own tile).
|
||||
- `SidebarNav.tsx`: renders the tile (26 px, radius 32%, `bgcolor:
|
||||
rgba(<hue>.mainChannel / 0.12)`, glyph color `<hue>.main`, svg 16 px)
|
||||
around every non-`rawIcon` item. No hardcoded hex; washes are
|
||||
channel-alpha so both schemes work.
|
||||
- Pinning test `navdata-icons.test.ts`: every non-raw icon renders to unique
|
||||
static markup (no two items may ever share a glyph again).
|
||||
|
||||
## Out of scope
|
||||
|
||||
Animation for non-Odin icons (explicitly rejected), page-level icons,
|
||||
mobile drawer changes (it reuses SidebarNav).
|
||||
@@ -0,0 +1,98 @@
|
||||
# Per-item Sleva (% discount) — Offers + Invoices
|
||||
|
||||
**Date:** 2026-06-13
|
||||
**Status:** Approved → implementing
|
||||
**Scope:** Add a per-line-item percentage discount ("Sleva") to **offers**
|
||||
(nabídky) and **issued invoices** (Faktury), on both the detail-page item
|
||||
editor and the PDF. Received invoices, issued orders and orders are NOT
|
||||
touched.
|
||||
|
||||
## Decisions (from brainstorming)
|
||||
|
||||
- **Type:** percentage per item (0–100), not an absolute amount.
|
||||
- **Totals/VAT:** the discount reduces the line **net**; on invoices VAT is
|
||||
computed on the **discounted** net. `net = qty × unit_price × (1 − discount/100)`.
|
||||
- **PDF column is conditional:** render the Sleva column only when at least one
|
||||
(included) item has `discount > 0`; otherwise the table is identical to today.
|
||||
- **Detail-page column is always visible** (it's the input).
|
||||
|
||||
## Data model
|
||||
|
||||
Add to `quotation_items` and `invoice_items`:
|
||||
|
||||
```
|
||||
discount Decimal? @default(0.00) @db.Decimal(5, 2) // percent, 0–100
|
||||
```
|
||||
|
||||
Nullable with default `0`, matching the existing money columns. "No sleva" =
|
||||
`0` or null. One tracked migration; apply to dev `app` and `app_test`, then
|
||||
`prisma generate`.
|
||||
|
||||
## Line math (single rule)
|
||||
|
||||
`lineNet = qty × unit_price × (1 − clamp(discount,0,100)/100)`
|
||||
|
||||
Add a shared backend helper so every site is identical:
|
||||
|
||||
```ts
|
||||
// src/utils/money.ts (new)
|
||||
export const lineNet = (qty: number, unitPrice: number, discountPct: number) =>
|
||||
qty * unitPrice * (1 - (discountPct || 0) / 100);
|
||||
```
|
||||
|
||||
## Backend
|
||||
|
||||
- **Schemas (Zod):** add `discount` to the offer-item and invoice-item schemas
|
||||
via `numberInRange(0, 100)` (shared coercer in `common.ts`), optional, default
|
||||
`0`.
|
||||
- **offers.service** (`enrichQuotation`): line total uses `lineNet`; document
|
||||
net ("Celkem bez DPH") sums discounted included lines. Persist `discount` on
|
||||
item create/update.
|
||||
- **invoices.service**: every `computeMoney` `getBase` callback
|
||||
(`computeInvoiceTotals`, monthly-stats `invoiceMonthlyAmount`, per-rate
|
||||
`vatMap`) returns `lineNet(...)` so subtotal **and** VAT use the discounted
|
||||
net. Persist `discount` on item create/update.
|
||||
- **DocumentItemsEditor's `documentItemsTotal`** (frontend) mirrors the same
|
||||
discounted net.
|
||||
|
||||
## Frontend (Section 1 — detail-page editor)
|
||||
|
||||
- **Offers** → shared `src/admin/components/document/DocumentItemsEditor.tsx`:
|
||||
`DocumentItem` gains `discount`; add a **"Sleva %"** numeric column (0–100);
|
||||
per-line total and the footer net total apply it. Mobile card layout gets the
|
||||
field. `emptyDocumentItem` defaults `discount: 0`. Hydration + save payloads
|
||||
carry `discount`.
|
||||
- **Invoices** → `src/admin/pages/InvoiceDetail.tsx` own editor
|
||||
(`SortableInvoiceRow` + create/edit rows): `InvoiceItem` gains `discount`;
|
||||
same column; net/VAT/gross totals apply it. Mobile layout too.
|
||||
|
||||
## PDF (Section 2 — conditional column)
|
||||
|
||||
`src/routes/admin/offers-pdf.ts` and `src/routes/admin/invoices-pdf.ts`:
|
||||
|
||||
- `const hasDiscount = items.some(i => includedInTotal(i) && Number(i.discount) > 0)`.
|
||||
- When `hasDiscount`: add a column — header **"Sleva"** (cs) / **"Discount"**
|
||||
(en, from the document's `language`), cell renders `"<n> %"` (escaped); adjust
|
||||
colspans of any full-width rows accordingly.
|
||||
- Line net / document total / VAT always use the discounted net regardless of
|
||||
`hasDiscount`.
|
||||
- `escapeHtml` every interpolation (string-built PDF templates).
|
||||
|
||||
## Tests
|
||||
|
||||
- `offer-invoice-totals` / invoice totals: net, VAT and gross with discounts
|
||||
(incl. a 100% line = 0, and VAT-on-discounted-net).
|
||||
- Schema: `discount` rejects <0 and >100, coerces form strings, defaults 0.
|
||||
- PDF: column present when an item has a discount; absent when none; values
|
||||
escaped.
|
||||
|
||||
## Non-goals (YAGNI)
|
||||
|
||||
- No separate "total discount" summary line, no document-level discount.
|
||||
- No changes to received invoices, issued orders, or orders.
|
||||
|
||||
## Migration etiquette
|
||||
|
||||
DB change → user stops the dev server first; create the migration via the
|
||||
non-interactive `prisma migrate diff` recipe, `migrate deploy` + `generate` on
|
||||
dev and `app_test`, commit schema + migration folder together.
|
||||
@@ -0,0 +1,211 @@
|
||||
# Per-document custom-field print selection
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Status:** Approved design — ready for implementation plan
|
||||
**Scope:** offers (quotations), issued orders, invoices
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Company custom fields are defined in company settings (`company_settings.custom_fields`,
|
||||
a JSON blob of `{name, value, showLabel}[]` plus a `field_order`). They render in the
|
||||
**sender/company block** of document PDFs via `buildAddressLines(settings, …)`.
|
||||
|
||||
Today **every** custom field with a value prints on **every** document PDF (offer, issued
|
||||
order, invoice). The only existing per-field control is the company-settings checkbox
|
||||
**"Zobrazit název v PDF"** (`showLabel`), which decides whether a printed field shows as
|
||||
`Name: Value` or just `Value` — it does **not** control whether the field appears at all.
|
||||
|
||||
The user wants per-document control: on each offer / issued order / invoice **detail page**,
|
||||
tick which company custom fields actually print on that specific document's PDF.
|
||||
|
||||
## Goals
|
||||
|
||||
- Each offer, issued order, and invoice independently selects which company custom fields
|
||||
print in its PDF sender block.
|
||||
- Selection lives on the document and is editable on its detail page.
|
||||
- Default is **none selected** — existing documents and new drafts print no custom fields
|
||||
until fields are deliberately ticked.
|
||||
- The company-settings `showLabel` ("Zobrazit název v PDF") checkbox is **unchanged**.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Order confirmations ("orders" / `orders-pdf.ts`) are **out of scope** — they keep current
|
||||
behavior (print all custom fields).
|
||||
- No change to how custom fields are _defined_ in company settings.
|
||||
- No stable per-field IDs — selection is **positional** (see Decisions).
|
||||
|
||||
## Decisions (locked)
|
||||
|
||||
1. **Default = none selected.** Existing rows get `NULL`; new documents start empty. A
|
||||
document prints custom fields only for the indices it explicitly stores.
|
||||
2. **Positional identity.** Selection stores field **positions** (`0,1,2…`) matching the
|
||||
existing `custom_<i>` keys in the PDF code. No settings-structure change, no backfill.
|
||||
Accepted caveat: reordering/deleting a custom field in company settings can shift what a
|
||||
saved document's stored indices point at. Low risk — company fields rarely change, and
|
||||
finalized PDFs are archived on NAS (served as-is, not re-rendered). The user accepted this
|
||||
over the more robust stable-ID approach.
|
||||
3. **Scope = 3 document types** (offers, issued orders, invoices). Order confirmations excluded.
|
||||
4. **`showLabel` retained** in company settings, untouched.
|
||||
|
||||
---
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Data storage
|
||||
|
||||
Add one nullable column to each of `quotations`, `issued_orders`, `invoices`:
|
||||
|
||||
| Column | Type | Meaning |
|
||||
| ------------------------ | --------- | ------------------------------------------------------------- |
|
||||
| `selected_custom_fields` | `VARCHAR` | JSON array of selected indices, e.g. `"[0,2]"`; `NULL` = none |
|
||||
|
||||
Stored as JSON-in-text, consistent with the existing `company_settings.custom_fields` /
|
||||
`customers.custom_fields` pattern. `NULL`/empty ⇒ no custom fields print.
|
||||
|
||||
One tracked migration per the project's non-interactive `prisma migrate diff` recipe
|
||||
(CLAUDE.md). **Apply to `app_test` as well** (`DATABASE_URL=<app_test> npx prisma migrate
|
||||
deploy`) or the suite breaks. Commit `schema.prisma` + migration folder together.
|
||||
|
||||
### 2. Backend — schemas
|
||||
|
||||
Add to each document's **Create and Update** Zod schema:
|
||||
|
||||
```ts
|
||||
selected_custom_fields: z.array(z.number().int().nonnegative()).max(200).optional(),
|
||||
```
|
||||
|
||||
Files:
|
||||
|
||||
- `src/schemas/offers.schema.ts` — `CreateQuotationSchema` (Update derives via `.partial().omit()`).
|
||||
- `src/schemas/issued-orders.schema.ts` — `CreateIssuedOrderSchema` (Update derives via `.partial().omit()`).
|
||||
- `src/schemas/invoices.schema.ts` — both `CreateInvoiceSchema` and `UpdateInvoiceSchema`
|
||||
(invoices define the two schemas separately).
|
||||
|
||||
### 3. Backend — services
|
||||
|
||||
In each create/update service, persist the field inside the **existing transaction**:
|
||||
|
||||
- On write: `selected_custom_fields: Array.isArray(body.selected_custom_fields) &&
|
||||
body.selected_custom_fields.length > 0 ? JSON.stringify(body.selected_custom_fields) : null`
|
||||
- No other logic changes; sits alongside the existing header column assignments.
|
||||
|
||||
Files: `src/services/offers.service.ts`, `src/services/issued-orders.service.ts`,
|
||||
`src/services/invoices.service.ts`.
|
||||
|
||||
### 4. Backend — detail responses
|
||||
|
||||
The detail endpoints spread the document row. Decode the stored string back into a
|
||||
`number[]` so the frontend receives a clean array (default `[]` when `NULL`/malformed —
|
||||
malformed JSON degrades gracefully with a logged warning, per the error convention). Add
|
||||
`selected_custom_fields: number[]` to the corresponding detail interfaces in
|
||||
`src/admin/lib/queries/{offers,issued-orders,invoices}.ts`.
|
||||
|
||||
### 5. PDF rendering
|
||||
|
||||
In each of `offers-pdf.ts`, `issued-orders-pdf.ts`, `invoices-pdf.ts`, extend the
|
||||
company-block `buildAddressLines()` with an optional parameter:
|
||||
|
||||
```ts
|
||||
buildAddressLines(entity, isSupplier, t, selectedCustomFields?: number[] | null)
|
||||
```
|
||||
|
||||
When building `fieldMap`, only emit a `custom_<i>` entry when `selectedCustomFields`
|
||||
includes `i`. Behavior:
|
||||
|
||||
- `null` / `undefined` / empty array ⇒ **no** custom lines (the new default).
|
||||
- Standard address lines (name, street, city/postal, country, IČO/`company_id`,
|
||||
DIČ/`vat_id`) are **unaffected** — always built as today.
|
||||
- For the custom fields that _are_ selected, the existing `showLabel` (`Name: Value` vs
|
||||
`Value`) and `field_order` ordering logic is preserved unchanged.
|
||||
|
||||
Only the **company/sender** block is filtered (that's where company custom fields render).
|
||||
The customer block (offers/invoices) and supplier block (issued orders) keep their own
|
||||
custom-field behavior unchanged — those come from `customers`/`sklad_suppliers`, not company
|
||||
settings, and are not in scope.
|
||||
|
||||
The PDF route reads the document's `selected_custom_fields` column, parses it to `number[]`,
|
||||
and passes it into `buildAddressLines(settings, …, selected)`.
|
||||
|
||||
> Archived-PDF note: finalized/numbered documents serve their archived NAS copy and won't
|
||||
> change retroactively. Drafts (and any forced re-render) reflect the current selection.
|
||||
|
||||
### 6. Frontend — shared picker component
|
||||
|
||||
New shared component under `src/admin/components/document/` (e.g.
|
||||
`CustomFieldsPrintPicker.tsx`), reused by all three detail pages (extend the shared module,
|
||||
don't fork three copies — per CLAUDE.md document-module conventions).
|
||||
|
||||
Props (shape): the parsed company custom fields (`{name, value}[]` from
|
||||
`companySettings.custom_fields`), the current selected indices, an `onChange`, and a
|
||||
`disabled` flag.
|
||||
|
||||
Behavior:
|
||||
|
||||
- Renders a checkbox per company custom field; label shows the field's name (and/or value)
|
||||
so the user knows what each is.
|
||||
- Bound to local state on the detail page, seeded from the document's
|
||||
`selected_custom_fields`.
|
||||
- Hidden/empty when the company has no custom fields defined.
|
||||
- Respects edit-lock and editable-status rules: read-only (`disabled`) when the document
|
||||
isn't editable or is locked by another user, matching how the rest of the header fields
|
||||
behave on that page.
|
||||
- Included in the page's save payload as `selected_custom_fields: number[]`.
|
||||
|
||||
Pages: `src/admin/pages/OfferDetail.tsx`, `IssuedOrderDetail.tsx`, `InvoiceDetail.tsx` —
|
||||
each already loads `companySettingsOptions()`, so the field definitions are available with
|
||||
no new query.
|
||||
|
||||
Placement: in the editable header/meta area of each detail page, near the other
|
||||
document-level settings (currency/language/etc.).
|
||||
|
||||
---
|
||||
|
||||
## Data flow
|
||||
|
||||
```
|
||||
Company settings: custom_fields = [{name:"Tel.",…}, {name:"Web",…}, {name:"Datová schránka",…}]
|
||||
idx 0 idx 1 idx 2
|
||||
|
||||
Offer detail page → user ticks "Tel." and "Datová schránka"
|
||||
→ save payload selected_custom_fields: [0, 2]
|
||||
→ service stores quotations.selected_custom_fields = "[0,2]"
|
||||
|
||||
Offer PDF render
|
||||
→ read column "[0,2]" → [0,2]
|
||||
→ buildAddressLines(settings, …, [0,2])
|
||||
→ fieldMap emits custom_0 ("Tel.: …") and custom_2 ("Datová schránka: …"), skips custom_1
|
||||
→ sender block prints Tel. and Datová schránka only
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Server-side Vitest against `app_test` (no Prisma mocking; mock Puppeteer/NAS only):
|
||||
|
||||
- Create/update each document with `selected_custom_fields` → column persists the JSON
|
||||
string; empty/omitted → `NULL`.
|
||||
- Detail response decodes to `number[]` (and `[]` for `NULL`).
|
||||
- Schema: non-integer / negative entries rejected; omitted is valid.
|
||||
- PDF: with a stubbed `html-to-pdf`, assert the rendered company block includes only the
|
||||
selected custom field lines and still includes standard address lines; empty selection ⇒
|
||||
no custom lines; standard lines unaffected.
|
||||
- Regression: customer/supplier custom fields still render regardless of company selection.
|
||||
|
||||
## Migration & rollout
|
||||
|
||||
- One migration adding the three columns (all default `NULL`), applied to dev `app` and
|
||||
`app_test`.
|
||||
- No data backfill (none-selected default is the intended post-ship state).
|
||||
- No production PDF changes for already-archived documents.
|
||||
|
||||
## Affected files (reference)
|
||||
|
||||
- `prisma/schema.prisma` (+ new migration folder)
|
||||
- `src/schemas/offers.schema.ts`, `issued-orders.schema.ts`, `invoices.schema.ts`
|
||||
- `src/services/offers.service.ts`, `issued-orders.service.ts`, `invoices.service.ts`
|
||||
- `src/routes/admin/offers-pdf.ts`, `issued-orders-pdf.ts`, `invoices-pdf.ts`
|
||||
- (detail route handlers, if decoding is done there rather than in the service)
|
||||
- `src/admin/lib/queries/offers.ts`, `issued-orders.ts`, `invoices.ts`
|
||||
- `src/admin/components/document/CustomFieldsPrintPicker.tsx` (new)
|
||||
- `src/admin/pages/OfferDetail.tsx`, `IssuedOrderDetail.tsx`, `InvoiceDetail.tsx`
|
||||
@@ -0,0 +1,96 @@
|
||||
# Status quick actions + project⇄order sync
|
||||
|
||||
**Date:** 2026-07-04 · **Status:** Approved (interactive design w/ owner) · **Scope:** offers, received orders, projects
|
||||
|
||||
## Problem
|
||||
|
||||
Status changes are inconsistent: the Invoices list has a quick chip action (click → confirm → paid),
|
||||
but Offers/ReceivedOrders/Projects tables have inert chips — every change needs the detail page.
|
||||
ProjectDetail edits status via a free combobox in the form (no transitions, no confirm), unlike
|
||||
OfferDetail/OrderDetail's transition buttons. Projects have **no status machine at all** (free-text
|
||||
column). Order→project completion sync exists one-way (`syncProjectStatus`), but finishing a
|
||||
**project** leaves its linked order untouched.
|
||||
|
||||
## Decisions (owner)
|
||||
|
||||
1. **Chip opens a menu** of valid next states (not single-click-advance) → ConfirmDialog per pick,
|
||||
danger styling + cascade notes on destructive/irreversible ones.
|
||||
2. **Reopen allowed**: `dokonceny/zruseny → aktivni` (projects), `dokoncena/stornovana → v_realizaci`
|
||||
(received orders). **Reopening never cascades** to the linked record.
|
||||
3. **Sync scope: finish + cancel, both directions.** Project `dokonceny` ⇄ order `dokoncena`;
|
||||
project `zruseny` ⇄ order `stornovana`.
|
||||
4. Offers quick menu: `Aktivovat` (draft — same number-assignment + PDF-archive semantics as the
|
||||
detail), `Zneplatnit` (danger), and **"Vytvořit objednávku…" which opens the existing
|
||||
create-order modal** (never a raw label flip to `ordered` — that state is owned by the
|
||||
create-order flow).
|
||||
|
||||
## Design
|
||||
|
||||
### Backend
|
||||
|
||||
**Projects gain a status machine** (`src/services/projects.service.ts`):
|
||||
`VALID_TRANSITIONS = { aktivni: [dokonceny, zruseny], dokonceny: [aktivni], zruseny: [aktivni] }`.
|
||||
`updateProject` validates status changes (token `invalid_transition` → Czech 400 in the route);
|
||||
a legacy/unknown current status may transition to any canonical value (tolerant). `getProject`
|
||||
returns `valid_transitions` (same contract as offers/orders).
|
||||
|
||||
**Project → order cascade** (new), inside one transaction with the project update:
|
||||
|
||||
- project → `dokonceny` ⇒ linked order → `dokoncena` **iff** order status ∈ {prijata, v_realizaci}
|
||||
- project → `zruseny` ⇒ linked order → `stornovana` **iff** order status ∈ {prijata, v_realizaci}
|
||||
- reopen ⇒ no order change; completed/cancelled orders are never resurrected by a cascade
|
||||
- direct `tx` write (no service recursion); sibling projects of the same order are NOT touched
|
||||
(multi-project orders are a rare schema possibility, not a flow; avoid surprise mass updates)
|
||||
- the service returns what cascaded so the route writes an audit row for the order change too
|
||||
|
||||
**Received orders** (`src/services/orders.service.ts`):
|
||||
|
||||
- `VALID_TRANSITIONS` gains reopen: `dokoncena: [v_realizaci]`, `stornovana: [v_realizaci]`
|
||||
- `syncProjectStatus` becomes reopen-aware: given the previous status, a transition OUT of a
|
||||
terminal state (reopen) skips project sync entirely (decision 2). Forward transitions keep the
|
||||
existing mapping (v_realizaci→aktivni no-op in practice, dokoncena→dokonceny,
|
||||
stornovana→zruseny), and the cascaded project change now gets an audit row.
|
||||
- item/section edit guards stay status-based, so a reopened order is editable again (intended).
|
||||
|
||||
No DB migration (status columns are strings already).
|
||||
|
||||
### Frontend
|
||||
|
||||
**Shared `StatusChipMenu`** (`src/admin/components/StatusChipMenu.tsx`): renders a `StatusChip`;
|
||||
click opens a small MUI `Menu` of actions; each action either opens a `ConfirmDialog`
|
||||
(danger variant + `loading` during the request; cascade note in the message) or runs a plain
|
||||
`onClick` (the modal-opening offer item). Hidden affordance fixed via `title` tooltip. Chip is
|
||||
plain (non-clickable) when the user lacks the edit permission or no actions exist.
|
||||
|
||||
**Offers list**: draft → `Aktivovat` (confirm notes the number assignment; after success the same
|
||||
fire-and-forget PDF-archive call the detail does); active → `Vytvořit objednávku…` (opens the
|
||||
existing modal) + `Zneplatnit` (danger); ordered → `Zneplatnit` (danger).
|
||||
|
||||
**ReceivedOrders list**: prijata → `Zahájit realizaci`, `Stornovat` (danger, note: linked project
|
||||
will be cancelled); v_realizaci → `Dokončit` (note: linked project will be completed),
|
||||
`Stornovat` (danger); dokoncena/stornovana → `Obnovit` (reopen, no cascade note).
|
||||
|
||||
**Projects list**: aktivni → `Dokončit` (note when `order_id` present: linked order will be
|
||||
completed), `Zrušit` (danger, order-storno note); dokonceny/zruseny → `Obnovit`.
|
||||
|
||||
**ProjectDetail**: status `Select` removed from the form (and status removed from the save
|
||||
payload); header gains transition buttons rendered from `valid_transitions`
|
||||
(`Dokončit projekt` / `Zrušit projekt` danger / `Obnovit projekt`), each via ConfirmDialog with
|
||||
cascade notes, as a status-only PUT with its own mutation
|
||||
(invalidate: projects, orders, offers, invoices, warehouse). OrderDetail keeps its pattern;
|
||||
its transition label shows `Obnovit` when reopening from a terminal state.
|
||||
|
||||
Invalidation for all new status mutations: `["orders","offers","projects","invoices"]`
|
||||
(+`["warehouse"]` on project mutations, matching the page's existing set).
|
||||
|
||||
### Tests
|
||||
|
||||
Service-level (real `app_test` DB): project transition validation (all legal/illegal edges incl.
|
||||
legacy-status tolerance), project→order cascade both mappings + the guard (no cascade onto
|
||||
dokoncena/stornovana orders), reopen-no-cascade both directions, order reopen transitions, and
|
||||
regression: order→project sync still fires on forward transitions.
|
||||
|
||||
## Out of scope
|
||||
|
||||
Offer machine changes (unchanged: draft→active→ordered/invalidated), issued orders, sibling-project
|
||||
propagation, ReceivedOrders detail-page button changes beyond the automatic reopen button.
|
||||
78
eslint.config.mjs
Normal file
78
eslint.config.mjs
Normal file
@@ -0,0 +1,78 @@
|
||||
import js from "@eslint/js";
|
||||
import tseslint from "typescript-eslint";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import reactRefresh from "eslint-plugin-react-refresh";
|
||||
import globals from "globals";
|
||||
import prettier from "eslint-config-prettier";
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: [
|
||||
"dist/**",
|
||||
"dist-client/**",
|
||||
"node_modules/**",
|
||||
"prisma/migrations/**",
|
||||
"src/admin/bones/**",
|
||||
"*.config.js",
|
||||
"*.config.mjs",
|
||||
"*.config.ts",
|
||||
".claude/**",
|
||||
],
|
||||
},
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
// Server + shared code
|
||||
files: ["src/**/*.{ts,tsx}", "scripts/**/*.ts", "prisma/seed.ts"],
|
||||
languageOptions: {
|
||||
globals: { ...globals.node, ...globals.browser },
|
||||
},
|
||||
rules: {
|
||||
// TS already resolves identifiers — `no-undef` only false-positives on
|
||||
// global types/ambient names in .ts files.
|
||||
"no-undef": "off",
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"warn",
|
||||
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
|
||||
],
|
||||
"@typescript-eslint/no-require-imports": "warn",
|
||||
"no-empty": ["warn", { allowEmptyCatch: false }],
|
||||
// Intentional control-character regexes (NUL/path-traversal guards,
|
||||
// combining-marks stripping) — not a defect here.
|
||||
"no-control-regex": "off",
|
||||
// Stylistic / advisory — surface as warnings, don't fail the lint gate.
|
||||
"no-useless-escape": "warn",
|
||||
"no-useless-assignment": "warn",
|
||||
"preserve-caught-error": "warn",
|
||||
"prefer-const": "warn",
|
||||
},
|
||||
},
|
||||
{
|
||||
// Frontend React code
|
||||
files: ["src/admin/**/*.{ts,tsx}", "src/**/*.tsx"],
|
||||
plugins: {
|
||||
"react-hooks": reactHooks,
|
||||
"react-refresh": reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
"react-hooks/rules-of-hooks": "error",
|
||||
"react-hooks/exhaustive-deps": "warn",
|
||||
},
|
||||
},
|
||||
{
|
||||
// Plain Node helper scripts (.js/.mjs/.cjs in scripts/)
|
||||
files: ["scripts/**/*.{js,mjs,cjs}"],
|
||||
languageOptions: { globals: { ...globals.node } },
|
||||
rules: { "no-undef": "off" },
|
||||
},
|
||||
{
|
||||
// Tests
|
||||
files: ["src/__tests__/**/*.ts"],
|
||||
languageOptions: { globals: { ...globals.node } },
|
||||
rules: {
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
},
|
||||
},
|
||||
prettier,
|
||||
);
|
||||
@@ -13,13 +13,13 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Urbanist:wght@300;400;500;600;700;800&display=swap"
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;0,6..72,600;1,6..72,400;1,6..72,500&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Urbanist:wght@300;400;500;600;700;800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="shortcut icon" href="/favicon.ico" />
|
||||
<title>Admin</title>
|
||||
<title>BOHA Admin</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
2864
package-lock.json
generated
2864
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
49
package.json
49
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "app-ts",
|
||||
"version": "2.0.7",
|
||||
"version": "2.4.46",
|
||||
"description": "",
|
||||
"main": "dist/server.js",
|
||||
"scripts": {
|
||||
@@ -14,20 +14,22 @@
|
||||
"preview": "vite preview",
|
||||
"db:generate": "prisma generate",
|
||||
"db:pull": "prisma db pull",
|
||||
"db:push": "prisma db push",
|
||||
"db:studio": "prisma studio",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
"seed": "tsx prisma/seed.ts",
|
||||
"typecheck": "tsc -b --noEmit",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check ."
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.102.0",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
@@ -41,52 +43,59 @@
|
||||
"@fastify/static": "^9.0.0",
|
||||
"@mui/material": "^7.3.11",
|
||||
"@mui/x-date-pickers": "^8.29.0",
|
||||
"@prisma/client": "^6.19.2",
|
||||
"@prisma/adapter-mariadb": "^7.8.0",
|
||||
"@prisma/client": "^7.8.0",
|
||||
"@tanstack/react-query": "^5.100.5",
|
||||
"@types/jsdom": "^28.0.1",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.3.3",
|
||||
"dotenv": "^17.3.1",
|
||||
"fastify": "^5.8.2",
|
||||
"file-type": "^16.5.4",
|
||||
"file-type": "^22.0.1",
|
||||
"framer-motion": "^12.38.0",
|
||||
"hi-base32": "^0.5.1",
|
||||
"jsdom": "^29.0.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"leaflet": "^1.9.4",
|
||||
"mariadb": "^3.5.2",
|
||||
"node-cron": "^4.2.1",
|
||||
"nodemailer": "^8.0.2",
|
||||
"otpauth": "^9.5.0",
|
||||
"prisma": "^6.19.2",
|
||||
"prisma": "^7.8.0",
|
||||
"puppeteer": "^24.40.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-datepicker": "^9.1.0",
|
||||
"react-dom": "^18.3.1",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-quill-new": "^3.8.3",
|
||||
"react-router-dom": "^6.30.3",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@types/jsdom": "^28.0.1",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"@types/mysql": "^2.15.27",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/node-cron": "^3.0.11",
|
||||
"@types/nodemailer": "^7.0.11",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^18.3.31",
|
||||
"@types/react-dom": "^18.3.7",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/supertest": "^7.2.0",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"concurrently": "^9.2.1",
|
||||
"eslint": "^10.4.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.6.0",
|
||||
"prettier": "^3.8.3",
|
||||
"supertest": "^7.2.2",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.61.0",
|
||||
"vite": "^8.0.0",
|
||||
"vitest": "^4.1.0"
|
||||
},
|
||||
"overrides": {
|
||||
"@hono/node-server": "^1.19.13"
|
||||
}
|
||||
}
|
||||
|
||||
16
prisma.config.ts
Normal file
16
prisma.config.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import "dotenv/config";
|
||||
import { defineConfig, env } from "prisma/config";
|
||||
|
||||
// Prisma 7 moved the datasource connection URL and seed config out of
|
||||
// schema.prisma / package.json into this file. `import "dotenv/config"` is
|
||||
// required because Prisma 7 no longer auto-loads .env. The runtime database
|
||||
// connection itself is made via the driver adapter in src/config/database.ts.
|
||||
export default defineConfig({
|
||||
schema: "prisma/schema.prisma",
|
||||
datasource: {
|
||||
url: env("DATABASE_URL"),
|
||||
},
|
||||
migrations: {
|
||||
seed: "tsx prisma/seed.ts",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
-- AI assistant (Phase 1): usage-tracking table, monthly budget column, ai.use permission.
|
||||
|
||||
CREATE TABLE `ai_usage` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`user_id` INTEGER NULL,
|
||||
`kind` VARCHAR(20) NOT NULL,
|
||||
`model` VARCHAR(50) NOT NULL,
|
||||
`input_tokens` INTEGER NOT NULL DEFAULT 0,
|
||||
`output_tokens` INTEGER NOT NULL DEFAULT 0,
|
||||
`cost_usd` DECIMAL(10, 6) NOT NULL DEFAULT 0,
|
||||
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
PRIMARY KEY (`id`),
|
||||
INDEX `idx_ai_usage_created` (`created_at`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `company_settings`
|
||||
ADD COLUMN `ai_monthly_budget_usd` DECIMAL(10, 2) NULL DEFAULT 50.00;
|
||||
|
||||
-- ai.use permission + grant to admin (INSERT IGNORE → idempotent), mirroring
|
||||
-- the warehouse-permissions migration.
|
||||
INSERT IGNORE INTO `permissions` (`name`, `display_name`, `module`, `description`, `created_at`) VALUES
|
||||
('ai.use', 'AI asistent', 'ai', 'Používat AI asistenta (chat a import faktur)', NOW());
|
||||
|
||||
INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`)
|
||||
SELECT r.id, p.id
|
||||
FROM `roles` r
|
||||
CROSS JOIN `permissions` p
|
||||
WHERE r.name = 'admin'
|
||||
AND p.name = 'ai.use';
|
||||
@@ -0,0 +1,11 @@
|
||||
-- AI assistant (Phase 1): per-user chat history (server-side, permanent).
|
||||
|
||||
CREATE TABLE `ai_chat_messages` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`user_id` INTEGER NOT NULL,
|
||||
`role` VARCHAR(20) NOT NULL,
|
||||
`content` TEXT NOT NULL,
|
||||
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
PRIMARY KEY (`id`),
|
||||
INDEX `idx_ai_chat_user` (`user_id`, `id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
@@ -0,0 +1,32 @@
|
||||
-- Multi-conversation Odin: conversations table + conversation_id on messages.
|
||||
|
||||
CREATE TABLE `ai_conversations` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`user_id` INTEGER NOT NULL,
|
||||
`title` VARCHAR(255) NOT NULL,
|
||||
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
PRIMARY KEY (`id`),
|
||||
INDEX `idx_ai_conv_user` (`user_id`, `id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `ai_chat_messages`
|
||||
ADD COLUMN `conversation_id` INTEGER NULL AFTER `user_id`;
|
||||
|
||||
-- Backfill: one conversation per user who has messages ("keep as first conversation").
|
||||
INSERT INTO `ai_conversations` (`user_id`, `title`, `created_at`, `updated_at`)
|
||||
SELECT `user_id`, 'Konverzace', NOW(), NOW()
|
||||
FROM `ai_chat_messages`
|
||||
GROUP BY `user_id`;
|
||||
|
||||
UPDATE `ai_chat_messages` m
|
||||
JOIN `ai_conversations` c ON c.`user_id` = m.`user_id`
|
||||
SET m.`conversation_id` = c.`id`;
|
||||
|
||||
-- Enforce: drop old per-user index, NOT NULL, FK (cascade), per-conversation index.
|
||||
ALTER TABLE `ai_chat_messages`
|
||||
DROP INDEX `idx_ai_chat_user`,
|
||||
MODIFY `conversation_id` INTEGER NOT NULL,
|
||||
ADD CONSTRAINT `fk_ai_chat_conv` FOREIGN KEY (`conversation_id`)
|
||||
REFERENCES `ai_conversations`(`id`) ON DELETE CASCADE,
|
||||
ADD INDEX `idx_ai_chat_conv` (`conversation_id`, `id`);
|
||||
@@ -0,0 +1,137 @@
|
||||
-- Audit schema hardening (from the 2026-06-09 codebase audit).
|
||||
--
|
||||
-- ⚠️ PENDING — NOT YET APPLIED. Review, then apply with the dev server stopped:
|
||||
-- npx prisma migrate deploy (prod / already-tracked)
|
||||
-- -- or, in dev, `npx prisma migrate dev` will pick it up as pending.
|
||||
--
|
||||
-- What this does:
|
||||
-- • Warehouse line→header relations now CASCADE on delete (deleting a
|
||||
-- receipt/issue/inventory session removes its lines/attachments).
|
||||
-- • Warehouse line→master-data (item/batch/location) and the financial FKs
|
||||
-- (invoices/orders/projects/quotations → customer/order/quotation) are now
|
||||
-- explicit ON DELETE RESTRICT — preventing deletion of a referenced master
|
||||
-- record / orphaning of a financial record. (Some of these were previously
|
||||
-- the optional-relation default SET NULL; RESTRICT is the safer intent.)
|
||||
-- • UNIQUE on warehouse document numbers (receipt_number/issue_number/
|
||||
-- session_number) — like every other document-number column.
|
||||
-- • New indexes on hot FK filters (sklad_issues/receipts, bank_accounts).
|
||||
--
|
||||
-- ⚠️ BEFORE APPLYING ON PRODUCTION, verify existing data won't violate the new
|
||||
-- constraints: no DUPLICATE non-null receipt/issue/session numbers (else the
|
||||
-- UNIQUE index fails), and no rows that would break the RESTRICT FKs. Test on
|
||||
-- a copy first.
|
||||
--
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `invoices` DROP FOREIGN KEY `invoices_ibfk_1`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `invoices` DROP FOREIGN KEY `invoices_ibfk_2`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `orders` DROP FOREIGN KEY `orders_ibfk_1`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `orders` DROP FOREIGN KEY `orders_ibfk_2`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `projects` DROP FOREIGN KEY `projects_ibfk_1`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `projects` DROP FOREIGN KEY `projects_ibfk_2`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `projects` DROP FOREIGN KEY `projects_ibfk_3`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `quotations` DROP FOREIGN KEY `quotations_ibfk_1`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `sklad_receipt_lines` DROP FOREIGN KEY `sklad_receipt_lines_receipt_id_fkey`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `sklad_receipt_lines` DROP FOREIGN KEY `sklad_receipt_lines_location_id_fkey`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `sklad_receipt_attachments` DROP FOREIGN KEY `sklad_receipt_attachments_receipt_id_fkey`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `sklad_issue_lines` DROP FOREIGN KEY `sklad_issue_lines_issue_id_fkey`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `sklad_issue_lines` DROP FOREIGN KEY `sklad_issue_lines_location_id_fkey`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `sklad_inventory_lines` DROP FOREIGN KEY `sklad_inventory_lines_session_id_fkey`;
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `sklad_inventory_lines` DROP FOREIGN KEY `sklad_inventory_lines_location_id_fkey`;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `idx_bank_accounts_is_default` ON `bank_accounts`(`is_default`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX `sklad_receipts_receipt_number_key` ON `sklad_receipts`(`receipt_number`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `sklad_receipts_supplier_id` ON `sklad_receipts`(`supplier_id`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `sklad_receipts_received_by` ON `sklad_receipts`(`received_by`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX `sklad_issues_issue_number_key` ON `sklad_issues`(`issue_number`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `sklad_issues_project_id` ON `sklad_issues`(`project_id`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `sklad_issues_issued_by` ON `sklad_issues`(`issued_by`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX `sklad_inventory_sessions_session_number_key` ON `sklad_inventory_sessions`(`session_number`);
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `invoices` ADD CONSTRAINT `invoices_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `invoices` ADD CONSTRAINT `invoices_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `orders` ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`quotation_id`) REFERENCES `quotations`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `orders` ADD CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `projects` ADD CONSTRAINT `projects_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `projects` ADD CONSTRAINT `projects_ibfk_2` FOREIGN KEY (`quotation_id`) REFERENCES `quotations`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `projects` ADD CONSTRAINT `projects_ibfk_3` FOREIGN KEY (`order_id`) REFERENCES `orders`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `quotations` ADD CONSTRAINT `quotations_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `sklad_receipt_lines` ADD CONSTRAINT `sklad_receipt_lines_receipt_id_fkey` FOREIGN KEY (`receipt_id`) REFERENCES `sklad_receipts`(`id`) ON DELETE CASCADE 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 RESTRICT 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 CASCADE 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 CASCADE 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 RESTRICT 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 CASCADE 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 RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `ai_chat_messages` DROP FOREIGN KEY `fk_ai_chat_conv`;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `quotations` MODIFY `project_code` VARCHAR(100) NULL;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `ai_chat_messages` ADD CONSTRAINT `ai_chat_messages_conversation_id_fkey` FOREIGN KEY (`conversation_id`) REFERENCES `ai_conversations`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
52
prisma/migrations/20260609085152_issued_orders/migration.sql
Normal file
52
prisma/migrations/20260609085152_issued_orders/migration.sql
Normal file
@@ -0,0 +1,52 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `company_settings` ADD COLUMN `issued_order_number_pattern` VARCHAR(100) NULL,
|
||||
ADD COLUMN `issued_order_type_code` VARCHAR(10) NULL;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `issued_orders` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`po_number` VARCHAR(50) NULL,
|
||||
`customer_id` INTEGER NULL,
|
||||
`status` ENUM('draft', 'sent', 'confirmed', 'completed', 'cancelled') NOT NULL DEFAULT 'draft',
|
||||
`currency` VARCHAR(10) NULL DEFAULT 'CZK',
|
||||
`vat_rate` DECIMAL(5, 2) NULL DEFAULT 21.00,
|
||||
`apply_vat` BOOLEAN NULL DEFAULT true,
|
||||
`exchange_rate` DECIMAL(10, 4) NULL DEFAULT 1.0000,
|
||||
`order_date` DATE NULL,
|
||||
`delivery_date` DATE NULL,
|
||||
`language` VARCHAR(5) NULL DEFAULT 'cs',
|
||||
`delivery_terms` VARCHAR(500) NULL,
|
||||
`payment_terms` VARCHAR(500) NULL,
|
||||
`issued_by` VARCHAR(255) NULL,
|
||||
`notes` TEXT NULL,
|
||||
`internal_notes` TEXT NULL,
|
||||
`created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
|
||||
`modified_at` DATETIME(0) NULL,
|
||||
|
||||
UNIQUE INDEX `idx_issued_orders_number_unique`(`po_number`),
|
||||
INDEX `issued_orders_customer_id`(`customer_id`),
|
||||
INDEX `idx_issued_orders_status_date`(`status`, `order_date`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `issued_order_items` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`issued_order_id` INTEGER NOT NULL,
|
||||
`description` VARCHAR(500) NULL,
|
||||
`item_description` TEXT NULL,
|
||||
`quantity` DECIMAL(12, 3) NULL DEFAULT 1.000,
|
||||
`unit` VARCHAR(20) NULL,
|
||||
`unit_price` DECIMAL(12, 2) NULL DEFAULT 0.00,
|
||||
`vat_rate` DECIMAL(5, 2) NULL DEFAULT 21.00,
|
||||
`position` INTEGER NULL DEFAULT 0,
|
||||
|
||||
INDEX `issued_order_id`(`issued_order_id`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `issued_orders` ADD CONSTRAINT `issued_orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `issued_order_items` ADD CONSTRAINT `issued_order_items_ibfk_1` FOREIGN KEY (`issued_order_id`) REFERENCES `issued_orders`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `company_settings` ADD COLUMN `project_number_pattern` VARCHAR(100) NULL,
|
||||
ADD COLUMN `project_type_code` VARCHAR(10) NULL;
|
||||
@@ -0,0 +1,61 @@
|
||||
-- Drop the three DEAD document "export" permissions and make the 12 surviving
|
||||
-- document permissions reproducible on a fresh production database.
|
||||
--
|
||||
-- Why: `offers.export`, `orders.export`, `invoices.export` gate NOTHING on the
|
||||
-- backend — every PDF/export route is guarded by `*.view`. They only ever
|
||||
-- toggled frontend buttons and showed up as dead checkboxes in role management.
|
||||
-- The 12 real keys (offers/orders/invoices x view/create/edit/delete) ARE each
|
||||
-- enforced on >=1 route and must survive.
|
||||
--
|
||||
-- All 15 keys were previously defined ONLY in prisma/seed.ts (dev-only), so a
|
||||
-- fresh production DB never had ANY of them. This migration both removes the 3
|
||||
-- dead keys AND seeds the 12 survivors + their admin grant, mirroring the
|
||||
-- prisma/seed.ts column set exactly (name, display_name, module, description,
|
||||
-- created_at; role_permissions has only the composite PK).
|
||||
--
|
||||
-- Idempotent: safe whether the rows exist or not, and safe on a prod DB that
|
||||
-- never had them. Deletes are no-ops when absent; INSERT IGNORE skips on the
|
||||
-- unique `permissions.name` key and on the `role_permissions` composite PK.
|
||||
|
||||
-- 1. Remove the dead export role assignments first (FK-safe: children before
|
||||
-- parents). No-op when the permissions/assignments don't exist.
|
||||
DELETE FROM `role_permissions`
|
||||
WHERE `permission_id` IN (
|
||||
SELECT `id` FROM `permissions`
|
||||
WHERE `name` IN ('offers.export', 'orders.export', 'invoices.export')
|
||||
);
|
||||
|
||||
-- 2. Remove the dead export permissions themselves.
|
||||
DELETE FROM `permissions`
|
||||
WHERE `name` IN ('offers.export', 'orders.export', 'invoices.export');
|
||||
|
||||
-- 3. Idempotently (re)insert the 12 surviving document permissions. INSERT
|
||||
-- IGNORE skips any that already exist (unique `name`). display_name /
|
||||
-- description / module match prisma/seed.ts verbatim.
|
||||
INSERT IGNORE INTO `permissions` (`name`, `display_name`, `module`, `description`, `created_at`) VALUES
|
||||
('offers.view', 'Zobrazit nabídky', 'offers', 'Prohlížet seznam nabídek', NOW()),
|
||||
('offers.create', 'Vytvořit nabídku', 'offers', 'Vytvářet nové nabídky', NOW()),
|
||||
('offers.edit', 'Upravit nabídku', 'offers', 'Upravovat existující nabídky', NOW()),
|
||||
('offers.delete', 'Smazat nabídku', 'offers', 'Mazat nabídky', NOW()),
|
||||
('orders.view', 'Zobrazit objednávky', 'orders', 'Prohlížet seznam objednávek', NOW()),
|
||||
('orders.create', 'Vytvořit objednávku', 'orders', 'Vytvářet nové objednávky', NOW()),
|
||||
('orders.edit', 'Upravit objednávku', 'orders', 'Upravovat existující objednávky', NOW()),
|
||||
('orders.delete', 'Smazat objednávku', 'orders', 'Mazat objednávky', NOW()),
|
||||
('invoices.view', 'Zobrazit faktury', 'invoices', 'Prohlížet seznam faktur', NOW()),
|
||||
('invoices.create', 'Vytvořit fakturu', 'invoices', 'Vytvářet nové faktury', NOW()),
|
||||
('invoices.edit', 'Upravit fakturu', 'invoices', 'Upravovat existující faktury', NOW()),
|
||||
('invoices.delete', 'Smazat fakturu', 'invoices', 'Mazat faktury', NOW());
|
||||
|
||||
-- 4. Grant all 12 survivors to the admin role. INSERT IGNORE on the composite
|
||||
-- PK (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 (
|
||||
'offers.view', 'offers.create', 'offers.edit', 'offers.delete',
|
||||
'orders.view', 'orders.create', 'orders.edit', 'orders.delete',
|
||||
'invoices.view', 'invoices.create', 'invoices.edit', 'invoices.delete'
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- DropForeignKey
|
||||
ALTER TABLE `issued_orders` DROP FOREIGN KEY `issued_orders_ibfk_1`;
|
||||
|
||||
-- DropIndex
|
||||
DROP INDEX `issued_orders_customer_id` ON `issued_orders`;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `issued_orders` DROP COLUMN `customer_id`,
|
||||
ADD COLUMN `supplier_id` INTEGER NULL;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `issued_orders_supplier_id` ON `issued_orders`(`supplier_id`);
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `issued_orders` ADD CONSTRAINT `issued_orders_supplier_fk` FOREIGN KEY (`supplier_id`) REFERENCES `sklad_suppliers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `issued_orders` ADD COLUMN `order_text` VARCHAR(500) NULL;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `issued_order_items` DROP COLUMN `vat_rate`;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `issued_orders` DROP COLUMN `apply_vat`,
|
||||
DROP COLUMN `vat_rate`;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `orders` DROP COLUMN `apply_vat`,
|
||||
DROP COLUMN `vat_rate`;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `quotations` DROP COLUMN `apply_vat`,
|
||||
DROP COLUMN `vat_rate`;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `issued_orders` ADD COLUMN `locked_at` DATETIME(0) NULL,
|
||||
ADD COLUMN `locked_by` INTEGER NULL;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `issued_order_sections` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`issued_order_id` INTEGER NOT NULL,
|
||||
`position` INTEGER NULL DEFAULT 0,
|
||||
`title` VARCHAR(500) NULL,
|
||||
`title_cz` VARCHAR(500) NULL,
|
||||
`content` TEXT NULL,
|
||||
`modified_at` DATETIME(0) NULL,
|
||||
|
||||
INDEX `issued_order_sections_order_id`(`issued_order_id`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `issued_order_sections` ADD CONSTRAINT `issued_order_sections_fk` FOREIGN KEY (`issued_order_id`) REFERENCES `issued_orders`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `issued_orders` DROP COLUMN `delivery_terms`,
|
||||
DROP COLUMN `issued_by`,
|
||||
DROP COLUMN `notes`,
|
||||
DROP COLUMN `payment_terms`;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
-- Invoices: rich-text "Obsah" sections (mirrors issued_order_sections) replace
|
||||
-- the printed notes block; notes become internal-only. Existing printed notes
|
||||
-- are preserved by merging them into internal_notes before the column drop
|
||||
-- (both are Quill HTML — concatenation is valid markup).
|
||||
|
||||
-- Preserve data: move printed notes into internal_notes
|
||||
UPDATE `invoices`
|
||||
SET `internal_notes` = CASE
|
||||
WHEN `internal_notes` IS NULL OR `internal_notes` = '' THEN `notes`
|
||||
ELSE CONCAT(`internal_notes`, `notes`)
|
||||
END
|
||||
WHERE `notes` IS NOT NULL AND `notes` <> '';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `invoices` DROP COLUMN `notes`;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `invoice_sections` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`invoice_id` INTEGER NOT NULL,
|
||||
`position` INTEGER NULL DEFAULT 0,
|
||||
`title` VARCHAR(500) NULL,
|
||||
`title_cz` VARCHAR(500) NULL,
|
||||
`content` TEXT NULL,
|
||||
`modified_at` DATETIME(0) NULL,
|
||||
|
||||
INDEX `invoice_sections_invoice_id`(`invoice_id`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `invoice_sections` ADD CONSTRAINT `invoice_sections_fk` FOREIGN KEY (`invoice_id`) REFERENCES `invoices`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Suppliers get a structured address (street/city/postal_code/country) like
|
||||
-- customers; the single free-text `address` blob is dropped. Existing data is
|
||||
-- split best-effort: newlines normalized to ", ", first comma segment ->
|
||||
-- street, the PSC (3+2 digits) -> postal_code, the remainder -> city.
|
||||
-- Unparseable one-segment addresses keep their full text in `street`.
|
||||
|
||||
-- AlterTable: add the structured columns
|
||||
ALTER TABLE `sklad_suppliers`
|
||||
ADD COLUMN `street` VARCHAR(255) NULL AFTER `phone`,
|
||||
ADD COLUMN `city` VARCHAR(255) NULL AFTER `street`,
|
||||
ADD COLUMN `postal_code` VARCHAR(20) NULL AFTER `city`,
|
||||
ADD COLUMN `country` VARCHAR(100) NULL AFTER `postal_code`;
|
||||
|
||||
-- Preserve data: best-effort split of the legacy free-text address
|
||||
UPDATE `sklad_suppliers`
|
||||
SET
|
||||
`street` = NULLIF(TRIM(SUBSTRING_INDEX(REPLACE(REPLACE(`address`, '\r', ''), '\n', ', '), ',', 1)), ''),
|
||||
`postal_code` = REGEXP_SUBSTR(`address`, '[0-9]{3}[ ]?[0-9]{2}'),
|
||||
`city` = NULLIF(TRIM(BOTH ',' FROM TRIM(REGEXP_REPLACE(
|
||||
SUBSTRING(
|
||||
REPLACE(REPLACE(`address`, '\r', ''), '\n', ', '),
|
||||
CHAR_LENGTH(SUBSTRING_INDEX(REPLACE(REPLACE(`address`, '\r', ''), '\n', ', '), ',', 1)) + 2
|
||||
),
|
||||
'[0-9]{3}[ ]?[0-9]{2}', ''))), '')
|
||||
WHERE `address` IS NOT NULL AND `address` <> '';
|
||||
|
||||
-- AlterTable: drop the legacy blob
|
||||
ALTER TABLE `sklad_suppliers` DROP COLUMN `address`;
|
||||
@@ -0,0 +1,43 @@
|
||||
-- Suppliers become a full mirror of the customers model: dedicated
|
||||
-- contact_person/email/phone/notes columns are replaced by the same
|
||||
-- custom_fields JSON blob customers use ({"fields":[{name,value,showLabel}],
|
||||
-- "field_order":[]}). Existing contact data is preserved as custom fields.
|
||||
|
||||
-- AlterTable: add the custom_fields blob
|
||||
ALTER TABLE `sklad_suppliers` ADD COLUMN `custom_fields` LONGTEXT NULL AFTER `country`;
|
||||
|
||||
-- Seed an empty container for rows that carry any contact data
|
||||
UPDATE `sklad_suppliers`
|
||||
SET `custom_fields` = JSON_OBJECT('fields', JSON_ARRAY(), 'field_order', JSON_ARRAY())
|
||||
WHERE COALESCE(`contact_person`, '') <> ''
|
||||
OR COALESCE(`email`, '') <> ''
|
||||
OR COALESCE(`phone`, '') <> ''
|
||||
OR COALESCE(`notes`, '') <> '';
|
||||
|
||||
-- Preserve data: each legacy column becomes one labeled custom field
|
||||
UPDATE `sklad_suppliers`
|
||||
SET `custom_fields` = JSON_ARRAY_APPEND(`custom_fields`, '$.fields',
|
||||
JSON_OBJECT('name', 'Kontaktní osoba', 'value', `contact_person`, 'showLabel', TRUE))
|
||||
WHERE COALESCE(`contact_person`, '') <> '';
|
||||
|
||||
UPDATE `sklad_suppliers`
|
||||
SET `custom_fields` = JSON_ARRAY_APPEND(`custom_fields`, '$.fields',
|
||||
JSON_OBJECT('name', 'E-mail', 'value', `email`, 'showLabel', TRUE))
|
||||
WHERE COALESCE(`email`, '') <> '';
|
||||
|
||||
UPDATE `sklad_suppliers`
|
||||
SET `custom_fields` = JSON_ARRAY_APPEND(`custom_fields`, '$.fields',
|
||||
JSON_OBJECT('name', 'Telefon', 'value', `phone`, 'showLabel', TRUE))
|
||||
WHERE COALESCE(`phone`, '') <> '';
|
||||
|
||||
UPDATE `sklad_suppliers`
|
||||
SET `custom_fields` = JSON_ARRAY_APPEND(`custom_fields`, '$.fields',
|
||||
JSON_OBJECT('name', 'Poznámky', 'value', `notes`, 'showLabel', TRUE))
|
||||
WHERE COALESCE(`notes`, '') <> '';
|
||||
|
||||
-- AlterTable: drop the dedicated columns
|
||||
ALTER TABLE `sklad_suppliers`
|
||||
DROP COLUMN `contact_person`,
|
||||
DROP COLUMN `email`,
|
||||
DROP COLUMN `phone`,
|
||||
DROP COLUMN `notes`;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Odin Phase 2a: assistant turns carry structured metadata (tool-call trace,
|
||||
-- later full content blocks). `content` stays the plain-text display
|
||||
-- projection; `content_json` holds the structured form. Anticipated by the
|
||||
-- Phase-2 design notes (2026-06-08).
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `ai_chat_messages` ADD COLUMN `content_json` LONGTEXT NULL AFTER `content`;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `project_notes` ADD COLUMN `edited_at` DATETIME(0) NULL;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `audit_logs` MODIFY `created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0);
|
||||
|
||||
|
||||
-- Stock invariants enforced by the database itself: a future cumulative-
|
||||
-- decrement bug (the C2 class — duplicate issue lines driving a batch
|
||||
-- negative and silently vanishing from stock totals) becomes a loud error
|
||||
-- instead of hidden corruption. All databases verified clean of negative
|
||||
-- rows before this migration (2026-06-12).
|
||||
ALTER TABLE `sklad_batches`
|
||||
ADD CONSTRAINT `chk_sklad_batches_quantity_nonneg` CHECK (`quantity` >= 0);
|
||||
|
||||
ALTER TABLE `sklad_item_locations`
|
||||
ADD CONSTRAINT `chk_sklad_item_locations_quantity_nonneg` CHECK (`quantity` >= 0);
|
||||
@@ -0,0 +1,6 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `invoice_items` ADD COLUMN `discount` DECIMAL(5, 2) NULL DEFAULT 0.00;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `quotation_items` ADD COLUMN `discount` DECIMAL(5, 2) NULL DEFAULT 0.00;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `invoices` ADD COLUMN `selected_custom_fields` VARCHAR(255) NULL;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `issued_orders` ADD COLUMN `selected_custom_fields` VARCHAR(255) NULL;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `quotations` ADD COLUMN `selected_custom_fields` VARCHAR(255) NULL;
|
||||
|
||||
@@ -4,33 +4,32 @@ generator client {
|
||||
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model attendance {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
shift_date DateTime @db.Date
|
||||
arrival_time DateTime? @db.DateTime(0)
|
||||
arrival_lat Decimal? @db.Decimal(10, 8)
|
||||
arrival_lng Decimal? @db.Decimal(11, 8)
|
||||
arrival_accuracy Decimal? @db.Decimal(10, 2)
|
||||
arrival_address String? @db.VarChar(500)
|
||||
break_start DateTime? @db.DateTime(0)
|
||||
break_end DateTime? @db.DateTime(0)
|
||||
departure_time DateTime? @db.DateTime(0)
|
||||
departure_lat Decimal? @db.Decimal(10, 8)
|
||||
departure_lng Decimal? @db.Decimal(11, 8)
|
||||
departure_accuracy Decimal? @db.Decimal(10, 2)
|
||||
departure_address String? @db.VarChar(500)
|
||||
notes String? @db.Text
|
||||
project_id Int?
|
||||
leave_type attendance_leave_type? @default(work)
|
||||
leave_hours Decimal? @db.Decimal(4, 2)
|
||||
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
users users @relation(fields: [user_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "attendance_ibfk_1")
|
||||
attendance_project_logs attendance_project_logs[]
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
shift_date DateTime @db.Date
|
||||
arrival_time DateTime? @db.DateTime(0)
|
||||
arrival_lat Decimal? @db.Decimal(10, 8)
|
||||
arrival_lng Decimal? @db.Decimal(11, 8)
|
||||
arrival_accuracy Decimal? @db.Decimal(10, 2)
|
||||
arrival_address String? @db.VarChar(500)
|
||||
break_start DateTime? @db.DateTime(0)
|
||||
break_end DateTime? @db.DateTime(0)
|
||||
departure_time DateTime? @db.DateTime(0)
|
||||
departure_lat Decimal? @db.Decimal(10, 8)
|
||||
departure_lng Decimal? @db.Decimal(11, 8)
|
||||
departure_accuracy Decimal? @db.Decimal(10, 2)
|
||||
departure_address String? @db.VarChar(500)
|
||||
notes String? @db.Text
|
||||
project_id Int?
|
||||
leave_type attendance_leave_type? @default(work)
|
||||
leave_hours Decimal? @db.Decimal(4, 2)
|
||||
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
users users @relation(fields: [user_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "attendance_ibfk_1")
|
||||
attendance_project_logs attendance_project_logs[]
|
||||
|
||||
@@index([user_id, shift_date], map: "idx_attendance_user_date")
|
||||
@@index([user_id, departure_time], map: "idx_attendance_user_departure")
|
||||
@@ -66,9 +65,10 @@ model audit_logs {
|
||||
new_values String? @db.LongText
|
||||
user_agent String? @db.Text
|
||||
session_id String? @db.VarChar(128)
|
||||
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
// DATETIME, not TIMESTAMP — TIMESTAMP dies in 2038 and converts through
|
||||
// the session timezone (2026-06-12 hardening migration).
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
|
||||
@@index([created_at], map: "idx_audit_log_created")
|
||||
@@index([action], map: "idx_audit_logs_action")
|
||||
@@index([created_at], map: "idx_audit_logs_created")
|
||||
@@index([entity_type, entity_id, created_at], map: "idx_audit_logs_entity")
|
||||
@@ -76,6 +76,43 @@ model audit_logs {
|
||||
@@fulltext([description], map: "idx_audit_search")
|
||||
}
|
||||
|
||||
model ai_usage {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int?
|
||||
kind String @db.VarChar(20)
|
||||
model String @db.VarChar(50)
|
||||
input_tokens Int @default(0)
|
||||
output_tokens Int @default(0)
|
||||
cost_usd Decimal @default(0) @db.Decimal(10, 6)
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
|
||||
@@index([created_at], map: "idx_ai_usage_created")
|
||||
}
|
||||
|
||||
model ai_conversations {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
title String @db.VarChar(255)
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime @default(now()) @updatedAt @db.Timestamp(0)
|
||||
messages ai_chat_messages[]
|
||||
|
||||
@@index([user_id, id], map: "idx_ai_conv_user")
|
||||
}
|
||||
|
||||
model ai_chat_messages {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
conversation_id Int
|
||||
role String @db.VarChar(20)
|
||||
content String @db.Text
|
||||
content_json String? @db.LongText
|
||||
created_at DateTime @default(now()) @db.Timestamp(0)
|
||||
conversation ai_conversations @relation(fields: [conversation_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([conversation_id, id], map: "idx_ai_chat_conv")
|
||||
}
|
||||
|
||||
model bank_accounts {
|
||||
id Int @id @default(autoincrement())
|
||||
account_name String? @db.VarChar(255)
|
||||
@@ -88,52 +125,59 @@ model bank_accounts {
|
||||
position Int? @default(0)
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
|
||||
@@index([is_default], map: "idx_bank_accounts_is_default")
|
||||
}
|
||||
|
||||
model company_settings {
|
||||
id Int @id @default(autoincrement())
|
||||
company_name String? @db.VarChar(255)
|
||||
street String? @db.VarChar(255)
|
||||
city String? @db.VarChar(255)
|
||||
postal_code String? @db.VarChar(20)
|
||||
country String? @db.VarChar(100)
|
||||
company_id String? @db.VarChar(50)
|
||||
vat_id String? @db.VarChar(50)
|
||||
custom_fields String? @db.LongText
|
||||
logo_data Bytes?
|
||||
logo_data_dark Bytes? @db.MediumBlob
|
||||
quotation_prefix String? @db.VarChar(20)
|
||||
default_currency String? @default("CZK") @db.VarChar(10)
|
||||
default_vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
uuid String? @unique @db.VarChar(36)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
is_deleted Boolean? @default(false)
|
||||
sync_version Int? @default(0)
|
||||
order_type_code String? @db.VarChar(10)
|
||||
invoice_type_code String? @db.VarChar(10)
|
||||
require_2fa Boolean @default(false)
|
||||
break_threshold_hours Decimal? @default(6.00) @db.Decimal(4, 2)
|
||||
break_duration_short Int? @default(15)
|
||||
break_duration_long Int? @default(30)
|
||||
clock_rounding_minutes Int? @default(15)
|
||||
invoice_alert_email String? @db.VarChar(255)
|
||||
leave_notify_email String? @db.VarChar(255)
|
||||
max_login_attempts Int? @default(5)
|
||||
lockout_minutes Int? @default(15)
|
||||
max_requests_per_minute Int? @default(300)
|
||||
available_vat_rates String? @db.LongText
|
||||
available_currencies String? @db.LongText
|
||||
smtp_from String? @db.VarChar(255)
|
||||
smtp_from_name String? @db.VarChar(255)
|
||||
offer_number_pattern String? @db.VarChar(100)
|
||||
order_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)
|
||||
id Int @id @default(autoincrement())
|
||||
company_name String? @db.VarChar(255)
|
||||
street String? @db.VarChar(255)
|
||||
city String? @db.VarChar(255)
|
||||
postal_code String? @db.VarChar(20)
|
||||
country String? @db.VarChar(100)
|
||||
company_id String? @db.VarChar(50)
|
||||
vat_id String? @db.VarChar(50)
|
||||
custom_fields String? @db.LongText
|
||||
logo_data Bytes?
|
||||
logo_data_dark Bytes? @db.MediumBlob
|
||||
quotation_prefix String? @db.VarChar(20)
|
||||
default_currency String? @default("CZK") @db.VarChar(10)
|
||||
default_vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
uuid String? @unique @db.VarChar(36)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
is_deleted Boolean? @default(false)
|
||||
sync_version Int? @default(0)
|
||||
order_type_code String? @db.VarChar(10)
|
||||
invoice_type_code String? @db.VarChar(10)
|
||||
require_2fa Boolean @default(false)
|
||||
break_threshold_hours Decimal? @default(6.00) @db.Decimal(4, 2)
|
||||
break_duration_short Int? @default(15)
|
||||
break_duration_long Int? @default(30)
|
||||
clock_rounding_minutes Int? @default(15)
|
||||
invoice_alert_email String? @db.VarChar(255)
|
||||
leave_notify_email String? @db.VarChar(255)
|
||||
max_login_attempts Int? @default(5)
|
||||
lockout_minutes Int? @default(15)
|
||||
max_requests_per_minute Int? @default(300)
|
||||
available_vat_rates String? @db.LongText
|
||||
available_currencies String? @db.LongText
|
||||
smtp_from String? @db.VarChar(255)
|
||||
smtp_from_name String? @db.VarChar(255)
|
||||
offer_number_pattern String? @db.VarChar(100)
|
||||
order_number_pattern String? @db.VarChar(100)
|
||||
invoice_number_pattern String? @db.VarChar(100)
|
||||
issued_order_number_pattern String? @db.VarChar(100)
|
||||
issued_order_type_code String? @db.VarChar(10)
|
||||
project_number_pattern String? @db.VarChar(100)
|
||||
project_type_code String? @db.VarChar(10)
|
||||
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)
|
||||
ai_monthly_budget_usd Decimal? @default(50.00) @db.Decimal(10, 2)
|
||||
}
|
||||
|
||||
model customers {
|
||||
@@ -157,49 +201,51 @@ model customers {
|
||||
}
|
||||
|
||||
model invoice_items {
|
||||
id Int @id @default(autoincrement())
|
||||
invoice_id Int
|
||||
description String? @db.VarChar(500)
|
||||
id Int @id @default(autoincrement())
|
||||
invoice_id Int
|
||||
description String? @db.VarChar(500)
|
||||
item_description String? @db.Text
|
||||
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
||||
unit String? @db.VarChar(20)
|
||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
position Int? @default(0)
|
||||
invoices invoices @relation(fields: [invoice_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "invoice_items_ibfk_1")
|
||||
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
||||
unit String? @db.VarChar(20)
|
||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||
discount Decimal? @default(0.00) @db.Decimal(5, 2)
|
||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
position Int? @default(0)
|
||||
invoices invoices @relation(fields: [invoice_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "invoice_items_ibfk_1")
|
||||
|
||||
@@index([invoice_id], map: "invoice_id")
|
||||
}
|
||||
|
||||
model invoices {
|
||||
id Int @id @default(autoincrement())
|
||||
invoice_number String? @unique(map: "idx_invoices_number_unique") @db.VarChar(50)
|
||||
order_id Int?
|
||||
customer_id Int?
|
||||
status String? @default("issued") @db.VarChar(30)
|
||||
currency String? @default("CZK") @db.VarChar(10)
|
||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
apply_vat Boolean? @default(true)
|
||||
payment_method String? @db.VarChar(50)
|
||||
constant_symbol String? @db.VarChar(20)
|
||||
bank_name String? @db.VarChar(255)
|
||||
bank_swift String? @db.VarChar(20)
|
||||
bank_iban String? @db.VarChar(50)
|
||||
bank_account String? @db.VarChar(50)
|
||||
issue_date DateTime? @db.Date
|
||||
due_date DateTime? @db.Date
|
||||
tax_date DateTime? @db.Date
|
||||
paid_date DateTime? @db.Date
|
||||
issued_by String? @db.VarChar(255)
|
||||
billing_text String? @db.VarChar(500)
|
||||
language String? @default("cs") @db.VarChar(5)
|
||||
notes String? @db.Text
|
||||
internal_notes String? @db.Text
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
invoice_items invoice_items[]
|
||||
orders orders? @relation(fields: [order_id], references: [id], onUpdate: NoAction, map: "invoices_ibfk_1")
|
||||
customers customers? @relation(fields: [customer_id], references: [id], onUpdate: NoAction, map: "invoices_ibfk_2")
|
||||
id Int @id @default(autoincrement())
|
||||
invoice_number String? @unique(map: "idx_invoices_number_unique") @db.VarChar(50)
|
||||
order_id Int?
|
||||
customer_id Int?
|
||||
status String? @default("issued") @db.VarChar(30)
|
||||
currency String? @default("CZK") @db.VarChar(10)
|
||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
apply_vat Boolean? @default(true)
|
||||
payment_method String? @db.VarChar(50)
|
||||
constant_symbol String? @db.VarChar(20)
|
||||
bank_name String? @db.VarChar(255)
|
||||
bank_swift String? @db.VarChar(20)
|
||||
bank_iban String? @db.VarChar(50)
|
||||
bank_account String? @db.VarChar(50)
|
||||
issue_date DateTime? @db.Date
|
||||
due_date DateTime? @db.Date
|
||||
tax_date DateTime? @db.Date
|
||||
paid_date DateTime? @db.Date
|
||||
issued_by String? @db.VarChar(255)
|
||||
billing_text String? @db.VarChar(500)
|
||||
language String? @default("cs") @db.VarChar(5)
|
||||
internal_notes String? @db.Text
|
||||
selected_custom_fields String? @db.VarChar(255)
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
invoice_items invoice_items[]
|
||||
invoice_sections invoice_sections[]
|
||||
orders orders? @relation(fields: [order_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "invoices_ibfk_1")
|
||||
customers customers? @relation(fields: [customer_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "invoices_ibfk_2")
|
||||
|
||||
@@index([customer_id], map: "customer_id")
|
||||
@@index([due_date], map: "idx_invoices_due_date")
|
||||
@@ -208,6 +254,19 @@ model invoices {
|
||||
@@index([order_id], map: "order_id")
|
||||
}
|
||||
|
||||
model invoice_sections {
|
||||
id Int @id @default(autoincrement())
|
||||
invoice_id Int
|
||||
position Int? @default(0)
|
||||
title String? @db.VarChar(500)
|
||||
title_cz String? @db.VarChar(500)
|
||||
content String? @db.Text
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
invoices invoices @relation(fields: [invoice_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "invoice_sections_fk")
|
||||
|
||||
@@index([invoice_id], map: "invoice_sections_invoice_id")
|
||||
}
|
||||
|
||||
model item_templates {
|
||||
id Int @id @default(autoincrement())
|
||||
name String? @db.VarChar(255)
|
||||
@@ -306,8 +365,6 @@ model orders {
|
||||
status String? @default("prijata") @db.VarChar(30)
|
||||
currency String? @default("CZK") @db.VarChar(10)
|
||||
language String? @default("cs") @db.VarChar(5)
|
||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
apply_vat Boolean? @default(true)
|
||||
exchange_rate Decimal? @default(1.0000) @db.Decimal(10, 4)
|
||||
scope_title String? @db.VarChar(500)
|
||||
scope_description String? @db.Text
|
||||
@@ -317,14 +374,77 @@ model orders {
|
||||
invoices invoices[]
|
||||
order_items order_items[]
|
||||
order_sections order_sections[]
|
||||
quotations quotations? @relation(fields: [quotation_id], references: [id], onUpdate: NoAction, map: "orders_ibfk_1")
|
||||
customers customers? @relation(fields: [customer_id], references: [id], onUpdate: NoAction, map: "orders_ibfk_2")
|
||||
quotations quotations? @relation(fields: [quotation_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "orders_ibfk_1")
|
||||
customers customers? @relation(fields: [customer_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "orders_ibfk_2")
|
||||
projects projects[]
|
||||
|
||||
@@index([customer_id], map: "customer_id")
|
||||
@@index([quotation_id], map: "quotation_id")
|
||||
}
|
||||
|
||||
model issued_orders {
|
||||
id Int @id @default(autoincrement())
|
||||
po_number String? @unique(map: "idx_issued_orders_number_unique") @db.VarChar(50)
|
||||
supplier_id Int?
|
||||
status issued_orders_status @default(draft)
|
||||
currency String? @default("CZK") @db.VarChar(10)
|
||||
exchange_rate Decimal? @default(1.0000) @db.Decimal(10, 4)
|
||||
order_date DateTime? @db.Date
|
||||
delivery_date DateTime? @db.Date
|
||||
language String? @default("cs") @db.VarChar(5)
|
||||
order_text String? @db.VarChar(500)
|
||||
internal_notes String? @db.Text
|
||||
selected_custom_fields String? @db.VarChar(255)
|
||||
locked_by Int?
|
||||
locked_at DateTime? @db.DateTime(0)
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
issued_order_items issued_order_items[]
|
||||
issued_order_sections issued_order_sections[]
|
||||
suppliers sklad_suppliers? @relation(fields: [supplier_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "issued_orders_supplier_fk")
|
||||
|
||||
@@index([supplier_id], map: "issued_orders_supplier_id")
|
||||
@@index([status, order_date], map: "idx_issued_orders_status_date")
|
||||
}
|
||||
|
||||
// Mirrors scope_sections (offers) 1:1 — free-form bilingual rich-text sections
|
||||
// rendered on their own PDF page. Kept as a separate table (not shared) so the
|
||||
// FK cascade and per-document ordering stay simple.
|
||||
model issued_order_sections {
|
||||
id Int @id @default(autoincrement())
|
||||
issued_order_id Int
|
||||
position Int? @default(0)
|
||||
title String? @db.VarChar(500)
|
||||
title_cz String? @db.VarChar(500)
|
||||
content String? @db.Text
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
issued_orders issued_orders @relation(fields: [issued_order_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "issued_order_sections_fk")
|
||||
|
||||
@@index([issued_order_id], map: "issued_order_sections_order_id")
|
||||
}
|
||||
|
||||
model issued_order_items {
|
||||
id Int @id @default(autoincrement())
|
||||
issued_order_id Int
|
||||
description String? @db.VarChar(500)
|
||||
item_description String? @db.Text
|
||||
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
||||
unit String? @db.VarChar(20)
|
||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||
position Int? @default(0)
|
||||
issued_orders issued_orders @relation(fields: [issued_order_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "issued_order_items_ibfk_1")
|
||||
|
||||
@@index([issued_order_id], map: "issued_order_id")
|
||||
}
|
||||
|
||||
enum issued_orders_status {
|
||||
draft
|
||||
sent
|
||||
confirmed
|
||||
completed
|
||||
cancelled
|
||||
}
|
||||
|
||||
model permissions {
|
||||
id Int @id @default(autoincrement())
|
||||
name String @unique(map: "name") @db.VarChar(50)
|
||||
@@ -342,35 +462,36 @@ model project_notes {
|
||||
user_name String? @db.VarChar(100)
|
||||
content String? @db.Text
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
edited_at DateTime? @db.DateTime(0)
|
||||
projects projects @relation(fields: [project_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "project_notes_ibfk_1")
|
||||
|
||||
@@index([project_id], map: "project_id")
|
||||
}
|
||||
|
||||
model projects {
|
||||
id Int @id @default(autoincrement())
|
||||
project_number String? @unique @db.VarChar(50)
|
||||
name String? @db.VarChar(255)
|
||||
customer_id Int?
|
||||
responsible_user_id Int?
|
||||
quotation_id Int?
|
||||
order_id Int?
|
||||
status String? @default("aktivni") @db.VarChar(30)
|
||||
start_date DateTime? @db.Date
|
||||
end_date DateTime? @db.Date
|
||||
notes String? @db.Text
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
id Int @id @default(autoincrement())
|
||||
project_number String? @unique @db.VarChar(50)
|
||||
name String? @db.VarChar(255)
|
||||
customer_id Int?
|
||||
responsible_user_id Int?
|
||||
quotation_id Int?
|
||||
order_id Int?
|
||||
status String? @default("aktivni") @db.VarChar(30)
|
||||
start_date DateTime? @db.Date
|
||||
end_date DateTime? @db.Date
|
||||
notes String? @db.Text
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
attendance_project_logs attendance_project_logs[]
|
||||
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")
|
||||
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")
|
||||
orders orders? @relation(fields: [order_id], references: [id], onUpdate: NoAction, map: "projects_ibfk_3")
|
||||
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")
|
||||
customers customers? @relation(fields: [customer_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "projects_ibfk_1")
|
||||
quotations quotations? @relation(fields: [quotation_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "projects_ibfk_2")
|
||||
orders orders? @relation(fields: [order_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "projects_ibfk_3")
|
||||
|
||||
@@index([customer_id], map: "customer_id")
|
||||
@@index([responsible_user_id], map: "fk_projects_responsible_user")
|
||||
@@ -387,6 +508,7 @@ model quotation_items {
|
||||
quantity Decimal? @default(1.000) @db.Decimal(12, 3)
|
||||
unit String? @db.VarChar(20)
|
||||
unit_price Decimal? @default(0.00) @db.Decimal(12, 2)
|
||||
discount Decimal? @default(0.00) @db.Decimal(5, 2)
|
||||
is_included_in_total Boolean? @default(true)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "quotation_items_ibfk_1")
|
||||
@@ -395,28 +517,27 @@ model quotation_items {
|
||||
}
|
||||
|
||||
model quotations {
|
||||
id Int @id @default(autoincrement())
|
||||
quotation_number String? @unique @db.VarChar(50)
|
||||
project_code String? @db.VarChar(100)
|
||||
customer_id Int?
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
valid_until DateTime? @db.Date
|
||||
currency String? @default("CZK") @db.VarChar(10)
|
||||
language String? @default("cs") @db.VarChar(5)
|
||||
vat_rate Decimal? @default(21.00) @db.Decimal(5, 2)
|
||||
apply_vat Boolean? @default(true)
|
||||
order_id Int?
|
||||
status String @default("active") @db.VarChar(20)
|
||||
scope_title String? @db.VarChar(500)
|
||||
scope_description String? @db.Text
|
||||
locked_by Int?
|
||||
locked_at DateTime? @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
orders orders[]
|
||||
projects projects[]
|
||||
quotation_items quotation_items[]
|
||||
customers customers? @relation(fields: [customer_id], references: [id], onUpdate: NoAction, map: "quotations_ibfk_1")
|
||||
scope_sections scope_sections[]
|
||||
id Int @id @default(autoincrement())
|
||||
quotation_number String? @unique @db.VarChar(50)
|
||||
project_code String? @db.VarChar(100)
|
||||
customer_id Int?
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
valid_until DateTime? @db.Date
|
||||
currency String? @default("CZK") @db.VarChar(10)
|
||||
language String? @default("cs") @db.VarChar(5)
|
||||
order_id Int?
|
||||
status String @default("active") @db.VarChar(20)
|
||||
scope_title String? @db.VarChar(500)
|
||||
scope_description String? @db.Text
|
||||
selected_custom_fields String? @db.VarChar(255)
|
||||
locked_by Int?
|
||||
locked_at DateTime? @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
orders orders[]
|
||||
projects projects[]
|
||||
quotation_items quotation_items[]
|
||||
customers customers? @relation(fields: [customer_id], references: [id], onDelete: Restrict, onUpdate: NoAction, map: "quotations_ibfk_1")
|
||||
scope_sections scope_sections[]
|
||||
|
||||
@@index([customer_id], map: "customer_id")
|
||||
@@index([quotation_number], map: "idx_quotations_number")
|
||||
@@ -490,14 +611,14 @@ model roles {
|
||||
}
|
||||
|
||||
model scope_sections {
|
||||
id Int @id @default(autoincrement())
|
||||
quotation_id Int
|
||||
position Int? @default(0)
|
||||
title String? @db.VarChar(500)
|
||||
title_cz String? @db.VarChar(500)
|
||||
content String? @db.Text
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "scope_sections_ibfk_1")
|
||||
id Int @id @default(autoincrement())
|
||||
quotation_id Int
|
||||
position Int? @default(0)
|
||||
title String? @db.VarChar(500)
|
||||
title_cz String? @db.VarChar(500)
|
||||
content String? @db.Text
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
quotations quotations @relation(fields: [quotation_id], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "scope_sections_ibfk_1")
|
||||
|
||||
@@index([quotation_id], map: "quotation_id")
|
||||
}
|
||||
@@ -566,38 +687,38 @@ model trips {
|
||||
}
|
||||
|
||||
model users {
|
||||
id Int @id @default(autoincrement())
|
||||
username String @unique(map: "username") @db.VarChar(50)
|
||||
email String @unique(map: "email") @db.VarChar(255)
|
||||
password_hash String @db.VarChar(255)
|
||||
first_name String @db.VarChar(50)
|
||||
last_name String @db.VarChar(50)
|
||||
id Int @id @default(autoincrement())
|
||||
username String @unique(map: "username") @db.VarChar(50)
|
||||
email String @unique(map: "email") @db.VarChar(255)
|
||||
password_hash String @db.VarChar(255)
|
||||
first_name String @db.VarChar(50)
|
||||
last_name String @db.VarChar(50)
|
||||
role_id Int?
|
||||
is_active Boolean? @default(true)
|
||||
last_login DateTime? @db.Timestamp(0)
|
||||
failed_login_attempts Int? @default(0)
|
||||
locked_until DateTime? @db.Timestamp(0)
|
||||
password_changed_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
totp_secret String? @db.VarChar(255)
|
||||
totp_enabled Boolean @default(false)
|
||||
totp_backup_codes String? @db.Text
|
||||
is_active Boolean? @default(true)
|
||||
last_login DateTime? @db.Timestamp(0)
|
||||
failed_login_attempts Int? @default(0)
|
||||
locked_until DateTime? @db.Timestamp(0)
|
||||
password_changed_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
created_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
updated_at DateTime? @default(now()) @db.Timestamp(0)
|
||||
totp_secret String? @db.VarChar(255)
|
||||
totp_enabled Boolean @default(false)
|
||||
totp_backup_codes String? @db.Text
|
||||
totp_last_used_counter Int?
|
||||
attendance attendance[]
|
||||
leave_balances leave_balances[]
|
||||
leave_requests_leave_requests_user_idTousers leave_requests[] @relation("leave_requests_user_idTousers")
|
||||
leave_requests_leave_requests_reviewer_idTousers leave_requests[] @relation("leave_requests_reviewer_idTousers")
|
||||
leave_requests_leave_requests_user_idTousers leave_requests[] @relation("leave_requests_user_idTousers")
|
||||
leave_requests_leave_requests_reviewer_idTousers leave_requests[] @relation("leave_requests_reviewer_idTousers")
|
||||
projects projects[]
|
||||
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")
|
||||
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([role_id], map: "idx_users_role_id")
|
||||
@@ -692,20 +813,21 @@ model 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)
|
||||
id Int @id @default(autoincrement())
|
||||
name String @db.VarChar(255)
|
||||
ico String? @db.VarChar(20)
|
||||
dic String? @db.VarChar(20)
|
||||
street String? @db.VarChar(255)
|
||||
city String? @db.VarChar(255)
|
||||
postal_code String? @db.VarChar(20)
|
||||
country String? @db.VarChar(100)
|
||||
custom_fields String? @db.LongText
|
||||
is_active Boolean @default(true)
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
|
||||
receipts sklad_receipts[]
|
||||
receipts sklad_receipts[]
|
||||
issued_orders issued_orders[]
|
||||
|
||||
@@map("sklad_suppliers")
|
||||
}
|
||||
@@ -719,7 +841,7 @@ model sklad_locations {
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
|
||||
items sklad_item_locations[]
|
||||
items sklad_item_locations[]
|
||||
receipt_lines sklad_receipt_lines[]
|
||||
issue_lines sklad_issue_lines[]
|
||||
inventory_lines sklad_inventory_lines[]
|
||||
@@ -728,19 +850,19 @@ model 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)
|
||||
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])
|
||||
category sklad_categories? @relation(fields: [category_id], references: [id], onDelete: SetNull)
|
||||
batches sklad_batches[]
|
||||
item_locations sklad_item_locations[]
|
||||
receipt_lines sklad_receipt_lines[]
|
||||
@@ -755,170 +877,174 @@ model sklad_items {
|
||||
model sklad_batches {
|
||||
id Int @id @default(autoincrement())
|
||||
item_id Int
|
||||
receipt_line_id Int @unique
|
||||
quantity Decimal @db.Decimal(12, 3)
|
||||
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[]
|
||||
item sklad_items @relation(fields: [item_id], references: [id], onDelete: Restrict)
|
||||
receipt_line sklad_receipt_lines @relation(fields: [receipt_line_id], references: [id], onDelete: Restrict)
|
||||
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())
|
||||
id Int @id @default(autoincrement())
|
||||
item_id Int
|
||||
location_id Int
|
||||
quantity Decimal @default(0) @db.Decimal(12, 3)
|
||||
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])
|
||||
item sklad_items @relation(fields: [item_id], references: [id], onDelete: Restrict)
|
||||
location sklad_locations @relation(fields: [location_id], references: [id], onDelete: Restrict)
|
||||
|
||||
@@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)
|
||||
id Int @id @default(autoincrement())
|
||||
receipt_number String? @unique @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[]
|
||||
supplier sklad_suppliers? @relation(fields: [supplier_id], references: [id], onDelete: SetNull)
|
||||
received_by_user users? @relation("SkladReceivedBy", fields: [received_by], references: [id], onDelete: SetNull)
|
||||
items sklad_receipt_lines[]
|
||||
attachments sklad_receipt_attachments[]
|
||||
|
||||
@@index([supplier_id], map: "sklad_receipts_supplier_id")
|
||||
@@index([received_by], map: "sklad_receipts_received_by")
|
||||
@@map("sklad_receipts")
|
||||
}
|
||||
|
||||
model sklad_receipt_lines {
|
||||
id Int @id @default(autoincrement())
|
||||
id Int @id @default(autoincrement())
|
||||
receipt_id Int
|
||||
item_id Int
|
||||
quantity Decimal @db.Decimal(12, 3)
|
||||
unit_price Decimal @db.Decimal(12, 2)
|
||||
quantity Decimal @db.Decimal(12, 3)
|
||||
unit_price Decimal @db.Decimal(12, 2)
|
||||
location_id Int?
|
||||
notes String? @db.VarChar(255)
|
||||
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?
|
||||
receipt sklad_receipts @relation(fields: [receipt_id], references: [id], onDelete: Cascade)
|
||||
item sklad_items @relation(fields: [item_id], references: [id], onDelete: Restrict)
|
||||
location sklad_locations? @relation(fields: [location_id], references: [id], onDelete: Restrict)
|
||||
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)
|
||||
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])
|
||||
receipt sklad_receipts @relation(fields: [receipt_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@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)
|
||||
id Int @id @default(autoincrement())
|
||||
issue_number String? @unique @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[]
|
||||
project projects @relation(fields: [project_id], references: [id], onDelete: Restrict)
|
||||
issued_by_user users? @relation("SkladIssuedBy", fields: [issued_by], references: [id], onDelete: SetNull)
|
||||
items sklad_issue_lines[]
|
||||
|
||||
@@index([project_id], map: "sklad_issues_project_id")
|
||||
@@index([issued_by], map: "sklad_issues_issued_by")
|
||||
@@map("sklad_issues")
|
||||
}
|
||||
|
||||
model sklad_issue_lines {
|
||||
id Int @id @default(autoincrement())
|
||||
id Int @id @default(autoincrement())
|
||||
issue_id Int
|
||||
item_id Int
|
||||
batch_id Int
|
||||
quantity Decimal @db.Decimal(12, 3)
|
||||
quantity Decimal @db.Decimal(12, 3)
|
||||
location_id Int?
|
||||
reservation_id Int?
|
||||
notes String? @db.VarChar(255)
|
||||
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])
|
||||
issue sklad_issues @relation(fields: [issue_id], references: [id], onDelete: Cascade)
|
||||
item sklad_items @relation(fields: [item_id], references: [id], onDelete: Restrict)
|
||||
batch sklad_batches @relation(fields: [batch_id], references: [id], onDelete: Restrict)
|
||||
location sklad_locations? @relation(fields: [location_id], references: [id], onDelete: Restrict)
|
||||
reservation sklad_reservations? @relation(fields: [reservation_id], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([issue_id], map: "sklad_issue_lines_issue_id")
|
||||
@@map("sklad_issue_lines")
|
||||
}
|
||||
|
||||
model sklad_reservations {
|
||||
id Int @id @default(autoincrement())
|
||||
id Int @id @default(autoincrement())
|
||||
item_id Int
|
||||
project_id Int
|
||||
quantity Decimal @db.Decimal(12, 3)
|
||||
remaining_qty Decimal @db.Decimal(12, 3)
|
||||
quantity Decimal @db.Decimal(12, 3)
|
||||
remaining_qty Decimal @db.Decimal(12, 3)
|
||||
reserved_by Int?
|
||||
notes String? @db.Text
|
||||
notes String? @db.Text
|
||||
status sklad_reservation_status @default(ACTIVE)
|
||||
created_at DateTime? @default(now()) @db.DateTime(0)
|
||||
modified_at DateTime? @db.DateTime(0)
|
||||
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[]
|
||||
item sklad_items @relation(fields: [item_id], references: [id], onDelete: Restrict)
|
||||
project projects @relation(fields: [project_id], references: [id], onDelete: Restrict)
|
||||
reserved_by_user users? @relation("SkladReservedBy", fields: [reserved_by], references: [id], onDelete: SetNull)
|
||||
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)
|
||||
id Int @id @default(autoincrement())
|
||||
session_number String? @unique @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[]
|
||||
items sklad_inventory_lines[]
|
||||
|
||||
@@map("sklad_inventory_sessions")
|
||||
}
|
||||
|
||||
model sklad_inventory_lines {
|
||||
id Int @id @default(autoincrement())
|
||||
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)
|
||||
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])
|
||||
session sklad_inventory_sessions @relation(fields: [session_id], references: [id], onDelete: Cascade)
|
||||
item sklad_items @relation(fields: [item_id], references: [id], onDelete: Restrict)
|
||||
location sklad_locations? @relation(fields: [location_id], references: [id], onDelete: Restrict)
|
||||
|
||||
@@index([session_id], map: "sklad_inventory_lines_session_id")
|
||||
@@map("sklad_inventory_lines")
|
||||
@@ -936,20 +1062,20 @@ model plan_categories {
|
||||
}
|
||||
|
||||
model work_plan_entries {
|
||||
id Int @id @default(autoincrement())
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
date_from DateTime @db.Date
|
||||
date_to DateTime @db.Date
|
||||
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)
|
||||
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)
|
||||
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")
|
||||
@@ -958,19 +1084,19 @@ model work_plan_entries {
|
||||
}
|
||||
|
||||
model work_plan_overrides {
|
||||
id Int @id @default(autoincrement())
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int
|
||||
shift_date DateTime @db.Date
|
||||
shift_date DateTime @db.Date
|
||||
project_id Int?
|
||||
category String @db.VarChar(50)
|
||||
note String @db.VarChar(500)
|
||||
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)
|
||||
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")
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import "dotenv/config";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
// Use the shared, adapter-wired client (Prisma 7 needs a driver adapter).
|
||||
// dotenv is imported first so DATABASE_URL is set before database.ts reads it.
|
||||
import prisma from "../src/config/database";
|
||||
|
||||
const PERMISSIONS: {
|
||||
name: string;
|
||||
@@ -94,12 +95,6 @@ const PERMISSIONS: {
|
||||
module: "offers",
|
||||
description: "Mazat nabídky",
|
||||
},
|
||||
{
|
||||
name: "offers.export",
|
||||
display_name: "Exportovat nabídku",
|
||||
module: "offers",
|
||||
description: "Exportovat nabídky do PDF",
|
||||
},
|
||||
|
||||
// Objednávky
|
||||
{
|
||||
@@ -126,12 +121,6 @@ const PERMISSIONS: {
|
||||
module: "orders",
|
||||
description: "Mazat objednávky",
|
||||
},
|
||||
{
|
||||
name: "orders.export",
|
||||
display_name: "Exportovat objednávku",
|
||||
module: "orders",
|
||||
description: "Exportovat objednávky do PDF",
|
||||
},
|
||||
|
||||
// Faktury
|
||||
{
|
||||
@@ -158,12 +147,6 @@ const PERMISSIONS: {
|
||||
module: "invoices",
|
||||
description: "Mazat faktury",
|
||||
},
|
||||
{
|
||||
name: "invoices.export",
|
||||
display_name: "Exportovat fakturu",
|
||||
module: "invoices",
|
||||
description: "Exportovat faktury do PDF",
|
||||
},
|
||||
|
||||
// Projekty
|
||||
{
|
||||
@@ -312,9 +295,35 @@ const PERMISSIONS: {
|
||||
module: "warehouse",
|
||||
description: "Vytvářet a potvrzovat inventurní sčítkání",
|
||||
},
|
||||
|
||||
// AI asistent (Odin) — mirrors migration 20260608120000_add_ai_assistant;
|
||||
// the seed WIPES permissions, so every migration-added permission must also
|
||||
// live here or a dev reseed silently loses it (happened 2026-06-10).
|
||||
{
|
||||
name: "ai.use",
|
||||
display_name: "AI asistent",
|
||||
module: "ai",
|
||||
description: "Používat AI asistenta (chat a import faktur)",
|
||||
},
|
||||
];
|
||||
|
||||
async function main() {
|
||||
// HARD PRODUCTION GUARD: this seed unconditionally wipes ALL permissions and
|
||||
// role_permissions (and seeds an admin/admin user) — purely dev-convenience
|
||||
// behavior. Production baseline data must come from tracked Prisma migrations,
|
||||
// never from the seed (see CLAUDE.md "Database Migrations"). Refuse to run on
|
||||
// production so the destructive wipe can never hit a live database.
|
||||
if (process.env.APP_ENV === "production") {
|
||||
throw new Error(
|
||||
"Odmítnuto: prisma/seed.ts NESMÍ běžet na produkci (APP_ENV=production). " +
|
||||
"Seed maže všechna oprávnění a je určen pouze pro vývoj. " +
|
||||
"Produkční data musí být zavedena migrací.\n" +
|
||||
"Refusing to run: prisma/seed.ts must NEVER run on production " +
|
||||
"(APP_ENV=production). It wipes all permissions and is dev-only; " +
|
||||
"seed production baseline data via a migration instead.",
|
||||
);
|
||||
}
|
||||
|
||||
console.log("Seeding permissions...");
|
||||
|
||||
// 1. Clear existing permissions and re-insert current set
|
||||
@@ -382,12 +391,12 @@ async function main() {
|
||||
console.log(` Admin role now has all ${allPerms.length} permissions`);
|
||||
|
||||
// 4. Ensure admin user exists
|
||||
let adminUser = await prisma.users.findFirst({
|
||||
const adminUser = await prisma.users.findFirst({
|
||||
where: { username: "admin" },
|
||||
});
|
||||
if (!adminUser) {
|
||||
const hash = bcrypt.hashSync("admin", 10);
|
||||
adminUser = await prisma.users.create({
|
||||
await prisma.users.create({
|
||||
data: {
|
||||
username: "admin",
|
||||
email: "admin@boha.local",
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
*/
|
||||
|
||||
import "../src/config/env";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import fs from "fs";
|
||||
import { nasFinancialsManager } from "../src/services/nas-financials-manager";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
// Shared adapter-wired client (Prisma 7 needs a driver adapter).
|
||||
import prisma from "../src/config/database";
|
||||
|
||||
async function main() {
|
||||
if (!nasFinancialsManager.isConfigured()) {
|
||||
@@ -51,6 +51,39 @@ async function main() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Read-back verification before we null out the ONLY DB copy of the bytes.
|
||||
// The manager uses writeFileSync (synchronous) and returns a relative path;
|
||||
// resolve it back to disk and confirm the file exists and its size matches
|
||||
// the source buffer. A 0-byte/truncated/corrupt write would otherwise lose
|
||||
// the invoice permanently once file_data is set to null. If verification
|
||||
// fails we KEEP file_data and report the row as failed.
|
||||
const expectedSize = rec.file_data.length;
|
||||
const readBack = nasFinancialsManager.readReceivedInvoice(result.filePath);
|
||||
let writtenSize: number;
|
||||
if (readBack) {
|
||||
writtenSize = readBack.data.length;
|
||||
} else {
|
||||
// Fall back to a direct stat in case readReceivedInvoice's path guard
|
||||
// rejects an otherwise-valid path; either way we need a confirmed size.
|
||||
try {
|
||||
writtenSize = fs.statSync(
|
||||
(nasFinancialsManager as unknown as { basePath: string }).basePath +
|
||||
"/" +
|
||||
result.filePath,
|
||||
).size;
|
||||
} catch {
|
||||
writtenSize = -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (writtenSize !== expectedSize) {
|
||||
console.error(
|
||||
` FAIL id=${rec.id}: read-back mismatch (expected ${expectedSize} bytes, got ${writtenSize}); keeping DB copy`,
|
||||
);
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
|
||||
await prisma.received_invoices.update({
|
||||
where: { id: rec.id },
|
||||
data: { file_path: result.filePath, file_data: null },
|
||||
|
||||
@@ -1,35 +1,29 @@
|
||||
import crypto from 'crypto';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import "dotenv/config";
|
||||
import { decryptWithKey, encryptWithKey } from "../src/utils/encryption";
|
||||
// Shared adapter-wired client (Prisma 7 needs a driver adapter).
|
||||
import prisma from "../src/config/database";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
function decrypt(ciphertext: string, keyHex: string): string {
|
||||
const key = Buffer.from(keyHex, 'hex');
|
||||
const [ivHex, encHex, tagHex] = ciphertext.split(':');
|
||||
const iv = Buffer.from(ivHex, 'hex');
|
||||
const encrypted = Buffer.from(encHex, 'hex');
|
||||
const tag = Buffer.from(tagHex, 'hex');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
return decipher.update(encrypted, undefined, 'utf8') + decipher.final('utf8');
|
||||
}
|
||||
|
||||
function encrypt(plaintext: string, keyHex: string): string {
|
||||
const key = Buffer.from(keyHex, 'hex');
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return `${iv.toString('hex')}:${encrypted.toString('hex')}:${tag.toString('hex')}`;
|
||||
}
|
||||
// Reuse the dual-format decrypt/encrypt from src/utils/encryption.ts so this
|
||||
// script handles BOTH wire formats: the TS `hex:hex:hex` form and the
|
||||
// PHP-legacy single-base64 blob. The previous hand-rolled `decrypt` only parsed
|
||||
// the TS form and threw `Buffer.from(undefined, 'hex')` on any legacy secret —
|
||||
// inside the $transaction that aborted/rolled back the ENTIRE batch on the first
|
||||
// legacy user. These key-parameterized helpers accept the old/new keys passed on
|
||||
// the command line (the config-bound `decrypt`/`encrypt` use the env key only).
|
||||
const decrypt = (ciphertext: string, keyHex: string): string =>
|
||||
decryptWithKey(ciphertext, keyHex);
|
||||
const encrypt = (plaintext: string, keyHex: string): string =>
|
||||
encryptWithKey(plaintext, keyHex);
|
||||
|
||||
async function main() {
|
||||
const oldKey = process.argv[2];
|
||||
const newKey = process.argv[3];
|
||||
const dryRun = process.argv.includes('--dry-run');
|
||||
const dryRun = process.argv.includes("--dry-run");
|
||||
|
||||
if (!oldKey || !newKey) {
|
||||
console.error('Usage: tsx scripts/rotate-totp-key.ts <old-key-hex> <new-key-hex> [--dry-run]');
|
||||
console.error(
|
||||
"Usage: tsx scripts/rotate-totp-key.ts <old-key-hex> <new-key-hex> [--dry-run]",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -46,12 +40,14 @@ async function main() {
|
||||
const decrypted = decrypt(user.totp_secret!, oldKey);
|
||||
const reEncrypted = encrypt(decrypted, newKey);
|
||||
decrypt(reEncrypted, newKey); // verify round-trip
|
||||
console.log(` [OK] ${user.username} (id=${user.id}) — decryption and re-encryption verified`);
|
||||
console.log(
|
||||
` [OK] ${user.username} (id=${user.id}) — decryption and re-encryption verified`,
|
||||
);
|
||||
} catch (e) {
|
||||
console.error(` [FAIL] ${user.username} (id=${user.id}) — ${e}`);
|
||||
}
|
||||
}
|
||||
console.log('\nDry run complete. No changes made.');
|
||||
console.log("\nDry run complete. No changes made.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -59,13 +55,19 @@ async function main() {
|
||||
for (const user of users) {
|
||||
const decrypted = decrypt(user.totp_secret!, oldKey);
|
||||
const reEncrypted = encrypt(decrypted, newKey);
|
||||
await tx.users.update({ where: { id: user.id }, data: { totp_secret: reEncrypted } });
|
||||
await tx.users.update({
|
||||
where: { id: user.id },
|
||||
data: { totp_secret: reEncrypted },
|
||||
});
|
||||
console.log(` Re-encrypted TOTP for ${user.username} (id=${user.id})`);
|
||||
}
|
||||
});
|
||||
|
||||
console.log('\nAll TOTP secrets re-encrypted successfully.');
|
||||
console.log("\nAll TOTP secrets re-encrypted successfully.");
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
378
src/__tests__/__snapshots__/attendance-print-html.test.ts.snap
Normal file
378
src/__tests__/__snapshots__/attendance-print-html.test.ts.snap
Normal file
@@ -0,0 +1,378 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`buildUserSectionHtml > produces a stable per-user section (full output pinned) 1`] = `
|
||||
"<div class="user-section">
|
||||
<div class="user-header">
|
||||
<h3>Jan Novák</h3>
|
||||
<span class="total">Odpracováno: 8:00 h</span>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th style="width:55px">Datum</th>
|
||||
<th style="width:55px">Den</th>
|
||||
<th style="width:60px">Typ</th>
|
||||
<th class="text-center" style="width:55px">Příchod</th>
|
||||
<th class="text-center" style="width:80px">Pauza</th>
|
||||
<th class="text-center" style="width:55px">Odchod</th>
|
||||
<th class="text-center" style="width:85px">Hodiny</th>
|
||||
<th>Projekty</th>
|
||||
<th>Poznámka</th>
|
||||
</tr></thead>
|
||||
<tbody><tr class="weekend">
|
||||
<td>1. 3. 2098</td>
|
||||
<td>Sobota</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><tr class="weekend">
|
||||
<td>2. 3. 2098</td>
|
||||
<td>Neděle</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><tr class="">
|
||||
<td>3. 3. 2098</td>
|
||||
<td>Pondělí</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><tr class="">
|
||||
<td>4. 3. 2098</td>
|
||||
<td>Úterý</td>
|
||||
<td>Práce</td>
|
||||
<td class="text-center">08:00</td>
|
||||
<td class="text-center">12:00 - 12:30</td>
|
||||
<td class="text-center">16:30</td>
|
||||
<td class="text-center">8:00 (8,00)</td>
|
||||
<td style="font-size:8px"><div>Alpha (8:00h)</div></td>
|
||||
<td>Poznámka <b></td>
|
||||
</tr><tr class="vacation">
|
||||
<td>5. 3. 2098</td>
|
||||
<td>Středa</td>
|
||||
<td>Dovolená</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">—</td>
|
||||
<td class="text-center">8,00</td>
|
||||
<td style="font-size:8px">—</td>
|
||||
<td></td>
|
||||
</tr><tr class="">
|
||||
<td>6. 3. 2098</td>
|
||||
<td>Čtvrtek</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><tr class="">
|
||||
<td>7. 3. 2098</td>
|
||||
<td>Pátek</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><tr class="weekend">
|
||||
<td>8. 3. 2098</td>
|
||||
<td>Sobota</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><tr class="weekend">
|
||||
<td>9. 3. 2098</td>
|
||||
<td>Neděle</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><tr class="">
|
||||
<td>10. 3. 2098</td>
|
||||
<td>Pondělí</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><tr class="">
|
||||
<td>11. 3. 2098</td>
|
||||
<td>Úterý</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><tr class="">
|
||||
<td>12. 3. 2098</td>
|
||||
<td>Středa</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><tr class="">
|
||||
<td>13. 3. 2098</td>
|
||||
<td>Čtvrtek</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><tr class="">
|
||||
<td>14. 3. 2098</td>
|
||||
<td>Pátek</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><tr class="weekend">
|
||||
<td>15. 3. 2098</td>
|
||||
<td>Sobota</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><tr class="weekend">
|
||||
<td>16. 3. 2098</td>
|
||||
<td>Neděle</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><tr class="">
|
||||
<td>17. 3. 2098</td>
|
||||
<td>Pondělí</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><tr class="">
|
||||
<td>18. 3. 2098</td>
|
||||
<td>Úterý</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><tr class="">
|
||||
<td>19. 3. 2098</td>
|
||||
<td>Středa</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><tr class="">
|
||||
<td>20. 3. 2098</td>
|
||||
<td>Čtvrtek</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><tr class="">
|
||||
<td>21. 3. 2098</td>
|
||||
<td>Pátek</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><tr class="weekend">
|
||||
<td>22. 3. 2098</td>
|
||||
<td>Sobota</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><tr class="weekend">
|
||||
<td>23. 3. 2098</td>
|
||||
<td>Neděle</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><tr class="">
|
||||
<td>24. 3. 2098</td>
|
||||
<td>Pondělí</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><tr class="">
|
||||
<td>25. 3. 2098</td>
|
||||
<td>Úterý</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><tr class="">
|
||||
<td>26. 3. 2098</td>
|
||||
<td>Středa</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><tr class="">
|
||||
<td>27. 3. 2098</td>
|
||||
<td>Čtvrtek</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><tr class="">
|
||||
<td>28. 3. 2098</td>
|
||||
<td>Pátek</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><tr class="weekend">
|
||||
<td>29. 3. 2098</td>
|
||||
<td>Sobota</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><tr class="weekend">
|
||||
<td>30. 3. 2098</td>
|
||||
<td>Neděle</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><tr class="">
|
||||
<td>31. 3. 2098</td>
|
||||
<td>Pondělí</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></tbody>
|
||||
</table>
|
||||
<div class="user-summary">
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Odpracováno:</span>
|
||||
<span class="summary-value">8,00h</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">8,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Dovolená:</span>
|
||||
<span class="summary-value">8,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Přesčas:</span>
|
||||
<span class="summary-value">0,00h</span>
|
||||
</div>
|
||||
<div class="summary-row summary-alert">
|
||||
<span class="summary-label">Chybějící hodiny:</span>
|
||||
<span class="summary-value">152,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Svátek:</span>
|
||||
<span class="summary-value">0,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">So/Ne:</span>
|
||||
<span class="summary-value">0,00h</span>
|
||||
</div>
|
||||
<div class="summary-row">
|
||||
<span class="summary-label">Práce v noci:</span>
|
||||
<span class="summary-value">0,00h</span>
|
||||
</div>
|
||||
<div class="summary-row summary-fund">
|
||||
<span class="summary-label">Fond měsíce:</span>
|
||||
<span class="summary-value">168,00h (21 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>
|
||||
</div>"
|
||||
`;
|
||||
137
src/__tests__/ai-budget-permission.test.ts
Normal file
137
src/__tests__/ai-budget-permission.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import aiRoutes from "../routes/admin/ai";
|
||||
import { getBudgetUsd, setBudgetUsd } from "../services/ai.service";
|
||||
|
||||
/**
|
||||
* Pinning test for audit finding L8a: the company-wide AI monthly budget must
|
||||
* NOT be mutable by an ordinary ai.use holder (budget_usd=0 is a company-wide
|
||||
* AI DoS; a huge value removes the cost cap). It is a company setting —
|
||||
* settings.company / settings.system / admin only.
|
||||
*/
|
||||
|
||||
const N = "ai_budget_perm_";
|
||||
const stamp = Date.now().toString(36);
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let aiUserToken: string;
|
||||
let aiRoleId: number;
|
||||
let savedBudget: number;
|
||||
|
||||
function token(user: { id: number; username: string; roleName: string }) {
|
||||
return jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: user.roleName },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.users.deleteMany({ where: { username: { startsWith: N } } });
|
||||
const roles = await prisma.roles.findMany({
|
||||
where: { name: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const roleIds = roles.map((r) => r.id);
|
||||
if (roleIds.length > 0) {
|
||||
await prisma.role_permissions.deleteMany({
|
||||
where: { role_id: { in: roleIds } },
|
||||
});
|
||||
await prisma.roles.deleteMany({ where: { id: { in: roleIds } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
savedBudget = await getBudgetUsd();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(cookie);
|
||||
await app.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
app.addHook("onRequest", securityHeaders);
|
||||
await app.register(aiRoutes, { prefix: "/api/admin/ai" });
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = token({
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
roleName: "admin",
|
||||
});
|
||||
|
||||
// Ordinary ai.use holder — may chat, must NOT control the budget.
|
||||
const role = await prisma.roles.create({
|
||||
data: { name: `${N}aiuse_${stamp}`, display_name: "AI Use Only" },
|
||||
});
|
||||
aiRoleId = role.id;
|
||||
const perm = await prisma.permissions.findFirst({
|
||||
where: { name: "ai.use" },
|
||||
});
|
||||
if (!perm) throw new Error("Test setup: ai.use permission missing");
|
||||
await prisma.role_permissions.create({
|
||||
data: { role_id: aiRoleId, permission_id: perm.id },
|
||||
});
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user_${stamp}`,
|
||||
email: `${N}${stamp}@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
first_name: "AiUse",
|
||||
last_name: "Only",
|
||||
is_active: true,
|
||||
role_id: aiRoleId,
|
||||
},
|
||||
});
|
||||
aiUserToken = token({
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
roleName: role.name,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await setBudgetUsd(savedBudget); // restore whatever the test DB had
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("PUT /ai/budget permission gate (audit L8a)", () => {
|
||||
it("rejects an ordinary ai.use holder with 403", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/admin/ai/budget",
|
||||
headers: {
|
||||
Authorization: `Bearer ${aiUserToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { budget_usd: 0 },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
// ...and the budget must be untouched.
|
||||
expect(await getBudgetUsd()).toBe(savedBudget);
|
||||
});
|
||||
|
||||
it("allows an admin to set the budget", async () => {
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/admin/ai/budget",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { budget_usd: savedBudget },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
1107
src/__tests__/ai-tools.test.ts
Normal file
1107
src/__tests__/ai-tools.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
468
src/__tests__/ai.test.ts
Normal file
468
src/__tests__/ai.test.ts
Normal file
@@ -0,0 +1,468 @@
|
||||
import { describe, it, expect, beforeEach, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import cookie from "@fastify/cookie";
|
||||
import rateLimit from "@fastify/rate-limit";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config as appConfig } from "../config/env";
|
||||
import { securityHeaders } from "../middleware/security";
|
||||
import aiRoutes from "../routes/admin/ai";
|
||||
import {
|
||||
computeCostUsd,
|
||||
recordUsage,
|
||||
getMonthSpendUsd,
|
||||
getBudgetUsd,
|
||||
assertBudgetAvailable,
|
||||
isConfigured,
|
||||
listConversations,
|
||||
createConversation,
|
||||
getConversationMessages,
|
||||
appendConversationMessages,
|
||||
renameConversation,
|
||||
deleteConversation,
|
||||
} from "../services/ai.service";
|
||||
|
||||
const KIND = "test_ai"; // marker so we only clean our own rows
|
||||
const CONV_UID_A = 999999991; // synthetic, FK-free owner ids
|
||||
const CONV_UID_B = 999999992;
|
||||
const HIST_MARKER = "「test-conv」"; // marks HTTP-test conversations on real users
|
||||
|
||||
beforeEach(async () => {
|
||||
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await prisma.ai_usage.deleteMany({ where: { kind: KIND } });
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
|
||||
});
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { title: { contains: HIST_MARKER } },
|
||||
});
|
||||
});
|
||||
|
||||
describe("ai.service cost + budget", () => {
|
||||
it("computes Sonnet 4.6 cost from tokens", () => {
|
||||
// 1,000,000 input @ $3 + 1,000,000 output @ $15 = $18
|
||||
expect(
|
||||
computeCostUsd("claude-sonnet-4-6", 1_000_000, 1_000_000),
|
||||
).toBeCloseTo(18, 6);
|
||||
expect(computeCostUsd("claude-sonnet-4-6", 4000, 500)).toBeCloseTo(
|
||||
0.0195,
|
||||
6,
|
||||
);
|
||||
});
|
||||
|
||||
it("records usage with the computed cost", async () => {
|
||||
await recordUsage({
|
||||
userId: null,
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
inputTokens: 4000,
|
||||
outputTokens: 500,
|
||||
});
|
||||
const rows = await prisma.ai_usage.findMany({ where: { kind: KIND } });
|
||||
expect(rows.length).toBe(1);
|
||||
expect(Number(rows[0].cost_usd)).toBeCloseTo(0.0195, 6);
|
||||
});
|
||||
|
||||
it("sums only the current month's spend (excludes prior months)", async () => {
|
||||
// Measure the baseline so the assertion is robust to any OTHER current-month
|
||||
// rows that may already exist in the test DB (getMonthSpendUsd sums ALL
|
||||
// kinds, not just ours). We assert the DELTA we introduce, not an absolute
|
||||
// upper bound.
|
||||
const before = await getMonthSpendUsd();
|
||||
|
||||
await recordUsage({
|
||||
userId: null,
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
inputTokens: 1_000_000,
|
||||
outputTokens: 0,
|
||||
}); // +$3 this month
|
||||
// An old row (year 2000) must NOT count toward the current month.
|
||||
await prisma.ai_usage.create({
|
||||
data: {
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
input_tokens: 1_000_000,
|
||||
output_tokens: 0,
|
||||
cost_usd: 3,
|
||||
created_at: new Date("2000-01-01T00:00:00Z"),
|
||||
},
|
||||
});
|
||||
|
||||
const after = await getMonthSpendUsd();
|
||||
// Only the $3 current-month row moved the needle; the year-2000 $3 is
|
||||
// excluded. The delta is exactly $3 (not $6).
|
||||
expect(after - before).toBeCloseTo(3, 6);
|
||||
});
|
||||
|
||||
it("assertBudgetAvailable blocks at/over budget, allows under", async () => {
|
||||
const budget = await getBudgetUsd();
|
||||
// Under budget → null (allowed)
|
||||
expect(await assertBudgetAvailable()).toBeNull();
|
||||
// Push spend over budget for this month, then it must block with 402.
|
||||
// Tag with a unique marker so we can delete EXACTLY this row at the end of
|
||||
// the test — that keeps the inflated spend from leaking into any other
|
||||
// current-month test regardless of execution order (the beforeEach kind=KIND
|
||||
// cleanup would catch it too, but cleaning in-test makes it order-proof).
|
||||
const overBudget = await prisma.ai_usage.create({
|
||||
data: {
|
||||
kind: KIND,
|
||||
model: "claude-sonnet-4-6",
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cost_usd: budget + 1,
|
||||
created_at: new Date(),
|
||||
},
|
||||
});
|
||||
try {
|
||||
const blocked = await assertBudgetAvailable();
|
||||
expect(blocked).not.toBeNull();
|
||||
expect(blocked?.status).toBe(402);
|
||||
} finally {
|
||||
// Remove the over-budget row immediately so it cannot inflate
|
||||
// getMonthSpendUsd for any subsequently-running test.
|
||||
await prisma.ai_usage
|
||||
.delete({ where: { id: overBudget.id } })
|
||||
.catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it("isConfigured reflects the API key presence", () => {
|
||||
expect(typeof isConfigured()).toBe("boolean");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ai.service conversations", () => {
|
||||
beforeEach(async () => {
|
||||
await prisma.ai_conversations.deleteMany({
|
||||
where: { user_id: { in: [CONV_UID_A, CONV_UID_B] } },
|
||||
});
|
||||
});
|
||||
|
||||
// Narrow a service result to its error branch with a clear failure message.
|
||||
const expectError = (
|
||||
r: { error: string; status: number } | { data: unknown },
|
||||
status: number,
|
||||
) => {
|
||||
if (!("error" in r))
|
||||
throw new Error(`expected an error result, got ${JSON.stringify(r)}`);
|
||||
expect(r.status).toBe(status);
|
||||
};
|
||||
|
||||
it("creates, lists, appends (auto-title), and reads oldest→newest", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
expect(conv.title).toBe("Nová konverzace");
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "Kolik je hodin v Praze?" },
|
||||
{ role: "assistant", content: "Nevím, ale…" },
|
||||
]);
|
||||
const list = await listConversations(CONV_UID_A);
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].title).toBe("Kolik je hodin v Praze?"); // auto-titled
|
||||
const msgs = await getConversationMessages(CONV_UID_A, conv.id);
|
||||
if (!("data" in msgs)) throw new Error("expected messages, got an error");
|
||||
expect(msgs.data.map((m) => m.content)).toEqual([
|
||||
"Kolik je hodin v Praze?",
|
||||
"Nevím, ale…",
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not overwrite a renamed title on later appends", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
await renameConversation(CONV_UID_A, conv.id, "Moje téma");
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "tohle by nemělo přepsat název" },
|
||||
]);
|
||||
const list = await listConversations(CONV_UID_A);
|
||||
expect(list[0].title).toBe("Moje téma");
|
||||
});
|
||||
|
||||
it("bumps updated_at on append", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
// Force an old timestamp, then prove append refreshes it (TIMESTAMP(0) is
|
||||
// second-precision, so compare against a year rather than ms deltas).
|
||||
await prisma.ai_conversations.update({
|
||||
where: { id: conv.id },
|
||||
data: { updated_at: new Date("2000-01-01T00:00:00Z") },
|
||||
});
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "ping" },
|
||||
]);
|
||||
const after = (await listConversations(CONV_UID_A))[0].updated_at;
|
||||
expect(after.getFullYear()).toBeGreaterThan(2000);
|
||||
});
|
||||
|
||||
it("isolates conversations per user (404 on every op across owners)", async () => {
|
||||
const a = await createConversation(CONV_UID_A);
|
||||
expect(await listConversations(CONV_UID_B)).toHaveLength(0);
|
||||
expectError(await getConversationMessages(CONV_UID_B, a.id), 404);
|
||||
expectError(
|
||||
await appendConversationMessages(CONV_UID_B, a.id, [
|
||||
{ role: "user", content: "x" },
|
||||
]),
|
||||
404,
|
||||
);
|
||||
expectError(await renameConversation(CONV_UID_B, a.id, "hack"), 404);
|
||||
expectError(await deleteConversation(CONV_UID_B, a.id), 404);
|
||||
});
|
||||
|
||||
it("cascade-deletes messages with the conversation", async () => {
|
||||
const conv = await createConversation(CONV_UID_A);
|
||||
await appendConversationMessages(CONV_UID_A, conv.id, [
|
||||
{ role: "user", content: "x" },
|
||||
]);
|
||||
await deleteConversation(CONV_UID_A, conv.id);
|
||||
const remaining = await prisma.ai_chat_messages.count({
|
||||
where: { conversation_id: conv.id },
|
||||
});
|
||||
expect(remaining).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTTP /api/admin/ai", () => {
|
||||
let app: Awaited<ReturnType<typeof buildAiApp>>;
|
||||
let adminToken: string;
|
||||
let noPermToken: string;
|
||||
let noPermRoleId: number;
|
||||
let noPermUserId: number;
|
||||
let savedKey: string;
|
||||
|
||||
async function buildAiApp() {
|
||||
const a = Fastify({ logger: false });
|
||||
await a.register(cookie);
|
||||
await a.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
||||
a.addHook("onRequest", securityHeaders);
|
||||
await a.register(aiRoutes, { prefix: "/api/admin/ai" });
|
||||
return a;
|
||||
}
|
||||
function token(user: {
|
||||
id: number;
|
||||
username: string;
|
||||
roleName: string | null;
|
||||
}) {
|
||||
return jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: user.roleName },
|
||||
appConfig.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
savedKey = appConfig.anthropic.apiKey;
|
||||
app = await buildAiApp();
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
include: { roles: true },
|
||||
});
|
||||
if (!admin) throw new Error("admin not found");
|
||||
adminToken = token({
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
roleName: admin.roles?.name ?? null,
|
||||
});
|
||||
const stamp = Date.now();
|
||||
const role = await prisma.roles.create({
|
||||
data: { name: `noperm_ai_${stamp}`, display_name: "No Perm AI" },
|
||||
});
|
||||
noPermRoleId = role.id;
|
||||
const u = await prisma.users.create({
|
||||
data: {
|
||||
username: `noperm_ai_${stamp}`,
|
||||
first_name: "No",
|
||||
last_name: "Perm",
|
||||
email: `noperm_ai_${stamp}@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
role_id: role.id,
|
||||
is_active: true,
|
||||
},
|
||||
});
|
||||
noPermUserId = u.id;
|
||||
noPermToken = token({
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
roleName: role.name,
|
||||
});
|
||||
});
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
(appConfig.anthropic as { apiKey: string }).apiKey = savedKey;
|
||||
if (noPermUserId)
|
||||
await prisma.users
|
||||
.deleteMany({ where: { id: noPermUserId } })
|
||||
.catch(() => {});
|
||||
if (noPermRoleId)
|
||||
await prisma.roles
|
||||
.deleteMany({ where: { id: noPermRoleId } })
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
it("GET /usage requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/usage",
|
||||
headers: { Authorization: `Bearer ${noPermToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /usage returns spend + budget for an admin", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/usage",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(typeof body.data.budget_usd).toBe("number");
|
||||
expect(typeof body.data.month_spend_usd).toBe("number");
|
||||
});
|
||||
|
||||
it("POST /chat returns 503 when AI is not configured", async () => {
|
||||
(appConfig.anthropic as { apiKey: string }).apiKey = "";
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/chat",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [{ role: "user", content: "ahoj" }] },
|
||||
});
|
||||
expect(res.statusCode).toBe(503);
|
||||
(appConfig.anthropic as { apiKey: string }).apiKey = savedKey;
|
||||
});
|
||||
|
||||
it("GET /conversations requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: { Authorization: `Bearer ${noPermToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("conversation lifecycle over HTTP (create → append → list → rename → delete)", async () => {
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} t` },
|
||||
});
|
||||
expect(created.statusCode).toBe(200);
|
||||
const id = created.json().data.conversation.id as number;
|
||||
|
||||
const appended = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/admin/ai/conversations/${id}/messages`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [{ role: "user", content: "ahoj" }] },
|
||||
});
|
||||
expect(appended.statusCode).toBe(200);
|
||||
|
||||
const msgs = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/ai/conversations/${id}/messages`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(
|
||||
msgs.json().data.messages.map((m: { content: string }) => m.content),
|
||||
).toContain("ahoj");
|
||||
|
||||
const renamed = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/admin/ai/conversations/${id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} renamed` },
|
||||
});
|
||||
expect(renamed.json().data.conversation.title).toBe(
|
||||
`${HIST_MARKER} renamed`,
|
||||
);
|
||||
|
||||
const del = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/admin/ai/conversations/${id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(del.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("GET messages of a non-existent conversation → 404", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations/999999000/messages",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("POST /conversations requires ai.use", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: {
|
||||
Authorization: `Bearer ${noPermToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: "x" },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /conversations lists the user's conversations", async () => {
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: `${HIST_MARKER} listed` },
|
||||
});
|
||||
const id = created.json().data.conversation.id as number;
|
||||
const list = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/ai/conversations",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(list.statusCode).toBe(200);
|
||||
expect(
|
||||
list.json().data.conversations.map((c: { id: number }) => c.id),
|
||||
).toContain(id);
|
||||
});
|
||||
|
||||
it("rejects an empty title (PATCH) and empty messages (POST) with 400", async () => {
|
||||
const patch = await app.inject({
|
||||
method: "PATCH",
|
||||
url: "/api/admin/ai/conversations/999999000",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { title: "" },
|
||||
});
|
||||
expect(patch.statusCode).toBe(400);
|
||||
|
||||
const append = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/ai/conversations/999999000/messages",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { messages: [] },
|
||||
});
|
||||
expect(append.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
46
src/__tests__/app-version-store.test.ts
Normal file
46
src/__tests__/app-version-store.test.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import {
|
||||
reportServerVersion,
|
||||
subscribeNewVersion,
|
||||
getNewVersion,
|
||||
BUILD_VERSION,
|
||||
__resetVersionStateForTest,
|
||||
} from "../admin/utils/appVersion";
|
||||
|
||||
/**
|
||||
* Client store backing the "new version available" banner. The server stamps
|
||||
* X-App-Version on every response; apiFetch feeds it here. A version that
|
||||
* differs from the one baked into THIS bundle (BUILD_VERSION) means a deploy
|
||||
* happened → latch it and notify subscribers (the banner).
|
||||
*/
|
||||
|
||||
describe("appVersion store", () => {
|
||||
beforeEach(() => __resetVersionStateForTest());
|
||||
|
||||
it("ignores the same version, empty, or null", () => {
|
||||
reportServerVersion(BUILD_VERSION);
|
||||
reportServerVersion("");
|
||||
reportServerVersion(null);
|
||||
reportServerVersion(undefined);
|
||||
expect(getNewVersion()).toBeNull();
|
||||
});
|
||||
|
||||
it("latches + notifies once when the server reports a different version", () => {
|
||||
let notified = 0;
|
||||
const unsub = subscribeNewVersion(() => {
|
||||
notified++;
|
||||
});
|
||||
|
||||
reportServerVersion(`${BUILD_VERSION}-next`);
|
||||
expect(getNewVersion()).toBe(`${BUILD_VERSION}-next`);
|
||||
expect(notified).toBe(1);
|
||||
|
||||
// Idempotent: once a new version is known, further reports don't re-notify
|
||||
// or overwrite (the banner is already showing).
|
||||
reportServerVersion("99.0.0");
|
||||
expect(getNewVersion()).toBe(`${BUILD_VERSION}-next`);
|
||||
expect(notified).toBe(1);
|
||||
|
||||
unsub();
|
||||
});
|
||||
});
|
||||
116
src/__tests__/ares.test.ts
Normal file
116
src/__tests__/ares.test.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { aresLookupByIco, aresSearchByName } from "../services/ares.service";
|
||||
|
||||
// ARES is a true external — mock global fetch (the only allowed mock class).
|
||||
const SUBJECT = {
|
||||
ico: "22599851",
|
||||
obchodniJmeno: "BOHA Automation s.r.o.",
|
||||
dic: "CZ22599851",
|
||||
sidlo: {
|
||||
nazevStatu: "Česká republika",
|
||||
nazevObce: "Turnov",
|
||||
nazevCastiObce: "Turnov",
|
||||
nazevUlice: "Nádražní",
|
||||
cisloDomovni: 485,
|
||||
psc: 51101,
|
||||
textovaAdresa: "Nádražní 485, 51101 Turnov",
|
||||
},
|
||||
};
|
||||
|
||||
function mockFetchOnce(status: number, body?: unknown) {
|
||||
return vi.spyOn(globalThis, "fetch").mockResolvedValueOnce({
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () => body,
|
||||
} as Response);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("aresLookupByIco", () => {
|
||||
it("maps a subject to the normalized prefill shape", async () => {
|
||||
mockFetchOnce(200, SUBJECT);
|
||||
const res = await aresLookupByIco("22599851");
|
||||
expect(res).toEqual({
|
||||
ico: "22599851",
|
||||
dic: "CZ22599851",
|
||||
name: "BOHA Automation s.r.o.",
|
||||
street: "Nádražní 485",
|
||||
city: "Turnov",
|
||||
postal_code: "511 01",
|
||||
country: "Česká republika",
|
||||
});
|
||||
});
|
||||
|
||||
it("builds Prague-style orientation numbers as 'Ulice 485/12a'", async () => {
|
||||
mockFetchOnce(200, {
|
||||
...SUBJECT,
|
||||
sidlo: {
|
||||
...SUBJECT.sidlo,
|
||||
cisloOrientacni: 12,
|
||||
cisloOrientacniPismeno: "a",
|
||||
},
|
||||
});
|
||||
const res = await aresLookupByIco("22599851");
|
||||
expect("street" in res && res.street).toBe("Nádražní 485/12a");
|
||||
});
|
||||
|
||||
it("rejects a non-8-digit IČO without calling ARES", async () => {
|
||||
const spy = vi.spyOn(globalThis, "fetch");
|
||||
expect(await aresLookupByIco("123")).toEqual({ error: "invalid_ico" });
|
||||
expect(await aresLookupByIco("abcdefgh")).toEqual({
|
||||
error: "invalid_ico",
|
||||
});
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts an IČO with stray whitespace", async () => {
|
||||
const spy = mockFetchOnce(200, SUBJECT);
|
||||
const res = await aresLookupByIco(" 225 99851 ");
|
||||
expect("ico" in res && res.ico).toBe("22599851");
|
||||
expect(String(spy.mock.calls[0][0])).toContain("/22599851");
|
||||
});
|
||||
|
||||
it("maps 404 to not_found and network failure to ares_unavailable", async () => {
|
||||
mockFetchOnce(404);
|
||||
expect(await aresLookupByIco("12345678")).toEqual({ error: "not_found" });
|
||||
|
||||
vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("ETIMEDOUT"));
|
||||
expect(await aresLookupByIco("12345678")).toEqual({
|
||||
error: "ares_unavailable",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("aresSearchByName", () => {
|
||||
it("maps the result list and sends the name in the POST body", async () => {
|
||||
const spy = mockFetchOnce(200, { ekonomickeSubjekty: [SUBJECT] });
|
||||
const res = await aresSearchByName("BOHA Automation");
|
||||
expect(Array.isArray(res)).toBe(true);
|
||||
if (Array.isArray(res)) {
|
||||
expect(res).toHaveLength(1);
|
||||
expect(res[0].name).toBe("BOHA Automation s.r.o.");
|
||||
expect(res[0].postal_code).toBe("511 01");
|
||||
}
|
||||
const init = spy.mock.calls[0][1] as RequestInit;
|
||||
expect(JSON.parse(String(init.body))).toMatchObject({
|
||||
obchodniJmeno: "BOHA Automation",
|
||||
pocet: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns [] for a blank query without calling ARES", async () => {
|
||||
const spy = vi.spyOn(globalThis, "fetch");
|
||||
expect(await aresSearchByName(" ")).toEqual([]);
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("maps upstream failure to ares_unavailable", async () => {
|
||||
mockFetchOnce(503);
|
||||
expect(await aresSearchByName("BOHA")).toEqual({
|
||||
error: "ares_unavailable",
|
||||
});
|
||||
});
|
||||
});
|
||||
139
src/__tests__/attendance-delete-balance.test.ts
Normal file
139
src/__tests__/attendance-delete-balance.test.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { createLeave, deleteAttendance } from "../services/attendance.service";
|
||||
import { localDateStr } from "../utils/date";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding C1: deleting a vacation/sick attendance
|
||||
* record must restore the hours it charged to leave_balances. Without the
|
||||
* restore, cancelling booked leave by deleting its rows permanently inflates
|
||||
* vacation_used/sick_used.
|
||||
*/
|
||||
|
||||
const N = "att_delbal_";
|
||||
|
||||
let userId: number;
|
||||
|
||||
/** First Monday of March in the given year — always before the earliest
|
||||
* possible Easter holiday and clear of all fixed Czech holidays, so a
|
||||
* Mon-Fri range books exactly 5 days. (Far-future year per fixture hygiene.) */
|
||||
function firstMondayOfMarch(year: number): Date {
|
||||
const d = new Date(year, 2, 1, 12, 0, 0);
|
||||
while (d.getDay() !== 1) d.setDate(d.getDate() + 1);
|
||||
return d;
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
const users = await prisma.users.findMany({
|
||||
where: { username: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const ids = users.map((u) => u.id);
|
||||
if (ids.length > 0) {
|
||||
await prisma.attendance.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.leave_balances.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.users.deleteMany({ where: { id: { in: ids } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const adminRole = await prisma.roles.findFirst({ where: { name: "admin" } });
|
||||
if (!adminRole)
|
||||
throw new Error("Admin role not found — seed the database first");
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash:
|
||||
"$2a$12$LJ3m4ys3Lg4oLBFnYP2amuPBzJnJBbGzCl5Y6X9Y8r0q5.s3L6OyO",
|
||||
first_name: "Delete",
|
||||
last_name: "Balance",
|
||||
is_active: true,
|
||||
role_id: adminRole.id,
|
||||
},
|
||||
});
|
||||
userId = user.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
async function balance(year: number) {
|
||||
return prisma.leave_balances.findFirst({ where: { user_id: userId, year } });
|
||||
}
|
||||
|
||||
describe("deleteAttendance leave-balance restore (audit C1)", () => {
|
||||
it("restores vacation_used when booked vacation rows are deleted", async () => {
|
||||
const monday = firstMondayOfMarch(2098);
|
||||
const friday = new Date(monday);
|
||||
friday.setDate(friday.getDate() + 4);
|
||||
|
||||
const created = await createLeave(
|
||||
{
|
||||
user_id: userId,
|
||||
date_from: localDateStr(monday),
|
||||
date_to: localDateStr(friday),
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
expect("created" in created && created.created).toBe(5);
|
||||
expect(Number((await balance(2098))?.vacation_used)).toBe(40);
|
||||
|
||||
const rows = await prisma.attendance.findMany({
|
||||
where: { user_id: userId, leave_type: "vacation" },
|
||||
});
|
||||
expect(rows).toHaveLength(5);
|
||||
for (const row of rows) {
|
||||
const res = await deleteAttendance(row.id);
|
||||
expect("success" in res && res.success).toBe(true);
|
||||
}
|
||||
|
||||
expect(Number((await balance(2098))?.vacation_used)).toBe(0);
|
||||
});
|
||||
|
||||
it("restores sick_used when a booked sick day is deleted", async () => {
|
||||
const monday = firstMondayOfMarch(2099);
|
||||
await createLeave(
|
||||
{
|
||||
user_id: userId,
|
||||
date_from: localDateStr(monday),
|
||||
leave_type: "sick",
|
||||
leave_hours: 8,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
expect(Number((await balance(2099))?.sick_used)).toBe(8);
|
||||
|
||||
const row = await prisma.attendance.findFirst({
|
||||
where: { user_id: userId, leave_type: "sick" },
|
||||
});
|
||||
expect(row).not.toBeNull();
|
||||
await deleteAttendance(row!.id);
|
||||
|
||||
expect(Number((await balance(2099))?.sick_used)).toBe(0);
|
||||
});
|
||||
|
||||
it("does not touch balances when deleting a plain work shift", async () => {
|
||||
const wednesday = firstMondayOfMarch(2098);
|
||||
wednesday.setDate(wednesday.getDate() + 9); // a weekday a week later
|
||||
const shift = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
shift_date: wednesday,
|
||||
leave_type: "work",
|
||||
},
|
||||
});
|
||||
|
||||
const before = await balance(2098);
|
||||
await deleteAttendance(shift.id);
|
||||
const after = await balance(2098);
|
||||
|
||||
expect(Number(after?.vacation_used)).toBe(Number(before?.vacation_used));
|
||||
expect(Number(after?.sick_used)).toBe(Number(before?.sick_used));
|
||||
});
|
||||
});
|
||||
284
src/__tests__/attendance-mzda-summary.test.ts
Normal file
284
src/__tests__/attendance-mzda-summary.test.ts
Normal file
@@ -0,0 +1,284 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
computeMzdaSummary,
|
||||
formatHoursDecimal1,
|
||||
} from "../admin/utils/attendanceHelpers";
|
||||
import { buildUserSectionHtml } from "../admin/hooks/useAttendanceAdmin";
|
||||
|
||||
/**
|
||||
* BINDING payroll-recap formulas (owner spec 2026-07, back-computed against
|
||||
* the real payslip of Dominik Vesecký 5/2026 — the dataset below is the
|
||||
* built-in acceptance test and MUST match exactly, not approximately):
|
||||
*
|
||||
* fond = (Po–Pá dny, které NEJSOU svátek) × 8
|
||||
* odpracováno = (kalendářní dny se záznamem Práce mimo svátek) × 8, paušálně
|
||||
* svátek = čisté odpracované hodiny ve dnech svátku
|
||||
* dovolená = Σ leave_hours (evidence)
|
||||
* přesčas = max(0, (worked_total + dovolená) − fond) [měsíční]
|
||||
* vč. svátků = odpracováno + přesčas
|
||||
* so/ne = čisté hodiny směn začínajících v So/Ne (celá směna)
|
||||
* noc = průnik s 22:00–06:00 minus pauzy v pásmu, ke dni začátku
|
||||
*
|
||||
* Expected 5/2026 (holidays 1.5. + 8.5.): fond 152 · odpracováno 144 ·
|
||||
* svátek 8 · dovolená 24 · přesčas 17,25 (=17,3 na desetiny) · vč. 161,25
|
||||
* (=161,3) · So/Ne 57,25 · noc 36,75 (payslip said 31 — accountant's own
|
||||
* error, she missed the 31.5.→1.6. overnight shift; 36,75 is CORRECT).
|
||||
*/
|
||||
|
||||
const W = (d: string, from: string, to: string, brk?: [string, string]) => ({
|
||||
shift_date: `${d}T02:00:00`,
|
||||
arrival_time: from.includes(" ") ? from.replace(" ", "T") : `${d}T${from}:00`,
|
||||
departure_time: to.includes(" ") ? to.replace(" ", "T") : `${d}T${to}:00`,
|
||||
break_start: brk
|
||||
? brk[0].includes(" ")
|
||||
? brk[0].replace(" ", "T")
|
||||
: `${d}T${brk[0]}:00`
|
||||
: null,
|
||||
break_end: brk
|
||||
? brk[1].includes(" ")
|
||||
? brk[1].replace(" ", "T")
|
||||
: `${d}T${brk[1]}:00`
|
||||
: null,
|
||||
leave_type: "work",
|
||||
});
|
||||
const V = (d: string, h: number) => ({
|
||||
shift_date: `${d}T02:00:00`,
|
||||
leave_type: "vacation",
|
||||
leave_hours: h,
|
||||
arrival_time: null,
|
||||
departure_time: null,
|
||||
break_start: null,
|
||||
break_end: null,
|
||||
});
|
||||
|
||||
/** The exact dataset from the spec (times with a space carry a full date). */
|
||||
const DOMINIK_MAY_2026 = [
|
||||
W("2026-05-01", "08:15", "17:15", ["12:30", "13:30"]),
|
||||
W("2026-05-03", "21:30", "2026-05-04 06:15:00", [
|
||||
"2026-05-04 01:52:00",
|
||||
"2026-05-04 02:22:00",
|
||||
]),
|
||||
V("2026-05-05", 8),
|
||||
V("2026-05-06", 8),
|
||||
V("2026-05-07", 8),
|
||||
W("2026-05-10", "21:15", "2026-05-11 06:30:00", [
|
||||
"2026-05-11 01:52:00",
|
||||
"2026-05-11 02:22:00",
|
||||
]),
|
||||
W("2026-05-12", "07:45", "16:00", ["11:52", "12:22"]),
|
||||
W("2026-05-13", "08:00", "16:15", ["12:07", "12:37"]),
|
||||
W("2026-05-14", "08:00", "16:15", ["12:07", "12:37"]),
|
||||
W("2026-05-15", "08:00", "16:00", ["12:00", "12:30"]),
|
||||
W("2026-05-16", "10:00", "23:30", ["16:45", "17:45"]),
|
||||
W("2026-05-17", "21:30", "2026-05-18 06:30:00", [
|
||||
"2026-05-18 02:00:00",
|
||||
"2026-05-18 02:30:00",
|
||||
]),
|
||||
W("2026-05-19", "09:30", "17:00", ["13:15", "13:45"]),
|
||||
W("2026-05-20", "08:30", "16:30", ["12:30", "13:00"]),
|
||||
W("2026-05-21", "09:45", "15:15"),
|
||||
W("2026-05-22", "10:45", "15:30"),
|
||||
W("2026-05-24", "17:45", "2026-05-25 06:00:00", [
|
||||
"23:45",
|
||||
"2026-05-25 00:45:00",
|
||||
]),
|
||||
W("2026-05-26", "09:00", "14:30"),
|
||||
W("2026-05-27", "10:00", "15:30"),
|
||||
W("2026-05-28", "08:00", "15:45", ["11:45", "12:15"]),
|
||||
W("2026-05-29", "08:15", "15:00", ["11:30", "12:00"]),
|
||||
W("2026-05-31", "19:45", "2026-06-01 04:15:00", [
|
||||
"2026-06-01 00:00:00",
|
||||
"2026-06-01 00:30:00",
|
||||
]),
|
||||
];
|
||||
|
||||
describe("computeMzdaSummary — built-in acceptance dataset (Dominik 5/2026)", () => {
|
||||
const s = computeMzdaSummary(DOMINIK_MAY_2026 as never, "2026-05");
|
||||
|
||||
it("Fond měsíce = 152 (19 Po–Pá dnů mimo svátky 1.5. a 8.5.)", () => {
|
||||
expect(s.businessDays).toBe(19);
|
||||
expect(s.fund).toBe(152);
|
||||
});
|
||||
|
||||
it("Odpracováno = 144 (18 pracovních dnů mimo svátek × 8, paušálně)", () => {
|
||||
expect(s.odpracovano).toBe(144);
|
||||
});
|
||||
|
||||
it("Svátek = 8 (skutečné hodiny odpracované 1. 5.)", () => {
|
||||
expect(s.svatekHours).toBe(8);
|
||||
});
|
||||
|
||||
it("Dovolená = 24", () => {
|
||||
expect(s.vacationHours).toBe(24);
|
||||
});
|
||||
|
||||
it("worked_total = 145,25 (145:15 čistého času)", () => {
|
||||
expect(s.workedHoursRaw).toBe(145.25);
|
||||
});
|
||||
|
||||
it("Přesčas = 17,25 → zobrazeno 17,3 ((145,25 + 24) − 152)", () => {
|
||||
expect(s.prescas).toBe(17.25);
|
||||
expect(formatHoursDecimal1(s.prescas * 60)).toBe("17,3");
|
||||
});
|
||||
|
||||
it("Odpracováno včetně svátků a přesčasů = 161,25 → zobrazeno 161,3 (144 + 17,25)", () => {
|
||||
expect(s.vcetneSvatku).toBe(161.25);
|
||||
expect(formatHoursDecimal1(s.vcetneSvatku * 60)).toBe("161,3");
|
||||
});
|
||||
|
||||
it("So/Ne = 57,25 (6 směn začínajících v So/Ne, celé směny)", () => {
|
||||
expect(s.weekendHours).toBe(57.25);
|
||||
});
|
||||
|
||||
it("Práce v noci = 36,75 — VČETNĚ směny 31.5.→1.6. (výplatnice s 31 h se mýlí)", () => {
|
||||
expect(s.nightMinutes / 60).toBe(36.75);
|
||||
});
|
||||
|
||||
it("Chybějící hodiny = 0 (145,25 + 24 pokrývá fond 152)", () => {
|
||||
expect(s.manko).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeMzdaSummary — Chybějící hodiny (Dominik 6/2026, reálná data)", () => {
|
||||
// Real production month exposing the gap the paušál hides: 21 attended days
|
||||
// × 8 = 168 + 8h dovolená = 176 = fond exactly (weekend shifts nominally
|
||||
// compensate 3 missing weekdays 1.6./11.6./15.6.), yet REAL worked time is
|
||||
// only 136,5h → 31,5h below the fond. Přesčas must stay 0 (formulas are
|
||||
// binding), manko must surface the 31,5.
|
||||
const JUNE = [
|
||||
W("2026-06-02", "06:15", "14:00", ["10:00", "10:30"]),
|
||||
W("2026-06-03", "06:30", "13:30", ["10:00", "10:30"]),
|
||||
W("2026-06-04", "06:00", "13:45", ["09:45", "10:15"]),
|
||||
W("2026-06-05", "06:15", "13:45", ["10:00", "10:30"]),
|
||||
W("2026-06-07", "07:15", "13:00", ["09:30", "10:00"]), // Sunday
|
||||
W("2026-06-08", "07:15", "13:30", ["10:15", "10:45"]),
|
||||
W("2026-06-09", "06:00", "11:15", ["09:30", "10:00"]),
|
||||
W("2026-06-10", "06:00", "11:45", ["09:30", "10:00"]),
|
||||
W("2026-06-12", "06:00", "13:45", ["09:45", "10:15"]),
|
||||
W("2026-06-14", "17:30", "2026-06-15 04:15:00", ["22:45", "23:15"]), // Sun→Mon
|
||||
W("2026-06-16", "07:30", "13:30", ["10:00", "10:30"]),
|
||||
W("2026-06-17", "10:45", "13:15"),
|
||||
W("2026-06-18", "06:00", "13:15", ["09:30", "10:00"]),
|
||||
W("2026-06-19", "07:00", "13:15", ["10:00", "10:30"]),
|
||||
W("2026-06-22", "06:00", "13:30", ["09:45", "10:15"]),
|
||||
W("2026-06-23", "06:00", "13:45", ["09:45", "10:15"]),
|
||||
W("2026-06-24", "05:30", "13:45", ["09:30", "10:00"]),
|
||||
V("2026-06-25", 8),
|
||||
W("2026-06-26", "05:45", "14:45", ["10:15", "10:45"]),
|
||||
W("2026-06-27", "05:45", "17:00", ["11:15", "11:45"]), // Saturday
|
||||
W("2026-06-29", "11:45", "14:30"),
|
||||
W("2026-06-30", "06:30", "09:15"),
|
||||
W("2026-06-30", "10:45", "13:30"),
|
||||
];
|
||||
const s = computeMzdaSummary(JUNE as never, "2026-06");
|
||||
|
||||
it("verified rows stay exactly as before (fond 176, odpracováno 168, přesčas 0)", () => {
|
||||
expect(s.fund).toBe(176);
|
||||
expect(s.businessDays).toBe(22);
|
||||
expect(s.odpracovano).toBe(168); // 21 days × 8 flat
|
||||
expect(s.vacationHours).toBe(8);
|
||||
expect(s.workedHoursRaw).toBe(136.5);
|
||||
expect(s.prescas).toBe(0); // (136,5 + 8) − 176 < 0 — unchanged formula
|
||||
expect(s.vcetneSvatku).toBe(168);
|
||||
expect(s.svatekHours).toBe(0);
|
||||
expect(s.weekendHours).toBe(26.25); // shifts starting 7.6., 14.6., 27.6.
|
||||
// 14.6. shift (22:00–04:15 minus break = 5:45) + early starts before
|
||||
// 06:00: 24.6. 05:30 (0:30), 26.6. 05:45 (0:15), 27.6. 05:45 (0:15).
|
||||
expect(s.nightMinutes / 60).toBe(6.75);
|
||||
});
|
||||
|
||||
it("Chybějící hodiny = 31,5 — the gap the paušál nominally hides", () => {
|
||||
expect(s.manko).toBe(31.5); // 176 − (136,5 + 8)
|
||||
});
|
||||
|
||||
it("nemoc a neplacené volno kryjí fond stejně jako dovolená", () => {
|
||||
const withSick = [...JUNE, { ...V("2026-06-01", 8), leave_type: "sick" }];
|
||||
const s2 = computeMzdaSummary(withSick as never, "2026-06");
|
||||
expect(s2.sickHours).toBe(8);
|
||||
expect(s2.manko).toBe(23.5); // 31,5 − 8
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeMzdaSummary — formula edge cases", () => {
|
||||
it("Odpracováno is a flat 8h per day: a lone 4:45 day counts as 8", () => {
|
||||
const s = computeMzdaSummary(
|
||||
[W("2026-06-02", "10:45", "15:30")] as never,
|
||||
"2026-06",
|
||||
);
|
||||
expect(s.odpracovano).toBe(8);
|
||||
expect(s.workedHoursRaw).toBe(4.75);
|
||||
expect(s.prescas).toBe(0); // (4,75 + 0) − 176 < 0
|
||||
expect(s.vcetneSvatku).toBe(8); // odpracováno + přesčas
|
||||
});
|
||||
|
||||
it("two shifts on one day count that day ONCE (8h, not 16h)", () => {
|
||||
const s = computeMzdaSummary(
|
||||
[
|
||||
W("2026-06-02", "06:00", "10:00"),
|
||||
W("2026-06-02", "14:00", "18:00"),
|
||||
] as never,
|
||||
"2026-06",
|
||||
);
|
||||
expect(s.odpracovano).toBe(8);
|
||||
expect(s.workedHoursRaw).toBe(8);
|
||||
});
|
||||
|
||||
it("dovolená covers the fond in Přesčas", () => {
|
||||
// 176h fond (June 2026): 152h worked + 30h vacation = 182 → +6 přesčas.
|
||||
const recs: unknown[] = [];
|
||||
const days = [
|
||||
"01",
|
||||
"02",
|
||||
"03",
|
||||
"04",
|
||||
"05",
|
||||
"08",
|
||||
"09",
|
||||
"10",
|
||||
"11",
|
||||
"12",
|
||||
"15",
|
||||
"16",
|
||||
"17",
|
||||
"18",
|
||||
"19",
|
||||
"22",
|
||||
"23",
|
||||
"24",
|
||||
"25",
|
||||
].map((d) => `2026-06-${d}`);
|
||||
for (const d of days) recs.push(W(d, "08:00", "16:30", ["12:00", "12:30"])); // 19×8=152
|
||||
recs.push(V("2026-06-29", 8), V("2026-06-30", 8), V("2026-06-26", 14));
|
||||
const s = computeMzdaSummary(recs as never, "2026-06");
|
||||
expect(s.vacationHours).toBe(30);
|
||||
expect(s.prescas).toBe(6);
|
||||
});
|
||||
|
||||
it("a shift STARTING on a holiday goes to Svátek, not to Odpracováno days", () => {
|
||||
const s = computeMzdaSummary(
|
||||
[W("2026-07-06", "08:00", "18:30", ["12:00", "12:30"])] as never, // 6.7. holiday, 10h
|
||||
"2026-07",
|
||||
);
|
||||
expect(s.svatekHours).toBe(10);
|
||||
expect(s.odpracovano).toBe(0);
|
||||
expect(s.fund).toBe(176); // 23 Mon–Fri − 6.7. holiday = 22 × 8
|
||||
});
|
||||
});
|
||||
|
||||
describe("print day table — multiple records on one day", () => {
|
||||
it("renders one row per record (two shifts are both visible)", () => {
|
||||
const records = [
|
||||
W("2026-06-02", "06:00", "10:00"),
|
||||
W("2026-06-02", "14:00", "18:00"),
|
||||
];
|
||||
const html = buildUserSectionHtml(
|
||||
"1",
|
||||
{ name: "Test", minutes: 480, vacation_hours: 0, records } as never,
|
||||
{ month: "2026-06", month_name: "Červen 2026", user_totals: {} } as never,
|
||||
);
|
||||
expect(html).toContain("06:00");
|
||||
expect(html).toContain("14:00");
|
||||
const rows = html.match(/<td>2\. 6\. 2026<\/td>/g) || [];
|
||||
expect(rows.length).toBe(2);
|
||||
});
|
||||
});
|
||||
155
src/__tests__/attendance-print-html.test.ts
Normal file
155
src/__tests__/attendance-print-html.test.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
buildProjectLogsHtml,
|
||||
buildUserSectionHtml,
|
||||
buildPrintHtml,
|
||||
} from "../admin/hooks/useAttendanceAdmin";
|
||||
|
||||
/**
|
||||
* Characterization test for the attendance print-HTML builders.
|
||||
*
|
||||
* These builders had `any`-typed params; this pins their CURRENT output so the
|
||||
* follow-up retyping (precise AttendanceRecord/UserTotal/PrintData types) is
|
||||
* provably behavior-preserving. The only runtime touch in that retype is
|
||||
* `parseInt(log.hours)` → `parseInt(String(log.hours))` to satisfy the typed
|
||||
* `string | number | null` shape — the cases below exercise both string and
|
||||
* numeric hours/minutes precisely so that equivalence is locked in.
|
||||
*
|
||||
* Fixtures are cast through `Parameters<typeof fn>` so the test compiles both
|
||||
* before and after the param types tighten.
|
||||
*/
|
||||
|
||||
type RecordArg = Parameters<typeof buildProjectLogsHtml>[0];
|
||||
type UserDataArg = Parameters<typeof buildUserSectionHtml>[1];
|
||||
type PrintDataArg = Parameters<typeof buildUserSectionHtml>[2];
|
||||
const asRecord = (o: unknown) => o as unknown as RecordArg;
|
||||
const asUserData = (o: unknown) => o as unknown as UserDataArg;
|
||||
const asPrintData = (o: unknown) => o as unknown as PrintDataArg;
|
||||
|
||||
describe("buildProjectLogsHtml", () => {
|
||||
it("formats hours/minutes given as strings", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({
|
||||
project_logs: [
|
||||
{ project_id: 1, project_name: "Alpha", hours: "2", minutes: "30" },
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe("<div>Alpha (2:30h)</div>");
|
||||
});
|
||||
|
||||
it("formats hours/minutes given as numbers (parseInt-of-number path)", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({
|
||||
project_logs: [
|
||||
{ project_id: 2, project_name: "Beta", hours: 1, minutes: 5 },
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe("<div>Beta (1:05h)</div>");
|
||||
});
|
||||
|
||||
it("derives duration from started_at/ended_at when hours are absent", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({
|
||||
project_logs: [
|
||||
{
|
||||
project_id: 3,
|
||||
project_name: "Gamma",
|
||||
started_at: "2098-01-05T08:00:00",
|
||||
ended_at: "2098-01-05T10:30:00",
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe("<div>Gamma (2:30h)</div>");
|
||||
});
|
||||
|
||||
it("falls back to '#id' and 0:00 when name and times are missing", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(asRecord({ project_logs: [{ project_id: 7 }] })),
|
||||
).toBe("<div>#7 (0:00h)</div>");
|
||||
});
|
||||
|
||||
it("renders the bare project name when there are no logs", () => {
|
||||
expect(
|
||||
buildProjectLogsHtml(
|
||||
asRecord({ project_name: "Solo & <Co>", project_logs: [] }),
|
||||
),
|
||||
).toBe("Solo & <Co>");
|
||||
});
|
||||
});
|
||||
|
||||
// Deterministic fixture: a fixed far-future month, one work day (with a numeric
|
||||
// project log so the snapshot also guards the parseInt path in context) and one
|
||||
// vacation day.
|
||||
const workRecord = {
|
||||
id: 1,
|
||||
user_id: 5,
|
||||
shift_date: "2098-03-04",
|
||||
leave_type: "work",
|
||||
arrival_time: "2098-03-04T08:00:00",
|
||||
departure_time: "2098-03-04T16:30:00",
|
||||
break_start: "2098-03-04T12:00:00",
|
||||
break_end: "2098-03-04T12:30:00",
|
||||
notes: "Poznámka <b>",
|
||||
project_logs: [
|
||||
{ project_id: 1, project_name: "Alpha", hours: 8, minutes: 0 },
|
||||
],
|
||||
};
|
||||
const leaveRecord = {
|
||||
id: 2,
|
||||
user_id: 5,
|
||||
shift_date: "2098-03-05",
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
};
|
||||
const userData = {
|
||||
name: "Jan Novák",
|
||||
minutes: 480,
|
||||
records: [workRecord, leaveRecord],
|
||||
};
|
||||
const printData = {
|
||||
month: "2098-03",
|
||||
month_name: "Březen 2098",
|
||||
selected_user_name: null,
|
||||
user_totals: { "5": userData },
|
||||
};
|
||||
|
||||
describe("buildUserSectionHtml", () => {
|
||||
it("produces a stable per-user section (full output pinned)", () => {
|
||||
const html = buildUserSectionHtml(
|
||||
"5",
|
||||
asUserData(userData),
|
||||
asPrintData(printData),
|
||||
);
|
||||
expect(html).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPrintHtml", () => {
|
||||
// NB: the document footer embeds `new Date()`, so assert stable fragments
|
||||
// rather than snapshotting the whole (non-deterministic) output.
|
||||
it("wraps the user sections in a stable document shell", () => {
|
||||
const section = buildUserSectionHtml(
|
||||
"5",
|
||||
asUserData(userData),
|
||||
asPrintData(printData),
|
||||
);
|
||||
const html = buildPrintHtml(
|
||||
asPrintData(printData),
|
||||
section,
|
||||
"",
|
||||
"",
|
||||
"Firma s.r.o.",
|
||||
);
|
||||
expect(html).toContain("<title>Docházka - Březen 2098</title>");
|
||||
expect(html).toContain("EVIDENCE DOCHÁZKY");
|
||||
expect(html).toContain('<div class="period">Březen 2098</div>');
|
||||
expect(html).toContain("Firma s.r.o.");
|
||||
expect(html).toContain(section);
|
||||
});
|
||||
});
|
||||
77
src/__tests__/attendance-print-tz.test.ts
Normal file
77
src/__tests__/attendance-print-tz.test.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
getCzechWeekday,
|
||||
isWeekendDate,
|
||||
formatTimeOrDatetimePrint,
|
||||
} from "../admin/utils/attendanceHelpers";
|
||||
import { formatDate } from "../admin/utils/formatters";
|
||||
|
||||
/**
|
||||
* Regression: the attendance admin print builds its day rows from date-ONLY
|
||||
* strings ("2026-06-01"). `new Date("YYYY-MM-DD")` is UTC midnight per the
|
||||
* ECMAScript spec, so formatting it with local getters rendered the PREVIOUS
|
||||
* day for viewers west of UTC — a June print opened with "31. 5. 2026 Neděle"
|
||||
* (a May row) and every weekday name was shifted by one. The helpers now
|
||||
* parse the calendar day from the string parts, which is timezone-proof by
|
||||
* construction: these assertions hold in EVERY zone (on a machine west of
|
||||
* UTC the old implementation fails them).
|
||||
*/
|
||||
describe("attendance print — timezone-proof date rendering", () => {
|
||||
it("formatDate renders a date-only string as that exact calendar day", () => {
|
||||
expect(formatDate("2026-06-01")).toBe("1. 6. 2026");
|
||||
expect(formatDate("2026-06-30")).toBe("30. 6. 2026");
|
||||
});
|
||||
|
||||
it("formatDate keeps naive-datetime (wire format) behavior", () => {
|
||||
expect(formatDate("2026-06-01T02:00:00")).toBe("1. 6. 2026");
|
||||
});
|
||||
|
||||
it("getCzechWeekday names the string's own calendar day", () => {
|
||||
expect(getCzechWeekday("2026-06-01")).toBe("Pondělí");
|
||||
expect(getCzechWeekday("2026-06-06")).toBe("Sobota");
|
||||
expect(getCzechWeekday("2026-06-07")).toBe("Neděle");
|
||||
// naive-datetime wire format resolves to the same day
|
||||
expect(getCzechWeekday("2026-06-01T02:00:00")).toBe("Pondělí");
|
||||
});
|
||||
|
||||
it("isWeekendDate flags the string's own calendar day", () => {
|
||||
expect(isWeekendDate("2026-06-06")).toBe(true); // Saturday
|
||||
expect(isWeekendDate("2026-06-07")).toBe(true); // Sunday
|
||||
expect(isWeekendDate("2026-06-01")).toBe(false); // Monday
|
||||
expect(isWeekendDate("2026-06-06T02:00:00")).toBe(true);
|
||||
});
|
||||
|
||||
it("agrees with a locally-constructed date in the current zone (guards a regression to UTC parsing)", () => {
|
||||
// Local construction is the ground truth for "calendar day" in any zone.
|
||||
const local = new Date(2026, 5, 1, 12).toLocaleDateString("cs-CZ", {
|
||||
weekday: "long",
|
||||
});
|
||||
const expected = local.charAt(0).toUpperCase() + local.slice(1);
|
||||
expect(getCzechWeekday("2026-06-01")).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("attendance print — overnight date prefix on time cells", () => {
|
||||
// shift_date arrives as a naive datetime on the wire ("2026-06-01T02:00:00");
|
||||
// the guard used to compare it raw against the extracted date part, so the
|
||||
// overnight-only "d.m." prefix fired on EVERY cell ("1.6. 08:00").
|
||||
const wireShiftDate = "2026-06-01T02:00:00";
|
||||
|
||||
it("same-day punch renders time only", () => {
|
||||
expect(
|
||||
formatTimeOrDatetimePrint("2026-06-01T08:00:00", wireShiftDate),
|
||||
).toBe("08:00");
|
||||
});
|
||||
|
||||
it("overnight punch keeps the date prefix", () => {
|
||||
expect(
|
||||
formatTimeOrDatetimePrint("2026-06-02T01:30:00", wireShiftDate),
|
||||
).toBe("2.6. 01:30");
|
||||
});
|
||||
|
||||
it("date-only shiftDate also matches", () => {
|
||||
expect(formatTimeOrDatetimePrint("2026-06-01T08:00:00", "2026-06-01")).toBe(
|
||||
"08:00",
|
||||
);
|
||||
});
|
||||
});
|
||||
445
src/__tests__/attendance.test.ts
Normal file
445
src/__tests__/attendance.test.ts
Normal file
@@ -0,0 +1,445 @@
|
||||
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 attendanceRoutes from "../routes/admin/attendance";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Regression tests for the attendance create/edit wire format.
|
||||
//
|
||||
// The admin create/edit forms send COMBINED local datetimes
|
||||
// ("YYYY-MM-DDTHH:MM:00", built by combineDatetime from a date + time input)
|
||||
// for arrival_time / departure_time / break_start / break_end, and the
|
||||
// service parses them with `new Date(...)`. Commit 519edce validated these
|
||||
// fields with `timeString` (bare HH:MM), which rejected every create/edit
|
||||
// containing a time, and CreateAttendanceSchema lacked break_start/break_end
|
||||
// entirely, so breaks were silently stripped on create. These tests pin the
|
||||
// combined-datetime contract at the HTTP route level.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// All fixtures live on far-future dates so they can never collide with real
|
||||
// rows in the throwaway test DB; cleanup deletes exactly this range.
|
||||
const RANGE_START = new Date("2098-01-01T00:00:00");
|
||||
const RANGE_END = new Date("2099-01-01T00:00:00");
|
||||
|
||||
let app: Awaited<ReturnType<typeof buildApp>>;
|
||||
let adminUserId: number;
|
||||
let adminToken: string;
|
||||
|
||||
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(attendanceRoutes, { prefix: "/api/admin/attendance" });
|
||||
return a;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a JWT access token. `requireAuth` re-loads auth data from the DB
|
||||
* via `loadAuthData(payload.sub)`, so only the `sub` (user id) matters here.
|
||||
*/
|
||||
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 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 authPut(path: string, token: string, body: unknown) {
|
||||
return app.inject({
|
||||
method: "PUT",
|
||||
url: path,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: body as object,
|
||||
});
|
||||
}
|
||||
|
||||
async function cleanupFixtureRows() {
|
||||
await prisma.attendance.deleteMany({
|
||||
where: {
|
||||
user_id: adminUserId,
|
||||
shift_date: { gte: RANGE_START, lt: RANGE_END },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
include: { roles: true },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminUserId = admin.id;
|
||||
adminToken = generateToken({
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
roleName: admin.roles?.name ?? null,
|
||||
});
|
||||
|
||||
await cleanupFixtureRows();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupFixtureRows();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanupFixtureRows();
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe("POST /api/admin/attendance (combined datetimes)", () => {
|
||||
it("creates a work record with arrival+departure datetimes and persists them", async () => {
|
||||
const arrival = "2098-03-10T08:00:00";
|
||||
const departure = "2098-03-10T16:30:00";
|
||||
|
||||
const res = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-03-10",
|
||||
leave_type: "work",
|
||||
arrival_time: arrival,
|
||||
departure_time: departure,
|
||||
notes: "attendance_wire_test work",
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
|
||||
const rec = await prisma.attendance.findUnique({
|
||||
where: { id: body.data.id },
|
||||
});
|
||||
expect(rec).toBeTruthy();
|
||||
expect(rec!.leave_type).toBe("work");
|
||||
expect(rec!.arrival_time?.getTime()).toBe(new Date(arrival).getTime());
|
||||
expect(rec!.departure_time?.getTime()).toBe(new Date(departure).getTime());
|
||||
});
|
||||
|
||||
it("persists break_start/break_end on create (previously silently stripped)", async () => {
|
||||
const res = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-03-11",
|
||||
leave_type: "work",
|
||||
arrival_time: "2098-03-11T08:00:00",
|
||||
departure_time: "2098-03-11T16:30:00",
|
||||
break_start: "2098-03-11T12:00:00",
|
||||
break_end: "2098-03-11T12:30:00",
|
||||
notes: "attendance_wire_test break",
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
|
||||
const rec = await prisma.attendance.findUnique({
|
||||
where: { id: body.data.id },
|
||||
});
|
||||
expect(rec!.break_start?.getTime()).toBe(
|
||||
new Date("2098-03-11T12:00:00").getTime(),
|
||||
);
|
||||
expect(rec!.break_end?.getTime()).toBe(
|
||||
new Date("2098-03-11T12:30:00").getTime(),
|
||||
);
|
||||
});
|
||||
|
||||
it("creates a leave record with NO time fields", async () => {
|
||||
const res = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-03-12",
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
notes: "attendance_wire_test leave",
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
|
||||
const rec = await prisma.attendance.findUnique({
|
||||
where: { id: body.data.id },
|
||||
});
|
||||
expect(rec!.leave_type).toBe("vacation");
|
||||
expect(Number(rec!.leave_hours)).toBe(8);
|
||||
expect(rec!.arrival_time).toBeNull();
|
||||
expect(rec!.departure_time).toBeNull();
|
||||
});
|
||||
|
||||
it('tolerates "" for unset datetime fields (old form payloads) → null', async () => {
|
||||
// The AttendanceCreate page historically always sent empty strings for
|
||||
// the unfilled time fields — even for leave records — which 400'd EVERY
|
||||
// submit after 519edce. The schema must treat "" as "not set".
|
||||
const res = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-03-13",
|
||||
leave_type: "sick",
|
||||
leave_hours: 8,
|
||||
arrival_time: "",
|
||||
departure_time: "",
|
||||
break_start: "",
|
||||
break_end: "",
|
||||
notes: "attendance_wire_test empty strings",
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
|
||||
const rec = await prisma.attendance.findUnique({
|
||||
where: { id: body.data.id },
|
||||
});
|
||||
expect(rec!.leave_type).toBe("sick");
|
||||
expect(rec!.arrival_time).toBeNull();
|
||||
expect(rec!.departure_time).toBeNull();
|
||||
expect(rec!.break_start).toBeNull();
|
||||
expect(rec!.break_end).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/admin/attendance (complete month, no truncation)", () => {
|
||||
it("returns every record of a month with more than 100 rows", async () => {
|
||||
// The admin month view computes the KPI cards and summary totals from
|
||||
// this single fetch, so it must cover the COMPLETE month. With the old
|
||||
// 100-row pagination cap, months with >100 records were silently
|
||||
// truncated (newest-first) and the screen totals dropped the earliest
|
||||
// days while the print stayed complete.
|
||||
const rows = [];
|
||||
for (let day = 1; day <= 30; day++) {
|
||||
for (let s = 0; s < 4; s++) {
|
||||
rows.push({
|
||||
user_id: adminUserId,
|
||||
shift_date: new Date(2098, 4, day, 12, 0, 0),
|
||||
leave_type: "work" as const,
|
||||
arrival_time: new Date(2098, 4, day, 6 + s, 0, 0),
|
||||
departure_time: new Date(2098, 4, day, 10 + s, 0, 0),
|
||||
notes: "attendance_wire_test bulk month",
|
||||
});
|
||||
}
|
||||
}
|
||||
await prisma.attendance.createMany({ data: rows });
|
||||
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/attendance?year=2098&month=5&limit=2000",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data).toHaveLength(120);
|
||||
expect(body.pagination.total).toBe(120);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/admin/attendance (month window boundaries, @db.Date)", () => {
|
||||
it("includes the month's own LAST day and excludes the neighbor month's first day", async () => {
|
||||
// shift_date is @db.Date — Prisma compares the filter Dates by their UTC
|
||||
// date part. The old LOCAL-midnight month bounds (22:00/23:00 UTC of the
|
||||
// previous day) shifted the whole window a day back: the June list
|
||||
// included May 31 and DROPPED June 30. Fixture rows sit exactly on the
|
||||
// 2098-06 / 2098-07 boundary.
|
||||
const juneLast = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
shift_date: new Date(2098, 5, 30, 12, 0, 0), // 2098-06-30, local noon
|
||||
leave_type: "work",
|
||||
arrival_time: new Date(2098, 5, 30, 8, 0, 0),
|
||||
departure_time: new Date(2098, 5, 30, 16, 0, 0),
|
||||
notes: "attendance_wire_test june-last-day",
|
||||
},
|
||||
});
|
||||
const julyFirst = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
shift_date: new Date(2098, 6, 1, 12, 0, 0), // 2098-07-01, local noon
|
||||
leave_type: "work",
|
||||
arrival_time: new Date(2098, 6, 1, 8, 0, 0),
|
||||
departure_time: new Date(2098, 6, 1, 16, 0, 0),
|
||||
notes: "attendance_wire_test july-first-day",
|
||||
},
|
||||
});
|
||||
|
||||
const june = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/attendance?year=2098&month=6&limit=100",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(june.statusCode).toBe(200);
|
||||
const juneIds = june.json().data.map((r: { id: number }) => r.id);
|
||||
expect(juneIds).toContain(juneLast.id);
|
||||
expect(juneIds).not.toContain(julyFirst.id);
|
||||
|
||||
const july = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/attendance?year=2098&month=7&limit=100",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(july.statusCode).toBe(200);
|
||||
const julyIds = july.json().data.map((r: { id: number }) => r.id);
|
||||
expect(julyIds).toContain(julyFirst.id);
|
||||
expect(julyIds).not.toContain(juneLast.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/admin/attendance (same-day duplicate window, @db.Date)", () => {
|
||||
it("rejects a second leave record on the SAME day", async () => {
|
||||
const first = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-08-10",
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
notes: "attendance_wire_test dup-leave-first",
|
||||
});
|
||||
expect(first.statusCode).toBe(201);
|
||||
|
||||
// Old bug: the duplicate/overlap window was built from LOCAL midnights of
|
||||
// the UTC-midnight shiftDate, so the validation queried ONLY the previous
|
||||
// day — a same-day duplicate leave sailed through undetected.
|
||||
const second = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-08-10",
|
||||
leave_type: "sick",
|
||||
leave_hours: 8,
|
||||
notes: "attendance_wire_test dup-leave-second",
|
||||
});
|
||||
expect(second.statusCode).toBe(400);
|
||||
expect(second.json().success).toBe(false);
|
||||
});
|
||||
|
||||
it("does NOT falsely reject a leave on the day AFTER an existing record", async () => {
|
||||
const first = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-08-10",
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
notes: "attendance_wire_test neighbor-day-first",
|
||||
});
|
||||
expect(first.statusCode).toBe(201);
|
||||
|
||||
// Old bug (the other half): creating a record for the NEXT day queried
|
||||
// the window [Aug 10, Aug 11) — i.e. yesterday's records — and bounced
|
||||
// with a false "záznam o nepřítomnosti již existuje".
|
||||
const nextDay = await authPost("/api/admin/attendance", adminToken, {
|
||||
user_id: adminUserId,
|
||||
shift_date: "2098-08-11",
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
notes: "attendance_wire_test neighbor-day-next",
|
||||
});
|
||||
expect(nextDay.statusCode).toBe(201);
|
||||
expect(nextDay.json().success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/admin/attendance/:id (combined datetimes)", () => {
|
||||
it("updates a record with combined datetimes (incl. overnight departure)", async () => {
|
||||
const created = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
shift_date: new Date(2098, 2, 14, 12, 0, 0),
|
||||
leave_type: "work",
|
||||
arrival_time: new Date("2098-03-14T08:00:00"),
|
||||
departure_time: new Date("2098-03-14T16:30:00"),
|
||||
notes: "attendance_wire_test update",
|
||||
},
|
||||
});
|
||||
|
||||
const res = await authPut(
|
||||
`/api/admin/attendance/${created.id}`,
|
||||
adminToken,
|
||||
{
|
||||
leave_type: "work",
|
||||
arrival_time: "2098-03-14T22:00:00",
|
||||
departure_time: "2098-03-15T06:00:00",
|
||||
break_start: "2098-03-15T02:00:00",
|
||||
break_end: "2098-03-15T02:30:00",
|
||||
notes: "attendance_wire_test updated",
|
||||
},
|
||||
);
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
|
||||
const rec = await prisma.attendance.findUnique({
|
||||
where: { id: created.id },
|
||||
});
|
||||
expect(rec!.arrival_time?.getTime()).toBe(
|
||||
new Date("2098-03-14T22:00:00").getTime(),
|
||||
);
|
||||
expect(rec!.departure_time?.getTime()).toBe(
|
||||
new Date("2098-03-15T06:00:00").getTime(),
|
||||
);
|
||||
expect(rec!.break_start?.getTime()).toBe(
|
||||
new Date("2098-03-15T02:00:00").getTime(),
|
||||
);
|
||||
expect(rec!.break_end?.getTime()).toBe(
|
||||
new Date("2098-03-15T02:30:00").getTime(),
|
||||
);
|
||||
expect(rec!.notes).toBe("attendance_wire_test updated");
|
||||
});
|
||||
|
||||
it("clears times when null is sent (leave-type edit)", async () => {
|
||||
const created = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
shift_date: new Date(2098, 2, 16, 12, 0, 0),
|
||||
leave_type: "work",
|
||||
arrival_time: new Date("2098-03-16T08:00:00"),
|
||||
departure_time: new Date("2098-03-16T16:30:00"),
|
||||
notes: "attendance_wire_test to-leave",
|
||||
},
|
||||
});
|
||||
|
||||
const res = await authPut(
|
||||
`/api/admin/attendance/${created.id}`,
|
||||
adminToken,
|
||||
{
|
||||
leave_type: "vacation",
|
||||
leave_hours: 8,
|
||||
arrival_time: null,
|
||||
departure_time: null,
|
||||
break_start: null,
|
||||
break_end: null,
|
||||
notes: "attendance_wire_test to-leave",
|
||||
},
|
||||
);
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().success).toBe(true);
|
||||
|
||||
const rec = await prisma.attendance.findUnique({
|
||||
where: { id: created.id },
|
||||
});
|
||||
expect(rec!.leave_type).toBe("vacation");
|
||||
expect(rec!.arrival_time).toBeNull();
|
||||
expect(rec!.departure_time).toBeNull();
|
||||
});
|
||||
});
|
||||
96
src/__tests__/audit-log-date-filter.test.ts
Normal file
96
src/__tests__/audit-log-date-filter.test.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import auditLogRoutes from "../routes/admin/audit-log";
|
||||
|
||||
/**
|
||||
* Pinning test for audit finding L8b: the audit-log date_from boundary must
|
||||
* be the LOCAL midnight of the requested day, symmetric with the date_to
|
||||
* side (which already parses "T23:59:59" as local). The old
|
||||
* `new Date(date_from)` was UTC midnight = 01:00/02:00 Prague, silently
|
||||
* excluding events logged in the first morning hours of the from-day.
|
||||
*
|
||||
* NOTE: audit_logs.created_at is @db.Timestamp(0) — capped at 2038, so the
|
||||
* far-future fixture year is 2037, not 2098.
|
||||
*/
|
||||
|
||||
const N = "auditlog_datefilter_";
|
||||
const DAY = "2037-04-09";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let earlyId: number; // 00:30 local — inside the old excluded window
|
||||
let middayId: number; // 12:00 local
|
||||
let prevDayId: number; // 23:30 local the day BEFORE — must stay excluded
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.audit_logs.deleteMany({
|
||||
where: { description: { contains: N } },
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(auditLogRoutes, { prefix: "/api/admin/audit-log" });
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = jwt.sign(
|
||||
{ sub: admin.id, username: admin.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
|
||||
const early = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}early`,
|
||||
created_at: new Date(2037, 3, 9, 0, 30, 0),
|
||||
},
|
||||
});
|
||||
earlyId = early.id;
|
||||
const midday = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}midday`,
|
||||
created_at: new Date(2037, 3, 9, 12, 0, 0),
|
||||
},
|
||||
});
|
||||
middayId = midday.id;
|
||||
const prevDay = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}prevday`,
|
||||
created_at: new Date(2037, 3, 8, 23, 30, 0),
|
||||
},
|
||||
});
|
||||
prevDayId = prevDay.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("audit-log date_from boundary (audit L8b)", () => {
|
||||
it("includes events from the first morning hours of the from-day", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/audit-log?date_from=${DAY}&date_to=${DAY}&limit=100`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const ids = (res.json().data as Array<{ id: number }>).map((r) => r.id);
|
||||
|
||||
expect(ids).toContain(earlyId); // 00:30 — dropped by the old UTC from-bound
|
||||
expect(ids).toContain(middayId);
|
||||
expect(ids).not.toContain(prevDayId); // previous evening stays out
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,72 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
|
||||
import { verifyAccessToken, hashToken } from "../services/auth";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { config } from "../config/env";
|
||||
import prisma from "../config/database";
|
||||
|
||||
// Prefix for fixtures so cleanup never touches real data.
|
||||
const N = "auth_svc_test_";
|
||||
|
||||
let testUserId: number;
|
||||
let testUsername: string;
|
||||
let testRoleName: string | null;
|
||||
|
||||
beforeAll(async () => {
|
||||
// Clean up any leftover fixtures from a previous failed run.
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
|
||||
// Use a real (active, unlocked) user from the seeded DB so loadAuthData
|
||||
// returns a full AuthData. We don't need a specific role — any active user
|
||||
// works — but we record its role so we can assert roleName precisely.
|
||||
const role = await prisma.roles.findFirst();
|
||||
if (!role) throw new Error("Test setup: no roles found — seed the database");
|
||||
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
// DUMMY_HASH used elsewhere in the suite; we never verify a password
|
||||
// here, only that the token's `sub` resolves to this user.
|
||||
password_hash:
|
||||
"$2a$12$LJ3m4ys3Lg4oLBFnYP2amuPBzJnJBbGzCl5Y6X9Y8r0q5.s3L6OyO",
|
||||
first_name: "Auth",
|
||||
last_name: "Service",
|
||||
is_active: true,
|
||||
role_id: role.id,
|
||||
},
|
||||
include: { roles: true },
|
||||
});
|
||||
testUserId = user.id;
|
||||
testUsername = user.username;
|
||||
testRoleName = user.roles?.name ?? null;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
describe("auth service", () => {
|
||||
describe("verifyAccessToken", () => {
|
||||
it("returns AuthData for a valid token signed for a real user", async () => {
|
||||
const token = jwt.sign(
|
||||
{ sub: testUserId, username: testUsername, role: testRoleName },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: config.jwt.accessTokenExpiry, algorithm: "HS256" },
|
||||
);
|
||||
|
||||
const result = await verifyAccessToken(token);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.userId).toBe(testUserId);
|
||||
expect(result!.username).toBe(testUsername);
|
||||
expect(result!.roleName).toBe(testRoleName);
|
||||
// Permissions resolve to an array (admins get all, others get role perms).
|
||||
expect(Array.isArray(result!.permissions)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns null WITHOUT logging for an invalid JWT (expected condition)", async () => {
|
||||
const consoleSpy = vi
|
||||
.spyOn(console, "error")
|
||||
@@ -35,6 +97,14 @@ describe("auth service", () => {
|
||||
});
|
||||
|
||||
describe("hashToken", () => {
|
||||
it("matches the known SHA-256 vector for a fixed input", () => {
|
||||
// SHA-256("hello") — pins the algorithm so a silent change (e.g. to a
|
||||
// different but still 64-hex-deterministic hash) is caught.
|
||||
expect(hashToken("hello")).toBe(
|
||||
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
|
||||
);
|
||||
});
|
||||
|
||||
it("produces deterministic SHA-256 hex output", () => {
|
||||
const t1 = hashToken("hello");
|
||||
const t2 = hashToken("hello");
|
||||
|
||||
@@ -1,12 +1,73 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { buildApp, extractCookie } from "./helpers";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
|
||||
let app: Awaited<ReturnType<typeof buildApp>>;
|
||||
|
||||
// Fixture prefix so cleanup never touches real data.
|
||||
const N = "auth_test_";
|
||||
const TEST_USERNAME = `${N}user`;
|
||||
const TEST_PASSWORD = "Sup3r-Secret-Pw!";
|
||||
|
||||
let testUserId: number;
|
||||
|
||||
/** Pull every Set-Cookie header line for a given cookie name (raw, with attrs). */
|
||||
function rawSetCookie(res: { headers: Record<string, any> }, name: string) {
|
||||
const cookies = res.headers["set-cookie"];
|
||||
if (!cookies) return undefined;
|
||||
const arr = Array.isArray(cookies) ? cookies : [cookies];
|
||||
return arr.find((c: string) => c.startsWith(`${name}=`));
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
|
||||
// Clean up any leftover fixture from a previous failed run, plus its tokens.
|
||||
const leftovers = await prisma.users.findMany({
|
||||
where: { username: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (leftovers.length) {
|
||||
await prisma.refresh_tokens.deleteMany({
|
||||
where: { user_id: { in: leftovers.map((u) => u.id) } },
|
||||
});
|
||||
await prisma.users.deleteMany({ where: { username: { startsWith: N } } });
|
||||
}
|
||||
|
||||
const role = await prisma.roles.findFirst();
|
||||
if (!role) throw new Error("Test setup: no roles found — seed the database");
|
||||
|
||||
// Hash the known password with the SAME bcrypt cost the app uses so login's
|
||||
// bcrypt.compare succeeds.
|
||||
const passwordHash = await bcrypt.hash(
|
||||
TEST_PASSWORD,
|
||||
config.security.bcryptCost,
|
||||
);
|
||||
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: TEST_USERNAME,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash: passwordHash,
|
||||
first_name: "Auth",
|
||||
last_name: "Test",
|
||||
is_active: true,
|
||||
totp_enabled: false,
|
||||
role_id: role.id,
|
||||
},
|
||||
});
|
||||
testUserId = user.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prisma.refresh_tokens
|
||||
.deleteMany({ where: { user_id: testUserId } })
|
||||
.catch(() => {});
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
await app.close();
|
||||
});
|
||||
|
||||
@@ -29,6 +90,39 @@ describe("POST /api/admin/login", () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 401 for a valid user with the wrong password", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/login",
|
||||
payload: { username: TEST_USERNAME, password: "definitely-wrong" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json().success).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 200 with an access token and a refresh cookie on valid credentials", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/login",
|
||||
payload: { username: TEST_USERNAME, password: TEST_PASSWORD },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(typeof body.data.access_token).toBe("string");
|
||||
expect(body.data.access_token.length).toBeGreaterThan(0);
|
||||
expect(body.data.expires_in).toBe(config.jwt.accessTokenExpiry);
|
||||
expect(body.data.user.userId).toBe(testUserId);
|
||||
expect(body.data.user.username).toBe(TEST_USERNAME);
|
||||
|
||||
// The refresh token must be set as an httpOnly, SameSite=Strict cookie.
|
||||
const cookie = extractCookie(res, "refresh_token");
|
||||
expect(cookie).toBeTruthy();
|
||||
const rawCookie = rawSetCookie(res, "refresh_token")!;
|
||||
expect(rawCookie).toMatch(/HttpOnly/i);
|
||||
expect(rawCookie).toMatch(/SameSite=Strict/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/admin/refresh", () => {
|
||||
@@ -39,14 +133,88 @@ describe("POST /api/admin/refresh", () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 401 for an invalid/unknown refresh token", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/refresh",
|
||||
cookies: { refresh_token: "not-a-real-token" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json().success).toBe(false);
|
||||
});
|
||||
|
||||
it("rotates a valid refresh cookie into a new access token + new refresh cookie", async () => {
|
||||
// First log in to obtain a valid refresh cookie.
|
||||
const loginRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/login",
|
||||
payload: { username: TEST_USERNAME, password: TEST_PASSWORD },
|
||||
});
|
||||
expect(loginRes.statusCode).toBe(200);
|
||||
const originalRefresh = extractCookie(loginRes, "refresh_token")!;
|
||||
expect(originalRefresh).toBeTruthy();
|
||||
|
||||
const refreshRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/refresh",
|
||||
cookies: { refresh_token: originalRefresh },
|
||||
});
|
||||
expect(refreshRes.statusCode).toBe(200);
|
||||
const body = refreshRes.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(typeof body.data.access_token).toBe("string");
|
||||
expect(body.data.user.userId).toBe(testUserId);
|
||||
|
||||
// The refresh token must be ROTATED: a new cookie value, different from
|
||||
// the one we presented.
|
||||
const rotated = extractCookie(refreshRes, "refresh_token");
|
||||
expect(rotated).toBeTruthy();
|
||||
expect(rotated).not.toBe(originalRefresh);
|
||||
|
||||
// Reuse-detection: presenting the now-consumed original token must fail.
|
||||
const reuseRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/refresh",
|
||||
cookies: { refresh_token: originalRefresh },
|
||||
});
|
||||
expect(reuseRes.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/admin/logout", () => {
|
||||
it("clears refresh token cookie", async () => {
|
||||
it("clears the refresh token cookie", async () => {
|
||||
// Log in so logout has a real token to delete.
|
||||
const loginRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/login",
|
||||
payload: { username: TEST_USERNAME, password: TEST_PASSWORD },
|
||||
});
|
||||
const refresh = extractCookie(loginRes, "refresh_token")!;
|
||||
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/logout",
|
||||
cookies: { refresh_token: refresh },
|
||||
});
|
||||
expect(res.statusCode).toBeLessThan(500);
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// The response must actively clear the cookie — an expiry in the past
|
||||
// and/or an empty value (clearCookie sets Max-Age=0 / Expires in the past).
|
||||
const raw = rawSetCookie(res, "refresh_token");
|
||||
expect(raw).toBeTruthy();
|
||||
const cleared =
|
||||
/Max-Age=0/i.test(raw!) ||
|
||||
/Expires=Thu, 01 Jan 1970/i.test(raw!) ||
|
||||
/^refresh_token=;/.test(raw!);
|
||||
expect(cleared).toBe(true);
|
||||
|
||||
// The deleted token must no longer be usable for refresh.
|
||||
const reuseRes = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/refresh",
|
||||
cookies: { refresh_token: refresh },
|
||||
});
|
||||
expect(reuseRes.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
152
src/__tests__/bank-accounts.test.ts
Normal file
152
src/__tests__/bank-accounts.test.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import bankAccountsRoutes from "../routes/admin/bank-accounts";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
|
||||
// Fixture marker so cleanup never touches real data.
|
||||
const N = "bank_accounts_test_";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let token: string;
|
||||
const createdIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(bankAccountsRoutes, {
|
||||
prefix: "/api/admin/bank-accounts",
|
||||
});
|
||||
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
|
||||
// Admin role bypasses the settings.banking permission guard.
|
||||
const adminRole = await prisma.roles.findFirst({ where: { name: "admin" } });
|
||||
if (!adminRole)
|
||||
throw new Error("Test setup: no admin role found — seed the database");
|
||||
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash: "x",
|
||||
first_name: "Bank",
|
||||
last_name: "Test",
|
||||
is_active: true,
|
||||
totp_enabled: false,
|
||||
role_id: adminRole.id,
|
||||
},
|
||||
});
|
||||
token = jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: config.jwt.accessTokenExpiry },
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (createdIds.length) {
|
||||
await prisma.bank_accounts
|
||||
.deleteMany({ where: { id: { in: createdIds } } })
|
||||
.catch(() => {});
|
||||
}
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
await app.close();
|
||||
});
|
||||
|
||||
const auth = { authorization: () => `Bearer ${token}` };
|
||||
|
||||
describe("bank accounts — flat-body create/update persists all fields", () => {
|
||||
it("creates an account from a flat top-level body and persists every field", async () => {
|
||||
const payload = {
|
||||
account_name: `${N}Hlavní účet`,
|
||||
bank_name: "Komerční banka",
|
||||
account_number: "123456789/0100",
|
||||
iban: "CZ6508000000192000145399",
|
||||
bic: "KOMBCZPP",
|
||||
currency: "CZK",
|
||||
is_default: true,
|
||||
};
|
||||
|
||||
const post = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/bank-accounts/",
|
||||
headers: { authorization: auth.authorization() },
|
||||
payload,
|
||||
});
|
||||
expect(post.statusCode).toBe(201);
|
||||
const id = post.json().data.id as number;
|
||||
expect(typeof id).toBe("number");
|
||||
createdIds.push(id);
|
||||
|
||||
// Read back via the list endpoint and confirm NONE of the fields are blank.
|
||||
const row = await prisma.bank_accounts.findUnique({ where: { id } });
|
||||
expect(row?.account_name).toBe(payload.account_name);
|
||||
expect(row?.bank_name).toBe(payload.bank_name);
|
||||
expect(row?.account_number).toBe(payload.account_number);
|
||||
expect(row?.iban).toBe(payload.iban);
|
||||
expect(row?.bic).toBe(payload.bic);
|
||||
expect(row?.currency).toBe("CZK");
|
||||
expect(row?.is_default).toBe(true);
|
||||
});
|
||||
|
||||
it("updates an account from a flat body that also carries the id", async () => {
|
||||
const created = await prisma.bank_accounts.create({
|
||||
data: { account_name: `${N}orig`, bank_name: "Orig", currency: "CZK" },
|
||||
});
|
||||
createdIds.push(created.id);
|
||||
|
||||
// Mirrors the client payload: spread fields + id (id routes the URL/method,
|
||||
// is declared in the schema, and is ignored by the route which uses :id).
|
||||
const put = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/bank-accounts/${created.id}`,
|
||||
headers: { authorization: auth.authorization() },
|
||||
payload: {
|
||||
id: created.id,
|
||||
account_name: `${N}upraveno`,
|
||||
bank_name: "Nová banka",
|
||||
iban: "CZ9999",
|
||||
currency: "EUR",
|
||||
is_default: false,
|
||||
},
|
||||
});
|
||||
expect(put.statusCode).toBe(200);
|
||||
|
||||
const row = await prisma.bank_accounts.findUnique({
|
||||
where: { id: created.id },
|
||||
});
|
||||
expect(row?.account_name).toBe(`${N}upraveno`);
|
||||
expect(row?.bank_name).toBe("Nová banka");
|
||||
expect(row?.iban).toBe("CZ9999");
|
||||
expect(row?.currency).toBe("EUR");
|
||||
});
|
||||
|
||||
it("rejects the old nested {bank:{...}} body shape with 400 (no silent blank save)", async () => {
|
||||
const post = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/bank-accounts/",
|
||||
headers: { authorization: auth.authorization() },
|
||||
payload: { bank: { account_name: `${N}nested`, bank_name: "X" } },
|
||||
});
|
||||
expect(post.statusCode).toBe(400);
|
||||
|
||||
// And nothing was persisted under that name.
|
||||
const leaked = await prisma.bank_accounts.findFirst({
|
||||
where: { account_name: `${N}nested` },
|
||||
});
|
||||
expect(leaked).toBeNull();
|
||||
});
|
||||
|
||||
it("requires authentication", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/bank-accounts/",
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
132
src/__tests__/company-settings-numbering.test.ts
Normal file
132
src/__tests__/company-settings-numbering.test.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import companySettingsRoutes from "../routes/admin/company-settings";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
|
||||
// Fixture prefix so cleanup never touches real data.
|
||||
const N = "settings_numbering_test_";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let token: string;
|
||||
|
||||
// Snapshot the prior values of the four numbering fields we mutate so we can
|
||||
// restore them in afterAll — other tests read company_settings and must not be
|
||||
// poisoned by our writes.
|
||||
let priorValues: {
|
||||
issued_order_number_pattern: string | null;
|
||||
issued_order_type_code: string | null;
|
||||
project_number_pattern: string | null;
|
||||
project_type_code: string | null;
|
||||
} | null = null;
|
||||
let settingsId: number | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(companySettingsRoutes, {
|
||||
prefix: "/api/admin/company-settings",
|
||||
});
|
||||
|
||||
// Clean up any leftover fixture from a previous failed run.
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
|
||||
// Attach the fixture user to the admin role so the PUT/GET permission guards
|
||||
// (settings.company / settings.system) pass.
|
||||
const adminRole = await prisma.roles.findFirst({ where: { name: "admin" } });
|
||||
if (!adminRole)
|
||||
throw new Error("Test setup: no admin role found — seed the database");
|
||||
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash: "x",
|
||||
first_name: "Settings",
|
||||
last_name: "Test",
|
||||
is_active: true,
|
||||
totp_enabled: false,
|
||||
role_id: adminRole.id,
|
||||
},
|
||||
});
|
||||
token = jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: config.jwt.accessTokenExpiry },
|
||||
);
|
||||
|
||||
// Snapshot existing settings so we can restore after the suite.
|
||||
const existing = await prisma.company_settings.findFirst({
|
||||
select: {
|
||||
id: true,
|
||||
issued_order_number_pattern: true,
|
||||
issued_order_type_code: true,
|
||||
project_number_pattern: true,
|
||||
project_type_code: true,
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
settingsId = existing.id;
|
||||
priorValues = {
|
||||
issued_order_number_pattern: existing.issued_order_number_pattern,
|
||||
issued_order_type_code: existing.issued_order_type_code,
|
||||
project_number_pattern: existing.project_number_pattern,
|
||||
project_type_code: existing.project_type_code,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Restore the four numbering fields to their pre-test values.
|
||||
if (settingsId !== null && priorValues !== null) {
|
||||
await prisma.company_settings
|
||||
.update({ where: { id: settingsId }, data: priorValues })
|
||||
.catch(() => {});
|
||||
}
|
||||
await prisma.users
|
||||
.deleteMany({ where: { username: { startsWith: N } } })
|
||||
.catch(() => {});
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("company-settings numbering — issued orders + projects round-trip", () => {
|
||||
it("persists and returns issued_order_* and project_* numbering fields", async () => {
|
||||
const payload = {
|
||||
issued_order_number_pattern: "{YY}V{NNNN}",
|
||||
issued_order_type_code: "72",
|
||||
project_number_pattern: "{YY}P{NNNN}",
|
||||
project_type_code: "73",
|
||||
};
|
||||
|
||||
const put = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/admin/company-settings/",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload,
|
||||
});
|
||||
expect(put.statusCode).toBe(200);
|
||||
expect(put.json().success).toBe(true);
|
||||
|
||||
const get = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/company-settings/",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(get.statusCode).toBe(200);
|
||||
const data = get.json().data;
|
||||
expect(data.issued_order_number_pattern).toBe("{YY}V{NNNN}");
|
||||
expect(data.issued_order_type_code).toBe("72");
|
||||
expect(data.project_number_pattern).toBe("{YY}P{NNNN}");
|
||||
expect(data.project_type_code).toBe("73");
|
||||
});
|
||||
|
||||
it("requires authentication", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/company-settings/",
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { UpdateCustomerSchema } from "../schemas/customers.schema";
|
||||
import {
|
||||
CreateCustomerSchema,
|
||||
UpdateCustomerSchema,
|
||||
} from "../schemas/customers.schema";
|
||||
|
||||
describe("UpdateCustomerSchema", () => {
|
||||
it("rejects empty name", () => {
|
||||
@@ -16,4 +19,87 @@ describe("UpdateCustomerSchema", () => {
|
||||
const result = UpdateCustomerSchema.safeParse({ street: "Main St" });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a name longer than 255 chars", () => {
|
||||
const result = UpdateCustomerSchema.safeParse({ name: "x".repeat(256) });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts nullable address/identity fields set to null", () => {
|
||||
const result = UpdateCustomerSchema.safeParse({
|
||||
street: null,
|
||||
city: null,
|
||||
postal_code: null,
|
||||
country: null,
|
||||
company_id: null,
|
||||
vat_id: null,
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CreateCustomerSchema", () => {
|
||||
it("requires a name", () => {
|
||||
const result = CreateCustomerSchema.safeParse({ street: "Main St" });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a full valid payload with all optional fields", () => {
|
||||
const result = CreateCustomerSchema.safeParse({
|
||||
name: "Acme Corp",
|
||||
street: "Main St 1",
|
||||
city: "Praha",
|
||||
postal_code: "11000",
|
||||
country: "CZ",
|
||||
company_id: "12345678",
|
||||
vat_id: "CZ12345678",
|
||||
custom_fields: [{ label: "Note", value: "VIP" }],
|
||||
customer_field_order: ["name", "street"],
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts custom_fields as an array of arbitrary objects", () => {
|
||||
const result = CreateCustomerSchema.safeParse({
|
||||
name: "Acme Corp",
|
||||
custom_fields: [
|
||||
{ label: "a", value: 1 },
|
||||
{ nested: { deep: true } },
|
||||
"raw string",
|
||||
],
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects custom_fields that is not an array", () => {
|
||||
const result = CreateCustomerSchema.safeParse({
|
||||
name: "Acme Corp",
|
||||
custom_fields: { not: "an array" },
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects custom_fields longer than the 100-item cap", () => {
|
||||
const result = CreateCustomerSchema.safeParse({
|
||||
name: "Acme Corp",
|
||||
custom_fields: Array.from({ length: 101 }, (_, i) => ({ i })),
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects customer_field_order entries that are not strings", () => {
|
||||
const result = CreateCustomerSchema.safeParse({
|
||||
name: "Acme Corp",
|
||||
customer_field_order: ["name", 5],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an over-length nullable field (vat_id > 255)", () => {
|
||||
const result = CreateCustomerSchema.safeParse({
|
||||
name: "Acme Corp",
|
||||
vat_id: "x".repeat(256),
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
100
src/__tests__/dashboard.test.ts
Normal file
100
src/__tests__/dashboard.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import dashboardRoutes from "../routes/admin/dashboard";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Regression test for the "Docházka dnes" / "Přítomní dnes" dashboard window.
|
||||
//
|
||||
// attendance.shift_date is @db.Date and Prisma truncates a filter Date to its
|
||||
// UTC date part. The dashboard used local-midnight boundaries
|
||||
// (new Date(y, m, d) = 22:00/23:00 UTC of the PREVIOUS day under
|
||||
// TZ=Europe/Prague), which truncated to [yesterday, today) — today's punches
|
||||
// matched zero rows and everyone showed as absent. The boundaries must be
|
||||
// UTC-midnight instants of the LOCAL calendar day.
|
||||
//
|
||||
// Unlike the other suites this one has to use the REAL current date (the
|
||||
// route computes "today" internally), so fixtures are tracked by id and
|
||||
// deleted in afterAll.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let app: Awaited<ReturnType<typeof buildApp>>;
|
||||
let adminUserId: number;
|
||||
let adminToken: string;
|
||||
const createdIds: number[] = [];
|
||||
|
||||
async function buildApp() {
|
||||
const a = Fastify({ logger: false });
|
||||
await a.register(dashboardRoutes, { prefix: "/api/admin/dashboard" });
|
||||
return a;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
include: { roles: true },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminUserId = admin.id;
|
||||
adminToken = jwt.sign(
|
||||
{ sub: admin.id, username: admin.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (createdIds.length) {
|
||||
await prisma.attendance.deleteMany({ where: { id: { in: createdIds } } });
|
||||
}
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe("GET /api/admin/dashboard — today's attendance window", () => {
|
||||
it("counts a punched-in user as present (local-noon @db.Date row)", async () => {
|
||||
const now = new Date();
|
||||
// The attendance regime stores shift_date at LOCAL NOON (so the UTC date
|
||||
// part equals the Prague calendar date) — same as punchAction does.
|
||||
const row = await prisma.attendance.create({
|
||||
data: {
|
||||
user_id: adminUserId,
|
||||
shift_date: new Date(
|
||||
now.getFullYear(),
|
||||
now.getMonth(),
|
||||
now.getDate(),
|
||||
12,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
leave_type: "work",
|
||||
arrival_time: now,
|
||||
departure_time: null,
|
||||
notes: "dashboard_window_test",
|
||||
},
|
||||
});
|
||||
createdIds.push(row.id);
|
||||
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/admin/dashboard",
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
|
||||
const attendance = body.data.attendance;
|
||||
expect(attendance).toBeTruthy();
|
||||
const me = attendance.users.find(
|
||||
(u: { user_id: number }) => u.user_id === adminUserId,
|
||||
);
|
||||
expect(me).toBeTruthy();
|
||||
expect(me.status).toBe("in");
|
||||
expect(attendance.present_today).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
136
src/__tests__/db-constraints.test.ts
Normal file
136
src/__tests__/db-constraints.test.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
|
||||
/**
|
||||
* Pins the 2026-06-12 DB hardening migration:
|
||||
* 1. CHECK (quantity >= 0) on sklad_batches + sklad_item_locations — the DB
|
||||
* itself rejects negative stock, so a future C2-class bug (cumulative
|
||||
* decrements driving a batch negative) becomes a loud error instead of
|
||||
* silently hidden corruption.
|
||||
* 2. audit_logs.created_at is DATETIME, not TIMESTAMP — no 2038 cap.
|
||||
*/
|
||||
|
||||
const N = "db_constraints_";
|
||||
|
||||
let itemId: number;
|
||||
let locationId: number;
|
||||
let receiptId: number;
|
||||
let lineAId: number;
|
||||
let lineBId: number;
|
||||
|
||||
async function cleanup() {
|
||||
await prisma.sklad_batches.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_item_locations.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipt_lines.deleteMany({
|
||||
where: { item: { name: { contains: N } } },
|
||||
});
|
||||
await prisma.sklad_receipts.deleteMany({ where: { notes: { contains: N } } });
|
||||
await prisma.sklad_items.deleteMany({ where: { name: { contains: N } } });
|
||||
await prisma.sklad_locations.deleteMany({
|
||||
where: { name: { contains: N } },
|
||||
});
|
||||
await prisma.audit_logs.deleteMany({
|
||||
where: { description: { contains: N } },
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
const item = await prisma.sklad_items.create({
|
||||
data: { name: `${N}item`, unit: "ks" },
|
||||
});
|
||||
itemId = item.id;
|
||||
const location = await prisma.sklad_locations.create({
|
||||
data: { code: `DBC${Date.now() % 100000}`, name: `${N}loc` },
|
||||
});
|
||||
locationId = location.id;
|
||||
const receipt = await prisma.sklad_receipts.create({
|
||||
data: { notes: `${N}receipt`, status: "CONFIRMED" },
|
||||
});
|
||||
receiptId = receipt.id;
|
||||
const lineA = await prisma.sklad_receipt_lines.create({
|
||||
data: {
|
||||
receipt_id: receiptId,
|
||||
item_id: itemId,
|
||||
quantity: 5,
|
||||
unit_price: 1,
|
||||
},
|
||||
});
|
||||
lineAId = lineA.id;
|
||||
const lineB = await prisma.sklad_receipt_lines.create({
|
||||
data: {
|
||||
receipt_id: receiptId,
|
||||
item_id: itemId,
|
||||
quantity: 5,
|
||||
unit_price: 1,
|
||||
},
|
||||
});
|
||||
lineBId = lineB.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("stock CHECK constraints", () => {
|
||||
it("rejects inserting a negative batch quantity", async () => {
|
||||
await expect(
|
||||
prisma.sklad_batches.create({
|
||||
data: {
|
||||
item_id: itemId,
|
||||
receipt_line_id: lineAId,
|
||||
quantity: -1,
|
||||
original_qty: 5,
|
||||
unit_price: 1,
|
||||
is_consumed: false,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rejects updating a batch quantity below zero", async () => {
|
||||
const batch = await prisma.sklad_batches.create({
|
||||
data: {
|
||||
item_id: itemId,
|
||||
receipt_line_id: lineBId,
|
||||
quantity: 5,
|
||||
original_qty: 5,
|
||||
unit_price: 1,
|
||||
is_consumed: false,
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
prisma.$executeRaw`UPDATE sklad_batches SET quantity = -2 WHERE id = ${batch.id}`,
|
||||
).rejects.toThrow();
|
||||
const fresh = await prisma.sklad_batches.findUnique({
|
||||
where: { id: batch.id },
|
||||
});
|
||||
expect(Number(fresh?.quantity)).toBe(5);
|
||||
});
|
||||
|
||||
it("rejects a negative item_location quantity", async () => {
|
||||
await expect(
|
||||
prisma.sklad_item_locations.create({
|
||||
data: { item_id: itemId, location_id: locationId, quantity: -1 },
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("audit_logs.created_at has no 2038 cap", () => {
|
||||
it("accepts a far-future timestamp (DATETIME, not TIMESTAMP)", async () => {
|
||||
const row = await prisma.audit_logs.create({
|
||||
data: {
|
||||
action: "test",
|
||||
description: `${N}future`,
|
||||
created_at: new Date(Date.UTC(2098, 0, 15, 12, 0, 0)),
|
||||
},
|
||||
});
|
||||
expect(row.created_at?.getUTCFullYear()).toBe(2098);
|
||||
});
|
||||
});
|
||||
116
src/__tests__/drafts-aggregation.test.ts
Normal file
116
src/__tests__/drafts-aggregation.test.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { createInvoice, getInvoiceStats } from "../services/invoices.service";
|
||||
import { createOffer } from "../services/offers.service";
|
||||
|
||||
// These tests prove that DRAFT documents (a status introduced by the DB-drafts
|
||||
// feature) are NOT counted in period reporting aggregations. A draft is not a
|
||||
// real financial document, so its VAT/amount/created-count must be excluded.
|
||||
//
|
||||
// They hit the real `app_test` DB (per the suite convention) via the service
|
||||
// layer directly. Every row we create is tracked and removed in afterEach so we
|
||||
// leave the DB clean, and we reset the touched number sequences so a finalized
|
||||
// (issued/active) doc created here doesn't leak a consumed number into other
|
||||
// files.
|
||||
|
||||
const invoiceIds: number[] = [];
|
||||
const offerIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
for (const id of offerIds)
|
||||
await prisma.quotations.deleteMany({ where: { id } });
|
||||
invoiceIds.length = 0;
|
||||
offerIds.length = 0;
|
||||
await prisma.number_sequences.deleteMany({
|
||||
where: { type: { in: ["invoice", "offer"] } },
|
||||
});
|
||||
});
|
||||
|
||||
describe("drafts excluded from invoice monthly stats (VAT)", () => {
|
||||
it("a draft invoice's VAT is NOT in vat_month while an issued one IS", async () => {
|
||||
// Pick a far-future month so no seeded/other-test invoices fall in it and
|
||||
// the totals are deterministic. issue_date drives the stats window.
|
||||
const year = 2099;
|
||||
const month = 7;
|
||||
const issueDate = `${year}-0${month}-15`;
|
||||
|
||||
// Single CZK line, 21% VAT: base 1000, VAT 210. Identical on both docs so
|
||||
// the only difference between "draft excluded" and "issued counted" is the
|
||||
// status filter under test.
|
||||
const item = { quantity: 1, unit_price: 1000, vat_rate: 21 };
|
||||
|
||||
const draft = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
apply_vat: true,
|
||||
vat_rate: 21,
|
||||
issue_date: issueDate,
|
||||
items: [item],
|
||||
});
|
||||
invoiceIds.push(draft.id);
|
||||
expect(draft.status).toBe("draft");
|
||||
expect(draft.invoice_number).toBeNull();
|
||||
|
||||
// Sanity: with ONLY the draft present, vat_month must be empty (draft excluded).
|
||||
const draftOnly = await getInvoiceStats(month, year);
|
||||
expect(draftOnly.vat_month).toEqual([]);
|
||||
expect(draftOnly.vat_month_czk).toBe(0);
|
||||
|
||||
const issued = await createInvoice({
|
||||
status: "issued",
|
||||
currency: "CZK",
|
||||
apply_vat: true,
|
||||
vat_rate: 21,
|
||||
issue_date: issueDate,
|
||||
items: [item],
|
||||
});
|
||||
invoiceIds.push(issued.id);
|
||||
expect(issued.status).toBe("issued");
|
||||
|
||||
// Now the issued invoice's VAT (210 CZK) must be counted — and ONLY that
|
||||
// one, not the draft's (which would double it to 420 if drafts leaked in).
|
||||
const stats = await getInvoiceStats(month, year);
|
||||
const czk = stats.vat_month.find((v) => v.currency === "CZK");
|
||||
expect(czk?.amount).toBe(210);
|
||||
expect(stats.vat_month_czk).toBe(210);
|
||||
});
|
||||
});
|
||||
|
||||
describe("drafts excluded from quotations created-this-month count", () => {
|
||||
it("a draft offer is NOT counted; an active one IS", async () => {
|
||||
// Mirror the dashboard route's exact aggregation: count quotations created
|
||||
// in the window, excluding drafts. Use a tight window around `now` (the
|
||||
// route uses the current month) and assert the delta this test introduces.
|
||||
const now = new Date();
|
||||
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 1);
|
||||
|
||||
const countNonDraft = () =>
|
||||
prisma.quotations.count({
|
||||
where: {
|
||||
status: { not: "draft" },
|
||||
created_at: { gte: monthStart, lt: monthEnd },
|
||||
},
|
||||
});
|
||||
|
||||
const before = await countNonDraft();
|
||||
|
||||
const draft = await createOffer({ status: "draft" });
|
||||
if ("error" in draft) throw new Error(`createOffer failed: ${draft.error}`);
|
||||
offerIds.push(draft.id);
|
||||
expect(draft.status).toBe("draft");
|
||||
|
||||
// The draft must not move the non-draft count.
|
||||
expect(await countNonDraft()).toBe(before);
|
||||
|
||||
const active = await createOffer({ status: "active" });
|
||||
if ("error" in active)
|
||||
throw new Error(`createOffer failed: ${active.error}`);
|
||||
offerIds.push(active.id);
|
||||
|
||||
// The active offer is a real document → the count goes up by exactly 1.
|
||||
expect(await countNonDraft()).toBe(before + 1);
|
||||
});
|
||||
});
|
||||
592
src/__tests__/drafts-deferred-numbering.test.ts
Normal file
592
src/__tests__/drafts-deferred-numbering.test.ts
Normal file
@@ -0,0 +1,592 @@
|
||||
import { describe, it, expect, afterEach, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import {
|
||||
previewIssuedOrderNumber,
|
||||
previewInvoiceNumber,
|
||||
previewOfferNumber,
|
||||
} from "../services/numbering.service";
|
||||
import {
|
||||
createIssuedOrder,
|
||||
updateIssuedOrder,
|
||||
deleteIssuedOrder,
|
||||
} from "../services/issued-orders.service";
|
||||
import {
|
||||
createInvoice,
|
||||
updateInvoice,
|
||||
deleteInvoice,
|
||||
} from "../services/invoices.service";
|
||||
import {
|
||||
createOffer,
|
||||
updateOffer,
|
||||
deleteOffer,
|
||||
invalidateOffer,
|
||||
getOffer,
|
||||
listOffers,
|
||||
} from "../services/offers.service";
|
||||
import quotationsRoutes from "../routes/admin/quotations";
|
||||
|
||||
// Track every row we create so the suite leaves the (real) app_test DB clean.
|
||||
const issuedOrderIds: number[] = [];
|
||||
const invoiceIds: number[] = [];
|
||||
const offerIds: number[] = [];
|
||||
const customerIds: number[] = [];
|
||||
const linkedOrderIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of issuedOrderIds)
|
||||
await prisma.issued_orders.deleteMany({ where: { id } });
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
// Linked orders FIRST — orders.quotation_id is a Restrict FK on quotations.
|
||||
for (const id of linkedOrderIds)
|
||||
await prisma.orders.deleteMany({ where: { id } });
|
||||
for (const id of offerIds)
|
||||
await prisma.quotations.deleteMany({ where: { id } });
|
||||
for (const id of customerIds)
|
||||
await prisma.customers.deleteMany({ where: { id } });
|
||||
issuedOrderIds.length = 0;
|
||||
invoiceIds.length = 0;
|
||||
linkedOrderIds.length = 0;
|
||||
offerIds.length = 0;
|
||||
customerIds.length = 0;
|
||||
// Reset every sequence this suite may have touched so preview values are
|
||||
// stable across tests and we don't leak consumed numbers into other files.
|
||||
await prisma.number_sequences.deleteMany({
|
||||
where: { type: { in: ["issued_order", "invoice", "offer"] } },
|
||||
});
|
||||
});
|
||||
|
||||
/** createOffer + narrow the token union + track cleanup. */
|
||||
async function mkOffer(body: Record<string, unknown> = {}) {
|
||||
const res = await createOffer(body);
|
||||
if ("error" in res) throw new Error(`createOffer failed: ${res.error}`);
|
||||
offerIds.push(res.id);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Issued orders */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("issued-order drafts — deferred numbering", () => {
|
||||
it("a draft has no number and does NOT consume the sequence", async () => {
|
||||
const before = (await previewIssuedOrderNumber()).number;
|
||||
const draft = await createIssuedOrder({}); // defaults to draft
|
||||
if ("error" in draft)
|
||||
throw new Error(`createIssuedOrder failed: ${draft.error}`);
|
||||
issuedOrderIds.push(draft.id);
|
||||
expect(draft.status).toBe("draft");
|
||||
expect(draft.po_number).toBeNull();
|
||||
// Preview is unchanged → the sequence was not consumed.
|
||||
const after = (await previewIssuedOrderNumber()).number;
|
||||
expect(after).toBe(before);
|
||||
});
|
||||
|
||||
it("finalizing a draft (draft -> sent) assigns the next sequence number", async () => {
|
||||
const expected = (await previewIssuedOrderNumber()).number;
|
||||
const draft = await createIssuedOrder({
|
||||
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
|
||||
});
|
||||
if ("error" in draft)
|
||||
throw new Error(`createIssuedOrder failed: ${draft.error}`);
|
||||
issuedOrderIds.push(draft.id);
|
||||
|
||||
const res = await updateIssuedOrder(draft.id, { status: "sent" });
|
||||
expect("error" in res).toBe(false);
|
||||
|
||||
const row = await prisma.issued_orders.findUnique({
|
||||
where: { id: draft.id },
|
||||
});
|
||||
expect(row?.status).toBe("sent");
|
||||
expect(row?.po_number).toBe(expected);
|
||||
expect("po_number" in res && res.po_number).toBe(expected);
|
||||
});
|
||||
|
||||
it("finalizing is idempotent — re-finalizing does not re-number", async () => {
|
||||
const draft = await createIssuedOrder({
|
||||
items: [{ description: "Položka", quantity: 1, unit_price: 1 }],
|
||||
});
|
||||
if ("error" in draft)
|
||||
throw new Error(`createIssuedOrder failed: ${draft.error}`);
|
||||
issuedOrderIds.push(draft.id);
|
||||
|
||||
await updateIssuedOrder(draft.id, { status: "sent" });
|
||||
const first = (
|
||||
await prisma.issued_orders.findUnique({ where: { id: draft.id } })
|
||||
)?.po_number;
|
||||
const seqAfterFirst = await prisma.number_sequences.findFirst({
|
||||
where: { type: "issued_order" },
|
||||
});
|
||||
|
||||
// draft -> sent is no longer valid (already sent); the number must not change.
|
||||
// Drive a second finalize-style update that keeps status sent.
|
||||
await updateIssuedOrder(draft.id, { status: "sent" });
|
||||
const second = (
|
||||
await prisma.issued_orders.findUnique({ where: { id: draft.id } })
|
||||
)?.po_number;
|
||||
const seqAfterSecond = await prisma.number_sequences.findFirst({
|
||||
where: { type: "issued_order" },
|
||||
});
|
||||
|
||||
expect(second).toBe(first);
|
||||
expect(seqAfterSecond?.last_number).toBe(seqAfterFirst?.last_number);
|
||||
});
|
||||
|
||||
it("two drafts coexist with null numbers (no unique violation)", async () => {
|
||||
const a = await createIssuedOrder({});
|
||||
const b = await createIssuedOrder({});
|
||||
if ("error" in a) throw new Error(`createIssuedOrder failed: ${a.error}`);
|
||||
if ("error" in b) throw new Error(`createIssuedOrder failed: ${b.error}`);
|
||||
issuedOrderIds.push(a.id, b.id);
|
||||
expect(a.po_number).toBeNull();
|
||||
expect(b.po_number).toBeNull();
|
||||
});
|
||||
|
||||
it("deleting a draft releases nothing (no number was consumed)", async () => {
|
||||
const before = (await previewIssuedOrderNumber()).number;
|
||||
const draft = await createIssuedOrder({});
|
||||
if ("error" in draft)
|
||||
throw new Error(`createIssuedOrder failed: ${draft.error}`);
|
||||
await deleteIssuedOrder(draft.id);
|
||||
const after = (await previewIssuedOrderNumber()).number;
|
||||
expect(after).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Invoices */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("invoice drafts — deferred numbering", () => {
|
||||
it("a draft has no number and does NOT consume the sequence", async () => {
|
||||
const before = (await previewInvoiceNumber()).number;
|
||||
const draft = await createInvoice({});
|
||||
invoiceIds.push(draft.id);
|
||||
expect(draft.status).toBe("draft");
|
||||
expect(draft.invoice_number).toBeNull();
|
||||
const after = (await previewInvoiceNumber()).number;
|
||||
expect(after).toBe(before);
|
||||
});
|
||||
|
||||
it("finalizing a draft (draft -> issued) assigns the next sequence number", async () => {
|
||||
const expected = (await previewInvoiceNumber()).number;
|
||||
const draft = await createInvoice({});
|
||||
invoiceIds.push(draft.id);
|
||||
|
||||
const res = await updateInvoice(draft.id, { status: "issued" });
|
||||
expect("error" in res).toBe(false);
|
||||
|
||||
const row = await prisma.invoices.findUnique({ where: { id: draft.id } });
|
||||
expect(row?.status).toBe("issued");
|
||||
expect(row?.invoice_number).toBe(expected);
|
||||
expect("invoice_number" in res && res.invoice_number).toBe(expected);
|
||||
});
|
||||
|
||||
it("finalizing twice does not re-number / double-consume", async () => {
|
||||
const draft = await createInvoice({});
|
||||
invoiceIds.push(draft.id);
|
||||
|
||||
await updateInvoice(draft.id, { status: "issued" });
|
||||
const first = (
|
||||
await prisma.invoices.findUnique({ where: { id: draft.id } })
|
||||
)?.invoice_number;
|
||||
const seqAfterFirst = await prisma.number_sequences.findFirst({
|
||||
where: { type: "invoice" },
|
||||
});
|
||||
|
||||
// issued -> issued is a no-op status-wise; the number must stay put.
|
||||
await updateInvoice(draft.id, { status: "issued" });
|
||||
const second = (
|
||||
await prisma.invoices.findUnique({ where: { id: draft.id } })
|
||||
)?.invoice_number;
|
||||
const seqAfterSecond = await prisma.number_sequences.findFirst({
|
||||
where: { type: "invoice" },
|
||||
});
|
||||
|
||||
expect(second).toBe(first);
|
||||
expect(seqAfterSecond?.last_number).toBe(seqAfterFirst?.last_number);
|
||||
});
|
||||
|
||||
it("two invoice drafts coexist with null numbers", async () => {
|
||||
const a = await createInvoice({});
|
||||
const b = await createInvoice({});
|
||||
invoiceIds.push(a.id, b.id);
|
||||
expect(a.invoice_number).toBeNull();
|
||||
expect(b.invoice_number).toBeNull();
|
||||
});
|
||||
|
||||
it("deleting a draft releases nothing", async () => {
|
||||
const before = (await previewInvoiceNumber()).number;
|
||||
const draft = await createInvoice({});
|
||||
await deleteInvoice(draft.id);
|
||||
const after = (await previewInvoiceNumber()).number;
|
||||
expect(after).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Offers */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("offer drafts — deferred numbering", () => {
|
||||
it("a draft has no number and does NOT consume the sequence", async () => {
|
||||
const before = await previewOfferNumber();
|
||||
const draft = await createOffer({});
|
||||
if ("error" in draft) throw new Error(`createOffer failed: ${draft.error}`);
|
||||
offerIds.push(draft.id);
|
||||
expect(draft.status).toBe("draft");
|
||||
expect(draft.quotation_number).toBeNull();
|
||||
const after = await previewOfferNumber();
|
||||
expect(after).toBe(before);
|
||||
});
|
||||
|
||||
it("finalizing a draft (draft -> active) assigns the next sequence number", async () => {
|
||||
const expected = await previewOfferNumber();
|
||||
const draft = await createOffer({});
|
||||
if ("error" in draft) throw new Error(`createOffer failed: ${draft.error}`);
|
||||
offerIds.push(draft.id);
|
||||
|
||||
const res = await updateOffer(draft.id, { status: "active" });
|
||||
expect("error" in res).toBe(false);
|
||||
|
||||
const row = await prisma.quotations.findUnique({ where: { id: draft.id } });
|
||||
expect(row?.status).toBe("active");
|
||||
expect(row?.quotation_number).toBe(expected);
|
||||
expect("quotation_number" in res && res.quotation_number).toBe(expected);
|
||||
});
|
||||
|
||||
it("finalizing twice does not re-number / double-consume", async () => {
|
||||
const draft = await createOffer({});
|
||||
if ("error" in draft) throw new Error(`createOffer failed: ${draft.error}`);
|
||||
offerIds.push(draft.id);
|
||||
|
||||
await updateOffer(draft.id, { status: "active" });
|
||||
const first = (
|
||||
await prisma.quotations.findUnique({ where: { id: draft.id } })
|
||||
)?.quotation_number;
|
||||
const seqAfterFirst = await prisma.number_sequences.findFirst({
|
||||
where: { type: "offer" },
|
||||
});
|
||||
|
||||
// active -> active is a no-op; the number must stay put.
|
||||
await updateOffer(draft.id, { status: "active" });
|
||||
const second = (
|
||||
await prisma.quotations.findUnique({ where: { id: draft.id } })
|
||||
)?.quotation_number;
|
||||
const seqAfterSecond = await prisma.number_sequences.findFirst({
|
||||
where: { type: "offer" },
|
||||
});
|
||||
|
||||
expect(second).toBe(first);
|
||||
expect(seqAfterSecond?.last_number).toBe(seqAfterFirst?.last_number);
|
||||
});
|
||||
|
||||
it("two offer drafts coexist with null numbers", async () => {
|
||||
const a = await createOffer({});
|
||||
const b = await createOffer({});
|
||||
if ("error" in a) throw new Error(`createOffer failed: ${a.error}`);
|
||||
if ("error" in b) throw new Error(`createOffer failed: ${b.error}`);
|
||||
offerIds.push(a.id, b.id);
|
||||
expect(a.quotation_number).toBeNull();
|
||||
expect(b.quotation_number).toBeNull();
|
||||
});
|
||||
|
||||
it("an offer created already-finalized (status active) numbers immediately", async () => {
|
||||
const expected = await previewOfferNumber();
|
||||
const offer = await createOffer({ status: "active" });
|
||||
if ("error" in offer) throw new Error(`createOffer failed: ${offer.error}`);
|
||||
offerIds.push(offer.id);
|
||||
expect(offer.quotation_number).toBe(expected);
|
||||
});
|
||||
|
||||
it("deleting a draft releases nothing", async () => {
|
||||
const before = await previewOfferNumber();
|
||||
const draft = await createOffer({});
|
||||
if ("error" in draft) throw new Error(`createOffer failed: ${draft.error}`);
|
||||
await deleteOffer(draft.id);
|
||||
const after = await previewOfferNumber();
|
||||
expect(after).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Offers — status transition table (service) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("offer status transitions (service)", () => {
|
||||
it("rejects draft -> ordered so a numberless 'ordered' offer can never exist", async () => {
|
||||
const draft = await mkOffer({});
|
||||
const res = await updateOffer(draft.id, { status: "ordered" });
|
||||
expect("error" in res && res.error).toBe("invalid_transition");
|
||||
const row = await prisma.quotations.findUnique({ where: { id: draft.id } });
|
||||
expect(row!.status).toBe("draft");
|
||||
expect(row!.quotation_number).toBeNull();
|
||||
});
|
||||
|
||||
it("allows active -> invalidated via update", async () => {
|
||||
const offer = await mkOffer({ status: "active" });
|
||||
const res = await updateOffer(offer.id, { status: "invalidated" });
|
||||
expect("error" in res).toBe(false);
|
||||
const row = await prisma.quotations.findUnique({ where: { id: offer.id } });
|
||||
expect(row!.status).toBe("invalidated");
|
||||
});
|
||||
|
||||
it("invalidateOffer respects the table: draft rejected, ordered ok, terminal stays terminal", async () => {
|
||||
const draft = await mkOffer({});
|
||||
const rejected = await invalidateOffer(draft.id);
|
||||
expect("error" in rejected && rejected.error).toBe("invalid_transition");
|
||||
|
||||
const ordered = await mkOffer({ status: "ordered" });
|
||||
const ok = await invalidateOffer(ordered.id);
|
||||
expect("error" in ok).toBe(false);
|
||||
|
||||
// invalidated is terminal — a second invalidate is rejected too.
|
||||
const again = await invalidateOffer(ordered.id);
|
||||
expect("error" in again && again.error).toBe("invalid_transition");
|
||||
});
|
||||
|
||||
it("getOffer exposes valid_transitions computed from the current status", async () => {
|
||||
const draft = await mkOffer({});
|
||||
expect((await getOffer(draft.id))?.valid_transitions).toEqual(["active"]);
|
||||
|
||||
const active = await mkOffer({ status: "active" });
|
||||
expect((await getOffer(active.id))?.valid_transitions).toEqual([
|
||||
"ordered",
|
||||
"invalidated",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Offers — editable-state guard (service) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("offer editable-state guard (service)", () => {
|
||||
it("explicitly rejects a field edit on an ordered offer (not silently dropped)", async () => {
|
||||
const offer = await mkOffer({ status: "ordered", project_code: "PŮVODNÍ" });
|
||||
const res = await updateOffer(offer.id, { project_code: "ZMĚNA" });
|
||||
expect("error" in res && res.error).toBe("not_editable");
|
||||
const row = await prisma.quotations.findUnique({ where: { id: offer.id } });
|
||||
expect(row!.project_code).toBe("PŮVODNÍ");
|
||||
});
|
||||
|
||||
it("rejects a field edit on an invalidated offer", async () => {
|
||||
const offer = await mkOffer({ status: "invalidated" });
|
||||
const res = await updateOffer(offer.id, { scope_title: "X" });
|
||||
expect("error" in res && res.error).toBe("not_editable");
|
||||
});
|
||||
|
||||
it("still allows the status-only ordered -> invalidated payload", async () => {
|
||||
const offer = await mkOffer({ status: "ordered" });
|
||||
const res = await updateOffer(offer.id, { status: "invalidated" });
|
||||
expect("error" in res).toBe(false);
|
||||
const row = await prisma.quotations.findUnique({ where: { id: offer.id } });
|
||||
expect(row!.status).toBe("invalidated");
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Offers — customer FK handling (service) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("offer customer FK handling (service)", () => {
|
||||
async function mkCustomer() {
|
||||
const c = await prisma.customers.create({
|
||||
data: { name: "drafts_test_zákazník" },
|
||||
});
|
||||
customerIds.push(c.id);
|
||||
return c;
|
||||
}
|
||||
|
||||
it("create rejects a nonexistent customer with a clean token (no P2003 500)", async () => {
|
||||
const res = await createOffer({ customer_id: 99999999 });
|
||||
expect("error" in res && res.error).toBe("customer_not_found");
|
||||
});
|
||||
|
||||
it("update rejects a nonexistent customer with a clean token", async () => {
|
||||
const offer = await mkOffer({});
|
||||
const res = await updateOffer(offer.id, { customer_id: 99999999 });
|
||||
expect("error" in res && res.error).toBe("customer_not_found");
|
||||
});
|
||||
|
||||
it("explicit null CLEARS the customer (the old Number(null) -> 0 bug)", async () => {
|
||||
const customer = await mkCustomer();
|
||||
const offer = await mkOffer({ customer_id: customer.id });
|
||||
expect(offer.customer_id).toBe(customer.id);
|
||||
|
||||
const res = await updateOffer(offer.id, { customer_id: null });
|
||||
expect("error" in res).toBe(false);
|
||||
const row = await prisma.quotations.findUnique({ where: { id: offer.id } });
|
||||
expect(row!.customer_id).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Offers — deterministic list ordering */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("listOffers deterministic ordering", () => {
|
||||
it("tiebreaks same-created_at rows by id (stable in both directions)", async () => {
|
||||
const MARK = `TIEBREAK-${Date.now()}`;
|
||||
const ids: number[] = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const o = await mkOffer({ project_code: MARK });
|
||||
ids.push(o.id);
|
||||
}
|
||||
// created_at is second-precision; pin all three to the SAME timestamp so
|
||||
// only the id tiebreak can order them.
|
||||
await prisma.quotations.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data: { created_at: new Date("2026-01-15T10:00:00") },
|
||||
});
|
||||
|
||||
const base = { page: 1, limit: 10, skip: 0, search: MARK };
|
||||
const desc = await listOffers({
|
||||
...base,
|
||||
sort: "created_at",
|
||||
order: "desc",
|
||||
});
|
||||
expect(desc.data.map((o: { id: number }) => o.id)).toEqual(
|
||||
[...ids].sort((a, b) => b - a),
|
||||
);
|
||||
|
||||
const asc = await listOffers({ ...base, sort: "created_at", order: "asc" });
|
||||
expect(asc.data.map((o: { id: number }) => o.id)).toEqual(
|
||||
[...ids].sort((a, b) => a - b),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Offers — route-level hardening (Czech messages + status codes) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
let app: ReturnType<typeof Fastify> | null = null;
|
||||
let adminToken = "";
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(quotationsRoutes, { prefix: "/api/admin/offers" });
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = jwt.sign(
|
||||
{ sub: admin.id, username: admin.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe("offers routes — hardening (HTTP)", () => {
|
||||
const auth = () => ({ Authorization: `Bearer ${adminToken}` });
|
||||
|
||||
it("PUT rejects a field edit on an ordered offer with the explicit Czech 400", async () => {
|
||||
const offer = await mkOffer({ status: "ordered" });
|
||||
const res = await app!.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/offers/${offer.id}`,
|
||||
headers: auth(),
|
||||
payload: { project_code: "ZMĚNA" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toBe("Nabídku v tomto stavu nelze upravovat");
|
||||
});
|
||||
|
||||
it("PUT rejects draft -> ordered with the transition message", async () => {
|
||||
const draft = await mkOffer({});
|
||||
const res = await app!.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/offers/${draft.id}`,
|
||||
headers: auth(),
|
||||
payload: { status: "ordered" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toBe(
|
||||
'Neplatný přechod stavu z "draft" na "ordered"',
|
||||
);
|
||||
});
|
||||
|
||||
it("POST 400s a 501-char item description (schema cap, not a DB 500)", async () => {
|
||||
const res = await app!.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/offers",
|
||||
headers: auth(),
|
||||
payload: { items: [{ description: "x".repeat(501) }] },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().success).toBe(false);
|
||||
});
|
||||
|
||||
it("POST 400s a nonexistent customer with 'Zákazník nenalezen'", async () => {
|
||||
const res = await app!.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/offers",
|
||||
headers: auth(),
|
||||
payload: { customer_id: 99999999 },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toBe("Zákazník nenalezen");
|
||||
});
|
||||
|
||||
it("DELETE returns a Czech 409 when the offer is linked to an order (real Restrict FK)", async () => {
|
||||
const offer = await mkOffer({ status: "active" });
|
||||
const order = await prisma.orders.create({
|
||||
data: {
|
||||
order_number: `DRAFTSLINK-${Date.now()}`,
|
||||
quotation_id: offer.id,
|
||||
},
|
||||
});
|
||||
linkedOrderIds.push(order.id);
|
||||
|
||||
const res = await app!.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/admin/offers/${offer.id}`,
|
||||
headers: auth(),
|
||||
});
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().error).toBe(
|
||||
"Nabídku nelze smazat, je navázána na objednávku nebo projekt",
|
||||
);
|
||||
// The offer survived the rejected delete.
|
||||
expect(
|
||||
await prisma.quotations.findUnique({ where: { id: offer.id } }),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it("PUT writes an audit row carrying oldValues and newValues ('koncept' fallback)", async () => {
|
||||
const draft = await mkOffer({ project_code: "PŘED" });
|
||||
const res = await app!.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/offers/${draft.id}`,
|
||||
headers: auth(),
|
||||
payload: { project_code: "PO" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
const audit = await prisma.audit_logs.findFirst({
|
||||
where: {
|
||||
entity_type: "quotation",
|
||||
entity_id: draft.id,
|
||||
action: "update",
|
||||
},
|
||||
orderBy: { id: "desc" },
|
||||
});
|
||||
expect(audit).not.toBeNull();
|
||||
expect(audit!.old_values).toBeTruthy();
|
||||
expect(audit!.new_values).toBeTruthy();
|
||||
expect(JSON.parse(audit!.old_values!).project_code).toBe("PŘED");
|
||||
expect(JSON.parse(audit!.new_values!).project_code).toBe("PO");
|
||||
// Unnumbered drafts read "koncept", never "null".
|
||||
expect(audit!.description).toContain("koncept");
|
||||
expect(audit!.description).not.toContain("null");
|
||||
});
|
||||
});
|
||||
@@ -32,3 +32,37 @@ describe("env validation", () => {
|
||||
expect(config.db.url).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("env validation — failure path", () => {
|
||||
// The config singleton runs its validation at module-load time and is then
|
||||
// cached by the module system, so we cannot re-import it with bad env to
|
||||
// observe a throw without complex module-registry resetting. Instead we test
|
||||
// the exact predicates config/env.ts uses to reject bad input — this is the
|
||||
// logic that protects the boot, and the loaded config above proves the
|
||||
// happy path. (Predicates kept in sync with src/config/env.ts.)
|
||||
const HEX64_RE = /^[0-9a-fA-F]{64}$/;
|
||||
|
||||
it("rejects a too-short / non-hex JWT_SECRET", () => {
|
||||
expect(HEX64_RE.test("short")).toBe(false);
|
||||
expect(HEX64_RE.test("a".repeat(63))).toBe(false); // one char short
|
||||
expect(HEX64_RE.test("z".repeat(64))).toBe(false); // 64 chars, not hex
|
||||
// The real config's secret must pass the very same check.
|
||||
expect(HEX64_RE.test(config.jwt.secret)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an out-of-range or non-numeric PORT", () => {
|
||||
const portValid = (p: number) => !Number.isNaN(p) && p >= 1 && p <= 65535;
|
||||
expect(portValid(parseInt("0", 10))).toBe(false);
|
||||
expect(portValid(parseInt("70000", 10))).toBe(false);
|
||||
expect(portValid(parseInt("notaport", 10))).toBe(false); // NaN
|
||||
expect(portValid(config.port)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a non-positive ACCESS_TOKEN_EXPIRY", () => {
|
||||
const expiryValid = (n: number) => !Number.isNaN(n) && n > 0;
|
||||
expect(expiryValid(0)).toBe(false);
|
||||
expect(expiryValid(-1)).toBe(false);
|
||||
expect(expiryValid(parseInt("oops", 10))).toBe(false); // NaN
|
||||
expect(expiryValid(config.jwt.accessTokenExpiry)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { toCzk, getRate } from "../services/exchange-rates";
|
||||
import {
|
||||
toCzk,
|
||||
getRate,
|
||||
__resetRateCacheForTest,
|
||||
} from "../services/exchange-rates";
|
||||
|
||||
// Mock global fetch
|
||||
const mockFetch = vi.fn();
|
||||
@@ -8,6 +12,11 @@ global.fetch = mockFetch;
|
||||
describe("exchange-rates", () => {
|
||||
beforeEach(() => {
|
||||
mockFetch.mockReset();
|
||||
// The rate cache is module-level and persists across tests. Without this
|
||||
// reset, the first test to populate "today" would short-circuit every
|
||||
// later mockFetch resolution (cache hit), making assertions order-dependent
|
||||
// and asserting stale rates. Reset it so each test gets a clean fetch.
|
||||
__resetRateCacheForTest();
|
||||
});
|
||||
|
||||
describe("toCzk", () => {
|
||||
@@ -43,6 +52,21 @@ describe("exchange-rates", () => {
|
||||
const result = await toCzk(100, "EUR");
|
||||
expect(result).toBe(2500);
|
||||
});
|
||||
|
||||
it("honours amount != 1 (currency quoted per 100 units)", async () => {
|
||||
// CNB quotes some currencies (e.g. HUF, JPY) per 100 units: the `rate`
|
||||
// is for `amount` units, so the per-unit rate is rate/amount. Here the
|
||||
// per-unit rate is 250/100 = 2.5 CZK; converting 100 units → 250 CZK.
|
||||
// If the service ignored `amount` it would compute 100*250 = 25000.
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
rates: [{ currencyCode: "HUF", rate: 250, amount: 100 }],
|
||||
}),
|
||||
});
|
||||
const result = await toCzk(100, "HUF");
|
||||
expect(result).toBe(250);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRate", () => {
|
||||
@@ -60,5 +84,17 @@ describe("exchange-rates", () => {
|
||||
});
|
||||
await expect(getRate("XYZ")).rejects.toThrow(/Neznámá měna: XYZ/);
|
||||
});
|
||||
|
||||
it("returns the per-unit rate for amount != 1", async () => {
|
||||
// rate 250 for amount 100 → per-unit rate 2.5 (CZK per 1 unit).
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
rates: [{ currencyCode: "HUF", rate: 250, amount: 100 }],
|
||||
}),
|
||||
});
|
||||
const result = await getRate("HUF");
|
||||
expect(result).toBe(2.5);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,13 +13,31 @@ export async function buildApp() {
|
||||
return app;
|
||||
}
|
||||
|
||||
export function extractCookie(response: any, name: string): string | undefined {
|
||||
/**
|
||||
* Minimal structural shape of the only thing extractCookie needs from a
|
||||
* response — its `set-cookie` header. Matches Fastify's `LightMyRequestResponse`
|
||||
* (from `app.inject`) and a plain supertest response without coupling to either.
|
||||
*/
|
||||
interface ResponseWithCookies {
|
||||
headers: Record<string, string | string[] | number | undefined>;
|
||||
}
|
||||
|
||||
export function extractCookie(
|
||||
response: ResponseWithCookies,
|
||||
name: string,
|
||||
): string | undefined {
|
||||
const cookies = response.headers["set-cookie"];
|
||||
if (!cookies) return undefined;
|
||||
const arr = Array.isArray(cookies) ? cookies : [cookies];
|
||||
for (const c of arr) {
|
||||
if (typeof c !== "string") continue;
|
||||
if (c.startsWith(`${name}=`)) {
|
||||
return c.split(";")[0].split("=")[1];
|
||||
// The value is everything from the first "=" up to the first ";".
|
||||
// Split ONLY on the first "=" so a base64/JWT value containing "=" (e.g.
|
||||
// padding) is not truncated — `split("=")[1]` would drop everything after
|
||||
// the second "=".
|
||||
const pair = c.split(";")[0];
|
||||
return pair.slice(pair.indexOf("=") + 1);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
|
||||
73
src/__tests__/html-to-pdf-retry.test.ts
Normal file
73
src/__tests__/html-to-pdf-retry.test.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M12: a shared Puppeteer browser that
|
||||
* disconnects between getBrowser()'s point-in-time `connected` check and the
|
||||
* actual render must be re-acquired once — instead of failing the request
|
||||
* with a 500 that an immediate retry would have served fine.
|
||||
*/
|
||||
|
||||
const { launchMock } = vi.hoisted(() => ({ launchMock: vi.fn() }));
|
||||
|
||||
vi.mock("puppeteer", () => ({ default: { launch: launchMock } }));
|
||||
|
||||
function healthyBrowser(pdfBytes = new Uint8Array([1, 2, 3])) {
|
||||
return {
|
||||
connected: true,
|
||||
newPage: vi.fn(async () => ({
|
||||
setContent: vi.fn(async () => undefined),
|
||||
pdf: vi.fn(async () => pdfBytes),
|
||||
close: vi.fn(async () => undefined),
|
||||
})),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
}
|
||||
|
||||
/** Browser whose connection dies the moment a page is requested — the
|
||||
* post-guard crash window from the finding. */
|
||||
function dyingBrowser() {
|
||||
const b = {
|
||||
connected: true,
|
||||
newPage: vi.fn(async () => {
|
||||
b.connected = false;
|
||||
throw new Error("Protocol error (Target.createTarget): Session closed.");
|
||||
}),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
return b;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
launchMock.mockReset();
|
||||
});
|
||||
|
||||
describe("htmlToPdf browser re-acquire (audit M12)", () => {
|
||||
it("relaunches once and resolves when the cached browser died mid-acquire", async () => {
|
||||
launchMock
|
||||
.mockResolvedValueOnce(dyingBrowser())
|
||||
.mockResolvedValueOnce(healthyBrowser());
|
||||
|
||||
const { htmlToPdf } = await import("../utils/html-to-pdf");
|
||||
const pdf = await htmlToPdf("<html><body>retry</body></html>");
|
||||
|
||||
expect(Buffer.isBuffer(pdf)).toBe(true);
|
||||
expect(launchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does NOT retry a genuine render error on a healthy browser", async () => {
|
||||
const browser = healthyBrowser();
|
||||
browser.newPage = vi.fn(async () => ({
|
||||
setContent: vi.fn(async () => {
|
||||
throw new Error("Render timeout");
|
||||
}),
|
||||
pdf: vi.fn(async () => new Uint8Array()),
|
||||
close: vi.fn(async () => undefined),
|
||||
}));
|
||||
launchMock.mockResolvedValue(browser);
|
||||
|
||||
const { htmlToPdf } = await import("../utils/html-to-pdf");
|
||||
await expect(htmlToPdf("<html></html>")).rejects.toThrow("Render timeout");
|
||||
expect(launchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
50
src/__tests__/invoice-alerts.test.ts
Normal file
50
src/__tests__/invoice-alerts.test.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { computeAlertWindow } from "../services/invoice-alerts";
|
||||
import { utcMidnightOfLocalDay } from "../utils/date";
|
||||
|
||||
// Pure tests — no DB rows are touched. due_date is @db.Date: Prisma truncates
|
||||
// a Date used in a WHERE filter to its UTC date part, so the alert window
|
||||
// boundaries must be UTC midnights of the LOCAL calendar day. The old code
|
||||
// used local midnights (= 22:00/23:00 UTC of the PREVIOUS day), which shifted
|
||||
// the [today, today+3] due_date window a day early — the "splatnost za 3 dny"
|
||||
// advance alert (due == today+3) could then never fire. All assertions below
|
||||
// are timezone-independent (inputs are built from local components).
|
||||
|
||||
describe("utcMidnightOfLocalDay", () => {
|
||||
it("preserves the LOCAL calendar day shortly after local midnight (the night window)", () => {
|
||||
// 00:30 local on 2098-07-01 — in Prague (UTC+2) this instant is
|
||||
// 2098-06-30T22:30Z, i.e. its UTC date part is the PREVIOUS day, which is
|
||||
// exactly what Prisma would truncate a bare Date to.
|
||||
const justAfterMidnight = new Date(2098, 6, 1, 0, 30, 0);
|
||||
expect(utcMidnightOfLocalDay(justAfterMidnight).getTime()).toBe(
|
||||
Date.UTC(2098, 6, 1),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns UTC midnight of the local day for a mid-day instant", () => {
|
||||
const noon = new Date(2098, 0, 15, 12, 0, 0);
|
||||
expect(utcMidnightOfLocalDay(noon).getTime()).toBe(Date.UTC(2098, 0, 15));
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeAlertWindow", () => {
|
||||
it("builds [today, today+3] as UTC midnights of the LOCAL day, with matching strings", () => {
|
||||
// 00:30 local — the window where the old local-midnight computation
|
||||
// produced yesterday's UTC date and the whole window slid a day early.
|
||||
const now = new Date(2098, 6, 1, 0, 30, 0);
|
||||
const w = computeAlertWindow(now);
|
||||
|
||||
expect(w.today.getTime()).toBe(Date.UTC(2098, 6, 1));
|
||||
expect(w.in3days.getTime()).toBe(Date.UTC(2098, 6, 4));
|
||||
expect(w.todayStr).toBe("2098-07-01");
|
||||
expect(w.in3daysStr).toBe("2098-07-04");
|
||||
});
|
||||
|
||||
it("rolls the +3-day bound over a month boundary", () => {
|
||||
const now = new Date(2098, 0, 30, 8, 0, 0); // 2098-01-30
|
||||
const w = computeAlertWindow(now);
|
||||
|
||||
expect(w.in3days.getTime()).toBe(Date.UTC(2098, 1, 2)); // 2098-02-02
|
||||
expect(w.in3daysStr).toBe("2098-02-02");
|
||||
});
|
||||
});
|
||||
91
src/__tests__/invoice-date-coercion.test.ts
Normal file
91
src/__tests__/invoice-date-coercion.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import invoicesRoutes from "../routes/admin/invoices";
|
||||
import {
|
||||
CreateInvoiceSchema,
|
||||
UpdateInvoiceSchema,
|
||||
} from "../schemas/invoices.schema";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M1: invoice date fields must go through the
|
||||
* lenient ISO-date coercion. A round-tripped datetime string like
|
||||
* "2026-03-02T00:00:00" (the toJSON override emits LOCAL time, no Z) parses
|
||||
* as local Prague midnight = 23:00Z of the PREVIOUS day, and Prisma truncates
|
||||
* @db.Date columns to the UTC date part — the invoice lands a day early and
|
||||
* in the wrong month bucket.
|
||||
*/
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
const createdInvoiceIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(invoicesRoutes, { prefix: "/api/admin/invoices" });
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = jwt.sign(
|
||||
{ sub: admin.id, username: admin.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of createdInvoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
if (app) await app.close();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
describe("invoice @db.Date coercion (audit M1)", () => {
|
||||
it("stores the submitted calendar day when issue_date carries a time part", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/invoices",
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
status: "draft",
|
||||
issue_date: "2026-03-02T00:00:00",
|
||||
items: [],
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const id = res.json().data.id as number;
|
||||
createdInvoiceIds.push(id);
|
||||
|
||||
const row = await prisma.invoices.findUnique({ where: { id } });
|
||||
// @db.Date reads back as UTC midnight of the stored calendar day.
|
||||
expect(row?.issue_date?.toISOString().slice(0, 10)).toBe("2026-03-02");
|
||||
});
|
||||
|
||||
it("schema rejects a Czech-format date", () => {
|
||||
const result = CreateInvoiceSchema.safeParse({
|
||||
issue_date: "15.03.2026",
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("schema normalizes an empty string to null (edit forms clear with '')", () => {
|
||||
const result = CreateInvoiceSchema.safeParse({ issue_date: "" });
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) expect(result.data.issue_date).toBeNull();
|
||||
});
|
||||
|
||||
it("update schema strips the time part from tax_date", () => {
|
||||
const result = UpdateInvoiceSchema.safeParse({
|
||||
tax_date: "2026-03-02T00:00:00",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) expect(result.data.tax_date).toBe("2026-03-02");
|
||||
});
|
||||
});
|
||||
108
src/__tests__/invoice-pdf-cnb-degrade.test.ts
Normal file
108
src/__tests__/invoice-pdf-cnb-degrade.test.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import invoicesPdfRoutes from "../routes/admin/invoices-pdf";
|
||||
import { createInvoice } from "../services/invoices.service";
|
||||
import { getRate } from "../services/exchange-rates";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding M5: a foreign-currency invoice PDF must
|
||||
* degrade gracefully when the CNB rate lookup fails — render WITHOUT the CZK
|
||||
* VAT recap/conversion footnote instead of 500ing the whole preview AND the
|
||||
* NAS archival. The rate only feeds the recap conversion; the document itself
|
||||
* is renderable without it.
|
||||
*/
|
||||
|
||||
vi.mock("../services/exchange-rates", async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import("../services/exchange-rates")>();
|
||||
return { ...actual, getRate: vi.fn() };
|
||||
});
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
const createdInvoiceIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(invoicesPdfRoutes, { prefix: "/api/admin/invoices-pdf" });
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = jwt.sign(
|
||||
{ sub: admin.id, username: admin.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of createdInvoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
if (app) await app.close();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
async function makeEurInvoice() {
|
||||
// Draft → no number consumed; EUR → triggers the CNB rate lookup.
|
||||
const invoice = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "EUR",
|
||||
apply_vat: true,
|
||||
vat_rate: 21,
|
||||
items: [
|
||||
{
|
||||
description: "CNB-DEGRADE-MARKER",
|
||||
quantity: 1,
|
||||
unit_price: 100,
|
||||
vat_rate: 21,
|
||||
},
|
||||
],
|
||||
});
|
||||
createdInvoiceIds.push(invoice.id);
|
||||
return invoice;
|
||||
}
|
||||
|
||||
describe("invoice PDF vs unreachable CNB (audit M5)", () => {
|
||||
it("renders the invoice without the CZK recap when the rate lookup throws", async () => {
|
||||
vi.mocked(getRate).mockRejectedValue(
|
||||
new Error("Nepodařilo se získat aktuální kurzy z ČNB"),
|
||||
);
|
||||
const invoice = await makeEurInvoice();
|
||||
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/invoices-pdf/${invoice.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const html = res.body;
|
||||
expect(html).toContain("CNB-DEGRADE-MARKER");
|
||||
// The CZK recap and the conversion footnote are omitted — their numbers
|
||||
// cannot be computed without the rate.
|
||||
expect(html).not.toContain("Rekapitulace DPH v Kč");
|
||||
expect(html).not.toContain("Přepočet kurzem ČNB");
|
||||
});
|
||||
|
||||
it("still renders the recap + conversion footnote when the rate is available", async () => {
|
||||
vi.mocked(getRate).mockResolvedValue(25.0);
|
||||
const invoice = await makeEurInvoice();
|
||||
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/invoices-pdf/${invoice.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const html = res.body;
|
||||
expect(html).toContain("Rekapitulace DPH v Kč");
|
||||
expect(html).toContain("Přepočet kurzem ČNB");
|
||||
expect(html).toContain("25,000");
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,57 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { invoiceTotalWithVat } from "../services/invoices.service";
|
||||
import { describe, it, expect, afterEach, beforeEach } from "vitest";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import prisma from "../config/database";
|
||||
import {
|
||||
invoiceTotalWithVat,
|
||||
createInvoice,
|
||||
updateInvoice,
|
||||
getInvoice,
|
||||
listInvoices,
|
||||
getInvoiceListTotals,
|
||||
} from "../services/invoices.service";
|
||||
import {
|
||||
CreateInvoiceSchema,
|
||||
UpdateInvoiceSchema,
|
||||
} from "../schemas/invoices.schema";
|
||||
|
||||
// `invoiceTotalWithVat` receives a Prisma row whose money columns are real
|
||||
// `Prisma.Decimal` instances (the model maps `@db.Decimal` → Decimal). Using
|
||||
// real Decimals here — instead of the old `{ toNumber: () => N }` duck types —
|
||||
// means a regression in genuine Decimal handling (e.g. swapping `.toNumber()`
|
||||
// for `Number(decimal)`) is actually caught.
|
||||
|
||||
const dec = (n: number | string) => new Prisma.Decimal(n);
|
||||
|
||||
// Helper so each test reads as a small declarative table of lines.
|
||||
function buildInvoice(opts: {
|
||||
applyVat: boolean;
|
||||
vatRate: number | null;
|
||||
currency?: string;
|
||||
items: Array<{
|
||||
quantity: number | null;
|
||||
unit_price: number | null;
|
||||
vat_rate: number | null;
|
||||
}>;
|
||||
}) {
|
||||
return {
|
||||
apply_vat: opts.applyVat,
|
||||
vat_rate: opts.vatRate === null ? null : dec(opts.vatRate),
|
||||
currency: opts.currency ?? "CZK",
|
||||
invoice_items: opts.items.map((i) => ({
|
||||
quantity: i.quantity === null ? null : dec(i.quantity),
|
||||
unit_price: i.unit_price === null ? null : dec(i.unit_price),
|
||||
vat_rate: i.vat_rate === null ? null : dec(i.vat_rate),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
describe("invoiceTotalWithVat", () => {
|
||||
it("calculates subtotal without VAT when apply_vat is false", () => {
|
||||
const inv = {
|
||||
apply_vat: false,
|
||||
vat_rate: { toNumber: () => 21 },
|
||||
currency: "CZK",
|
||||
invoice_items: [
|
||||
{
|
||||
quantity: { toNumber: () => 2 },
|
||||
unit_price: { toNumber: () => 100 },
|
||||
vat_rate: { toNumber: () => 21 },
|
||||
},
|
||||
],
|
||||
};
|
||||
const inv = buildInvoice({
|
||||
applyVat: false,
|
||||
vatRate: 21,
|
||||
items: [{ quantity: 2, unit_price: 100, vat_rate: 21 }],
|
||||
});
|
||||
expect(invoiceTotalWithVat(inv)).toBe(200);
|
||||
});
|
||||
|
||||
@@ -24,32 +61,298 @@ describe("invoiceTotalWithVat", () => {
|
||||
// Total VAT = 7.00 * 3 = 21.00
|
||||
// Subtotal = 33.33 * 3 = 99.99
|
||||
// Total = 99.99 + 21.00 = 120.99
|
||||
const inv = {
|
||||
apply_vat: true,
|
||||
vat_rate: { toNumber: () => 21 },
|
||||
currency: "CZK",
|
||||
invoice_items: Array.from({ length: 3 }, () => ({
|
||||
quantity: { toNumber: () => 1 },
|
||||
unit_price: { toNumber: () => 33.33 },
|
||||
vat_rate: { toNumber: () => 21 },
|
||||
const inv = buildInvoice({
|
||||
applyVat: true,
|
||||
vatRate: 21,
|
||||
items: Array.from({ length: 3 }, () => ({
|
||||
quantity: 1,
|
||||
unit_price: 33.33,
|
||||
vat_rate: 21,
|
||||
})),
|
||||
};
|
||||
});
|
||||
expect(invoiceTotalWithVat(inv)).toBe(120.99);
|
||||
});
|
||||
|
||||
it("handles null quantity and unit_price gracefully", () => {
|
||||
const inv = {
|
||||
apply_vat: true,
|
||||
vat_rate: { toNumber: () => 21 },
|
||||
currency: "CZK",
|
||||
invoice_items: [
|
||||
{
|
||||
quantity: { toNumber: () => 0 },
|
||||
unit_price: { toNumber: () => 0 },
|
||||
vat_rate: { toNumber: () => 21 },
|
||||
},
|
||||
it("treats a null quantity (and null unit_price) as 0 for that line", () => {
|
||||
// The line is genuinely null here (not 0): quantity?.toNumber() === undefined
|
||||
// -> Number(undefined) is NaN -> `|| 0` -> base 0. A second, well-formed
|
||||
// line proves the null line contributes nothing while the rest still totals.
|
||||
const inv = buildInvoice({
|
||||
applyVat: true,
|
||||
vatRate: 21,
|
||||
items: [
|
||||
{ quantity: null, unit_price: null, vat_rate: 21 },
|
||||
{ quantity: 1, unit_price: 100, vat_rate: 21 }, // base 100, vat 21
|
||||
],
|
||||
};
|
||||
});
|
||||
expect(invoiceTotalWithVat(inv)).toBe(121);
|
||||
});
|
||||
|
||||
it("returns 0 when every line is null", () => {
|
||||
const inv = buildInvoice({
|
||||
applyVat: true,
|
||||
vatRate: 21,
|
||||
items: [{ quantity: null, unit_price: null, vat_rate: null }],
|
||||
});
|
||||
expect(invoiceTotalWithVat(inv)).toBe(0);
|
||||
});
|
||||
|
||||
it("applies mixed per-line vat_rate values, falling back to the invoice rate when a line rate is 0/absent", () => {
|
||||
// Line 1: 2 x 100 @ 21% -> base 200, vat 42
|
||||
// Line 2: 1 x 50 @ 12% -> base 50, vat 6
|
||||
// Line 3: 1 x 100 @ 0% -> a line rate of 0 falls through to the invoice
|
||||
// default (15%) per the `|| inv.vat_rate || 21` semantics -> vat 15
|
||||
// Subtotal = 350, VAT = 63, Total = 413
|
||||
const inv = buildInvoice({
|
||||
applyVat: true,
|
||||
vatRate: 15,
|
||||
items: [
|
||||
{ quantity: 2, unit_price: 100, vat_rate: 21 },
|
||||
{ quantity: 1, unit_price: 50, vat_rate: 12 },
|
||||
{ quantity: 1, unit_price: 100, vat_rate: 0 },
|
||||
],
|
||||
});
|
||||
expect(invoiceTotalWithVat(inv)).toBe(413);
|
||||
});
|
||||
|
||||
it("handles a negative (discount) line correctly", () => {
|
||||
// Line 1: 1 x 1000 @ 21% -> base 1000, vat 210
|
||||
// Line 2 (discount): 1 x -200 @ 21% -> base -200, vat -42
|
||||
// Subtotal = 800, VAT = 168, Total = 968
|
||||
const inv = buildInvoice({
|
||||
applyVat: true,
|
||||
vatRate: 21,
|
||||
items: [
|
||||
{ quantity: 1, unit_price: 1000, vat_rate: 21 },
|
||||
{ quantity: 1, unit_price: -200, vat_rate: 21 },
|
||||
],
|
||||
});
|
||||
expect(invoiceTotalWithVat(inv)).toBe(968);
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* PUT regression — billing_text must survive UpdateInvoiceSchema */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
// The PUT route does `parseBody(UpdateInvoiceSchema, body)` and hands the
|
||||
// PARSED data to `updateInvoice`. UpdateInvoiceSchema is a plain z.object,
|
||||
// which STRIPS unknown keys — so a field missing from the schema is silently
|
||||
// dropped before the service ever sees it, while the client still gets a
|
||||
// success response. This block mirrors that exact flow against the real DB.
|
||||
|
||||
describe("updateInvoice — billing_text round-trips through UpdateInvoiceSchema", () => {
|
||||
const invoiceIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
invoiceIds.length = 0;
|
||||
});
|
||||
|
||||
it("persists an edited billing_text (the schema must not strip it)", async () => {
|
||||
const draft = await createInvoice({ billing_text: "Původní text" });
|
||||
invoiceIds.push(draft.id);
|
||||
|
||||
// Mirror the route: raw body -> UpdateInvoiceSchema -> updateInvoice.
|
||||
const parsed = UpdateInvoiceSchema.parse({
|
||||
billing_text: "Fakturujeme Vám dle objednávky č. 123",
|
||||
});
|
||||
expect(parsed.billing_text).toBe("Fakturujeme Vám dle objednávky č. 123");
|
||||
|
||||
const res = await updateInvoice(draft.id, parsed);
|
||||
expect("error" in res).toBe(false);
|
||||
|
||||
const row = await prisma.invoices.findUnique({ where: { id: draft.id } });
|
||||
expect(row?.billing_text).toBe("Fakturujeme Vám dle objednávky č. 123");
|
||||
});
|
||||
|
||||
it("clears billing_text when null is sent, and leaves it untouched when absent", async () => {
|
||||
const draft = await createInvoice({ billing_text: "Text na PDF" });
|
||||
invoiceIds.push(draft.id);
|
||||
|
||||
// Absent from the body -> updateInvoice's `!== undefined` guard skips it.
|
||||
await updateInvoice(
|
||||
draft.id,
|
||||
UpdateInvoiceSchema.parse({ internal_notes: "x" }),
|
||||
);
|
||||
let row = await prisma.invoices.findUnique({ where: { id: draft.id } });
|
||||
expect(row?.billing_text).toBe("Text na PDF");
|
||||
|
||||
// Explicit null -> cleared (the strFields path maps falsy -> null).
|
||||
await updateInvoice(
|
||||
draft.id,
|
||||
UpdateInvoiceSchema.parse({ billing_text: null }),
|
||||
);
|
||||
row = await prisma.invoices.findUnique({ where: { id: draft.id } });
|
||||
expect(row?.billing_text).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* "Obsah" sections + internal-only notes (mirrors issued orders) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
describe("invoice sections round-trip; dropped `notes` is stripped", () => {
|
||||
const invoiceIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
invoiceIds.length = 0;
|
||||
});
|
||||
|
||||
it("creates, returns and replaces CZ/EN sections in position order", async () => {
|
||||
const parsed = CreateInvoiceSchema.parse({
|
||||
billing_text: "Sekce test",
|
||||
sections: [
|
||||
{ title: "Scope", title_cz: "Rozsah", content: "<p>obsah 1</p>" },
|
||||
{ title: "", title_cz: "Podmínky", content: "<p>obsah 2</p>" },
|
||||
],
|
||||
});
|
||||
const draft = await createInvoice(parsed);
|
||||
invoiceIds.push(draft.id);
|
||||
|
||||
const detail = await getInvoice(draft.id);
|
||||
expect(detail?.sections?.length).toBe(2);
|
||||
expect(detail?.sections?.[0].title_cz).toBe("Rozsah");
|
||||
expect(detail?.sections?.[1].title_cz).toBe("Podmínky");
|
||||
expect(detail?.sections?.[0].position).toBe(0);
|
||||
expect(detail?.sections?.[1].position).toBe(1);
|
||||
|
||||
// Full-replace on update (same model as items).
|
||||
const upd = UpdateInvoiceSchema.parse({
|
||||
sections: [
|
||||
{ title: "Only", title_cz: "Jediná", content: "<p>nový obsah</p>" },
|
||||
],
|
||||
});
|
||||
const res = await updateInvoice(draft.id, upd);
|
||||
expect("error" in res).toBe(false);
|
||||
|
||||
const after = await getInvoice(draft.id);
|
||||
expect(after?.sections?.length).toBe(1);
|
||||
expect(after?.sections?.[0].title_cz).toBe("Jediná");
|
||||
expect(after?.sections?.[0].content).toBe("<p>nový obsah</p>");
|
||||
});
|
||||
|
||||
it("sections survive an items-only update untouched (absent = keep)", async () => {
|
||||
const draft = await createInvoice(
|
||||
CreateInvoiceSchema.parse({
|
||||
sections: [{ title: "", title_cz: "Drží", content: "<p>x</p>" }],
|
||||
}),
|
||||
);
|
||||
invoiceIds.push(draft.id);
|
||||
|
||||
await updateInvoice(
|
||||
draft.id,
|
||||
UpdateInvoiceSchema.parse({
|
||||
items: [{ description: "Práce", quantity: 1, unit_price: 100 }],
|
||||
}),
|
||||
);
|
||||
|
||||
const after = await getInvoice(draft.id);
|
||||
expect(after?.sections?.length).toBe(1);
|
||||
expect(after?.sections?.[0].title_cz).toBe("Drží");
|
||||
expect(after?.items?.length).toBe(1);
|
||||
});
|
||||
|
||||
it("silently strips the dropped `notes` key from legacy payloads", async () => {
|
||||
// The printed-notes column was dropped (notes are internal-only now) —
|
||||
// a legacy client still sending `notes` must not 500 or write anything.
|
||||
const parsedCreate = CreateInvoiceSchema.parse({
|
||||
notes: "<p>stará poznámka</p>",
|
||||
internal_notes: "<p>interní</p>",
|
||||
});
|
||||
expect("notes" in parsedCreate).toBe(false);
|
||||
|
||||
const draft = await createInvoice(parsedCreate);
|
||||
invoiceIds.push(draft.id);
|
||||
const row = await prisma.invoices.findUnique({ where: { id: draft.id } });
|
||||
expect(row?.internal_notes).toBe("<p>interní</p>");
|
||||
|
||||
const parsedUpdate = UpdateInvoiceSchema.parse({ notes: "x" });
|
||||
expect("notes" in parsedUpdate).toBe(false);
|
||||
const res = await updateInvoice(draft.id, parsedUpdate);
|
||||
expect("error" in res).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Month filter boundaries — issue_date is @db.Date */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
// issue_date is @db.Date: Prisma compares a Date filter by its UTC date part.
|
||||
// The old LOCAL-midnight month bounds (= 22:00/23:00 UTC of the previous day)
|
||||
// shifted the window a day back — the list/totals included the previous
|
||||
// month's last day and DROPPED invoices issued on the selected month's LAST
|
||||
// day. buildInvoiceWhere is shared by listInvoices AND getInvoiceListTotals,
|
||||
// so both are exercised. Fixtures use the test-only "TST" currency + far-future
|
||||
// 2098 dates so totals can be asserted exactly without colliding with other
|
||||
// suites' rows.
|
||||
|
||||
describe("listInvoices / getInvoiceListTotals — month filter (@db.Date boundaries)", () => {
|
||||
const cleanup = async () => {
|
||||
// invoice_items cascade on invoice delete.
|
||||
await prisma.invoices.deleteMany({ where: { currency: "TST" } });
|
||||
};
|
||||
|
||||
beforeEach(cleanup);
|
||||
afterEach(cleanup);
|
||||
|
||||
const listParams = {
|
||||
page: 1,
|
||||
limit: 100,
|
||||
skip: 0,
|
||||
sort: "id",
|
||||
order: "asc" as const,
|
||||
search: "",
|
||||
};
|
||||
|
||||
async function createBoundaryFixtures() {
|
||||
// Drafts: no invoice number is consumed, but buildInvoiceWhere has no
|
||||
// status filter so they appear in the list/totals like any invoice.
|
||||
const lastDayJan = await createInvoice({
|
||||
status: "draft",
|
||||
issue_date: "2098-01-31",
|
||||
currency: "TST",
|
||||
vat_rate: 21,
|
||||
items: [{ quantity: 1, unit_price: 100, vat_rate: 21 }], // total 121
|
||||
});
|
||||
const firstDayFeb = await createInvoice({
|
||||
status: "draft",
|
||||
issue_date: "2098-02-01",
|
||||
currency: "TST",
|
||||
vat_rate: 21,
|
||||
items: [{ quantity: 1, unit_price: 200, vat_rate: 21 }], // total 242
|
||||
});
|
||||
return { lastDayJan, firstDayFeb };
|
||||
}
|
||||
|
||||
it("a month's list contains its own LAST day and not the neighbor month's first day", async () => {
|
||||
const { lastDayJan, firstDayFeb } = await createBoundaryFixtures();
|
||||
|
||||
const jan = await listInvoices({ ...listParams, month: 1, year: 2098 });
|
||||
const janIds = jan.data.map((i) => i.id);
|
||||
expect(janIds).toContain(lastDayJan.id);
|
||||
expect(janIds).not.toContain(firstDayFeb.id);
|
||||
|
||||
const feb = await listInvoices({ ...listParams, month: 2, year: 2098 });
|
||||
const febIds = feb.data.map((i) => i.id);
|
||||
expect(febIds).toContain(firstDayFeb.id);
|
||||
expect(febIds).not.toContain(lastDayJan.id);
|
||||
});
|
||||
|
||||
it("per-currency totals include the month's last day exactly once", async () => {
|
||||
await createBoundaryFixtures();
|
||||
|
||||
const jan = await getInvoiceListTotals({ month: 1, year: 2098 });
|
||||
const janTst = jan.totals.find((t) => t.currency === "TST");
|
||||
// 100 + 21 % VAT — proves the Jan 31 invoice is counted and the
|
||||
// Feb 1 invoice (242) is NOT pulled into January.
|
||||
expect(janTst?.amount).toBe(121);
|
||||
|
||||
const feb = await getInvoiceListTotals({ month: 2, year: 2098 });
|
||||
const febTst = feb.totals.find((t) => t.currency === "TST");
|
||||
expect(febTst?.amount).toBe(242);
|
||||
});
|
||||
});
|
||||
|
||||
1390
src/__tests__/issued-orders.test.ts
Normal file
1390
src/__tests__/issued-orders.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
130
src/__tests__/item-discount-pdf.test.ts
Normal file
130
src/__tests__/item-discount-pdf.test.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import offersPdfRoutes from "../routes/admin/offers-pdf";
|
||||
import invoicesPdfRoutes from "../routes/admin/invoices-pdf";
|
||||
import { createInvoice } from "../services/invoices.service";
|
||||
|
||||
/**
|
||||
* The per-item Sleva column is CONDITIONAL on the PDF: render it only when at
|
||||
* least one item carries a discount > 0; otherwise the table looks exactly as
|
||||
* before. The discounted net always flows into the line/grand totals.
|
||||
*/
|
||||
|
||||
let app: ReturnType<typeof Fastify> | null = null;
|
||||
let adminToken = "";
|
||||
const quotationIds: number[] = [];
|
||||
const invoiceIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(offersPdfRoutes, { prefix: "/api/admin/offers-pdf" });
|
||||
await app.register(invoicesPdfRoutes, { prefix: "/api/admin/invoices-pdf" });
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = jwt.sign(
|
||||
{ sub: admin.id, username: admin.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of quotationIds)
|
||||
await prisma.quotations.deleteMany({ where: { id } });
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
const offerHtml = async (discount: number): Promise<string> => {
|
||||
const q = await prisma.quotations.create({
|
||||
data: {
|
||||
quotation_number: `Q-SLEVA-${discount}-${Date.now()}`,
|
||||
status: "active",
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
quotation_items: {
|
||||
create: [
|
||||
{
|
||||
description: "Položka",
|
||||
quantity: 2,
|
||||
unit: "ks",
|
||||
unit_price: 100,
|
||||
discount,
|
||||
is_included_in_total: true,
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
quotationIds.push(q.id);
|
||||
const res = await app!.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/offers-pdf/${q.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return res.body;
|
||||
};
|
||||
|
||||
describe("offer PDF Sleva column", () => {
|
||||
it("renders a Sleva column + discounted total when an item has a discount", async () => {
|
||||
const html = await offerHtml(10);
|
||||
expect(html).toContain("Sleva");
|
||||
// 2 × 100 with 10% off => 180,00 (no thousands separator at this size).
|
||||
expect(html).toContain("180,00");
|
||||
expect(html).not.toContain("200,00");
|
||||
});
|
||||
|
||||
it("omits the Sleva column when no item has a discount", async () => {
|
||||
const html = await offerHtml(0);
|
||||
expect(html).not.toContain("Sleva");
|
||||
expect(html).toContain("200,00");
|
||||
});
|
||||
});
|
||||
|
||||
const invoiceHtml = async (discount: number): Promise<string> => {
|
||||
const inv = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
apply_vat: true,
|
||||
vat_rate: 21,
|
||||
language: "cs",
|
||||
items: [
|
||||
{
|
||||
description: "Položka",
|
||||
quantity: 2,
|
||||
unit_price: 1000,
|
||||
discount,
|
||||
vat_rate: 21,
|
||||
},
|
||||
],
|
||||
});
|
||||
invoiceIds.push(inv.id);
|
||||
const res = await app!.inject({
|
||||
method: "GET",
|
||||
url: `/api/admin/invoices-pdf/${inv.id}`,
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return res.body;
|
||||
};
|
||||
|
||||
describe("invoice PDF Sleva column", () => {
|
||||
it("renders a Sleva column when an item has a discount", async () => {
|
||||
const html = await invoiceHtml(10);
|
||||
expect(html).toContain("Sleva");
|
||||
expect(html).toContain("10");
|
||||
});
|
||||
|
||||
it("omits the Sleva column when no item has a discount", async () => {
|
||||
const html = await invoiceHtml(0);
|
||||
expect(html).not.toContain("Sleva");
|
||||
});
|
||||
});
|
||||
55
src/__tests__/item-discount-schema.test.ts
Normal file
55
src/__tests__/item-discount-schema.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { CreateQuotationSchema } from "../schemas/offers.schema";
|
||||
import { CreateInvoiceSchema } from "../schemas/invoices.schema";
|
||||
|
||||
/**
|
||||
* The per-item Sleva is a percentage: the offer- and invoice-item schemas must
|
||||
* accept 0–100, default to 0 when absent, and reject out-of-range values.
|
||||
*/
|
||||
|
||||
describe("offer item discount schema", () => {
|
||||
it("accepts a 0–100 discount", () => {
|
||||
const r = CreateQuotationSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100, discount: 15 }],
|
||||
});
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.success && r.data.items?.[0].discount).toBe(15);
|
||||
});
|
||||
|
||||
it("defaults discount to 0 when absent", () => {
|
||||
const r = CreateQuotationSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100 }],
|
||||
});
|
||||
expect(r.success && r.data.items?.[0].discount).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects a discount above 100", () => {
|
||||
const r = CreateQuotationSchema.safeParse({
|
||||
items: [
|
||||
{ description: "X", quantity: 1, unit_price: 100, discount: 150 },
|
||||
],
|
||||
});
|
||||
expect(r.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("invoice item discount schema", () => {
|
||||
it("accepts a 0–100 discount and defaults to 0", () => {
|
||||
const ok = CreateInvoiceSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100, discount: 10 }],
|
||||
});
|
||||
expect(ok.success && ok.data.items?.[0].discount).toBe(10);
|
||||
|
||||
const def = CreateInvoiceSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100 }],
|
||||
});
|
||||
expect(def.success && def.data.items?.[0].discount).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects a negative discount", () => {
|
||||
const r = CreateInvoiceSchema.safeParse({
|
||||
items: [{ description: "X", quantity: 1, unit_price: 100, discount: -5 }],
|
||||
});
|
||||
expect(r.success).toBe(false);
|
||||
});
|
||||
});
|
||||
94
src/__tests__/item-discount-totals.test.ts
Normal file
94
src/__tests__/item-discount-totals.test.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { createOffer, getOfferTotals } from "../services/offers.service";
|
||||
import {
|
||||
createInvoice,
|
||||
getInvoiceListTotals,
|
||||
} from "../services/invoices.service";
|
||||
|
||||
/**
|
||||
* Per-item Sleva (% discount) must reduce the line NET — and on invoices the
|
||||
* VAT is computed on the discounted net. Hits the real `app_test` DB through the
|
||||
* service layer (suite convention), mirroring offer-invoice-totals.test.ts.
|
||||
*/
|
||||
|
||||
const MARKER = "SLEVA-TOTALS-2096";
|
||||
const YEAR = 2096;
|
||||
const MONTH = 8; // invoice issue_date window [2096-08-01, 2096-09-01)
|
||||
const dateStr = `${YEAR}-0${MONTH}-15`;
|
||||
|
||||
const offerIds: number[] = [];
|
||||
const invoiceIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of offerIds)
|
||||
await prisma.quotations.deleteMany({ where: { id } });
|
||||
for (const id of invoiceIds)
|
||||
await prisma.invoices.deleteMany({ where: { id } });
|
||||
offerIds.length = 0;
|
||||
invoiceIds.length = 0;
|
||||
await prisma.number_sequences.deleteMany({
|
||||
where: { type: { in: ["offer", "invoice"] } },
|
||||
});
|
||||
});
|
||||
|
||||
const amountFor = (
|
||||
totals: { currency: string; amount: number }[],
|
||||
currency: string,
|
||||
): number | undefined => totals.find((t) => t.currency === currency)?.amount;
|
||||
|
||||
describe("offer per-item discount", () => {
|
||||
it("reduces the offer NET total by the per-item percentage", async () => {
|
||||
// 2 × 1000 with 10% off => 1800 net.
|
||||
const res = await createOffer({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
project_code: MARKER,
|
||||
items: [
|
||||
{ description: "X", quantity: 2, unit_price: 1000, discount: 10 },
|
||||
],
|
||||
});
|
||||
if ("error" in res) throw new Error(JSON.stringify(res));
|
||||
offerIds.push(res.id);
|
||||
|
||||
const { totals } = await getOfferTotals({ search: MARKER });
|
||||
expect(amountFor(totals, "CZK")).toBe(1800);
|
||||
});
|
||||
});
|
||||
|
||||
describe("invoice per-item discount", () => {
|
||||
it("computes VAT on the discounted net (gross = discounted net + VAT)", async () => {
|
||||
// 2 × 1000 with 10% off => net 1800, VAT@21% = 378, gross 2178.
|
||||
const inv = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
vat_rate: 21,
|
||||
apply_vat: true,
|
||||
issue_date: dateStr,
|
||||
items: [
|
||||
{ description: "X", quantity: 2, unit_price: 1000, discount: 10 },
|
||||
],
|
||||
});
|
||||
invoiceIds.push(inv.id);
|
||||
|
||||
const { totals } = await getInvoiceListTotals({ month: MONTH, year: YEAR });
|
||||
expect(amountFor(totals, "CZK")).toBe(2178);
|
||||
});
|
||||
|
||||
it("treats a 100% discount line as zero", async () => {
|
||||
const inv = await createInvoice({
|
||||
status: "draft",
|
||||
currency: "CZK",
|
||||
vat_rate: 21,
|
||||
apply_vat: true,
|
||||
issue_date: dateStr,
|
||||
items: [
|
||||
{ description: "Free", quantity: 5, unit_price: 200, discount: 100 },
|
||||
],
|
||||
});
|
||||
invoiceIds.push(inv.id);
|
||||
|
||||
const { totals } = await getInvoiceListTotals({ month: MONTH, year: YEAR });
|
||||
expect(amountFor(totals, "CZK")).toBeUndefined(); // zero totals are dropped
|
||||
});
|
||||
});
|
||||
202
src/__tests__/leave-requests-holidays.test.ts
Normal file
202
src/__tests__/leave-requests-holidays.test.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import Fastify from "fastify";
|
||||
import jwt from "jsonwebtoken";
|
||||
import prisma from "../config/database";
|
||||
import { config } from "../config/env";
|
||||
import leaveRequestsRoutes from "../routes/admin/leave-requests";
|
||||
|
||||
/**
|
||||
* Pinning tests for audit finding H6 + the year-spanning fast-follow:
|
||||
* leave-request creation and approval must mirror attendance.service
|
||||
* createLeave — skip Czech public holidays (a weekday holiday is already
|
||||
* paid/free; charging it double-deducts) and book each day's hours against
|
||||
* ITS OWN calendar year's balance (a Dec→Jan request used to charge
|
||||
* everything to the start year).
|
||||
*
|
||||
* Fixture math (verified): 2098-05-01 (Thu) and 2098-05-08 (Thu) are both
|
||||
* weekday holidays → the 05-01..05-08 range has 4 chargeable days (32h),
|
||||
* not 6 (48h). 2098-12-28 (Sun)..2099-01-05 (Mon) has 3 chargeable days in
|
||||
* 2098 (29/30/31 = 24h) and 2 in 2099 (Jan 2 + Jan 5 = 16h; Jan 1 is a
|
||||
* holiday).
|
||||
*/
|
||||
|
||||
const N = "leave_holiday_";
|
||||
|
||||
let app: ReturnType<typeof Fastify>;
|
||||
let adminToken: string;
|
||||
let userToken: string;
|
||||
let userId: number;
|
||||
|
||||
async function cleanup() {
|
||||
const users = await prisma.users.findMany({
|
||||
where: { username: { startsWith: N } },
|
||||
select: { id: true },
|
||||
});
|
||||
const ids = users.map((u) => u.id);
|
||||
if (ids.length > 0) {
|
||||
await prisma.attendance.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.leave_requests.deleteMany({
|
||||
where: { user_id: { in: ids } },
|
||||
});
|
||||
await prisma.leave_balances.deleteMany({ where: { user_id: { in: ids } } });
|
||||
await prisma.users.deleteMany({ where: { id: { in: ids } } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await cleanup();
|
||||
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(leaveRequestsRoutes, {
|
||||
prefix: "/api/admin/leave-requests",
|
||||
});
|
||||
|
||||
const admin = await prisma.users.findFirst({
|
||||
where: { roles: { name: "admin" } },
|
||||
});
|
||||
if (!admin) throw new Error("Test setup: admin user not found");
|
||||
adminToken = jwt.sign(
|
||||
{ sub: admin.id, username: admin.username, role: "admin" },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
|
||||
const role = await prisma.roles.findFirst();
|
||||
const user = await prisma.users.create({
|
||||
data: {
|
||||
username: `${N}user`,
|
||||
email: `${N}user@test.local`,
|
||||
password_hash:
|
||||
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
||||
first_name: "Leave",
|
||||
last_name: "Holiday",
|
||||
is_active: true,
|
||||
role_id: role!.id,
|
||||
},
|
||||
});
|
||||
userId = user.id;
|
||||
userToken = jwt.sign(
|
||||
{ sub: user.id, username: user.username, role: role!.name },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
|
||||
for (const year of [2098, 2099]) {
|
||||
await prisma.leave_balances.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
year,
|
||||
vacation_total: 200,
|
||||
vacation_used: 0,
|
||||
sick_used: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (app) await app.close();
|
||||
await cleanup();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
async function balance(year: number) {
|
||||
return prisma.leave_balances.findFirst({
|
||||
where: { user_id: userId, year },
|
||||
});
|
||||
}
|
||||
|
||||
describe("leave requests vs Czech holidays (audit H6)", () => {
|
||||
it("creation excludes weekday public holidays from the charged total", async () => {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/admin/leave-requests",
|
||||
headers: {
|
||||
Authorization: `Bearer ${userToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: {
|
||||
leave_type: "vacation",
|
||||
date_from: "2098-05-01",
|
||||
date_to: "2098-05-08",
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const row = await prisma.leave_requests.findFirst({
|
||||
where: { id: res.json().data.id },
|
||||
});
|
||||
expect(row?.total_days).toBe(4);
|
||||
expect(Number(row?.total_hours)).toBe(32);
|
||||
// Leave it cancelled so the approval test's range stays free.
|
||||
await prisma.leave_requests.update({
|
||||
where: { id: row!.id },
|
||||
data: { status: "cancelled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("approval charges only non-holiday business days and skips holiday attendance rows", async () => {
|
||||
// Stored totals mimic a PRE-FIX request (weekend-only counting) — the
|
||||
// approval must recompute, not trust them.
|
||||
const req = await prisma.leave_requests.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
leave_type: "vacation",
|
||||
date_from: new Date(Date.UTC(2098, 4, 1)),
|
||||
date_to: new Date(Date.UTC(2098, 4, 8)),
|
||||
total_hours: 48,
|
||||
total_days: 6,
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/leave-requests/${req.id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { status: "approved" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
expect(Number((await balance(2098))?.vacation_used)).toBe(32);
|
||||
|
||||
const rows = await prisma.attendance.findMany({
|
||||
where: { user_id: userId, leave_type: "vacation" },
|
||||
});
|
||||
const days = rows.map((r) => r.shift_date.toISOString().slice(0, 10));
|
||||
expect(rows).toHaveLength(4);
|
||||
expect(days).not.toContain("2098-05-01");
|
||||
expect(days).not.toContain("2098-05-08");
|
||||
});
|
||||
|
||||
it("a year-spanning approval books each day against its own year's balance", async () => {
|
||||
const req = await prisma.leave_requests.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
leave_type: "sick",
|
||||
date_from: new Date(Date.UTC(2098, 11, 28)),
|
||||
date_to: new Date(Date.UTC(2099, 0, 5)),
|
||||
total_hours: 48,
|
||||
total_days: 6,
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/admin/leave-requests/${req.id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
payload: { status: "approved" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// 29/30/31 Dec 2098 = 24h; Jan 2 + Jan 5 2099 = 16h (Jan 1 is a holiday).
|
||||
expect(Number((await balance(2098))?.sick_used)).toBe(24);
|
||||
expect(Number((await balance(2099))?.sick_used)).toBe(16);
|
||||
});
|
||||
});
|
||||
@@ -1,85 +1,296 @@
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import prisma from "../config/database";
|
||||
import { createProject } from "../services/projects.service";
|
||||
import { createOrder } from "../services/orders.service";
|
||||
import {
|
||||
createOrder,
|
||||
createOrderFromQuotation,
|
||||
deleteOrder,
|
||||
} from "../services/orders.service";
|
||||
import { previewProjectNumber } from "../services/numbering.service";
|
||||
|
||||
const YEAR = new Date().getFullYear();
|
||||
|
||||
const createdProjectIds: number[] = [];
|
||||
const createdOrderIds: number[] = [];
|
||||
const createdQuotationIds: number[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const id of createdProjectIds)
|
||||
await prisma.projects.deleteMany({ where: { id } });
|
||||
for (const id of createdOrderIds)
|
||||
await prisma.orders.deleteMany({ where: { id } });
|
||||
for (const id of createdQuotationIds)
|
||||
await prisma.quotations.deleteMany({ where: { id } });
|
||||
createdProjectIds.length = 0;
|
||||
createdOrderIds.length = 0;
|
||||
await prisma.number_sequences.deleteMany({ where: { type: "shared" } });
|
||||
createdQuotationIds.length = 0;
|
||||
// Orders and projects now draw from SEPARATE sequences — reset both.
|
||||
await prisma.number_sequences.deleteMany({
|
||||
where: { type: { in: ["shared", "project"] } },
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Read the current `last_number` of a (type, current-year) sequence row, or 0
|
||||
* when the row doesn't exist yet (the first allocation creates it at 1). Used to
|
||||
* prove each generator advances its OWN row by exactly 1.
|
||||
*/
|
||||
async function seqLastNumber(type: "shared" | "project"): Promise<number> {
|
||||
const row = await prisma.number_sequences.findFirst({
|
||||
where: { type, year: YEAR },
|
||||
select: { last_number: true },
|
||||
});
|
||||
return row?.last_number ?? 0;
|
||||
}
|
||||
|
||||
const baseOrder = {
|
||||
status: "prijata" as const,
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
vat_rate: 21,
|
||||
apply_vat: true,
|
||||
exchange_rate: 1,
|
||||
};
|
||||
|
||||
/**
|
||||
* Fail loudly (instead of the old `if (!("id" in res)) return;`, which silently
|
||||
* passed the test when a create failed) while still narrowing the union via the
|
||||
* `in` operator so the success-branch fields stay typed.
|
||||
*/
|
||||
function failResult(res: unknown): never {
|
||||
throw new Error(`expected a success result, got ${JSON.stringify(res)}`);
|
||||
}
|
||||
|
||||
describe("createOrder (manual, optional linked project)", () => {
|
||||
it("creates an order AND a project sharing one number when create_project=true", async () => {
|
||||
it("creates an order AND a project, each with its OWN number, linked by FK", async () => {
|
||||
// Capture BOTH sequence counters before the create so we can prove each
|
||||
// generator advanced its OWN row (not that the project consumed the shared
|
||||
// counter). Format difference alone (OBJ-… vs 26730…) would let `not.toBe`
|
||||
// pass even if the project drew from `shared` — the deltas catch that.
|
||||
const sharedBefore = await seqLastNumber("shared");
|
||||
const projectBefore = await seqLastNumber("project");
|
||||
|
||||
const res = await createOrder({
|
||||
...baseOrder,
|
||||
scope_title: "Ruční zakázka",
|
||||
create_project: true,
|
||||
});
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
if (!("id" in res)) failResult(res);
|
||||
createdOrderIds.push(res.id!);
|
||||
expect(res.project_id).toBeTruthy();
|
||||
const project = await prisma.projects.findUnique({
|
||||
where: { id: res.project_id! },
|
||||
});
|
||||
if (project) createdProjectIds.push(project.id);
|
||||
expect(project?.project_number).toBe(res.order_number);
|
||||
// The auto-created project now draws from the dedicated project sequence,
|
||||
// so its number is distinct from the order's shared number. They relate
|
||||
// only via the order_id FK, not by sharing a number.
|
||||
expect(project?.project_number).toBeTruthy();
|
||||
expect(project?.project_number).not.toBe(res.order_number);
|
||||
expect(project?.order_id).toBe(res.id);
|
||||
|
||||
// Sequence isolation: the order consumed exactly one `shared` number and
|
||||
// the project consumed exactly one `project` number — each generator
|
||||
// advanced its OWN row by 1. A regression where the project draws from the
|
||||
// `shared` counter would bump `shared` by 2 and leave `project` at 0.
|
||||
const sharedAfter = await seqLastNumber("shared");
|
||||
const projectAfter = await seqLastNumber("project");
|
||||
expect(sharedAfter - sharedBefore).toBe(1);
|
||||
expect(projectAfter - projectBefore).toBe(1);
|
||||
});
|
||||
|
||||
it("creates only the order when create_project=false", async () => {
|
||||
const res = await createOrder({ ...baseOrder, create_project: false });
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
if (!("id" in res)) failResult(res);
|
||||
createdOrderIds.push(res.id!);
|
||||
expect(res.project_id).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("shared pool coherence (tracking)", () => {
|
||||
it("order → standalone project → order produce three distinct shared numbers", async () => {
|
||||
const o1 = await createOrder({ ...baseOrder, create_project: true });
|
||||
if ("id" in o1) {
|
||||
createdOrderIds.push(o1.id);
|
||||
if (o1.project_id) createdProjectIds.push(o1.project_id);
|
||||
}
|
||||
const p = await createProject({ name: "Mezi-projekt", status: "aktivni" });
|
||||
if ("project_number" in p) createdProjectIds.push(p.id);
|
||||
const o2 = await createOrder({ ...baseOrder, create_project: false });
|
||||
if ("id" in o2) createdOrderIds.push(o2.id);
|
||||
describe("createOrderFromQuotation (auto-project gets its OWN number)", () => {
|
||||
it("links a project whose number is from the project sequence, distinct from the order number", async () => {
|
||||
// Seed a minimal quotation (no items/sections needed — createOrderFrom
|
||||
// Quotation copies whatever is present and both arrays may be empty).
|
||||
const quotation = await prisma.quotations.create({
|
||||
data: {
|
||||
quotation_number: `Q-FROMQ-${Date.now()}`,
|
||||
status: "active",
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
},
|
||||
});
|
||||
createdQuotationIds.push(quotation.id);
|
||||
|
||||
const n1 = "id" in o1 ? o1.order_number : null;
|
||||
const np = "project_number" in p ? p.project_number : null;
|
||||
const n2 = "id" in o2 ? o2.order_number : null;
|
||||
expect(new Set([n1, np, n2]).size).toBe(3);
|
||||
const res = await createOrderFromQuotation({
|
||||
quotationId: quotation.id,
|
||||
customerOrderNumber: "PO-FROMQ",
|
||||
});
|
||||
if (!("data" in res) || !res.data) failResult(res);
|
||||
const orderId = res.data.order_id;
|
||||
createdOrderIds.push(orderId);
|
||||
|
||||
const order = await prisma.orders.findUnique({ where: { id: orderId } });
|
||||
const project = await prisma.projects.findFirst({
|
||||
where: { order_id: orderId },
|
||||
});
|
||||
if (project) createdProjectIds.push(project.id);
|
||||
|
||||
// Primary flow: the auto-created project must get a non-empty number from
|
||||
// the dedicated `project` sequence (code 73), DISTINCT from the order's
|
||||
// shared number (code 71). Pre-split they shared one number.
|
||||
expect(project).toBeTruthy();
|
||||
expect(project?.project_number).toBeTruthy();
|
||||
expect(order?.order_number).toBeTruthy();
|
||||
expect(project?.project_number).not.toBe(order?.order_number);
|
||||
expect(project?.order_id).toBe(orderId);
|
||||
});
|
||||
|
||||
it("rejects a DRAFT offer (a numberless 'ordered' offer must never exist)", async () => {
|
||||
const draft = await prisma.quotations.create({
|
||||
data: { status: "draft", currency: "CZK", language: "cs" },
|
||||
});
|
||||
createdQuotationIds.push(draft.id);
|
||||
|
||||
const res = await createOrderFromQuotation({ quotationId: draft.id });
|
||||
expect("error" in res).toBe(true);
|
||||
if ("error" in res) {
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.error).toContain('ve stavu "draft"');
|
||||
}
|
||||
// The offer is untouched — still a numberless draft.
|
||||
const row = await prisma.quotations.findUnique({ where: { id: draft.id } });
|
||||
expect(row!.status).toBe("draft");
|
||||
expect(row!.quotation_number).toBeNull();
|
||||
expect(row!.order_id).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects an INVALIDATED offer (terminal status — no ordered transition)", async () => {
|
||||
const invalidated = await prisma.quotations.create({
|
||||
data: {
|
||||
quotation_number: `Q-INVAL-${Date.now()}`,
|
||||
status: "invalidated",
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
},
|
||||
});
|
||||
createdQuotationIds.push(invalidated.id);
|
||||
|
||||
const res = await createOrderFromQuotation({
|
||||
quotationId: invalidated.id,
|
||||
});
|
||||
expect("error" in res).toBe(true);
|
||||
if ("error" in res) {
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.error).toContain('ve stavu "invalidated"');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteOrder reverts the source offer (stuck-ordered regression)", () => {
|
||||
it("returns the linked quotation to active with order_id cleared", async () => {
|
||||
const quotation = await prisma.quotations.create({
|
||||
data: {
|
||||
quotation_number: `Q-REVERT-${Date.now()}`,
|
||||
status: "active",
|
||||
currency: "CZK",
|
||||
language: "cs",
|
||||
},
|
||||
});
|
||||
createdQuotationIds.push(quotation.id);
|
||||
|
||||
const res = await createOrderFromQuotation({ quotationId: quotation.id });
|
||||
if (!("data" in res) || !res.data) failResult(res);
|
||||
const project = await prisma.projects.findFirst({
|
||||
where: { order_id: res.data.order_id },
|
||||
});
|
||||
if (project) createdProjectIds.push(project.id);
|
||||
|
||||
const afterCreate = await prisma.quotations.findUnique({
|
||||
where: { id: quotation.id },
|
||||
});
|
||||
expect(afterCreate!.status).toBe("ordered");
|
||||
expect(afterCreate!.order_id).toBe(res.data.order_id);
|
||||
|
||||
const del = await deleteOrder(res.data.order_id);
|
||||
if ("error" in del) failResult(del);
|
||||
|
||||
// The offer must be orderable again — `ordered` with no order_id is a
|
||||
// dead end (the transition table only allows ordered -> invalidated).
|
||||
const afterDelete = await prisma.quotations.findUnique({
|
||||
where: { id: quotation.id },
|
||||
});
|
||||
expect(afterDelete!.order_id).toBeNull();
|
||||
expect(afterDelete!.status).toBe("active");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteOrder releases the project number (release regression)", () => {
|
||||
it("frees the auto-created project's number back to the project sequence", async () => {
|
||||
// The project sequence is reset in afterEach, so the preview before the
|
||||
// create is the number createOrder will consume for the project.
|
||||
const previewBefore = await previewProjectNumber();
|
||||
|
||||
const res = await createOrder({
|
||||
...baseOrder,
|
||||
scope_title: "Smazatelná zakázka",
|
||||
create_project: true,
|
||||
});
|
||||
if (!("id" in res)) failResult(res);
|
||||
const orderId = res.id!;
|
||||
expect(res.project_id).toBeTruthy();
|
||||
const project = await prisma.projects.findUnique({
|
||||
where: { id: res.project_id! },
|
||||
});
|
||||
expect(project?.project_number).toBe(previewBefore);
|
||||
|
||||
// After the order delete, the project row is gone AND its number must have
|
||||
// been released (decremented) so the preview returns the freed number — not
|
||||
// a permanent gap. This is the fix #1 regression guard.
|
||||
const del = await deleteOrder(orderId);
|
||||
if ("error" in del) failResult(del);
|
||||
|
||||
const gone = await prisma.projects.findUnique({
|
||||
where: { id: res.project_id! },
|
||||
});
|
||||
expect(gone).toBeNull();
|
||||
|
||||
const previewAfter = await previewProjectNumber();
|
||||
expect(previewAfter).toBe(previewBefore);
|
||||
});
|
||||
});
|
||||
|
||||
describe("separate order vs project sequences (coherence)", () => {
|
||||
it("order → standalone project → order produce three distinct numbers (from separate sequences)", async () => {
|
||||
const o1 = await createOrder({ ...baseOrder, create_project: true });
|
||||
if (!("id" in o1)) failResult(o1);
|
||||
createdOrderIds.push(o1.id!);
|
||||
if (o1.project_id) createdProjectIds.push(o1.project_id);
|
||||
|
||||
const p = await createProject({ name: "Mezi-projekt", status: "aktivni" });
|
||||
if (!("project_number" in p)) failResult(p);
|
||||
createdProjectIds.push(p.id);
|
||||
|
||||
const o2 = await createOrder({ ...baseOrder, create_project: false });
|
||||
if (!("id" in o2)) failResult(o2);
|
||||
createdOrderIds.push(o2.id!);
|
||||
|
||||
// All three numbers must be present (non-null) AND distinct. Orders draw
|
||||
// from the `shared` sequence (code 71); projects from the dedicated
|
||||
// `project` sequence (code 73), so they never collide.
|
||||
expect(o1.order_number).toBeTruthy();
|
||||
expect(p.project_number).toBeTruthy();
|
||||
expect(o2.order_number).toBeTruthy();
|
||||
expect(
|
||||
new Set([o1.order_number, p.project_number, o2.order_number]).size,
|
||||
).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createProject (manual, standalone)", () => {
|
||||
it("assigns a shared number and is not linked to an order", async () => {
|
||||
it("assigns a project number and is not linked to an order", async () => {
|
||||
const result = await createProject({
|
||||
name: "Test projekt",
|
||||
status: "aktivni",
|
||||
});
|
||||
expect("project_number" in result).toBe(true);
|
||||
if (!("project_number" in result)) return;
|
||||
if (!("project_number" in result)) failResult(result);
|
||||
createdProjectIds.push(result.id);
|
||||
expect(typeof result.project_number).toBe("string");
|
||||
expect(result.project_number!.length).toBeGreaterThan(0);
|
||||
@@ -112,9 +323,8 @@ describe("createOrder with price line item + attachment", () => {
|
||||
},
|
||||
],
|
||||
});
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
if (!("id" in res)) failResult(res);
|
||||
createdOrderIds.push(res.id!);
|
||||
const items = await prisma.order_items.findMany({
|
||||
where: { order_id: res.id },
|
||||
});
|
||||
@@ -122,21 +332,25 @@ describe("createOrder with price line item + attachment", () => {
|
||||
expect(Number(items[0].unit_price)).toBe(12345);
|
||||
});
|
||||
|
||||
it("stores an uploaded PO attachment", async () => {
|
||||
const buf = Buffer.from("%PDF-1.4 fake");
|
||||
it("stores an uploaded PO attachment with the exact bytes", async () => {
|
||||
const buf = Buffer.from("%PDF-1.4 fake-attachment-bytes-éí");
|
||||
const res = await createOrder(
|
||||
{ ...baseOrder, create_project: false },
|
||||
buf,
|
||||
"po.pdf",
|
||||
);
|
||||
expect("id" in res).toBe(true);
|
||||
if (!("id" in res)) return;
|
||||
createdOrderIds.push(res.id);
|
||||
if (!("id" in res)) failResult(res);
|
||||
createdOrderIds.push(res.id!);
|
||||
const order = await prisma.orders.findUnique({
|
||||
where: { id: res.id },
|
||||
select: { attachment_name: true, attachment_data: true },
|
||||
});
|
||||
expect(order?.attachment_name).toBe("po.pdf");
|
||||
// Verify the stored content/size, not just truthiness: round-trip the
|
||||
// bytes and compare length + value against what we uploaded.
|
||||
expect(order?.attachment_data).toBeTruthy();
|
||||
const stored = Buffer.from(order!.attachment_data!);
|
||||
expect(stored.length).toBe(buf.length);
|
||||
expect(stored.equals(buf)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user