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> {
|
||||
// 使用Shopyy API的搜索功能通过sku查询产品
|
||||
const response = await this.getAllProducts({ where: { sku } });
|
||||
console.log('getProductBySku', response)
|
||||
const product = response?.[0]
|
||||
if (!product) {
|
||||
throw new Error(`未找到sku为${sku}的产品`);
|
||||
|
|
@ -1126,7 +1125,6 @@ export class ShopyyAdapter implements ISiteAdapter {
|
|||
// ========== 产品变体映射方法 ==========
|
||||
mapPlatformToUnifiedVariation(variant: ShopyyVariant): UnifiedProductVariationDTO {
|
||||
// 映射变体
|
||||
console.log('ivarianttem', variant)
|
||||
return {
|
||||
id: variant.id,
|
||||
name: variant.title || '',
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ import DictSeeder from '../db/seeds/dict.seeder';
|
|||
import CategorySeeder from '../db/seeds/category.seeder';
|
||||
import CategoryAttributeSeeder from '../db/seeds/category_attribute.seeder';
|
||||
import { SiteSku } from '../entity/site-sku.entity';
|
||||
import { logisticsAlias } from '../entity/logistics_alias.emtity';
|
||||
|
||||
export default {
|
||||
// use for cookie sign key, should change to your own and keep security
|
||||
|
|
@ -88,6 +89,7 @@ export default {
|
|||
Area,
|
||||
CategoryAttribute,
|
||||
Category,
|
||||
logisticsAlias,
|
||||
],
|
||||
synchronize: true,
|
||||
logging: false,
|
||||
|
|
|
|||
|
|
@ -40,7 +40,6 @@ export class AreaController {
|
|||
}));
|
||||
return successResponse(countryList, '查询成功');
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse(error?.message || error);
|
||||
}
|
||||
}
|
||||
|
|
@ -54,7 +53,6 @@ export class AreaController {
|
|||
const newArea = await this.areaService.createArea(area);
|
||||
return successResponse(newArea, '创建成功');
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse(error?.message || error);
|
||||
}
|
||||
}
|
||||
|
|
@ -68,7 +66,6 @@ export class AreaController {
|
|||
const updatedArea = await this.areaService.updateArea(id, area);
|
||||
return successResponse(updatedArea, '更新成功');
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse(error?.message || error);
|
||||
}
|
||||
}
|
||||
|
|
@ -81,7 +78,6 @@ export class AreaController {
|
|||
await this.areaService.deleteArea(id);
|
||||
return successResponse(null, '删除成功');
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse(error?.message || error);
|
||||
}
|
||||
}
|
||||
|
|
@ -95,7 +91,6 @@ export class AreaController {
|
|||
const { list, total } = await this.areaService.getAreaList(query);
|
||||
return successResponse({ list, total }, '查询成功');
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse(error?.message || error);
|
||||
}
|
||||
}
|
||||
|
|
@ -111,7 +106,6 @@ export class AreaController {
|
|||
}
|
||||
return successResponse(area, '查询成功');
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse(error?.message || error);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,8 +42,7 @@ export class OrderController {
|
|||
const result = await this.orderService.syncOrders(siteId, params);
|
||||
return successResponse(result);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse('同步失败');
|
||||
return errorResponse(`同步失败,${error?.message || '未知错误'}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -59,7 +58,6 @@ export class OrderController {
|
|||
const result = await this.orderService.syncOrderById(siteId, orderId);
|
||||
return successResponse(result);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return errorResponse('同步失败');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export class ShipmentBookDTO {
|
|||
shipmentPlatform: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Rule(RuleType.string())
|
||||
@Rule(RuleType.any())
|
||||
courierCompany: 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;
|
||||
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ import {
|
|||
} from 'typeorm';
|
||||
import { ApiProperty } from '@midwayjs/swagger';
|
||||
import { Product } from './product.entity';
|
||||
// 这个其实是 alias 后面改一下
|
||||
@Entity('product_site_sku')
|
||||
export class SiteSku {
|
||||
@ApiProperty({ description: 'sku'})
|
||||
|
|
|
|||
|
|
@ -373,7 +373,7 @@ export class CustomerService {
|
|||
per_page = 20,
|
||||
where = {},
|
||||
} = params;
|
||||
if (where.phone) {
|
||||
if (where?.phone) {
|
||||
where.phone = Like(`%${where.phone}%`);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -735,14 +735,10 @@ export class LogisticsService {
|
|||
|
||||
if (data.shipmentPlatform === 'freightwaves') {
|
||||
|
||||
let courierCompany: string = "";
|
||||
if (data.courierCompany != "最优物流") {
|
||||
courierCompany = data.courierCompany;
|
||||
}
|
||||
// 根据TMS系统对接说明文档格式化参数
|
||||
const reqBody: any = {
|
||||
// shipCompany: 'UPSYYZ7000NEW',
|
||||
shipCompany: courierCompany,
|
||||
shipCompany: data.courierCompany,
|
||||
partnerOrderNumber: order.siteId + '-' + order.externalOrderId,
|
||||
warehouseId: '25072621030107400060',
|
||||
shipper: {
|
||||
|
|
@ -836,15 +832,12 @@ export class LogisticsService {
|
|||
id: data.address_id,
|
||||
},
|
||||
})
|
||||
|
||||
const address = shipments?.address;
|
||||
let courierCompany: string = "";
|
||||
if (data.courierCompany != "最优物流") {
|
||||
courierCompany = data.courierCompany;
|
||||
}
|
||||
// 转换为RateTryRequest格式
|
||||
const r = {
|
||||
//shipCompany: 'UPSYYZ7000NEW', // 必填,但ShipmentFeeBookDTO中缺少
|
||||
shipCompany: courierCompany,
|
||||
shipCompany: data.courierCompany,
|
||||
partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成
|
||||
warehouseId: '25072621030107400060', // 可选,使用stockPointId转换
|
||||
shipper: {
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ import { UnifiedOrderDTO } from '../dto/site-api.dto';
|
|||
import { CustomerService } from './customer.service';
|
||||
import { ProductService } from './product.service';
|
||||
import { Site } from '../entity/site.entity';
|
||||
import { logisticsAlias } from '../entity/logistics_alias.emtity';
|
||||
@Provide()
|
||||
export class OrderService {
|
||||
|
||||
|
|
@ -54,6 +55,9 @@ export class OrderService {
|
|||
@InjectEntityModel(Order)
|
||||
orderModel: Repository<Order>;
|
||||
|
||||
@InjectEntityModel(logisticsAlias)
|
||||
logisticsAliasModel: Repository<logisticsAlias>;
|
||||
|
||||
@InjectEntityModel(User)
|
||||
userModel: Repository<User>;
|
||||
|
||||
|
|
@ -133,7 +137,7 @@ export class OrderService {
|
|||
async syncOrders(siteId: number, params: Record<string, any> = {}): Promise<SyncOperationResult> {
|
||||
// 调用 WooCommerce API 获取订单
|
||||
const result = await (await this.siteApiService.getAdapter(siteId)).getAllOrders(params);
|
||||
|
||||
this.logger.info('开始进入循环同步订单', result.length, '个订单')
|
||||
// 初始化同步结果对象
|
||||
const syncResult: SyncOperationResult = {
|
||||
total: result.length,
|
||||
|
|
@ -143,7 +147,6 @@ export class OrderService {
|
|||
updated: 0,
|
||||
errors: []
|
||||
};
|
||||
this.logger.info('开始进入循环同步订单', result.length, '个订单')
|
||||
// 遍历每个订单进行同步
|
||||
for (const order of result) {
|
||||
try {
|
||||
|
|
@ -479,6 +482,20 @@ export class OrderService {
|
|||
const existingOrder = await this.orderModel.findOne({
|
||||
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) {
|
||||
// 检查是否可以更新 ERP 状态
|
||||
|
|
@ -495,20 +512,7 @@ export class OrderService {
|
|||
}
|
||||
// 如果订单不存在,则映射订单状态
|
||||
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({
|
||||
// where: { email: order.customer_email },
|
||||
// });
|
||||
|
|
@ -745,7 +749,7 @@ export class OrderService {
|
|||
orderId: orderItem.orderId,
|
||||
siteId: orderItem.siteId,
|
||||
externalOrderItemId: orderItem.externalOrderItemId,// 原始 itemId
|
||||
parentProductId: parentProduct.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
|
||||
parentProductId: parentProduct?.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
|
||||
productId: product.id,
|
||||
isPackage: product.type === 'bundle',// 这里是否是套餐取决于父产品
|
||||
name: product.name,
|
||||
|
|
@ -758,7 +762,7 @@ export class OrderService {
|
|||
flavor: attrsObj?.['flavor']?.name,
|
||||
humidity: attrsObj?.['humidity']?.name,
|
||||
size: attrsObj?.['size']?.name,
|
||||
category: product.category.name,
|
||||
category: product.category?.name,
|
||||
});
|
||||
return orderSale
|
||||
}).filter(v => v !== null)
|
||||
|
|
@ -2866,6 +2870,11 @@ export class OrderService {
|
|||
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++) {
|
||||
const row = dataRows[i];
|
||||
|
|
@ -2877,9 +2886,11 @@ export class OrderService {
|
|||
}
|
||||
|
||||
try {
|
||||
let orderNumbers="";
|
||||
if (orderNumber.includes('_')&&orderNumber.includes('-')) {
|
||||
orderNumbers = orderNumber.split('_')[0].toString();
|
||||
let orderNumbers = orderNumber;
|
||||
// 确保 orderNumber 是字符串类型
|
||||
const orderNumberStr = String(orderNumber);
|
||||
if (orderNumberStr.includes('_') && orderNumberStr.includes('-')) {
|
||||
orderNumbers = orderNumberStr.split('_')[0].toString();
|
||||
orderNumbers = orderNumbers.split('-')[1];
|
||||
}
|
||||
// 通过订单号查询订单
|
||||
|
|
@ -2890,9 +2901,11 @@ export class OrderService {
|
|||
|
||||
if (fulfillments && fulfillments.length > 0) {
|
||||
const fulfillment = fulfillments[0]; // 假设每个订单只有一个物流信息
|
||||
|
||||
const shipping_provider = logisticsAliasMap.get(fulfillment.shipping_provider);
|
||||
// 回填物流信息
|
||||
if (columnIndices.logisticsCompany !== -1) {
|
||||
row[columnIndices.logisticsCompany] = fulfillment.shipping_provider || '';
|
||||
row[columnIndices.logisticsCompany] = shipping_provider || '';
|
||||
}
|
||||
if (columnIndices.trackingNumber !== -1) {
|
||||
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 { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import * as fs from 'fs';
|
||||
|
|
@ -38,6 +38,9 @@ import { Site } from '../entity/site.entity';
|
|||
|
||||
@Provide()
|
||||
export class ProductService {
|
||||
@Logger()
|
||||
logger: ILogger; // 注入 Logger 实例
|
||||
|
||||
@Inject()
|
||||
ctx: Context;
|
||||
|
||||
|
|
@ -856,7 +859,7 @@ export class ProductService {
|
|||
// 检查完全相同属性组合是否已存在(避免重复)
|
||||
// 仅当产品类型为 'single' 且有属性时才检查重复
|
||||
if (type === 'single' && resolvedAttributes.length > 0) {
|
||||
const qb = this.productModel.createQueryBuilder('product');
|
||||
const qb = this.productModel.createQueryBuilder('product')
|
||||
resolvedAttributes.forEach((attr, index) => {
|
||||
qb.innerJoin(
|
||||
'product.attributes',
|
||||
|
|
@ -865,8 +868,12 @@ export class ProductService {
|
|||
{ [`attrId${index}`]: attr.id }
|
||||
);
|
||||
});
|
||||
// 添加属性数量的判断,确保产品的属性数量与指定的属性数量相同
|
||||
qb.andWhere('(SELECT COUNT(*) FROM product_attributes_dict_item pad WHERE pad.productId = product.id) = :attrCount', {
|
||||
attrCount: resolvedAttributes.length
|
||||
});
|
||||
const isExist = await qb.getOne();
|
||||
if (isExist) throw new Error('相同产品属性的产品已存在');
|
||||
if (isExist) throw new Error(`相同产品属性的产品已存在,sku 为${isExist?.sku}`);
|
||||
}
|
||||
|
||||
// 创建新产品实例(绑定属性与基础字段)
|
||||
|
|
@ -2030,9 +2037,9 @@ export class ProductService {
|
|||
// 将工作表转换为 JSON 数组
|
||||
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) {
|
||||
console.log('First record keys:', Object.keys(records[0]));
|
||||
this.logger.debug('First record keys:', Object.keys(records[0]));
|
||||
}
|
||||
return records;
|
||||
} catch (e: any) {
|
||||
|
|
@ -2046,6 +2053,7 @@ export class ProductService {
|
|||
let updated = 0;
|
||||
const errors: BatchErrorItem[] = [];
|
||||
const records = await this.getRecordsFromTable(file);
|
||||
this.logger.debug('Total records count:', records.length);
|
||||
// 逐条处理记录
|
||||
for (const rec of records) {
|
||||
try {
|
||||
|
|
@ -2074,7 +2082,7 @@ export class ProductService {
|
|||
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 };
|
||||
}
|
||||
|
||||
|
|
@ -2132,16 +2140,10 @@ export class ProductService {
|
|||
component.sku = product.sku;
|
||||
component.quantity = 1;
|
||||
product.components = [component];
|
||||
} else {
|
||||
// 混装商品返回持久化的 SKU 组成
|
||||
product.components = await this.productStockComponentModel.find({
|
||||
where: { productId: product.id },
|
||||
});
|
||||
}
|
||||
|
||||
return product;
|
||||
}
|
||||
|
||||
// 根据站点SKU查询产品
|
||||
async getProductBySiteSku(siteSku: string, site?: Site): Promise<Product> {
|
||||
// 使用查询构建器来正确查询关联表
|
||||
|
|
|
|||
Loading…
Reference in New Issue