import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; @Injectable() export class UsersService { constructor(private prisma: PrismaService) {} async findById(id: string) { return this.prisma.user.findUnique({ where: { id }, include: { pets: { include: { medicalConditions: true, reminders: { include: { completions: true } }, healthLogs: true, } }, orders: { orderBy: { createdAt: 'desc' }, include: { orderItems: { include: { product: true } } } }, addresses: true, walletTransactions: { orderBy: { createdAt: 'desc' }, take: 50 } } }); } async update(id: string, data: any) { return this.prisma.user.update({ where: { id }, data, include: { pets: true, orders: { include: { orderItems: { include: { product: true } } } }, addresses: true, walletTransactions: true } }); } async addAddress(userId: string, data: any) { if (data.isDefault) { await this.prisma.userAddress.updateMany({ where: { userId }, data: { isDefault: false }, }); } return this.prisma.userAddress.create({ data: { title: data.title, receptorName: data.receptorName, phone: data.phone, province: data.province, city: data.city, detail: data.detail, zipCode: data.zipCode, isDefault: data.isDefault || false, userId: userId, }, }); } async updateAddress(userId: string, addressId: string, data: any) { if (data.isDefault) { await this.prisma.userAddress.updateMany({ where: { userId, NOT: { id: addressId } }, data: { isDefault: false }, }); } return this.prisma.userAddress.update({ where: { id: addressId, userId }, data: { title: data.title, receptorName: data.receptorName, phone: data.phone, province: data.province, city: data.city, detail: data.detail, zipCode: data.zipCode, isDefault: data.isDefault || false, }, }); } async deleteAddress(userId: string, addressId: string) { return this.prisma.userAddress.delete({ where: { id: addressId, userId }, }); } async setDefaultAddress(userId: string, addressId: string) { await this.prisma.userAddress.updateMany({ where: { userId }, data: { isDefault: false }, }); return this.prisma.userAddress.update({ where: { id: addressId, userId }, data: { isDefault: true }, }); } async topUpWallet(userId: string, amount: number) { if (amount <= 0) { throw new Error('مبلغ شارژ باید بزرگتر از صفر باشد'); } const [transaction] = await this.prisma.$transaction([ this.prisma.walletTransaction.create({ data: { userId, amount, type: 'deposit', status: 'completed', description: 'شارژ کیف پول', }, }), this.prisma.user.update({ where: { id: userId }, data: { walletBalance: { increment: amount } }, }), ]); return transaction; } async findByPhone(phoneNumber: string) { return this.prisma.user.findUnique({ where: { mobile: phoneNumber }, }); } }