import prisma from '../config/database'; import { Prisma, LicenseStatus, LicensePlan } from '@prisma/client'; export class LicenseRepository { async create(data: Prisma.LicenseCreateInput) { return prisma.license.create({ data }); } async findById(id: string) { return prisma.license.findUnique({ where: { id }, include: { user: true } }); } async findByKey(key: string) { return prisma.license.findUnique({ where: { key }, include: { user: true } }); } async findByUserId(userId: string) { return prisma.license.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, }); } async findActiveByUserId(userId: string) { return prisma.license.findFirst({ where: { userId, status: LicenseStatus.ACTIVE }, orderBy: { createdAt: 'desc' }, }); } async update(id: string, data: Prisma.LicenseUpdateInput) { return prisma.license.update({ where: { id }, data }); } async deactivateExpired() { return prisma.license.updateMany({ where: { status: LicenseStatus.ACTIVE, expiredAt: { lt: new Date() }, }, data: { status: LicenseStatus.EXPIRED }, }); } async updateLastCheck(id: string) { return prisma.license.update({ where: { id }, data: { lastCheckAt: new Date() }, }); } async findAll(page: number, limit: number) { const [licenses, total] = await Promise.all([ prisma.license.findMany({ skip: (page - 1) * limit, take: limit, orderBy: { createdAt: 'desc' }, include: { user: { select: { id: true, email: true, name: true }, }, }, }), prisma.license.count(), ]); return { licenses, total, page, limit, totalPages: Math.ceil(total / limit) }; } async countByPlan() { return prisma.license.groupBy({ by: ['plan'], where: { status: LicenseStatus.ACTIVE }, _count: true, }); } } export default new LicenseRepository();