Compare commits

..

1 Commits

Author SHA1 Message Date
zksu 65fd1aec1e Merge pull request 'feat: 修复产品与站点同步诸多问题' (#39) from zksu/API:main into main
Reviewed-on: #39
Reviewed-by: longbot <444693295@qq.com>
2026-01-04 12:48:56 +00:00
19 changed files with 186 additions and 1177 deletions

View File

@ -15,11 +15,9 @@ import {
CreateWebhookDTO,
UpdateWebhookDTO,
UnifiedAddressDTO,
UnifiedShippingLineDTO,
OrderFulfillmentStatus,
FulfillmentDTO
UnifiedShippingLineDTO
} from '../dto/site-api.dto';
import { UnifiedPaginationDTO, UnifiedSearchParamsDTO, } from '../dto/api.dto';
import { UnifiedPaginationDTO, UnifiedSearchParamsDTO, } from '../dto/api.dto';
import {
ShopyyCustomer,
ShopyyOrder,
@ -31,16 +29,6 @@ import {
OrderStatus,
} from '../enums/base.enum';
export class ShopyyAdapter implements ISiteAdapter {
shopyyFinancialStatusMap= {
'200': '待支付',
'210': "支付中",
'220':"部分支付",
'230':"已支付",
'240':"支付失败",
'250':"部分退款",
'260':"已退款",
'290':"已取消",
}
constructor(private site: any, private shopyyService: ShopyyService) {
this.mapCustomer = this.mapCustomer.bind(this);
this.mapProduct = this.mapProduct.bind(this);
@ -144,11 +132,9 @@ export class ShopyyAdapter implements ISiteAdapter {
};
}
shopyyOrderStatusMap = {//订单状态 100 未完成110 待处理180 已完成(确认收货); 190 取消;
shopyyOrderAutoNextStatusMap = {//订单状态 100 未完成110 待处理180 已完成(确认收货); 190 取消;
[100]: OrderStatus.PENDING, // 100 未完成 转为 pending
[110]: OrderStatus.PROCESSING, // 110 待处理 转为 processing
// 已发货
[180]: OrderStatus.COMPLETED, // 180 已完成(确认收货) 转为 completed
[190]: OrderStatus.CANCEL // 190 取消 转为 cancelled
}
@ -202,14 +188,14 @@ export class ShopyyAdapter implements ISiteAdapter {
'',
};
// 构建送货地址对象
// 构建送货地址对象
const shipping_lines: UnifiedShippingLineDTO[] = [
{
id: item.fulfillments?.[0]?.id || 0,
method_title: item.payment_method || '',
method_id: item.payment_method || '',
total: Number(item.current_shipping_price).toExponential(2) || '0.00',
total_tax: '0.00',
total_tax: '0.00',
taxes: [],
meta_data: [],
},
@ -243,32 +229,28 @@ export class ShopyyAdapter implements ISiteAdapter {
price: String(p.price ?? ''),
})
);
// 货币符号
const currencySymbols: Record<string, string> = {
'EUR': '€',
'USD': '$',
'GBP': '£',
'JPY': '¥',
'AUD': 'A$',
'CAD': 'C$',
'CHF': 'CHF',
'CNY': '¥',
'HKD': 'HK$',
'NZD': 'NZ$',
'SGD': 'S$'
// 可以根据需要添加更多货币代码和符号
};
// 映射订单状态,如果不存在则默认 pending
const status = this.shopyyOrderStatusMap[item.status ?? item.order_status] || OrderStatus.PENDING;
const finalcial_status = this.shopyyFinancialStatusMap[item.financial_status]
// 发货状态
const fulfillment_status = this.shopyyFulfillmentStatusMap[item.fulfillment_status];
const currencySymbols: Record<string, string> = {
'EUR': '€',
'USD': '$',
'GBP': '£',
'JPY': '¥',
'AUD': 'A$',
'CAD': 'C$',
'CHF': 'CHF',
'CNY': '¥',
'HKD': 'HK$',
'NZD': 'NZ$',
'SGD': 'S$'
// 可以根据需要添加更多货币代码和符号
};
const originStatus = item.status;
item.status = this.shopyyOrderAutoNextStatusMap[originStatus];
return {
id: item.id || item.order_id,
number: item.order_number || item.order_sn,
status,
financial_status: finalcial_status,
status: String(item.status || item.order_status),
currency: item.currency_code || item.currency,
total: String(item.total_price ?? item.total_amount ?? ''),
customer_id: item.customer_id || item.user_id,
@ -289,7 +271,7 @@ export class ShopyyAdapter implements ISiteAdapter {
customer_ip_address: item.ip || '',
device_type: item.source_device || '',
utm_source: item.utm_source || '',
source_type: 'shopyy', // FIXME
source_type: 'shopyy',
date_paid: typeof item.pay_at === 'number'
? item.pay_at === 0 ? null : new Date(item.pay_at * 1000).toISOString()
: null,
@ -307,31 +289,10 @@ export class ShopyyAdapter implements ISiteAdapter {
: item.date_updated ||
item.last_modified ||
(typeof item.updated_at === 'string' ? item.updated_at : ''),
fulfillment_status,
fulfillments: item.fulfillments?.map?.((f) => ({
id: f.id,
tracking_number: f.tracking_number || '',
shipping_provider: f.tracking_company || '',
shipping_method: f.tracking_company || '',
date_created: typeof f.created_at === 'number'
? new Date(f.created_at * 1000).toISOString()
: f.created_at || '',
// status: f.payment_tracking_status
})) || [],
raw: item,
};
}
shopyyFulfillmentStatusMap = {
// 未发货
'300': OrderFulfillmentStatus.PENDING,
// 部分发货
'310': OrderFulfillmentStatus.PARTIALLY_FULFILLED,
// 已发货
'320': OrderFulfillmentStatus.FULFILLED,
// 已取消
'330': OrderFulfillmentStatus.CANCELLED,
// 确认发货
}
private mapCustomer(item: ShopyyCustomer): UnifiedCustomerDTO {
// 处理多地址结构
@ -402,11 +363,11 @@ export class ShopyyAdapter implements ISiteAdapter {
'products/list',
params
);
const { items = [], total, totalPages, page, per_page } = response;
const { items=[], total, totalPages, page, per_page } = response;
const finalItems = items.map((item) => ({
...item,
permalink: `${this.site.websiteUrl}/products/${item.handle}`,
})).map(this.mapProduct.bind(this))
...item,
permalink: `${this.site.websiteUrl}/products/${item.handle}`,
})).map(this.mapProduct.bind(this))
return {
items: finalItems as UnifiedProductDTO[],
total,
@ -466,37 +427,15 @@ export class ShopyyAdapter implements ISiteAdapter {
): Promise<any> {
return await this.shopyyService.batchProcessProducts(this.site, data);
}
mapUnifiedOrderQueryToShopyyQuery(params: UnifiedSearchParamsDTO) {
const { where = {} as any, ...restParams } = params || {}
const statusMap = {
'pending': '100', // 100 未完成
'processing': '110', // 110 待处理
'completed': "180", // 180 已完成(确认收货)
'cancelled': '190', // 190 取消
}
const normalizedParams: any = {
...restParams,
}
if (where) {
normalizedParams.where = {
...where,
}
if (where.status) {
normalizedParams.where.status = statusMap[where.status];
}
}
return normalizedParams
}
async getOrders(
params: UnifiedSearchParamsDTO
): Promise<UnifiedPaginationDTO<UnifiedOrderDTO>> {
const normalizedParams = this.mapUnifiedOrderQueryToShopyyQuery(params);
const { items, total, totalPages, page, per_page } =
await this.shopyyService.fetchResourcePaged<any>(
this.site,
'orders',
normalizedParams
params
);
return {
items: items.map(this.mapOrder.bind(this)),
@ -508,7 +447,7 @@ export class ShopyyAdapter implements ISiteAdapter {
}
async getAllOrders(params?: UnifiedSearchParamsDTO): Promise<UnifiedOrderDTO[]> {
const data = await this.shopyyService.getAllOrders(this.site.id, params);
const data = await this.shopyyService.getAllOrders(this.site.id,params);
return data.map(this.mapOrder.bind(this));
}
@ -582,7 +521,7 @@ export class ShopyyAdapter implements ISiteAdapter {
// 调用 ShopyyService 的取消履行方法
const cancelShipData = {
order_id: String(orderId),
fulfillment_id: data.shipment_id || ''
fullfillment_id: data.shipment_id || ''
};
const result = await this.shopyyService.cancelFulfillment(this.site, cancelShipData);
@ -613,13 +552,18 @@ export class ShopyyAdapter implements ISiteAdapter {
* @param data
* @returns
*/
async createOrderFulfillment(orderId: string | number, data: FulfillmentDTO): Promise<any> {
async createOrderFulfillment(orderId: string | number, data: {
tracking_number: string;
tracking_provider: string;
date_shipped?: string;
status_shipped?: string;
}): Promise<any> {
// 调用 Shopyy Service 的 createFulfillment 方法
const fulfillmentData = {
tracking_number: data.tracking_number,
carrier_code: data.shipping_provider,
carrier_name: data.shipping_provider,
shipping_method: data.shipping_method || 'standard'
carrier_code: data.tracking_provider,
carrier_name: data.tracking_provider,
shipping_method: data.status_shipped || 'standard'
};
return await this.shopyyService.createFulfillment(this.site, String(orderId), fulfillmentData);
@ -785,7 +729,7 @@ export class ShopyyAdapter implements ISiteAdapter {
id: item.id,
name: item.webhook_name || `Webhook-${item.id}`,
topic: item.event_code || '',
delivery_url: item.url || '',
delivery_url: item.url|| '',
status: 'active',
};
}
@ -825,7 +769,7 @@ export class ShopyyAdapter implements ISiteAdapter {
return await this.shopyyService.deleteWebhook(this.site, id);
}
async getLinks(): Promise<Array<{ title: string, url: string }>> {
async getLinks(): Promise<Array<{title: string, url: string}>> {
// ShopYY站点的管理后台链接通常基于apiUrl构建
const url = this.site.websiteUrl
// 提取基础域名,去掉可能的路径部分

View File

@ -454,13 +454,12 @@ export class WooCommerceAdapter implements ISiteAdapter {
// 包含账单地址与收货地址以及创建与更新时间
// 映射物流追踪信息,将后端格式转换为前端期望的格式
const fulfillments = (item.fulfillments || []).map((track: any) => ({
const tracking = (item.trackings || []).map((track: any) => ({
order_id: String(item.id),
tracking_provider: track.tracking_provider || '',
tracking_number: track.tracking_number || '',
shipping_provider: track.shipping_provider || '',
shipping_method: track.shipping_method || '',
status: track.status || '',
date_created: track.date_created || '',
items: track.items || [],
date_shipped: track.date_shipped || '',
status_shipped: track.status_shipped || '',
}));
return {
@ -482,11 +481,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
...li,
productId: li.product_id,
})),
customer_ip_address: item.customer_ip_address ?? '',
date_paid: item.date_paid ?? '',
utm_source: item?.meta_data?.find(el => el.key === '_wc_order_attribution_utm_source')?.value || '',
device_type: item?.meta_data?.find(el => el.key === '_wc_order_attribution_device_type')?.value || '',
source_type: item?.meta_data?.find(el => el.key === '_wc_order_attribution_source_type')?.value || '',
billing: item.billing,
shipping: item.shipping,
billing_full_address: this.buildFullAddress(item.billing),
@ -497,7 +492,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
shipping_lines: item.shipping_lines,
fee_lines: item.fee_lines,
coupon_lines: item.coupon_lines,
fulfillments,
tracking: tracking,
raw: item,
};
}
@ -688,29 +683,29 @@ export class WooCommerceAdapter implements ISiteAdapter {
await this.wpService.fetchResourcePaged<any>(this.site, 'orders', requestParams);
// 并行获取所有订单的履行信息
const ordersWithFulfillments = await Promise.all(
const ordersWithTracking = await Promise.all(
items.map(async (order: any) => {
try {
// 获取订单的履行信息
const fulfillments = await this.getOrderFulfillments(order.id);
const trackings = await this.getOrderFulfillments(order.id);
// 将履行信息添加到订单对象中
return {
...order,
fulfillments: fulfillments || []
trackings: trackings || []
};
} catch (error) {
// 如果获取履行信息失败,仍然返回订单,只是履行信息为空数组
console.error(`获取订单 ${order.id} 的履行信息失败:`, error);
return {
...order,
fulfillments: []
trackings: []
};
}
})
);
return {
items: ordersWithFulfillments.map(this.mapOrder),
items: ordersWithTracking.map(this.mapOrder),
total,
totalPages,
page,
@ -1017,34 +1012,21 @@ export class WooCommerceAdapter implements ISiteAdapter {
async createOrderFulfillment(orderId: string | number, data: {
tracking_number: string;
shipping_provider: string;
shipping_method?: string;
status?: string;
date_created?: string;
items?: Array<{
order_item_id: number;
quantity: number;
}>;
tracking_provider: string;
date_shipped?: string;
status_shipped?: string;
}): Promise<any> {
const shipmentData: any = {
shipping_provider: data.shipping_provider,
tracking_provider: data.tracking_provider,
tracking_number: data.tracking_number,
};
if (data.shipping_method) {
shipmentData.shipping_method = data.shipping_method;
if (data.date_shipped) {
shipmentData.date_shipped = data.date_shipped;
}
if (data.status) {
shipmentData.status = data.status;
}
if (data.date_created) {
shipmentData.date_created = data.date_created;
}
if (data.items) {
shipmentData.items = data.items;
if (data.status_shipped) {
shipmentData.status_shipped = data.status_shipped;
}
const response = await this.wpService.createFulfillment(this.site, String(orderId), shipmentData);
@ -1053,14 +1035,9 @@ export class WooCommerceAdapter implements ISiteAdapter {
async updateOrderFulfillment(orderId: string | number, fulfillmentId: string, data: {
tracking_number?: string;
shipping_provider?: string;
shipping_method?: string;
status?: string;
date_created?: string;
items?: Array<{
order_item_id: number;
quantity: number;
}>;
tracking_provider?: string;
date_shipped?: string;
status_shipped?: string;
}): Promise<any> {
return await this.wpService.updateFulfillment(this.site, String(orderId), fulfillmentId, data);
}

View File

@ -16,7 +16,6 @@ import { OrderRefundItem } from '../entity/order_refund_item.entity';
import { OrderSale } from '../entity/order_sale.entity';
import { OrderItemOriginal } from '../entity/order_item_original.entity';
import { OrderShipping } from '../entity/order_shipping.entity';
import { OrderFulfillment } from '../entity/order_fulfillment.entity';
import { Service } from '../entity/service.entity';
import { ShippingAddress } from '../entity/shipping_address.entity';
import { OrderNote } from '../entity/order_note.entity';
@ -68,7 +67,6 @@ export default {
ShipmentItem,
Shipment,
OrderShipping,
OrderFulfillment,
Service,
ShippingAddress,
OrderNote,

View File

@ -9,7 +9,6 @@ import {
Put,
Query,
} from '@midwayjs/core';
import { SyncOperationResult } from '../dto/api.dto';
import { ApiOkResponse } from '@midwayjs/swagger';
import {
BooleanRes,
@ -48,7 +47,7 @@ export class OrderController {
}
@ApiOkResponse({
type: SyncOperationResult,
type: BooleanRes,
})
@Post('/syncOrder/:siteId/order/:orderId')
async syncOrderById(
@ -253,15 +252,4 @@ export class OrderController {
return errorResponse(error?.message || '获取失败');
}
}
@ApiOkResponse()
@Post('/export')
async exportOrder(@Body('ids') ids: number[]) {
try {
const csvContent = await this.orderService.exportOrder(ids);
return successResponse(csvContent);
} catch (error) {
return errorResponse(error?.message || '导出失败');
}
}
}

View File

@ -663,7 +663,8 @@ export class SiteApiController {
this.logger.info(`[Site API] 获取订单列表开始, siteId: ${siteId}, query: ${JSON.stringify(query)}`);
try {
const adapter = await this.siteApiService.getAdapter(siteId);
const data = await adapter.getOrders(query);
const where = { ...(query.where || {}) };
const data = await adapter.getOrders({ ...query, where });
this.logger.info(`[Site API] 获取订单列表成功, siteId: ${siteId}, 共获取到 ${data.total} 个订单`);
return successResponse(data);
} catch (error) {
@ -1017,7 +1018,7 @@ export class SiteApiController {
body.orders.map(order =>
adapter.createOrderFulfillment(order.order_id, {
tracking_number: order.tracking_number,
shipping_provider: order.shipping_provider,
tracking_provider: order.shipping_provider,
items: order.items,
}).catch(error => ({
order_id: order.order_id,
@ -1081,10 +1082,9 @@ export class SiteApiController {
const adapter = await this.siteApiService.getAdapter(siteId);
const data = await adapter.createOrderFulfillment(orderId, {
tracking_number: body.tracking_number,
shipping_provider: body.shipping_provider,
shipping_method: body.shipping_method,
status: body.status,
date_created: body.date_created,
tracking_provider: body.tracking_provider,
date_shipped: body.date_shipped,
status_shipped: body.status_shipped,
});
this.logger.info(`[Site API] 创建订单履约跟踪信息成功, siteId: ${siteId}, orderId: ${orderId}`);
return successResponse(data);
@ -1108,10 +1108,9 @@ export class SiteApiController {
const adapter = await this.siteApiService.getAdapter(siteId);
const data = await adapter.updateOrderFulfillment(orderId, fulfillmentId, {
tracking_number: body.tracking_number,
shipping_provider: body.shipping_provider,
shipping_method: body.shipping_method,
status: body.status,
date_created: body.date_created,
tracking_provider: body.tracking_provider,
date_shipped: body.date_shipped,
status_shipped: body.status_shipped,
});
this.logger.info(`[Site API] 更新订单履约跟踪信息成功, siteId: ${siteId}, orderId: ${orderId}, fulfillmentId: ${fulfillmentId}`);
return successResponse(data);

View File

@ -38,14 +38,12 @@ export class WebhookController {
return 'webhook';
}
// TODO 这里得检查一下是否对 SHOPYY有效,否则得另外书写
@Post('/woocommerce')
async handleWooWebhook(
@Body() body: any,
@Query('siteId') siteIdStr: string,
@Headers() header: any
) {
console.log(`webhook woocommerce`, siteIdStr, body,header)
const signature = header['x-wc-webhook-signature'];
const topic = header['x-wc-webhook-topic'];
const source = header['x-wc-webhook-source'];

View File

@ -81,14 +81,7 @@ export interface BatchOperationResult {
/**
*
*/
export class SyncOperationResult implements BatchOperationResult {
total: number;
processed: number;
created?: number;
updated?: number;
deleted?: number;
skipped?: number;
errors: BatchErrorItem[];
export interface SyncOperationResult extends BatchOperationResult {
// 同步成功数量
synced: number;
}

View File

@ -73,7 +73,7 @@ export class CreateCustomerDTO {
site_id: number;
@ApiProperty({ description: '原始ID', required: false })
origin_id?: string;
origin_id?: number;
@ApiProperty({ description: '邮箱' })
email: string;

View File

@ -187,39 +187,18 @@ export interface ShopyyOrder {
transaction_no?: string;
}>;
fulfillments?: Array<{
// 物流回传状态
payment_tracking_status?: number;
// 备注
note?: string;
// 更新时间
updated_at?: number;
// 追踪接口编号
courier_code?: string;
// 物流公司 id
courier_id?: number;
// 创建时间
created_at?: number;
id?: number;
// 物流单号
tracking_number?: string;
// 物流公司名称
id?: number;
tracking_company?: string;
// 物流回传结果
payment_tracking_result?: string;
// 物流回传时间
payment_tracking_at?: number;
// 商品
products?: Array<{
// 订单商品表 id
order_product_id?: number;
// 数量
quantity?: number;
// 更新时间
updated_at?: number;
// 创建时间
created_at?: number;
// 发货商品表 id
id?: number }>;
products?: Array<{ order_product_id?: number; quantity?: number; updated_at?: number; created_at?: number; id?: number }>;
}>;
shipping_zone_plans?: Array<{
shipping_price?: number | string;
@ -446,9 +425,9 @@ export class ShopyPartFulfillmentDTO {
// https://www.apizza.net/project/e114fb8e628e0f604379f5b26f0d8330/browse
export class ShopyyCancelFulfillmentDTO {
order_id: string;
fulfillment_id: string;
fullfillment_id: string;
}
export class ShopyyBatchFulfillmentItemDTO {
fulfillments: ShopyPartFulfillmentDTO[]
fullfillments: ShopyPartFulfillmentDTO[]
}

View File

@ -2,21 +2,7 @@ import { ApiProperty } from '@midwayjs/swagger';
import {
UnifiedPaginationDTO,
} from './api.dto';
// export class UnifiedOrderWhere{
// []
// }
export enum OrderFulfillmentStatus {
// 未发货
PENDING,
// 部分发货
PARTIALLY_FULFILLED,
// 已发货
FULFILLED,
// 已取消
CANCELLED,
// 确认发货
CONFIRMED,
}
export class UnifiedTagDTO {
// 标签DTO用于承载统一标签数据
@ApiProperty({ description: '标签ID' })
@ -33,6 +19,23 @@ export class UnifiedCategoryDTO {
@ApiProperty({ description: '分类名称' })
name: string;
}
// 订单跟踪号
export class UnifiedOrderTrackingDTO {
@ApiProperty({ description: '订单ID' })
order_id: string;
@ApiProperty({ description: '快递公司' })
tracking_provider: string;
@ApiProperty({ description: '运单跟踪号' })
tracking_number: string;
@ApiProperty({ description: '发货日期' })
date_shipped: string;
@ApiProperty({ description: '发货状态' })
status_shipped: string;
}
export class UnifiedImageDTO {
// 图片DTO用于承载统一图片数据
@ -315,9 +318,6 @@ export class UnifiedOrderDTO {
@ApiProperty({ description: '订单状态' })
status: string;
@ApiProperty({ description: '财务状态',nullable: true })
financial_status?: string;
@ApiProperty({ description: '货币' })
currency: string;
@ -384,6 +384,9 @@ export class UnifiedOrderDTO {
@ApiProperty({ description: '优惠券项', type: () => [UnifiedCouponLineDTO], required: false })
coupon_lines?: UnifiedCouponLineDTO[];
@ApiProperty({ description: '物流追踪信息', type: () => [UnifiedOrderTrackingDTO], required: false })
tracking?: UnifiedOrderTrackingDTO[];
@ApiProperty({ description: '支付时间', required: false })
date_paid?: string | null;
@ -398,12 +401,6 @@ export class UnifiedOrderDTO {
@ApiProperty({ description: '来源类型', required: false })
source_type?: string;
@ApiProperty({ description: '订单状态', required: false })
fulfillment_status?: OrderFulfillmentStatus;
// 物流信息
@ApiProperty({ description: '物流信息', type: () => [FulfillmentDTO], required: false })
fulfillments?: FulfillmentDTO[];
}
export class UnifiedShippingLineDTO {
@ -799,12 +796,6 @@ export class FulfillmentDTO {
@ApiProperty({ description: '发货方式', required: false })
shipping_method?: string;
@ApiProperty({ description: '状态', required: false })
status?: string;
@ApiProperty({ description: '创建时间', required: false })
date_created?: string;
@ApiProperty({ description: '发货商品项', type: () => [FulfillmentItemDTO], required: false })
items?: FulfillmentItemDTO[];
}
@ -964,24 +955,3 @@ export class BatchFulfillmentsDTO {
@ApiProperty({ description: '批量发货订单列表', type: () => [BatchFulfillmentItemDTO] })
orders: BatchFulfillmentItemDTO[];
}
// 订单跟踪号
export class UnifiedOrderTrackingDTO {
@ApiProperty({ description: '订单ID' })
order_id: string;
@ApiProperty({ description: '物流单号' })
tracking_number: string;
@ApiProperty({ description: '物流公司' })
shipping_provider: string;
@ApiProperty({ description: '发货方式' })
shipping_method?: string;
@ApiProperty({ description: '状态' })
status?: string;
@ApiProperty({ description: '创建时间' })
date_created?: string;
}

View File

@ -370,16 +370,11 @@ export interface WooOrder {
date_modified?: string;
date_modified_gmt?: string;
// 物流追踪信息
fulfillments?: Array<{
trackings?: Array<{
tracking_provider?: string;
tracking_number?: string;
shipping_provider?: string;
shipping_method?: string;
status?: string;
date_created?: string;
items?: Array<{
order_item_id?: number;
quantity?: number;
}>;
date_shipped?: string;
status_shipped?: string;
}>;
}
export interface WooOrderRefund {

View File

@ -1,86 +0,0 @@
import { ApiProperty } from '@midwayjs/swagger';
import { Exclude, Expose } from 'class-transformer';
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity('order_fulfillment')
@Exclude()
export class OrderFulfillment {
@ApiProperty()
@PrimaryGeneratedColumn()
@Expose()
id: number;
@ApiProperty()
@Column({ name: 'order_id', nullable: true })
@Expose()
order_id: number; // 订单 ID
@ApiProperty()
@Column({ name: 'site_id', nullable: true })
@Expose()
site_id: number; // 站点ID
@ApiProperty()
@Column({ name: 'external_order_id', nullable: true })
@Expose()
external_order_id: string; // 外部订单 ID
@ApiProperty()
@Column({ name: 'external_fulfillment_id', nullable: true })
@Expose()
external_fulfillment_id: string; // 外部履约 ID
@ApiProperty()
@Column({ name: 'tracking_number' })
@Expose()
tracking_number: string; // 物流单号
@ApiProperty()
@Column({ name: 'shipping_provider', nullable: true })
@Expose()
shipping_provider: string; // 物流公司
@ApiProperty()
@Column({ name: 'shipping_method', nullable: true })
@Expose()
shipping_method: string; // 发货方式
@ApiProperty()
@Column({ nullable: true })
@Expose()
status: string; // 状态
@ApiProperty()
@Column({ name: 'date_created', type: 'timestamp', nullable: true })
@Expose()
date_created: Date; // 创建时间
@ApiProperty()
@Column({ type: 'json', nullable: true })
@Expose()
items: any[]; // 发货商品项
@ApiProperty({
example: '2022-12-12 11:11:11',
description: '创建时间',
required: true,
})
@CreateDateColumn({ name: 'created_at' })
@Expose()
created_at: Date;
@ApiProperty({
example: '2022-12-12 11:11:11',
description: '更新时间',
required: true,
})
@UpdateDateColumn({ name: 'updated_at' })
@Expose()
updated_at: Date;
}

View File

@ -37,7 +37,7 @@ export class Site {
@Column({ default: false })
isDisabled: boolean;
@ManyToMany(() => Area, { cascade: true })
@ManyToMany(() => Area)
@JoinTable({
name: 'site_areas_area',
joinColumn: {

View File

@ -238,14 +238,10 @@ export interface ISiteAdapter {
*/
createOrderFulfillment(orderId: string | number, data: {
tracking_number: string;
shipping_provider: string;
shipping_method?: string;
status?: string;
date_created?: string;
items?: Array<{
order_item_id: number;
quantity: number;
}>;
tracking_provider: string;
date_shipped?: string;
status_shipped?: string;
items?: any[];
}): Promise<any>;
/**
@ -253,14 +249,9 @@ export interface ISiteAdapter {
*/
updateOrderFulfillment(orderId: string | number, fulfillmentId: string, data: {
tracking_number?: string;
shipping_provider?: string;
shipping_method?: string;
status?: string;
date_created?: string;
items?: Array<{
order_item_id: number;
quantity: number;
}>;
tracking_provider?: string;
date_shipped?: string;
status_shipped?: string;
}): Promise<any>;
/**

View File

@ -39,7 +39,7 @@ export class CustomerService {
site_id: siteId, // 使用站点ID而不是客户ID
site_created_at: this.parseDate(siteCustomer.date_created),
site_updated_at: this.parseDate(siteCustomer.date_modified),
origin_id: String(siteCustomer.id),
origin_id: Number(siteCustomer.id),
email: siteCustomer.email,
first_name: siteCustomer.first_name,
last_name: siteCustomer.last_name,
@ -171,7 +171,10 @@ export class CustomerService {
// 第二步:将站点客户数据转换为客户实体数据
const customersData = siteCustomers.map(siteCustomer => {
return this.mapSiteCustomerToCustomer(siteCustomer, siteId);
})
}).map(customer => ({
...customer,
origin_id: String(customer.origin_id),
}));
// 第三步批量upsert客户数据
const upsertResult = await this.upsertManyCustomers(customersData);

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
import { ILogger, Inject, Provide } from '@midwayjs/core';
import { Inject, Provide } from '@midwayjs/core';
import axios, { AxiosRequestConfig } from 'axios';
import * as fs from 'fs';
import * as FormData from 'form-data';
@ -13,8 +13,6 @@ import { UnifiedSearchParamsDTO } from '../dto/api.dto';
*/
@Provide()
export class ShopyyService {
@Inject()
logger:ILogger;
/**
* ShopYY评论列表
* @param site
@ -203,12 +201,10 @@ export class ShopyyService {
page,
limit
};
this.logger.debug('ShopYY API请求分页参数:'+ JSON.stringify(requestParams));
const response = await this.request(site, endpoint, 'GET', null, requestParams);
if (response?.code !== 0) {
throw new Error(response?.msg)
}
return {
items: (response.data.list || []) as T[],
total: response.data?.paginate?.total || 0,
@ -1025,7 +1021,7 @@ export class ShopyyService {
*/
async cancelFulfillment(site: any, data: {
order_id: string;
fulfillment_id: string;
fullfillment_id: string;
}): Promise<boolean> {
try {
// ShopYY API: POST /orders/fulfillment/cancel

View File

@ -5,7 +5,6 @@ import { Site } from '../entity/site.entity';
import { CreateSiteDTO, UpdateSiteDTO } from '../dto/site.dto';
import { Area } from '../entity/area.entity';
import { StockPoint } from '../entity/stock_point.entity';
import * as countries from 'i18n-iso-countries';
@Provide()
@Scope(ScopeEnum.Singleton)
@ -26,26 +25,12 @@ export class SiteService {
const newSite = new Site();
Object.assign(newSite, restData);
// 如果传入了区域代码,则查询或创建 Area 实体
// 如果传入了区域代码,则查询并关联 Area 实体
if (areaCodes && areaCodes.length > 0) {
// 先查询数据库中已存在的 Area 实体
const existingAreas = await this.areaModel.findBy({
const areas = await this.areaModel.findBy({
code: In(areaCodes),
});
const existingCodes = new Set(existingAreas.map(area => area.code));
// 为不存在的 Area 创建新实体
const newAreas = areaCodes
.filter(code => !existingCodes.has(code))
.map(areaCode => {
const area = new Area();
area.code = areaCode;
area.name = countries.getName(areaCode, 'zh') || areaCode; // 使用 countries 获取中文名称,如果获取不到则使用 code
return area;
});
// 合并已存在和新创建的 Area 实体
newSite.areas = [...existingAreas, ...newAreas];
newSite.areas = areas;
} else {
// 如果没有传入区域,则关联一个空数组,代表"全局"
newSite.areas = [];
@ -62,8 +47,7 @@ export class SiteService {
}
// 使用 save 方法保存实体及其关联关系
const result = await this.siteModel.save(newSite);
console.log('result create siteId',result)
await this.siteModel.save(newSite);
return true;
}
@ -89,25 +73,11 @@ export class SiteService {
// 如果 DTO 中传入了 areas 字段(即使是空数组),也要更新关联关系
if (areaCodes !== undefined) {
if (areaCodes.length > 0) {
// 先查询数据库中已存在的 Area 实体
const existingAreas = await this.areaModel.findBy({
// 如果区域代码数组不为空,则查找并更新关联
const areas = await this.areaModel.findBy({
code: In(areaCodes),
});
const existingCodes = new Set(existingAreas.map(area => area.code));
// 为不存在的 Area 创建新实体
const newAreas = areaCodes
.filter(code => !existingCodes.has(code))
.map(areaCode => {
const area = new Area();
area.code = areaCode;
// name 使用 i18n-contries 获取
area.name = countries.getName(areaCode, 'zh') || areaCode; // 使用 code 作为 name 的默认值
return area;
});
// 合并已存在和新创建的 Area 实体
siteToUpdate.areas = [...existingAreas, ...newAreas];
siteToUpdate.areas = areas;
} else {
// 如果传入空数组,则清空所有关联,代表"全局"
siteToUpdate.areas = [];

View File

@ -719,14 +719,9 @@ export class WPService implements IPlatformService {
fulfillmentId: string,
data: {
tracking_number?: string;
shipping_provider?: string;
shipping_method?: string;
status?: string;
date_created?: string;
items?: Array<{
order_item_id: number;
quantity: number;
}>;
tracking_provider?: string;
date_shipped?: string;
status_shipped?: string;
}
): Promise<any> {
const apiUrl = site.apiUrl;
@ -737,28 +732,20 @@ export class WPService implements IPlatformService {
const fulfillmentData: any = {};
if (data.shipping_provider !== undefined) {
fulfillmentData.shipping_provider = data.shipping_provider;
if (data.tracking_provider !== undefined) {
fulfillmentData.tracking_provider = data.tracking_provider;
}
if (data.tracking_number !== undefined) {
fulfillmentData.tracking_number = data.tracking_number;
}
if (data.shipping_method !== undefined) {
fulfillmentData.shipping_method = data.shipping_method;
if (data.date_shipped !== undefined) {
fulfillmentData.date_shipped = data.date_shipped;
}
if (data.status !== undefined) {
fulfillmentData.status = data.status;
}
if (data.date_created !== undefined) {
fulfillmentData.date_created = data.date_created;
}
if (data.items !== undefined) {
fulfillmentData.items = data.items;
if (data.status_shipped !== undefined) {
fulfillmentData.status_shipped = data.status_shipped;
}
const config: AxiosRequestConfig = {