12 Commits

Author SHA1 Message Date
BOHA
96ba5d034f 1.4.0 2026-03-28 09:03:06 +01:00
BOHA
2402b7cbc8 fix: "Moje žádosti" page shows only current user's requests
Admins were seeing all requests on their own requests page.
Added mine=1 param to force user_id filter regardless of role.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-28 09:03:05 +01:00
BOHA
79b2fa5570 1.3.9 2026-03-28 08:56:14 +01:00
BOHA
35fa172d36 fix: trips admin shows only users with trips.record permission
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-28 08:56:14 +01:00
BOHA
000a77ccf4 1.3.8 2026-03-27 21:27:16 +01:00
BOHA
ecd9f6a181 chore: fix npm audit vulnerabilities (brace-expansion, fastify, nodemailer, picomatch)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 21:27:14 +01:00
BOHA
68e6d80903 1.3.7 2026-03-27 17:32:22 +01:00
BOHA
af1b41994c fix: attendance shows only users with attendance.record permission
- Filter attendance admin/balances/workfund to users with attendance.record
  permission or admin role
- New attendance_users API action for user dropdown
- Fix missing prisma import in attendance route
- Fix user edit: empty password no longer blocks save (preprocess to undefined)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 17:32:22 +01:00
BOHA
9779112066 1.3.6 2026-03-27 13:50:00 +01:00
BOHA
e8d6dc1567 fix: dashboard offers card showing wrong counts
Queried status "converted"/"expired" but actual DB values are
"ordered"/"invalidated". Updated label "Prošlé" → "Zneplatněné".

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 13:50:00 +01:00
BOHA
f9dd49591e 1.3.5 2026-03-27 13:44:54 +01:00
BOHA
8cdf057ab3 feat: CNB exchange rates, multi-currency KPI stats, invoice PDF VAT in CZK
- ČNB exchange rate service with date-specific rates and caching
- Invoice/received invoice stats convert foreign currencies to CZK
- Dashboard revenue converts all currencies to CZK
- Invoice PDF: VAT recap table always in CZK with CNB rate footer
- Inline styles replaced with utility classes (step 4 cleanup)
- Spinner animation exempt from prefers-reduced-motion

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 13:44:53 +01:00
24 changed files with 300 additions and 163 deletions

