Files
canina/frontend/admin-panel/src/pages/PrescriptionsManager.tsx
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- 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.
2026-10-13 16:01:00 +00:00

421 lines
19 KiB
TypeScript

import { Cat,CheckCircle2,Clock,Dog,Eye,FileText,Filter,Package,User,XCircle } from 'lucide-react';
import { useEffect,useState } from 'react';
import { toast } from 'react-hot-toast';
import Badge from '../components/ui/Badge';
import Button from '../components/ui/Button';
import ImagePreviewModal from '../components/ui/ImagePreviewModal';
import Modal from '../components/ui/Modal';
import Spinner from '../components/ui/Spinner';
import api,{ BASE_DOMAIN } from '../services/api';
import type { Prescription } from '../types/admin';
interface ProductItem {
id: string;
name: string;
price: number;
slug?: string;
image?: string;
}
export default function PrescriptionsManager() {
const [prescriptions, setPrescriptions] = useState<Prescription[]>([]);
const [products, setProducts] = useState<ProductItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [statusFilter, setStatusFilter] = useState<string>('ALL');
// Review Modal State
const [selectedRx, setSelectedRx] = useState<Prescription | null>(null);
const [reviewStatus, setReviewStatus] = useState<'APPROVED' | 'REJECTED' | 'PENDING'>('APPROVED');
const [adminNotes, setAdminNotes] = useState('');
const [selectedProductIds, setSelectedProductIds] = useState<string[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [previewImageUrl, setPreviewImageUrl] = useState<string | null>(null);
const fetchPrescriptions = async () => {
try {
const res = await api.get('/prescriptions');
const data = Array.isArray(res.data) ? res.data : (res.data?.data || []);
setPrescriptions(data);
} catch (err) {
console.error('Failed to fetch prescriptions:', err);
toast.error('خطا در دریافت لیست نسخه‌های پزشکی');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
let isMounted = true;
Promise.all([
api.get('/prescriptions'),
api.get('/products?limit=100').catch(() => ({ data: { data: [] } }))
])
.then(([rxRes, prodRes]) => {
if (!isMounted) return;
const rxData = Array.isArray(rxRes.data) ? rxRes.data : (rxRes.data?.data || []);
setPrescriptions(rxData);
const prodData = Array.isArray(prodRes.data) ? prodRes.data : (prodRes.data?.data || []);
setProducts(prodData);
})
.catch(err => {
console.error('Failed to load prescriptions or products:', err);
toast.error('خطا در بارگذاری اطلاعات');
})
.finally(() => {
if (isMounted) setIsLoading(false);
});
return () => {
isMounted = false;
};
}, []);
const openReviewModal = (rx: Prescription) => {
setSelectedRx(rx);
setReviewStatus(rx.status === 'REJECTED' ? 'REJECTED' : 'APPROVED');
// Parse existing admin notes and product attachments if stored as JSON or text
let existingNotes = rx.adminNotes || '';
let existingProductIds: string[] = [];
if (existingNotes.includes('__PRESCRIBED_PRODUCTS__:')) {
const parts = existingNotes.split('__PRESCRIBED_PRODUCTS__:');
existingNotes = parts[0].trim();
try {
existingProductIds = JSON.parse(parts[1]);
} catch {
existingProductIds = [];
}
}
setAdminNotes(existingNotes);
setSelectedProductIds(existingProductIds);
};
const handleReviewSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedRx) return;
try {
setIsSubmitting(true);
let finalAdminNotes = adminNotes.trim();
if (selectedProductIds.length > 0) {
finalAdminNotes += `\n__PRESCRIBED_PRODUCTS__:${JSON.stringify(selectedProductIds)}`;
}
await api.patch(`/prescriptions/${selectedRx.id}/review`, {
status: reviewStatus,
adminNotes: finalAdminNotes || undefined,
});
toast.success(`نسخه پزشکی با موفقیت ${reviewStatus === 'APPROVED' ? 'تایید و پیامک ارسال' : 'بررسی'} شد`);
setSelectedRx(null);
fetchPrescriptions();
} catch (err) {
console.error('Failed to review prescription:', err);
toast.error('خطا در تغییر وضعیت نسخه پزشکی');
} finally {
setIsSubmitting(false);
}
};
const getFileFullUrl = (url: string) => {
if (!url) return '';
if (url.startsWith('http')) return url;
return url.startsWith('/') ? `${BASE_DOMAIN}${url}` : `${BASE_DOMAIN}/${url}`;
};
const filteredPrescriptions = prescriptions.filter(rx => {
if (statusFilter === 'ALL') return true;
return rx.status === statusFilter;
});
return (
<div className="space-y-6 font-vazir text-right" dir="rtl">
<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">
<FileText className="w-6 h-6 text-purple-600" />
داشبورد بررسی نسخه‌های پزشکی (Prescriptions)
</h2>
<p className="text-gray-500 font-medium mt-1">
بررسی تخصصی نسخه‌های ارسال شده، تجویز مکمل‌های مناسب کنینا و ارسال پیامک خودکار به کاربر
</p>
</div>
{/* Status Filters */}
<div className="flex items-center gap-2 bg-white p-1.5 rounded-2xl border border-gray-200 shadow-xs">
<Filter className="w-4 h-4 text-gray-400 mr-2" />
{[
{ id: 'ALL', label: 'همه' },
{ id: 'PENDING', label: 'در انتظار بررسی' },
{ id: 'APPROVED', label: 'تایید شده' },
{ id: 'REJECTED', label: 'رد شده' },
].map(f => (
<button
key={f.id}
onClick={() => setStatusFilter(f.id)}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${
statusFilter === f.id
? 'bg-purple-600 text-white shadow-xs'
: 'text-gray-600 hover:bg-gray-50'
}`}
>
{f.label}
</button>
))}
</div>
</div>
<div className="bg-white rounded-2xl shadow-xs 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-xs font-black text-gray-500">تاریخ / شناسه</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">مشخصات سرپرست و همدم</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">فایل نسخه</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">توضیحات کاربر</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">وضعیت</th>
<th className="py-4 px-6 text-xs font-black text-gray-500 w-32">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{isLoading ? (
<tr>
<td colSpan={6} className="py-12 text-center">
<Spinner size="lg" className="mx-auto text-purple-600" />
</td>
</tr>
) : filteredPrescriptions.length === 0 ? (
<tr>
<td colSpan={6} className="py-12 text-center text-gray-500 font-medium">هیچ نسخه‌ای با این فیلتر یافت نشد</td>
</tr>
) : (
filteredPrescriptions.map((rx: Prescription) => {
const fullFile = getFileFullUrl(rx.fileUrl);
return (
<tr key={rx.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6">
<div className="flex flex-col">
<span className="font-mono text-xs font-bold text-gray-800">{rx.id.slice(0, 8)}...</span>
<span className="text-[11px] text-gray-400 mt-0.5">
{rx.createdAt ? new Date(rx.createdAt).toLocaleDateString('fa-IR') : '-'}
</span>
</div>
</td>
<td className="py-4 px-6">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-1.5 text-xs font-bold text-gray-900">
<User className="w-3.5 h-3.5 text-gray-400" />
<span>{rx.user ? `${rx.user.firstName || ''} ${rx.user.lastName || ''}`.trim() || rx.user.mobile : 'کاربر مهمان'}</span>
</div>
{rx.user?.mobile && (
<span className="text-[11px] font-mono text-gray-500">{rx.user.mobile}</span>
)}
{rx.pet ? (
<div className="flex items-center gap-1 text-[11px] text-purple-700 font-bold mt-1">
{rx.pet.type === 'گربه' ? <Cat className="w-3 h-3" /> : <Dog className="w-3 h-3" />}
<span>{rx.pet.name} ({rx.pet.breed || rx.pet.type})</span>
</div>
) : (
<span className="text-[10px] text-gray-400">بدون نام پت</span>
)}
</div>
</td>
<td className="py-4 px-6">
<button
type="button"
onClick={() => setPreviewImageUrl(fullFile)}
className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-purple-50 text-purple-700 text-xs font-bold rounded-xl border border-purple-100 hover:bg-purple-100 transition-colors cursor-pointer"
>
<Eye className="w-3.5 h-3.5" />
مشاهده تصویر نسخه
</button>
</td>
<td className="py-4 px-6 text-gray-600 text-xs max-w-xs line-clamp-2">
{rx.notes || '-'}
</td>
<td className="py-4 px-6">
{rx.status === 'APPROVED' ? (
<Badge variant="success" icon={<CheckCircle2 className="w-3.5 h-3.5" />}>تایید شده</Badge>
) : rx.status === 'REJECTED' ? (
<Badge variant="danger" icon={<XCircle className="w-3.5 h-3.5" />}>رد شده</Badge>
) : (
<Badge variant="warning" icon={<Clock className="w-3.5 h-3.5" />}>در انتظار بررسی</Badge>
)}
</td>
<td className="py-4 px-6">
<Button
variant="primary"
size="xs"
onClick={() => openReviewModal(rx)}
>
بررسی و تجویز
</Button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
{/* Review Modal */}
{selectedRx && (
<Modal
isOpen={!!selectedRx}
onClose={() => setSelectedRx(null)}
title="بررسی و ثبت نظر تخصصی نسخه"
icon={FileText}
maxWidth="2xl"
footer={
<div className="flex justify-end gap-2.5 w-full">
<Button
variant="secondary"
size="sm"
type="button"
onClick={() => setSelectedRx(null)}
>
انصراف
</Button>
<Button
variant="primary"
size="sm"
type="submit"
form="prescriptionForm"
isLoading={isSubmitting}
>
ثبت نهایی و ارسال پیامک
</Button>
</div>
}
>
<div className="space-y-5 text-right font-vazir">
<form id="prescriptionForm" onSubmit={handleReviewSubmit} className="space-y-5">
{/* Pet & User Details Card */}
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-200 text-xs space-y-2">
<div className="flex items-center justify-between">
<span className="font-bold text-gray-700">سرپرست: {selectedRx.user ? `${selectedRx.user.firstName || ''} ${selectedRx.user.lastName || ''}`.trim() || selectedRx.user.mobile : 'کاربر مهمان'}</span>
<span className="font-mono text-gray-600">{selectedRx.user?.mobile || '-'}</span>
</div>
{selectedRx.pet && (
<div className="pt-2 border-t border-gray-200 flex items-center justify-between text-purple-900 font-bold">
<span>همدم: {selectedRx.pet.name} ({selectedRx.pet.type} - {selectedRx.pet.breed})</span>
<span>وزن: {selectedRx.pet.weight} kg | سن: {selectedRx.pet.age} سال</span>
</div>
)}
{selectedRx.notes && (
<div className="pt-2 border-t border-gray-200 text-gray-500">
<span className="font-bold text-gray-700">توضیحات کاربر: </span>
{selectedRx.notes}
</div>
)}
<div className="pt-2 border-t border-gray-200 flex justify-between items-center">
<Button
type="button"
variant="outline"
size="xs"
startIcon={Eye}
onClick={() => setPreviewImageUrl(getFileFullUrl(selectedRx.fileUrl))}
>
مشاهده تصویر نسخه بارگذاری شده
</Button>
<span className="text-[11px] text-gray-400 font-mono">
تاریخ ثبت: {selectedRx.createdAt ? new Date(selectedRx.createdAt).toLocaleDateString('fa-IR') : '-'}
</span>
</div>
</div>
{/* Action Decision */}
<div>
<label className="block text-xs font-black text-gray-700 mb-2">تصمیم بالینی و وضعیت تایید *</label>
<div className="grid grid-cols-3 gap-3">
{[
{ id: 'APPROVED', label: 'تایید نسخه و پیشنهاد دارو', color: 'border-green-500 bg-green-50 text-green-700' },
{ id: 'REJECTED', label: 'عدم تایید / ناخوانا', color: 'border-red-500 bg-red-50 text-red-700' },
{ id: 'PENDING', label: 'در انتظار پیگیری بیمار', color: 'border-amber-500 bg-amber-50 text-amber-700' },
].map((s) => (
<button
type="button"
key={s.id}
onClick={() => setReviewStatus(s.id as any)}
className={`p-3 rounded-2xl border text-xs font-bold text-center transition-all cursor-pointer ${
reviewStatus === s.id
? `${s.color} shadow-xs ring-2 ring-purple-600/20`
: 'border-gray-200 text-gray-600 hover:border-gray-300'
}`}
>
{s.label}
</button>
))}
</div>
</div>
{/* Recommended Products Selector */}
<div>
<label className="block text-xs font-black text-gray-700 mb-1">
داروها و مکمل‌های تجویزی (انتخاب از محصولات سایت برای خرید فوری سرپرست)
</label>
<p className="text-[11px] text-gray-400 mb-2">محصولاتی که تیک می‌زنید مستقیماً در پنل کاربر به عنوان سبد پیشنهادی نسخه قرار می‌گیرند.</p>
<div className="max-h-48 overflow-y-auto border border-gray-200 rounded-2xl p-2 space-y-1 bg-white">
{products.map((p) => {
const isSelected = selectedProductIds.includes(p.id);
return (
<div
key={p.id}
onClick={() => {
setSelectedProductIds((prev) =>
isSelected ? prev.filter((id) => id !== p.id) : [...prev, p.id]
);
}}
className={`p-2 rounded-lg text-xs font-bold flex items-center justify-between cursor-pointer transition-colors ${
isSelected ? 'bg-purple-100 text-purple-900' : 'hover:bg-gray-50 text-gray-700'
}`}
>
<div className="flex items-center gap-2 truncate">
<Package className="w-3.5 h-3.5 shrink-0 text-purple-600" />
<span className="truncate">{p.name}</span>
</div>
<span className="text-[11px] font-mono text-gray-500 shrink-0">
{p.price ? `${p.price.toLocaleString('fa-IR')} تومان` : ''}
</span>
</div>
);
})}
</div>
</div>
{/* Doctor / Admin Clinical Note */}
<div>
<label className="block text-xs font-black text-gray-700 mb-1">
توضیحات و دستور مصرف داروها برای بیمار (پیام به کاربر)
</label>
<textarea
rows={3}
value={adminNotes}
onChange={(e) => setAdminNotes(e.target.value)}
placeholder="مثال: نسخه تایید شد. مکمل کانین ایمون روزانه ۱ قرص به همراه وعده غذایی مصرف شود."
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs leading-relaxed"
/>
</div>
</form>
</div>
</Modal>
)}
{/* Fullscreen Lightbox for Prescription Image */}
<ImagePreviewModal
isOpen={!!previewImageUrl}
imageUrl={previewImageUrl || ''}
onClose={() => setPreviewImageUrl(null)}
title="تصویر نسخه پزشکی بیمار"
/>
</div>
);
}