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

Compare commits

...

3 Commits

Author SHA1 Message Date
tikkhun 96a3e5c76d feat(产品服务): 重构产品查询逻辑并添加价格字段
重构 getProductBySiteSku 方法以支持更灵活的查询条件
在 site-product 实体中添加 price 字段
新增 site-product 控制器和服务用于管理站点商品
修改订单服务以支持站点参数传递
2026-01-27 10:33:13 +08:00
zhuotianyuan 8b2aea7038 feat(订单服务): 添加导出XLSX功能并优化导入逻辑
添加exportToXlsx方法支持将数据导出为XLSX格式
重构importWintopayTable方法,增加物流信息回填功能
移除未使用的BatchOperationResult导入
2026-01-26 15:41:30 +08:00
zhuotianyuan 39401aeaa0 feat(订单): 添加CSV文件导入产品功能
在订单控制器和服务中添加导入产品功能,支持通过CSV文件批量导入产品数据
文件解析使用xlsx库自动识别文件类型并处理UTF-8编码
2026-01-26 15:41:30 +08:00
9 changed files with 440 additions and 70 deletions

View File

@ -2,6 +2,7 @@ import {
Body, Body,
Controller, Controller,
Del, Del,
Files,
Get, Get,
Inject, Inject,
Param, Param,
@ -27,7 +28,6 @@ import {
} from '../dto/order.dto'; } from '../dto/order.dto';
import { User } from '../decorator/user.decorator'; import { User } from '../decorator/user.decorator';
import { ErpOrderStatus } from '../enums/base.enum'; import { ErpOrderStatus } from '../enums/base.enum';
@Controller('/order') @Controller('/order')
export class OrderController { export class OrderController {
@Inject() @Inject()
@ -264,4 +264,21 @@ export class OrderController {
return errorResponse(error?.message || '导出失败'); return errorResponse(error?.message || '导出失败');
} }
} }
// 导入产品(CSV 文件)
@ApiOkResponse()
@Post('/import')
async importWintopay(@Files() files: any) {
try {
// 条件判断:确保存在文件
const file = files?.[0];
if (!file) return errorResponse('未接收到上传文件');
const result = await this.orderService.importWintopayTable(file);
return successResponse(result);
} catch (error) {
return errorResponse(error?.message || error);
}
}
} }

View File

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

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

View File

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

View File

