feat(warehouse): add receipt pages
This commit is contained in:
460
src/admin/pages/WarehouseReceiptDetail.tsx
Normal file
460
src/admin/pages/WarehouseReceiptDetail.tsx
Normal file
@@ -0,0 +1,460 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Link } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { motion } from "framer-motion";
|
||||
import ConfirmModal from "../components/ConfirmModal";
|
||||
import FormField from "../components/FormField";
|
||||
|
||||
import apiFetch from "../utils/api";
|
||||
import { formatCurrency, formatDate } from "../utils/formatters";
|
||||
import {
|
||||
warehouseReceiptDetailOptions,
|
||||
type WarehouseReceipt,
|
||||
} from "../lib/queries/warehouse";
|
||||
|
||||
const STATUS_BADGE: Record<string, string> = {
|
||||
DRAFT: "admin-badge-warning",
|
||||
CONFIRMED: "admin-badge-active",
|
||||
CANCELLED: "admin-badge-danger",
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
DRAFT: "Návrh",
|
||||
CONFIRMED: "Potvrzeno",
|
||||
CANCELLED: "Zrušeno",
|
||||
};
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export default function WarehouseReceiptDetail() {
|
||||
const { id } = useParams();
|
||||
const alert = useAlert();
|
||||
const { hasPermission } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [cancelConfirm, setCancelConfirm] = useState(false);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
|
||||
const {
|
||||
data: receipt,
|
||||
isPending,
|
||||
error,
|
||||
} = useQuery(warehouseReceiptDetailOptions(id));
|
||||
|
||||
if (!hasPermission("warehouse.view")) return <Forbidden />;
|
||||
|
||||
const canOperate = hasPermission("warehouse.operate");
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!receipt) return;
|
||||
setConfirming(true);
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`/api/admin/warehouse/receipts/${receipt.id}/confirm`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
queryClient.invalidateQueries({ queryKey: ["warehouse", "receipts"] });
|
||||
alert.success("Doklad byl potvrzen");
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se potvrdit doklad");
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
} finally {
|
||||
setConfirming(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = async () => {
|
||||
if (!receipt) return;
|
||||
setCancelling(true);
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`/api/admin/warehouse/receipts/${receipt.id}/cancel`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
queryClient.invalidateQueries({ queryKey: ["warehouse", "receipts"] });
|
||||
setCancelConfirm(false);
|
||||
alert.success("Doklad byl zrušen");
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se zrušit doklad");
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
} finally {
|
||||
setCancelling(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAttachment = async (attachmentId: number) => {
|
||||
if (!receipt) return;
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`/api/admin/warehouse/receipts/${receipt.id}/attachments/${attachmentId}`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
queryClient.invalidateQueries({ queryKey: ["warehouse", "receipts"] });
|
||||
alert.success("Příloha byla smazána");
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se smazat přílohu");
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
}
|
||||
};
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="admin-loading">
|
||||
<div className="admin-spinner" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !receipt) {
|
||||
return (
|
||||
<div>
|
||||
<div className="admin-page-header">
|
||||
<div>
|
||||
<Link
|
||||
to="/warehouse/receipts"
|
||||
className="admin-btn-icon"
|
||||
title="Zpět na seznam"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M19 12H5M12 19l-7-7 7-7" />
|
||||
</svg>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-card">
|
||||
<div className="admin-card-body">
|
||||
<div className="admin-empty-state">
|
||||
<p>Doklad nebyl nalezen.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const r = receipt as WarehouseReceipt;
|
||||
const lines = r.lines ?? [];
|
||||
const attachments = r.attachments ?? [];
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Header */}
|
||||
<motion.div
|
||||
className="admin-page-header"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25 }}
|
||||
>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
|
||||
<Link
|
||||
to="/warehouse/receipts"
|
||||
className="admin-btn-icon"
|
||||
title="Zpět na seznam"
|
||||
aria-label="Zpět na seznam"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M19 12H5M12 19l-7-7 7-7" />
|
||||
</svg>
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="admin-page-title">
|
||||
{r.receipt_number || "Nový doklad"}
|
||||
</h1>
|
||||
{r.supplier?.name && (
|
||||
<p className="admin-page-subtitle">{r.supplier.name}</p>
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`admin-badge ${STATUS_BADGE[r.status] ?? ""}`}
|
||||
style={{ marginLeft: "0.5rem" }}
|
||||
>
|
||||
{STATUS_LABEL[r.status] ?? r.status}
|
||||
</span>
|
||||
</div>
|
||||
{canOperate && (
|
||||
<div className="admin-page-actions">
|
||||
{r.status === "DRAFT" && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => navigate(`/warehouse/receipts/${r.id}/edit`)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
>
|
||||
Upravit
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirm}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={confirming}
|
||||
>
|
||||
{confirming ? "Potvrzování..." : "Potvrdit"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setCancelConfirm(true)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
style={{ color: "var(--danger)" }}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{r.status === "CONFIRMED" && (
|
||||
<button
|
||||
onClick={() => setCancelConfirm(true)}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
style={{ color: "var(--danger)" }}
|
||||
>
|
||||
Zrušit
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
{/* Header info */}
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.06 }}
|
||||
>
|
||||
<div className="admin-card-body">
|
||||
<h3 className="admin-card-title">Základní údaje</h3>
|
||||
<div className="admin-form">
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Číslo dokladu">
|
||||
<div className="admin-mono" style={{ fontWeight: 500 }}>
|
||||
{r.receipt_number || "—"}
|
||||
</div>
|
||||
</FormField>
|
||||
<FormField label="Dodavatel">
|
||||
<div style={{ fontWeight: 500 }}>{r.supplier?.name || "—"}</div>
|
||||
</FormField>
|
||||
</div>
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Číslo dodacího listu">
|
||||
<div className="admin-mono">
|
||||
{r.delivery_note_number || "—"}
|
||||
</div>
|
||||
</FormField>
|
||||
<FormField label="Datum dodacího listu">
|
||||
<div className="admin-mono">
|
||||
{formatDate(r.delivery_note_date)}
|
||||
</div>
|
||||
</FormField>
|
||||
</div>
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Přijal">
|
||||
<div>
|
||||
{r.received_by_user
|
||||
? `${r.received_by_user.first_name} ${r.received_by_user.last_name}`
|
||||
: "—"}
|
||||
</div>
|
||||
</FormField>
|
||||
<FormField label="Vytvořeno">
|
||||
<div className="admin-mono">{formatDate(r.created_at)}</div>
|
||||
</FormField>
|
||||
</div>
|
||||
{r.notes && (
|
||||
<FormField label="Poznámky">
|
||||
<div style={{ whiteSpace: "pre-wrap" }}>{r.notes}</div>
|
||||
</FormField>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Lines table */}
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.08 }}
|
||||
>
|
||||
<div className="admin-card-body">
|
||||
<h3 className="admin-card-title">Řádky dokladu</h3>
|
||||
{lines.length === 0 ? (
|
||||
<div
|
||||
style={{
|
||||
color: "var(--text-tertiary)",
|
||||
fontSize: "0.875rem",
|
||||
textAlign: "center",
|
||||
padding: "1.5rem 0",
|
||||
}}
|
||||
>
|
||||
Žádné řádky
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-table-responsive">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Položka</th>
|
||||
<th className="text-right">Množství</th>
|
||||
<th className="text-right">Cena/ks</th>
|
||||
<th className="text-right">Celkem</th>
|
||||
<th>Lokace</th>
|
||||
<th>Poznámka</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{lines.map((line) => (
|
||||
<tr key={line.id}>
|
||||
<td className="fw-500">
|
||||
{line.item?.name || `ID: ${line.item_id}`}
|
||||
</td>
|
||||
<td className="admin-mono text-right">
|
||||
{Number(line.quantity)}
|
||||
</td>
|
||||
<td className="admin-mono text-right">
|
||||
{formatCurrency(Number(line.unit_price), "CZK")}
|
||||
</td>
|
||||
<td className="admin-mono text-right fw-500">
|
||||
{formatCurrency(
|
||||
Number(line.quantity) * Number(line.unit_price),
|
||||
"CZK",
|
||||
)}
|
||||
</td>
|
||||
<td className="admin-mono">
|
||||
{line.location?.code || "—"}
|
||||
</td>
|
||||
<td>{line.notes || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Attachments */}
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.1 }}
|
||||
>
|
||||
<div className="admin-card-body">
|
||||
<h3 className="admin-card-title">Přílohy</h3>
|
||||
{attachments.length === 0 ? (
|
||||
<div
|
||||
style={{
|
||||
color: "var(--text-tertiary)",
|
||||
fontSize: "0.875rem",
|
||||
textAlign: "center",
|
||||
padding: "1.5rem 0",
|
||||
}}
|
||||
>
|
||||
Žádné přílohy
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-table-responsive">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Název souboru</th>
|
||||
<th>Velikost</th>
|
||||
<th>Datum</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{attachments.map((att) => (
|
||||
<tr key={att.id}>
|
||||
<td className="fw-500">
|
||||
<a
|
||||
href={`/api/admin/warehouse/receipts/${r.id}/attachments/${att.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{att.file_name}
|
||||
</a>
|
||||
</td>
|
||||
<td className="admin-mono">
|
||||
{formatFileSize(att.file_size)}
|
||||
</td>
|
||||
<td className="admin-mono">
|
||||
{formatDate(att.created_at)}
|
||||
</td>
|
||||
<td>
|
||||
{r.status === "DRAFT" && canOperate && (
|
||||
<button
|
||||
onClick={() => handleDeleteAttachment(att.id)}
|
||||
className="admin-btn-icon danger"
|
||||
title="Smazat přílohu"
|
||||
aria-label="Smazat přílohu"
|
||||
>
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<polyline points="3 6 5 6 21 6" />
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Cancel confirmation modal */}
|
||||
<ConfirmModal
|
||||
isOpen={cancelConfirm}
|
||||
onClose={() => setCancelConfirm(false)}
|
||||
onConfirm={handleCancel}
|
||||
title="Zrušit doklad"
|
||||
message={`Opravdu chcete zrušit příjmový doklad „${r.receipt_number || r.id}"?`}
|
||||
confirmText="Zrušit doklad"
|
||||
confirmVariant="danger"
|
||||
loading={cancelling}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
499
src/admin/pages/WarehouseReceiptForm.tsx
Normal file
499
src/admin/pages/WarehouseReceiptForm.tsx
Normal file
@@ -0,0 +1,499 @@
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useParams, useNavigate, Link } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { motion } from "framer-motion";
|
||||
import FormField from "../components/FormField";
|
||||
import SupplierSelect from "../components/warehouse/SupplierSelect";
|
||||
import WarehouseMovementTable, {
|
||||
type MovementLine,
|
||||
} from "../components/warehouse/WarehouseMovementTable";
|
||||
import { warehouseLocationListOptions } from "../lib/queries/warehouse";
|
||||
|
||||
import apiFetch from "../utils/api";
|
||||
import {
|
||||
warehouseReceiptDetailOptions,
|
||||
type WarehouseLocation,
|
||||
} from "../lib/queries/warehouse";
|
||||
|
||||
interface ReceiptForm {
|
||||
supplier_id: number | null;
|
||||
delivery_note_number: string;
|
||||
delivery_note_date: string;
|
||||
notes: string;
|
||||
}
|
||||
|
||||
let lineCounter = 0;
|
||||
|
||||
export default function WarehouseReceiptForm() {
|
||||
const { id } = useParams();
|
||||
const alert = useAlert();
|
||||
const { hasPermission } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const isEdit = id !== undefined && id !== "new";
|
||||
|
||||
const [form, setForm] = useState<ReceiptForm>({
|
||||
supplier_id: null,
|
||||
delivery_note_number: "",
|
||||
delivery_note_date: "",
|
||||
notes: "",
|
||||
});
|
||||
const [lines, setLines] = useState<MovementLine[]>([]);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [uploadingFiles, setUploadingFiles] = useState(false);
|
||||
|
||||
const formInitialized = useRef(false);
|
||||
|
||||
const { data: receipt, isPending } = useQuery(
|
||||
warehouseReceiptDetailOptions(isEdit ? id : undefined),
|
||||
);
|
||||
|
||||
const { data: locations = [] } = useQuery(warehouseLocationListOptions());
|
||||
|
||||
useEffect(() => {
|
||||
formInitialized.current = false;
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isEdit && receipt && !formInitialized.current) {
|
||||
setForm({
|
||||
supplier_id: receipt.supplier_id,
|
||||
delivery_note_number: receipt.delivery_note_number || "",
|
||||
delivery_note_date: receipt.delivery_note_date
|
||||
? receipt.delivery_note_date.split("T")[0]
|
||||
: "",
|
||||
notes: receipt.notes || "",
|
||||
});
|
||||
if (receipt.lines && receipt.lines.length > 0) {
|
||||
setLines(
|
||||
receipt.lines.map((line) => ({
|
||||
key: `line-${++lineCounter}`,
|
||||
item_id: line.item_id,
|
||||
item_name: line.item?.name,
|
||||
quantity: Number(line.quantity),
|
||||
unit_price: Number(line.unit_price),
|
||||
location_id: line.location_id,
|
||||
batch_id: null,
|
||||
reservation_id: null,
|
||||
notes: line.notes,
|
||||
})),
|
||||
);
|
||||
}
|
||||
formInitialized.current = true;
|
||||
}
|
||||
}, [isEdit, receipt]);
|
||||
|
||||
if (!hasPermission("warehouse.operate")) return <Forbidden />;
|
||||
|
||||
const addEmptyLine = () => {
|
||||
setLines((prev) => [
|
||||
...prev,
|
||||
{
|
||||
key: `line-${++lineCounter}`,
|
||||
item_id: null,
|
||||
quantity: 0,
|
||||
unit_price: 0,
|
||||
location_id: null,
|
||||
batch_id: null,
|
||||
reservation_id: null,
|
||||
notes: null,
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
// Start with one empty line in create mode
|
||||
useEffect(() => {
|
||||
if (!isEdit && lines.length === 0) {
|
||||
addEmptyLine();
|
||||
}
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const validate = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
const validLines = lines.filter((l) => l.item_id !== null);
|
||||
if (validLines.length === 0) {
|
||||
newErrors.lines = "Přidejte alespoň jednu položku";
|
||||
}
|
||||
for (const line of validLines) {
|
||||
if (line.quantity <= 0) {
|
||||
newErrors.lines = "Množství musí být větší než 0";
|
||||
break;
|
||||
}
|
||||
}
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const buildPayload = () => ({
|
||||
supplier_id: form.supplier_id,
|
||||
delivery_note_number: form.delivery_note_number.trim() || null,
|
||||
delivery_note_date: form.delivery_note_date || null,
|
||||
notes: form.notes.trim() || null,
|
||||
lines: lines
|
||||
.filter((l) => l.item_id !== null)
|
||||
.map((l) => ({
|
||||
item_id: l.item_id!,
|
||||
quantity: l.quantity,
|
||||
unit_price: l.unit_price,
|
||||
location_id: l.location_id,
|
||||
notes: l.notes?.trim() || null,
|
||||
})),
|
||||
});
|
||||
|
||||
const saveReceipt = async (): Promise<number | null> => {
|
||||
const url = isEdit
|
||||
? `/api/admin/warehouse/receipts/${id}`
|
||||
: "/api/admin/warehouse/receipts";
|
||||
const method = isEdit ? "PUT" : "POST";
|
||||
|
||||
try {
|
||||
const response = await apiFetch(url, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(buildPayload()),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
queryClient.invalidateQueries({ queryKey: ["warehouse", "receipts"] });
|
||||
return result.data?.id ?? Number(id);
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se uložit doklad");
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const confirmReceipt = async (receiptId: number) => {
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`/api/admin/warehouse/receipts/${receiptId}/confirm`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
queryClient.invalidateQueries({ queryKey: ["warehouse", "receipts"] });
|
||||
alert.success("Doklad byl potvrzen");
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se potvrdit doklad");
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveDraft = async () => {
|
||||
if (!validate()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const savedId = await saveReceipt();
|
||||
if (savedId) {
|
||||
alert.success("Doklad byl uložen jako návrh");
|
||||
navigate(`/warehouse/receipts/${savedId}`);
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAndConfirm = async () => {
|
||||
if (!validate()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const savedId = await saveReceipt();
|
||||
if (savedId) {
|
||||
await confirmReceipt(savedId);
|
||||
navigate(`/warehouse/receipts/${savedId}`);
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = useCallback(
|
||||
async (files: FileList | File[]) => {
|
||||
if (!isEdit || !id) return;
|
||||
setUploadingFiles(true);
|
||||
try {
|
||||
for (const file of files) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
const response = await apiFetch(
|
||||
`/api/admin/warehouse/receipts/${id}/attachments`,
|
||||
{
|
||||
method: "POST",
|
||||
body: formData,
|
||||
},
|
||||
);
|
||||
const result = await response.json();
|
||||
if (!result.success) {
|
||||
alert.error(
|
||||
result.error || `Nepodařilo se nahrát soubor ${file.name}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ["warehouse", "receipts"] });
|
||||
alert.success("Soubory byly nahrány");
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
} finally {
|
||||
setUploadingFiles(false);
|
||||
}
|
||||
},
|
||||
[id, isEdit, alert, queryClient],
|
||||
);
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
if (e.dataTransfer.files.length > 0) {
|
||||
handleFileUpload(e.dataTransfer.files);
|
||||
}
|
||||
},
|
||||
[handleFileUpload],
|
||||
);
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
}, []);
|
||||
|
||||
if (isEdit && isPending) {
|
||||
return (
|
||||
<div className="admin-loading">
|
||||
<div className="admin-spinner" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Header */}
|
||||
<motion.div
|
||||
className="admin-page-header"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25 }}
|
||||
>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
|
||||
<Link
|
||||
to="/warehouse/receipts"
|
||||
className="admin-btn-icon"
|
||||
title="Zpět na seznam"
|
||||
aria-label="Zpět na seznam"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M19 12H5M12 19l-7-7 7-7" />
|
||||
</svg>
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="admin-page-title">
|
||||
{isEdit ? "Upravit příjmový doklad" : "Nový příjmový doklad"}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-page-actions">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSaveDraft}
|
||||
className="admin-btn admin-btn-secondary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? "Ukládání..." : "Uložit jako návrh"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSaveAndConfirm}
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? "Ukládání..." : "Uložit a potvrdit"}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Header fields */}
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.06 }}
|
||||
>
|
||||
<div className="admin-card-body">
|
||||
<h3 className="admin-card-title">Základní údaje</h3>
|
||||
<div className="admin-form">
|
||||
<FormField label="Dodavatel">
|
||||
<SupplierSelect
|
||||
value={form.supplier_id}
|
||||
onChange={(val) =>
|
||||
setForm((prev) => ({ ...prev, supplier_id: val }))
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
<div className="admin-form-row">
|
||||
<FormField label="Číslo dodacího listu">
|
||||
<input
|
||||
type="text"
|
||||
value={form.delivery_note_number}
|
||||
onChange={(e) =>
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
delivery_note_number: e.target.value,
|
||||
}))
|
||||
}
|
||||
className="admin-form-input"
|
||||
placeholder="Např. DL-2024-001"
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Datum dodacího listu">
|
||||
<input
|
||||
type="date"
|
||||
value={form.delivery_note_date}
|
||||
onChange={(e) =>
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
delivery_note_date: e.target.value,
|
||||
}))
|
||||
}
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField label="Poznámky">
|
||||
<textarea
|
||||
value={form.notes}
|
||||
onChange={(e) =>
|
||||
setForm((prev) => ({ ...prev, notes: e.target.value }))
|
||||
}
|
||||
className="admin-form-input"
|
||||
rows={3}
|
||||
placeholder="Volitelné poznámky"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Lines */}
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.08 }}
|
||||
>
|
||||
<div className="admin-card-body">
|
||||
<h3 className="admin-card-title">Řádky dokladu</h3>
|
||||
{errors.lines && (
|
||||
<div
|
||||
style={{
|
||||
color: "var(--danger)",
|
||||
fontSize: "0.875rem",
|
||||
marginBottom: "0.75rem",
|
||||
}}
|
||||
>
|
||||
{errors.lines}
|
||||
</div>
|
||||
)}
|
||||
<WarehouseMovementTable
|
||||
lines={lines}
|
||||
onChange={setLines}
|
||||
mode="receipt"
|
||||
locations={locations as WarehouseLocation[]}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* File upload — only in edit mode for existing receipts */}
|
||||
{isEdit && (
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.1 }}
|
||||
>
|
||||
<div className="admin-card-body">
|
||||
<h3 className="admin-card-title">Přílohy</h3>
|
||||
<div
|
||||
className="admin-file-dropzone"
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
style={{
|
||||
border: "2px dashed var(--border)",
|
||||
borderRadius: "8px",
|
||||
padding: "2rem",
|
||||
textAlign: "center",
|
||||
cursor: "pointer",
|
||||
opacity: uploadingFiles ? 0.6 : 1,
|
||||
transition: "opacity 0.2s",
|
||||
}}
|
||||
onClick={() => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.multiple = true;
|
||||
input.onchange = () => {
|
||||
if (input.files && input.files.length > 0) {
|
||||
handleFileUpload(input.files);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
}}
|
||||
>
|
||||
{uploadingFiles ? (
|
||||
<>
|
||||
<div className="admin-spinner admin-spinner-sm" />
|
||||
<p style={{ marginTop: "0.5rem" }}>Nahrávání...</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg
|
||||
width="32"
|
||||
height="32"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
style={{
|
||||
color: "var(--text-tertiary)",
|
||||
margin: "0 auto 0.5rem",
|
||||
}}
|
||||
>
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="17 8 12 3 7 8" />
|
||||
<line x1="12" y1="3" x2="12" y2="15" />
|
||||
</svg>
|
||||
<p style={{ color: "var(--text-secondary)" }}>
|
||||
Přetáhněte soubory sem nebo klikněte pro výběr
|
||||
</p>
|
||||
<p
|
||||
style={{
|
||||
color: "var(--text-tertiary)",
|
||||
fontSize: "0.8rem",
|
||||
marginTop: "0.25rem",
|
||||
}}
|
||||
>
|
||||
Dodací listy, faktury a další dokumenty
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
333
src/admin/pages/WarehouseReceipts.tsx
Normal file
333
src/admin/pages/WarehouseReceipts.tsx
Normal file
@@ -0,0 +1,333 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import Pagination from "../components/Pagination";
|
||||
import useDebounce from "../hooks/useDebounce";
|
||||
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
|
||||
|
||||
import { formatDate } from "../utils/formatters";
|
||||
import {
|
||||
warehouseReceiptListOptions,
|
||||
warehouseSupplierListOptions,
|
||||
type WarehouseReceipt,
|
||||
} from "../lib/queries/warehouse";
|
||||
|
||||
const PER_PAGE = 20;
|
||||
|
||||
const STATUS_BADGE: Record<string, string> = {
|
||||
DRAFT: "admin-badge-warning",
|
||||
CONFIRMED: "admin-badge-active",
|
||||
CANCELLED: "admin-badge-danger",
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
DRAFT: "Návrh",
|
||||
CONFIRMED: "Potvrzeno",
|
||||
CANCELLED: "Zrušeno",
|
||||
};
|
||||
|
||||
export default function WarehouseReceipts() {
|
||||
const { hasPermission } = useAuth();
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [search, setSearch] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState<string>("");
|
||||
const [supplierId, setSupplierId] = useState<number | "">("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
const debouncedSearch = useDebounce(search, 300);
|
||||
|
||||
const { data: suppliersData } = useQuery(
|
||||
warehouseSupplierListOptions({ perPage: 100 }),
|
||||
);
|
||||
const suppliers = suppliersData?.data ?? [];
|
||||
|
||||
const { items, pagination, isPending, isFetching } =
|
||||
usePaginatedQuery<WarehouseReceipt>(
|
||||
warehouseReceiptListOptions({
|
||||
search: debouncedSearch || undefined,
|
||||
page,
|
||||
perPage: PER_PAGE,
|
||||
status: statusFilter || undefined,
|
||||
supplier_id: supplierId ? Number(supplierId) : undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
}),
|
||||
);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!hasPermission("warehouse.view")) return <Forbidden />;
|
||||
|
||||
const canOperate = hasPermission("warehouse.operate");
|
||||
|
||||
const handleRowClick = (receipt: WarehouseReceipt) => {
|
||||
navigate(`/warehouse/receipts/${receipt.id}`);
|
||||
};
|
||||
|
||||
const resetFilters = () => {
|
||||
setSearch("");
|
||||
setStatusFilter("");
|
||||
setSupplierId("");
|
||||
setDateFrom("");
|
||||
setDateTo("");
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const hasActiveFilters = statusFilter || supplierId || dateFrom || dateTo;
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="admin-loading">
|
||||
<div className="admin-spinner" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<motion.div
|
||||
className="admin-page-header"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25 }}
|
||||
>
|
||||
<div>
|
||||
<h1 className="admin-page-title">Příjmové doklady</h1>
|
||||
<p className="admin-page-subtitle">
|
||||
{pagination?.total ?? items.length}{" "}
|
||||
{pagination?.total === 1
|
||||
? "doklad"
|
||||
: pagination?.total !== undefined &&
|
||||
pagination.total >= 2 &&
|
||||
pagination.total <= 4
|
||||
? "doklady"
|
||||
: "dokladů"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="admin-page-actions">
|
||||
{canOperate && (
|
||||
<button
|
||||
onClick={() => navigate("/warehouse/receipts/new")}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
<svg
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<line x1="12" y1="5" x2="12" y2="19" />
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
Nový doklad
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
className="admin-card"
|
||||
initial={{ opacity: 0, y: 12 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.25, delay: 0.06 }}
|
||||
style={{ opacity: isFetching ? 0.6 : 1, transition: "opacity 0.2s" }}
|
||||
>
|
||||
<div className="admin-card-body">
|
||||
<div className="admin-search-bar mb-4">
|
||||
<div className="admin-search">
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
<line x1="21" y1="21" x2="16.65" y2="16.65" />
|
||||
</svg>
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Hledat podle čísla dokladu..."
|
||||
className="admin-form-input"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="admin-form-select"
|
||||
style={{ minWidth: 140 }}
|
||||
>
|
||||
<option value="">Všechny stavy</option>
|
||||
<option value="DRAFT">Návrh</option>
|
||||
<option value="CONFIRMED">Potvrzeno</option>
|
||||
<option value="CANCELLED">Zrušeno</option>
|
||||
</select>
|
||||
{suppliers.length > 0 && (
|
||||
<select
|
||||
value={supplierId}
|
||||
onChange={(e) => {
|
||||
setSupplierId(
|
||||
e.target.value === "" ? "" : Number(e.target.value),
|
||||
);
|
||||
setPage(1);
|
||||
}}
|
||||
className="admin-form-select"
|
||||
style={{ minWidth: 180 }}
|
||||
>
|
||||
<option value="">Všichni dodavatelé</option>
|
||||
{suppliers.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<input
|
||||
type="date"
|
||||
value={dateFrom}
|
||||
onChange={(e) => {
|
||||
setDateFrom(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="admin-form-input"
|
||||
style={{ width: 140 }}
|
||||
placeholder="Od"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
value={dateTo}
|
||||
onChange={(e) => {
|
||||
setDateTo(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="admin-form-input"
|
||||
style={{ width: 140 }}
|
||||
placeholder="Do"
|
||||
/>
|
||||
{hasActiveFilters && (
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-secondary"
|
||||
onClick={resetFilters}
|
||||
style={{ whiteSpace: "nowrap" }}
|
||||
>
|
||||
Zrušit filtry
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={`${debouncedSearch}-${statusFilter}-${supplierId}-${dateFrom}-${dateTo}-${page}-${items.length}`}
|
||||
initial={{ opacity: 0, y: 6 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
{items.length === 0 && (
|
||||
<div className="admin-empty-state">
|
||||
<div className="admin-empty-icon">
|
||||
<svg
|
||||
width="28"
|
||||
height="28"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<polyline points="14 2 14 8 20 8" />
|
||||
<line x1="16" y1="13" x2="8" y2="13" />
|
||||
<line x1="16" y1="17" x2="8" y2="17" />
|
||||
</svg>
|
||||
</div>
|
||||
<p>
|
||||
{search || hasActiveFilters
|
||||
? "Žádné doklady pro zadaný filtr."
|
||||
: "Zatím nejsou žádné příjmové doklady."}
|
||||
</p>
|
||||
{canOperate && !search && !hasActiveFilters && (
|
||||
<button
|
||||
onClick={() => navigate("/warehouse/receipts/new")}
|
||||
className="admin-btn admin-btn-primary"
|
||||
>
|
||||
Vytvořit první doklad
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{items.length > 0 && (
|
||||
<div className="admin-table-responsive">
|
||||
<table className="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Číslo dokladu</th>
|
||||
<th>Dodavatel</th>
|
||||
<th>Stav</th>
|
||||
<th>Dodací list</th>
|
||||
<th>Vytvořeno</th>
|
||||
<th className="text-right">Řádků</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((receipt) => (
|
||||
<tr
|
||||
key={receipt.id}
|
||||
onClick={() => handleRowClick(receipt)}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<td className="admin-mono fw-500">
|
||||
{receipt.receipt_number || "—"}
|
||||
</td>
|
||||
<td>{receipt.supplier?.name || "—"}</td>
|
||||
<td>
|
||||
<span
|
||||
className={`admin-badge ${STATUS_BADGE[receipt.status] ?? ""}`}
|
||||
>
|
||||
{STATUS_LABEL[receipt.status] ?? receipt.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="admin-mono">
|
||||
{receipt.delivery_note_number || "—"}
|
||||
</td>
|
||||
<td className="admin-mono">
|
||||
{formatDate(receipt.created_at)}
|
||||
</td>
|
||||
<td className="admin-mono text-right">
|
||||
{receipt.lines?.length ?? 0}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
|
||||
<Pagination pagination={pagination} onPageChange={setPage} />
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user