/**
* 新增配方頁面
*/
import { useState, useEffect } from "react";
import { BookOpen, Plus, Trash2, ArrowLeft, Save } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, useForm, Link } from "@inertiajs/react";
import { toast } from "sonner";
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
interface Product {
id: number;
name: string;
code: string;
base_unit_id?: number;
large_unit_id?: number;
}
interface Unit {
id: number;
name: string;
}
interface RecipeItem {
product_id: string;
quantity: string;
unit_id: string;
remark: string;
// UI Helpers
ui_product_name?: string;
ui_product_code?: string;
}
interface Props {
products: Product[];
units: Unit[];
}
export default function RecipeCreate({ products, units }: Props) {
const { data, setData, post, processing, errors } = useForm({
product_id: "",
code: "",
name: "",
description: "",
yield_quantity: "1",
items: [] as RecipeItem[],
});
// 自動產生配方名稱 (當選擇商品時)
useEffect(() => {
if (data.product_id && !data.name) {
const product = products.find(p => String(p.id) === data.product_id);
if (product) {
setData(d => ({ ...d, name: `${product.name} 標準配方` }));
}
}
// 自動產生代號 (簡易版)
if (data.product_id && !data.code) {
const product = products.find(p => String(p.id) === data.product_id);
if (product) {
setData(d => ({ ...d, code: `REC-${product.code}` }));
}
}
}, [data.product_id]);
const addItem = () => {
setData('items', [
...data.items,
{ product_id: "", quantity: "1", unit_id: "", remark: "" }
]);
};
const removeItem = (index: number) => {
setData('items', data.items.filter((_, i) => i !== index));
};
const updateItem = (index: number, field: keyof RecipeItem, value: string) => {
const newItems = [...data.items];
newItems[index] = { ...newItems[index], [field]: value };
// Auto-fill unit when product selected
if (field === 'product_id') {
const product = products.find(p => String(p.id) === value);
if (product) {
newItems[index].ui_product_name = product.name;
newItems[index].ui_product_code = product.code;
// Default to base unit
if (product.base_unit_id) {
newItems[index].unit_id = String(product.base_unit_id);
}
}
}
setData('items', newItems);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
post(route('recipes.store'), {
onSuccess: () => {
toast.success("配方已建立");
},
onError: (errors) => {
toast.error("儲存失敗,請檢查欄位");
}
});
};
return (
定義新的生產配方
{errors.product_id}
}{errors.code}
}{errors.name}
}{errors.yield_quantity}
}{errors.items}
}