feat: port QA/money fixes from tehran_taj (atomic document confirm, validated inputs, expert customer edit/toggle/weights, made-to-order, grid sort/customer column)
Order-revision workflow kept as is: the direct admin line-edit routes were not ported. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
756ecef6db
commit
3eaecde876
@@ -1,6 +1,13 @@
|
||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
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
|
||||
@@ -16,7 +23,161 @@ import { PrismaService } from '../../prisma/prisma.service';
|
||||
*/
|
||||
@Injectable()
|
||||
export class SalesExpertAppService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
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<string, unknown>) {
|
||||
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 {
|
||||
@@ -80,7 +241,15 @@ export class SalesExpertAppService {
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
include: {
|
||||
items: true,
|
||||
// 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 } },
|
||||
},
|
||||
}),
|
||||
@@ -150,8 +319,15 @@ export class SalesExpertAppService {
|
||||
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,
|
||||
@@ -167,8 +343,16 @@ export class SalesExpertAppService {
|
||||
// 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,
|
||||
|
||||
Reference in New Issue
Block a user