Compare commits

..

8 Commits

Author SHA1 Message Date
zhuotianyuan 3c5261f5b1 fix(logistics): 修复货运平台courierCompany字段处理逻辑
当courierCompany为"最优物流"时设置为空字符串,否则使用原值
2026-01-28 19:36:51 +08:00
zhuotianyuan 02544c8310 feat(service): 新增Wintopay物流服务并优化订单导出和物流处理
新增Wintopay物流服务接口,支持物流信息更新功能
优化订单导出功能,增加动态商品列显示
简化物流服务状态判断逻辑,修复运单号生成问题
2026-01-28 17:37:39 +08:00
zhuotianyuan 1657b96694 fix(logistics): 修复物流订单状态检查和结果合并问题
修复 resShipmentOrder 状态检查时的可选链操作问题
修正 partnerOrderNumber 的拼接格式
调整查询结果合并方式,避免直接 push 操作
优化错误处理,使用 Error 对象抛出异常
2026-01-27 19:27:18 +08:00
zhuotianyuan 0a14a7c1ae fix(logistics): 修复物流服务中的错误处理和快递公司字段
修复freightwaves服务中的错误响应处理,增加错误码检查
添加courierCompany字段到物流DTO以支持不同快递公司
移除订单服务中注释掉的saveOrderSale调用
更新物流服务中使用courierCompany代替硬编码的shipCompany
2026-01-27 19:27:18 +08:00
zhuotianyuan 51b59ca176 Merge pull request 'feat(产品服务): 重构产品查询逻辑并添加价格字段' (#66) from zksu/API:main into main
Reviewed-on: #66
2026-01-27 11:19:15 +00:00
tikkhun b879202d13 refactor(product): 重构获取组件详情逻辑并支持数量参数
将获取组件详情的逻辑从order.service.ts移到product.service.ts中统一处理
新增quantity参数支持组件数量计算
返回结果中增加parentProduct信息用于追踪父产品
2026-01-27 18:53:54 +08:00
tikkhun d3d493f858 fix: 修复订单服务中产品详情检查逻辑
添加对productDetail.product的检查,避免在product为undefined时访问components属性
2026-01-27 18:42:00 +08:00
tikkhun 96a3e5c76d feat(产品服务): 重构产品查询逻辑并添加价格字段
重构 getProductBySiteSku 方法以支持更灵活的查询条件
在 site-product 实体中添加 price 字段
新增 site-product 控制器和服务用于管理站点商品
修改订单服务以支持站点参数传递
2026-01-27 10:33:13 +08:00
11 changed files with 158 additions and 193 deletions

View File

@ -996,6 +996,7 @@ export class ShopyyAdapter implements ISiteAdapter {
private async getProductBySku(sku: string): Promise<UnifiedProductDTO> { private async getProductBySku(sku: string): Promise<UnifiedProductDTO> {
// 使用Shopyy API的搜索功能通过sku查询产品 // 使用Shopyy API的搜索功能通过sku查询产品
const response = await this.getAllProducts({ where: { sku } }); const response = await this.getAllProducts({ where: { sku } });
console.log('getProductBySku', response)
const product = response?.[0] const product = response?.[0]
if (!product) { if (!product) {
throw new Error(`未找到sku为${sku}的产品`); throw new Error(`未找到sku为${sku}的产品`);
@ -1125,6 +1126,7 @@ export class ShopyyAdapter implements ISiteAdapter {
// ========== 产品变体映射方法 ========== // ========== 产品变体映射方法 ==========
mapPlatformToUnifiedVariation(variant: ShopyyVariant): UnifiedProductVariationDTO { mapPlatformToUnifiedVariation(variant: ShopyyVariant): UnifiedProductVariationDTO {
// 映射变体 // 映射变体
console.log('ivarianttem', variant)
return { return {
id: variant.id, id: variant.id,
name: variant.title || '', name: variant.title || '',

View File

@ -42,7 +42,6 @@ import DictSeeder from '../db/seeds/dict.seeder';
import CategorySeeder from '../db/seeds/category.seeder'; import CategorySeeder from '../db/seeds/category.seeder';
import CategoryAttributeSeeder from '../db/seeds/category_attribute.seeder'; import CategoryAttributeSeeder from '../db/seeds/category_attribute.seeder';
import { SiteSku } from '../entity/site-sku.entity'; import { SiteSku } from '../entity/site-sku.entity';
import { logisticsAlias } from '../entity/logistics_alias.emtity';
export default { export default {
// use for cookie sign key, should change to your own and keep security // use for cookie sign key, should change to your own and keep security
@ -89,7 +88,6 @@ export default {
Area, Area,
CategoryAttribute, CategoryAttribute,
Category, Category,
logisticsAlias,
], ],
synchronize: true, synchronize: true,
logging: false, logging: false,

View File

@ -40,6 +40,7 @@ export class AreaController {
})); }));
return successResponse(countryList, '查询成功'); return successResponse(countryList, '查询成功');
} catch (error) { } catch (error) {
console.log(error);
return errorResponse(error?.message || error); return errorResponse(error?.message || error);
} }
} }
@ -53,6 +54,7 @@ export class AreaController {
const newArea = await this.areaService.createArea(area); const newArea = await this.areaService.createArea(area);
return successResponse(newArea, '创建成功'); return successResponse(newArea, '创建成功');
} catch (error) { } catch (error) {
console.log(error);
return errorResponse(error?.message || error); return errorResponse(error?.message || error);
} }
} }
@ -66,6 +68,7 @@ export class AreaController {
const updatedArea = await this.areaService.updateArea(id, area); const updatedArea = await this.areaService.updateArea(id, area);
return successResponse(updatedArea, '更新成功'); return successResponse(updatedArea, '更新成功');
} catch (error) { } catch (error) {
console.log(error);
return errorResponse(error?.message || error); return errorResponse(error?.message || error);
} }
} }
@ -78,6 +81,7 @@ export class AreaController {
await this.areaService.deleteArea(id); await this.areaService.deleteArea(id);
return successResponse(null, '删除成功'); return successResponse(null, '删除成功');
} catch (error) { } catch (error) {
console.log(error);
return errorResponse(error?.message || error); return errorResponse(error?.message || error);
} }
} }
@ -91,6 +95,7 @@ export class AreaController {
const { list, total } = await this.areaService.getAreaList(query); const { list, total } = await this.areaService.getAreaList(query);
return successResponse({ list, total }, '查询成功'); return successResponse({ list, total }, '查询成功');
} catch (error) { } catch (error) {
console.log(error);
return errorResponse(error?.message || error); return errorResponse(error?.message || error);
} }
} }
@ -106,6 +111,7 @@ export class AreaController {
} }
return successResponse(area, '查询成功'); return successResponse(area, '查询成功');
} catch (error) { } catch (error) {
console.log(error);
return errorResponse(error?.message || error); return errorResponse(error?.message || error);
} }
} }

