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

+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,
};
}
}