import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException } from '@nestjs/common'; import { OrderStatus, Prisma } from '@prisma/client'; import { PrismaService } from '../../prisma/prisma.service'; import { OrdersService } from '../orders/orders.service'; import { SmsService } from '../sms/sms.service'; import { AccountingHooksService } from '../accounting-sync/accounting-hooks.service'; import { faToEn } from '../customer-auth/digits'; import { brandName, brandSiteUrl } from '../../common/brand'; import { birthDateOrNull, nationalCodeOrNull } from '../../common/customer-input'; import { activeExpertHoldsMobile, EXPERT_HOLDS_MOBILE } from '../../common/mobile-owner'; /** * The two screens a sales expert has in the app beyond what every customer * gets: "سفارش مشتریان" (their referred customers' orders) and * "انتخاب مشتری" (their referred customers). * * Reference: ApiMobileController::getChildOrder (:759-781) and ::myChild * (:184-195). Both scoped on `reagent_id = auth()->id()` — in the reference the * agent was a Customer, so that was the logged-in customer's own id. Here the * expert is an AdminUser (D17) and `Customer.referredByAgentId` points at it, * so the scope is the AdminUser id taken from the token. Nothing is ever read * from the request. */ @Injectable() export class SalesExpertAppService { private readonly logger = new Logger(SalesExpertAppService.name); constructor( private readonly prisma: PrismaService, private readonly orders: OrdersService, private readonly sms: SmsService, private readonly accounting: AccountingHooksService, ) {} /** * The customer, but only if it is one of THIS expert's. Anyone else's is "not * found" — never "forbidden" — so ids cannot be probed. (The reference's * `customer/toggle-active` checked nothing at all: any signed-in customer * could switch any account off; its `customer/update` did check ownership.) */ private async ownCustomer(agentId: string, customerId: string) { const c = await this.prisma.customer.findFirst({ where: { id: customerId, referredByAgentId: agentId }, }); if (!c) throw new NotFoundException('مشتری یافت نشد'); return c; } /** * Port of `POST customer/toggle-active` (AdminController::customerToggleActive) * for «مشتریان من»: the expert switches one of their customers' accounts off * or on. Off, the customer's token stops working on the next request (the * customer guard reads `isActive` every time); on, the customer is told by SMS, * as the reference told them. */ async toggleCustomerActive(adminUserId: string | undefined, customerId: string) { const agentId = this.assertExpert(adminUserId); const c = await this.ownCustomer(agentId, customerId); const updated = await this.prisma.customer.update({ where: { id: c.id }, data: { isActive: !c.isActive }, }); if (updated.isActive) { const text = `${updated.fullName} عزیز\n` + 'حساب کاربری شما در اپلیکیشن فعال شد.\n' + 'هم‌اکنون می‌توانید محصولات جدید را بررسی و ثبت سفارش کنید.\n' + 'با مراجعه به لینک زیر می‌توانید وارد پروفایل کاربری خود شوید.\n' + `${brandSiteUrl()}\n${brandName()}`; void this.sms.send(updated.mobile, text).catch((e: unknown) => { this.logger.error(`Activation SMS to ${updated.mobile} failed: ${String(e)}`); }); } return { id: updated.id, active: updated.isActive ? 1 : -1 }; } /** * Port of `POST customer/update` (AdminController::updateCustomer) for * «ویرایش مشتری»: the expert corrects the contact details of one of their own * customers. * * Only contact details can be changed here. The customer's making-charge * percent, credit limit, kind, expert, account switches and codes are money * and administration — the admin panel's, not the app's — so they are not * read from the request at all, whatever it carries. (The reference form * could also change the customer's `type`; that is not carried over.) */ async updateCustomer(adminUserId: string | undefined, customerId: string, body: Record) { const agentId = this.assertExpert(adminUserId); const existing = await this.ownCustomer(agentId, customerId); const patch: Prisma.CustomerUpdateInput = {}; // A value that is not text (an object, a list) would be stored as "[object Object]". const text = (key: string): unknown => { const v = body[key]; if (v !== undefined && v !== null && typeof v !== 'string' && typeof v !== 'number') { throw new BadRequestException('مقدار وارد شده معتبر نیست'); } return v; }; // The reference required both names. const firstName = String(text('fname') ?? existing.firstName ?? '').trim(); const lastName = String(text('lname') ?? existing.lastName ?? '').trim(); if (!firstName || !lastName) throw new BadRequestException('نام و نام خانوادگی الزامی است'); patch.firstName = firstName; patch.lastName = lastName; if (body.mobile !== undefined && body.mobile !== null && String(body.mobile).trim() !== '') { const mobile = faToEn(String(body.mobile).trim()); if (!/^09\d{9}$/.test(mobile)) throw new BadRequestException('شماره موبایل معتبر نیست'); if (mobile !== existing.mobile) { // One mobile, one person: another customer (the unique index) or an active // expert (they sign in with it too) may already hold it. if (await activeExpertHoldsMobile(this.prisma, mobile)) throw new BadRequestException(EXPERT_HOLDS_MOBILE); if (await this.prisma.customer.findFirst({ where: { mobile, NOT: { id: existing.id } }, select: { id: true } })) { throw new BadRequestException('این شماره موبایل قبلاً برای مشتری دیگری ثبت شده است'); } patch.mobile = mobile; } } const optional = (key: string, max: number) => { if (body[key] === undefined) return undefined; const s = String(text(key) ?? '').trim(); if (s.length > max) throw new BadRequestException('طول مقدار وارد شده بیش از حد مجاز است'); return s || null; }; const phone = optional('phone', 30); if (phone !== undefined) patch.phone = phone; const address = optional('address', 500); if (address !== undefined) patch.address = address; const storeName = optional('store_name', 150); if (storeName !== undefined) patch.storeName = storeName; const pasazhName = optional('pasazh_name', 150); if (pasazhName !== undefined) patch.pasazhName = pasazhName; const zone = optional('zone', 20); if (zone !== undefined) patch.zone = zone; if (body.city_id !== undefined) { patch.city = body.city_id ? { connect: { id: String(body.city_id) } } : { disconnect: true }; } if (body.national_code !== undefined) patch.nationalCode = nationalCodeOrNull(body.national_code); const birthDate = birthDateOrNull(body.birth_date); if (birthDate !== undefined) patch.birthDate = birthDate; // D27 — the accounting account carries name, mobile, national code, phone, address. const contactChanged = ['fname', 'lname', 'mobile', 'national_code', 'phone', 'address'].some((k) => body[k] !== undefined); const updated = await this.prisma.$transaction(async (tx) => { const row = await tx.customer.update({ where: { id: existing.id }, data: patch }); if (contactChanged) await this.accounting.customerEdited(tx, existing.id); return row; }); return { id: updated.id, name: updated.fullName, mobile: updated.mobile }; } /** * Port of `updateChildOrder` (ApiMobileController.php, `PUT order/child/{id}`): * the expert enters the real raw weight of each piece of an order that is in * their hands, and may submit it as final, which hands it to the customer. * Scope is the expert's own orders only; the rules and the totals, debt and * accounting that follow are OrdersService.expertAdjust. */ async adjustChildOrder( adminUserId: string | undefined, orderId: string, body: { items?: { id?: unknown; rash_weight?: unknown }[]; final_submit?: unknown }, ) { const agentId = this.assertExpert(adminUserId); const finalSubmit = body?.final_submit === true || body?.final_submit === 'true'; const items = body?.items ?? []; if (!Array.isArray(items)) throw new BadRequestException('items باید فهرست ردیف‌ها باشد'); return this.orders.expertAdjust( orderId, agentId, items.map((i) => ({ id: i?.id, rashWeightGrams: i?.rash_weight })), finalSubmit, ); } /** Refuses any principal that is not a sales expert. */ private assertExpert(adminUserId: string | undefined): string { if (!adminUserId) { throw new ForbiddenException('این بخش فقط برای کارشناس فروش است'); } return adminUserId; } /** * Port of `getChildOrder` (ApiMobileController.php:759-781). * * The reference filtered `where('sts', 5)` — legacy status 5 is * «تحویل مسئول فروش» (delivered to the sales agent), the point at which the * agent has to act on the order. Reproduced with the equivalent status here; * the heading the reference hardcodes on every card is that same label * (ChildOrders.vue:48). * * Search covers what the reference searched: order id, customer name and * customer mobile (`initSearch(['id','customer_id','customer.name','customer.mobile'])`). * Ordered `id DESC`, i.e. newest first. */ async childOrders( adminUserId: string | undefined, params: { page?: number; limit?: number; search?: string | null }, ) { const agentId = this.assertExpert(adminUserId); const page = Math.max(1, Number(params.page ?? 1)); const limit = Math.min(100, Math.max(1, Number(params.limit ?? 20))); const search = (params.search ?? '').trim(); const scope: Prisma.OrderWhereInput = { // Legacy getChildOrder: `where('reagent_id', auth()->id())` // (ApiMobileController.php:779) — the orders credited to THIS expert when // they were placed (Order.salesAgentId), not the customer's current // referrer. No id from the request takes part in this. salesAgentId: agentId, status: OrderStatus.DELIVERED_TO_AGENT, }; const where: Prisma.OrderWhereInput = search ? { AND: [ scope, { OR: [ { orderNumber: { contains: search, mode: 'insensitive' } }, { customer: { fullName: { contains: search, mode: 'insensitive' } } }, { customer: { mobile: { contains: search } } }, ], }, ], } : scope; const [rows, total] = await Promise.all([ this.prisma.order.findMany({ where, orderBy: { createdAt: 'desc' }, skip: (page - 1) * limit, take: limit, include: { // The product and variant titles label each line where the expert // enters the real weights. items: { include: { productVariant: { select: { id: true, title: true, product: { select: { id: true, title: true } } }, }, }, }, customer: { select: { id: true, fullName: true, mobile: true } }, }, }), this.prisma.order.count({ where }), ]); return { rows: rows.map((o) => ({ id: o.id, orderNumber: o.orderNumber, status: o.status, // The reference's card shows the order's total weight as `item.w` // (ChildOrders.vue:55) and the item count as `items.length`. w: o.totalGoldWeightGrams, totalGoldWeightGrams: o.totalGoldWeightGrams, createdAt: o.createdAt, items: o.items, customer: o.customer ? { id: o.customer.id, name: o.customer.fullName, mobile: o.customer.mobile } : null, })), total, page, limit, }; } /** * Port of `myChild` (ApiMobileController.php:184-195) — the expert's own * referred customers, for "انتخاب مشتری". * * The reference searched name, mobile, phone, store_name and pasazh_name; * all five exist here. It also returned EVERY referred customer, active or * not — the `active()` scope is commented out at :187 — so that is * reproduced rather than "fixed" (D4). * * NOT ported: the reference minted an `api_token` for each listed customer * as a side effect (:197-201), which let an agent act AS that customer. That * is a session-hijack primitive; this system derives every session from the * caller's own token. See D21. */ async myCustomers(adminUserId: string | undefined, params: { search?: string | null }) { const agentId = this.assertExpert(adminUserId); const search = (params.search ?? '').trim(); const scope: Prisma.CustomerWhereInput = { referredByAgentId: agentId }; const where: Prisma.CustomerWhereInput = search ? { AND: [ scope, { OR: [ { fullName: { contains: search, mode: 'insensitive' } }, { mobile: { contains: search } }, { phone: { contains: search } }, { storeName: { contains: search, mode: 'insensitive' } }, { pasazhName: { contains: search, mode: 'insensitive' } }, ], }, ], } : scope; const rows = await this.prisma.customer.findMany({ where, orderBy: { createdAt: 'desc' }, select: { id: true, fullName: true, firstName: true, lastName: true, mobile: true, phone: true, address: true, zone: true, cityId: true, nationalCode: true, birthDate: true, storeName: true, pasazhName: true, goldCreditLimitGrams: true, goldDebtGrams: true, fiatDebtRial: true, isActive: true, createdAt: true, }, }); return rows.map((c) => ({ id: c.id, // legacy key, which the ported card binds to name: c.fullName, fullName: c.fullName, // What «ویرایش مشتری» opens with. fname: c.firstName ?? c.fullName, lname: c.lastName ?? '', mobile: c.mobile, phone: c.phone, address: c.address, zone: c.zone, city_id: c.cityId, national_code: c.nationalCode, birth_date: c.birthDate ? c.birthDate.toISOString().slice(0, 10) : null, store_name: c.storeName, pasazh_name: c.pasazhName, gram_level: c.goldCreditLimitGrams, remain: c.goldDebtGrams, rial_remain: c.fiatDebtRial, active: c.isActive ? 1 : -1, createdAt: c.createdAt, })); } /** The expert's own profile strip, for the app header. */ async me(adminUserId: string | undefined) { const agentId = this.assertExpert(adminUserId); const admin = await this.prisma.adminUser.findUnique({ where: { id: agentId }, select: { id: true, fullName: true, firstName: true, lastName: true, mobile: true, wagePercent: true, salesExpertProfile: { select: { gramLevel: true, tradingCustomerId: true, city: { select: { id: true, name: true } } }, }, _count: { select: { referredCustomers: true } }, }, }); return { id: admin?.id, name: admin?.fullName, fname: admin?.firstName ?? admin?.fullName, lname: admin?.lastName ?? '', mobile: admin?.mobile, percent: admin?.wagePercent, gram_level: admin?.salesExpertProfile?.gramLevel ?? null, city: admin?.salesExpertProfile?.city ? { id: admin.salesExpertProfile.city.id, title: admin.salesExpertProfile.city.name } : null, customers_count: admin?._count.referredCustomers ?? 0, /** The Customer row the expert's OWN orders land on. */ trading_customer_id: admin?.salesExpertProfile?.tradingCustomerId ?? null, }; } }