From 96a3e5c76d590cd2417d517874ac8abcc9dea1bc Mon Sep 17 00:00:00 2001 From: tikkhun Date: Tue, 27 Jan 2026 10:29:50 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(=E4=BA=A7=E5=93=81=E6=9C=8D=E5=8A=A1):?= =?UTF-8?q?=20=E9=87=8D=E6=9E=84=E4=BA=A7=E5=93=81=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E5=B9=B6=E6=B7=BB=E5=8A=A0=E4=BB=B7=E6=A0=BC?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 重构 getProductBySiteSku 方法以支持更灵活的查询条件 在 site-product 实体中添加 price 字段 新增 site-product 控制器和服务用于管理站点商品 修改订单服务以支持站点参数传递 --- src/controller/product.controller.ts | 2 +- src/controller/site-product.controller.ts | 90 +++++++++++++++++++ src/entity/product.entity.ts | 1 - src/entity/site-product.entity.ts | 4 + src/service/order.service.ts | 8 +- src/service/product.service.ts | 95 ++++++++------------ src/service/site-api.service.ts | 2 +- src/service/site-product.service.ts | 102 ++++++++++++++++++++++ 8 files changed, 238 insertions(+), 66 deletions(-) create mode 100644 src/controller/site-product.controller.ts diff --git a/src/controller/product.controller.ts b/src/controller/product.controller.ts index b67f02f..aebb74d 100644 --- a/src/controller/product.controller.ts +++ b/src/controller/product.controller.ts @@ -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 || '获取数据失败'); diff --git a/src/controller/site-product.controller.ts b/src/controller/site-product.controller.ts new file mode 100644 index 0000000..c8af65e --- /dev/null +++ b/src/controller/site-product.controller.ts @@ -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); + } + } +} diff --git a/src/entity/product.entity.ts b/src/entity/product.entity.ts index 1a1bf22..9e1a7a0 100644 --- a/src/entity/product.entity.ts +++ b/src/entity/product.entity.ts @@ -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 }) diff --git a/src/entity/site-product.entity.ts b/src/entity/site-product.entity.ts index 7b338b9..d5ed4fd 100644 --- a/src/entity/site-product.entity.ts +++ b/src/entity/site-product.entity.ts @@ -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: '更新时间', diff --git a/src/service/order.service.ts b/src/service/order.service.ts index 1e872f3..c764bb4 100644 --- a/src/service/order.service.ts +++ b/src/service/order.service.ts @@ -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,7 +733,7 @@ export class OrderService { if (!orderItem.sku) return; // 从数据库查询产品,关联查询组件 - const productDetail = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name }); + const productDetail = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name },site); if (!productDetail || !productDetail.quantity) return; const { product, quantity } = productDetail diff --git a/src/service/product.service.ts b/src/service/product.service.ts index 4198309..cea866c 100644 --- a/src/service/product.service.ts +++ b/src/service/product.service.ts @@ -34,6 +34,7 @@ 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 { @@ -477,7 +478,7 @@ export class ProductService { .leftJoinAndSelect('attribute.dict', 'dict') .leftJoinAndSelect('product.category', 'category') .leftJoinAndSelect('product.siteSkus', 'siteSkus'); - + // 验证分组字段 const groupBy = query.groupBy; if (!groupBy) { @@ -705,10 +706,10 @@ export class ProductService { // 按指定字段分组 const groupedResult: Record = {}; - + // 检查是否按属性的字典名称分组 const isAttributeGrouping = await this.dictModel.findOne({ where: { name: groupBy } }); - + if (isAttributeGrouping) { // 使用原生SQL查询获取每个产品对应的分组属性值 const attributeGroupQuery = ` @@ -719,26 +720,26 @@ export class ProductService { INNER JOIN dict ON dict_item.dict_id = dict.id WHERE dict.name = ? `; - + const attributeGroupResults = await this.productModel.query(attributeGroupQuery, [groupBy]); - + // 创建产品ID到分组值的映射 const productGroupMap: Record = {}; attributeGroupResults.forEach((result: any) => { productGroupMap[result.productId] = result.attributeName; }); - + items.forEach(product => { // 获取分组值 const groupValue = productGroupMap[product.id] || 'unknown'; // 转换为字符串作为键 const groupKey = String(groupValue); - + // 初始化分组 if (!groupedResult[groupKey]) { groupedResult[groupKey] = []; } - + // 添加产品到分组 groupedResult[groupKey].push(product); }); @@ -749,12 +750,12 @@ export class ProductService { const groupValue = product[groupBy as keyof Product]; // 转换为字符串作为键 const groupKey = String(groupValue); - + // 初始化分组 if (!groupedResult[groupKey]) { groupedResult[groupKey] = []; } - + // 添加产品到分组 groupedResult[groupKey].push(product); }); @@ -1777,57 +1778,23 @@ export class ProductService { attributes: attributes.length > 0 ? attributes : undefined, } } - isMixedSku(sku: string){ + 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) { 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'], - }); - } + let product = await this.getProductBySiteSku(siteProduct.sku, site) - if (!product) { - throw new Error(`产品 ${siteProduct.sku} 不存在`); - } return { product, - quantity, + quantity: 1, } } @@ -2162,18 +2129,26 @@ export class ProductService { } // 根据站点SKU查询产品 - async findProductBySiteSku(siteSku: string): Promise { - const product = await this.productModel.findOne({ - where: { siteSkus: Like(`%${siteSku}%`) }, - relations: ['category', 'attributes', 'attributes.dict', 'components'] - }); + async getProductBySiteSku(siteSku: string, site?: Site): Promise { + // 使用查询构建器来正确查询关联表 + 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列表 @@ -2182,7 +2157,7 @@ export class ProductService { if (!product) { throw new Error(`产品 ID ${productId} 不存在`); } - return product.siteSkus.map(({sku})=>sku) || []; + return product.siteSkus.map(({ sku }) => sku) || []; } // 绑定产品的站点SKU列表 @@ -2194,7 +2169,7 @@ export class ProductService { const normalizedSiteSkus = (siteSkus || []) .map(c => String(c).trim()) .filter(c => c.length > 0); - + // 更新产品的站点SKU列表 product.siteSkus = normalizedSiteSkus.map(sku => { const siteSku = new SiteSku(); @@ -2202,7 +2177,7 @@ export class ProductService { siteSku.isOld = false; return siteSku; }); - + await this.productModel.save(product); return normalizedSiteSkus; } diff --git a/src/service/site-api.service.ts b/src/service/site-api.service.ts index 3af2439..8815d9e 100644 --- a/src/service/site-api.service.ts +++ b/src/service/site-api.service.ts @@ -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 { diff --git a/src/service/site-product.service.ts b/src/service/site-product.service.ts index e69de29..9a8d09c 100644 --- a/src/service/site-product.service.ts +++ b/src/service/site-product.service.ts @@ -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; + + @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) { + const siteProduct = this.siteProductModel.create(data); + return await this.siteProductModel.save(siteProduct); + } + + async updateSiteProduct(id: string, data: Partial) { + 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: '同步成功', + }; + } +} From d3d493f85820c56648954315641deb413787cb0f Mon Sep 17 00:00:00 2001 From: tikkhun Date: Tue, 27 Jan 2026 18:42:00 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E4=B8=AD=E4=BA=A7=E5=93=81=E8=AF=A6=E6=83=85?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加对productDetail.product的检查,避免在product为undefined时访问components属性 --- src/service/order.service.ts | 3 ++- src/service/product.service.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/service/order.service.ts b/src/service/order.service.ts index c764bb4..7553dfc 100644 --- a/src/service/order.service.ts +++ b/src/service/order.service.ts @@ -735,8 +735,9 @@ export class OrderService { // 从数据库查询产品,关联查询组件 const productDetail = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name },site); - if (!productDetail || !productDetail.quantity) return; + if (!productDetail || !productDetail.product || !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({ diff --git a/src/service/product.service.ts b/src/service/product.service.ts index cea866c..fef1c8f 100644 --- a/src/service/product.service.ts +++ b/src/service/product.service.ts @@ -1791,7 +1791,7 @@ export class ProductService { } let product = await this.getProductBySiteSku(siteProduct.sku, site) - + return { product, quantity: 1, From b879202d131ccf7ec6903bf774a8a58650b4a263 Mon Sep 17 00:00:00 2001 From: tikkhun Date: Tue, 27 Jan 2026 18:53:54 +0800 Subject: [PATCH 3/3] =?UTF-8?q?refactor(product):=20=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E7=BB=84=E4=BB=B6=E8=AF=A6=E6=83=85=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E5=B9=B6=E6=94=AF=E6=8C=81=E6=95=B0=E9=87=8F=E5=8F=82?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将获取组件详情的逻辑从order.service.ts移到product.service.ts中统一处理 新增quantity参数支持组件数量计算 返回结果中增加parentProduct信息用于追踪父产品 --- src/service/order.service.ts | 33 ++++++++++++--------------------- src/service/product.service.ts | 26 ++++++++++++++++++++------ 2 files changed, 32 insertions(+), 27 deletions(-) diff --git a/src/service/order.service.ts b/src/service/order.service.ts index 7553dfc..1a2d8a3 100644 --- a/src/service/order.service.ts +++ b/src/service/order.service.ts @@ -733,33 +733,24 @@ export class OrderService { if (!orderItem.sku) return; // 从数据库查询产品,关联查询组件 - const productDetail = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name },site); + const componentDetails = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name },orderItem.quantity,site); + if(!componentDetails?.length){ + return + } - if (!productDetail || !productDetail.product || !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, - } - })) : [{ 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 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, @@ -767,7 +758,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) diff --git a/src/service/product.service.ts b/src/service/product.service.ts index fef1c8f..362b6ca 100644 --- a/src/service/product.service.ts +++ b/src/service/product.service.ts @@ -1785,17 +1785,31 @@ export class ProductService { // 这里判断 second 是否是数字 return sku.includes('-MX-') || sku.includes('-Mixed-') || /^\d+$/.test(second) && /^\d+$/.test(last) } - async getComponentDetailFromSiteSku(siteProduct: { sku: string, name: string }, site: Site) { + async getComponentDetailFromSiteSku(siteProduct: { sku: string, name: string }, quantity: number = 1, site: Site): Promise<{ product: Product,parentProduct?: Product, quantity: number }[]> { if (!siteProduct.sku) { throw new Error('siteSku 不能为空') } - let product = await this.getProductBySiteSku(siteProduct.sku, site) - - return { - product, - quantity: 1, + const product = await this.getProductBySiteSku(siteProduct.sku, site) + + if (!product) return + + if(!product?.components?.length){ + return [{ + product, + quantity + }] } + + return await Promise.all(product.components.map(async comp => { + return { + product: await this.productModel.findOne({ + where: { id: comp.productId }, + }), + parentProduct: product, // 这里得记录一下他的爸爸用来记录 + quantity: comp.quantity * quantity, + } + })) } // 准备创建产品的 DTO, 处理类型转换和默认值