feat(admin): implement smart pricing, rounding rules, formula margins and bulk price adjustment
Deploy Canina / deploy (push) Successful in 45s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 6s

This commit is contained in:
parsa aghaei committed 2026-09-02 10:05:41 +03:30
1 parent 382ebc0ce6
commit ac15ece619
21 files changed
+17219 -14083

No files matched your search

+2
View File
@@ -201,6 +201,8 @@ model Product {
wholesalePrice Decimal? @map("wholesale_price") @db.Decimal(15, 2)
requiresRx Boolean @default(false) @map("requires_rx")
buyPrice Decimal @default(0) @map("buy_price") @db.Decimal(15, 2)
marginRetailPercent Decimal? @map("margin_retail_percent") @db.Decimal(6, 2)
marginWholesalePercent Decimal? @map("margin_wholesale_percent") @db.Decimal(6, 2)
priceDisplay String @map("price_display") @db.VarChar(50)
unit String @db.VarChar(50)
packageSize Decimal @map("package_size") @db.Decimal(10, 2)
+32
View File
@@ -11,6 +11,11 @@ import {
} from '@nestjs/common';
import { AdminService, CouponInput } from './admin.service';
import { ProductDto } from './dto/product.dto';
import {
UpdatePricingSettingsDto,
ApplyGlobalMarginsDto,
BulkPriceAdjustmentDto,
} from './dto/pricing.dto';
import { AdminQueryDto } from './dto/admin-query.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import {
@@ -147,6 +152,33 @@ export class AdminController {
return { success: true };
}
@Get('pricing/settings')
@ApiOperation({ summary: 'دریافت تنظیمات هوشمند قیمت‌گذاری و گرد کردن' })
async getPricingSettings() {
const data = await this.adminService.getPricingSettings();
return { success: true, data };
}
@Put('pricing/settings')
@ApiOperation({ summary: 'بروزرسانی تنظیمات هوشمند قیمت‌گذاری و گرد کردن' })
async updatePricingSettings(@Body() dto: UpdatePricingSettingsDto) {
return this.adminService.updatePricingSettings(dto);
}
@Post('pricing/apply-global-margins')
@ApiOperation({ summary: 'اعمال سراسری درصد سود تک و عمده بر روی محصولات' })
async applyGlobalMargins(@Body() dto: ApplyGlobalMarginsDto) {
return this.adminService.applyGlobalMargins(dto);
}
@Post('pricing/bulk-adjust')
@ApiOperation({
summary: 'تغییرات گروهی قیمت (درصدی یا مبلغ ثابت) بر روی محصولات',
})
async bulkPriceAdjustment(@Body() dto: BulkPriceAdjustmentDto) {
return this.adminService.bulkPriceAdjustment(dto);
}
@Get('orders')
@ApiOperation({ summary: 'لیست سفارش‌ها (مدیریت)' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
+305
View File
@@ -10,6 +10,18 @@ import { RedisService } from '../redis/redis.service';
import * as bcrypt from 'bcryptjs';
import { CreateUserDto, UpdateUserDto } from './dto/user.dto';
import { ProductDto } from './dto/product.dto';
import {
UpdatePricingSettingsDto,
ApplyGlobalMarginsDto,
BulkPriceAdjustmentDto,
} from './dto/pricing.dto';
import {
DEFAULT_PRICING_SETTINGS,
PricingSettings,
applyRounding,
calculateSellingPrice,
RoundingMode,
} from '../common/utils/pricing.utils';
import { normalizeMobile } from '../common/utils/phone.utils';
import { CANONICAL_ALIASES } from '../settings/settings.service';
import { RevalidationService } from '../common/revalidation/revalidation.service';
@@ -424,6 +436,11 @@ export class AdminService {
}
async createProduct(data: ProductDto) {
const marginRetail =
data.marginRetailPercent ?? data.priceValueMarginPercent;
const marginWholesale =
data.marginWholesalePercent ?? data.wholesaleMarginPercent;
const product = await this.prisma.product.create({
data: {
artNo: data.artNo || `ART-${Date.now()}`,
@@ -435,6 +452,10 @@ export class AdminService {
categoryId: data.categoryId || '',
categorySlug: data.categorySlug || 'general',
buyPrice: data.buyPrice !== undefined ? data.buyPrice : 0,
marginRetailPercent:
marginRetail !== undefined ? marginRetail : undefined,
marginWholesalePercent:
marginWholesale !== undefined ? marginWholesale : undefined,
priceValue: data.priceValue || 0,
wholesalePrice:
data.wholesalePrice !== undefined ? data.wholesalePrice : null,
@@ -498,6 +519,11 @@ export class AdminService {
throw new NotFoundException(`محصولی با شناسه ${id} یافت نشد.`);
}
const marginRetail =
data.marginRetailPercent ?? data.priceValueMarginPercent;
const marginWholesale =
data.marginWholesalePercent ?? data.wholesaleMarginPercent;
const product = await this.prisma.product.update({
where: { id },
data: {
@@ -510,6 +536,10 @@ export class AdminService {
categoryId: data.categoryId,
categorySlug: data.categorySlug,
buyPrice: data.buyPrice !== undefined ? data.buyPrice : undefined,
marginRetailPercent:
marginRetail !== undefined ? marginRetail : undefined,
marginWholesalePercent:
marginWholesale !== undefined ? marginWholesale : undefined,
priceValue: data.priceValue,
wholesalePrice:
data.wholesalePrice !== undefined ? data.wholesalePrice : undefined,
@@ -1027,4 +1057,279 @@ export class AdminService {
return transaction;
}
async getPricingSettings(): Promise<PricingSettings> {
const setting = await this.prisma.setting.findUnique({
where: { key: 'pricing_config' },
});
if (!setting || !setting.value || typeof setting.value !== 'object') {
return DEFAULT_PRICING_SETTINGS;
}
const val = setting.value as Record<string, any>;
return {
roundingStep: Number(
val.roundingStep ?? DEFAULT_PRICING_SETTINGS.roundingStep,
),
roundingMode: (val.roundingMode ||
DEFAULT_PRICING_SETTINGS.roundingMode) as RoundingMode,
defaultRetailMarginPercent: Number(
val.defaultRetailMarginPercent ??
DEFAULT_PRICING_SETTINGS.defaultRetailMarginPercent,
),
defaultWholesaleMarginPercent: Number(
val.defaultWholesaleMarginPercent ??
DEFAULT_PRICING_SETTINGS.defaultWholesaleMarginPercent,
),
};
}
async updatePricingSettings(dto: UpdatePricingSettingsDto) {
const value = {
roundingStep: Number(dto.roundingStep ?? 5000),
roundingMode: dto.roundingMode || 'UP',
defaultRetailMarginPercent: Number(dto.defaultRetailMarginPercent ?? 30),
defaultWholesaleMarginPercent: Number(
dto.defaultWholesaleMarginPercent ?? 15,
),
};
await this.prisma.setting.upsert({
where: { key: 'pricing_config' },
update: { category: 'pricing', value },
create: { key: 'pricing_config', category: 'pricing', value },
});
return {
success: true,
message: 'تنظیمات قیمت‌گذاری و گرد کردن با موفقیت ذخیره شد.',
data: value,
};
}
async applyGlobalMargins(dto: ApplyGlobalMarginsDto) {
const pricingSettings = await this.getPricingSettings();
const roundingStep =
dto.roundingStep !== undefined
? Number(dto.roundingStep)
: pricingSettings.roundingStep;
const roundingMode = (dto.roundingMode ||
pricingSettings.roundingMode) as RoundingMode;
const retailMargin = Number(dto.retailMarginPercent);
const wholesaleMargin = Number(dto.wholesaleMarginPercent);
const whereCondition: Prisma.ProductWhereInput = {};
if (
dto.scope === 'CATEGORY' &&
dto.categoryIds &&
dto.categoryIds.length > 0
) {
whereCondition.categoryId = { in: dto.categoryIds };
} else if (
dto.scope === 'SPECIFIC' &&
dto.productIds &&
dto.productIds.length > 0
) {
whereCondition.id = { in: dto.productIds };
}
const products = await this.prisma.product.findMany({
where: whereCondition,
select: {
id: true,
slug: true,
artNo: true,
buyPrice: true,
priceValue: true,
wholesalePrice: true,
},
});
let updatedCount = 0;
const revalidateSlugs: string[] = [];
for (const prod of products) {
const buyPrice = Number(prod.buyPrice || 0);
if (buyPrice > 0) {
const newRetailPrice = calculateSellingPrice(
buyPrice,
retailMargin,
roundingStep,
roundingMode,
);
const newWholesalePrice = calculateSellingPrice(
buyPrice,
wholesaleMargin,
roundingStep,
roundingMode,
);
await this.prisma.product.update({
where: { id: prod.id },
data: {
priceValue: newRetailPrice,
wholesalePrice: newWholesalePrice,
marginRetailPercent: retailMargin,
marginWholesalePercent: wholesaleMargin,
},
});
updatedCount++;
if (prod.slug) revalidateSlugs.push(prod.slug);
}
}
if (revalidateSlugs.length > 0) {
for (const slug of revalidateSlugs.slice(0, 20)) {
this.revalidationService.revalidateProduct(slug).catch(() => {});
}
}
return {
success: true,
message: `درصد سود با موفقیت بر روی ${updatedCount} محصول اعمال و قیمت‌ها گرد شدند.`,
updatedCount,
totalMatched: products.length,
};
}
async bulkPriceAdjustment(dto: BulkPriceAdjustmentDto) {
const pricingSettings = await this.getPricingSettings();
const roundingStep =
dto.roundingStep !== undefined
? Number(dto.roundingStep)
: pricingSettings.roundingStep;
const roundingMode = (dto.roundingMode ||
pricingSettings.roundingMode) as RoundingMode;
const applyRound = dto.applyRounding !== false;
const adjValue = Number(dto.value || 0);
const whereCondition: Prisma.ProductWhereInput = {};
if (
dto.scope === 'CATEGORY' &&
dto.categoryIds &&
dto.categoryIds.length > 0
) {
whereCondition.categoryId = { in: dto.categoryIds };
} else if (
dto.scope === 'SPECIFIC' &&
dto.productIds &&
dto.productIds.length > 0
) {
whereCondition.id = { in: dto.productIds };
}
const products = await this.prisma.product.findMany({
where: whereCondition,
select: {
id: true,
slug: true,
artNo: true,
buyPrice: true,
priceValue: true,
wholesalePrice: true,
},
});
let updatedCount = 0;
const revalidateSlugs: string[] = [];
const computeNewPrice = (currentPrice: number): number => {
let result = currentPrice;
if (dto.adjustmentType === 'PERCENT') {
const factor =
dto.adjustmentDirection === 'INCREASE'
? 1 + adjValue / 100
: 1 - adjValue / 100;
result = currentPrice * Math.max(0, factor);
} else {
const delta =
dto.adjustmentDirection === 'INCREASE' ? adjValue : -adjValue;
result = Math.max(0, currentPrice + delta);
}
return applyRound
? applyRounding(result, roundingStep, roundingMode)
: Math.round(result);
};
for (const prod of products) {
const updateData: Prisma.ProductUpdateInput = {};
let changed = false;
const currentBuyPrice = Number(prod.buyPrice || 0);
const currentRetailPrice = Number(prod.priceValue || 0);
const currentWholesalePrice = Number(prod.wholesalePrice || 0);
let newBuyPrice = currentBuyPrice;
let newRetailPrice = currentRetailPrice;
let newWholesalePrice = currentWholesalePrice;
if (dto.targetField === 'BUY' || dto.targetField === 'ALL') {
if (currentBuyPrice > 0) {
newBuyPrice = computeNewPrice(currentBuyPrice);
updateData.buyPrice = newBuyPrice;
changed = true;
}
}
if (
dto.targetField === 'RETAIL' ||
dto.targetField === 'BOTH_SELLING' ||
dto.targetField === 'ALL'
) {
if (currentRetailPrice > 0) {
newRetailPrice = computeNewPrice(currentRetailPrice);
updateData.priceValue = newRetailPrice;
changed = true;
}
}
if (
dto.targetField === 'WHOLESALE' ||
dto.targetField === 'BOTH_SELLING' ||
dto.targetField === 'ALL'
) {
if (currentWholesalePrice > 0) {
newWholesalePrice = computeNewPrice(currentWholesalePrice);
updateData.wholesalePrice = newWholesalePrice;
changed = true;
}
}
if (changed) {
if (newBuyPrice > 0) {
if (newRetailPrice > 0) {
updateData.marginRetailPercent =
Math.round(
((newRetailPrice - newBuyPrice) / newBuyPrice) * 10000,
) / 100;
}
if (newWholesalePrice > 0) {
updateData.marginWholesalePercent =
Math.round(
((newWholesalePrice - newBuyPrice) / newBuyPrice) * 10000,
) / 100;
}
}
await this.prisma.product.update({
where: { id: prod.id },
data: updateData,
});
updatedCount++;
if (prod.slug) revalidateSlugs.push(prod.slug);
}
}
if (revalidateSlugs.length > 0) {
for (const slug of revalidateSlugs.slice(0, 20)) {
this.revalidationService.revalidateProduct(slug).catch(() => {});
}
}
return {
success: true,
message: `تغییرات قیمت با موفقیت بر روی ${updatedCount} محصول اعمال شد.`,
updatedCount,
totalMatched: products.length,
};
}
}
+158
View File
@@ -0,0 +1,158 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsNumber,
IsString,
IsIn,
IsOptional,
IsArray,
IsBoolean,
Min,
} from 'class-validator';
export class UpdatePricingSettingsDto {
@ApiProperty({ description: 'گام گرد کردن قیمت به تومان', example: 5000 })
@IsNumber()
@Min(0)
roundingStep!: number;
@ApiProperty({
description: 'جهت گرد کردن',
enum: ['UP', 'DOWN', 'NEAREST'],
example: 'UP',
})
@IsString()
@IsIn(['UP', 'DOWN', 'NEAREST'])
roundingMode!: 'UP' | 'DOWN' | 'NEAREST';
@ApiProperty({ description: 'درصد سود پیش‌فرض تک‌فروشی', example: 30 })
@IsNumber()
@Min(0)
defaultRetailMarginPercent!: number;
@ApiProperty({ description: 'درصد سود پیش‌فرض عمده‌فروشی', example: 15 })
@IsNumber()
@Min(0)
defaultWholesaleMarginPercent!: number;
}
export class ApplyGlobalMarginsDto {
@ApiProperty({ description: 'درصد سود تک‌فروشی برای اعمال سراسری', example: 30 })
@IsNumber()
@Min(0)
retailMarginPercent!: number;
@ApiProperty({ description: 'درصد سود عمده‌فروشی برای اعمال سراسری', example: 15 })
@IsNumber()
@Min(0)
wholesaleMarginPercent!: number;
@ApiPropertyOptional({ description: 'گام گرد کردن سفارشی (اختیاری)' })
@IsOptional()
@IsNumber()
@Min(0)
roundingStep?: number;
@ApiPropertyOptional({
description: 'جهت گرد کردن سفارشی',
enum: ['UP', 'DOWN', 'NEAREST'],
})
@IsOptional()
@IsString()
@IsIn(['UP', 'DOWN', 'NEAREST'])
roundingMode?: 'UP' | 'DOWN' | 'NEAREST';
@ApiPropertyOptional({
description: 'دامنه محصولات',
enum: ['ALL', 'CATEGORY', 'SPECIFIC'],
default: 'ALL',
})
@IsOptional()
@IsString()
@IsIn(['ALL', 'CATEGORY', 'SPECIFIC'])
scope?: 'ALL' | 'CATEGORY' | 'SPECIFIC';
@ApiPropertyOptional({ description: 'شناسه دسته‌بندی‌ها در صورت انتخاب دامنه CATEGORY' })
@IsOptional()
@IsArray()
categoryIds?: string[];
@ApiPropertyOptional({ description: 'شناسه محصولات در صورت انتخاب دامنه SPECIFIC' })
@IsOptional()
@IsArray()
productIds?: string[];
}
export class BulkPriceAdjustmentDto {
@ApiProperty({
description: 'دامنه محصولات',
enum: ['ALL', 'CATEGORY', 'SPECIFIC'],
example: 'ALL',
})
@IsString()
@IsIn(['ALL', 'CATEGORY', 'SPECIFIC'])
scope!: 'ALL' | 'CATEGORY' | 'SPECIFIC';
@ApiPropertyOptional({ description: 'شناسه دسته‌بندی‌ها در صورت انتخاب دامنه CATEGORY' })
@IsOptional()
@IsArray()
categoryIds?: string[];
@ApiPropertyOptional({ description: 'شناسه محصولات در صورت انتخاب دامنه SPECIFIC' })
@IsOptional()
@IsArray()
productIds?: string[];
@ApiProperty({
description: 'فیلد هدف برای تغییر قیمت',
enum: ['RETAIL', 'WHOLESALE', 'BUY', 'BOTH_SELLING', 'ALL'],
example: 'RETAIL',
})
@IsString()
@IsIn(['RETAIL', 'WHOLESALE', 'BUY', 'BOTH_SELLING', 'ALL'])
targetField!: 'RETAIL' | 'WHOLESALE' | 'BUY' | 'BOTH_SELLING' | 'ALL';
@ApiProperty({
description: 'نوع تغییر: PERCENT (درصدی) یا FIXED (مبلغ ثابت)',
enum: ['PERCENT', 'FIXED'],
example: 'PERCENT',
})
@IsString()
@IsIn(['PERCENT', 'FIXED'])
adjustmentType!: 'PERCENT' | 'FIXED';
@ApiProperty({
description: 'جهت تغییر: INCREASE (افزایش / گران‌تر) یا DECREASE (کاهش / ارزان‌تر)',
enum: ['INCREASE', 'DECREASE'],
example: 'INCREASE',
})
@IsString()
@IsIn(['INCREASE', 'DECREASE'])
adjustmentDirection!: 'INCREASE' | 'DECREASE';
@ApiProperty({
description: 'مقدار تغییر (مثلاً 10 برای 10 درصد، یا 100000 برای 100 هزار تومان)',
example: 10,
})
@IsNumber()
@Min(0)
value!: number;
@ApiPropertyOptional({ description: 'آیا پس از تغییر قیمت، گرد کردن اعمال شود؟', default: true })
@IsOptional()
@IsBoolean()
applyRounding?: boolean;
@ApiPropertyOptional({ description: 'گام گرد کردن سفارشی (در صورت خالی بودن از تنظیمات سیستم استفاده می‌شود)' })
@IsOptional()
@IsNumber()
roundingStep?: number;
@ApiPropertyOptional({
description: 'جهت گرد کردن سفارشی',
enum: ['UP', 'DOWN', 'NEAREST'],
})
@IsOptional()
@IsString()
@IsIn(['UP', 'DOWN', 'NEAREST'])
roundingMode?: 'UP' | 'DOWN' | 'NEAREST';
}
+10
View File
@@ -66,11 +66,21 @@ export class ProductDto {
@ApiPropertyOptional({ description: 'درصد سود قیمت مصرف‌کننده' })
@IsOptional()
@IsNumber()
marginRetailPercent?: number;
@ApiPropertyOptional({ description: 'درصد سود قیمت مصرف‌کننده (نام دیگر)' })
@IsOptional()
@IsNumber()
priceValueMarginPercent?: number;
@ApiPropertyOptional({ description: 'درصد سود قیمت عمده‌فروشی' })
@IsOptional()
@IsNumber()
marginWholesalePercent?: number;
@ApiPropertyOptional({ description: 'درصد سود قیمت عمده‌فروشی (نام دیگر)' })
@IsOptional()
@IsNumber()
wholesaleMarginPercent?: number;
@ApiPropertyOptional({ description: 'نمایش متنی قیمت' })
+52
View File
@@ -0,0 +1,52 @@
export type RoundingMode = 'UP' | 'DOWN' | 'NEAREST';
export interface PricingSettings {
roundingStep: number;
roundingMode: RoundingMode;
defaultRetailMarginPercent: number;
defaultWholesaleMarginPercent: number;
}
export const DEFAULT_PRICING_SETTINGS: PricingSettings = {
roundingStep: 5000,
roundingMode: 'UP',
defaultRetailMarginPercent: 30,
defaultWholesaleMarginPercent: 15,
};
/**
* Rounds a given numeric price according to the configured step and direction.
* @param price Raw price in Tomans
* @param step Rounding step (e.g. 1000, 5000, 10000, 50000)
* @param mode Direction: 'UP' (Ceil), 'DOWN' (Floor), 'NEAREST' (Round)
*/
export function applyRounding(
price: number,
step: number = 5000,
mode: RoundingMode = 'UP',
): number {
if (isNaN(price) || price <= 0) return 0;
if (!step || step <= 1) return Math.round(price);
if (mode === 'UP') {
return Math.ceil(price / step) * step;
} else if (mode === 'DOWN') {
return Math.floor(price / step) * step;
} else {
return Math.round(price / step) * step;
}
}
/**
* Calculates selling price from buy price and profit margin, with smart rounding applied.
*/
export function calculateSellingPrice(
buyPrice: number,
marginPercent: number,
roundingStep: number = 5000,
roundingMode: RoundingMode = 'UP',
): number {
if (isNaN(buyPrice) || buyPrice <= 0) return 0;
const rawPrice = buyPrice * (1 + (marginPercent || 0) / 100);
return applyRounding(rawPrice, roundingStep, roundingMode);
}