@ -1,5 +1,6 @@
import { Inject, Logger, Provide } from '@midwayjs/core'; import { Inject, Logger, Provide } from '@midwayjs/core';
import { WPService } from './wp.service'; import { WPService } from './wp.service';
import * as xlsx from 'xlsx';
import { Order } from '../entity/order.entity'; import { Order } from '../entity/order.entity';
import { In, Like, Repository } from 'typeorm'; import { In, Like, Repository } from 'typeorm';
import { InjectEntityModel, TypeORMDataSourceManager } from '@midwayjs/typeorm'; import { InjectEntityModel, TypeORMDataSourceManager } from '@midwayjs/typeorm';
@ -32,7 +33,7 @@ import { UpdateStockDTO } from '../dto/stock.dto';
import { StockService } from './stock.service'; import { StockService } from './stock.service';
import { OrderItemOriginal } from '../entity/order_item_original.entity'; import { OrderItemOriginal } from '../entity/order_item_original.entity';
import { SiteApiService } from './site-api.service'; import { SiteApiService } from './site-api.service';
import { SyncOperationResult } from '../dto/api.dto'; import { BatchErrorItem, SyncOperationResult } from '../dto/api.dto';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
@ -40,6 +41,7 @@ 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'; import { ProductService } from './product.service';
import { Site } from '../entity/site.entity';
@Provide() @Provide()
export class OrderService { export class OrderService {
@ -627,7 +629,8 @@ export class OrderService {
// 保存订单项 // 保存订单项
await this.saveOrderItem(entity); await this.saveOrderItem(entity);
// 为每个订单项创建对应的销售项(OrderSale) // 为每个订单项创建对应的销售项(OrderSale)
await this.saveOrderSale(entity); const site = await this.siteService.get(siteId);
await this.saveOrderSale(entity,site);
} }
} }
@ -717,7 +720,7 @@ export class OrderService {
*/ */
// TODO 这里存的是库存商品实际 // TODO 这里存的是库存商品实际
// 所以叫做 orderInventoryItems 可能更合适 // 所以叫做 orderInventoryItems 可能更合适
async saveOrderSale(orderItem: OrderItem) { 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,
@ -730,7 +733,7 @@ export class OrderService {
if (!orderItem.sku) return; 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; if (!productDetail || !productDetail.quantity) return;
const { product, quantity } = productDetail const { product, quantity } = productDetail
@ -2654,6 +2657,82 @@ export class OrderService {
} }
} }
/**
* XLSX格式
* @param {any[]} data
* @param {Object} options
* @param {string} [options.type='buffer'] :'buffer' | 'string' (XLSX默认返回buffer)
* @param {string} [options.fileName] (使)
* @param {boolean} [options.writeFile=false]
* @returns {string|Buffer} type返回字符串或Buffer
*/
async exportToXlsx(data: any[], options: { type?: 'buffer' | 'string'; fileName?: string; writeFile?: boolean } = {}): Promise<string | Buffer> {
try {
// 检查数据是否为空
if (!data || data.length === 0) {
throw new Error('导出数据不能为空');
}
const { type = 'buffer', fileName, writeFile = false } = options;
// 获取表头
const headers = Object.keys(data[0]);
// 构建二维数组数据(包含表头)
const aoaData = [headers];
data.forEach(item => {
const row = headers.map(key => {
const value = item[key as keyof any];
// 处理undefined和null
if (value === undefined || value === null) {
return '';
}
// 处理日期类型
if (value instanceof Date) {
return value.toISOString();
}
return value;
});
aoaData.push(row);
});
// 创建工作簿和工作表
const workbook = xlsx.utils.book_new();
const worksheet = xlsx.utils.aoa_to_sheet(aoaData);
xlsx.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
// 生成XLSX buffer
const buffer = xlsx.write(workbook, { bookType: 'xlsx', type: 'buffer' });
// 如果需要写入文件
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, buffer);
return filePath;
}
// 根据类型返回不同结果
if (type === 'string') {
return buffer.toString('base64');
}
return buffer;
} catch (error) {
throw new Error(`导出XLSX文件失败: ${error.message}`);
}
}
/** /**
* *
* @param str * @param str
@ -2729,4 +2808,108 @@ export class OrderService {
return result; return result;
} }
// 从 CSV 导入产品;存在则更新,不存在则创建
/**
* Wintopay
* @param file
* @returns
*/
async importWintopayTable(file: any): Promise<any> {
let updated = 0;
const errors: BatchErrorItem[] = [];
// 解析文件获取工作表
let buffer: Buffer;
if (Buffer.isBuffer(file)) {
buffer = file;
} else if (file?.data) {
if (typeof file.data === 'string') {
buffer = fs.readFileSync(file.data);
} else {
buffer = file.data;
}
} else {
throw new Error('无效的文件输入');
}
const workbook = xlsx.read(buffer, { type: 'buffer', codepage: 65001 });
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 获取表头和数据
const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 });
const headers = jsonData[0] as string[];
const dataRows = jsonData.slice(1) as any[][];
// 查找各列的索引
const columnIndices = {
orderNumber: headers.indexOf('订单号'),
logisticsCompany: headers.indexOf('物流公司'),
trackingNumber: headers.indexOf('单号-单元格文本格式'),
orderCreateTime: headers.indexOf('订单创建时间'),
orderEmail: headers.indexOf('订单邮箱'),
orderSite: headers.indexOf('订单网站'),
name: headers.indexOf('姓名'),
refund: headers.indexOf('退款'),
chargeback: headers.indexOf('拒付')
};
// 遍历数据行
for (let i = 0; i < dataRows.length; i++) {
const row = dataRows[i];
const orderNumber = row[columnIndices.orderNumber];
if (!orderNumber) {
errors.push({ identifier: `${i + 2}`, error: '订单号为空' });
continue;
}
try {
let orderNumbers="";
if (orderNumber.includes('_')&&orderNumber.includes('-')) {
orderNumbers = orderNumber.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]; // 假设每个订单只有一个物流信息
// 回填物流信息
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;
}
} }

