Merge remote-tracking branch 'origin/main' into main

This commit is contained in:
zhuotianyuan 2026-01-13 14:58:13 +08:00
commit 6be91f14a4
11 changed files with 3011 additions and 334 deletions

View File

@ -227,8 +227,10 @@ export class ShopyyAdapter implements ISiteAdapter {
// ========== 订单映射方法 ========== // ========== 订单映射方法 ==========
mapPlatformToUnifiedOrder(item: ShopyyOrder): UnifiedOrderDTO { mapPlatformToUnifiedOrder(item: ShopyyOrder): UnifiedOrderDTO {
// console.log(item)
if(!item) throw new Error('订单数据不能为空')
// 提取账单和送货地址 如果不存在则为空对象 // 提取账单和送货地址 如果不存在则为空对象
const billing = (item as any).billing_address || {}; const billing = (item).bill_address || {};
const shipping = (item as any).shipping_address || {}; const shipping = (item as any).shipping_address || {};
// 构建账单地址对象 // 构建账单地址对象
@ -313,7 +315,7 @@ export class ShopyyAdapter implements ISiteAdapter {
product_id: p.product_id, product_id: p.product_id,
quantity: p.quantity, quantity: p.quantity,
total: String(p.price ?? ''), total: String(p.price ?? ''),
sku: p.sku || p.sku_code || '', sku: p.sku_code || '',
price: String(p.price ?? ''), price: String(p.price ?? ''),
}) })
); );
@ -440,7 +442,7 @@ export class ShopyyAdapter implements ISiteAdapter {
} }
// 更新账单地址 // 更新账单地址
params.billing_address = params.billing_address || {}; params.billing_address = params?.billing_address || {};
if (data.billing.first_name !== undefined) { if (data.billing.first_name !== undefined) {
params.billing_address.first_name = data.billing.first_name; params.billing_address.first_name = data.billing.first_name;
} }

View File

@ -98,13 +98,9 @@ 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())
@ -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

