order update refactor

This commit is contained in:
2026-02-01 15:34:06 +03:30
parent 918d774cad
commit 71319de649
12 changed files with 129 additions and 31 deletions
@@ -5,7 +5,7 @@ import { Field } from './field.entity';
@Entity({ tableName: 'field_option' })
export class FieldOption extends BaseEntity {
@PrimaryKey({ autoincrement: true, type: 'bigint' })
id: bigint;
id: number;
@Property()
value: string;
@@ -7,7 +7,7 @@ import { BaseEntity } from 'src/common/entities/base.entity';
@Entity({ tableName: 'field' })
export class Field extends BaseEntity {
@PrimaryKey({ type: 'bigint', autoincrement: true })
id: bigint
id: number
@OneToMany(() => FieldOption, (attrValue) => attrValue.field)
options = new Collection<FieldOption>(this)
@@ -18,7 +18,7 @@ export class Field extends BaseEntity {
// Foreign key based on entityType
@Property({ type: 'bigint' })
entityId: bigint;
entityId: number;
@Property()
name: string;
@@ -7,7 +7,7 @@ import { Admin } from 'src/modules/admin/entities/admin.entity';
@Entity({ tableName: 'notifications' })
export class Notification extends BaseEntity {
@PrimaryKey({ type: 'bigint', autoincrement: true })
id: bigint
id: number
@ManyToOne(() => User, { nullable: true })
user?: User;
@@ -111,11 +111,18 @@ export class OrderController {
}
// @Patch('admin/orders/:orderId')
// @UseGuards(AdminAuthGuard)
// @ApiOperation({ summary: 'Update Order ' })
// updateOrder(@Param('orderId') orderId: string, @Body() dto: UpdateOrderAsAdminDto) {
// return this.orderService.updateOrderAsAdmin(orderId, dto);
// }
@Patch('admin/orders/:orderId')
@UseGuards(AdminAuthGuard)
@ApiOperation({ summary: 'Update Order ' })
updateOrder(@Param('orderId') orderId: string, @Body() dto: UpdateOrderAsAdminDto) {
return this.orderService.updateOrderAsAdmin(orderId, dto);
return this.orderService.updateOrderAsAdmin2(orderId, dto);
}
@Patch('admin/orders/:id/item/:itemId/print')
+12 -3
View File
@@ -5,7 +5,8 @@ import {
ArrayMinSize,
IsOptional,
IsBoolean,
IsEnum
IsEnum,
IsDateString
} from 'class-validator';
import { ApiPropertyOptional, ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
@@ -57,6 +58,14 @@ export class CreateOrderItemDtoAsAdmin extends CreateOrderItemAsUserDto {
@IsNumber()
discount: number
@ApiPropertyOptional()
@IsString()
adminDescription: string
@ApiPropertyOptional()
@IsDateString()
confirmedAt: string
}
export class CreateOrderAsUSerDto {
@@ -102,8 +111,8 @@ export class CreateOrderAsAdminDto {
// printAttachments: [{ url: '', type: '' }],
quantity: 100,
attributes: [],
unitPrice:150000,
discount:20000
unitPrice: 150000,
discount: 20000
}
]
})
+12 -3
View File
@@ -1,5 +1,14 @@
import { OmitType, PartialType } from '@nestjs/swagger';
import { CreateOrderAsAdminDto } from './create-order.dto';
import { ApiProperty, OmitType, PartialType } from '@nestjs/swagger';
import { CreateOrderAsAdminDto, CreateOrderItemDtoAsAdmin } from './create-order.dto';
import { IsNumber } from 'class-validator';
export class UpdateOrderAsAdminDto extends PartialType(OmitType(CreateOrderAsAdminDto, 'items' as any)) { }
export class UpdateOrderAsAdminDto extends PartialType(OmitType(CreateOrderAsAdminDto, 'items' as any)) {
@ApiProperty()
items: UpdateOrCreateOrderItem[]
}
export class UpdateOrCreateOrderItem extends CreateOrderItemDtoAsAdmin {
@ApiProperty()
@IsNumber()
id: number
}
@@ -12,7 +12,7 @@ export class OrderItem {
[OptionalProps]?: 'createdAt' | 'deletedAt' | 'subTotal' | 'total';
@PrimaryKey({ type: 'bigint', autoincrement: true })
id: bigint
id: number
@ManyToOne(() => Order)
order!: Order;
@@ -55,8 +55,8 @@ export class OrderItem {
@Property({ type: 'json', nullable: true })
attachments?: IAttachment[] // user attachments like voice and photos
@Property({ type: 'json', nullable: true })
printAttachments?: IAttachment[]
// @Property({ type: 'json', nullable: true })
// printAttachments?: IAttachment[]
@Property({ type: 'json', nullable: true })
+82 -9
View File
@@ -1,4 +1,4 @@
import { Injectable, BadRequestException, Logger } from '@nestjs/common';
import { Injectable, BadRequestException, Logger, BadGatewayException } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/postgresql';
import { OrderRepository } from '../repositories/order.repository';
import { FindOrdersDto } from '../dto/find-orders.dto';
@@ -30,6 +30,7 @@ import { AdminService } from 'src/modules/admin/providers/admin.service';
import { OrderItem } from '../entities/order-item.entity';
import { UpdateOrderAsAdminDto } from '../dto/update-order.dto';
import { CreatePrintFormDto } from '../dto/create-print-form.dto';
import { Product } from 'src/modules/product/entities/product.entity';
@Injectable()
@@ -67,11 +68,10 @@ export class OrderService {
}
async updateOrderAsAdmin(orderId: string, dto: UpdateOrderAsAdminDto) {
const order = await this.findOrderOrFail(orderId)
const updateOrder = await this.updateOrder(order, dto)
// const updateOrder = await this.updateOrder(order, dto)
// const updateOrder = await this.calculateOrder(order)
@@ -79,7 +79,82 @@ export class OrderService {
this.logger.log("Order updated as admin")
return updateOrder
// return updateOrder
}
async updateOrderAsAdmin2(orderId: string, dto: UpdateOrderAsAdminDto) {
const order = await this.findOrderOrFail(orderId)
const { items, ...rest } = dto
return this.em.transactional(async (em) => {
em.assign(order, rest)
for (const item of items) {
if (item.id) { // update
const currentItem = order.items.find(i => Number(i.id) == item.id)
if (!currentItem) {
throw new BadGatewayException("Order Item not found")
}
const { designerId, productId, ...itemRest } = item
let newProduct: Product | undefined
if (productId && productId !== currentItem.product.id) {
newProduct = await this.productService.findOneOrFail(productId)
}
let newDesigner: Admin | undefined
if (designerId && designerId !== currentItem.designer?.id) {
newDesigner = await this.adminService.findOrFail(designerId)
}
em.assign(currentItem, { ...itemRest, designer: newDesigner, product: newProduct })
} else {
if (!item.productId) {
throw new BadRequestException(`Product id is required for item ${item.id}`)
}
const product = await this.productService.findOneOrFail(item.productId)
const newOrderItem = em.create(OrderItem, {
order,
product,
quantity: item.quantity,
unitPrice: item.unitPrice,
adminDescription: item.adminDescription,
attachments: item.attachments,
attributes: item.attributes,
description: item.description,
discount: item.discount,
confirmedAt: item.confirmedAt,
})
em.persist(newOrderItem)
}
}
await em.flush()
this.logger.log("Order updated as admin")
return order
})
}
async addOrderItemAsUser(userId: string, orderId: string, dto: CreateOrderItemAsUserDto) {
@@ -354,7 +429,7 @@ export class OrderService {
unitPrice,
product,
printAttributes: printAttributes,
printAttachments
// printAttachments
})
}
@@ -476,9 +551,7 @@ export class OrderService {
if (attributes != undefined) {
orderItem.attributes = attributes
}
if (printAttachments != undefined) {
orderItem.printAttachments = printAttachments
}
if (description != undefined) {
orderItem.description = description
}
@@ -537,7 +610,7 @@ export class OrderService {
async findOrderOrFail(orderId: string) {
const order = await this.orderRepository.findOne({ id: orderId },
{ populate: ['items', 'items.product', 'payments', 'user'] })
{ populate: ['items', 'items.product', 'payments', 'user', 'items.designer'] })
if (!order) {
throw new BadRequestException('Order not found')
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { BaseEntity } from 'src/common/entities/base.entity';
@Entity({ tableName: 'print' })
export class Print extends BaseEntity {
@PrimaryKey({ type: 'bigint', autoincrement: true })
id: bigint
id: number
// @OneToMany(() => Field, (attrValue) => attrValue.entityId, { cascade: [Cascade.PERSIST, Cascade.REMOVE] })
// fields = new Collection<Field>(this)
@@ -143,7 +143,7 @@ export class ProductController {
@ApiOperation({ summary: 'Get a product by id' })
@ApiParam({ name: 'id', required: true })
findById(@Param('id') id: string,) {
return this.productService.findById(id);
return this.productService.findById(+id);
}
@Patch('admin/products/:id')
@@ -154,7 +154,7 @@ export class ProductController {
@ApiParam({ name: 'id', required: true })
@ApiBody({ type: UpdateproductDto })
update(@Param('id') id: string, @Body() updateproductDto: UpdateproductDto) {
return this.productService.update(id, updateproductDto);
return this.productService.update(+id, updateproductDto);
}
@Delete('admin/products/:id')
@@ -164,7 +164,7 @@ export class ProductController {
@ApiOperation({ summary: 'Delete (soft) a product' })
@ApiParam({ name: 'id', required: true })
remove(@Param('id') id: string,) {
return this.productService.remove(id);
return this.productService.remove(+id);
}
@@ -11,7 +11,7 @@ export class Product extends BaseEntity {
@PrimaryKey({ type: 'bigint', autoincrement: true })
id: bigint
id: number
@Property()
title: string;
@@ -44,7 +44,7 @@ export class ProductService {
}
async update(productId: string, createproductDto: Partial<CreateproductDto>) {
async update(productId: number, createproductDto: Partial<CreateproductDto>) {
const { categoryId, ...rest } = createproductDto;
const product = await this.productRepository.findOne({ id: productId })
if (!product) {
@@ -70,7 +70,7 @@ export class ProductService {
return this.productRepository.findAllPaginated(dto);
}
async findById(productId: string) {
async findById(productId: number) {
const product = await this.productRepository.findOne({ id: productId },
{ populate: ['category'] });
@@ -79,7 +79,7 @@ export class ProductService {
return product;
}
async remove(id: string): Promise<void> {
async remove(id: number): Promise<void> {
const product = await this.productRepository.findOne({ id });
if (!product) {
throw new NotFoundException(productMessage.NOT_FOUND);