diff --git a/backend/src/products/products.controller.ts b/backend/src/products/products.controller.ts index 6850eb03..8d9eac02 100644 --- a/backend/src/products/products.controller.ts +++ b/backend/src/products/products.controller.ts @@ -61,6 +61,22 @@ export class ProductsController { return this.productsService.findAll(query); } + @Get('filters') + @ApiOperation({ summary: 'دریافت فیلترهای فعال محصولات (دسته، علائم، نوع پت)' }) + @ApiOkResponse({ + description: 'لیست فیلترهای پویا استخراج شده از دیتابیس', + schema: { + example: { + categories: [{ id: '1', name: 'مفاصل و استخوان', slug: 'joints' }], + symptoms: ['لنگش', 'ریزش مو'], + petTypes: ['سگ', 'گربه', 'هر دو'] + } + } + }) + getActiveFilters() { + return this.productsService.getActiveFilters(); + } + @Get(':id') @ApiOperation({ summary: 'دریافت اطلاعات محصول با شناسه یکتا (ID)' }) @ApiOkResponse({ diff --git a/backend/src/products/products.service.ts b/backend/src/products/products.service.ts index e973a366..41c9dd9b 100644 --- a/backend/src/products/products.service.ts +++ b/backend/src/products/products.service.ts @@ -63,4 +63,39 @@ export class ProductsService { }, }); } + + async getActiveFilters() { + const [categories, symptomsDb, petTypesDb] = await Promise.all([ + this.prisma.category.findMany({ + where: { + products: { + some: {} + } + }, + select: { + id: true, + name: true, + slug: true, + } + }), + this.prisma.productSymptom.findMany({ + distinct: ['symptom'], + select: { + symptom: true, + } + }), + this.prisma.product.findMany({ + distinct: ['suitableFor'], + select: { + suitableFor: true, + } + }) + ]); + + return { + categories, + symptoms: symptomsDb.map(s => s.symptom).filter(Boolean), + petTypes: petTypesDb.map(p => p.suitableFor).filter(Boolean), + }; + } } diff --git a/frontend/application/app/shop/page.tsx b/frontend/application/app/shop/page.tsx index 228a0a3f..59f453ce 100644 --- a/frontend/application/app/shop/page.tsx +++ b/frontend/application/app/shop/page.tsx @@ -21,6 +21,15 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [ const resolvedParams = await searchParams; const category = typeof resolvedParams.category === 'string' ? resolvedParams.category : "all"; const search = typeof resolvedParams.search === 'string' ? resolvedParams.search : ""; + const petType = typeof resolvedParams.petType === 'string' ? resolvedParams.petType : "all"; + const symptoms = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : ""; - return ; + return ( + + ); } diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index 10f8bd30..d129baad 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -26,15 +26,14 @@ import { import { useCartStore } from "../lib/store/cartStore"; import SafeImage from "./SafeImage"; -const CATEGORIES = [ - { id: "all", label: "همه محصولات", icon: }, - { id: "joints", label: "مفاصل و استخوان", icon: }, - { id: "immune", label: "ایمنی و گوارش", icon: }, - { id: "energy", label: "ویتامین و انرژی", icon: }, - { id: "special-care", label: "مراقبت ویژه", icon: }, - { id: "general", label: "تقویت عمومی", icon: }, - { id: "nutrition", label: "تغذیه تخصصی", icon: }, -]; +const ICON_MAP: Record = { + joints: , + immune: , + energy: , + "special-care": , + general: , + nutrition: , +}; const CATEGORY_MAP: Record = { // Main Categories @@ -67,10 +66,6 @@ const CATEGORY_MAP: Record void }> = ({ product, onClick }) => { const { addItem } = useCartStore(); const [isAdding, setIsAdding] = useState(false); @@ -168,40 +163,59 @@ import { useRouter } from 'next/navigation'; export default function ArchivePage({ initialCategory = "all", - initialSearch = "" + initialSearch = "", + initialPetType = "all", + initialSymptoms = "" }: { initialCategory?: string, - initialSearch?: string + initialSearch?: string, + initialPetType?: string, + initialSymptoms?: string }) { const router = useRouter(); const [selectedCategory, setSelectedCategory] = useState(initialCategory); - const [selectedPet, setSelectedPet] = useState("all"); - const [activeSymptoms, setActiveSymptoms] = useState([]); + const [selectedPet, setSelectedPet] = useState(initialPetType as any); + const [activeSymptoms, setActiveSymptoms] = useState(initialSymptoms ? initialSymptoms.split(',') : []); const [searchQuery, setSearchQuery] = useState(initialSearch); const [isUpdating, setIsUpdating] = useState(false); const [filteredProducts, setFilteredProducts] = useState([]); const [page, setPage] = useState(1); const [meta, setMeta] = useState({ total: 0, lastPage: 1 }); - const CATEGORY_LABELS: Record = { - all: "همه محصولات", - joints: "مفاصل و استخوان", - immune: "ایمنی و گوارش", - energy: "ویتامین و انرژی", - "special-care": "مراقبت ویژه", - general: "تقویت عمومی", - nutrition: "تغذیه تخصصی", - }; + const [categories, setCategories] = useState<{ id: string; label: string; icon: React.ReactNode }[]>([]); + const [symptoms, setSymptoms] = useState([]); - // Debug Log for Search Params useEffect(() => { - console.log("[ArchivePage] URL Params Sync:", { initialCategory, initialSearch }); - }, [initialCategory, initialSearch]); + const loadFilters = async () => { + try { + const filters = await productService.getActiveFilters(); + const mapped = [ + { id: "all", label: "همه محصولات", icon: }, + ...filters.categories.map(c => ({ + id: c.slug, + label: c.name, + icon: ICON_MAP[c.slug] || + })) + ]; + setCategories(mapped); + setSymptoms(filters.symptoms); + } catch (e) { + console.error("Failed to load active filters:", e); + } + }; + loadFilters(); + }, []); + + const CATEGORY_LABELS = useMemo(() => { + const labels: Record = { all: "همه محصولات" }; + categories.forEach(c => { + labels[c.id] = c.label; + }); + return labels; + }, [categories]); // Sync state with prop change (e.g. from Header menu) useEffect(() => { - setIsUpdating(true); - // Normalize Input (Trim and lowercase) const normSearch = (initialSearch || "").trim().toLowerCase(); const normCat = initialCategory.trim().toLowerCase(); @@ -209,8 +223,12 @@ export default function ArchivePage({ const mapKey = normSearch || normCat; const mapping = CATEGORY_MAP[mapKey]; - console.log("[ArchivePage] Processing Mapping for:", mapKey); + if (selectedCategory === initialCategory && searchQuery === initialSearch) { + return; + } + setIsUpdating(true); + // Reset ALL other filters when a new category/solution is selected from menu setSelectedPet("all"); setActiveSymptoms([]); @@ -226,7 +244,7 @@ export default function ArchivePage({ setSelectedCategory(initialCategory); setSearchQuery(initialSearch); - if (initialSearch && SYMPTOMS.includes(initialSearch)) { + if (initialSearch && symptoms.includes(initialSearch)) { setActiveSymptoms([initialSearch]); } } @@ -236,7 +254,20 @@ export default function ArchivePage({ }, 400); return () => clearTimeout(timer); - }, [initialCategory, initialSearch]); + }, [initialCategory, initialSearch, symptoms]); + + // Update URL Query Parameters + useEffect(() => { + const params = new URLSearchParams(); + if (selectedCategory && selectedCategory !== "all") params.set('category', selectedCategory); + if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet); + if (searchQuery) params.set('search', searchQuery); + if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(',')); + + const queryString = params.toString(); + const newUrl = `/shop${queryString ? `?${queryString}` : ''}`; + router.push(newUrl, { scroll: false }); + }, [selectedCategory, selectedPet, searchQuery, activeSymptoms]); useEffect(() => { const fetchProducts = async () => { @@ -365,7 +396,7 @@ export default function ArchivePage({ راهکار درمانی - {CATEGORIES.map(cat => ( + {categories.map(cat => ( setSelectedCategory(cat.id)} @@ -382,7 +413,7 @@ export default function ArchivePage({ جستجو بر اساس علائم - {SYMPTOMS.map(s => ( + {symptoms.map(s => ( toggleSymptom(s)} diff --git a/frontend/application/lib/services/productService.ts b/frontend/application/lib/services/productService.ts index fdc4d238..8a1bd613 100644 --- a/frontend/application/lib/services/productService.ts +++ b/frontend/application/lib/services/productService.ts @@ -154,6 +154,20 @@ export class ProductService { return []; } } + + public async getActiveFilters(): Promise<{ + categories: { id: string; name: string; slug: string }[]; + symptoms: string[]; + petTypes: string[]; + }> { + try { + const response = await api.get('/products/filters'); + return response.data; + } catch (error) { + console.error("[ProductService] Failed to fetch active filters:", error); + return { categories: [], symptoms: [], petTypes: [] }; + } + } } export const productService = ProductService.getInstance();