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>
This commit is contained in:
BOHA
2026-03-27 13:44:53 +01:00
parent a3ef37d0d2
commit 8cdf057ab3
13 changed files with 173 additions and 117 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,6 +3,7 @@ import prisma from "../../config/database";
import { requireAuth } from "../../middleware/auth"; import { requireAuth } from "../../middleware/auth";
import { success } from "../../utils/response"; import { success } from "../../utils/response";
import { localTimeStr } from "../../utils/date"; import { localTimeStr } from "../../utils/date";
import { toCzk } from "../../services/exchange-rates";
export default async function dashboardRoutes( export default async function dashboardRoutes(
fastify: FastifyInstance, fastify: FastifyInstance,
@@ -206,10 +207,13 @@ export default async function dashboardRoutes(
}), }),
), ),
unpaid_count: unpaidCount, unpaid_count: unpaidCount,
revenue_czk: revenue_czk: await (async () => {
revenueByCurrency["CZK"] != null let total = 0;
? Math.round(revenueByCurrency["CZK"] * 100) / 100 for (const [cur, amount] of Object.entries(revenueByCurrency)) {
: null, total += await toCzk(Math.round(amount * 100) / 100, cur);
}
return Math.round(total * 100) / 100;
})(),
}; };
result.unpaid_invoices = unpaidCount; result.unpaid_invoices = unpaidCount;
} }

View File

@@ -5,6 +5,8 @@ import { requirePermission } from "../../middleware/auth";
import { localDateCzStr } from "../../utils/date"; import { localDateCzStr } from "../../utils/date";
import { nasFinancialsManager } from "../../services/nas-financials-manager"; import { nasFinancialsManager } from "../../services/nas-financials-manager";
import { htmlToPdf } from "../../utils/html-to-pdf"; import { htmlToPdf } from "../../utils/html-to-pdf";
import { getRate } from "../../services/exchange-rates";
import { localDateStr } from "../../utils/date";
/* ── Helpers ─────────────────────────────────────────────────────── */ /* ── Helpers ─────────────────────────────────────────────────────── */
@@ -358,9 +360,12 @@ export default async function invoicesPdfRoutes(
// QR generation failed — leave empty // QR generation failed — leave empty
} }
// VAT recapitulation (always in CZK) // VAT recapitulation (always in CZK — Czech tax requirement)
const isForeign = currency.toUpperCase() !== "CZK"; 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 vatRates = [21, 12, 0];
const vatRecap: Array<{ const vatRecap: Array<{
rate: number; rate: number;
@@ -1007,6 +1012,17 @@ ${indentCSS}
<tbody> <tbody>
${vatRecapHtml} ${vatRecapHtml}
</tbody> </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> </table>
</div> </div>

View File

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

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 prisma from "../config/database";
import { toCzk } from "./exchange-rates";
// Status transition rules matching PHP // Status transition rules matching PHP
const VALID_TRANSITIONS: Record<string, string[]> = { 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; let total = 0;
for (const inv of invoices) { 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; return Math.round(total * 100) / 100;
}; };
@@ -224,18 +226,24 @@ export async function getInvoiceStats(queryMonth?: number, queryYear?: number) {
let vatCzk = 0; let vatCzk = 0;
for (const [, v] of Object.entries(vatMap)) vatCzk += v; 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 { return {
paid_month: aggregateByCurrency(paidInvoices), paid_month: aggregateByCurrency(paidInvoices),
paid_month_czk: sumCzk(paidInvoices), paid_month_czk: await sumCzk(paidInvoices),
paid_month_count: paidInvoices.length, paid_month_count: paidInvoices.length,
awaiting: aggregateByCurrency(awaitingInvoices), awaiting: aggregateByCurrency(awaitingInvoices),
awaiting_czk: sumCzk(awaitingInvoices), awaiting_czk: await sumCzk(awaitingInvoices),
awaiting_count: awaitingInvoices.length, awaiting_count: awaitingInvoices.length,
overdue: aggregateByCurrency(overdueInvoices), overdue: aggregateByCurrency(overdueInvoices),
overdue_czk: sumCzk(overdueInvoices), overdue_czk: await sumCzk(overdueInvoices),
overdue_count: overdueInvoices.length, overdue_count: overdueInvoices.length,
vat_month: vatAmounts, vat_month: vatAmounts,
vat_month_czk: Math.round(vatCzk * 100) / 100, vat_month_czk: Math.round(vatCzkConverted * 100) / 100,
month, month,
year, year,
}; };