import { Injectable, BadRequestException, NotFoundException, Optional, } from "@nestjs/common"; import { Prisma } from "@prisma/client"; import { PrismaService } from "../prisma/prisma.service"; import { SmsService } from "../common/services/sms.service"; import * as bcrypt from "bcryptjs"; import { normalizeMobile } from "../common/utils/phone.utils"; import { UpdateProfileDto } from "./dto/update-profile.dto"; export interface UserAddressInput { title: string; receptorName: string; phone: string; province: string; city: string; detail: string; zipCode: string; isDefault?: boolean; } @Injectable() export class UsersService { constructor( private prisma: PrismaService, @Optional() private smsService?: SmsService, ) {} async findById(id: string) { const user = await 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, }, }, }); if (!user) return null; const { password, ...safeUser } = user; return { ...safeUser, hasPassword: !!password, }; } async update(id: string, dto: UpdateProfileDto) { const user = await this.prisma.user.findUnique({ where: { id } }); if (!user) { throw new NotFoundException("کاربر یافت نشد"); } const updateData: Prisma.UserUpdateInput = {}; if (dto.firstName !== undefined) updateData.firstName = dto.firstName.trim(); if (dto.lastName !== undefined) updateData.lastName = dto.lastName.trim(); if (dto.mobile !== undefined) { const normalizedMobile = normalizeMobile(dto.mobile); if (normalizedMobile && normalizedMobile !== user.mobile) { const existing = await this.prisma.user.findUnique({ where: { mobile: normalizedMobile }, }); if (existing && existing.id !== id) { throw new BadRequestException( "این شماره موبایل قبلاً توسط کاربر دیگری ثبت شده است", ); } updateData.mobile = normalizedMobile; } } if (dto.email !== undefined) { const normalizedEmail = dto.email ? dto.email.trim().toLowerCase() : null; if (normalizedEmail && normalizedEmail !== user.email) { const existing = await this.prisma.user.findUnique({ where: { email: normalizedEmail }, }); if (existing && existing.id !== id) { throw new BadRequestException( "این آدرس ایمیل قبلاً توسط کاربر دیگری ثبت شده است", ); } } updateData.email = normalizedEmail; } if (dto.password && dto.password.trim().length >= 6) { // If user already has a password set, require and verify currentPassword if (user.password) { if (!dto.currentPassword) { throw new BadRequestException( "برای تغییر رمز عبور، وارد کردن رمز عبور فعلی الزامی است", ); } const isCurrentMatch = await bcrypt.compare( dto.currentPassword.trim(), user.password, ); if (!isCurrentMatch) { throw new BadRequestException("رمز عبور فعلی اشتباه است"); } } updateData.password = await bcrypt.hash(dto.password.trim(), 10); } const updatedUser = await this.prisma.user.update({ where: { id }, data: updateData, include: { pets: true, orders: { include: { orderItems: { include: { product: true }, }, }, }, addresses: true, walletTransactions: true, }, }); const { password, ...safeUser } = updatedUser; return { ...safeUser, hasPassword: !!password, }; } async addAddress(userId: string, data: UserAddressInput) { 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: UserAddressInput, ) { 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, updatedUser] = 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 } }, }), ]); if (this.smsService && updatedUser.mobile) { try { const customerFullName = ( updatedUser.firstName ? `${updatedUser.firstName} ${updatedUser.lastName || ""}` : "کاربر گرامی" ).trim(); const topupData = { customerName: customerFullName, customerPhone: updatedUser.mobile, amount: Number(amount || 0).toLocaleString("fa-IR"), balance: Number(updatedUser.walletBalance || 0).toLocaleString( "fa-IR", ), reason: "افزایش موجودی کیف پول", date: new Date().toLocaleDateString("fa-IR"), }; this.smsService .triggerEvent("WALLET_CHARGED", topupData) .catch(() => {}); } catch (err) { // Silently catch SMS error } } return transaction; } async findByPhone(phoneNumber: string) { return this.prisma.user.findUnique({ where: { mobile: phoneNumber }, }); } }