From c7b95b4d2b28535131b61a5acaf7cc8e052ef36a Mon Sep 17 00:00:00 2001 From: devops Date: Sun, 18 Oct 2026 13:26:01 +0000 Subject: [PATCH] feat: dock PDP buy bar above mobile nav, redesign B2B modal to mobile-card layout, and implement full symptoms CRUD in backend & admin panel --- backend/src/admin/admin.controller.ts | 33 +- backend/src/admin/admin.service.ts | 167 ++++++--- .../admin-panel/src/components/Sidebar.tsx | 1 + .../admin-panel/src/pages/SymptomsPage.tsx | 321 ++++++++++++++++++ .../admin-panel/src/routes/adminRoutes.tsx | 4 + frontend/application/components/B2BPortal.tsx | 94 ++++- .../application/components/ProductPage.tsx | 4 +- 7 files changed, 555 insertions(+), 69 deletions(-) create mode 100644 frontend/admin-panel/src/pages/SymptomsPage.tsx diff --git a/backend/src/admin/admin.controller.ts b/backend/src/admin/admin.controller.ts index 18e238ef..d879e392 100644 --- a/backend/src/admin/admin.controller.ts +++ b/backend/src/admin/admin.controller.ts @@ -355,18 +355,33 @@ export class AdminController { return { success: true, data: body }; } + @Get("symptoms") - @ApiOperation({ summary: "لیست کامل علائم درمانی به همراه تعداد محصولات متصل" }) - async getAllSymptoms() { - const data = await this.adminService.getAllSymptoms(); - return { success: true, data }; + @ApiOperation({ summary: "لیست کامل علائم درمانی با صفحه‌بندی، جستجو و متادیتا" }) + async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) { + const res = await this.adminService.getSymptoms(query); + return { success: true, ...res }; } - @Put("symptoms/rename") - @ApiOperation({ summary: "تغییر نام یکپارچه یک علامت در سراسر محصولات و دیتابیس" }) - async renameSymptom(@Body() body: { oldName: string; newName: string }) { - const result = await this.adminService.renameSymptom(body.oldName, body.newName); - return result; + @Post("symptoms") + @ApiOperation({ summary: "افزودن علامت درمانی جدید" }) + async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) { + const res = await this.adminService.createSymptom(body); + return { success: true, data: res }; + } + + @Put("symptoms/:id") + @ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" }) + async updateSymptom(@Param("id") id: string, @Body() body: any) { + const res = await this.adminService.updateSymptom(id, body); + return { success: true, data: res }; + } + + @Delete("symptoms/:id") + @ApiOperation({ summary: "حذف علامت درمانی" }) + async deleteSymptom(@Param("id") id: string) { + const res = await this.adminService.deleteSymptom(id); + return { success: true, ...res }; } } diff --git a/backend/src/admin/admin.service.ts b/backend/src/admin/admin.service.ts index 74307860..df5f5055 100644 --- a/backend/src/admin/admin.service.ts +++ b/backend/src/admin/admin.service.ts @@ -1870,63 +1870,134 @@ export class AdminService { }); } - async getAllSymptoms() { - const rawSymptoms = await this.prisma.productSymptom.groupBy({ - by: ['symptom'], - _count: { - productId: true, - }, - orderBy: { - symptom: 'asc', - }, - }); + + async getSymptoms(params?: { page?: number; limit?: number; search?: string }) { + const page = Math.max(1, Number(params?.page) || 1); + const limit = Math.max(1, Number(params?.limit) || 20); + const offset = (page - 1) * limit; + const search = params?.search?.trim() || ''; - return rawSymptoms.map((s) => ({ - name: s.symptom, - productsCount: s._count.productId, - })); + const whereClause = search ? `WHERE s.name ILIKE '%${search}%' OR s.slug ILIKE '%${search}%'` : ''; + + const listQuery = ` + SELECT + s.id, + s.name, + s.slug, + s.description, + s.meta_title as "metaTitle", + s.meta_description as "metaDescription", + s.keywords, + s.icon, + s.created_at as "createdAt", + COALESCE(COUNT(ps.product_id), 0)::int as "productsCount" + FROM symptoms s + LEFT JOIN product_symptoms ps ON ps.symptom = s.name + ${whereClause} + GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at + ORDER BY s.name ASC + LIMIT ${limit} OFFSET ${offset}; + `; + + const countQuery = ` + SELECT COUNT(*)::int as total + FROM symptoms s + ${whereClause}; + `; + + const [items, totalRes] = await Promise.all([ + this.prisma.$queryRawUnsafe(listQuery), + this.prisma.$queryRawUnsafe(countQuery), + ]); + + const total = totalRes[0]?.total || 0; + const lastPage = Math.ceil(total / limit) || 1; + + return { + data: items, + meta: { + page, + limit, + total, + lastPage, + }, + }; } - async renameSymptom(oldName: string, newName: string) { - if (!oldName?.trim() || !newName?.trim()) { - throw new BadRequestException('نام قبلی و جدید علامت الزامی است'); - } - const cleanOld = oldName.trim(); - const cleanNew = newName.trim(); + async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) { + if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است'); + const name = dto.name.trim(); + const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase(); + + return await this.prisma.$queryRawUnsafe(` + INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords; + `, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || ''); + } + + async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) { + // 1. Get existing symptom + const existing = await this.prisma.$queryRawUnsafe(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id); + if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد'); + const oldName = existing[0].name; + const newName = dto.name?.trim() || oldName; + const newSlug = dto.slug?.trim() || existing[0].slug; return await this.prisma.$transaction(async (tx) => { - // 1. Rename in product_symptoms join table - const updatedJoin = await tx.$executeRaw` - UPDATE product_symptoms - SET symptom = ${cleanNew} - WHERE symptom = ${cleanOld}; - `; + // Update symptoms table + const updated = await tx.$queryRawUnsafe(` + UPDATE symptoms + SET + name = $2, + slug = $3, + description = $4, + meta_title = $5, + meta_description = $6, + keywords = $7, + updated_at = CURRENT_TIMESTAMP + WHERE id = $1::uuid + RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords; + `, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords); - // 2. Cascade rename in products.dosage_config->'symptoms' jsonb array - await tx.$executeRaw` - UPDATE products - SET dosage_config = jsonb_set( - dosage_config, - '{symptoms}', - ( - SELECT jsonb_agg( - CASE - WHEN elem::text = to_jsonb(${cleanOld}::text)::text THEN to_jsonb(${cleanNew}::text) - ELSE elem - END + // If name changed, cascade update across product_symptoms & products JSON + if (oldName !== newName) { + await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`; + await tx.$executeRaw` + UPDATE products + SET dosage_config = jsonb_set( + dosage_config, + '{symptoms}', + ( + SELECT jsonb_agg( + CASE + WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text) + ELSE elem + END + ) + FROM jsonb_array_elements(dosage_config->'symptoms') AS elem ) - FROM jsonb_array_elements(dosage_config->'symptoms') AS elem ) - ) - WHERE dosage_config ? 'symptoms' - AND dosage_config->'symptoms' @> to_jsonb(${cleanOld}::text); - `; + WHERE dosage_config ? 'symptoms' + AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text); + `; + } - return { - success: true, - message: `علامت «${cleanOld}» با موفقیت به «${cleanNew}» در سراسر سیستم تغییر یافت`, - updatedCount: updatedJoin, - }; + return updated; + }); + } + + async deleteSymptom(id: string) { + const existing = await this.prisma.$queryRawUnsafe(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id); + if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد'); + const name = existing[0].name; + + return await this.prisma.$transaction(async (tx) => { + // Delete join links + await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`; + // Delete symptom row + await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id); + return { success: true, message: `علامت «${name}» با موفقیت حذف شد` }; }); } diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index c6c20151..95a6a148 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -157,6 +157,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side { icon: Package, label: 'لیست محصولات', path: '/products' }, { icon: Star, label: 'نظرات و امتیازات', path: '/reviews' }, { icon: FolderTree, label: 'دسته‌بندی‌های تخصصی', path: '/categories' }, + { icon: Activity, label: 'علائم بالینی و درمانی', path: '/symptoms' }, { icon: Tag, label: 'کدهای تخفیف', path: '/coupons' }, { icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' }, { icon: FileText, label: 'نسخه‌های دریافتی', path: '/prescriptions' }, diff --git a/frontend/admin-panel/src/pages/SymptomsPage.tsx b/frontend/admin-panel/src/pages/SymptomsPage.tsx new file mode 100644 index 00000000..fa41dc63 --- /dev/null +++ b/frontend/admin-panel/src/pages/SymptomsPage.tsx @@ -0,0 +1,321 @@ +import { Edit2, Plus, Search, Trash2, Activity, Tag, Sparkles } from 'lucide-react'; +import { useCallback, useEffect, useState } from 'react'; +import { toast } from 'react-hot-toast'; +import Button from '../components/ui/Button'; +import ConfirmModal from '../components/ui/ConfirmModal'; +import Modal from '../components/ui/Modal'; +import Pagination from '../components/ui/Pagination'; +import Spinner from '../components/ui/Spinner'; +import api from '../services/api'; +import { useSearchParams } from 'react-router-dom'; + +export interface Symptom { + id: string; + name: string; + slug: string; + description?: string; + metaTitle?: string; + metaDescription?: string; + keywords?: string; + productsCount?: number; + createdAt?: string; +} + +export default function SymptomsPage() { + const [searchParams, setSearchParams] = useSearchParams(); + const [symptoms, setSymptoms] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [search, setSearch] = useState(() => searchParams.get('search') || ''); + const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1); + const [totalPages, setTotalPages] = useState(1); + const limit = 15; + + const [isModalOpen, setIsModalOpen] = useState(false); + const [editingSymptom, setEditingSymptom] = useState(null); + const [deleteTargetId, setDeleteTargetId] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); + + const [formData, setFormData] = useState({ + name: '', + slug: '', + description: '', + metaTitle: '', + metaDescription: '', + keywords: '' + }); + + const openModal = (symptom: Symptom | null = null) => { + if (symptom) { + setEditingSymptom(symptom); + setFormData({ + name: symptom.name, + slug: symptom.slug, + description: symptom.description || '', + metaTitle: symptom.metaTitle || '', + metaDescription: symptom.metaDescription || '', + keywords: symptom.keywords || '' + }); + } else { + setEditingSymptom(null); + setFormData({ + name: '', + slug: '', + description: '', + metaTitle: '', + metaDescription: '', + keywords: '' + }); + } + setIsModalOpen(true); + }; + + const closeModal = () => { + setIsModalOpen(false); + }; + + const fetchSymptoms = useCallback(async () => { + try { + setIsLoading(true); + const res = await api.get('/admin/symptoms', { params: { page, limit, search } }); + if (res.data?.data) { + setSymptoms(res.data.data); + setTotalPages(res.data.meta?.lastPage || 1); + } + } catch { + toast.error('خطا در دریافت لیست علائم'); + } finally { + setIsLoading(false); + } + }, [page, search]); + + useEffect(() => { + fetchSymptoms(); + }, [fetchSymptoms]); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + if (!formData.name.trim()) { + toast.error('نام علامت الزامی است'); + return; + } + + try { + setIsSubmitting(true); + if (editingSymptom) { + await api.put(`/admin/symptoms/${editingSymptom.id}`, formData); + toast.success('علامت با موفقیت ویرایش و در تمامی محصولات همگام شد'); + } else { + await api.post('/admin/symptoms', formData); + toast.success('علامت درمانی جدید با موفقیت ایجاد شد'); + } + closeModal(); + fetchSymptoms(); + } catch { + toast.error('خطا در ذخیره اطلاعات علامت'); + } finally { + setIsSubmitting(false); + } + }; + + const handleDelete = async () => { + if (!deleteTargetId) return; + try { + await api.delete(`/admin/symptoms/${deleteTargetId}`); + toast.success('علامت با موفقیت حذف شد'); + setDeleteTargetId(null); + fetchSymptoms(); + } catch { + toast.error('خطا در حذف علامت'); + } + }; + + return ( +
+ {/* Header */} +
+
+
+ + + +

