import prisma from '../utils/db'; import { catatAudit } from '../utils/audit'; import { moveToTrash } from '../utils/trash'; import { APIError } from '../utils/errors'; export class SupplierService { static async getSuppliers(skip = 0, limit = 10, pencarian?: string) { const where: any = { deleted_at: null, }; if (pencarian) { where.nama = { contains: pencarian, }; } return await prisma.supplier.findMany({ where, skip, take: limit, }); } static async getSupplierById(id: number) { const supplier = await prisma.supplier.findFirst({ where: { id, deleted_at: null }, }); if (!supplier) { throw new APIError('Supplier tidak ditemukan', 404); } return supplier; } static async create(data: any, actorId: number, ip: string, userAgent: string) { const supplier = await prisma.supplier.create({ data: { nama: data.nama, kontak: data.kontak ?? null, nomor_hp: data.nomor_hp ?? null, alamat: data.alamat ?? null, hutang: data.hutang ?? 0, aktif: data.aktif ?? 1, }, }); await catatAudit({ userId: actorId, aksi: 'create', entitas: 'supplier', entitasId: supplier.id, dataBaru: { nama: supplier.nama, kontak: supplier.kontak, hutang: Number(supplier.hutang) }, ipAddress: ip, userAgent, }); return supplier; } static async update(id: number, data: any, actorId: number, ip: string, userAgent: string) { const supplier = await this.getSupplierById(id); const dataLama = { nama: supplier.nama, kontak: supplier.kontak, nomor_hp: supplier.nomor_hp, alamat: supplier.alamat, hutang: Number(supplier.hutang), aktif: supplier.aktif, }; const updateData: any = {}; if (data.nama !== undefined) updateData.nama = data.nama; if (data.kontak !== undefined) updateData.kontak = data.kontak; if (data.nomor_hp !== undefined) updateData.nomor_hp = data.nomor_hp; if (data.alamat !== undefined) updateData.alamat = data.alamat; if (data.hutang !== undefined) updateData.hutang = data.hutang; if (data.aktif !== undefined) updateData.aktif = data.aktif; const updated = await prisma.supplier.update({ where: { id }, data: updateData, }); const dataBaru = { nama: updated.nama, kontak: updated.kontak, nomor_hp: updated.nomor_hp, alamat: updated.alamat, hutang: Number(updated.hutang), aktif: updated.aktif, }; await catatAudit({ userId: actorId, aksi: 'update', entitas: 'supplier', entitasId: updated.id, dataLama, dataBaru, ipAddress: ip, userAgent, }); return updated; } static async delete(id: number, actorId: number, ip: string, userAgent: string) { const supplier = await this.getSupplierById(id); await moveToTrash({ instance: supplier, entityType: 'supplier', actorId, }); await catatAudit({ userId: actorId, aksi: 'delete', entitas: 'supplier', entitasId: supplier.id, dataLama: { nama: supplier.nama, aktif: 1 }, dataBaru: { nama: supplier.nama, aktif: 0 }, ipAddress: ip, userAgent, }); return true; } }