View File

@ -42,7 +42,8 @@ export class OrderController {
const result = await this.orderService.syncOrders(siteId, params); const result = await this.orderService.syncOrders(siteId, params);
return successResponse(result); return successResponse(result);
} catch (error) { } catch (error) {
return errorResponse(`同步失败,${error?.message || '未知错误'}`); console.log(error);
return errorResponse('同步失败');
} }
} }
@ -58,6 +59,7 @@ export class OrderController {
const result = await this.orderService.syncOrderById(siteId, orderId); const result = await this.orderService.syncOrderById(siteId, orderId);
return successResponse(result); return successResponse(result);
} catch (error) { } catch (error) {
console.log(error);
return errorResponse('同步失败'); return errorResponse('同步失败');
} }
} }

View File

@ -25,7 +25,7 @@ export class ShipmentBookDTO {
shipmentPlatform: string; shipmentPlatform: string;
@ApiProperty() @ApiProperty()
@Rule(RuleType.any()) @Rule(RuleType.string())
courierCompany: string; courierCompany: string;
} }

View File

@ -1,34 +0,0 @@
import { ApiProperty } from '@midwayjs/swagger';
import { Entity,CreateDateColumn,UpdateDateColumn, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('logistics_alias')
export class logisticsAlias {
@PrimaryGeneratedColumn()
id: number;
@ApiProperty({ type: 'string' })
@Column()
logistics_company:string
@ApiProperty({ type: 'string' })
@Column()
logistics_alias:string
@ApiProperty({ type: 'string' })
@Column()
platform:string
// 是否可删除
@Column({ default: true, comment: '是否可删除' })
deletable: boolean;
// 创建时间
@CreateDateColumn()
createdAt: Date;
// 更新时间
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -6,7 +6,6 @@ import {
} from 'typeorm'; } from 'typeorm';
import { ApiProperty } from '@midwayjs/swagger'; import { ApiProperty } from '@midwayjs/swagger';
import { Product } from './product.entity'; import { Product } from './product.entity';
// 这个其实是 alias 后面改一下
@Entity('product_site_sku') @Entity('product_site_sku')
export class SiteSku { export class SiteSku {
@ApiProperty({ description: 'sku'}) @ApiProperty({ description: 'sku'})

View File

@ -371,9 +371,9 @@ export class CustomerService {
const { const {
page = 1, page = 1,
per_page = 20, per_page = 20,
where = {}, where ={},
} = params; } = params;
if (where?.phone) { if (where.phone) {
where.phone = Like(`%${where.phone}%`); where.phone = Like(`%${where.phone}%`);
} }

View File

@ -735,10 +735,14 @@ export class LogisticsService {
if (data.shipmentPlatform === 'freightwaves') { if (data.shipmentPlatform === 'freightwaves') {
let courierCompany: string = "";
if (data.courierCompany != "最优物流") {
courierCompany = data.courierCompany;
}
// 根据TMS系统对接说明文档格式化参数 // 根据TMS系统对接说明文档格式化参数
const reqBody: any = { const reqBody: any = {
// shipCompany: 'UPSYYZ7000NEW', // shipCompany: 'UPSYYZ7000NEW',
shipCompany: data.courierCompany, shipCompany: courierCompany,
partnerOrderNumber: order.siteId + '-' + order.externalOrderId, partnerOrderNumber: order.siteId + '-' + order.externalOrderId,
warehouseId: '25072621030107400060', warehouseId: '25072621030107400060',
shipper: { shipper: {
@ -832,12 +836,15 @@ export class LogisticsService {
id: data.address_id, id: data.address_id,
}, },
}) })
const address = shipments?.address; const address = shipments?.address;
let courierCompany: string = "";
if (data.courierCompany != "最优物流") {
courierCompany = data.courierCompany;
}
// 转换为RateTryRequest格式 // 转换为RateTryRequest格式
const r = { const r = {
//shipCompany: 'UPSYYZ7000NEW', // 必填但ShipmentFeeBookDTO中缺少 //shipCompany: 'UPSYYZ7000NEW', // 必填但ShipmentFeeBookDTO中缺少
shipCompany: data.courierCompany, shipCompany: courierCompany,
partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成 partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成
warehouseId: '25072621030107400060', // 可选使用stockPointId转换 warehouseId: '25072621030107400060', // 可选使用stockPointId转换
shipper: { shipper: {

View File

@ -42,7 +42,6 @@ import { UnifiedOrderDTO } from '../dto/site-api.dto';
import { CustomerService } from './customer.service'; import { CustomerService } from './customer.service';
import { ProductService } from './product.service'; import { ProductService } from './product.service';
import { Site } from '../entity/site.entity'; import { Site } from '../entity/site.entity';
import { logisticsAlias } from '../entity/logistics_alias.emtity';
@Provide() @Provide()
export class OrderService { export class OrderService {
@ -55,9 +54,6 @@ export class OrderService {
@InjectEntityModel(Order) @InjectEntityModel(Order)
orderModel: Repository<Order>; orderModel: Repository<Order>;
@InjectEntityModel(logisticsAlias)
logisticsAliasModel: Repository<logisticsAlias>;
@InjectEntityModel(User) @InjectEntityModel(User)
userModel: Repository<User>; userModel: Repository<User>;
@ -137,7 +133,7 @@ export class OrderService {
async syncOrders(siteId: number, params: Record<string, any> = {}): Promise<SyncOperationResult> { async syncOrders(siteId: number, params: Record<string, any> = {}): Promise<SyncOperationResult> {
// 调用 WooCommerce API 获取订单 // 调用 WooCommerce API 获取订单
const result = await (await this.siteApiService.getAdapter(siteId)).getAllOrders(params); const result = await (await this.siteApiService.getAdapter(siteId)).getAllOrders(params);
this.logger.info('开始进入循环同步订单', result.length, '个订单')
// 初始化同步结果对象 // 初始化同步结果对象
const syncResult: SyncOperationResult = { const syncResult: SyncOperationResult = {
total: result.length, total: result.length,
@ -147,6 +143,7 @@ export class OrderService {
updated: 0, updated: 0,
errors: [] errors: []
}; };
this.logger.info('开始进入循环同步订单', result.length, '个订单')
// 遍历每个订单进行同步 // 遍历每个订单进行同步
for (const order of result) { for (const order of result) {
try { try {
@ -155,7 +152,7 @@ export class OrderService {
where: { externalOrderId: String(order.id), siteId: siteId }, where: { externalOrderId: String(order.id), siteId: siteId },
}); });
if (!existingOrder) { if (!existingOrder) {
this.logger.debug("数据库中不存在", order.id, '订单状态:', order.status) this.logger.debug("数据库中不存在", order.id, '订单状态:', order.status)
} }
// 同步单个订单 // 同步单个订单
await this.syncSingleOrder(siteId, order); await this.syncSingleOrder(siteId, order);
@ -482,20 +479,6 @@ export class OrderService {
const existingOrder = await this.orderModel.findOne({ const existingOrder = await this.orderModel.findOne({
where: { externalOrderId, siteId: siteId }, where: { externalOrderId, siteId: siteId },
}); });
// 提前不然存在就不更新客户信息了
// 创建或更新客户信息
await this.customerService.upsertCustomer({
email: order.customer_email,
site_id: siteId,
origin_id: String(order.customer_id),
billing: order.billing,
shipping: order.shipping,
first_name: order?.billing?.first_name || order?.shipping?.first_name,
last_name: order?.billing?.last_name || order?.shipping?.last_name,
fullname: order?.billing?.fullname || order?.shipping?.fullname || order?.billing?.first_name + ' ' + order?.billing?.last_name,
phone: order?.billing?.phone || order?.shipping?.phone,
// tags:['fromOrder']
});
// 如果订单已存在 // 如果订单已存在
if (existingOrder) { if (existingOrder) {
// 检查是否可以更新 ERP 状态 // 检查是否可以更新 ERP 状态
@ -512,7 +495,20 @@ export class OrderService {
} }
// 如果订单不存在,则映射订单状态 // 如果订单不存在,则映射订单状态
entity.orderStatus = this.mapOrderStatus(entity.status); entity.orderStatus = this.mapOrderStatus(entity.status);
// 创建或更新客户信息
await this.customerService.upsertCustomer({
email: order.customer_email,
site_id: siteId,
origin_id: String(order.customer_id),
billing: order.billing,
shipping: order.shipping,
first_name: order?.billing?.first_name || order?.shipping?.first_name,
last_name: order?.billing?.last_name || order?.shipping?.last_name,
fullname: order?.billing?.fullname || order?.shipping?.fullname,
phone: order?.billing?.phone || order?.shipping?.phone,
// tags:['fromOrder']
});
// const customer = await this.customerModel.findOne({ // const customer = await this.customerModel.findOne({
// where: { email: order.customer_email }, // where: { email: order.customer_email },
// }); // });
@ -634,7 +630,7 @@ export class OrderService {
await this.saveOrderItem(entity); await this.saveOrderItem(entity);
// 为每个订单项创建对应的销售项(OrderSale) // 为每个订单项创建对应的销售项(OrderSale)
const site = await this.siteService.get(siteId); const site = await this.siteService.get(siteId);
await this.saveOrderSale(entity, site); await this.saveOrderSale(entity,site);
} }
} }
@ -724,7 +720,7 @@ export class OrderService {
*/ */
// TODO 这里存的是库存商品实际 // TODO 这里存的是库存商品实际
// 所以叫做 orderInventoryItems 可能更合适 // 所以叫做 orderInventoryItems 可能更合适
async saveOrderSale(orderItem: OrderItem, site: Site) { async saveOrderSale(orderItem: OrderItem,site:Site) {
const currentOrderSale = await this.orderSaleModel.find({ const currentOrderSale = await this.orderSaleModel.find({
where: { where: {
siteId: orderItem.siteId, siteId: orderItem.siteId,
@ -737,19 +733,19 @@ export class OrderService {
if (!orderItem.sku) return; if (!orderItem.sku) return;
// 从数据库查询产品,关联查询组件 // 从数据库查询产品,关联查询组件
const componentDetails = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name }, orderItem.quantity, site); const componentDetails = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name },orderItem.quantity,site);
if (!componentDetails?.length) { if(!componentDetails?.length){
return return
} }
const orderSales: OrderSale[] = componentDetails.map(({ product, parentProduct, quantity }) => { const orderSales: OrderSale[] = componentDetails.map(({product, parentProduct, quantity}) => {
if (!product) return null if (!product) return null
const attrsObj = this.productService.getAttributesObject(product.attributes) const attrsObj = this.productService.getAttributesObject(product.attributes)
const orderSale = plainToClass(OrderSale, { const orderSale = plainToClass(OrderSale, {
orderId: orderItem.orderId, orderId: orderItem.orderId,
siteId: orderItem.siteId, siteId: orderItem.siteId,
externalOrderItemId: orderItem.externalOrderItemId,// 原始 itemId externalOrderItemId: orderItem.externalOrderItemId,// 原始 itemId
parentProductId: parentProduct?.id, // 父产品 ID 用于统计套餐 如果是单品则不记录 parentProductId: parentProduct.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
productId: product.id, productId: product.id,
isPackage: product.type === 'bundle',// 这里是否是套餐取决于父产品 isPackage: product.type === 'bundle',// 这里是否是套餐取决于父产品
name: product.name, name: product.name,
@ -762,7 +758,7 @@ export class OrderService {
flavor: attrsObj?.['flavor']?.name, flavor: attrsObj?.['flavor']?.name,
humidity: attrsObj?.['humidity']?.name, humidity: attrsObj?.['humidity']?.name,
size: attrsObj?.['size']?.name, size: attrsObj?.['size']?.name,
category: product.category?.name, category: product.category.name,
}); });
return orderSale return orderSale
}).filter(v => v !== null) }).filter(v => v !== null)
@ -2825,116 +2821,107 @@ export class OrderService {
return result; return result;
} }
// 从 CSV 导入产品;存在则更新,不存在则创建 // 从 CSV 导入产品;存在则更新,不存在则创建
/** /**
* Wintopay * Wintopay
* @param file * @param file
* @returns * @returns
*/ */
async importWintopayTable(file: any): Promise<any> { async importWintopayTable(file: any): Promise<any> {
let updated = 0; let updated = 0;
const errors: BatchErrorItem[] = []; const errors: BatchErrorItem[] = [];
// 解析文件获取工作表 // 解析文件获取工作表
let buffer: Buffer; let buffer: Buffer;
if (Buffer.isBuffer(file)) { if (Buffer.isBuffer(file)) {
buffer = file; buffer = file;
} else if (file?.data) { } else if (file?.data) {
if (typeof file.data === 'string') { if (typeof file.data === 'string') {
buffer = fs.readFileSync(file.data); buffer = fs.readFileSync(file.data);
} else { } else {
buffer = file.data; buffer = file.data;
} }
} else { } else {
throw new Error('无效的文件输入'); throw new Error('无效的文件输入');
} }
const workbook = xlsx.read(buffer, { type: 'buffer', codepage: 65001 }); const workbook = xlsx.read(buffer, { type: 'buffer', codepage: 65001 });
const worksheet = workbook.Sheets[workbook.SheetNames[0]]; const worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 获取表头和数据 // 获取表头和数据
const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 }); const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 });
const headers = jsonData[0] as string[]; const headers = jsonData[0] as string[];
const dataRows = jsonData.slice(1) as any[][]; const dataRows = jsonData.slice(1) as any[][];
// 查找各列的索引 // 查找各列的索引
const columnIndices = { const columnIndices = {
orderNumber: headers.indexOf('订单号'), orderNumber: headers.indexOf('订单号'),
logisticsCompany: headers.indexOf('物流公司'), logisticsCompany: headers.indexOf('物流公司'),
trackingNumber: headers.indexOf('单号-单元格文本格式'), trackingNumber: headers.indexOf('单号-单元格文本格式'),
orderCreateTime: headers.indexOf('订单创建时间'), orderCreateTime: headers.indexOf('订单创建时间'),
orderEmail: headers.indexOf('订单邮箱'), orderEmail: headers.indexOf('订单邮箱'),
orderSite: headers.indexOf('订单网站'), orderSite: headers.indexOf('订单网站'),
name: headers.indexOf('姓名'), name: headers.indexOf('姓名'),
refund: headers.indexOf('退款'), refund: headers.indexOf('退款'),
chargeback: headers.indexOf('拒付') chargeback: headers.indexOf('拒付')
}; };
const logisticsAliases = await this.logisticsAliasModel.find(); // 遍历数据行
for (let i = 0; i < dataRows.length; i++) {
// 构建物流公司别名映射 const row = dataRows[i];
const logisticsAliasMap = new Map(logisticsAliases.map(alias => [ alias.logistics_alias,alias.logistics_company])); const orderNumber = row[columnIndices.orderNumber];
// 遍历数据行 if (!orderNumber) {
for (let i = 0; i < dataRows.length; i++) { errors.push({ identifier: `${i + 2}`, error: '订单号为空' });
const row = dataRows[i]; continue;
const orderNumber = row[columnIndices.orderNumber]; }
if (!orderNumber) { try {
errors.push({ identifier: `${i + 2}`, error: '订单号为空' }); let orderNumbers="";
continue; if (orderNumber.includes('_')&&orderNumber.includes('-')) {
} orderNumbers = orderNumber.split('_')[0].toString();
orderNumbers = orderNumbers.split('-')[1];
try {
let orderNumbers = orderNumber;
// 确保 orderNumber 是字符串类型
const orderNumberStr = String(orderNumber);
if (orderNumberStr.includes('_') && orderNumberStr.includes('-')) {
orderNumbers = orderNumberStr.split('_')[0].toString();
orderNumbers = orderNumbers.split('-')[1];
}
// 通过订单号查询订单
const order = await this.orderModel.findOne({ where: { externalOrderId: orderNumbers } });
if (order) {
// 通过orderId查询fulfillments
const fulfillments = await this.orderFulfillmentModel.find({ where: { order_id: order.id } });
if (fulfillments && fulfillments.length > 0) {
const fulfillment = fulfillments[0]; // 假设每个订单只有一个物流信息
const shipping_provider = logisticsAliasMap.get(fulfillment.shipping_provider);
// 回填物流信息
if (columnIndices.logisticsCompany !== -1) {
row[columnIndices.logisticsCompany] = shipping_provider || '';
}
if (columnIndices.trackingNumber !== -1) {
row[columnIndices.trackingNumber] = fulfillment.tracking_number || '';
} }
// 通过订单号查询订单
const order = await this.orderModel.findOne({ where: { externalOrderId: orderNumbers } });
if (order) {
// 通过orderId查询fulfillments
const fulfillments = await this.orderFulfillmentModel.find({ where: { order_id: order.id } });
if (fulfillments && fulfillments.length > 0) {
const fulfillment = fulfillments[0]; // 假设每个订单只有一个物流信息
// 回填物流信息
if (columnIndices.logisticsCompany !== -1) {
row[columnIndices.logisticsCompany] = fulfillment.shipping_provider || '';
}
if (columnIndices.trackingNumber !== -1) {
row[columnIndices.trackingNumber] = fulfillment.tracking_number || '';
}
updated++;
}
}
} catch (error) {
errors.push({ identifier: `${i + 2}`, error: `处理失败: ${error.message}` });
}
}
// 将数据转换为对象数组,与 exportOrder 方法返回格式一致
const resultData = dataRows.map((row, index) => {
const rowData: any = {};
headers.forEach((header, colIndex) => {
rowData[header] = row[colIndex] || '';
});
// 添加行号信息
rowData['行号'] = index + 2;
return rowData;
});
// 返回XLSX buffer内容给前端
// const xlsxBuffer = await this.exportToXlsx(resultData, { type: 'buffer' });
return resultData;
updated++;
}
}
} catch (error) {
errors.push({ identifier: `${i + 2}`, error: `处理失败: ${error.message}` });
}
} }
// 将数据转换为对象数组,与 exportOrder 方法返回格式一致
const resultData = dataRows.map((row, index) => {
const rowData: any = {};
headers.forEach((header, colIndex) => {
rowData[header] = row[colIndex] || '';
});
// 添加行号信息
rowData['行号'] = index + 2;
return rowData;
});
// 返回XLSX buffer内容给前端
// const xlsxBuffer = await this.exportToXlsx(resultData, { type: 'buffer' });
return resultData;
}
} }

View File

@ -1,4 +1,4 @@
import { ILogger, Inject, Logger, Provide } from '@midwayjs/core'; import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa'; import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm'; import { InjectEntityModel } from '@midwayjs/typeorm';
import * as fs from 'fs'; import * as fs from 'fs';
@ -38,9 +38,6 @@ import { Site } from '../entity/site.entity';
@Provide() @Provide()
export class ProductService { export class ProductService {
@Logger()
logger: ILogger; // 注入 Logger 实例
@Inject() @Inject()
ctx: Context; ctx: Context;
@ -859,7 +856,7 @@ export class ProductService {
// 检查完全相同属性组合是否已存在(避免重复) // 检查完全相同属性组合是否已存在(避免重复)
// 仅当产品类型为 'single' 且有属性时才检查重复 // 仅当产品类型为 'single' 且有属性时才检查重复
if (type === 'single' && resolvedAttributes.length > 0) { if (type === 'single' && resolvedAttributes.length > 0) {
const qb = this.productModel.createQueryBuilder('product') const qb = this.productModel.createQueryBuilder('product');
resolvedAttributes.forEach((attr, index) => { resolvedAttributes.forEach((attr, index) => {
qb.innerJoin( qb.innerJoin(
'product.attributes', 'product.attributes',
@ -868,12 +865,8 @@ export class ProductService {
{ [`attrId${index}`]: attr.id } { [`attrId${index}`]: attr.id }
); );
}); });
// 添加属性数量的判断,确保产品的属性数量与指定的属性数量相同
qb.andWhere('(SELECT COUNT(*) FROM product_attributes_dict_item pad WHERE pad.productId = product.id) = :attrCount', {
attrCount: resolvedAttributes.length
});
const isExist = await qb.getOne(); const isExist = await qb.getOne();
if (isExist) throw new Error(`相同产品属性的产品已存在,sku 为${isExist?.sku}`); if (isExist) throw new Error('相同产品属性的产品已存在');
} }
// 创建新产品实例(绑定属性与基础字段) // 创建新产品实例(绑定属性与基础字段)
@ -2037,9 +2030,9 @@ export class ProductService {
// 将工作表转换为 JSON 数组 // 将工作表转换为 JSON 数组
records = xlsx.utils.sheet_to_json(worksheet); records = xlsx.utils.sheet_to_json(worksheet);
this.logger.debug('Parsed records count:', records.length); console.log('Parsed records count:', records.length);
if (records.length > 0) { if (records.length > 0) {
this.logger.debug('First record keys:', Object.keys(records[0])); console.log('First record keys:', Object.keys(records[0]));
} }
return records; return records;
} catch (e: any) { } catch (e: any) {
@ -2053,7 +2046,6 @@ export class ProductService {
let updated = 0; let updated = 0;
const errors: BatchErrorItem[] = []; const errors: BatchErrorItem[] = [];
const records = await this.getRecordsFromTable(file); const records = await this.getRecordsFromTable(file);
this.logger.debug('Total records count:', records.length);
// 逐条处理记录 // 逐条处理记录
for (const rec of records) { for (const rec of records) {
try { try {
@ -2082,7 +2074,7 @@ export class ProductService {
errors.push({ identifier: '' + rec.sku, error: `产品${rec?.sku}导入失败:${e?.message || String(e)}` }); errors.push({ identifier: '' + rec.sku, error: `产品${rec?.sku}导入失败:${e?.message || String(e)}` });
} }
} }
this.logger.info(`导入 ${records.length} 条记录,成功创建 ${created} 条,更新 ${updated} 条,失败 ${errors.length} 条,错误详情:${JSON.stringify(errors)}`);
return { total: records.length, processed: records.length - errors.length, created, updated, errors }; return { total: records.length, processed: records.length - errors.length, created, updated, errors };
} }
@ -2140,10 +2132,16 @@ export class ProductService {
component.sku = product.sku; component.sku = product.sku;
component.quantity = 1; component.quantity = 1;
product.components = [component]; product.components = [component];
} else {
// 混装商品返回持久化的 SKU 组成
product.components = await this.productStockComponentModel.find({
where: { productId: product.id },
});
} }
return product; return product;
} }
// 根据站点SKU查询产品 // 根据站点SKU查询产品
async getProductBySiteSku(siteSku: string, site?: Site): Promise<Product> { async getProductBySiteSku(siteSku: string, site?: Site): Promise<Product> {
// 使用查询构建器来正确查询关联表 // 使用查询构建器来正确查询关联表