feat(warehouse): add issue pages
This commit is contained in:
363
src/admin/pages/WarehouseIssueForm.tsx
Normal file
363
src/admin/pages/WarehouseIssueForm.tsx
Normal file
@@ -0,0 +1,363 @@
|
||||
import { useState, useEffect, useRef } 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 WarehouseMovementTable, {
|
||||
type MovementLine,
|
||||
} from "../components/warehouse/WarehouseMovementTable";
|
||||
import { warehouseLocationListOptions } from "../lib/queries/warehouse";
|
||||
|
||||
import apiFetch from "../utils/api";
|
||||
import {
|
||||
warehouseIssueDetailOptions,
|
||||
type WarehouseLocation,
|
||||
} from "../lib/queries/warehouse";
|
||||
import { projectListOptions } from "../lib/queries/projects";
|
||||
|
||||
interface IssueForm {
|
||||
project_id: number | null;
|
||||
notes: string;
|
||||
}
|
||||
|
||||
let lineCounter = 0;
|
||||
|
||||
export default function WarehouseIssueForm() {
|
||||
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<IssueForm>({
|
||||
project_id: null,
|
||||
notes: "",
|
||||
});
|
||||
const [lines, setLines] = useState<MovementLine[]>([]);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const formInitialized = useRef(false);
|
||||
|
||||
const { data: issue, isPending } = useQuery(
|
||||
warehouseIssueDetailOptions(isEdit ? id : undefined),
|
||||
);
|
||||
|
||||
const { data: locations = [] } = useQuery(warehouseLocationListOptions());
|
||||
|
||||
const { data: projectsData } = useQuery(projectListOptions({ perPage: 100 }));
|
||||
const projects = projectsData?.data ?? [];
|
||||
|
||||
useEffect(() => {
|
||||
formInitialized.current = false;
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isEdit && issue && !formInitialized.current) {
|
||||
setForm({
|
||||
project_id: issue.project_id,
|
||||
notes: issue.notes || "",
|
||||
});
|
||||
if (issue.lines && issue.lines.length > 0) {
|
||||
setLines(
|
||||
issue.lines.map((line) => ({
|
||||
key: `line-${++lineCounter}`,
|
||||
item_id: line.item_id,
|
||||
item_name: line.item?.name,
|
||||
quantity: Number(line.quantity),
|
||||
unit_price: line.batch ? Number(line.batch.unit_price) : 0,
|
||||
location_id: line.location_id,
|
||||
batch_id: line.batch_id,
|
||||
reservation_id: line.reservation_id,
|
||||
notes: line.notes,
|
||||
})),
|
||||
);
|
||||
}
|
||||
formInitialized.current = true;
|
||||
}
|
||||
}, [isEdit, issue]);
|
||||
|
||||
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> = {};
|
||||
if (!form.project_id) {
|
||||
newErrors.project_id = "Projekt je povinný";
|
||||
}
|
||||
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 = () => ({
|
||||
project_id: form.project_id,
|
||||
notes: form.notes.trim() || null,
|
||||
lines: lines
|
||||
.filter((l) => l.item_id !== null)
|
||||
.map((l) => ({
|
||||
item_id: l.item_id!,
|
||||
batch_id: l.batch_id,
|
||||
quantity: l.quantity,
|
||||
location_id: l.location_id,
|
||||
reservation_id: l.reservation_id,
|
||||
notes: l.notes?.trim() || null,
|
||||
})),
|
||||
});
|
||||
|
||||
const saveIssue = async (): Promise<number | null> => {
|
||||
const url = isEdit
|
||||
? `/api/admin/warehouse/issues/${id}`
|
||||
: "/api/admin/warehouse/issues";
|
||||
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", "issues"] });
|
||||
return result.data?.id ?? Number(id);
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se uložit výdejku");
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const confirmIssue = async (issueId: number) => {
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`/api/admin/warehouse/issues/${issueId}/confirm`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
queryClient.invalidateQueries({ queryKey: ["warehouse", "issues"] });
|
||||
alert.success("Výdejka byla potvrzena");
|
||||
} else {
|
||||
alert.error(result.error || "Nepodařilo se potvrdit výdejku");
|
||||
}
|
||||
} catch {
|
||||
alert.error("Chyba připojení");
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveDraft = async () => {
|
||||
if (!validate()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const savedId = await saveIssue();
|
||||
if (savedId) {
|
||||
alert.success("Výdejka byla uložena jako návrh");
|
||||
navigate(`/warehouse/issues/${savedId}`);
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAndConfirm = async () => {
|
||||
if (!validate()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const savedId = await saveIssue();
|
||||
if (savedId) {
|
||||
await confirmIssue(savedId);
|
||||
navigate(`/warehouse/issues/${savedId}`);
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
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/issues"
|
||||
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 výdejku" : "Nová výdejka"}
|
||||
</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="Projekt">
|
||||
<select
|
||||
value={form.project_id ?? ""}
|
||||
onChange={(e) =>
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
project_id:
|
||||
e.target.value === "" ? null : Number(e.target.value),
|
||||
}))
|
||||
}
|
||||
className="admin-form-select"
|
||||
>
|
||||
<option value="">Vyberte projekt...</option>
|
||||
{projects.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.project_number} – {p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.project_id && (
|
||||
<div
|
||||
style={{
|
||||
color: "var(--danger)",
|
||||
fontSize: "0.875rem",
|
||||
marginTop: "0.25rem",
|
||||
}}
|
||||
>
|
||||
{errors.project_id}
|
||||
</div>
|
||||
)}
|
||||
</FormField>
|
||||
<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 výdejky</h3>
|
||||
{errors.lines && (
|
||||
<div
|
||||
style={{
|
||||
color: "var(--danger)",
|
||||
fontSize: "0.875rem",
|
||||
marginBottom: "0.75rem",
|
||||
}}
|
||||
>
|
||||
{errors.lines}
|
||||
</div>
|
||||
)}
|
||||
<WarehouseMovementTable
|
||||
lines={lines}
|
||||
onChange={setLines}
|
||||
mode="issue"
|
||||
locations={locations as WarehouseLocation[]}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user