@ -200,7 +200,7 @@ export interface ShopyyOrder {
customer_email?: string; customer_email?: string;
email?: string; email?: string;
// 地址字段 // 地址字段
billing_address?: { bill_address?: {
first_name?: string; first_name?: string;
last_name?: string; last_name?: string;
name?: string; name?: string;

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

@ -1,8 +1,8 @@
import { ApiProperty } from '@midwayjs/swagger'; import { ApiProperty } from '@midwayjs/swagger';
import { Exclude, Expose } from 'class-transformer'; import { Exclude, Expose } from 'class-transformer';
import { import {
BeforeInsert, // BeforeInsert,
BeforeUpdate, // BeforeUpdate,
Column, Column,
CreateDateColumn, CreateDateColumn,
Entity, Entity,
@ -22,22 +22,22 @@ export class OrderSale {
@Expose() @Expose()
id?: number; id?: number;
@ApiProperty() @ApiProperty({ name:'原始订单ID' })
@Column() @Column()
@Expose() @Expose()
orderId: number; // 订单 ID orderId: number; // 订单 ID
@ApiProperty() @ApiProperty({ name:'站点' })
@Column({ nullable: true }) @Column()
@Expose() @Expose()
siteId: number; // 来源站点唯一标识 siteId: number; // 来源站点唯一标识
@ApiProperty() @ApiProperty({name: "原始订单 itemId"})
@Column({ nullable: true }) @Column({ nullable: true })
@Expose() @Expose()
externalOrderItemId: string; // WooCommerce 订单item ID externalOrderItemId: string; // WooCommerce 订单item ID
@ApiProperty() @ApiProperty({name: "产品 ID"})
@Column() @Column()
@Expose() @Expose()
productId: number; productId: number;
@ -62,25 +62,35 @@ export class OrderSale {
@Expose() @Expose()
isPackage: boolean; isPackage: boolean;
@ApiProperty() @ApiProperty({ description: '品牌', type: 'string',nullable: true})
@Column({ default: false })
@Expose() @Expose()
isYoone: boolean; @Column({ nullable: true })
brand?: string;
@ApiProperty() @ApiProperty({ description: '口味', type: 'string', nullable: true })
@Column({ default: false })
@Expose() @Expose()
isZex: boolean; @Column({ nullable: true })
flavor?: string;
@ApiProperty({ nullable: true }) @ApiProperty({ description: '湿度', type: 'string', nullable: true })
@Column({ type: 'int', nullable: true })
@Expose() @Expose()
size: number | null; @Column({ nullable: true })
humidity?: string;
@ApiProperty() @ApiProperty({ description: '尺寸', type: 'string', nullable: true })
@Column({ default: false })
@Expose() @Expose()
isYooneNew: boolean; @Column({ nullable: true })
size?: string;
@ApiProperty({name: '强度', nullable: true })
@Column({ nullable: true })
@Expose()
strength: string | null;
@ApiProperty({ description: '版本', type: 'string', nullable: true })
@Expose()
@Column({ nullable: true })
version?: string;
@ApiProperty({ @ApiProperty({
example: '2022-12-12 11:11:11', example: '2022-12-12 11:11:11',
@ -97,25 +107,4 @@ export class OrderSale {
@UpdateDateColumn() @UpdateDateColumn()
@Expose() @Expose()
updatedAt?: Date; updatedAt?: Date;
// === 自动计算逻辑 ===
@BeforeInsert()
@BeforeUpdate()
setFlags() {
if (!this.name) return;
const lower = this.name.toLowerCase();
this.isYoone = lower.includes('yoone');
this.isZex = lower.includes('zex');
this.isYooneNew = this.isYoone && lower.includes('new');
let size: number | null = null;
const sizes = [3, 6, 9, 12, 15, 18];
for (const s of sizes) {
if (lower.includes(s.toString())) {
size = s;
break;
}
}
this.size = size;
}
} }

View File

@ -75,17 +75,20 @@ export class SyncUniuniShipmentJob implements IJob{
'255': 'Gateway_To_Gateway_Transit' '255': 'Gateway_To_Gateway_Transit'
}; };
async onTick() { async onTick() {
try {
const shipments:Shipment[] = await this.shipmentModel.findBy({ finished: false }); const shipments:Shipment[] = await this.shipmentModel.findBy({ finished: false });
shipments.forEach(shipment => { const results = await Promise.all(
this.logisticsService.updateShipmentState(shipment); shipments.map(async shipment => {
}); return await this.logisticsService.updateShipmentState(shipment);
} catch (error) { })
this.logger.error(`更新运单状态失败 ${error.message}`); )
} this.logger.info(`更新运单状态完毕 ${JSON.stringify(results)}`);
return results
} }
onComplete(result: any) { onComplete(result: any) {
this.logger.info(`更新运单状态完成 ${result}`);
}
onError(error: any) {
this.logger.error(`更新运单状态失败 ${error.message}`);
} }
} }

View File

@ -125,6 +125,10 @@ export class LogisticsService {
try { try {
const data = await this.uniExpressService.getOrderStatus(shipment.return_tracking_number); const data = await this.uniExpressService.getOrderStatus(shipment.return_tracking_number);
console.log('updateShipmentState data:', data); console.log('updateShipmentState data:', data);
// huo
if(data.status === 'FAIL'){
throw new Error('获取运单状态失败,原因为'+ data.ret_msg)
}
shipment.state = data.data[0].state; shipment.state = data.data[0].state;
if (shipment.state in [203, 215, 216, 230]) { // todo,写常数 if (shipment.state in [203, 215, 216, 230]) { // todo,写常数
shipment.finished = true; shipment.finished = true;

File diff suppressed because it is too large Load Diff

View File

@ -39,6 +39,7 @@ 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 { ProductService } from './product.service';
@Provide() @Provide()
export class OrderService { export class OrderService {
@ -110,7 +111,9 @@ export class OrderService {
@Logger() @Logger()
logger; // 注入 Logger 实例 logger; // 注入 Logger 实例
@Inject()
productService: ProductService;
/** /**
* *
* : * :
@ -146,8 +149,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);
@ -211,8 +214,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);
@ -271,7 +274,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,然后切换至下一状态
@ -281,6 +284,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 },
});
}
/** /**
* *
* : * :
@ -318,47 +326,28 @@ 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;
} }
// 检查数据库中是否已存在该订单 // 这里其实不用过滤不可编辑的行为,而是应在 save 中做判断
const existingOrder = await this.orderModel.findOne({ // if(!order.is_editable && !forceUpdate){
where: { externalOrderId: String(order.id), siteId: siteId }, // this.logger.debug('订单不可编辑,跳过处理', siteId, order.id)
}); // 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 as any);
}
// 更新订单主数据
await this.orderModel.update({ externalOrderId: String(order.id), siteId: siteId }, updateData);
// 更新 fulfillments 数据
await this.saveOrderFulfillments({
siteId,
orderId: existingOrder.id,
externalOrderId:order.id,
fulfillments: fulfillments,
});
}
const externalOrderId = String(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({
@ -462,13 +451,14 @@ export class OrderService {
* @param order * @param order
* @returns * @returns
*/ */
async saveOrder(siteId: number, order: Partial<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 },
@ -711,6 +701,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: {
@ -725,50 +717,53 @@ export class OrderService {
// 从数据库查询产品,关联查询组件 // 从数据库查询产品,关联查询组件
const product = await this.productModel.findOne({ const product = await this.productModel.findOne({
where: { siteSkus: Like(`%${orderItem.sku}%`) }, where: { siteSkus: Like(`%${orderItem.sku}%`) },
relations: ['components'], relations: ['components','attributes','attributes.dict'],
}); });
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 },
}); relations: ['components', 'attributes','attributes.dict'],
if (baseProduct) { }),
const orderSaleItem: OrderSale = plainToClass(OrderSale, { quantity: comp.quantity * orderItem.quantity,
orderId: orderItem.orderId,
siteId: orderItem.siteId,
externalOrderItemId: orderItem.externalOrderItemId,
productId: baseProduct.id,
name: baseProduct.name,
quantity: comp.quantity * orderItem.quantity,
sku: comp.sku,
isPackage: orderItem.name.toLowerCase().includes('package'),
});
orderSales.push(orderSaleItem);
}
} }
} else { })) : [{ product, quantity: orderItem.quantity }]
const orderSaleItem: OrderSale = plainToClass(OrderSale, {
const orderSales: OrderSale[] = componentDetails.map(componentDetail => {
if (!componentDetail.product) return null
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'), // 理论上直接存 product 的全部数据才是对的,因为这样我的数据才全面。
isPackage: componentDetail.product.type === 'bundle',
isYoone: attrsObj?.['brand']?.name === 'yoone',
isZyn: attrsObj?.['brand']?.name === 'zyn',
isZex: attrsObj?.['brand']?.name === 'zex',
isYooneNew: attrsObj?.['brand']?.name === 'yoone' && attrsObj?.['version']?.name === 'new',
strength: attrsObj?.['strength']?.name,
}); });
orderSales.push(orderSaleItem); return orderSale
} }).filter(v => v !== null)
console.log("orderSales",orderSales)
if (orderSales.length > 0) { if (orderSales.length > 0) {
await this.orderSaleModel.save(orderSales); await this.orderSaleModel.save(orderSales);
} }
} }
// // extract stren
// extractNumberFromString(str: string): number {
// if (!str) return 0;
// const num = parseInt(str, 10);
// return isNaN(num) ? 0 : num;
// }
/** /**
* 退 * 退
@ -1429,7 +1424,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');
@ -1582,14 +1577,14 @@ export class OrderService {
`; `;
let yooneSql = ` let yooneSql = `
SELECT SELECT
SUM(CASE WHEN os.isYoone = 1 AND os.size = 3 THEN os.quantity ELSE 0 END) AS yoone3Quantity, SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '3mg' THEN os.quantity ELSE 0 END) AS yoone3Quantity,
SUM(CASE WHEN os.isYoone = 1 AND os.size = 6 THEN os.quantity ELSE 0 END) AS yoone6Quantity, SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '6mg' THEN os.quantity ELSE 0 END) AS yoone6Quantity,
SUM(CASE WHEN os.isYoone = 1 AND os.size = 9 THEN os.quantity ELSE 0 END) AS yoone9Quantity, SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '9mg' THEN os.quantity ELSE 0 END) AS yoone9Quantity,
SUM(CASE WHEN os.isYoone = 1 AND os.size = 12 THEN os.quantity ELSE 0 END) AS yoone12Quantity, SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '12mg' THEN os.quantity ELSE 0 END) AS yoone12Quantity,
SUM(CASE WHEN os.isYooneNew = 1 AND os.size = 12 THEN os.quantity ELSE 0 END) AS yoone12QuantityNew, SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '12mg' THEN os.quantity ELSE 0 END) AS yoone12QuantityNew,
SUM(CASE WHEN os.isYoone = 1 AND os.size = 15 THEN os.quantity ELSE 0 END) AS yoone15Quantity, SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '15mg' THEN os.quantity ELSE 0 END) AS yoone15Quantity,
SUM(CASE WHEN os.isYoone = 1 AND os.size = 18 THEN os.quantity ELSE 0 END) AS yoone18Quantity, SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '18mg' THEN os.quantity ELSE 0 END) AS yoone18Quantity,
SUM(CASE WHEN os.isZex = 1 THEN os.quantity ELSE 0 END) AS zexQuantity SUM(CASE WHEN os.brand = 'zex' THEN os.quantity ELSE 0 END) AS zexQuantity
FROM order_sale os FROM order_sale os
INNER JOIN \`order\` o ON o.id = os.orderId INNER JOIN \`order\` o ON o.id = os.orderId
WHERE o.date_paid BETWEEN ? AND ? WHERE o.date_paid BETWEEN ? AND ?
@ -1645,11 +1640,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) : [];
@ -1907,8 +1903,8 @@ export class OrderService {
const key = it?.externalSubscriptionId const key = it?.externalSubscriptionId
? `sub:${it.externalSubscriptionId}` ? `sub:${it.externalSubscriptionId}`
: it?.externalOrderId : it?.externalOrderId
? `ord:${it.externalOrderId}` ? `ord:${it.externalOrderId}`
: `id:${it?.id}`; : `id:${it?.id}`;
if (!seen.has(key)) { if (!seen.has(key)) {
seen.add(key); seen.add(key);
relatedList.push(it); relatedList.push(it);
@ -2202,14 +2198,14 @@ export class OrderService {
for (const sale of sales) { for (const sale of sales) {
const product = await productRepo.findOne({ where: { sku: sale.sku } }); const product = await productRepo.findOne({ where: { sku: sale.sku } });
const saleItem = { const saleItem = {
orderId: order.id, orderId: order.id,
siteId: order.siteId, siteId: order.siteId,
externalOrderItemId: '-1', externalOrderItemId: '-1',
productId: product.id, productId: product.id,
name: product.name, name: product.name,
sku: sale.sku, sku: sale.sku,
quantity: sale.quantity, quantity: sale.quantity,
}; };
await orderSaleRepo.save(saleItem); await orderSaleRepo.save(saleItem);
} }
}); });
@ -2342,83 +2338,83 @@ export class OrderService {
//换货功能更新OrderSale和Orderitem数据 //换货功能更新OrderSale和Orderitem数据
async updateExchangeOrder(orderId: number, data: any) { async updateExchangeOrder(orderId: number, data: any) {
throw new Error('暂未实现') throw new Error('暂未实现')
// try { // try {
// const dataSource = this.dataSourceManager.getDataSource('default'); // const dataSource = this.dataSourceManager.getDataSource('default');
// let transactionError = undefined; // let transactionError = undefined;
// await dataSource.transaction(async manager => { // await dataSource.transaction(async manager => {
// const orderRepo = manager.getRepository(Order); // const orderRepo = manager.getRepository(Order);
// const orderSaleRepo = manager.getRepository(OrderSale); // const orderSaleRepo = manager.getRepository(OrderSale);
// const orderItemRepo = manager.getRepository(OrderItem); // const orderItemRepo = manager.getRepository(OrderItem);
// const productRepo = manager.getRepository(ProductV2); // const productRepo = manager.getRepository(ProductV2);
// const order = await orderRepo.findOneBy({ id: orderId }); // const order = await orderRepo.findOneBy({ id: orderId });
// let product: ProductV2; // let product: ProductV2;
// await orderSaleRepo.delete({ orderId }); // await orderSaleRepo.delete({ orderId });
// await orderItemRepo.delete({ orderId }); // await orderItemRepo.delete({ orderId });
// for (const sale of data['sales']) { // for (const sale of data['sales']) {
// product = await productRepo.findOneBy({ sku: sale['sku'] }); // product = await productRepo.findOneBy({ sku: sale['sku'] });
// await orderSaleRepo.save({ // await orderSaleRepo.save({
// orderId, // orderId,
// siteId: order.siteId, // siteId: order.siteId,
// productId: product.id, // productId: product.id,
// name: product.name, // name: product.name,
// sku: sale['sku'], // sku: sale['sku'],
// quantity: sale['quantity'], // quantity: sale['quantity'],
// }); // });
// }; // };
// for (const item of data['items']) { // for (const item of data['items']) {
// product = await productRepo.findOneBy({ sku: item['sku'] }); // product = await productRepo.findOneBy({ sku: item['sku'] });
// await orderItemRepo.save({ // await orderItemRepo.save({
// orderId, // orderId,
// siteId: order.siteId, // siteId: order.siteId,
// productId: product.id, // productId: product.id,
// name: product.name, // name: product.name,
// externalOrderId: order.externalOrderId, // externalOrderId: order.externalOrderId,
// externalProductId: product.externalProductId, // externalProductId: product.externalProductId,
// sku: item['sku'], // sku: item['sku'],
// quantity: item['quantity'], // quantity: item['quantity'],
// }); // });
// }; // };
// //将是否换货状态改为true // //将是否换货状态改为true
// await orderRepo.update( // await orderRepo.update(
// order.id // order.id
// , { // , {
// is_exchange: true // is_exchange: true
// }); // });
// //查询这个用户换过多少次货 // //查询这个用户换过多少次货
// const counts = await orderRepo.countBy({ // const counts = await orderRepo.countBy({
// is_editable: true, // is_editable: true,
// customer_email: order.customer_email, // customer_email: order.customer_email,
// }); // });
// //批量更新当前用户换货次数 // //批量更新当前用户换货次数
// await orderRepo.update({ // await orderRepo.update({
// customer_email: order.customer_email // customer_email: order.customer_email
// }, { // }, {
// exchange_frequency: counts // exchange_frequency: counts
// }); // });
// }).catch(error => { // }).catch(error => {
// transactionError = error; // transactionError = error;
// }); // });
// if (transactionError !== undefined) { // if (transactionError !== undefined) {
// throw new Error(`更新物流信息错误:${transactionError.message}`); // throw new Error(`更新物流信息错误:${transactionError.message}`);
// } // }
// return true; // return true;
// } catch (error) { // } catch (error) {
// throw new Error(`更新发货产品失败:${error.message}`); // throw new Error(`更新发货产品失败:${error.message}`);
// } // }
} }
/** /**
@ -2464,17 +2460,17 @@ export class OrderService {
} }
try { try {
// 过滤掉NaN和非数字值只保留有效的数字ID // 过滤掉NaN和非数字值只保留有效的数字ID
const validIds = ids?.filter?.(id => Number.isFinite(id) && id > 0); const validIds = ids?.filter?.(id => Number.isFinite(id) && id > 0);
const dataSource = this.dataSourceManager.getDataSource('default'); const dataSource = this.dataSourceManager.getDataSource('default');
// 优化事务使用 // 优化事务使用
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);
} }
@ -2490,7 +2486,7 @@ export class OrderService {
// 获取所有订单ID // 获取所有订单ID
const orderIds = orders.map(order => order.id); const orderIds = orders.map(order => order.id);
// 获取所有订单项 // 获取所有订单项
const orderItems = await manager.getRepository(OrderItem).find({ const orderItems = await manager.getRepository(OrderItem).find({
where: { where: {
@ -2511,13 +2507,13 @@ export class OrderService {
const exportDataList: ExportData[] = orders.map(order => { const exportDataList: ExportData[] = orders.map(order => {
// 获取订单的订单项 // 获取订单的订单项
const items = orderItemsByOrderId[order.id] || []; const items = orderItemsByOrderId[order.id] || [];
// 计算总盒数 // 计算总盒数
const boxCount = items.reduce((total, item) => total + item.quantity, 0); const boxCount = items.reduce((total, item) => total + item.quantity, 0);
// 构建订单内容 // 构建订单内容
const orderContent = items.map(item => `${item.name} (${item.sku || ''}) x ${item.quantity}`).join('; '); const orderContent = items.map(item => `${item.name} (${item.sku || ''}) x ${item.quantity}`).join('; ');
// 构建姓名地址 // 构建姓名地址
const shipping = order.shipping; const shipping = order.shipping;
const billing = order.billing; const billing = order.billing;
@ -2531,10 +2527,10 @@ export class OrderService {
const postcode = shipping?.postcode || billing?.postcode || ''; const postcode = shipping?.postcode || billing?.postcode || '';
const country = shipping?.country || billing?.country || ''; const country = shipping?.country || billing?.country || '';
const nameAddress = `${name} ${address} ${address2} ${city} ${state} ${postcode} ${country}`; const nameAddress = `${name} ${address} ${address2} ${city} ${state} ${postcode} ${country}`;
// 获取电话号码 // 获取电话号码
const phone = shipping?.phone || billing?.phone || ''; const phone = shipping?.phone || billing?.phone || '';
// 获取快递号 // 获取快递号
const trackingNumber = order.shipment?.tracking_id || ''; const trackingNumber = order.shipment?.tracking_id || '';
@ -2570,84 +2566,86 @@ export class OrderService {
* CSV格式 * CSV格式
* @param {any[]} data * @param {any[]} data
* @param {Object} options * @param {Object} options
* @param {string} [options.type='string'] :'string' | 'buffer' * @param {string} [options.type='string'] :'string' | 'buffer'
* @param {string} [options.fileName] (使) * @param {string} [options.fileName] (使)
* @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) {
throw new Error('导出数据不能为空'); throw new Error('导出数据不能为空');
}
const { type = 'string', fileName, writeFile = false } = options;
// 生成表头
const headers = Object.keys(data[0]);
let csvContent = headers.join(',') + '\n';
// 处理数据行
data.forEach(item => {
const row = headers.map(key => {
const value = item[key as keyof any];
// 处理特殊字符
if (typeof value === 'string') {
// 转义双引号,将"替换为""
const escapedValue = value.replace(/"/g, '""');
// 如果包含逗号或换行符,需要用双引号包裹
if (escapedValue.includes(',') || escapedValue.includes('\n')) {
return `"${escapedValue}"`;
}
return escapedValue;
}
// 处理日期类型
if (value instanceof Date) {
return value.toISOString();
}
// 处理undefined和null
if (value === undefined || value === null) {
return '';
}
return String(value);
}).join(',');
csvContent += row + '\n';
});
// 如果需要写入文件
if (writeFile && fileName) {
// 获取当前用户目录
const userHomeDir = os.homedir();
// 构建目标路径(下载目录)
const downloadsDir = path.join(userHomeDir, 'Downloads');
// 确保下载目录存在
if (!fs.existsSync(downloadsDir)) {
fs.mkdirSync(downloadsDir, { recursive: true });
} }
const filePath = path.join(downloadsDir, fileName); const { type = 'string', fileName, writeFile = false } = options;
// 写入文件 // 生成表头
fs.writeFileSync(filePath, csvContent, 'utf8'); const headers = Object.keys(data[0]);
let csvContent = headers.join(',') + '\n';
console.log(`数据已成功导出至 ${filePath}`);
return filePath; // 处理数据行
data.forEach(item => {
const row = headers.map(key => {
const value = item[key as keyof any];
// 处理特殊字符
if (typeof value === 'string') {
// 转义双引号,将"替换为""
const escapedValue = value.replace(/"/g, '""');
// 如果包含逗号或换行符,需要用双引号包裹
if (escapedValue.includes(',') || escapedValue.includes('\n')) {
return `"${escapedValue}"`;
}
return escapedValue;
}
// 处理日期类型
if (value instanceof Date) {
return value.toISOString();
}
// 处理undefined和null
if (value === undefined || value === null) {
return '';
}
return String(value);
}).join(',');
csvContent += row + '\n';
});
// 如果需要写入文件
if (writeFile && fileName) {
// 获取当前用户目录
const userHomeDir = os.homedir();
// 构建目标路径(下载目录)
const downloadsDir = path.join(userHomeDir, 'Downloads');
// 确保下载目录存在
if (!fs.existsSync(downloadsDir)) {
fs.mkdirSync(downloadsDir, { recursive: true });
}
const filePath = path.join(downloadsDir, fileName);
// 写入文件
fs.writeFileSync(filePath, csvContent, 'utf8');
console.log(`数据已成功导出至 ${filePath}`);
return filePath;
}
// 根据类型返回不同结果
if (type === 'buffer') {
return Buffer.from(csvContent, 'utf8');
}
return csvContent;
} catch (error) {
console.error('导出CSV时出错:', error);
throw new Error(`导出CSV文件失败: ${error.message}`);
} }
// 根据类型返回不同结果
if (type === 'buffer') {
return Buffer.from(csvContent, 'utf8');
}
return csvContent;
} catch (error) {
console.error('导出CSV时出错:', error);
throw new Error(`导出CSV文件失败: ${error.message}`);
} }
} }
<<<<<<< HEAD
/** /**
* *
@ -2730,3 +2728,5 @@ async exportToCsv(data: any[], options: { type?: 'string' | 'buffer'; fileName?:
} }
=======
>>>>>>> 68574dbc7a74e0f8130f195eba4a28dd3887c485

View File

@ -1461,12 +1461,17 @@ export class ProductService {
return { return {
sku, sku,
name: val(rec.name), name: val(rec.name),
nameCn: val(rec.nameCn), nameCn: val(rec.nameCn),
description: val(rec.description), description: val(rec.description),
price: num(rec.price), price: num(rec.price),
promotionPrice: num(rec.promotionPrice), promotionPrice: num(rec.promotionPrice),
type: val(rec.type), type: val(rec.type),
siteSkus: rec.siteSkus ? String(rec.siteSkus).split(',').map(s => s.trim()).filter(Boolean) : undefined, siteSkus: rec.siteSkus
? String(rec.siteSkus)
.split(/[;,]/) // 支持英文分号或英文逗号分隔
.map(s => s.trim())
.filter(Boolean)
: undefined,
category, // 添加分类字段 category, // 添加分类字段
attributes: attributes.length > 0 ? attributes : undefined, attributes: attributes.length > 0 ? attributes : undefined,
@ -1531,7 +1536,14 @@ export class ProductService {
return dto; return dto;
} }
getAttributesObject(attributes:DictItem[]){
if(!attributes) return {}
const obj:any = {}
attributes.forEach(attr=>{
obj[attr.dict.name] = attr
})
return obj
}
// 将单个产品转换为 CSV 行数组 // 将单个产品转换为 CSV 行数组
transformProductToCsvRow( transformProductToCsvRow(
p: Product, p: Product,

View File

@ -73,16 +73,16 @@ export class StatisticsService {
order_sales_summary AS ( order_sales_summary AS (
SELECT SELECT
orderId, orderId,
SUM(CASE WHEN name LIKE '%zyn%' THEN quantity ELSE 0 END) AS zyn_quantity, SUM(CASE WHEN brand = 'zyn' THEN quantity ELSE 0 END) AS zyn_quantity,
SUM(CASE WHEN name LIKE '%yoone%' THEN quantity ELSE 0 END) AS yoone_quantity, SUM(CASE WHEN brand = 'yoone' THEN quantity ELSE 0 END) AS yoone_quantity,
SUM(CASE WHEN name LIKE '%zex%' THEN quantity ELSE 0 END) AS zex_quantity, SUM(CASE WHEN brand = 'zex' THEN quantity ELSE 0 END) AS zex_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity, SUM(CASE WHEN brand = 'yoone' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity, SUM(CASE WHEN brand = 'yoone' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%3%' THEN quantity ELSE 0 END) AS yoone_3_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '3mg' THEN quantity ELSE 0 END) AS yoone_3_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%6%' THEN quantity ELSE 0 END) AS yoone_6_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '6mg' THEN quantity ELSE 0 END) AS yoone_6_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%9%' THEN quantity ELSE 0 END) AS yoone_9_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '9mg' THEN quantity ELSE 0 END) AS yoone_9_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%12%' THEN quantity ELSE 0 END) AS yoone_12_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '12mg' THEN quantity ELSE 0 END) AS yoone_12_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%15%' THEN quantity ELSE 0 END) AS yoone_15_quantity SUM(CASE WHEN brand = 'yoone' AND strength = '15mg' THEN quantity ELSE 0 END) AS yoone_15_quantity
FROM order_sale FROM order_sale
GROUP BY orderId GROUP BY orderId
), ),
@ -269,16 +269,16 @@ export class StatisticsService {
order_sales_summary AS ( order_sales_summary AS (
SELECT SELECT
orderId, orderId,
SUM(CASE WHEN name LIKE '%zyn%' THEN quantity ELSE 0 END) AS zyn_quantity, SUM(CASE WHEN brand = 'zyn' THEN quantity ELSE 0 END) AS zyn_quantity,
SUM(CASE WHEN name LIKE '%yoone%' THEN quantity ELSE 0 END) AS yoone_quantity, SUM(CASE WHEN brand = 'yoone' THEN quantity ELSE 0 END) AS yoone_quantity,
SUM(CASE WHEN name LIKE '%zex%' THEN quantity ELSE 0 END) AS zex_quantity, SUM(CASE WHEN brand = 'zex' THEN quantity ELSE 0 END) AS zex_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity, SUM(CASE WHEN brand = 'yoone' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity, SUM(CASE WHEN brand = 'yoone' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%3%' THEN quantity ELSE 0 END) AS yoone_3_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '3mg' THEN quantity ELSE 0 END) AS yoone_3_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%6%' THEN quantity ELSE 0 END) AS yoone_6_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '6mg' THEN quantity ELSE 0 END) AS yoone_6_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%9%' THEN quantity ELSE 0 END) AS yoone_9_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '9mg' THEN quantity ELSE 0 END) AS yoone_9_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%12%' THEN quantity ELSE 0 END) AS yoone_12_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '12mg' THEN quantity ELSE 0 END) AS yoone_12_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%15%' THEN quantity ELSE 0 END) AS yoone_15_quantity SUM(CASE WHEN brand = 'yoone' AND strength = '15mg' THEN quantity ELSE 0 END) AS yoone_15_quantity
FROM order_sale FROM order_sale
GROUP BY orderId GROUP BY orderId
), ),
@ -466,16 +466,16 @@ export class StatisticsService {
order_sales_summary AS ( order_sales_summary AS (
SELECT SELECT
orderId, orderId,
SUM(CASE WHEN name LIKE '%zyn%' THEN quantity ELSE 0 END) AS zyn_quantity, SUM(CASE WHEN brand = 'zyn' THEN quantity ELSE 0 END) AS zyn_quantity,
SUM(CASE WHEN name LIKE '%yoone%' THEN quantity ELSE 0 END) AS yoone_quantity, SUM(CASE WHEN brand = 'yoone' THEN quantity ELSE 0 END) AS yoone_quantity,
SUM(CASE WHEN name LIKE '%zex%' THEN quantity ELSE 0 END) AS zex_quantity, SUM(CASE WHEN brand = 'zex' THEN quantity ELSE 0 END) AS zex_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity, SUM(CASE WHEN brand = 'yoone' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity, SUM(CASE WHEN brand = 'yoone' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%3%' THEN quantity ELSE 0 END) AS yoone_3_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '3mg' THEN quantity ELSE 0 END) AS yoone_3_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%6%' THEN quantity ELSE 0 END) AS yoone_6_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '6mg' THEN quantity ELSE 0 END) AS yoone_6_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%9%' THEN quantity ELSE 0 END) AS yoone_9_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '9mg' THEN quantity ELSE 0 END) AS yoone_9_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%12%' THEN quantity ELSE 0 END) AS yoone_12_quantity, SUM(CASE WHEN brand = 'yoone' AND strength = '12mg' THEN quantity ELSE 0 END) AS yoone_12_quantity,
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%15%' THEN quantity ELSE 0 END) AS yoone_15_quantity SUM(CASE WHEN brand = 'yoone' AND strength = '15mg' THEN quantity ELSE 0 END) AS yoone_15_quantity
FROM order_sale FROM order_sale
GROUP BY orderId GROUP BY orderId
), ),