feat: store and enforce per-product payment and check limits
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
-- سقف مدت چک و روشهای پرداخت مجاز برای هر محصول
|
||||
ALTER TABLE "Product" ADD COLUMN "maxCheckMonths" INTEGER NOT NULL DEFAULT 4;
|
||||
ALTER TABLE "Product" ADD COLUMN "allowCash" BOOLEAN NOT NULL DEFAULT true;
|
||||
ALTER TABLE "Product" ADD COLUMN "allowCashCheck" BOOLEAN NOT NULL DEFAULT true;
|
||||
ALTER TABLE "Product" ADD COLUMN "allowCheck" BOOLEAN NOT NULL DEFAULT true;
|
||||
@@ -241,6 +241,11 @@ model Product {
|
||||
subtitle String?
|
||||
rollMeters Float @default(50)
|
||||
isNew Boolean @default(false)
|
||||
/// حداکثر مدت چک برای این محصول (ماه)
|
||||
maxCheckMonths Int @default(4)
|
||||
allowCash Boolean @default(true)
|
||||
allowCashCheck Boolean @default(true)
|
||||
allowCheck Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- سقف مدت چک و روشهای پرداخت مجاز برای هر محصول
|
||||
ALTER TABLE "Product" ADD COLUMN "maxCheckMonths" INTEGER NOT NULL DEFAULT 4;
|
||||
ALTER TABLE "Product" ADD COLUMN "allowCash" BOOLEAN NOT NULL DEFAULT true;
|
||||
ALTER TABLE "Product" ADD COLUMN "allowCashCheck" BOOLEAN NOT NULL DEFAULT true;
|
||||
ALTER TABLE "Product" ADD COLUMN "allowCheck" BOOLEAN NOT NULL DEFAULT true;
|
||||
@@ -241,6 +241,11 @@ model Product {
|
||||
subtitle String?
|
||||
rollMeters Float @default(50)
|
||||
isNew Boolean @default(false)
|
||||
/// حداکثر مدت چک برای این محصول (ماه)
|
||||
maxCheckMonths Int @default(4)
|
||||
allowCash Boolean @default(true)
|
||||
allowCashCheck Boolean @default(true)
|
||||
allowCheck Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
|
||||
+7
-3
File diff suppressed because one or more lines are too long
+148
-9
File diff suppressed because one or more lines are too long
@@ -4,12 +4,21 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { paymentLimitsForProducts } from '../products/payment-rules';
|
||||
import {
|
||||
AddCartItemDto,
|
||||
UpdateCartItemMeterageDto,
|
||||
UpdateCartNotesDto,
|
||||
} from './dto/cart.dto';
|
||||
|
||||
const cartProductPaymentSelect = {
|
||||
name: true,
|
||||
allowCash: true,
|
||||
allowCashCheck: true,
|
||||
allowCheck: true,
|
||||
maxCheckMonths: true,
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export class CartsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -187,12 +196,12 @@ export class CartsService {
|
||||
private async ensureCart(userId: string) {
|
||||
let cart = await this.prisma.cart.findFirst({
|
||||
where: { userId },
|
||||
include: { items: true },
|
||||
include: { items: { include: { product: { select: cartProductPaymentSelect } } } },
|
||||
});
|
||||
if (!cart) {
|
||||
cart = await this.prisma.cart.create({
|
||||
data: { userId },
|
||||
include: { items: true },
|
||||
include: { items: { include: { product: { select: cartProductPaymentSelect } } } },
|
||||
});
|
||||
}
|
||||
return cart;
|
||||
@@ -216,6 +225,13 @@ export class CartsService {
|
||||
notes: string | null;
|
||||
companyId: string;
|
||||
companyName: string;
|
||||
product: {
|
||||
name: string;
|
||||
allowCash: boolean;
|
||||
allowCashCheck: boolean;
|
||||
allowCheck: boolean;
|
||||
maxCheckMonths: number;
|
||||
} | null;
|
||||
}>;
|
||||
}) {
|
||||
const companyNames = [
|
||||
@@ -227,6 +243,9 @@ export class CartsService {
|
||||
companyId: cart.companyId ?? cart.items[0]?.companyId,
|
||||
companyName: companyNames.join('، '),
|
||||
notes: cart.notes ?? undefined,
|
||||
paymentLimits: paymentLimitsForProducts(
|
||||
cart.items.flatMap((item) => (item.product ? [item.product] : [])),
|
||||
),
|
||||
items: cart.items.map((item) => ({
|
||||
id: item.id,
|
||||
productId: item.productId,
|
||||
|
||||
@@ -31,6 +31,10 @@ import {
|
||||
usesCashReceiptPhase,
|
||||
usesCheckSettlement,
|
||||
} from '../common/utils/settlement-type';
|
||||
import {
|
||||
assertPaymentFitsProducts,
|
||||
paymentLimitsForProducts,
|
||||
} from '../products/payment-rules';
|
||||
import { earliestCashInvoiceExpiry } from '../common/utils/cash-expiry';
|
||||
import {
|
||||
resolveAdminStatusFilter,
|
||||
@@ -53,7 +57,19 @@ import {
|
||||
} from '../common/utils/phone';
|
||||
|
||||
const orderInclude = {
|
||||
items: true,
|
||||
items: {
|
||||
include: {
|
||||
product: {
|
||||
select: {
|
||||
name: true,
|
||||
allowCash: true,
|
||||
allowCashCheck: true,
|
||||
allowCheck: true,
|
||||
maxCheckMonths: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
checks: { orderBy: { row: 'asc' as const } },
|
||||
cashReceipt: true,
|
||||
statusHistory: { orderBy: { changedAt: 'asc' as const } },
|
||||
@@ -64,6 +80,15 @@ const orderInclude = {
|
||||
|
||||
type OrderFull = Prisma.OrderGetPayload<{ include: typeof orderInclude }>;
|
||||
|
||||
/** داشبورد سفارش را بدون join محصول میفرستد؛ محدودیت پرداخت فقط وقتی محصول هست حساب میشود. */
|
||||
type OrderMappable = Omit<OrderFull, 'items'> & {
|
||||
items: Array<
|
||||
Omit<OrderFull['items'][number], 'product'> & {
|
||||
product?: OrderFull['items'][number]['product'];
|
||||
}
|
||||
>;
|
||||
};
|
||||
|
||||
/** مبالغ ریالی روی Float ذخیره میشوند؛ گرد کردن از انباشت خطای اعشاری جلوگیری میکند. */
|
||||
function roundMoney(value: number): number {
|
||||
return Math.round(value * 100) / 100;
|
||||
@@ -148,9 +173,10 @@ export class OrdersService {
|
||||
}
|
||||
|
||||
async submitOrder(userId: string, dto: SubmitOrderDto) {
|
||||
const { itemsData, totalMeterage, primaryCompany, companyNames, uniqueProductIds } =
|
||||
const { itemsData, totalMeterage, primaryCompany, companyNames, uniqueProductIds, products } =
|
||||
await this.resolveOrderLines(dto.items, dto.companyId);
|
||||
const plan = this.resolvePaymentPlan(dto);
|
||||
assertPaymentFitsProducts(products, plan.settlementType, plan.checkTermMonths);
|
||||
|
||||
const order = await this.createWithUniqueOrderNumber((orderNumber) =>
|
||||
this.prisma.$transaction(async (tx) => {
|
||||
@@ -299,6 +325,22 @@ export class OrdersService {
|
||||
);
|
||||
}
|
||||
const plan = this.resolvePaymentPlan(dto);
|
||||
const productIds = order.items
|
||||
.map((item) => item.productId)
|
||||
.filter((id): id is string => !!id);
|
||||
const products = productIds.length
|
||||
? await this.prisma.product.findMany({
|
||||
where: { id: { in: productIds } },
|
||||
select: {
|
||||
name: true,
|
||||
allowCash: true,
|
||||
allowCashCheck: true,
|
||||
allowCheck: true,
|
||||
maxCheckMonths: true,
|
||||
},
|
||||
})
|
||||
: [];
|
||||
assertPaymentFitsProducts(products, plan.settlementType, plan.checkTermMonths);
|
||||
await this.prisma.order.update({
|
||||
where: { id },
|
||||
data: {
|
||||
@@ -987,6 +1029,13 @@ export class OrdersService {
|
||||
primaryCompany,
|
||||
companyNames,
|
||||
uniqueProductIds,
|
||||
products: products.map((product) => ({
|
||||
name: product.name,
|
||||
allowCash: product.allowCash,
|
||||
allowCashCheck: product.allowCashCheck,
|
||||
allowCheck: product.allowCheck,
|
||||
maxCheckMonths: product.maxCheckMonths,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -999,7 +1048,7 @@ export class OrdersService {
|
||||
return order;
|
||||
}
|
||||
|
||||
mapOrder(order: OrderFull, adminView = false) {
|
||||
mapOrder(order: OrderMappable, adminView = false) {
|
||||
const customerName = joinFullName(
|
||||
order.user.firstName,
|
||||
order.user.lastName,
|
||||
@@ -1025,6 +1074,9 @@ export class OrdersService {
|
||||
settlementType: order.settlementType,
|
||||
settlementMethod: order.settlementType,
|
||||
checkTermMonths: order.checkTermMonths ?? undefined,
|
||||
paymentLimits: paymentLimitsForProducts(
|
||||
order.items.flatMap((item) => (item.product ? [item.product] : [])),
|
||||
),
|
||||
checkMode: order.checkMode ?? undefined,
|
||||
status: order.status,
|
||||
adminStatus: toAdminStatus(order.status),
|
||||
|
||||
@@ -2,9 +2,11 @@ import { OmitType, PartialType } from '@nestjs/mapped-types';
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsInt,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
@@ -139,6 +141,26 @@ export class CreateProductDto {
|
||||
@IsBoolean()
|
||||
isNew?: boolean;
|
||||
|
||||
/** حداکثر مدت چک (ماه) برای این محصول */
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(4)
|
||||
maxCheckMonths?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowCash?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowCashCheck?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowCheck?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => transformColorsJson(value))
|
||||
@IsArray()
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { SettlementType } from '@prisma/client';
|
||||
|
||||
export type ProductPaymentRule = {
|
||||
name: string;
|
||||
allowCash: boolean;
|
||||
allowCashCheck: boolean;
|
||||
allowCheck: boolean;
|
||||
maxCheckMonths: number;
|
||||
};
|
||||
|
||||
const METHOD_LABEL: Record<SettlementType, string> = {
|
||||
cash: 'نقدی',
|
||||
cash_check: 'نصف نقد، نصف چکی',
|
||||
check: 'چکی',
|
||||
};
|
||||
|
||||
export function productAllowsMethod(
|
||||
product: ProductPaymentRule,
|
||||
method: SettlementType,
|
||||
): boolean {
|
||||
if (method === 'cash') return product.allowCash;
|
||||
if (method === 'cash_check') return product.allowCashCheck;
|
||||
return product.allowCheck;
|
||||
}
|
||||
|
||||
export function paymentLimitsForProducts(products: ProductPaymentRule[]) {
|
||||
const methods = (
|
||||
['cash', 'cash_check', 'check'] as SettlementType[]
|
||||
).filter((method) =>
|
||||
products.every((product) => productAllowsMethod(product, method)),
|
||||
);
|
||||
const participants = products.filter(
|
||||
(product) =>
|
||||
(methods.includes('check') && product.allowCheck) ||
|
||||
(methods.includes('cash_check') && product.allowCashCheck),
|
||||
);
|
||||
const maxCheckMonths = participants.length
|
||||
? Math.min(...participants.map((product) => product.maxCheckMonths))
|
||||
: 4;
|
||||
return { methods, maxCheckMonths };
|
||||
}
|
||||
|
||||
export function assertPaymentFitsProducts(
|
||||
products: ProductPaymentRule[],
|
||||
settlementType: SettlementType,
|
||||
checkTermMonths: number | null,
|
||||
) {
|
||||
const limits = paymentLimitsForProducts(products);
|
||||
if (!limits.methods.includes(settlementType)) {
|
||||
const blocked = products.filter(
|
||||
(product) => !productAllowsMethod(product, settlementType),
|
||||
);
|
||||
const names = blocked.map((product) => product.name).join('، ');
|
||||
throw new BadRequestException(
|
||||
names
|
||||
? `روش «${METHOD_LABEL[settlementType]}» برای «${names}» مجاز نیست`
|
||||
: 'روش پرداخت انتخابشده برای محصولات این سفارش مجاز نیست',
|
||||
);
|
||||
}
|
||||
if (settlementType === 'cash') return;
|
||||
if (
|
||||
checkTermMonths == null ||
|
||||
checkTermMonths < 1 ||
|
||||
checkTermMonths > limits.maxCheckMonths
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
`مدت چک برای این محصولات حداکثر ${limits.maxCheckMonths} ماه است`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
@@ -117,6 +118,11 @@ export class ProductsService {
|
||||
async create(dto: CreateProductDto, preservedColorsJson?: unknown) {
|
||||
const code = (dto.code || dto.productCode || '').trim();
|
||||
if (!code) throw new ConflictException('کد محصول الزامی است');
|
||||
this.assertPaymentSelection(
|
||||
dto.allowCash ?? true,
|
||||
dto.allowCashCheck ?? true,
|
||||
dto.allowCheck ?? true,
|
||||
);
|
||||
const companyId = await resolveProductCompanyId(
|
||||
this.prisma,
|
||||
dto.companyId,
|
||||
@@ -145,6 +151,10 @@ export class ProductsService {
|
||||
subtitle: dto.subtitle?.trim() || null,
|
||||
rollMeters: dto.rollMeters,
|
||||
isNew: dto.isNew,
|
||||
maxCheckMonths: dto.maxCheckMonths ?? 4,
|
||||
allowCash: dto.allowCash ?? true,
|
||||
allowCashCheck: dto.allowCashCheck ?? true,
|
||||
allowCheck: dto.allowCheck ?? true,
|
||||
colorsJson: this.colorsJsonForWrite(
|
||||
preservedColorsJson,
|
||||
dto.colorsJson,
|
||||
@@ -172,7 +182,12 @@ export class ProductsService {
|
||||
dto: UpdateProductDto,
|
||||
preservedColorsJson?: unknown,
|
||||
) {
|
||||
await this.ensure(id);
|
||||
const existing = await this.ensure(id);
|
||||
this.assertPaymentSelection(
|
||||
dto.allowCash ?? existing.allowCash,
|
||||
dto.allowCashCheck ?? existing.allowCashCheck,
|
||||
dto.allowCheck ?? existing.allowCheck,
|
||||
);
|
||||
const code =
|
||||
dto.code !== undefined
|
||||
? dto.code.trim()
|
||||
@@ -239,6 +254,10 @@ export class ProductsService {
|
||||
: dto.subtitle?.trim() || null,
|
||||
rollMeters: dto.rollMeters,
|
||||
isNew: dto.isNew,
|
||||
maxCheckMonths: dto.maxCheckMonths,
|
||||
allowCash: dto.allowCash,
|
||||
allowCashCheck: dto.allowCashCheck,
|
||||
allowCheck: dto.allowCheck,
|
||||
colorsJson:
|
||||
dto.colorsJson === undefined && preservedColorsJson === undefined
|
||||
? undefined
|
||||
@@ -348,6 +367,16 @@ export class ProductsService {
|
||||
return null;
|
||||
}
|
||||
|
||||
private assertPaymentSelection(
|
||||
allowCash: boolean,
|
||||
allowCashCheck: boolean,
|
||||
allowCheck: boolean,
|
||||
) {
|
||||
if (!allowCash && !allowCashCheck && !allowCheck) {
|
||||
throw new BadRequestException('حداقل یک روش پرداخت برای محصول لازم است');
|
||||
}
|
||||
}
|
||||
|
||||
private async ensure(id: string) {
|
||||
const product = await this.prisma.product.findUnique({ where: { id } });
|
||||
if (!product) throw new NotFoundException('محصول یافت نشد');
|
||||
@@ -383,6 +412,10 @@ export class ProductsService {
|
||||
subtitle?: string | null;
|
||||
rollMeters?: number;
|
||||
isNew?: boolean;
|
||||
maxCheckMonths?: number;
|
||||
allowCash?: boolean;
|
||||
allowCashCheck?: boolean;
|
||||
allowCheck?: boolean;
|
||||
},
|
||||
hidePrice = false,
|
||||
) {
|
||||
@@ -437,6 +470,10 @@ export class ProductsService {
|
||||
subtitle: product.subtitle ?? undefined,
|
||||
rollMeters: product.rollMeters ?? 50,
|
||||
isNew: product.isNew ?? false,
|
||||
maxCheckMonths: product.maxCheckMonths ?? 4,
|
||||
allowCash: product.allowCash ?? true,
|
||||
allowCashCheck: product.allowCashCheck ?? true,
|
||||
allowCheck: product.allowCheck ?? true,
|
||||
createdAt: product.createdAt.toISOString(),
|
||||
updatedAt: product.updatedAt.toISOString(),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user