28
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "app-ts",
"version": "1.3.4",
"version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "app-ts",
"version": "1.3.4",
"version": "1.4.0",
"license": "ISC",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
@@ -2089,9 +2089,9 @@
}
},
"node_modules/brace-expansion": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz",
"integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==",
"version": "5.0.5",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
"integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
@@ -3086,9 +3086,9 @@
"license": "BSD-3-Clause"
},
"node_modules/fastify": {
"version": "5.8.2",
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.2.tgz",
"integrity": "sha512-lZmt3navvZG915IE+f7/TIVamxIwmBd+OMB+O9WBzcpIwOo6F0LTh0sluoMFk5VkrKTvvrwIaoJPkir4Z+jtAg==",
"version": "5.8.4",
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.4.tgz",
"integrity": "sha512-sa42J1xylbBAYUWALSBoyXKPDUvM3OoNOibIefA+Oha57FryXKKCZarA1iDntOCWp3O35voZLuDg2mdODXtPzQ==",
"funding": [
{
"type": "github",
@@ -4282,9 +4282,9 @@
"license": "MIT"
},
"node_modules/nodemailer": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.2.tgz",
"integrity": "sha512-zbj002pZAIkWQFxyAaqoxvn+zoIwRnS40hgjqTXudKOOJkiFFgBeNqjgD3/YCR12sZnrghWYBY+yP1ZucdDRpw==",
"version": "8.0.4",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.4.tgz",
"integrity": "sha512-k+jf6N8PfQJ0Fe8ZhJlgqU5qJU44Lpvp2yvidH3vp1lPnVQMgi4yEEMPXg5eJS1gFIJTVq1NHBk7Ia9ARdSBdQ==",
"license": "MIT-0",
"engines": {
"node": ">=6.0.0"
@@ -4540,9 +4540,9 @@
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"engines": {

View File

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

View File

@@ -412,4 +412,9 @@ img {
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
.admin-spinner {
animation-duration: 0.8s !important;
animation-iteration-count: infinite !important;
}
}

View File

@@ -561,7 +561,9 @@ export default function useAttendanceAdmin({ alert }: AlertContext) {
useEffect(() => {
const loadUsers = async () => {
try {
const response = await apiFetch(`${API_BASE}/users?limit=1000`);
const response = await apiFetch(
`${API_BASE}/attendance?action=attendance_users`,
);
const result = await response.json();
if (result.success) {
const apiUsers: ApiUser[] = result.data;

View File

@@ -576,10 +576,7 @@ export default function Attendance() {
<div className="attendance-project-header">
<span className="attendance-shift-label">Projekt</span>
{activeProjectId ? (
<span
className="admin-badge admin-badge-wrap"
style={{ fontSize: "0.8125rem" }}
>
<span className="admin-badge admin-badge-wrap text-sm">
{projects.find(
(p) => String(p.id) === String(activeProjectId),
)
@@ -587,12 +584,7 @@ export default function Attendance() {
: `Projekt #${activeProjectId}`}
</span>
) : (
<span
className="text-muted"
style={{ fontSize: "0.8125rem" }}
>
Žádný
</span>
<span className="text-muted text-sm">Žádný</span>
)}
</div>
<select
@@ -601,8 +593,7 @@ export default function Attendance() {
handleSwitchProject(e.target.value || null)
}
disabled={switchingProject}
className="admin-form-select"
style={{ fontSize: "0.875rem" }}
className="admin-form-select text-md"
>
<option value=""> Bez projektu </option>
{projects.map((p) => (
@@ -654,8 +645,7 @@ export default function Attendance() {
<button
onClick={handleBreak}
disabled={submitting}
className="admin-btn admin-btn-secondary"
style={{ width: "100%" }}
className="admin-btn admin-btn-secondary w-full"
>
Pauza (30 min)
</button>
@@ -663,15 +653,13 @@ export default function Attendance() {
<button
onClick={() => handlePunch("departure")}
disabled={submitting}
className="admin-btn admin-btn-primary"
style={{ width: "100%" }}
className="admin-btn admin-btn-primary w-full"
>
{submitting ? "Zpracovávám..." : "Odchod"}
</button>
<button
onClick={() => setShowLeaveModal(true)}
className="admin-btn admin-btn-secondary"
style={{ width: "100%" }}
className="admin-btn admin-btn-secondary w-full"
>
Žádost o nepřítomnost
</button>
@@ -703,16 +691,14 @@ export default function Attendance() {
<button
onClick={() => handlePunch("arrival")}
disabled={submitting}
className="admin-btn admin-btn-primary"
style={{ width: "100%" }}
className="admin-btn admin-btn-primary w-full"
>
{submitting ? "Zpracovávám..." : "Příchod"}
</button>
<button
onClick={() => setShowLeaveModal(true)}
className="admin-btn admin-btn-secondary"
style={{ width: "100%" }}
className="admin-btn admin-btn-secondary w-full"
>
Žádost o nepřítomnost
</button>
@@ -877,11 +863,10 @@ export default function Attendance() {
</div>
<div style={{ marginTop: "0.75rem" }}>
<div
className="text-secondary"
className="text-secondary text-sm"
style={{
display: "flex",
justifyContent: "space-between",
fontSize: "0.8125rem",
marginBottom: "0.5rem",
}}
>
@@ -905,8 +890,8 @@ export default function Attendance() {
</div>
{data.monthly_fund.leave_hours > 0 && (
<div
className="text-muted"
style={{ fontSize: "0.75rem", marginTop: "0.375rem" }}
className="text-muted text-xs"
style={{ marginTop: "0.375rem" }}
>
{"Pokryto: "}
{data.monthly_fund.covered}h (práce{" "}

View File

@@ -493,7 +493,7 @@ export default function Dashboard() {
</span>
</div>
<div className="dash-stat-row">
<span>Prošlé</span>
<span>Zneplatněné</span>
<span className="admin-badge admin-badge-warning">
{dashData.offers.expired_count}
</span>

View File

@@ -270,7 +270,7 @@ function SortableInvoiceRow({
</select>
</td>
) : null}
<td style={{ textAlign: "right", fontWeight: 600, whiteSpace: "nowrap" }}>
<td className="text-right fw-600 whitespace-nowrap">
{formatCurrency(lineTotal, currency)}
</td>
<td>
@@ -354,12 +354,7 @@ function SortableInvoiceEditRow({
</svg>
</button>
</td>
<td
className="text-tertiary"
style={{ textAlign: "center", fontWeight: 500 }}
>
{index + 1}
</td>
<td className="text-tertiary text-center fw-500">{index + 1}</td>
<td>
<input
type="text"
@@ -1371,10 +1366,7 @@ export default function InvoiceDetail() {
))}
</select>
{form.due_date && (
<span
className="text-tertiary"
style={{ fontSize: "0.75rem", marginTop: "0.25rem" }}
>
<span className="text-tertiary text-xs mt-1">
Splatnost:{" "}
{new Date(form.due_date).toLocaleDateString("cs-CZ")}
</span>
@@ -1448,10 +1440,7 @@ export default function InvoiceDetail() {
</FormField>
<FormField label="DPH">
<div className="flex-row-gap">
<label
className="admin-form-checkbox"
style={{ whiteSpace: "nowrap" }}
>
<label className="admin-form-checkbox whitespace-nowrap">
<input
type="checkbox"
checked={!!form.apply_vat}
@@ -1809,7 +1798,7 @@ export default function InvoiceDetail() {
{invoice.paid_date && (
<div className="admin-form-row mt-2">
<FormField label="Datum úhrady">
<div style={{ color: "var(--success)", fontWeight: 500 }}>
<div className="fw-500" style={{ color: "var(--success)" }}>
{formatDate(invoice.paid_date)}
</div>
</FormField>
@@ -1954,16 +1943,13 @@ export default function InvoiceDetail() {
: 0;
return (
<tr key={item.id || index}>
<td
className="text-tertiary"
style={{ textAlign: "center", fontWeight: 500 }}
>
<td className="text-tertiary text-center fw-500">
{index + 1}
</td>
<td className="fw-500">
{item.description || "\u2014"}
</td>
<td style={{ textAlign: "center" }}>
<td className="text-center">
{item.quantity}{" "}
{item.unit && (
<span className="text-tertiary">
@@ -1971,7 +1957,7 @@ export default function InvoiceDetail() {
</span>
)}
</td>
<td style={{ textAlign: "center" }}>
<td className="text-center">
{item.unit || "\u2014"}
</td>
<td className="admin-mono text-right">
@@ -1980,16 +1966,13 @@ export default function InvoiceDetail() {
invoice.currency,
)}
</td>
<td style={{ textAlign: "center" }}>
<td className="text-center">
{Number(invoice.apply_vat)
? Number(item.vat_rate)
: 0}
%
</td>
<td
className="admin-mono"
style={{ textAlign: "right", fontWeight: 600 }}
>
<td className="admin-mono text-right fw-600">
{formatCurrency(
lineSubtotal + lineVat,
invoice.currency,

View File

@@ -56,7 +56,7 @@ function formatCzkWithDetail(
if (!Array.isArray(amounts) || amounts.length === 0)
return { value: "0 Kč", detail: null };
const hasForeign = amounts.some((a) => a.currency !== "CZK");
if (hasForeign && totalCzk !== null && totalCzk !== undefined) {
if (hasForeign && totalCzk != null) {
return {
value: formatCurrency(totalCzk, "CZK"),
detail: formatMultiCurrency(amounts),

View File

@@ -61,7 +61,7 @@ export default function LeaveRequests() {
const fetchRequests = useCallback(async () => {
try {
const response = await apiFetch(`${API_BASE}/leave-requests`);
const response = await apiFetch(`${API_BASE}/leave-requests?mine=1`);
if (response.status === 401) return;
const result = await response.json();
if (result.success) {

View File

@@ -180,9 +180,7 @@ function SortableItemRow({
</button>
</td>
)}
<td style={{ textAlign: "center", color: "var(--text-tertiary)" }}>
{index + 1}
</td>
<td className="text-center text-tertiary">{index + 1}</td>
<td style={{ verticalAlign: "top" }}>
<div
style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}
@@ -191,10 +189,9 @@ function SortableItemRow({
type="text"
value={item.description}
onChange={(e) => onUpdate("description", e.target.value)}
className="admin-form-input"
className="admin-form-input fw-500"
placeholder="Název položky"
readOnly={readOnly}
style={{ fontWeight: 500 }}
/>
<input
type="text"
@@ -240,7 +237,7 @@ function SortableItemRow({
readOnly={readOnly}
/>
</td>
<td style={{ textAlign: "center" }}>
<td className="text-center">
<input
type="checkbox"
checked={item.is_included_in_total}
@@ -248,10 +245,7 @@ function SortableItemRow({
disabled={readOnly}
/>
</td>
<td
className="admin-mono"
style={{ textAlign: "right", fontWeight: 600 }}
>
<td className="admin-mono text-right fw-600">
{formatCurrency(lineTotal, currency)}
</td>
{!readOnly && (
@@ -874,11 +868,10 @@ export default function OfferDetail() {
{isEdit ? `Nabídka ${form.quotation_number}` : "Nová nabídka"}
{isInvalidated && (
<span
className="admin-badge admin-badge-danger"
className="admin-badge admin-badge-danger text-xs"
style={{
marginLeft: "0.75rem",
verticalAlign: "middle",
fontSize: "0.75rem",
}}
>
Zneplatněna
@@ -1208,10 +1201,7 @@ export default function OfferDetail() {
</option>
))}
</select>
<label
className="admin-form-checkbox"
style={{ whiteSpace: "nowrap" }}
>
<label className="admin-form-checkbox whitespace-nowrap">
<input
type="checkbox"
checked={form.apply_vat}
@@ -1672,7 +1662,7 @@ export default function OfferDetail() {
<FormField label="Příloha (PDF)">
{orderAttachment ? (
<div className="flex-row gap-2">
<span style={{ fontSize: "0.875rem" }}>
<span className="text-md">
{orderAttachment.name}{" "}
<span className="text-tertiary">
({(orderAttachment.size / 1024).toFixed(0)} KB)

View File

@@ -814,8 +814,8 @@ export default function Offers() {
<tr>
<td
colSpan={8}
className="text-muted"
style={{ textAlign: "center", padding: "1.5rem" }}
className="text-muted text-center"
style={{ padding: "1.5rem" }}
>
Žádné nabídky odpovídající hledání.
</td>
@@ -879,8 +879,8 @@ export default function Offers() {
<div className="admin-modal-header">
<h2 className="admin-modal-title">Vytvořit objednávku</h2>
<p
className="text-secondary"
style={{ marginTop: "0.25rem", fontSize: "0.875rem" }}
className="text-secondary text-md"
style={{ marginTop: "0.25rem" }}
>
Nabídka:{" "}
<strong>{orderModal.quotation?.quotation_number}</strong>
@@ -917,7 +917,7 @@ export default function Offers() {
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
</svg>
<span style={{ fontSize: "0.875rem" }}>
<span className="text-md">
{orderAttachment.name}{" "}
<span className="text-tertiary">
({(orderAttachment.size / 1024).toFixed(0)} KB)
@@ -944,11 +944,9 @@ export default function Offers() {
</div>
) : (
<label
className="admin-btn admin-btn-secondary admin-btn-sm"
className="admin-btn admin-btn-secondary admin-btn-sm inline-flex"
style={{
cursor: "pointer",
display: "inline-flex",
alignItems: "center",
gap: "0.4rem",
}}
>

View File

@@ -115,7 +115,7 @@ function formatCzkWithDetail(
return { value: "0 Kč", detail: null };
}
const hasForeign = amounts.some((a) => a.currency !== "CZK");
if (hasForeign && totalCzk !== null && totalCzk !== undefined) {
if (hasForeign && totalCzk != null) {
return {
value: formatCurrency(totalCzk, "CZK"),
detail: formatMultiCurrency(amounts),
@@ -709,9 +709,9 @@ export default function ReceivedInvoices({
<p>Žádné přijaté faktury v tomto měsíci.</p>
{hasPermission("invoices.create") && (
<p
className="text-md"
style={{
color: "var(--text-tertiary)",
fontSize: "0.875rem",
}}
>
Nahrajte faktury tlačítkem výše.
@@ -780,7 +780,8 @@ export default function ReceivedInvoices({
/>
</th>
<th
style={{ textAlign: "right", cursor: "pointer" }}
className="text-right"
style={{ cursor: "pointer" }}
onClick={() => handleSort("amount")}
>
Částka{" "}
@@ -959,9 +960,9 @@ export default function ReceivedInvoices({
Vybrat soubory
</button>
<span
className="text-sm"
style={{
marginLeft: "0.75rem",
fontSize: "0.8125rem",
color: "var(--text-tertiary)",
}}
>
@@ -1106,8 +1107,8 @@ export default function ReceivedInvoices({
</div>
{uploadMeta[idx]?.amount && (
<div
className="text-xs"
style={{
fontSize: "0.75rem",
color: "var(--text-tertiary)",
marginTop: "-0.25rem",
marginBottom: "0.5rem",
@@ -1320,8 +1321,8 @@ export default function ReceivedInvoices({
</div>
{editInvoice.amount && (
<div
className="text-xs"
style={{
fontSize: "0.75rem",
color: "var(--text-tertiary)",
marginBottom: "0.75rem",
}}

View File

@@ -639,17 +639,16 @@ export default function Settings() {
</div>
<div>
<div
className="fw-500 text-md"
style={{
fontWeight: 500,
color: "var(--text-primary)",
fontSize: "0.875rem",
}}
>
Povinné dvoufaktorové ověření (2FA)
</div>
<div
className="text-xs"
style={{
fontSize: "0.75rem",
color: "var(--text-secondary)",
}}
>
@@ -781,16 +780,16 @@ export default function Settings() {
<tr key={role.id}>
<td>
<div
className="fw-500"
style={{
fontWeight: 500,
color: "var(--text-primary)",
}}
>
{role.display_name}
</div>
<div
className="text-xs"
style={{
fontSize: "0.75rem",
color: "var(--text-tertiary)",
}}
>
@@ -1077,9 +1076,9 @@ export default function Settings() {
/>
</FormField>
<small
className="text-xs"
style={{
color: "var(--text-tertiary)",
fontSize: "0.75rem",
}}
>
Změna se projeví po restartu serveru
@@ -1179,10 +1178,9 @@ export default function Settings() {
/>
)}
<div
className="fw-600 text-md"
style={{
fontWeight: 600,
marginBottom: "0.5rem",
fontSize: "0.875rem",
}}
>
{cfg.label}
@@ -1355,8 +1353,8 @@ export default function Settings() {
<div className="admin-card-body">
{systemInfo ? (
<table
className="w-full"
style={{
width: "100%",
fontSize: "0.85rem",
borderCollapse: "collapse",
}}
@@ -1374,16 +1372,16 @@ export default function Settings() {
).map(([label, val]) => (
<tr key={label}>
<td
className="whitespace-nowrap"
style={{
padding: "6px 12px 6px 0",
color: "var(--text-secondary)",
whiteSpace: "nowrap",
width: 160,
}}
>
{label}
</td>
<td style={{ padding: "6px 0", fontWeight: 500 }}>
<td className="fw-500" style={{ padding: "6px 0" }}>
{val}
</td>
</tr>
@@ -1516,9 +1514,9 @@ export default function Settings() {
</span>
{info?.configured && (
<span
className="text-xs"
style={{
marginLeft: 8,
fontSize: "0.75rem",
color: "var(--text-tertiary)",
}}
>
@@ -1548,8 +1546,7 @@ export default function Settings() {
<button
onClick={handleSaveSystemSettings}
disabled={sysSettingsSaving}
className="admin-btn admin-btn-primary"
style={{ width: "100%" }}
className="admin-btn admin-btn-primary w-full"
>
{sysSettingsSaving ? (
<>
@@ -1637,9 +1634,9 @@ export default function Settings() {
/>
{!editingRole && (
<small
className="text-xs"
style={{
color: "var(--text-tertiary)",
fontSize: "0.75rem",
}}
>
Pouze malá písmena, čísla a pomlčky. Nelze později

View File

@@ -127,7 +127,7 @@ export default function TripsAdmin() {
try {
const [vRes, uRes, csRes] = await Promise.all([
apiFetch(`${API_BASE}/vehicles`),
apiFetch(`${API_BASE}/users?limit=1000`),
apiFetch(`${API_BASE}/trips/users`),
apiFetch(`${API_BASE}/company-settings`),
]);
const vJson = await vRes.json();
@@ -136,14 +136,7 @@ export default function TripsAdmin() {
if (vJson.success) setVehicles(vJson.data);
if (csJson.success) setCompanyName(csJson.data.company_name || "");
if (uJson.success) {
setUsers(
uJson.data.map(
(u: { id: number; first_name: string; last_name: string }) => ({
id: u.id,
name: `${u.first_name} ${u.last_name}`,
}),
),
);
setUsers(uJson.data);
}
} catch {
// silently fail, filters will just be empty

View File

@@ -1,4 +1,5 @@
import { FastifyInstance } from "fastify";
import prisma from "../../config/database";
import { requireAuth, requirePermission } from "../../middleware/auth";
import { logAudit } from "../../services/audit";
import { success, error, parseId } from "../../utils/response";
@@ -132,6 +133,38 @@ export default async function attendanceRoutes(
return reply.send({ success: true, data });
}
// --- action=attendance_users: users with attendance.record permission ---
if (action === "attendance_users") {
const users = await prisma.users.findMany({
where: {
is_active: true,
roles: {
is: {
OR: [
{ name: "admin" },
{
role_permissions: {
some: { permissions: { name: "attendance.record" } },
},
},
],
},
},
},
select: { id: true, first_name: true, last_name: true, username: true },
orderBy: { last_name: "asc" },
});
return reply.send({
success: true,
data: users.map((u) => ({
id: u.id,
first_name: u.first_name,
last_name: u.last_name,
username: u.username,
})),
});
}
// --- action=projects: active projects for attendance project switching ---
if (action === "projects") {
const data = await attendanceService.getActiveProjects();

View File

@@ -3,6 +3,7 @@ import prisma from "../../config/database";
import { requireAuth } from "../../middleware/auth";
import { success } from "../../utils/response";
import { localTimeStr } from "../../utils/date";
import { toCzk } from "../../services/exchange-rates";
export default async function dashboardRoutes(
fastify: FastifyInstance,
@@ -141,8 +142,8 @@ export default async function dashboardRoutes(
const [openCount, convertedCount, expiredCount, createdThisMonth] =
await Promise.all([
prisma.quotations.count({ where: { status: "active" } }),
prisma.quotations.count({ where: { status: "converted" } }),
prisma.quotations.count({ where: { status: "expired" } }),
prisma.quotations.count({ where: { status: "ordered" } }),
prisma.quotations.count({ where: { status: "invalidated" } }),
prisma.quotations.count({
where: { created_at: { gte: monthStart, lt: monthEnd } },
}),
@@ -206,10 +207,13 @@ export default async function dashboardRoutes(
}),
),
unpaid_count: unpaidCount,
revenue_czk:
revenueByCurrency["CZK"] != null
? Math.round(revenueByCurrency["CZK"] * 100) / 100
: null,
revenue_czk: await (async () => {
let total = 0;
for (const [cur, amount] of Object.entries(revenueByCurrency)) {
total += await toCzk(Math.round(amount * 100) / 100, cur);
}
return Math.round(total * 100) / 100;
})(),
};
result.unpaid_invoices = unpaidCount;
}

View File

@@ -5,6 +5,8 @@ import { requirePermission } from "../../middleware/auth";
import { localDateCzStr } from "../../utils/date";
import { nasFinancialsManager } from "../../services/nas-financials-manager";
import { htmlToPdf } from "../../utils/html-to-pdf";
import { getRate } from "../../services/exchange-rates";
import { localDateStr } from "../../utils/date";
/* ── Helpers ─────────────────────────────────────────────────────── */
@@ -358,9 +360,12 @@ export default async function invoicesPdfRoutes(
// QR generation failed — leave empty
}
// VAT recapitulation (always in CZK)
// VAT recapitulation (always in CZK — Czech tax requirement)
const isForeign = currency.toUpperCase() !== "CZK";
const cnbRate = 1.0; // Skip CNB rate conversion
const issueDateStr = invoice.issue_date
? localDateStr(new Date(invoice.issue_date))
: undefined;
const cnbRate = isForeign ? await getRate(currency, issueDateStr) : 1.0;
const vatRates = [21, 12, 0];
const vatRecap: Array<{
rate: number;
@@ -1007,6 +1012,17 @@ ${indentCSS}
<tbody>
${vatRecapHtml}
</tbody>
${
isForeign
? `<tfoot>
<tr>
<td colspan="4" style="font-size:0.7em; color:#666; padding-top:6px; text-align:left;">
Přepočet kurzem ČNB ke dni ${formatDate(invoice.issue_date)}: 1 ${escapeHtml(currency)} = ${cnbRate.toFixed(3).replace(".", ",")} CZK
</td>
</tr>
</tfoot>`
: ""
}
</table>
</div>

View File

@@ -29,7 +29,7 @@ export default async function leaveRequestsRoutes(
const isAdmin = authData.permissions.includes("attendance.approve");
const where: Record<string, unknown> = {};
if (!isAdmin) where.user_id = authData.userId;
if (!isAdmin || query.mine === "1") where.user_id = authData.userId;
else if (query.user_id) where.user_id = Number(query.user_id);
if (query.status) where.status = String(query.status);

View File

@@ -12,6 +12,7 @@ import {
UpdateReceivedInvoiceSchema,
} from "../../schemas/received-invoices.schema";
import { nasFinancialsManager } from "../../services/nas-financials-manager";
import { toCzk } from "../../services/exchange-rates";
const VALID_STATUSES = ["unpaid", "paid"] as const;
const ALLOWED_SORT_FIELDS = [
@@ -108,12 +109,15 @@ export default async function receivedInvoicesRoutes(
}));
};
const sumCzk = (
const sumCzk = async (
invs: typeof monthInvoices,
field: "amount" | "vat_amount",
) => {
let total = 0;
for (const inv of invs) total += Number(inv[field]) || 0;
for (const inv of invs) {
const amount = Number(inv[field]) || 0;
total += await toCzk(amount, inv.currency);
}
return Math.round(total * 100) / 100;
};
@@ -124,11 +128,11 @@ export default async function receivedInvoicesRoutes(
return success(reply, {
total_month: aggregateByCurrency(monthInvoices, "amount"),
total_month_czk: sumCzk(monthInvoices, "amount"),
total_month_czk: await sumCzk(monthInvoices, "amount"),
vat_month: aggregateByCurrency(monthInvoices, "vat_amount"),
vat_month_czk: sumCzk(monthInvoices, "vat_amount"),
vat_month_czk: await sumCzk(monthInvoices, "vat_amount"),
unpaid: aggregateByCurrency(allUnpaid, "amount"),
unpaid_czk: sumCzk(allUnpaid, "amount"),
unpaid_czk: await sumCzk(allUnpaid, "amount"),
unpaid_count: allUnpaid.length,
month_count: monthInvoices.length,
});

View File

@@ -66,6 +66,45 @@ export default async function tripsRoutes(
});
});
// GET /api/admin/trips/users — users with trips.record permission
fastify.get(
"/users",
{ preHandler: requireAuth },
async (_request, reply) => {
const users = await prisma.users.findMany({
where: {
is_active: true,
roles: {
is: {
OR: [
{ name: "admin" },
{
role_permissions: {
some: { permissions: { name: "trips.record" } },
},
},
],
},
},
},
select: {
id: true,
first_name: true,
last_name: true,
username: true,
},
orderBy: { last_name: "asc" },
});
return success(
reply,
users.map((u) => ({
id: u.id,
name: `${u.first_name} ${u.last_name}`.trim() || u.username,
})),
);
},
);
// GET /api/admin/trips/print — print data for trip report
fastify.get(
"/print",

View File

@@ -16,7 +16,10 @@ export const CreateUserSchema = z.object({
export const UpdateUserSchema = z.object({
username: z.string().optional(),
email: z.string().email("Neplatný formát e-mailu").optional(),
password: z.string().min(8, "Heslo musí mít alespoň 8 znaků").optional(),
password: z.preprocess(
(v) => (v === "" ? undefined : v),
z.string().min(8, "Heslo musí mít alespoň 8 znaků").optional(),
),
first_name: z.string().optional(),
last_name: z.string().optional(),
role_id: z.union([z.number(), z.string(), z.null()]).optional(),

View File

@@ -4,6 +4,29 @@ import { getBusinessDaysInMonth } from "../utils/czech-holidays";
import { localDateStr } from "../utils/date";
import { getSystemSettings } from "./system-settings";
/** Get active users whose role has attendance.record permission (or admin role) */
async function getAttendanceUsers() {
return prisma.users.findMany({
where: {
is_active: true,
roles: {
is: {
OR: [
{ name: "admin" },
{
role_permissions: {
some: { permissions: { name: "attendance.record" } },
},
},
],
},
},
},
select: { id: true, first_name: true, last_name: true },
orderBy: { last_name: "asc" },
});
}
type AttendanceWithRelations = Prisma.attendanceGetPayload<{
include: {
users: { select: { id: true; first_name: true; last_name: true } };
@@ -421,11 +444,7 @@ export async function switchProject(userId: number, projectId: number | null) {
}
export async function getBalances(year: number) {
const users = await prisma.users.findMany({
where: { is_active: true },
select: { id: true, first_name: true, last_name: true },
orderBy: { last_name: "asc" },
});
const users = await getAttendanceUsers();
const balances: Record<
string,
@@ -463,11 +482,7 @@ export async function getBalances(year: number) {
}
export async function getWorkfund(year: number) {
const users = await prisma.users.findMany({
where: { is_active: true },
select: { id: true, first_name: true, last_name: true },
orderBy: { last_name: "asc" },
});
const users = await getAttendanceUsers();
const now = new Date();
const currentYear = now.getFullYear();
@@ -734,11 +749,7 @@ export async function getPrintData(
const monthStart = new Date(yr, mo - 1, 1);
const monthEnd = new Date(yr, mo, 0, 23, 59, 59);
const users = await prisma.users.findMany({
where: { is_active: true },
select: { id: true, first_name: true, last_name: true },
orderBy: { last_name: "asc" },
});
const users = await getAttendanceUsers();
const where: Record<string, unknown> = {
shift_date: { gte: monthStart, lte: monthEnd },

View File

@@ -0,0 +1,65 @@
/**
* Czech National Bank (ČNB) exchange rate service.
* Fetches daily rates and caches them.
* API: https://api.cnb.cz/cnbapi/exrates/daily
*/
interface CnbRate {
currencyCode: string;
rate: number;
amount: number;
}
const rateCache: Record<string, Record<string, number>> = {};
async function fetchRatesForDate(
date?: string,
): Promise<Record<string, number>> {
const key = date || "today";
if (rateCache[key]) return rateCache[key];
try {
let url = "https://api.cnb.cz/cnbapi/exrates/daily?lang=EN";
if (date) url += `&date=${date}`;
const response = await fetch(url);
if (!response.ok) throw new Error(`CNB API: ${response.status}`);
const data = (await response.json()) as { rates: CnbRate[] };
const rates: Record<string, number> = { CZK: 1 };
for (const r of data.rates) {
rates[r.currencyCode] = r.rate / r.amount;
}
rateCache[key] = rates;
return rates;
} catch (err) {
console.error("Failed to fetch CNB exchange rates:", err);
if (rateCache["today"]) return rateCache["today"];
return { CZK: 1, EUR: 25, USD: 22, GBP: 28 };
}
}
/** Convert an amount from a given currency to CZK using CNB rates */
export async function toCzk(
amount: number,
currency: string,
date?: string,
): Promise<number> {
if (currency === "CZK") return amount;
const rates = await fetchRatesForDate(date);
const rate = rates[currency];
if (!rate) return amount;
return Math.round(amount * rate * 100) / 100;
}
/** Get CNB rate for a currency (CZK per 1 unit), optionally for a specific date */
export async function getRate(
currency: string,
date?: string,
): Promise<number> {
if (currency === "CZK") return 1;
const rates = await fetchRatesForDate(date);
return rates[currency] || 1;
}

View File

@@ -1,4 +1,5 @@
import prisma from "../config/database";
import { toCzk } from "./exchange-rates";
// Status transition rules matching PHP
const VALID_TRANSITIONS: Record<string, string[]> = {
@@ -186,10 +187,11 @@ export async function getInvoiceStats(queryMonth?: number, queryYear?: number) {
}));
};
const sumCzk = (invoices: typeof allInvoices) => {
const sumCzk = async (invoices: typeof allInvoices) => {
let total = 0;
for (const inv of invoices) {
total += invoiceTotalWithVat(inv); // Simplified: no real FX conversion
const amount = invoiceTotalWithVat(inv);
total += await toCzk(amount, inv.currency || "CZK");
}
return Math.round(total * 100) / 100;
};
@@ -224,18 +226,24 @@ export async function getInvoiceStats(queryMonth?: number, queryYear?: number) {
let vatCzk = 0;
for (const [, v] of Object.entries(vatMap)) vatCzk += v;
// VAT also needs conversion
let vatCzkConverted = 0;
for (const [cur, amount] of Object.entries(vatMap)) {
vatCzkConverted += await toCzk(amount, cur);
}
return {
paid_month: aggregateByCurrency(paidInvoices),
paid_month_czk: sumCzk(paidInvoices),
paid_month_czk: await sumCzk(paidInvoices),
paid_month_count: paidInvoices.length,
awaiting: aggregateByCurrency(awaitingInvoices),
awaiting_czk: sumCzk(awaitingInvoices),
awaiting_czk: await sumCzk(awaitingInvoices),
awaiting_count: awaitingInvoices.length,
overdue: aggregateByCurrency(overdueInvoices),
overdue_czk: sumCzk(overdueInvoices),
overdue_czk: await sumCzk(overdueInvoices),
overdue_count: overdueInvoices.length,
vat_month: vatAmounts,
vat_month_czk: Math.round(vatCzk * 100) / 100,
vat_month_czk: Math.round(vatCzkConverted * 100) / 100,
month,
year,
};