forked from yoone/API
Compare commits
17 Commits
3c5261f5b1
...
4bde698625
| Author | SHA1 | Date |
|---|---|---|
|
|
4bde698625 | |
|
|
5488e1b7c6 | |
|
|
5fa5ed21b0 | |
|
|
fe30fabf08 | |
|
|
12ebad6570 | |
|
|
0dac006116 | |
|
|
2cc434bb19 | |
|
|
6b782a9d6e | |
|
|
e94805c640 | |
|
|
d4b267106e | |
|
|
0b211628f3 | |
|
|
f37de5ac32 | |
|
|
4481cce886 | |
|
|
eeea2c5663 | |
|
|
083337a301 | |
|
|
cee8d7e029 | |
|
|
0d2411c511 |
|
|
@ -996,7 +996,6 @@ 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}的产品`);
|
||||||
|
|
@ -1126,7 +1125,6 @@ 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 || '',
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,7 @@ 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
|
||||||
|
|
@ -88,6 +89,7 @@ export default {
|
||||||
Area,
|
Area,
|
||||||
CategoryAttribute,
|
CategoryAttribute,
|
||||||
Category,
|
Category,
|
||||||
|
logisticsAlias,
|
||||||
],
|
],
|
||||||
synchronize: true,
|
synchronize: true,
|
||||||
logging: false,
|
logging: false,
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,6 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -54,7 +53,6 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -68,7 +66,6 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -81,7 +78,6 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -95,7 +91,6 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -111,7 +106,6 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -42,8 +42,7 @@ 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) {
|
||||||
console.log(error);
|
return errorResponse(`同步失败,${error?.message || '未知错误'}`);
|
||||||
return errorResponse('同步失败');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -59,7 +58,6 @@ 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('同步失败');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 || '获取数据失败');
|
||||||
|
|
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -23,6 +23,10 @@ export class ShipmentBookDTO {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
@Rule(RuleType.string())
|
@Rule(RuleType.string())
|
||||||
shipmentPlatform: string;
|
shipmentPlatform: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@Rule(RuleType.any())
|
||||||
|
courierCompany: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ShipmentFeeBookDTO {
|
export class ShipmentFeeBookDTO {
|
||||||
|
|
@ -30,6 +34,8 @@ export class ShipmentFeeBookDTO {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
shipmentPlatform: string;
|
shipmentPlatform: string;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
|
courierCompany: string;
|
||||||
|
@ApiProperty()
|
||||||
stockPointId: number;
|
stockPointId: number;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
sender: string;
|
sender: string;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,34 @@
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -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 })
|
||||||
|
|
|
||||||
|
|
@ -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: '更新时间',
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ 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'})
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,96 @@
|
||||||
|
import { Inject, Provide } from '@midwayjs/core';
|
||||||
|
import axios from 'axios';
|
||||||
|
import dayjs = require('dayjs');
|
||||||
|
import utc = require('dayjs/plugin/utc');
|
||||||
|
import timezone = require('dayjs/plugin/timezone');
|
||||||
|
|
||||||
|
// 扩展dayjs功能
|
||||||
|
dayjs.extend(utc);
|
||||||
|
dayjs.extend(timezone);
|
||||||
|
|
||||||
|
|
||||||
|
// Wintopay 物流更新请求接口
|
||||||
|
interface LogisticsUpdateRequest {
|
||||||
|
trade_id: string; // 订单的流水号
|
||||||
|
track_number: string; // 物流单号
|
||||||
|
track_brand: string; // 物流公司编号
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wintopay 物流更新响应接口
|
||||||
|
interface LogisticsUpdateResponse {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
data: {
|
||||||
|
trade_id: string;
|
||||||
|
track_brand: string;
|
||||||
|
track_number: string;
|
||||||
|
time: number;
|
||||||
|
};
|
||||||
|
error: any;
|
||||||
|
request_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provide()
|
||||||
|
export class WintopayService {
|
||||||
|
@Inject() logger;
|
||||||
|
|
||||||
|
// 默认配置
|
||||||
|
private config = {
|
||||||
|
//测试环境配置,在生产环境记得换掉
|
||||||
|
apiBaseUrl: 'https://stage-merchant-api.wintopay.com',
|
||||||
|
Authorization: 'Bearer kV8w1er8dFw9p9g2kb0mer398hD8hfWk',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 发送请求
|
||||||
|
private async sendRequest<T>(url: string, data: any): Promise<T> {
|
||||||
|
try {
|
||||||
|
const headers = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': this.config.Authorization,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 发送请求 - 临时禁用SSL证书验证以解决UNABLE_TO_VERIFY_LEAF_SIGNATURE错误
|
||||||
|
const response = await axios.post<T>(
|
||||||
|
`${this.config.apiBaseUrl}${url}`,
|
||||||
|
data,
|
||||||
|
{
|
||||||
|
headers,
|
||||||
|
httpsAgent: new (require('https').Agent)({
|
||||||
|
rejectUnauthorized: false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('Wintopay API请求失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新订单物流信息
|
||||||
|
* @param params 物流更新参数
|
||||||
|
* @returns 物流更新响应
|
||||||
|
*/
|
||||||
|
async logisticsUpdate(params: LogisticsUpdateRequest): Promise<LogisticsUpdateResponse> {
|
||||||
|
try {
|
||||||
|
this.logger.info('开始更新物流信息:', params);
|
||||||
|
|
||||||
|
const response = await this.sendRequest<LogisticsUpdateResponse>('/v1/logistics/update', params);
|
||||||
|
|
||||||
|
this.logger.info('物流更新成功:', response);
|
||||||
|
return response;
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error('物流更新失败:', error);
|
||||||
|
|
||||||
|
// 处理API返回的错误
|
||||||
|
if (error.response?.data) {
|
||||||
|
throw new Error(`物流更新失败: ${error.response.data.message || '未知错误'}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`物流更新请求失败: ${error.message || '网络错误'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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}%`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -247,6 +247,9 @@ export class FreightwavesService {
|
||||||
};
|
};
|
||||||
|
|
||||||
const response = await this.sendRequest<RateTryResponseData>('/shipService/order/rateTry', requestData);
|
const response = await this.sendRequest<RateTryResponseData>('/shipService/order/rateTry', requestData);
|
||||||
|
if (response.code !== '00000200') {
|
||||||
|
throw new Error(response.msg);
|
||||||
|
}
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -262,7 +265,10 @@ export class FreightwavesService {
|
||||||
};
|
};
|
||||||
|
|
||||||
const response = await this.sendRequest<CreateOrderResponseData>('/shipService/order/createOrder', requestData);
|
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);
|
const response = await this.sendRequest<ModifyOrderResponseData>('/shipService/order/modifyOrder', requestData);
|
||||||
|
if (response.code !== '00000200') {
|
||||||
|
throw new Error(response.msg);
|
||||||
|
}
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -309,6 +318,9 @@ export class FreightwavesService {
|
||||||
partner: this.config.partner,
|
partner: this.config.partner,
|
||||||
};
|
};
|
||||||
const response = await this.sendRequest<RefundOrderResponseData>('/shipService/order/refundOrder', requestData);
|
const response = await this.sendRequest<RefundOrderResponseData>('/shipService/order/refundOrder', requestData);
|
||||||
|
if (response.code !== '00000200') {
|
||||||
|
throw new Error(response.msg);
|
||||||
|
}
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -327,17 +327,20 @@ export class LogisticsService {
|
||||||
let resShipmentFee: any;
|
let resShipmentFee: any;
|
||||||
if (data.shipmentPlatform === 'uniuni') {
|
if (data.shipmentPlatform === 'uniuni') {
|
||||||
resShipmentFee = await this.uniExpressService.getRates(reqBody);
|
resShipmentFee = await this.uniExpressService.getRates(reqBody);
|
||||||
} else if (data.shipmentPlatform === 'freightwaves') {
|
|
||||||
const fre_reqBody = await this.convertToFreightwavesRateTry(data);
|
|
||||||
resShipmentFee = await this.freightwavesService.rateTry(fre_reqBody);
|
|
||||||
} else {
|
|
||||||
throw new Error('不支持的运单平台');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resShipmentFee.status !== 'SUCCESS') {
|
if (resShipmentFee.status !== 'SUCCESS') {
|
||||||
throw new Error(resShipmentFee.ret_msg);
|
throw new Error(resShipmentFee.ret_msg);
|
||||||
}
|
}
|
||||||
return resShipmentFee.data.totalAfterTax * 100;
|
return resShipmentFee.data.totalAfterTax * 100;
|
||||||
|
} else if (data.shipmentPlatform === 'freightwaves') {
|
||||||
|
const fre_reqBody = await this.convertToFreightwavesRateTry(data);
|
||||||
|
resShipmentFee = await this.freightwavesService.rateTry(fre_reqBody);
|
||||||
|
return resShipmentFee.totalAmount * 100;
|
||||||
|
} else {
|
||||||
|
throw new Error('不支持的运单平台');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
@ -360,12 +363,7 @@ export class LogisticsService {
|
||||||
try {
|
try {
|
||||||
resShipmentOrder = await this.mepShipment(data, order);
|
resShipmentOrder = await this.mepShipment(data, order);
|
||||||
|
|
||||||
// 记录物流信息,并将订单状态转到完成,uniuni状态为SUCCESS,tms.freightwaves状态为00000200
|
|
||||||
if (resShipmentOrder.status === 'SUCCESS' || resShipmentOrder.code === '00000200') {
|
|
||||||
order.orderStatus = ErpOrderStatus.COMPLETED;
|
order.orderStatus = ErpOrderStatus.COMPLETED;
|
||||||
} else {
|
|
||||||
throw new Error('运单生成失败');
|
|
||||||
}
|
|
||||||
const dataSource = this.dataSourceManager.getDataSource('default');
|
const dataSource = this.dataSourceManager.getDataSource('default');
|
||||||
let transactionError = undefined;
|
let transactionError = undefined;
|
||||||
let shipmentId = undefined;
|
let shipmentId = undefined;
|
||||||
|
|
@ -384,8 +382,8 @@ export class LogisticsService {
|
||||||
unique_id = resShipmentOrder.data.uni_order_sn;
|
unique_id = resShipmentOrder.data.uni_order_sn;
|
||||||
state = resShipmentOrder.data.uni_status_code;
|
state = resShipmentOrder.data.uni_status_code;
|
||||||
} else {
|
} else {
|
||||||
co = resShipmentOrder.data?.shipOrderId;
|
co = resShipmentOrder.shipOrderId;
|
||||||
unique_id = resShipmentOrder.data?.shipOrderId;
|
unique_id = resShipmentOrder.shipOrderId;
|
||||||
state = ErpOrderStatus.COMPLETED;
|
state = ErpOrderStatus.COMPLETED;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -464,7 +462,7 @@ export class LogisticsService {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (resShipmentOrder.status === 'SUCCESS') {
|
if (resShipmentOrder?.status === 'SUCCESS') {
|
||||||
await this.uniExpressService.deleteShipment(resShipmentOrder.data.tno);
|
await this.uniExpressService.deleteShipment(resShipmentOrder.data.tno);
|
||||||
}
|
}
|
||||||
throw new Error(`上游请求错误:${error}`);
|
throw new Error(`上游请求错误:${error}`);
|
||||||
|
|
@ -728,12 +726,19 @@ export class LogisticsService {
|
||||||
};
|
};
|
||||||
// 添加运单
|
// 添加运单
|
||||||
resShipmentOrder = await this.uniExpressService.createShipment(reqBody);
|
resShipmentOrder = await this.uniExpressService.createShipment(reqBody);
|
||||||
|
|
||||||
|
// 记录物流信息,并将订单状态转到完成,uniuni状态为SUCCESS,tms.freightwaves状态为00000200
|
||||||
|
if (resShipmentOrder.status !== 'SUCCESS') {
|
||||||
|
throw new Error('运单生成失败');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.shipmentPlatform === 'freightwaves') {
|
if (data.shipmentPlatform === 'freightwaves') {
|
||||||
|
|
||||||
// 根据TMS系统对接说明文档格式化参数
|
// 根据TMS系统对接说明文档格式化参数
|
||||||
const reqBody: any = {
|
const reqBody: any = {
|
||||||
shipCompany: 'UPSYYZ7000NEW',
|
// shipCompany: 'UPSYYZ7000NEW',
|
||||||
|
shipCompany: data.courierCompany,
|
||||||
partnerOrderNumber: order.siteId + '-' + order.externalOrderId,
|
partnerOrderNumber: order.siteId + '-' + order.externalOrderId,
|
||||||
warehouseId: '25072621030107400060',
|
warehouseId: '25072621030107400060',
|
||||||
shipper: {
|
shipper: {
|
||||||
|
|
@ -798,15 +803,20 @@ export class LogisticsService {
|
||||||
};
|
};
|
||||||
|
|
||||||
resShipmentOrder = await this.freightwavesService.createOrder(reqBody); // 创建订单
|
resShipmentOrder = await this.freightwavesService.createOrder(reqBody); // 创建订单
|
||||||
|
|
||||||
//tms只返回了物流订单号,需要查询一次来获取完整的物流信息
|
//tms只返回了物流订单号,需要查询一次来获取完整的物流信息
|
||||||
const queryRes = await this.freightwavesService.queryOrder({ shipOrderId: resShipmentOrder.shipOrderId }); // 查询订单
|
const queryRes = await this.freightwavesService.queryOrder({ shipOrderId: resShipmentOrder.shipOrderId }); // 查询订单
|
||||||
resShipmentOrder.push(queryRes);
|
return {
|
||||||
|
...resShipmentOrder,
|
||||||
|
...queryRes
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return resShipmentOrder;
|
return resShipmentOrder;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('物流订单处理失败:', error); // 使用console.log代替this.log
|
// 处理错误,例如记录日志或抛出异常
|
||||||
throw error;
|
throw new Error(`物流订单处理失败: ${error}`);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -826,7 +836,8 @@ export class LogisticsService {
|
||||||
const address = shipments?.address;
|
const address = shipments?.address;
|
||||||
// 转换为RateTryRequest格式
|
// 转换为RateTryRequest格式
|
||||||
const r = {
|
const r = {
|
||||||
shipCompany: 'UPSYYZ7000NEW', // 必填,但ShipmentFeeBookDTO中缺少
|
//shipCompany: 'UPSYYZ7000NEW', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
shipCompany: data.courierCompany,
|
||||||
partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成
|
partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成
|
||||||
warehouseId: '25072621030107400060', // 可选,使用stockPointId转换
|
warehouseId: '25072621030107400060', // 可选,使用stockPointId转换
|
||||||
shipper: {
|
shipper: {
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,8 @@ 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';
|
||||||
|
import { logisticsAlias } from '../entity/logistics_alias.emtity';
|
||||||
@Provide()
|
@Provide()
|
||||||
export class OrderService {
|
export class OrderService {
|
||||||
|
|
||||||
|
|
@ -53,6 +55,9 @@ 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>;
|
||||||
|
|
||||||
|
|
@ -132,7 +137,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,
|
||||||
|
|
@ -142,7 +147,6 @@ 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 {
|
||||||
|
|
@ -478,6 +482,20 @@ 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 状态
|
||||||
|
|
@ -494,20 +512,7 @@ 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 },
|
||||||
// });
|
// });
|
||||||
|
|
@ -628,7 +633,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -718,7 +724,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,
|
||||||
|
|
@ -731,32 +737,24 @@ export class OrderService {
|
||||||
if (!orderItem.sku) return;
|
if (!orderItem.sku) return;
|
||||||
|
|
||||||
// 从数据库查询产品,关联查询组件
|
// 从数据库查询产品,关联查询组件
|
||||||
const productDetail = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name });
|
const componentDetails = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name }, orderItem.quantity, site);
|
||||||
|
if (!componentDetails?.length) {
|
||||||
if (!productDetail || !productDetail.quantity) return;
|
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 => {
|
const orderSales: OrderSale[] = componentDetails.map(({ product, parentProduct, quantity }) => {
|
||||||
if (!componentDetail.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: product.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
|
parentProductId: parentProduct?.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
|
||||||
productId: componentDetail.product.id,
|
productId: product.id,
|
||||||
isPackage: product.type === 'bundle',// 这里是否是套餐取决于父产品
|
isPackage: product.type === 'bundle',// 这里是否是套餐取决于父产品
|
||||||
name: componentDetail.product.name,
|
name: product.name,
|
||||||
quantity: componentDetail.quantity * orderItem.quantity,
|
quantity: quantity * orderItem.quantity,
|
||||||
sku: componentDetail.product.sku,
|
sku: product.sku,
|
||||||
// 理论上直接存 product 的全部数据才是对的,因为这样我的数据才全面。
|
// 理论上直接存 product 的全部数据才是对的,因为这样我的数据才全面。
|
||||||
brand: attrsObj?.['brand']?.name,
|
brand: attrsObj?.['brand']?.name,
|
||||||
version: attrsObj?.['version']?.name,
|
version: attrsObj?.['version']?.name,
|
||||||
|
|
@ -764,7 +762,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: componentDetail.product.category.name,
|
category: product.category?.name,
|
||||||
});
|
});
|
||||||
return orderSale
|
return orderSale
|
||||||
}).filter(v => v !== null)
|
}).filter(v => v !== null)
|
||||||
|
|
@ -2460,18 +2458,18 @@ export class OrderService {
|
||||||
*/
|
*/
|
||||||
// TODO
|
// TODO
|
||||||
async exportOrder(ids: number[]) {
|
async exportOrder(ids: number[]) {
|
||||||
// 日期 订单号 姓名地址 邮箱 号码 订单内容 盒数 换盒数 换货内容 快递号
|
// 日期 订单号 姓名地址 邮箱 号码 盒数 换盒数 换货内容 快递号 商品1 数量1 商品2 数量2...
|
||||||
interface ExportData {
|
interface ExportData {
|
||||||
'日期': string;
|
'日期': string;
|
||||||
'订单号': string;
|
'订单号': string;
|
||||||
'姓名地址': string;
|
'姓名地址': string;
|
||||||
'邮箱': string;
|
'邮箱': string;
|
||||||
'号码': string;
|
'号码': string;
|
||||||
'订单内容': string;
|
|
||||||
'盒数': number;
|
'盒数': number;
|
||||||
'换盒数': number;
|
'换盒数': number;
|
||||||
'换货内容': string;
|
'换货内容': string;
|
||||||
'快递号': string;
|
'快递号': string;
|
||||||
|
[key: string]: any; // 支持动态添加的商品和数量列
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
@ -2518,6 +2516,15 @@ export class OrderService {
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as Record<number, OrderItem[]>);
|
}, {} as Record<number, OrderItem[]>);
|
||||||
|
|
||||||
|
// 计算最大商品数量
|
||||||
|
let maxItemsCount = 0;
|
||||||
|
orders.forEach(order => {
|
||||||
|
const items = orderItemsByOrderId[order.id] || [];
|
||||||
|
if (items.length > maxItemsCount) {
|
||||||
|
maxItemsCount = items.length;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// 构建导出数据
|
// 构建导出数据
|
||||||
const exportDataList: ExportData[] = orders.map(order => {
|
const exportDataList: ExportData[] = orders.map(order => {
|
||||||
// 获取订单的订单项
|
// 获取订单的订单项
|
||||||
|
|
@ -2526,9 +2533,6 @@ export class OrderService {
|
||||||
// 计算总盒数
|
// 计算总盒数
|
||||||
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} x ${item.quantity}`).join('; ');
|
|
||||||
|
|
||||||
// 构建姓名地址
|
// 构建姓名地址
|
||||||
const shipping = order.shipping;
|
const shipping = order.shipping;
|
||||||
const billing = order.billing;
|
const billing = order.billing;
|
||||||
|
|
@ -2553,18 +2557,32 @@ export class OrderService {
|
||||||
const exchangeBoxCount = 0;
|
const exchangeBoxCount = 0;
|
||||||
const exchangeContent = '';
|
const exchangeContent = '';
|
||||||
|
|
||||||
return {
|
// 构建基础数据对象
|
||||||
|
const baseData: ExportData = {
|
||||||
'日期': order.date_created?.toISOString().split('T')[0] || '',
|
'日期': order.date_created?.toISOString().split('T')[0] || '',
|
||||||
'订单号': order.externalOrderId || '',
|
'订单号': order.externalOrderId || '',
|
||||||
'姓名地址': nameAddress,
|
'姓名地址': nameAddress,
|
||||||
'邮箱': order.customer_email || '',
|
'邮箱': order.customer_email || '',
|
||||||
'号码': phone,
|
'号码': phone,
|
||||||
'订单内容': orderContent,
|
|
||||||
'盒数': boxCount,
|
'盒数': boxCount,
|
||||||
'换盒数': exchangeBoxCount,
|
'换盒数': exchangeBoxCount,
|
||||||
'换货内容': exchangeContent,
|
'换货内容': exchangeContent,
|
||||||
'快递号': trackingNumber
|
'快递号': trackingNumber
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 添加商品和数量列
|
||||||
|
items.forEach((item, index) => {
|
||||||
|
baseData[`商品${index + 1}`] = item.name;
|
||||||
|
baseData[`数量${index + 1}`] = item.quantity;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 填充空值,确保所有行的列数一致
|
||||||
|
for (let i = items.length; i < maxItemsCount; i++) {
|
||||||
|
baseData[`商品${i + 1}`] = '';
|
||||||
|
baseData[`数量${i + 1}`] = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return baseData;
|
||||||
});
|
});
|
||||||
|
|
||||||
// 返回CSV字符串内容给前端
|
// 返回CSV字符串内容给前端
|
||||||
|
|
@ -2852,6 +2870,11 @@ export class OrderService {
|
||||||
chargeback: headers.indexOf('拒付')
|
chargeback: headers.indexOf('拒付')
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const logisticsAliases = await this.logisticsAliasModel.find();
|
||||||
|
|
||||||
|
// 构建物流公司别名映射
|
||||||
|
const logisticsAliasMap = new Map(logisticsAliases.map(alias => [ alias.logistics_alias,alias.logistics_company]));
|
||||||
|
|
||||||
// 遍历数据行
|
// 遍历数据行
|
||||||
for (let i = 0; i < dataRows.length; i++) {
|
for (let i = 0; i < dataRows.length; i++) {
|
||||||
const row = dataRows[i];
|
const row = dataRows[i];
|
||||||
|
|
@ -2863,9 +2886,11 @@ export class OrderService {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let orderNumbers="";
|
let orderNumbers = orderNumber;
|
||||||
if (orderNumber.includes('_')&&orderNumber.includes('-')) {
|
// 确保 orderNumber 是字符串类型
|
||||||
orderNumbers = orderNumber.split('_')[0].toString();
|
const orderNumberStr = String(orderNumber);
|
||||||
|
if (orderNumberStr.includes('_') && orderNumberStr.includes('-')) {
|
||||||
|
orderNumbers = orderNumberStr.split('_')[0].toString();
|
||||||
orderNumbers = orderNumbers.split('-')[1];
|
orderNumbers = orderNumbers.split('-')[1];
|
||||||
}
|
}
|
||||||
// 通过订单号查询订单
|
// 通过订单号查询订单
|
||||||
|
|
@ -2876,9 +2901,11 @@ export class OrderService {
|
||||||
|
|
||||||
if (fulfillments && fulfillments.length > 0) {
|
if (fulfillments && fulfillments.length > 0) {
|
||||||
const fulfillment = fulfillments[0]; // 假设每个订单只有一个物流信息
|
const fulfillment = fulfillments[0]; // 假设每个订单只有一个物流信息
|
||||||
|
|
||||||
|
const shipping_provider = logisticsAliasMap.get(fulfillment.shipping_provider);
|
||||||
// 回填物流信息
|
// 回填物流信息
|
||||||
if (columnIndices.logisticsCompany !== -1) {
|
if (columnIndices.logisticsCompany !== -1) {
|
||||||
row[columnIndices.logisticsCompany] = fulfillment.shipping_provider || '';
|
row[columnIndices.logisticsCompany] = shipping_provider || '';
|
||||||
}
|
}
|
||||||
if (columnIndices.trackingNumber !== -1) {
|
if (columnIndices.trackingNumber !== -1) {
|
||||||
row[columnIndices.trackingNumber] = fulfillment.tracking_number || '';
|
row[columnIndices.trackingNumber] = fulfillment.tracking_number || '';
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { Inject, Provide } from '@midwayjs/core';
|
import { ILogger, Inject, Logger, 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';
|
||||||
|
|
@ -34,9 +34,13 @@ 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 {
|
||||||
|
@Logger()
|
||||||
|
logger: ILogger; // 注入 Logger 实例
|
||||||
|
|
||||||
@Inject()
|
@Inject()
|
||||||
ctx: Context;
|
ctx: Context;
|
||||||
|
|
||||||
|
|
@ -855,7 +859,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',
|
||||||
|
|
@ -864,8 +868,12 @@ 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('相同产品属性的产品已存在');
|
if (isExist) throw new Error(`相同产品属性的产品已存在,sku 为${isExist?.sku}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建新产品实例(绑定属性与基础字段)
|
// 创建新产品实例(绑定属性与基础字段)
|
||||||
|
|
@ -1777,58 +1785,38 @@ 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 }, quantity: number = 1, site: Site): Promise<{ product: Product,parentProduct?: Product, quantity: number }[]> {
|
||||||
if (!siteProduct.sku) {
|
if (!siteProduct.sku) {
|
||||||
throw new Error('siteSku 不能为空')
|
throw new Error('siteSku 不能为空')
|
||||||
}
|
}
|
||||||
|
|
||||||
let product = await this.productModel.findOne({
|
const product = await this.getProductBySiteSku(siteProduct.sku, site)
|
||||||
where: { siteSkus: Like(`%${siteProduct.sku}%`) },
|
|
||||||
relations: ['components', 'attributes', 'attributes.dict'],
|
if (!product) return
|
||||||
});
|
|
||||||
let quantity = 1;
|
if(!product?.components?.length){
|
||||||
// 这里处理一下特殊情况,就是无法直接通过 siteProduct.sku去获取, 但有一定规则转换成有的产品,就是 bundle 的部分
|
return [{
|
||||||
// 考察各个站点的 bundle 规则, 会发现
|
product,
|
||||||
// wordpress:
|
quantity
|
||||||
// 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) {
|
return await Promise.all(product.components.map(async comp => {
|
||||||
throw new Error(`产品 ${siteProduct.sku} 不存在`);
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
product,
|
product: await this.productModel.findOne({
|
||||||
quantity,
|
where: { id: comp.productId },
|
||||||
|
}),
|
||||||
|
parentProduct: product, // 这里得记录一下他的爸爸用来记录
|
||||||
|
quantity: comp.quantity * quantity,
|
||||||
}
|
}
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
// 准备创建产品的 DTO, 处理类型转换和默认值
|
// 准备创建产品的 DTO, 处理类型转换和默认值
|
||||||
|
|
@ -2049,9 +2037,9 @@ export class ProductService {
|
||||||
// 将工作表转换为 JSON 数组
|
// 将工作表转换为 JSON 数组
|
||||||
records = xlsx.utils.sheet_to_json(worksheet);
|
records = xlsx.utils.sheet_to_json(worksheet);
|
||||||
|
|
||||||
console.log('Parsed records count:', records.length);
|
this.logger.debug('Parsed records count:', records.length);
|
||||||
if (records.length > 0) {
|
if (records.length > 0) {
|
||||||
console.log('First record keys:', Object.keys(records[0]));
|
this.logger.debug('First record keys:', Object.keys(records[0]));
|
||||||
}
|
}
|
||||||
return records;
|
return records;
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
|
@ -2065,6 +2053,7 @@ 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 {
|
||||||
|
|
@ -2093,7 +2082,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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2151,29 +2140,31 @@ 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 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 +2173,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列表
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
||||||
|
|
|
||||||
|
|
@ -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: '同步成功',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue