import { Injectable, NotFoundException, BadRequestException, Logger, } from "@nestjs/common"; import { PrismaService } from "../prisma/prisma.service"; import { PaginationDto } from "../common/dto/pagination.dto"; import { CreateOrderDto } from "./dto/create-order.dto"; import { SmsService } from "../common/services/sms.service"; import { Prisma } from "@prisma/client"; @Injectable() export class OrdersService { private readonly logger = new Logger(OrdersService.name); constructor( private prisma: PrismaService, private smsService: SmsService, ) {} private generateTrackingNumber(): string { const random = Math.floor(10000 + Math.random() * 90000); return `CN-${random}`; } async validateCoupon( code: string, cartTotal: Prisma.Decimal, userId: string, ) { const coupon = await this.prisma.coupon.findUnique({ where: { code: code.toUpperCase().trim() }, include: { targets: true }, }); if (!coupon || !coupon.isActive) { throw new BadRequestException({ message: "کد تخفیف معتبر نیست یا منقضی شده است", error: "COUPON_INVALID", }); } if (coupon.expiresAt && new Date() > coupon.expiresAt) { throw new BadRequestException({ message: "کد تخفیف منقضی شده است", error: "COUPON_EXPIRED", }); } if (coupon.maxUses && coupon.usedCount >= coupon.maxUses) { throw new BadRequestException({ message: "ظرفیت استفاده از این کد تخفیف تکمیل شده است", error: "COUPON_LIMIT_REACHED", }); } if (coupon.minCartValue && cartTotal.lessThan(coupon.minCartValue)) { throw new BadRequestException({ message: `حداقل مبلغ سبد خرید برای استفاده از این کد ${Number(coupon.minCartValue).toLocaleString("fa-IR")} تومان است`, error: "COUPON_MIN_CART", }); } // Check user-specific targets const userTargets = coupon.targets.filter((t) => t.targetType === "USER"); if ( userTargets.length > 0 && !userTargets.some((t) => t.targetId === userId) ) { throw new BadRequestException({ message: "این کد تخفیف برای حساب کاربری شما فعال نیست", error: "COUPON_USER_MISMATCH", }); } let discountAmount = new Prisma.Decimal(0); if (coupon.type === "percent" || coupon.type === "PERCENTAGE") { discountAmount = cartTotal.mul(coupon.value).div(100); if ( coupon.maxCartValue && discountAmount.greaterThan(coupon.maxCartValue) ) { discountAmount = new Prisma.Decimal(coupon.maxCartValue); } } else { discountAmount = new Prisma.Decimal(coupon.value); } const finalDiscount = discountAmount.greaterThan(cartTotal) ? cartTotal : discountAmount; return { couponId: coupon.id, code: coupon.code, discountAmount: finalDiscount, }; } async create(userId: string, createOrderDto: CreateOrderDto) { // Check catalog mode settings const catalogSetting = await this.prisma.setting.findFirst({ where: { key: { in: ["catalog_mode", "catalog_disable_checkout"] } }, }); const catalogUiText = await this.prisma.uiText.findFirst({ where: { key: { in: ["catalog_mode", "catalog_disable_checkout"] }, value: "true", }, }); if ((catalogSetting && catalogSetting.value === "true") || catalogUiText) { throw new BadRequestException( "امکان ثبت سفارش به دلیل فعال بودن حالت کاتالوگ در حال حاضر وجود ندارد.", ); } if (!createOrderDto.items || createOrderDto.items.length === 0) { throw new BadRequestException("سبد خرید خالی است"); } // Validate quantities and duplicate product IDs const productIds = createOrderDto.items.map((item) => item.productId); const uniqueProductIds = new Set(productIds); if (uniqueProductIds.size !== productIds.length) { throw new BadRequestException("تکرار محصول در سبد خرید مجاز نیست"); } for (const item of createOrderDto.items) { if (item.quantity <= 0 || !Number.isInteger(item.quantity)) { throw new BadRequestException( `تعداد محصول ${item.productId} نامعتبر است`, ); } } // Batch fetch products using single findMany query const products = await this.prisma.product.findMany({ where: { id: { in: productIds } }, }); const productMap = new Map(products.map((p) => [p.id, p])); for (const item of createOrderDto.items) { const product = productMap.get(item.productId); if (!product) { throw new NotFoundException(`محصول یافت نشد`); } const isOutOfStock = product.stockStatus === "OUT_OF_STOCK" || product.stockStatus === "DISCONTINUED" || product.stock <= 0; if (isOutOfStock) { throw new BadRequestException( `محصول «${product.nameFa || (product as any).name}» در حال حاضر ناموجود است و امکان ثبت سفارش آن وجود ندارد`, ); } if (item.quantity > product.stock) { throw new BadRequestException( `تعداد درخواستی برای محصول «${product.nameFa || (product as any).name}» (${item.quantity} عدد) بیشتر از موجودی انبار (${product.stock} عدد) است`, ); } } let cartTotal = new Prisma.Decimal(0); const orderItemsData: Array<{ productId: string; quantity: number; }> = []; for (const item of createOrderDto.items) { const product = productMap.get(item.productId)!; const unitPrice = new Prisma.Decimal(product.priceValue); const totalItemPrice = unitPrice.mul(item.quantity); cartTotal = cartTotal.add(totalItemPrice); orderItemsData.push({ productId: item.productId, quantity: item.quantity, }); } let discountAmount = new Prisma.Decimal(0); let couponId: string | undefined = undefined; if (createOrderDto.couponCode) { const couponResult = await this.validateCoupon( createOrderDto.couponCode, cartTotal, userId, ); discountAmount = couponResult.discountAmount; couponId = couponResult.couponId; } const charityAmount = new Prisma.Decimal( createOrderDto.charityDonation || 0, ); const totalAfterDiscount = cartTotal.sub(discountAmount); const finalAmount = ( totalAfterDiscount.lessThan(0) ? new Prisma.Decimal(0) : totalAfterDiscount ).add(charityAmount); const trackingNumber = this.generateTrackingNumber(); // Deduct user wallet balance and create order atomically if (createOrderDto.paymentMethod === "wallet" && userId) { const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (!user) { throw new NotFoundException("کاربر یافت نشد"); } const createdWalletOrder = await this.prisma.$transaction(async (tx) => { // SEC-002: Atomic decrement preventing race condition & overdraft const updatedCount = await tx.$executeRaw` UPDATE "users" SET "wallet_balance" = "wallet_balance" - ${Number(finalAmount)}::decimal WHERE "id" = ${userId}::uuid AND "wallet_balance" >= ${Number(finalAmount)}::decimal `; if (updatedCount === 0) { throw new BadRequestException( "موجودی کیف پول برای پرداخت این سفارش کافی نیست", ); } await tx.walletTransaction.create({ data: { userId, amount: Number(finalAmount), type: "withdrawal", status: "completed", description: `پرداخت سفارش ${trackingNumber}`, }, }); if (charityAmount.greaterThan(0)) { await tx.user.update({ where: { id: userId }, data: { charityDonationTotal: { increment: Number(charityAmount) }, }, }); } const newOrder = await tx.order.create({ data: { userId, couponId, totalAmount: Number(finalAmount), charityDonation: Number(charityAmount), isRefill: Boolean(createOrderDto.isRefill), refillIntervalDays: createOrderDto.refillIntervalDays || 60, trackingNumber, status: "processing", paymentMethod: "wallet", shippingAddress: createOrderDto.shippingAddress, orderItems: { create: orderItemsData, }, }, include: { orderItems: { include: { product: true }, }, }, }); if (couponId) { await tx.coupon .update({ where: { id: couponId }, data: { usedCount: { increment: 1 } }, }) .catch(() => {}); } // Deduct inventory atomically for wallet orders for (const item of createOrderDto.items) { const updated = await tx.product.update({ where: { id: item.productId }, data: { stock: { decrement: item.quantity }, }, }); if (updated.stock <= 0) { await tx.product.update({ where: { id: item.productId }, data: { stockStatus: "OUT_OF_STOCK" }, }); } } return newOrder; }); // Send Order Confirmation SMS for wallet orders if (user.mobile) { const orderData = this.buildOrderEventData(createdWalletOrder, user); this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => { this.logger.warn(`Failed to trigger wallet order SMS: ${err}`); }); } return createdWalletOrder; } const isOnline = createOrderDto.paymentMethod === "online"; const initialStatus = isOnline ? "pending_payment" : "processing"; const reservationExpiry = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes hold const createdOrder = await this.prisma.$transaction(async (tx) => { const order = await tx.order.create({ data: { userId, couponId, totalAmount: Number(finalAmount), charityDonation: Number(charityAmount), isRefill: Boolean(createOrderDto.isRefill), refillIntervalDays: createOrderDto.refillIntervalDays || 60, trackingNumber, status: initialStatus, paymentMethod: createOrderDto.paymentMethod || "card", shippingAddress: createOrderDto.shippingAddress, orderItems: { create: orderItemsData, }, inventoryReservations: { create: orderItemsData.map((item) => ({ productId: item.productId, quantity: item.quantity, expiresAt: reservationExpiry, status: isOnline ? "ACTIVE" : "CONSUMED", })), }, }, include: { orderItems: { include: { product: true }, }, inventoryReservations: true, }, }); // Deduct inventory immediately for non-online orders (card to card) if (!isOnline) { for (const item of createOrderDto.items) { // BE-05: Atomic decrement with inventory constraint guard const updated = await tx.product.update({ where: { id: item.productId }, data: { stock: { decrement: item.quantity }, }, }); if (updated && updated.stock <= 0) { await tx.product.update({ where: { id: item.productId }, data: { stockStatus: "OUT_OF_STOCK" }, }); } } } return order; }); // Send Order Confirmation SMS (for card-to-card or non-online orders, online orders get SMS on verify) if (userId && !isOnline) { const user = await this.prisma.user.findUnique({ where: { id: userId }, }); if (user?.mobile) { const orderData = this.buildOrderEventData(createdOrder, user); this.smsService .triggerEvent("ORDER_CREATED", orderData) .catch(() => {}); } } return createdOrder; } private buildOrderEventData(order: any, user: any): Record { const rawShipping = order.shippingAddress; let shipping: Record = {}; if (typeof rawShipping === "object" && rawShipping !== null) { shipping = rawShipping; } else if (typeof rawShipping === "string") { const trimmed = rawShipping.trim(); if (trimmed.startsWith("{") && trimmed.endsWith("}")) { try { shipping = JSON.parse(trimmed); } catch { shipping = {}; } } // If not parsed as JSON or fields are missing, extract from formatted address string: // Pattern: "استان، شهر، آدرس پستی (کد پستی: ۱۲۳۴۵۶۷۸۹۰) (گیرنده: نام گیرنده - ۰۹۱۲۰۰۰۰۰۰۰)" if (!shipping.province || !shipping.address) { let text = trimmed; // 1. Extract recipient & phone: (گیرنده: نام گیرنده - ۰۹۱۲۰۰۰۰۰۰۰) const recipientMatch = text.match( /\(گیرنده:\s*([^-)]+)(?:-\s*([^)]+))?\)/, ); if (recipientMatch) { if (!shipping.fullName) shipping.fullName = recipientMatch[1]?.trim(); if (!shipping.phone && recipientMatch[2]) shipping.phone = recipientMatch[2]?.trim(); text = text.replace(recipientMatch[0], "").trim(); } // 2. Extract postal code: (کد پستی: ۱۲۳۴۵۶۷۸۹۰) const postalMatch = text.match(/\(کد پستی:\s*([^)]+)\)/); if (postalMatch) { if (!shipping.postalCode) shipping.postalCode = postalMatch[1]?.trim(); text = text.replace(postalMatch[0], "").trim(); } // 3. Extract province and city: "استان، شهر، بقیه آدرس" or "استان - شهر - بقیه آدرس" const parts = text .split(/[،,]/) .map((p) => p.trim()) .filter(Boolean); if (parts.length >= 3) { if (!shipping.province) shipping.province = parts[0]; if (!shipping.city) shipping.city = parts[1]; if (!shipping.address) shipping.address = parts.slice(2).join("، "); } else if (parts.length === 2) { if (!shipping.province) shipping.province = parts[0]; if (!shipping.address) shipping.address = parts[1]; } else if (parts.length === 1 && !shipping.address) { shipping.address = parts[0]; } } } const items = order.orderItems || []; const itemsSummary = items .map((i: any) => `${i.product?.nameFa || "محصول"} (${i.quantity})`) .join("، "); const itemCount = items.reduce( (sum: number, i: any) => sum + (i.quantity || 1), 0, ); const customerFullName = ( user?.firstName ? `${user.firstName} ${user.lastName || ""}` : shipping.fullName || "مشتری" ).trim(); const recipientFullName = ( shipping.fullName || shipping.receptorName || customerFullName ).trim(); const recipientMobile = (shipping.phone || user?.mobile || "").trim(); const provinceCity = ( shipping.province && shipping.city ? `${shipping.province} - ${shipping.city}` : shipping.province || shipping.city || "" ).trim(); const addressDetail = ( shipping.address || shipping.detail || (typeof rawShipping === "string" ? rawShipping : "") ).trim(); return { orderNumber: order.trackingNumber || order.id.slice(0, 8), amount: Number(order.totalAmount || 0).toLocaleString("fa-IR"), customerName: customerFullName, customerPhone: user?.mobile || shipping.phone || "", recipientName: recipientFullName, recipientPhone: recipientMobile, provinceCity: provinceCity || "ثبت نشده", postalCode: shipping.postalCode || shipping.zipCode || "", address: addressDetail || "", itemsSummary, itemCount: String(itemCount), paymentMethod: order.paymentMethod === "online" ? "آنلاین" : order.paymentMethod === "wallet" ? "کیف پول" : "کارت به کارت", orderDate: new Date().toLocaleDateString("fa-IR"), }; } async updateStatus(orderId: string, status: string, trackingCode?: string) { const order = await this.prisma.order.findUnique({ where: { id: orderId }, include: { user: true, orderItems: { include: { product: true } } }, }); if (!order) { throw new NotFoundException("سفارش یافت نشد"); } const updatedOrder = await this.prisma.order.update({ where: { id: orderId }, data: { status, ...(trackingCode ? { trackingNumber: trackingCode } : {}), }, include: { user: true, orderItems: { include: { product: true } } }, }); // Send Shipping SMS with Tracking Code (or courier delivery fallback) const mobile = updatedOrder.user?.mobile; const finalTracking = trackingCode || updatedOrder.trackingNumber || ""; if (status === "shipped" && mobile) { const orderData = this.buildOrderEventData( updatedOrder, updatedOrder.user, ); orderData.trackingCode = finalTracking || "ارسال با پیک شهری"; orderData.shippingTrackingCode = finalTracking || "ارسال با پیک شهری"; orderData.shippingMethod = finalTracking ? "پست پیشتاز / تیپاکس" : "پیک شهری"; this.smsService.triggerEvent("ORDER_SHIPPED", orderData).catch(() => {}); } return updatedOrder; } async findAllByUser(userId: string, filters: PaginationDto) { const { page = 1, limit = 10, sortBy = "createdAt", sortOrder = "desc", } = filters; const skip = (page - 1) * limit; const [data, total] = await Promise.all([ this.prisma.order.findMany({ where: { userId }, skip, take: limit, orderBy: { [sortBy]: sortOrder }, include: { orderItems: { include: { product: true } }, }, }), this.prisma.order.count({ where: { userId } }), ]); return { data, meta: { total, page, lastPage: Math.ceil(total / limit), limit, }, }; } async findOne(id: string, userId: string) { const order = await this.prisma.order.findFirst({ where: { id, userId }, include: { orderItems: { include: { product: true } }, }, }); if (!order) { throw new NotFoundException("سفارش یافت نشد"); } return order; } async checkAndSendRefillReminders() { const fiftyEightDaysAgo = new Date(Date.now() - 58 * 24 * 60 * 60 * 1000); const fiftyNineDaysAgo = new Date(Date.now() - 59 * 24 * 60 * 60 * 1000); const dueRefillOrders = await this.prisma.order.findMany({ where: { isRefill: true, createdAt: { gte: fiftyNineDaysAgo, lte: fiftyEightDaysAgo, }, }, include: { user: true }, }); for (const order of dueRefillOrders) { if (order.user?.mobile) { await this.smsService .sendSms( order.user.mobile, `کاربر گرامی، مکمل درمانی پت شما در حال اتمام است. جهت شارژ مجدد و استفاده از ۵٪ تخفیف دوره جدید به لینک زیر مراجعه کنید:\nhttps://canina.ir/shop`, ) .catch(() => {}); } } } /** * Release inventory reservations that expired without successful payment */ async releaseExpiredInventoryReservations() { const now = new Date(); const expiredReservations = await this.prisma.inventoryReservation.updateMany({ where: { status: "ACTIVE", expiresAt: { lte: now }, }, data: { status: "RELEASED", }, }); return { releasedCount: expiredReservations.count, executedAt: now, }; } /** * Retry or complete payment for an existing pending order with selectable payment method */ async retryPayment(userId: string, orderId: string, paymentMethod?: string) { const order = await this.prisma.order.findFirst({ where: { id: orderId, userId }, include: { user: true }, }); if (!order) { throw new NotFoundException("سفارش مورد نظر یافت نشد"); } const ALLOWED_RETRY_STATUSES = ["pending_payment", "failed"]; if (!ALLOWED_RETRY_STATUSES.includes(order.status)) { throw new BadRequestException( "تنها سفارش‌های در انتظار پرداخت یا ناموفق قابلیت پرداخت مجدد دارند.", ); } const selectedMethod = paymentMethod || order.paymentMethod || "online"; const finalAmount = Number(order.totalAmount); if (selectedMethod === "wallet") { const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (!user) throw new NotFoundException("کاربر یافت نشد"); await this.prisma.$transaction(async (tx) => { // SEC-002: Atomic decrement preventing race condition & overdraft const updatedCount = await tx.$executeRaw` UPDATE "users" SET "wallet_balance" = "wallet_balance" - ${finalAmount}::decimal WHERE "id" = ${userId}::uuid AND "wallet_balance" >= ${finalAmount}::decimal `; if (updatedCount === 0) { throw new BadRequestException( `موجودی کیف پول شما برای پرداخت این سفارش (${finalAmount.toLocaleString("fa-IR")} تومان) کافی نیست.`, ); } await tx.walletTransaction.create({ data: { userId, amount: finalAmount, type: "withdrawal", status: "completed", description: `پرداخت مجدد سفارش ${order.trackingNumber || order.id}`, }, }); if (Number(order.charityDonation) > 0) { await tx.user.update({ where: { id: userId }, data: { charityDonationTotal: { increment: Number(order.charityDonation), }, }, }); } await tx.order.update({ where: { id: order.id }, data: { status: "processing", paymentMethod: "wallet", }, }); }); if (user.mobile) { const orderData = this.buildOrderEventData(order, user); await this.smsService .triggerEvent("ORDER_PAID", orderData) .catch(() => {}); } return { success: true, message: "پرداخت با موفقیت از طریق کیف پول انجام شد.", paymentMethod: "wallet", orderId: order.id, }; } if (selectedMethod === "card") { await this.prisma.order.update({ where: { id: order.id }, data: { paymentMethod: "card", status: "pending_payment" }, }); return { success: true, message: "روش پرداخت به کارت به کارت تغییر یافت. لطفاً پس از واریز فیش را ثبت فرمایید.", paymentMethod: "card", orderId: order.id, }; } // Default: Online Gateway (Zibal) await this.prisma.order.update({ where: { id: order.id }, data: { paymentMethod: "online", status: "pending_payment" }, }); return { success: true, message: "سفارش آماده پرداخت آنلاین است.", paymentMethod: "online", orderId: order.id, paymentInitiateRequired: true, }; } }