مدیریت علائم بالینی و درمانی

+
+

+ تعریف و ویرایش علائم، بهینه‌سازی متادیتاهای سئو و همگام‌سازی یکپارچه با محصولات کاتالوگ +

+
+ +
+ + {/* Filter & Search */} +
+
+ + { + setSearch(e.target.value); + setPage(1); + }} + className="w-full bg-gray-50 border border-gray-200 rounded-2xl py-2.5 pr-10 pl-4 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20" + /> +
+
+ + {/* Table */} +
+ {isLoading ? ( +
+ +
+ ) : symptoms.length === 0 ? ( +
+ هیچ علامت بالینی یافت نشد. +
+ ) : ( +
+ + + + + + + + + + + + {symptoms.map((symptom) => ( + + + + + + + + ))} + +
نام علامت بالینیاسلاگ URLمحصولات متصلسئو متاتایتلعملیات
+ + {symptom.name} + + {symptom.slug} + + + {symptom.productsCount || 0} محصول + + + {symptom.metaTitle || '—'} + + + +
+
+ )} + +
+ setPage(p)} /> +
+
+ + {/* Modal CRUD */} + +
+
+ + setFormData({ ...formData, name: e.target.value })} + className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20" + placeholder="مثلاً: پوکی استخوان یا کم‌خونی" + /> +
+ +
+ + setFormData({ ...formData, slug: e.target.value })} + className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs dir-ltr focus:outline-none focus:ring-2 focus:ring-purple-500/20" + placeholder="anemia یا osteoporosis" + /> +
+ +
+ +