- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
449 lines
18 KiB
TypeScript
449 lines
18 KiB
TypeScript
import { Edit2,FlaskConical,Plus,Tag,Trash2,X } from 'lucide-react';
|
|
import { useEffect,useState } from 'react';
|
|
import { toast } from 'react-hot-toast';
|
|
import Button from '../components/ui/Button';
|
|
import ConfirmModal from '../components/ui/ConfirmModal';
|
|
import MediaSelector from '../components/ui/MediaSelector';
|
|
import Modal from '../components/ui/Modal';
|
|
import Spinner from '../components/ui/Spinner';
|
|
import api,{ BASE_DOMAIN } from '../services/api';
|
|
import type { Ingredient } from '../types/admin';
|
|
|
|
|
|
export default function IngredientsManager() {
|
|
const [ingredients, setIngredients] = useState<Ingredient[]>([]);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
|
const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false);
|
|
const [editingIngredient, setEditingIngredient] = useState<Ingredient | null>(null);
|
|
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
|
const [isSaving, setIsSaving] = useState(false);
|
|
|
|
// Benefits tags handling
|
|
const [benefitInput, setBenefitInput] = useState('');
|
|
|
|
const [formData, setFormData] = useState({
|
|
nameFa: '',
|
|
nameEn: '',
|
|
slug: '',
|
|
scientificName: '',
|
|
description: '',
|
|
imageUrl: '',
|
|
benefits: [] as string[],
|
|
});
|
|
|
|
const fetchIngredients = async () => {
|
|
try {
|
|
const res = await api.get('/ingredients');
|
|
const data = Array.isArray(res.data) ? res.data : (res.data?.data || []);
|
|
setIngredients(data);
|
|
} catch (err) {
|
|
console.error('Failed to fetch ingredients:', err);
|
|
toast.error('خطا در دریافت لیست ترکیبات دانشنامه');
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
let isMounted = true;
|
|
api.get('/ingredients')
|
|
.then(res => {
|
|
if (!isMounted) return;
|
|
const data = Array.isArray(res.data) ? res.data : (res.data?.data || []);
|
|
setIngredients(data);
|
|
})
|
|
.catch(err => {
|
|
console.error('Failed to fetch ingredients:', err);
|
|
toast.error('خطا در دریافت لیست ترکیبات دانشنامه');
|
|
})
|
|
.finally(() => {
|
|
if (isMounted) setIsLoading(false);
|
|
});
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, []);
|
|
|
|
const openModal = (item: Ingredient | null = null) => {
|
|
if (item) {
|
|
setEditingIngredient(item);
|
|
setFormData({
|
|
nameFa: item.nameFa || '',
|
|
nameEn: item.nameEn || '',
|
|
slug: item.slug || '',
|
|
scientificName: item.scientificName || '',
|
|
description: item.description || '',
|
|
imageUrl: item.imageUrl || '',
|
|
benefits: Array.isArray(item.benefits) ? item.benefits : [],
|
|
});
|
|
} else {
|
|
setEditingIngredient(null);
|
|
setFormData({
|
|
nameFa: '',
|
|
nameEn: '',
|
|
slug: '',
|
|
scientificName: '',
|
|
description: '',
|
|
imageUrl: '',
|
|
benefits: [],
|
|
});
|
|
}
|
|
setBenefitInput('');
|
|
setIsModalOpen(true);
|
|
};
|
|
|
|
const handleSave = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!formData.nameFa.trim() || !formData.nameEn.trim()) {
|
|
toast.error('نام فارسی و انگلیسی الزامی است');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setIsSaving(true);
|
|
const slugVal = formData.slug.trim() || formData.nameEn.toLowerCase().replace(/\s+/g, '-');
|
|
const payload = {
|
|
...formData,
|
|
slug: slugVal,
|
|
};
|
|
|
|
if (editingIngredient) {
|
|
await api.patch(`/ingredients/${editingIngredient.id}`, payload);
|
|
toast.success('ترکیب با موفقیت بروزرسانی شد');
|
|
} else {
|
|
await api.post('/ingredients', payload);
|
|
toast.success('ترکیب جدید با موفقیت ایجاد شد');
|
|
}
|
|
setIsModalOpen(false);
|
|
fetchIngredients();
|
|
} catch (err) {
|
|
console.error('Failed to save ingredient:', err);
|
|
toast.error('خطا در ذخیره اطلاعات ترکیب');
|
|
} finally {
|
|
setIsSaving(false);
|
|
}
|
|
};
|
|
|
|
const confirmDelete = async () => {
|
|
if (!deleteTargetId) return;
|
|
try {
|
|
await api.delete(`/ingredients/${deleteTargetId}`);
|
|
toast.success('ترکیب با موفقیت حذف شد');
|
|
fetchIngredients();
|
|
} catch (err) {
|
|
console.error('Failed to delete ingredient:', err);
|
|
toast.error('خطا در حذف ترکیب');
|
|
} finally {
|
|
setDeleteTargetId(null);
|
|
}
|
|
};
|
|
|
|
const addBenefitTag = () => {
|
|
const val = benefitInput.trim();
|
|
if (val && !formData.benefits.includes(val)) {
|
|
setFormData({ ...formData, benefits: [...formData.benefits, val] });
|
|
setBenefitInput('');
|
|
}
|
|
};
|
|
|
|
const removeBenefitTag = (tag: string) => {
|
|
setFormData({ ...formData, benefits: formData.benefits.filter(b => b !== tag) });
|
|
};
|
|
|
|
const getImageFullUrl = (url?: string) => {
|
|
if (!url) return '';
|
|
if (url.startsWith('http')) return url;
|
|
return url.startsWith('/') ? `${BASE_DOMAIN}${url}` : `${BASE_DOMAIN}/${url}`;
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
|
<div>
|
|
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
|
<FlaskConical className="w-6 h-6 text-purple-600" />
|
|
مدیریت ترکیبات و دانشنامه علمی (Scientific Wiki)
|
|
</h2>
|
|
<p className="text-gray-500 font-medium mt-1">مدیریت مواد موثره، ترکیبات دارویی و خواص درمانی محصولات کنینا</p>
|
|
</div>
|
|
<Button
|
|
variant="primary"
|
|
size="sm"
|
|
startIcon={Plus}
|
|
onClick={() => openModal()}
|
|
>
|
|
افزودن ترکیب جدید
|
|
</Button>
|
|
</div>
|
|
|
|
|
|
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-right">
|
|
<thead className="bg-gray-50 border-b border-gray-100">
|
|
<tr>
|
|
<th className="py-4 px-6 text-sm font-bold text-gray-500">تصویر</th>
|
|
<th className="py-4 px-6 text-sm font-bold text-gray-500">نام فارسی / انگلیسی</th>
|
|
<th className="py-4 px-6 text-sm font-bold text-gray-500">نام علمی (Scientific Name)</th>
|
|
<th className="py-4 px-6 text-sm font-bold text-gray-500">خواص و مزایا</th>
|
|
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-28">عملیات</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y divide-gray-100">
|
|
{isLoading ? (
|
|
<tr>
|
|
<td colSpan={5} className="py-12 text-center">
|
|
<Spinner size="lg" className="mx-auto text-purple-600" />
|
|
</td>
|
|
</tr>
|
|
) : ingredients.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={5} className="py-12 text-center text-gray-500 font-medium">هیچ ترکیبی ثبت نشده است</td>
|
|
</tr>
|
|
) : (
|
|
ingredients.map((item) => (
|
|
<tr key={item.id} className="hover:bg-gray-50/50 transition-colors">
|
|
<td className="py-3 px-6">
|
|
<div className="w-12 h-12 rounded-xl bg-gray-100 border border-gray-200 overflow-hidden flex items-center justify-center">
|
|
{item.imageUrl ? (
|
|
<img src={getImageFullUrl(item.imageUrl)} alt={item.nameFa} className="w-full h-full object-cover" />
|
|
) : (
|
|
<FlaskConical className="w-5 h-5 text-gray-400" />
|
|
)}
|
|
</div>
|
|
</td>
|
|
<td className="py-4 px-6">
|
|
<div className="flex flex-col">
|
|
<span className="font-bold text-gray-900">{item.nameFa}</span>
|
|
<span className="text-xs font-mono text-gray-400" dir="ltr">{item.nameEn}</span>
|
|
</div>
|
|
</td>
|
|
<td className="py-4 px-6 font-mono text-xs text-purple-700 italic" dir="ltr">
|
|
{item.scientificName || '-'}
|
|
</td>
|
|
<td className="py-4 px-6">
|
|
<div className="flex flex-wrap gap-1">
|
|
{item.benefits && item.benefits.map((b, i) => (
|
|
<span key={i} className="px-2 py-0.5 bg-purple-50 text-purple-700 text-[11px] font-bold rounded-full border border-purple-100">
|
|
{b}
|
|
</span>
|
|
))}
|
|
</div>
|
|
</td>
|
|
<td className="py-4 px-6">
|
|
<div className="flex items-center gap-2">
|
|
<Button
|
|
variant="ghost"
|
|
size="xs"
|
|
startIcon={Edit2}
|
|
onClick={() => openModal(item)}
|
|
className="text-blue-600 hover:bg-blue-50"
|
|
/>
|
|
<Button
|
|
variant="ghost"
|
|
size="xs"
|
|
startIcon={Trash2}
|
|
onClick={() => setDeleteTargetId(item.id)}
|
|
className="text-red-600 hover:bg-red-50"
|
|
/>
|
|
</div>
|
|
</td>
|
|
|
|
</tr>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Modal */}
|
|
{isModalOpen && (
|
|
<Modal
|
|
isOpen={isModalOpen}
|
|
onClose={() => setIsModalOpen(false)}
|
|
title={editingIngredient ? 'ویرایش ترکیب دانشنامه' : 'افزودن ترکیب جدید'}
|
|
icon={FlaskConical}
|
|
maxWidth="2xl"
|
|
footer={
|
|
<div className="flex justify-end gap-2.5 w-full">
|
|
<Button
|
|
variant="secondary"
|
|
size="sm"
|
|
type="button"
|
|
onClick={() => setIsModalOpen(false)}
|
|
>
|
|
انصراف
|
|
</Button>
|
|
<Button
|
|
variant="primary"
|
|
size="sm"
|
|
type="submit"
|
|
form="ingredientForm"
|
|
isLoading={isSaving}
|
|
>
|
|
ذخیره تغییرات
|
|
</Button>
|
|
</div>
|
|
}
|
|
>
|
|
<div className="space-y-6 text-right font-vazir">
|
|
<form id="ingredientForm" onSubmit={handleSave} className="space-y-4">
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">نام فارسی *</label>
|
|
<input
|
|
required
|
|
type="text"
|
|
value={formData.nameFa}
|
|
onChange={(e) => setFormData({ ...formData, nameFa: e.target.value })}
|
|
placeholder="مثال: صدف لبسبز"
|
|
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">نام انگلیسی (nameEn) *</label>
|
|
<input
|
|
required
|
|
type="text"
|
|
value={formData.nameEn}
|
|
onChange={(e) => setFormData({ ...formData, nameEn: e.target.value })}
|
|
placeholder="Green-Lipped Mussel"
|
|
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-mono"
|
|
dir="ltr"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">شناسه یکتا (slug)</label>
|
|
<input
|
|
type="text"
|
|
value={formData.slug}
|
|
onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
|
|
placeholder="green-lipped-mussel"
|
|
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-mono"
|
|
dir="ltr"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">نام علمی (scientificName)</label>
|
|
<input
|
|
type="text"
|
|
value={formData.scientificName}
|
|
onChange={(e) => setFormData({ ...formData, scientificName: e.target.value })}
|
|
placeholder="Perna canaliculus"
|
|
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-mono italic"
|
|
dir="ltr"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">تصویر ترکیب</label>
|
|
<div className="flex gap-2">
|
|
<input
|
|
type="text"
|
|
value={formData.imageUrl}
|
|
onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
|
|
placeholder="آدرس تصویر یا انتخاب از رسانهها..."
|
|
className="flex-1 px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-mono"
|
|
dir="ltr"
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setIsMediaSelectorOpen(true)}
|
|
>
|
|
انتخاب از رسانه
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">خواص و مزایا</label>
|
|
<div className="space-y-2">
|
|
<div className="flex gap-2">
|
|
<input
|
|
type="text"
|
|
value={benefitInput}
|
|
onChange={(e) => setBenefitInput(e.target.value)}
|
|
onKeyDown={(e) => {
|
|
if (e.key === 'Enter') {
|
|
e.preventDefault();
|
|
addBenefitTag();
|
|
}
|
|
}}
|
|
placeholder="تایپ کنید و اینتر بزنید (مثال: ترمیم غضروف)"
|
|
className="flex-1 px-4 py-2 rounded-xl border border-gray-200 text-xs outline-none focus:border-purple-500"
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="primary"
|
|
size="xs"
|
|
onClick={addBenefitTag}
|
|
>
|
|
افزودن
|
|
</Button>
|
|
</div>
|
|
<div className="flex flex-wrap gap-1.5 p-2 bg-gray-50 rounded-xl border border-gray-100 min-h-[40px]">
|
|
{formData.benefits.map((b, i) => (
|
|
<span key={i} className="inline-flex items-center gap-1 px-2.5 py-1 bg-purple-100 text-purple-800 text-xs font-bold rounded-lg">
|
|
<Tag className="w-3 h-3" />
|
|
{b}
|
|
<button type="button" onClick={() => removeBenefitTag(b)} className="hover:text-red-500 cursor-pointer">
|
|
<X className="w-3 h-3" />
|
|
</button>
|
|
</span>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">توضیحات جامع علمی</label>
|
|
<textarea
|
|
rows={4}
|
|
value={formData.description}
|
|
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
|
placeholder="توضیحات بیوشیمیایی و خواص بالینی ماده را وارد کنید..."
|
|
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
|
|
/>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</Modal>
|
|
)}
|
|
|
|
|
|
{/* Delete Confirmation Modal */}
|
|
{deleteTargetId && (
|
|
<ConfirmModal
|
|
isOpen={Boolean(deleteTargetId)}
|
|
title="حذف ترکیب"
|
|
message="آیا از حذف این ترکیب دانشنامه اطمینان دارید؟"
|
|
onConfirm={confirmDelete}
|
|
onCancel={() => setDeleteTargetId(null)}
|
|
/>
|
|
)}
|
|
|
|
{/* Media Selector */}
|
|
{isMediaSelectorOpen && (
|
|
<MediaSelector
|
|
isOpen={isMediaSelectorOpen}
|
|
onClose={() => setIsMediaSelectorOpen(false)}
|
|
onSelect={(url) => {
|
|
setFormData({ ...formData, imageUrl: url });
|
|
setIsMediaSelectorOpen(false);
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|