feat: NAS storage for invoices/offers, code cleanup, date/time fixes

- NAS storage for created invoices (PDF via puppeteer), received invoices,
  and offers with auto-save on create/edit
- Deterministic file paths derived from DB fields (no file_path column needed)
- Separate NAS mount points: NAS_FINANCIALS_PATH, NAS_OFFERS_PATH
- Invoice language field (cs/en) stored per invoice, replaces lang modal
- Invoices list filtered by month/year matching KPI card selection
- Centralized date helpers (src/utils/date.ts) replacing all .toISOString()
  calls that returned UTC instead of local time
- Attendance project switching uses exact time (not rounded)
- Comment cleanup: removed ~100 unnecessary/Czech comments
- Removed as-any casts in orders and attendance
- Prisma migrations: add invoice language, drop received_invoices BLOB columns

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-03-26 10:36:39 +01:00
parent 0317ba3168
commit baceb88347
60 changed files with 2475 additions and 563 deletions

View File

@@ -755,10 +755,7 @@ export default function Attendance() {
{formatTime(shift.departure_time)}
</td>
<td className="admin-mono">
{formatMinutes(
calculateWorkMinutes(shift as any),
true,
)}
{formatMinutes(calculateWorkMinutes(shift), true)}
</td>
{projects.length > 0 && (
<td>

View File

@@ -156,7 +156,6 @@ export default function AttendanceHistory() {
fetchData();
}, [fetchData]);
// Compute totals client-side from raw records
const computed = useMemo(() => {
const [yearStr, monthStr] = month.split("-");
const monthIndex = parseInt(monthStr, 10) - 1;
@@ -181,11 +180,9 @@ export default function AttendanceHistory() {
}
}
// Compute monthly fund (working days * 8h)
// Exclude holidays from business days (matching PHP CzechHolidays logic)
const yr = parseInt(yearStr, 10);
const mo = parseInt(monthStr, 10) - 1;
// Count holiday records to subtract from business days
const holidayDays = records.filter(
(r) => (r.leave_type || "work") === "holiday",
).length;

View File

@@ -12,7 +12,7 @@ import Forbidden from "../components/Forbidden";
import FormField from "../components/FormField";
import AdminDatePicker from "../components/AdminDatePicker";
import ConfirmModal from "../components/ConfirmModal";
import { motion, AnimatePresence } from "framer-motion";
import { motion } from "framer-motion";
import {
DndContext,
closestCenter,
@@ -104,6 +104,7 @@ interface InvoiceForm {
issued_by: string;
billing_text: string;
notes: string;
language: string;
bank_account_id: number | string;
bank_name: string;
bank_swift: string;
@@ -132,6 +133,7 @@ interface Invoice {
issued_by: string | null;
paid_date?: string;
notes: string;
language: string;
apply_vat: number | string;
items: Omit<InvoiceItem, "_key">[];
valid_transitions?: string[];
@@ -521,6 +523,7 @@ export default function InvoiceDetail() {
issued_by: user?.fullName || "",
billing_text: "",
notes: "",
language: "cs",
bank_account_id: "",
bank_name: "",
bank_swift: "",
@@ -536,12 +539,10 @@ export default function InvoiceDetail() {
const [loading, setLoading] = useState(true);
const [invoiceNumber, setInvoiceNumber] = useState("");
// Customer selector (create mode)
const [customers, setCustomers] = useState<Customer[]>([]);
const [customerSearch, setCustomerSearch] = useState("");
const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
// Draft
const DRAFT_KEY = "boha_invoice_draft";
const clearDraft = useCallback(() => {
@@ -561,18 +562,15 @@ export default function InvoiceDetail() {
status: string | null;
}>({ show: false, status: null });
const [pdfLoading, setPdfLoading] = useState(false);
const [langModal, setLangModal] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState(false);
const [deleting, setDeleting] = useState(false);
// Edit items (edit mode)
const [editingItems, setEditingItems] = useState(false);
const [editItems, setEditItems] = useState<InvoiceItem[]>([]);
const editKeyCounter = useRef(0);
// ─── Data loading ───
// Create mode: load next number, customers, bank accounts, order data
useEffect(() => {
if (isEdit) return;
const load = async () => {
@@ -843,6 +841,9 @@ export default function InvoiceDetail() {
const result = await response.json();
if (result.success) {
clearDraft();
await apiFetch(
`${API_BASE}/invoices-pdf/${result.data.invoice_id}?lang=${form.language}&save=1`,
).catch(() => {});
alert.success(result.message || "Faktura byla vytvořena");
navigate(`/invoices/${result.data.invoice_id}`);
} else {
@@ -918,6 +919,9 @@ export default function InvoiceDetail() {
});
const result = await response.json();
if (result.success) {
await apiFetch(
`${API_BASE}/invoices-pdf/${id}?lang=${invoice?.language || "cs"}&save=1`,
).catch(() => {});
alert.success("Poznámky byly uloženy");
} else {
alert.error(result.error || "Nepodařilo se uložit poznámky");
@@ -930,28 +934,19 @@ export default function InvoiceDetail() {
};
// ─── Edit mode: PDF export ───
const handleViewPdf = async (lang = "cs") => {
setLangModal(false);
const newWindow = window.open("", "_blank");
const handleViewPdf = async (_lang = "cs") => {
setPdfLoading(true);
try {
const response = await apiFetch(
`${API_BASE}/invoices-pdf/${id}?lang=${encodeURIComponent(lang)}`,
);
const response = await apiFetch(`${API_BASE}/invoices/${id}/file`);
if (!response.ok) {
newWindow?.close();
alert.error("Nepodařilo se vygenerovat PDF");
alert.error("PDF soubor nenalezen — uložte fakturu pro vygenerování");
return;
}
const html = await response.text();
if (newWindow) {
newWindow.document.open();
newWindow.document.write(html);
newWindow.document.close();
newWindow.onload = () => newWindow.print();
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
window.open(url, "_blank");
setTimeout(() => URL.revokeObjectURL(url), 60000);
} catch {
newWindow?.close();
alert.error("Chyba připojení");
} finally {
setPdfLoading(false);
@@ -1028,6 +1023,10 @@ export default function InvoiceDetail() {
});
const result = await response.json();
if (result.success) {
// Regenerate PDF on NAS (fire-and-forget)
await apiFetch(
`${API_BASE}/invoices-pdf/${id}?lang=${invoice?.language || "cs"}&save=1`,
).catch(() => {});
alert.success("Položky byly uloženy");
setEditingItems(false);
fetchDetail();
@@ -1379,6 +1378,21 @@ export default function InvoiceDetail() {
<option value="USD">USD ($)</option>
</select>
</FormField>
<FormField label="Jazyk faktury">
<select
value={form.language}
onChange={(e) =>
setForm((prev) => ({
...prev,
language: e.target.value,
}))
}
className="admin-form-select"
>
<option value="cs">Čeština</option>
<option value="en">English</option>
</select>
</FormField>
<FormField label="DPH">
<div className="flex-row-gap">
<label
@@ -1608,33 +1622,33 @@ export default function InvoiceDetail() {
</div>
</div>
<div className="admin-page-actions">
{hasPermission("invoices.export") && (
{hasPermission("invoices.export") && invoice && (
<button
onClick={() => setLangModal(true)}
onClick={() => handleViewPdf(invoice.language || "cs")}
className="admin-btn admin-btn-secondary"
style={{
display: "inline-flex",
alignItems: "center",
gap: "0.4rem",
}}
disabled={pdfLoading}
>
{pdfLoading ? (
<>
<div className="admin-spinner admin-spinner-sm" />
PDF...
</>
<div className="admin-spinner admin-spinner-sm" />
) : (
<>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
</svg>
PDF
</>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
</svg>
)}
Zobrazit fakturu
</button>
)}
{hasPermission("invoices.edit") &&
@@ -2026,70 +2040,6 @@ export default function InvoiceDetail() {
type="danger"
loading={deleting}
/>
{/* Language selection for PDF */}
<AnimatePresence>
{langModal && (
<motion.div
className="admin-modal-overlay"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
>
<div
className="admin-modal-backdrop"
onClick={() => setLangModal(false)}
/>
<motion.div
className="admin-modal admin-confirm-modal"
role="dialog"
aria-modal="true"
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 20 }}
transition={{ duration: 0.2 }}
>
<div className="admin-modal-body admin-confirm-content">
<div className="admin-confirm-icon admin-confirm-icon-info">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z" />
<path d="M2 12h20" />
<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
</svg>
</div>
<h2 className="admin-confirm-title">Jazyk faktury</h2>
<p className="admin-confirm-message">
V jakém jazyce chcete vygenerovat fakturu?
</p>
</div>
<div className="admin-modal-footer">
<button
type="button"
onClick={() => handleViewPdf("cs")}
className="admin-btn admin-btn-primary"
>
Čeština
</button>
<button
type="button"
onClick={() => handleViewPdf("en")}
className="admin-btn admin-btn-primary"
>
English
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}

View File

@@ -223,7 +223,11 @@ export default function Invoices() {
sort,
order,
page,
extraParams: statusFilter ? { status: statusFilter } : {},
extraParams: {
month: String(statsMonth),
year: String(statsYear),
...(statusFilter ? { status: statusFilter } : {}),
},
errorMsg: "Nepodařilo se načíst faktury",
});

View File

@@ -345,7 +345,6 @@ export default function OfferDetail() {
form.valid_until &&
new Date(form.valid_until) < new Date(new Date().toDateString());
// Load data
const fetchDetail = useCallback(async () => {
if (!id) return;
try {
@@ -473,7 +472,6 @@ export default function OfferDetail() {
}
}, [showCustomerDropdown]);
// Fetch next quotation number for new offers
useEffect(() => {
if (isEdit) return;
const fetchNextNumber = async () => {
@@ -584,7 +582,6 @@ export default function OfferDetail() {
setItems((prev) => prev.filter((_, i) => i !== index));
};
// Totals
const subtotal = items.reduce((sum, item) => {
if (item.is_included_in_total) {
return (
@@ -624,6 +621,12 @@ export default function OfferDetail() {
});
const result = await response.json();
if (result.success) {
const offerId = isEdit ? id : result.data?.id;
if (offerId) {
await apiFetch(`${API_BASE}/offers-pdf/${offerId}?save=1`).catch(
() => {},
);
}
alert.success(
result.message ||
(isEdit ? "Nabídka byla aktualizována" : "Nabídka byla vytvořena"),
@@ -736,22 +739,16 @@ export default function OfferDetail() {
if (!isEdit || pdfLoading) return;
setPdfLoading(true);
try {
const response = await apiFetch(`${API_BASE}/offers-pdf/${id}`);
const response = await apiFetch(`${API_BASE}/offers/${id}/file`);
if (response.status === 401) return;
if (!response.ok) {
alert.error("Nepodařilo se vygenerovat PDF");
alert.error("PDF soubor nenalezen — uložte nabídku pro vygenerování");
return;
}
const html = await response.text();
const w = window.open("", "_blank");
if (w) {
w.document.open();
w.document.write(html);
w.document.close();
w.onload = () => w.print();
} else {
alert.error("Prohlížeč zablokoval vyskakovací okno");
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
window.open(url, "_blank");
setTimeout(() => URL.revokeObjectURL(url), 60000);
} catch {
alert.error("Chyba při generování PDF");
} finally {
@@ -858,29 +855,29 @@ export default function OfferDetail() {
<button
onClick={handlePdf}
className="admin-btn admin-btn-secondary"
style={{
display: "inline-flex",
alignItems: "center",
gap: "0.4rem",
}}
disabled={pdfLoading}
>
{pdfLoading ? (
<>
<div className="admin-spinner admin-spinner-sm" />
PDF...
</>
<div className="admin-spinner admin-spinner-sm" />
) : (
<>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
</svg>
PDF
</>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
</svg>
)}
Zobrazit nabídku
</button>
)}
{isEdit &&

View File

@@ -148,7 +148,6 @@ export default function ReceivedInvoices({
const { sort, order, handleSort, activeSort } = useTableSort("created_at");
const [search, setSearch] = useState("");
// Data
const [invoices, setInvoices] = useState<ReceivedInvoice[]>([]);
const [loading, setLoading] = useState(true);
const [stats, setStats] = useState<ReceivedStats | null>(null);
@@ -159,7 +158,6 @@ export default function ReceivedInvoices({
const prevMonth = useRef(statsMonth);
const prevYear = useRef(statsYear);
// Modals
const [editOpen, setEditOpen] = useState(false);
const [editInvoice, setEditInvoice] = useState<EditInvoice | null>(null);
const [deleteConfirm, setDeleteConfirm] = useState<{
@@ -169,10 +167,8 @@ export default function ReceivedInvoices({
const [deleting, setDeleting] = useState(false);
const [saving, setSaving] = useState(false);
// Supplier autocomplete
const [supplierNames, setSupplierNames] = useState<string[]>([]);
// Upload state
const [uploadFiles, setUploadFiles] = useState<File[]>([]);
const [uploadMeta, setUploadMeta] = useState<UploadMeta[]>([]);
const [uploadErrors, setUploadErrors] = useState<UploadErrors>({});
@@ -180,7 +176,6 @@ export default function ReceivedInvoices({
useModalLock(uploadOpen || editOpen);
// Slide direction detection
useEffect(() => {
const prev = prevYear.current * 12 + prevMonth.current;
const curr = statsYear * 12 + statsMonth;
@@ -194,7 +189,6 @@ export default function ReceivedInvoices({
prevYear.current = statsYear;
}, [statsMonth, statsYear]);
// Fetch list
const fetchList = useCallback(async () => {
if (!hasLoadedOnce.current) setLoading(true);
try {
@@ -228,7 +222,6 @@ export default function ReceivedInvoices({
fetchList();
}, [fetchList]);
// Fetch supplier names for autocomplete
useEffect(() => {
apiFetch(`${API_BASE}/received-invoices/suppliers`)
.then((r) => r.json())
@@ -277,7 +270,6 @@ export default function ReceivedInvoices({
load();
}, [statsMonth, statsYear]);
// Upload handlers
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const selected = Array.from(e.target.files || []);
if (selected.length === 0) {
@@ -384,7 +376,6 @@ export default function ReceivedInvoices({
}
};
// Edit handlers
const toDateInput = (d: string | null | undefined): string => {
if (!d) return "";
const date = new Date(d);
@@ -455,7 +446,6 @@ export default function ReceivedInvoices({
}
};
// Delete
const handleDelete = async () => {
if (!deleteConfirm.invoice) {
return;
@@ -484,26 +474,20 @@ export default function ReceivedInvoices({
}
};
// View file
const openFile = async (inv: ReceivedInvoice) => {
const newWindow = window.open("", "_blank");
try {
const response = await apiFetch(
`${API_BASE}/received-invoices/${inv.id}/file`,
);
if (!response.ok) {
newWindow?.close();
alert.error("Nepodařilo se načíst soubor");
return;
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
if (newWindow) {
newWindow.location.href = url;
}
window.open(url, "_blank");
setTimeout(() => URL.revokeObjectURL(url), 60000);
} catch {
newWindow?.close();
alert.error("Chyba připojení");
}
};
@@ -531,7 +515,6 @@ export default function ReceivedInvoices({
const monthLabel = `${MONTH_NAMES[statsMonth - 1]}`;
// KPI
const renderKpi = () => {
if (!hasLoadedOnce.current && statsLoading) {
return (

View File

@@ -55,7 +55,6 @@ export default function Settings() {
Record<string, Permission[]>
>({});
// 2FA requirement
const [require2FA, setRequire2FA] = useState(false);
const [require2FALoading, setRequire2FALoading] = useState(true);
const [require2FASaving, setRequire2FASaving] = useState(false);