feat(warehouse): add receipt pages
This commit is contained in:
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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user