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

Compare commits

...

10 Commits

Author SHA1 Message Date
tikkhun f4a46bcf72 fix(订单服务): 修复产品分类可能为空的错误并优化产品查询
修复订单服务中产品分类可能为空导致的错误,改为可选链操作
优化产品服务中组件查询逻辑,使用sku查询并添加关联关系
移除产品服务中不必要的组件查询逻辑
2026-01-29 09:20:57 +08:00
tikkhun 534cc3f2c7 refactor(订单服务): 移除getComponentDetailFromSiteSku中不必要的quantity参数
简化组件详情查询逻辑,默认数量设为1,不再需要外部传入quantity参数
2026-01-29 09:20:57 +08:00
tikkhun d8a3422015 fix(product): 修复产品属性重复检查逻辑并添加日志记录
修复产品属性重复检查时未考虑属性数量的问题,确保只有当属性数量完全匹配时才认为重复
添加导入结果的调试日志记录
2026-01-29 09:20:57 +08:00
tikkhun 9d69af03b2 fix: 修复父产品ID可能为undefined时的处理 2026-01-29 09:20:57 +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: yoone/API#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 311 additions and 110 deletions

View File

@ -201,7 +201,7 @@ export class ProductController {
@Get('/site-sku/:siteSku')
async getProductBySiteSku(@Param('siteSku') siteSku: string) {
try {
const product = await this.productService.findProductBySiteSku(siteSku);
const product = await this.productService.getProductBySiteSku(siteSku);
return successResponse(product);
} catch (error) {
return errorResponse(error.message || '获取数据失败');

View File

@ -0,0 +1,90 @@
import {
Body,
Controller,
Get,
Inject,
Post,
Query,
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { ILogger } from '@midwayjs/logger';
import { ApiOkResponse } from '@midwayjs/swagger';
import { SiteProductService } from '../service/site-product.service';
import { errorResponse, successResponse } from '../utils/response.util';
@Controller('/site-product')
export class SiteProductController {
@Inject()
siteProductService: SiteProductService;
@Inject()
ctx: Context;
@Inject()
logger: ILogger;
@ApiOkResponse({
description: '获取站点商品列表',
})
@Get('/list')
async getSiteProductList(
@Query('current') current: number = 1,
@Query('pageSize') pageSize: number = 10,
@Query('siteId') siteId: number,
@Query('name') name: string,
@Query('sku') sku: string
) {
try {
const data = await this.siteProductService.getSiteProductList({
current,
pageSize,
siteId,
name,
sku,
});
return successResponse(data);
} catch (error) {
this.logger.error('获取站点商品列表失败', error);
return errorResponse(error?.message || error);
}
}
@ApiOkResponse({
description: '同步站点商品',
})
@Post('/sync')
async syncSiteProducts(@Body('siteId') siteId: number) {
try {
const result = await this.siteProductService.syncSiteProducts(siteId);
return successResponse(result);
} catch (error) {
this.logger.error('同步站点商品失败', error);
return errorResponse(error?.message || error);
}
}
@ApiOkResponse({
description: '批量修改站点商品价格',
})
@Post('/batch-update-price')
async batchUpdatePrice(
@Body('siteId') siteId: number,
@Body('productIds') productIds: string[],
@Body('price') price: number
) {
try {
const affected = await this.siteProductService.batchUpdatePrice(
siteId,
productIds,
price
);
return successResponse({
affected,
message: `成功修改 ${affected} 个商品的价格`,
});
} catch (error) {
this.logger.error('批量修改站点商品价格失败', error);
return errorResponse(error?.message || error);
}
}
}

View File

@ -23,6 +23,10 @@ export class ShipmentBookDTO {
@ApiProperty()
@Rule(RuleType.string())
shipmentPlatform: string;
@ApiProperty()
@Rule(RuleType.string())
courierCompany: string;
}
export class ShipmentFeeBookDTO {
@ -30,6 +34,8 @@ export class ShipmentFeeBookDTO {
@ApiProperty()
shipmentPlatform: string;
@ApiProperty()
courierCompany: string;
@ApiProperty()
stockPointId: number;
@ApiProperty()
sender: string;

View File

@ -99,7 +99,6 @@ export class Product {
@OneToMany(() => ProductStockComponent, (component) => component.product, { cascade: true })
components: ProductStockComponent[];
// 站点 SKU 关联
@ApiProperty({ description: '站点 SKU关联', type: SiteSku, isArray: true })
@OneToMany(() => SiteSku, siteSku => siteSku.product, { cascade: true })

View File

@ -76,6 +76,10 @@ export class SiteProduct {
@CreateDateColumn()
createdAt: Date;
@ApiProperty({ description: '价格' })
@Column({ type: 'decimal', precision: 10, scale: 2, nullable: true })
price: number;
@ApiProperty({
example: '2022-12-12 11:11:11',
description: '更新时间',

View File

@ -247,6 +247,9 @@ export class FreightwavesService {
};
const response = await this.sendRequest<RateTryResponseData>('/shipService/order/rateTry', requestData);
if (response.code !== '00000200') {
throw new Error(response.msg);
}
return response.data;
}
@ -262,7 +265,10 @@ export class FreightwavesService {
};
const response = await this.sendRequest<CreateOrderResponseData>('/shipService/order/createOrder', requestData);
return response;
if (response.code !== '00000200') {
throw new Error(response.msg);
}
return response.data;
}
/**
@ -295,6 +301,9 @@ export class FreightwavesService {
};
const response = await this.sendRequest<ModifyOrderResponseData>('/shipService/order/modifyOrder', requestData);
if (response.code !== '00000200') {
throw new Error(response.msg);
}
return response.data;
}
@ -309,6 +318,9 @@ export class FreightwavesService {
partner: this.config.partner,
};
const response = await this.sendRequest<RefundOrderResponseData>('/shipService/order/refundOrder', requestData);
if (response.code !== '00000200') {
throw new Error(response.msg);
}
return response.data;
}

View File

@ -464,7 +464,7 @@ export class LogisticsService {
}
};
} catch (error) {
if (resShipmentOrder.status === 'SUCCESS') {
if (resShipmentOrder?.status === 'SUCCESS') {
await this.uniExpressService.deleteShipment(resShipmentOrder.data.tno);
}
throw new Error(`上游请求错误:${error}`);
@ -733,8 +733,9 @@ export class LogisticsService {
if (data.shipmentPlatform === 'freightwaves') {
// 根据TMS系统对接说明文档格式化参数
const reqBody: any = {
shipCompany: 'UPSYYZ7000NEW',
partnerOrderNumber: order.siteId + '-' + order.externalOrderId,
// shipCompany: 'UPSYYZ7000NEW',
shipCompany: data.courierCompany || "",
partnerOrderNumber: order.siteId + '-1-' + order.externalOrderId,
warehouseId: '25072621030107400060',
shipper: {
name: data.details.origin.contact_name, // 姓名
@ -798,15 +799,20 @@ export class LogisticsService {
};
resShipmentOrder = await this.freightwavesService.createOrder(reqBody); // 创建订单
//tms只返回了物流订单号需要查询一次来获取完整的物流信息
const queryRes = await this.freightwavesService.queryOrder({ shipOrderId: resShipmentOrder.shipOrderId }); // 查询订单
resShipmentOrder.push(queryRes);
return {
...resShipmentOrder,
...queryRes
}
}
return resShipmentOrder;
} catch (error) {
console.log('物流订单处理失败:', error); // 使用console.log代替this.log
throw error;
// 处理错误,例如记录日志或抛出异常
throw new Error(`物流订单处理失败: ${error}`);
}
}
@ -826,7 +832,8 @@ export class LogisticsService {
const address = shipments?.address;
// 转换为RateTryRequest格式
const r = {
shipCompany: 'UPSYYZ7000NEW', // 必填但ShipmentFeeBookDTO中缺少
//shipCompany: 'UPSYYZ7000NEW', // 必填但ShipmentFeeBookDTO中缺少
shipCompany: data.courierCompany || "",
partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成
warehouseId: '25072621030107400060', // 可选使用stockPointId转换
shipper: {

View File

@ -41,6 +41,7 @@ import * as os from 'os';
import { UnifiedOrderDTO } from '../dto/site-api.dto';
import { CustomerService } from './customer.service';
import { ProductService } from './product.service';
import { Site } from '../entity/site.entity';
@Provide()
export class OrderService {
@ -628,7 +629,8 @@ export class OrderService {
// 保存订单项
await this.saveOrderItem(entity);
// 为每个订单项创建对应的销售项(OrderSale)
await this.saveOrderSale(entity);
const site = await this.siteService.get(siteId);
await this.saveOrderSale(entity,site);
}
}
@ -718,7 +720,7 @@ export class OrderService {
*/
// TODO 这里存的是库存商品实际
// 所以叫做 orderInventoryItems 可能更合适
async saveOrderSale(orderItem: OrderItem) {
async saveOrderSale(orderItem: OrderItem,site:Site) {
const currentOrderSale = await this.orderSaleModel.find({
where: {
siteId: orderItem.siteId,
@ -731,32 +733,25 @@ export class OrderService {
if (!orderItem.sku) return;
// 从数据库查询产品,关联查询组件
const productDetail = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name });
if (!productDetail || !productDetail.quantity) return;
const { product, quantity } = productDetail
const componentDetails: { product: Product, quantity: number }[] = product.components?.length > 0 ? await Promise.all(product.components.map(async comp => {
return {
product: await this.productModel.findOne({
where: { id: comp.productId },
}),
quantity: comp.quantity * orderItem.quantity,
const componentDetails = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name }, site);
if(!componentDetails?.length){
return
}
})) : [{ product, quantity }]
const orderSales: OrderSale[] = componentDetails.map(componentDetail => {
if (!componentDetail.product) return null
const orderSales: OrderSale[] = componentDetails.map(({product, parentProduct, quantity}) => {
if (!product) return null
console.log('product',product)
const attrsObj = this.productService.getAttributesObject(product.attributes)
const orderSale = plainToClass(OrderSale, {
orderId: orderItem.orderId,
siteId: orderItem.siteId,
externalOrderItemId: orderItem.externalOrderItemId,// 原始 itemId
parentProductId: product.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
productId: componentDetail.product.id,
parentProductId: parentProduct?.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
productId: product.id,
isPackage: product.type === 'bundle',// 这里是否是套餐取决于父产品
name: componentDetail.product.name,
quantity: componentDetail.quantity * orderItem.quantity,
sku: componentDetail.product.sku,
name: product.name,
quantity: quantity * orderItem.quantity,
sku: product.sku,
// 理论上直接存 product 的全部数据才是对的,因为这样我的数据才全面。
brand: attrsObj?.['brand']?.name,
version: attrsObj?.['version']?.name,
@ -764,7 +759,7 @@ export class OrderService {
flavor: attrsObj?.['flavor']?.name,
humidity: attrsObj?.['humidity']?.name,
size: attrsObj?.['size']?.name,
category: componentDetail.product.category.name,
category: product.category?.name,
});
return orderSale
}).filter(v => v !== null)

View File

@ -1,4 +1,4 @@
import { Inject, Provide } from '@midwayjs/core';
import { ILogger, Inject, Logger, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import * as fs from 'fs';
@ -34,9 +34,13 @@ import { paginate } from '../utils/paginate.util';
import { SiteApiService } from './site-api.service';
import { StockService } from './stock.service';
import { TemplateService } from './template.service';
import { Site } from '../entity/site.entity';
@Provide()
export class ProductService {
@Logger()
logger: ILogger; // 注入 Logger 实例
@Inject()
ctx: Context;
@ -855,7 +859,7 @@ export class ProductService {
// 检查完全相同属性组合是否已存在(避免重复)
// 仅当产品类型为 'single' 且有属性时才检查重复
if (type === 'single' && resolvedAttributes.length > 0) {
const qb = this.productModel.createQueryBuilder('product');
const qb = this.productModel.createQueryBuilder('product')
resolvedAttributes.forEach((attr, index) => {
qb.innerJoin(
'product.attributes',
@ -864,8 +868,12 @@ export class ProductService {
{ [`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();
if (isExist) throw new Error('相同产品属性的产品已存在');
if (isExist) throw new Error(`相同产品属性的产品已存在,sku 为${isExist?.sku}`);
}
// 创建新产品实例(绑定属性与基础字段)
@ -1777,58 +1785,33 @@ export class ProductService {
attributes: attributes.length > 0 ? attributes : undefined,
}
}
isMixedSku(sku: string){
const splitSKu = sku.split('-')
const last = splitSKu[splitSKu.length - 1]
const second = splitSKu[splitSKu.length - 2]
// 这里判断 second 是否是数字
return sku.includes('-MX-') || sku.includes('-Mixed-') || /^\d+$/.test(second) && /^\d+$/.test(last)
}
async getComponentDetailFromSiteSku(siteProduct: { sku: string, name: string }) {
// 获取库存单品列表
async getComponentDetailFromSiteSku(siteProduct: { sku: string, name?: string }, site: Site): Promise<{ product: Product,parentProduct?: Product, quantity: number }[]> {
if (!siteProduct.sku) {
throw new Error('siteSku 不能为空')
}
let product = await this.productModel.findOne({
where: { siteSkus: Like(`%${siteProduct.sku}%`) },
relations: ['components', 'attributes', 'attributes.dict'],
});
let quantity = 1;
// 这里处理一下特殊情况,就是无法直接通过 siteProduct.sku去获取 但有一定规则转换成有的产品,就是 bundle 的部分
// 考察各个站点的 bundle 规则, 会发现
// wordpress:
// togovape YOONE Wintergreen 9MG (Moisture) - 10 cans TV-YOONE-NP-S-WG-9MG-0010
// togovape mixed 是这样的 TV-YOONE-NP-G-12MG-MX-0003 TV-ZEX-NP-Mixed-12MG-0001
//
// shopyy: shopyy 已经
// 只有 bundle 做这个处理
if (!product && !this.isMixedSku(siteProduct.sku)) {
const skuSplitArr = siteProduct.sku.split('-')
const quantityStr = skuSplitArr[skuSplitArr.length - 1]
const isBundleSku = quantityStr.startsWith('0')
if(!isBundleSku){
return undefined
}
quantity = Number(quantityStr)
if(!isBundleSku){
return undefined
}
// 更正为正确的站点 sku
const childSku = skuSplitArr.slice(0, skuSplitArr.length - 1).join('-')
// 重新获取匹配的商品
product = await this.productModel.findOne({
where: { siteSkus: Like(`%${childSku}%`) },
relations: ['components', 'attributes', 'attributes.dict'],
});
const product = await this.getProductBySiteSku(siteProduct.sku, site)
if (!product) return
if(!product?.components?.length){
return [{
product,
quantity:1
}]
}
if (!product) {
throw new Error(`产品 ${siteProduct.sku} 不存在`);
}
return await Promise.all(product.components.map(async comp => {
return {
product,
quantity,
product: await this.productModel.findOne({
where: { sku: comp.sku },
relations: ['category', 'attributes', 'attributes.dict', 'components']
}),
parentProduct: product, // 这里得记录一下他的爸爸用来记录
quantity: comp.quantity,
}
}))
}
// 准备创建产品的 DTO, 处理类型转换和默认值
@ -2093,7 +2076,7 @@ export class ProductService {
errors.push({ identifier: '' + rec.sku, error: `产品${rec?.sku}导入失败:${e?.message || String(e)}` });
}
}
this.logger.debug(`导入 ${records.length} 条记录,成功创建 ${created} 条,更新 ${updated} 条,失败 ${errors.length} 条,错误详情:${JSON.stringify(errors)}`);
return { total: records.length, processed: records.length - errors.length, created, updated, errors };
}
@ -2151,29 +2134,32 @@ export class ProductService {
component.sku = product.sku;
component.quantity = 1;
product.components = [component];
} else {
// 混装商品返回持久化的 SKU 组成
product.components = await this.productStockComponentModel.find({
where: { productId: product.id },
});
}
return product;
}
// 根据站点SKU查询产品
async findProductBySiteSku(siteSku: string): Promise<Product> {
const product = await this.productModel.findOne({
where: { siteSkus: Like(`%${siteSku}%`) },
relations: ['category', 'attributes', 'attributes.dict', 'components']
});
async getProductBySiteSku(siteSku: string, site?: Site): Promise<Product> {
// 使用查询构建器来正确查询关联表
const queryBuilder = this.productModel
.createQueryBuilder('product')
.leftJoinAndSelect('product.category', 'category')
.leftJoinAndSelect('product.attributes', 'attributes')
.leftJoinAndSelect('attributes.dict', 'dict')
.leftJoinAndSelect('product.components', 'components')
.leftJoinAndSelect('product.siteSkus', 'siteSku')
.where('siteSku.sku LIKE :siteSku', { siteSku: `%${siteSku}%` })
.orWhere('product.sku = :siteSku', { siteSku });
if (!product) {
throw new Error(`站点SKU ${siteSku} 不存在`);
if (site) {
queryBuilder.orWhere('product.sku = :processedSku', {
processedSku: siteSku.replace(new RegExp(site.skuPrefix + '-'), '')
});
}
// 获取完整的产品信息,包含所有关联数据
return this.getProductById(product.id);
const product = await queryBuilder.getOne();
return product
}
// 获取产品的站点SKU列表

View File

@ -60,7 +60,7 @@ export class SiteApiService {
try {
// 使用站点SKU查询对应的ERP产品
const erpProduct = await this.productService.findProductBySiteSku(siteProduct.sku);
const erpProduct = await this.productService.getProductBySiteSku(siteProduct.sku);
// 将ERP产品信息合并到站点商品中
return {

View File

@ -0,0 +1,102 @@
import { Inject, Provide } from '@midwayjs/core';
import { ILogger } from '@midwayjs/logger';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { SiteProduct } from '../entity/site-product.entity';
@Provide()
export class SiteProductService {
@InjectEntityModel(SiteProduct)
siteProductModel: Repository<SiteProduct>;
@Inject()
logger: ILogger;
async getSiteProductList(params: {
current?: number;
pageSize?: number;
siteId?: number;
name?: string;
sku?: string;
}) {
const {
current = 1,
pageSize = 10,
siteId,
name,
sku,
} = params;
const queryBuilder = this.siteProductModel.createQueryBuilder('siteProduct');
// 根据 siteId 筛选
if (siteId) {
queryBuilder.where('siteProduct.siteId = :siteId', { siteId });
}
// 根据 name 或 sku 模糊搜索
if (name || sku) {
queryBuilder.andWhere(
'(siteProduct.name LIKE :keyword OR siteProduct.sku LIKE :keyword)',
{ keyword: `%${name || sku}%` }
);
}
// 计算总数
const total = await queryBuilder.getCount();
// 分页查询
const items = await queryBuilder
.skip((current - 1) * pageSize)
.take(pageSize)
.orderBy('siteProduct.updatedAt', 'DESC')
.getMany();
return {
total,
items,
current,
pageSize,
};
}
async getSiteProductById(id: string) {
return await this.siteProductModel.findOne({ where: { id } });
}
async createSiteProduct(data: Partial<SiteProduct>) {
const siteProduct = this.siteProductModel.create(data);
return await this.siteProductModel.save(siteProduct);
}
async updateSiteProduct(id: string, data: Partial<SiteProduct>) {
await this.siteProductModel.update(id, data);
return await this.getSiteProductById(id);
}
async deleteSiteProduct(id: string) {
await this.siteProductModel.delete(id);
return true;
}
async batchUpdatePrice(siteId: number, productIds: string[], price: number) {
const result = await this.siteProductModel
.createQueryBuilder()
.update()
.set({ price })
.where('siteId = :siteId AND id IN (:...productIds)', { siteId, productIds })
.execute();
return result.affected || 0;
}
async syncSiteProducts(siteId: number) {
// 这里实现同步逻辑,暂时返回成功
// 实际实现时需要调用对应的站点适配器进行同步
this.logger.info(`Syncing products for site ${siteId}`);
return {
success: true,
message: '同步成功',
};
}
}