order calc

This commit is contained in:
2026-01-26 12:21:04 +03:30
parent 5031e34064
commit 062365d437
6 changed files with 124 additions and 76 deletions
@@ -3,10 +3,14 @@ import {
IsInt, IsArray, IsNumber, IsInt, IsArray, IsNumber,
IsNotEmpty, IsNotEmpty,
ArrayMinSize, ArrayMinSize,
IsMobilePhone IsMobilePhone,
IsOptional,
IsBoolean,
IsEnum
} from 'class-validator'; } from 'class-validator';
import { ApiPropertyOptional, ApiProperty } from '@nestjs/swagger'; import { ApiPropertyOptional, ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { OrderStatusEnum } from '../interface/order.interface';
export class CreateOrderItemDto { export class CreateOrderItemDto {
@@ -38,14 +42,13 @@ export class CreateOrderItemDto {
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
attachments: { url: string, type: string }[] attachments: { url: string, type: string }[]
} }
export class CreateOrderAsAdminDto { export class CreateOrderAsAdminDto {
@ApiPropertyOptional({ example: 'توضیحات' }) @ApiProperty({ example: '' })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@IsMobilePhone('fa-IR') userId: string
userPhone: string
@IsArray() @IsArray()
@ApiProperty({ @ApiProperty({
@@ -62,5 +65,33 @@ export class CreateOrderAsAdminDto {
@Type(() => CreateOrderItemDto) @Type(() => CreateOrderItemDto)
items: CreateOrderItemDto[]; items: CreateOrderItemDto[];
@ApiProperty({ example: '' })
@IsString()
@IsNotEmpty()
designerId: string
@ApiProperty({ example: '' })
@IsArray()
@IsString({ each: true })
@IsNotEmpty()
attachments: string[]
@ApiProperty({})
@IsString()
@IsOptional()
paymentMethod: string
@ApiProperty({})
@IsBoolean()
enableTax: Boolean
@ApiProperty({})
@IsInt()
estimatedDays: number
@ApiProperty({ enum: OrderStatusEnum })
@IsEnum(OrderStatusEnum)
status: OrderStatusEnum
} }
@@ -22,24 +22,24 @@ export class OrderItem extends BaseEntity {
@Property({ type: 'int' }) @Property({ type: 'int' })
quantity!: number; quantity!: number;
@Property({ type: 'decimal', precision: 10, scale: 0 }) @Property({ type: 'decimal', precision: 10, scale: 0, nullable: true, })
unitPrice!: number; unitPrice?: number;
get subTotal(): number { get subTotal(): number {
return Number(this.unitPrice) * (this.quantity) return Number(this.unitPrice) * (this.quantity)
} }
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 }) @Property({ type: 'decimal', precision: 10, scale: 0, nullable: true })
discount: number = 0; discount?: number;
get total(): number { get total(): number {
return Number(this.subTotal) - Number(this.discount || 0) return Number(this.subTotal) - Number(this.discount || 0)
} }
@Property({type:'text', nullable: true }) @Property({ type: 'text', nullable: true })
description?: string; description?: string;
@Property({type:'text', nullable: true }) @Property({ type: 'text', nullable: true })
adminDescription?: string; adminDescription?: string;
@Property({ type: 'json', nullable: true }) @Property({ type: 'json', nullable: true })
+16 -19
View File
@@ -55,44 +55,41 @@ export class Order extends BaseEntity {
orderNumber?: number; orderNumber?: number;
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 }) @Property({ type: 'decimal', precision: 10, scale: 0, default: null, nullable: true })
discount: number = 0; discount?: number;
@Property({ type: 'decimal', precision: 10, scale: 0 }) @Property({ type: 'decimal', precision: 10, scale: 0, default: null, nullable: true })
subTotal!: number; subTotal?: number;
@Property({ type: 'decimal', precision: 10, scale: 0 }) @Property({ type: 'decimal', precision: 10, scale: 0, default: null, nullable: true })
taxAmount: number; taxAmount?: number;
@Property({ type: 'decimal', precision: 10, scale: 0 }) @Property({ type: 'decimal', precision: 10, scale: 0, default: null, nullable: true })
total!: number; total?: number;
@Property({ type: 'decimal', precision: 10, scale: 0 }) @Property({ type: 'decimal', precision: 10, scale: 0, default: null, nullable: true })
paidAmount!: number; paidAmount?: number;
// private _balance!: number; // private _balance!: number;
@Property({ type: 'decimal', precision: 10, scale: 0 })
balance!: number;
@Property({ type: 'decimal', precision: 10, scale: 0, nullable: true })
dueDate?: number; // number of days to be done
// get balance(): number { // get balance(): number {
// return this._balance // return this._balance
// } // }
// set balance(value) { // set balance(value) {
// this._balance = this.total - this.paidAmount // this._balance = this.total - this.paidAmount
// } // }
// @Property({ type: 'text', nullable: true })
// description?: string; @Property({ type: 'decimal', precision: 10, scale: 0, default: null, nullable: true })
balance?: number;
@Property({ type: 'int', nullable: true })
estimatedDays?: number; // number of days to be done
@Enum(() => OrderStatusEnum) @Enum(() => OrderStatusEnum)
status!: OrderStatusEnum; status!: OrderStatusEnum;
@Property({ type: 'json', nullable: true }) @Property({ type: 'json', nullable: true })
attachments?: string[] attachments?: string[]
+14 -2
View File
@@ -26,7 +26,7 @@ export enum OrderStatusEnum {
} }
export interface AddOrderItem { export interface IAddOrderItem {
productId: bigint; productId: bigint;
quantity: number quantity: number
attributesValues: string[] attributesValues: string[]
@@ -36,5 +36,17 @@ export interface AddOrderItem {
discount?: number discount?: number
} }
export type UpdateOrderItem = Partial<AddOrderItem> export type IUpdateOrderItem = Partial<IAddOrderItem>
export interface ICreateOrder {
userId: string
items: IAddOrderItem[];
status: OrderStatusEnum
//optional
enableTax?: Boolean
attachments?: string[]
paymentMethod?: string
adminId?: string
estimatedDays?: number
designerId?: string
}
+42 -38
View File
@@ -6,7 +6,7 @@ import { FindOrdersDto } from '../dto/find-orders.dto';
import { EventEmitter2 } from '@nestjs/event-emitter'; import { EventEmitter2 } from '@nestjs/event-emitter';
import { CreateOrderDto, CreateOrderItemAsUserDto, CreateOrderItemDtoAsAdmin } from '../dto/create-order.dto'; import { CreateOrderDto, CreateOrderItemAsUserDto, CreateOrderItemDtoAsAdmin } from '../dto/create-order.dto';
import { UserService } from 'src/modules/user/providers/user.service'; import { UserService } from 'src/modules/user/providers/user.service';
import { AddOrderItem, OrderStatusEnum, UpdateOrderItem } from '../interface/order.interface'; import { IAddOrderItem, ICreateOrder, OrderStatusEnum, IUpdateOrderItem } from '../interface/order.interface';
import { OrderItemRepository } from '../repositories/order-item.repository'; import { OrderItemRepository } from '../repositories/order-item.repository';
import { ProductService } from 'src/modules/product/providers/product.service'; import { ProductService } from 'src/modules/product/providers/product.service';
import { ProductRepository } from 'src/modules/product/repositories/product.repository'; import { ProductRepository } from 'src/modules/product/repositories/product.repository';
@@ -18,6 +18,7 @@ import { Order } from '../entities/order.entity';
import { PaymentRepository } from 'src/modules/payment/repositories/payment.repository'; import { PaymentRepository } from 'src/modules/payment/repositories/payment.repository';
import { UpdateOrderItemDtoAsAdmin, UpdateOrderItemDtoAsUser } from '../dto/update-order-item.dto'; import { UpdateOrderItemDtoAsAdmin, UpdateOrderItemDtoAsUser } from '../dto/update-order-item.dto';
import { UpdateOrderDto } from '../dto/update-order.dto'; import { UpdateOrderDto } from '../dto/update-order.dto';
import { Admin } from 'src/modules/admin/entities/admin.entity';
@Injectable() @Injectable()
@@ -131,7 +132,7 @@ export class OrderService {
return orderItem return orderItem
} }
private async persistOrderItem(order: Order, dto: AddOrderItem) { private async persistOrderItem(order: Order, dto: IAddOrderItem) {
const { attributesValues, description, productId, quantity, attachments, discount, unitPrice } = dto const { attributesValues, description, productId, quantity, attachments, discount, unitPrice } = dto
const found = order.items.find(it => it.product.id == productId) const found = order.items.find(it => it.product.id == productId)
@@ -187,7 +188,7 @@ export class OrderService {
return orderItem return orderItem
} }
async updateOrderItem(itemId: string, dto: UpdateOrderItem) { async updateOrderItem(itemId: string, dto: IUpdateOrderItem) {
const { attributesValues, description, productId, quantity, attachments, discount, unitPrice } = dto const { attributesValues, description, productId, quantity, attachments, discount, unitPrice } = dto
const orderItem = await this.orderItemRepository.findOne({ const orderItem = await this.orderItemRepository.findOne({
@@ -277,16 +278,39 @@ export class OrderService {
} }
async createOrderAsAdmin(adminId: string, dto: CreateOrderAsAdminDto) { async createOrderAsAdmin(adminId: string, dto: CreateOrderAsAdminDto) {
const { items, userPhone } = dto const order = await this.createOrder({ ...dto, adminId })
return order
const user = await this.userService.findByPhone(userPhone) }
async createOrderAsUser(userId: string, dto: CreateOrderDto) {
const order = await this.createOrder({ ...dto, userId, status: OrderStatusEnum.CREATED })
return order
}
async createOrder(dto: ICreateOrder) {
const { items, userId, attachments, designerId, enableTax, estimatedDays, paymentMethod, status, adminId } = dto
const user = await this.userService.findById(userId)
if (!user) { if (!user) {
throw new BadRequestException("User with this phone not found!") throw new BadRequestException("User not found!")
} }
const admin = await this.adminRepository.findOne({ id: adminId }) let admin: null | Admin = null
if (!admin) { if (adminId) {
throw new BadRequestException("Admin not found") admin = await this.adminRepository.findOne({ id: adminId })
if (!admin) {
throw new BadRequestException("Admin not found")
}
}
let designer: null | Admin = null
if (designerId) {
designer = await this.adminRepository.findOne({ id: designerId })
if (!designer) {
throw new BadRequestException("designer not found")
}
} }
const order = await this.em.transactional(async (em) => { const order = await this.em.transactional(async (em) => {
@@ -294,13 +318,12 @@ export class OrderService {
const order = this.orderRepository.create({ const order = this.orderRepository.create({
creator: admin, creator: admin,
user, user,
discount: 0, attachments,
subTotal: 0, designer,
total: 0, enableTax,
paidAmount: 0, estimatedDays,
balance: 0, paymentMethod,
status: OrderStatusEnum.INVOICED, status,
taxAmount: 0
}) })
em.persist(order) em.persist(order)
@@ -314,33 +337,14 @@ export class OrderService {
} }
items.forEach(item => { items.forEach(item => {
const product = products.find(p => p.id == item.productId) this.persistOrderItem(order, item)
if (!product) {
throw new BadRequestException(`product ${product} not found`)
}
const orderItem = this.orderItemRepository.create({
order,
attributesValues: item.attributesValues,
product,
quantity: item.quantity,
unitPrice: item.unitPrice,
total: item.unitPrice * item.quantity,
discount: item.discount,
subTotal: item.unitPrice * item.quantity - item.discount,
attachments: item.attachments,
description: item.description
})
em.persist(orderItem)
}); });
// TODO : calculation must be done after create order // TODO : calculation must be done after create order
await this.calculateOrder(order) await this.calculateOrder(order)
await em.flush() // await em.flush()
return order return order
}) })
@@ -381,7 +385,7 @@ export class OrderService {
// TODO : use reduce // TODO : use reduce
for (let orderItem of order.items) { for (let orderItem of order.items) {
subTotal += orderItem.total subTotal += orderItem.total
totalDiscount += orderItem.discount totalDiscount += Number(orderItem.discount)
} }
const totalBeforeTax = subTotal - totalDiscount const totalBeforeTax = subTotal - totalDiscount
@@ -67,6 +67,10 @@ export class PaymentService {
throw new NotFoundException(OrderMessage.NOT_FOUND); throw new NotFoundException(OrderMessage.NOT_FOUND);
} }
if (!order.balance) {
throw new NotFoundException('Balance is not set');
}
let admin: null | Admin = null let admin: null | Admin = null
if (adminId) { if (adminId) {
admin = await this.adminRepository.findOne({ id: adminId }) admin = await this.adminRepository.findOne({ id: adminId })
@@ -218,8 +222,8 @@ export class PaymentService {
payment.transactionId = referenceId; payment.transactionId = referenceId;
// TODO : use decimal js // TODO : use decimal js
// does need persist or not // does need persist or not
payment.order.paidAmount += payment.amount payment.order.paidAmount! += payment.amount
payment.order.balance -= payment.amount payment.order.balance! -= payment.amount
await em.flush(); await em.flush();
return payment; return payment;
@@ -257,8 +261,8 @@ export class PaymentService {
payment.failedAt = null; payment.failedAt = null;
// TODO : use decimal js // TODO : use decimal js
payment.order.paidAmount += payment.amount payment.order.paidAmount! += payment.amount
payment.order.balance -= payment.amount payment.order.balance! -= payment.amount
em.persist(payment); em.persist(payment);
em.persist(payment.order); em.persist(payment.order);
@@ -282,8 +286,8 @@ export class PaymentService {
} }
if (payment.status == PaymentStatusEnum.Paid) { if (payment.status == PaymentStatusEnum.Paid) {
payment.order.paidAmount -= payment.amount payment.order.paidAmount! -= payment.amount
payment.order.balance += payment.amount payment.order.balance! += payment.amount
em.persistAndFlush(payment.order) em.persistAndFlush(payment.order)
} }