View File

@ -34,6 +34,7 @@ import { paginate } from '../utils/paginate.util';
import { SiteApiService } from './site-api.service'; import { SiteApiService } from './site-api.service';
import { StockService } from './stock.service'; import { StockService } from './stock.service';
import { TemplateService } from './template.service'; import { TemplateService } from './template.service';
import { Site } from '../entity/site.entity';
@Provide() @Provide()
export class ProductService { export class ProductService {
@ -1777,57 +1778,23 @@ export class ProductService {
attributes: attributes.length > 0 ? attributes : undefined, attributes: attributes.length > 0 ? attributes : undefined,
} }
} }
isMixedSku(sku: string){ isMixedSku(sku: string) {
const splitSKu = sku.split('-') const splitSKu = sku.split('-')
const last = splitSKu[splitSKu.length - 1] const last = splitSKu[splitSKu.length - 1]
const second = splitSKu[splitSKu.length - 2] const second = splitSKu[splitSKu.length - 2]
// 这里判断 second 是否是数字 // 这里判断 second 是否是数字
return sku.includes('-MX-') || sku.includes('-Mixed-') || /^\d+$/.test(second) && /^\d+$/.test(last) 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) { if (!siteProduct.sku) {
throw new Error('siteSku 不能为空') throw new Error('siteSku 不能为空')
} }
let product = await this.productModel.findOne({ let product = await this.getProductBySiteSku(siteProduct.sku, site)
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'],
});
}
if (!product) {
throw new Error(`产品 ${siteProduct.sku} 不存在`);
}
return { return {
product, product,
quantity, quantity: 1,
} }
} }
@ -2162,18 +2129,26 @@ export class ProductService {
} }
// 根据站点SKU查询产品 // 根据站点SKU查询产品
async findProductBySiteSku(siteSku: string): Promise<Product> { async getProductBySiteSku(siteSku: string, site?: Site): Promise<Product> {
const product = await this.productModel.findOne({ // 使用查询构建器来正确查询关联表
where: { siteSkus: Like(`%${siteSku}%`) }, const queryBuilder = this.productModel
relations: ['category', 'attributes', 'attributes.dict', 'components'] .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) { if (site) {
throw new Error(`站点SKU ${siteSku} 不存在`); queryBuilder.orWhere('product.sku = :processedSku', {
processedSku: siteSku.replace(new RegExp(site.skuPrefix + '-'), '')
});
} }
// 获取完整的产品信息,包含所有关联数据 const product = await queryBuilder.getOne();
return this.getProductById(product.id); return product
} }
// 获取产品的站点SKU列表 // 获取产品的站点SKU列表
@ -2182,7 +2157,7 @@ export class ProductService {
if (!product) { if (!product) {
throw new Error(`产品 ID ${productId} 不存在`); throw new Error(`产品 ID ${productId} 不存在`);
} }
return product.siteSkus.map(({sku})=>sku) || []; return product.siteSkus.map(({ sku }) => sku) || [];
} }
// 绑定产品的站点SKU列表 // 绑定产品的站点SKU列表

View File

@ -60,7 +60,7 @@ export class SiteApiService {
try { try {
// 使用站点SKU查询对应的ERP产品 // 使用站点SKU查询对应的ERP产品
const erpProduct = await this.productService.findProductBySiteSku(siteProduct.sku); const erpProduct = await this.productService.getProductBySiteSku(siteProduct.sku);
// 将ERP产品信息合并到站点商品中 // 将ERP产品信息合并到站点商品中
return { 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: '同步成功',
};
}
}