import { Injectable, NotFoundException } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; @Injectable() export class CategoriesService { constructor(private prisma: PrismaService) {} async getCategories(query: any) { const { page = 1, limit = 10, search = '' } = query; const skip = (Number(page) - 1) * Number(limit); const where = search ? { name: { contains: search, mode: 'insensitive' as any } } : {}; const [data, total] = await Promise.all([ this.prisma.category.findMany({ where, skip, take: Number(limit), orderBy: { createdAt: 'desc' } }), this.prisma.category.count({ where }) ]); return { data, meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) } }; } async getAllCategoriesRaw() { return this.prisma.category.findMany({ orderBy: { name: 'asc' } }); } async createCategory(data: any) { const cleanData = { ...data }; Object.keys(cleanData).forEach(k => { if (cleanData[k] === '') cleanData[k] = null; }); // Ensure required fields if (!cleanData.slug) cleanData.slug = cleanData.name.replace(/\s+/g, '-').toLowerCase(); return this.prisma.category.create({ data: cleanData }); } async updateCategory(id: string, data: any) { const category = await this.prisma.category.findUnique({ where: { id } }); if (!category) throw new NotFoundException('Category not found'); const cleanData = { ...data }; Object.keys(cleanData).forEach(k => { if (cleanData[k] === '') cleanData[k] = null; }); return this.prisma.category.update({ where: { id }, data: cleanData }); } async deleteCategory(id: string) { const category = await this.prisma.category.findUnique({ where: { id } }); if (!category) throw new NotFoundException('Category not found'); return this.prisma.category.delete({ where: { id } }); } }