zksu
/
API
forked from yoone/API
1
0
Fork 0

feat(订单): 增强订单相关功能及数据模型

- 在订单实体中添加orderItems和orderSales字段
- 优化QueryOrderSalesDTO,增加排序字段和更多描述信息
- 重构saveOrderSale方法,使用产品属性自动设置品牌和强度
- 在订单查询中返回关联的orderItems和orderSales数据
- 添加getAttributesObject方法处理产品属性
This commit is contained in:
tikkhun 2026-01-10 11:15:24 +08:00
parent c9f9310a29
commit 17435b1381
6 changed files with 2974 additions and 264 deletions

View File

@ -98,14 +98,10 @@ export class QueryOrderDTO {
} }
export class QueryOrderSalesDTO { export class QueryOrderSalesDTO {
@ApiProperty() @ApiProperty({ description: '是否为原产品还是库存产品' })
@Rule(RuleType.bool().default(false)) @Rule(RuleType.bool().default(false))
isSource: boolean; isSource: boolean;
@ApiProperty()
@Rule(RuleType.bool().default(false))
exceptPackage: boolean;
@ApiProperty({ example: '1', description: '页码' }) @ApiProperty({ example: '1', description: '页码' })
@Rule(RuleType.number()) @Rule(RuleType.number())
current: number; current: number;
@ -114,19 +110,31 @@ export class QueryOrderSalesDTO {
@Rule(RuleType.number()) @Rule(RuleType.number())
pageSize: number; pageSize: number;
@ApiProperty() @ApiProperty({ description: '排序对象,格式如 { productName: "asc", sku: "desc" }',type: 'any', required: false })
@Rule(RuleType.object().allow(null))
orderBy?: Record<string, 'asc' | 'desc'>;
// filter
@ApiProperty({ description: '是否排除套餐' })
@Rule(RuleType.bool().default(false))
exceptPackage: boolean;
@ApiProperty({ description: '站点ID' })
@Rule(RuleType.number()) @Rule(RuleType.number())
siteId: number; siteId: number;
@ApiProperty() @ApiProperty({ description: '名称' })
@Rule(RuleType.string()) @Rule(RuleType.string())
name: string; name: string;
@ApiProperty() @ApiProperty({ description: 'SKU' })
@Rule(RuleType.string())
sku: string;
@ApiProperty({ description: '开始日期' })
@Rule(RuleType.date()) @Rule(RuleType.date())
startDate: Date; startDate: Date;
@ApiProperty() @ApiProperty({ description: '结束日期' })
@Rule(RuleType.date()) @Rule(RuleType.date())
endDate: Date; endDate: Date;
} }

View File

@ -272,6 +272,14 @@ export class Order {
@Expose() @Expose()
updatedAt: Date; updatedAt: Date;
@ApiProperty({ type: 'json', nullable: true, description: '订单项列表' })
@Expose()
orderItems?: any[];
@ApiProperty({ type: 'json', nullable: true, description: '销售项列表' })
@Expose()
orderSales?: any[];
// 在插入或更新前处理用户代理字符串 // 在插入或更新前处理用户代理字符串
@BeforeInsert() @BeforeInsert()
@BeforeUpdate() @BeforeUpdate()

View File

@ -75,7 +75,7 @@ export class OrderSale {
@ApiProperty({ nullable: true }) @ApiProperty({ nullable: true })
@Column({ type: 'int', nullable: true }) @Column({ type: 'int', nullable: true })
@Expose() @Expose()
size: number | null; size: number | null; // 其实是 strength
@ApiProperty() @ApiProperty()
@Column({ default: false }) @Column({ default: false })
@ -98,24 +98,24 @@ export class OrderSale {
@Expose() @Expose()
updatedAt?: Date; updatedAt?: Date;
// === 自动计算逻辑 === // // === 自动计算逻辑 ===
@BeforeInsert() // @BeforeInsert()
@BeforeUpdate() // @BeforeUpdate()
setFlags() { // setFlags() {
if (!this.name) return; // if (!this.name) return;
const lower = this.name.toLowerCase(); // const lower = this.name.toLowerCase();
this.isYoone = lower.includes('yoone'); // this.isYoone = lower.includes('yoone');
this.isZex = lower.includes('zex'); // this.isZex = lower.includes('zex');
this.isYooneNew = this.isYoone && lower.includes('new'); // this.isYooneNew = this.isYoone && lower.includes('new');
let size: number | null = null; // let size: number | null = null;
const sizes = [3, 6, 9, 12, 15, 18]; // const sizes = [3, 6, 9, 12, 15, 18];
for (const s of sizes) { // for (const s of sizes) {
if (lower.includes(s.toString())) { // if (lower.includes(s.toString())) {
size = s; // size = s;
break; // break;
} // }
} // }
this.size = size; // this.size = size;
} // }
} }

File diff suppressed because it is too large Load Diff

View File

@ -39,6 +39,8 @@ import * as path from 'path';
import * as os from 'os'; import * as os from 'os';
import { UnifiedOrderDTO } from '../dto/site-api.dto'; import { UnifiedOrderDTO } from '../dto/site-api.dto';
import { CustomerService } from './customer.service'; import { CustomerService } from './customer.service';
import { DictItem } from '../entity/dict_item.entity';
import { ProductService } from './product.service';
@Provide() @Provide()
export class OrderService { export class OrderService {
@ -110,6 +112,8 @@ export class OrderService {
@Logger() @Logger()
logger; // 注入 Logger 实例 logger; // 注入 Logger 实例
@Inject()
productService: ProductService;
/** /**
* *
@ -146,8 +150,8 @@ export class OrderService {
const existingOrder = await this.orderModel.findOne({ const existingOrder = await this.orderModel.findOne({
where: { externalOrderId: String(order.id), siteId: siteId }, where: { externalOrderId: String(order.id), siteId: siteId },
}); });
if(!existingOrder){ if (!existingOrder) {
console.log("数据库中不存在",order.id, '订单状态:', order.status ) console.log("数据库中不存在", order.id, '订单状态:', order.status)
} }
// 同步单个订单 // 同步单个订单
await this.syncSingleOrder(siteId, order); await this.syncSingleOrder(siteId, order);
@ -208,8 +212,8 @@ export class OrderService {
const existingOrder = await this.orderModel.findOne({ const existingOrder = await this.orderModel.findOne({
where: { externalOrderId: String(order.id), siteId: siteId }, where: { externalOrderId: String(order.id), siteId: siteId },
}); });
if(!existingOrder){ if (!existingOrder) {
console.log("数据库不存在", siteId , "订单:",order.id, '订单状态:' + order.status ) console.log("数据库不存在", siteId, "订单:", order.id, '订单状态:' + order.status)
} }
// 同步单个订单 // 同步单个订单
await this.syncSingleOrder(siteId, order, true); await this.syncSingleOrder(siteId, order, true);
@ -268,7 +272,7 @@ export class OrderService {
try { try {
const site = await this.siteService.get(siteId); const site = await this.siteService.get(siteId);
// 仅处理 WooCommerce 站点 // 仅处理 WooCommerce 站点
if(site.type !== 'woocommerce'){ if (site.type !== 'woocommerce') {
return return
} }
// 将订单状态同步到 WooCommerce,然后切换至下一状态 // 将订单状态同步到 WooCommerce,然后切换至下一状态
@ -278,6 +282,11 @@ export class OrderService {
console.error('更新订单状态失败,原因为:', error) console.error('更新订单状态失败,原因为:', error)
} }
} }
async getOrderByExternalOrderId(siteId: number, externalOrderId: string) {
return await this.orderModel.findOne({
where: { externalOrderId: String(externalOrderId), siteId },
});
}
/** /**
* *
* : * :
@ -301,7 +310,7 @@ export class OrderService {
* @param order * @param order
* @param forceUpdate * @param forceUpdate
*/ */
async syncSingleOrder(siteId: number, order: any, forceUpdate = false) { async syncSingleOrder(siteId: number, order: UnifiedOrderDTO, forceUpdate = false) {
// 从订单数据中解构出各个子项 // 从订单数据中解构出各个子项
let { let {
line_items, line_items,
@ -315,47 +324,27 @@ export class OrderService {
// console.log('同步进单个订单', order) // console.log('同步进单个订单', order)
// 如果订单状态为 AUTO_DRAFT,则跳过处理 // 如果订单状态为 AUTO_DRAFT,则跳过处理
if (order.status === OrderStatus.AUTO_DRAFT) { if (order.status === OrderStatus.AUTO_DRAFT) {
this.logger.debug('订单状态为 AUTO_DRAFT,跳过处理', siteId, order.id)
return; return;
} }
// 检查数据库中是否已存在该订单 // if(!order.is_editable && !forceUpdate){
const existingOrder = await this.orderModel.findOne({ // this.logger.debug('订单不可编辑,跳过处理', siteId, order.id)
where: { externalOrderId: order.id, siteId: siteId }, // return;
}); // }
// 自动更新订单状态(如果需要) // 自动转换远程订单的状态(如果需要)
await this.autoUpdateOrderStatus(siteId, order); await this.autoUpdateOrderStatus(siteId, order);
// 这里的 saveOrder 已经包括了创建订单和更新订单
if(existingOrder){ let orderRecord: Order = await this.saveOrder(siteId, orderData);
// 矫正数据库中的订单数据
const updateData: any = { status: order.status };
if (this.canUpdateErpStatus(existingOrder.orderStatus)) {
updateData.orderStatus = this.mapOrderStatus(order.status);
}
// 更新
await this.orderModel.update({ externalOrderId: order.id, siteId: siteId }, updateData);
// 更新 fulfillments 数据
await this.saveOrderFulfillments({
siteId,
orderId: existingOrder.id,
externalOrderId:order.id,
fulfillments: fulfillments,
});
}
const externalOrderId = order.id;
// 如果订单从未完成变为完成状态,则更新库存 // 如果订单从未完成变为完成状态,则更新库存
if ( if (
existingOrder && orderRecord &&
existingOrder.orderStatus !== ErpOrderStatus.COMPLETED && orderRecord.orderStatus !== ErpOrderStatus.COMPLETED &&
orderData.status === OrderStatus.COMPLETED orderData.status === OrderStatus.COMPLETED
) { ) {
this.updateStock(existingOrder); await this.updateStock(orderRecord);
// 不再直接返回,继续执行后续的更新操作 // 不再直接返回,继续执行后续的更新操作
} }
// 如果订单不可编辑且不强制更新,则跳过处理 const externalOrderId = String(order.id);
if (existingOrder && !existingOrder.is_editable && !forceUpdate) {
return;
}
// 保存订单主数据
const orderRecord = await this.saveOrder(siteId, orderData);
const orderId = orderRecord.id; const orderId = orderRecord.id;
// 保存订单项 // 保存订单项
await this.saveOrderItems({ await this.saveOrderItems({
@ -459,13 +448,14 @@ export class OrderService {
* @param order * @param order
* @returns * @returns
*/ */
async saveOrder(siteId: number, order: UnifiedOrderDTO): Promise<Order> { // 这里 omit 是因为处理在外头了 其实 saveOrder 应该包括 savelineitems 等
async saveOrder(siteId: number, order: Omit<UnifiedOrderDTO, 'line_items'|'refunds'>): Promise<Order> {
// 将外部订单ID转换为字符串 // 将外部订单ID转换为字符串
const externalOrderId = String(order.id) const externalOrderId = String(order.id)
delete order.id delete order.id
// 创建订单实体对象 // 创建订单实体对象
const entity = plainToClass(Order, {...order, externalOrderId, siteId}); const entity = plainToClass(Order, { ...order, externalOrderId, siteId });
// 检查数据库中是否已存在该订单 // 检查数据库中是否已存在该订单
const existingOrder = await this.orderModel.findOne({ const existingOrder = await this.orderModel.findOne({
where: { externalOrderId, siteId: siteId }, where: { externalOrderId, siteId: siteId },
@ -708,6 +698,8 @@ export class OrderService {
* *
* @param orderItem * @param orderItem
*/ */
// TODO 这里存的是库存商品实际
// 所以叫做 orderInventoryItems 可能更合适
async saveOrderSale(orderItem: OrderItem) { async saveOrderSale(orderItem: OrderItem) {
const currentOrderSale = await this.orderSaleModel.find({ const currentOrderSale = await this.orderSaleModel.find({
where: { where: {
@ -726,46 +718,44 @@ export class OrderService {
}); });
if (!product) return; if (!product) return;
const componentDetails: { product: Product, quantity: number }[] = product.components?.length > 0 ? await Promise.all(product.components.map(async comp => {
const orderSales: OrderSale[] = []; return {
product: await this.productModel.findOne({
if (product.components && product.components.length > 0) {
for (const comp of product.components) {
const baseProduct = await this.productModel.findOne({
where: { sku: comp.sku }, where: { sku: comp.sku },
}); }),
if (baseProduct) {
const orderSaleItem: OrderSale = plainToClass(OrderSale, {
orderId: orderItem.orderId,
siteId: orderItem.siteId,
externalOrderItemId: orderItem.externalOrderItemId,
productId: baseProduct.id,
name: baseProduct.name,
quantity: comp.quantity * orderItem.quantity, quantity: comp.quantity * orderItem.quantity,
sku: comp.sku,
isPackage: orderItem.name.toLowerCase().includes('package'),
});
orderSales.push(orderSaleItem);
} }
} })) : [{ product, quantity: orderItem.quantity }];
} else {
const orderSaleItem: OrderSale = plainToClass(OrderSale, { const orderSales: OrderSale[] = componentDetails.map(componentDetail => {
const attrsObj = this.productService.getAttributesObject(product.attributes)
const orderSale = plainToClass(OrderSale, {
orderId: orderItem.orderId, orderId: orderItem.orderId,
siteId: orderItem.siteId, siteId: orderItem.siteId,
externalOrderItemId: orderItem.externalOrderItemId, externalOrderItemId: orderItem.externalOrderItemId,
productId: product.id, productId: componentDetail.product.id,
name: product.name, name: componentDetail.product.name,
quantity: orderItem.quantity, quantity: componentDetail.quantity * orderItem.quantity,
sku: product.sku, sku: componentDetail.product.sku,
isPackage: orderItem.name.toLowerCase().includes('package'), isPackage: componentDetail.product.type === 'bundle',
isYoone: attrsObj?.['brand']?.name === 'yoone',
isZyn: attrsObj?.['brand']?.name === 'zyn',
isYooneNew: attrsObj?.['brand']?.name === 'yoone' && attrsObj?.['version']?.name === 'new',
size: this.extractNumberFromString(attrsObj?.['strength']?.name) || null,
}); });
orderSales.push(orderSaleItem); return orderSale
} })
if (orderSales.length > 0) { if (orderSales.length > 0) {
await this.orderSaleModel.save(orderSales); await this.orderSaleModel.save(orderSales);
} }
} }
extractNumberFromString(str: string): number {
if (!str) return 0;
const num = parseInt(str, 10);
return isNaN(num) ? 0 : num;
}
/** /**
* 退 * 退
@ -1192,7 +1182,53 @@ export class OrderService {
) END ) END
), ),
JSON_ARRAY() JSON_ARRAY()
) as fulfillments ) as fulfillments,
(
SELECT COALESCE(
JSON_ARRAYAGG(
JSON_OBJECT(
'id', oi.id,
'name', oi.name,
'orderId', oi.orderId,
'siteId', oi.siteId,
'externalOrderId', oi.externalOrderId,
'externalOrderItemId', oi.externalOrderItemId,
'externalProductId', oi.externalProductId,
'externalVariationId', oi.externalVariationId,
'quantity', oi.quantity,
'subtotal', oi.subtotal,
'subtotal_tax', oi.subtotal_tax,
'total', oi.total,
'total_tax', oi.total_tax,
'sku', oi.sku,
'price', oi.price
)
),
JSON_ARRAY()
)
FROM order_item oi
WHERE oi.orderId = o.id
) AS orderItems,
(
SELECT COALESCE(
JSON_ARRAYAGG(
JSON_OBJECT(
'id', os.id,
'orderId', os.orderId,
'siteId', os.siteId,
'externalOrderItemId', os.externalOrderItemId,
'productId', os.productId,
'name', os.name,
'sku', os.sku,
'quantity', os.quantity,
'isPackage', os.isPackage
)
),
JSON_ARRAY()
)
FROM order_sale os
WHERE os.orderId = o.id
) AS orderSales
FROM \`order\` o FROM \`order\` o
LEFT JOIN ( LEFT JOIN (
SELECT SELECT
@ -1426,7 +1462,7 @@ export class OrderService {
* @param params * @param params
* @returns * @returns
*/ */
async getOrderSales({ siteId, startDate, endDate, current, pageSize, name, exceptPackage }: QueryOrderSalesDTO) { async getOrderSales({ siteId, startDate, endDate, current, pageSize, name, exceptPackage, orderBy }: QueryOrderSalesDTO) {
const nameKeywords = name ? name.split(' ').filter(Boolean) : []; const nameKeywords = name ? name.split(' ').filter(Boolean) : [];
const defaultStart = dayjs().subtract(30, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss'); const defaultStart = dayjs().subtract(30, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss');
const defaultEnd = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'); const defaultEnd = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');
@ -1642,11 +1678,12 @@ export class OrderService {
* @returns * @returns
*/ */
async getOrderItems({ async getOrderItems({
current,
pageSize,
siteId, siteId,
startDate, startDate,
endDate, endDate,
current, sku,
pageSize,
name, name,
}: QueryOrderSalesDTO) { }: QueryOrderSalesDTO) {
const nameKeywords = name ? name.split(' ').filter(Boolean) : []; const nameKeywords = name ? name.split(' ').filter(Boolean) : [];
@ -2471,7 +2508,7 @@ export class OrderService {
return await dataSource.transaction(async manager => { return await dataSource.transaction(async manager => {
// 准备查询条件 // 准备查询条件
const whereCondition: any = {}; const whereCondition: any = {};
if(validIds.length > 0){ if (validIds.length > 0) {
whereCondition.id = In(validIds); whereCondition.id = In(validIds);
} }
@ -2572,7 +2609,7 @@ export class OrderService {
* @param {boolean} [options.writeFile=false] * @param {boolean} [options.writeFile=false]
* @returns {string|Buffer} type返回字符串或Buffer * @returns {string|Buffer} type返回字符串或Buffer
*/ */
async exportToCsv(data: any[], options: { type?: 'string' | 'buffer'; fileName?: string; writeFile?: boolean } = {}): Promise<string | Buffer> { async exportToCsv(data: any[], options: { type?: 'string' | 'buffer'; fileName?: string; writeFile?: boolean } = {}): Promise<string | Buffer> {
try { try {
// 检查数据是否为空 // 检查数据是否为空
if (!data || data.length === 0) { if (!data || data.length === 0) {
@ -2644,7 +2681,7 @@ async exportToCsv(data: any[], options: { type?: 'string' | 'buffer'; fileName?:
console.error('导出CSV时出错:', error); console.error('导出CSV时出错:', error);
throw new Error(`导出CSV文件失败: ${error.message}`); throw new Error(`导出CSV文件失败: ${error.message}`);
} }
} }

View File

@ -1536,7 +1536,13 @@ export class ProductService {
return dto; return dto;
} }
getAttributesObject(attributes:DictItem[]){
const obj:any = {}
attributes.forEach(attr=>{
obj[attr.dict.name] = attr
})
return obj
}
// 将单个产品转换为 CSV 行数组 // 将单个产品转换为 CSV 行数组
transformProductToCsvRow( transformProductToCsvRow(
p: Product, p: Product,