Compare commits
48 Commits
main-backu
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
3968fd8965 | |
|
|
c26918d4db | |
|
|
16d27179e7 | |
|
|
a556ab69bf | |
|
|
efbd318917 | |
|
|
e8424afd91 | |
|
|
5f16801f98 | |
|
|
22a13ce0b8 | |
|
|
2f57dc0d8c | |
|
|
926e531d4f | |
|
|
66a70f6209 | |
|
|
1eacee307d | |
|
|
bff03de8b0 | |
|
|
86aa5f5790 | |
|
|
52fa7d651e | |
|
|
0ea834218d | |
|
|
86fd31ac12 | |
|
|
75056db42c | |
|
|
d5384944a4 | |
|
|
cb876e8c0f | |
|
|
71b2c249be | |
|
|
b3b7ee4793 | |
|
|
b7101ac866 | |
|
|
72cd20fcd6 | |
|
|
8766cf4a4c | |
|
|
d39341d683 | |
|
|
7f04de4583 | |
|
|
bdac4860df | |
|
|
fff62d6864 | |
|
|
c75c0a614f | |
|
|
bfa03fc6a0 | |
|
|
16539b133f | |
|
|
9fc1bedb0c | |
|
|
0f79b7536a | |
|
|
fbbb86ae37 | |
|
|
56deb447b3 | |
|
|
68574dbc7a | |
|
|
eb5cb215a9 | |
|
|
ca0b5e63a7 | |
|
|
5d7e0090aa | |
|
|
ecdedcc041 | |
|
|
b2ee61e47d | |
|
|
64c1d1afe5 | |
|
|
4eb45af452 | |
|
|
a8d12a695e | |
|
|
a00a95c9a3 | |
|
|
82c8640f0c | |
|
|
cb00076bd3 |
|
|
@ -523,6 +523,23 @@
|
||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@faker-js/faker": {
|
||||||
|
"version": "10.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@faker-js/faker/-/faker-10.2.0.tgz",
|
||||||
|
"integrity": "sha512-rTXwAsIxpCqzUnZvrxVh3L0QA0NzToqWBLAhV+zDV3MIIwiQhAZHMdPCIaj5n/yADu/tyk12wIPgL6YHGXJP+g==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/fakerjs"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || ^22.13.0 || ^23.5.0 || >=24.0.0",
|
||||||
|
"npm": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@hapi/bourne": {
|
"node_modules/@hapi/bourne": {
|
||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmmirror.com/@hapi/bourne/-/bourne-3.0.0.tgz",
|
"resolved": "https://registry.npmmirror.com/@hapi/bourne/-/bourne-3.0.0.tgz",
|
||||||
|
|
|
||||||
|
|
@ -21,13 +21,16 @@ import {
|
||||||
CreateReviewDTO,
|
CreateReviewDTO,
|
||||||
CreateVariationDTO,
|
CreateVariationDTO,
|
||||||
UpdateReviewDTO,
|
UpdateReviewDTO,
|
||||||
|
OrderPaymentStatus,
|
||||||
} from '../dto/site-api.dto';
|
} from '../dto/site-api.dto';
|
||||||
import { UnifiedPaginationDTO, UnifiedSearchParamsDTO, } from '../dto/api.dto';
|
import { UnifiedPaginationDTO, UnifiedSearchParamsDTO, ShopyyGetAllOrdersParams } from '../dto/api.dto';
|
||||||
import {
|
import {
|
||||||
ShopyyAllProductQuery,
|
ShopyyAllProductQuery,
|
||||||
ShopyyCustomer,
|
ShopyyCustomer,
|
||||||
ShopyyOrder,
|
ShopyyOrder,
|
||||||
|
ShopyyOrderCreateParams,
|
||||||
ShopyyOrderQuery,
|
ShopyyOrderQuery,
|
||||||
|
ShopyyOrderUpdateParams,
|
||||||
ShopyyProduct,
|
ShopyyProduct,
|
||||||
ShopyyProductQuery,
|
ShopyyProductQuery,
|
||||||
ShopyyVariant,
|
ShopyyVariant,
|
||||||
|
|
@ -37,16 +40,17 @@ import {
|
||||||
OrderStatus,
|
OrderStatus,
|
||||||
} from '../enums/base.enum';
|
} from '../enums/base.enum';
|
||||||
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
||||||
|
import dayjs = require('dayjs');
|
||||||
export class ShopyyAdapter implements ISiteAdapter {
|
export class ShopyyAdapter implements ISiteAdapter {
|
||||||
shopyyFinancialStatusMap= {
|
shopyyFinancialStatusMap = {
|
||||||
'200': '待支付',
|
'200': '待支付',
|
||||||
'210': "支付中",
|
'210': "支付中",
|
||||||
'220':"部分支付",
|
'220': "部分支付",
|
||||||
'230':"已支付",
|
'230': "已支付",
|
||||||
'240':"支付失败",
|
'240': "支付失败",
|
||||||
'250':"部分退款",
|
'250': "部分退款",
|
||||||
'260':"已退款",
|
'260': "已退款",
|
||||||
'290':"已取消",
|
'290': "已取消",
|
||||||
}
|
}
|
||||||
constructor(private site: any, private shopyyService: ShopyyService) {
|
constructor(private site: any, private shopyyService: ShopyyService) {
|
||||||
this.mapPlatformToUnifiedCustomer = this.mapPlatformToUnifiedCustomer.bind(this);
|
this.mapPlatformToUnifiedCustomer = this.mapPlatformToUnifiedCustomer.bind(this);
|
||||||
|
|
@ -123,8 +127,8 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
async getCustomer(where: {id?: string | number,email?: string,phone?: string}): Promise<UnifiedCustomerDTO> {
|
async getCustomer(where: { id?: string | number, email?: string, phone?: string }): Promise<UnifiedCustomerDTO> {
|
||||||
if(!where.id && !where.email && !where.phone){
|
if (!where.id && !where.email && !where.phone) {
|
||||||
throw new Error('必须传入 id 或 email 或 phone')
|
throw new Error('必须传入 id 或 email 或 phone')
|
||||||
}
|
}
|
||||||
const customer = await this.shopyyService.getCustomer(this.site, where.id);
|
const customer = await this.shopyyService.getCustomer(this.site, where.id);
|
||||||
|
|
@ -153,12 +157,12 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return this.mapPlatformToUnifiedCustomer(createdCustomer);
|
return this.mapPlatformToUnifiedCustomer(createdCustomer);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateCustomer(where: {id: string | number}, data: Partial<UnifiedCustomerDTO>): Promise<UnifiedCustomerDTO> {
|
async updateCustomer(where: { id: string | number }, data: Partial<UnifiedCustomerDTO>): Promise<UnifiedCustomerDTO> {
|
||||||
const updatedCustomer = await this.shopyyService.updateCustomer(this.site, where.id, data);
|
const updatedCustomer = await this.shopyyService.updateCustomer(this.site, where.id, data);
|
||||||
return this.mapPlatformToUnifiedCustomer(updatedCustomer);
|
return this.mapPlatformToUnifiedCustomer(updatedCustomer);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteCustomer(where: {id: string | number}): Promise<boolean> {
|
async deleteCustomer(where: { id: string | number }): Promise<boolean> {
|
||||||
return await this.shopyyService.deleteCustomer(this.site, where.id);
|
return await this.shopyyService.deleteCustomer(this.site, where.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -212,12 +216,12 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return this.mapPlatformToUnifiedMedia(createdMedia);
|
return this.mapPlatformToUnifiedMedia(createdMedia);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateMedia(where: {id: string | number}, data: any): Promise<UnifiedMediaDTO> {
|
async updateMedia(where: { id: string | number }, data: any): Promise<UnifiedMediaDTO> {
|
||||||
const updatedMedia = await this.shopyyService.updateMedia(this.site, where.id, data);
|
const updatedMedia = await this.shopyyService.updateMedia(this.site, where.id, data);
|
||||||
return this.mapPlatformToUnifiedMedia(updatedMedia);
|
return this.mapPlatformToUnifiedMedia(updatedMedia);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteMedia(where: {id: string | number}): Promise<boolean> {
|
async deleteMedia(where: { id: string | number }): Promise<boolean> {
|
||||||
return await this.shopyyService.deleteMedia(this.site, where.id);
|
return await this.shopyyService.deleteMedia(this.site, where.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -227,9 +231,11 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
|
|
||||||
// ========== 订单映射方法 ==========
|
// ========== 订单映射方法 ==========
|
||||||
mapPlatformToUnifiedOrder(item: ShopyyOrder): UnifiedOrderDTO {
|
mapPlatformToUnifiedOrder(item: ShopyyOrder): UnifiedOrderDTO {
|
||||||
|
// console.log(item)
|
||||||
|
if (!item) throw new Error('订单数据不能为空')
|
||||||
// 提取账单和送货地址 如果不存在则为空对象
|
// 提取账单和送货地址 如果不存在则为空对象
|
||||||
const billing = (item as any).billing_address || {};
|
const billing = item.billing_address || {};
|
||||||
const shipping = (item as any).shipping_address || {};
|
const shipping = item.shipping_address || {};
|
||||||
|
|
||||||
// 构建账单地址对象
|
// 构建账单地址对象
|
||||||
const billingObj: UnifiedAddressDTO = {
|
const billingObj: UnifiedAddressDTO = {
|
||||||
|
|
@ -238,7 +244,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
fullname: billing.name || `${item.firstname} ${item.lastname}`.trim(),
|
fullname: billing.name || `${item.firstname} ${item.lastname}`.trim(),
|
||||||
company: billing.company || '',
|
company: billing.company || '',
|
||||||
email: item.customer_email || item.email || '',
|
email: item.customer_email || item.email || '',
|
||||||
phone: billing.phone || (item as any).telephone || '',
|
phone: billing.phone || item.telephone || '',
|
||||||
address_1: billing.address1 || item.payment_address || '',
|
address_1: billing.address1 || item.payment_address || '',
|
||||||
address_2: billing.address2 || '',
|
address_2: billing.address2 || '',
|
||||||
city: billing.city || item.payment_city || '',
|
city: billing.city || item.payment_city || '',
|
||||||
|
|
@ -269,6 +275,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
state: shipping.province || item.shipping_zone || '',
|
state: shipping.province || item.shipping_zone || '',
|
||||||
postcode: shipping.zip || item.shipping_postcode || '',
|
postcode: shipping.zip || item.shipping_postcode || '',
|
||||||
method_title: item.payment_method || '',
|
method_title: item.payment_method || '',
|
||||||
|
phone: shipping.phone || item.telephone || '',
|
||||||
country:
|
country:
|
||||||
shipping.country_name ||
|
shipping.country_name ||
|
||||||
shipping.country_code ||
|
shipping.country_code ||
|
||||||
|
|
@ -307,14 +314,14 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
};
|
};
|
||||||
|
|
||||||
const lineItems: UnifiedOrderLineItemDTO[] = (item.products || []).map(
|
const lineItems: UnifiedOrderLineItemDTO[] = (item.products || []).map(
|
||||||
(p: any) => ({
|
(product) => ({
|
||||||
id: p.id,
|
id: product.id,
|
||||||
name: p.product_title || p.name,
|
name:product.sku_value?.[0]?.value || product.product_title || product.name,
|
||||||
product_id: p.product_id,
|
product_id: product.product_id,
|
||||||
quantity: p.quantity,
|
quantity: product.quantity,
|
||||||
total: String(p.price ?? ''),
|
total: String(product.price ?? ''),
|
||||||
sku: p.sku || p.sku_code || '',
|
sku: product.sku || product.sku_code || '',
|
||||||
price: String(p.price ?? ''),
|
price: String(product.price ?? ''),
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
// 货币符号
|
// 货币符号
|
||||||
|
|
@ -337,7 +344,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
const status = this.shopyyOrderStatusMap[item.status ?? item.order_status] || OrderStatus.PENDING;
|
const status = this.shopyyOrderStatusMap[item.status ?? item.order_status] || OrderStatus.PENDING;
|
||||||
const finalcial_status = this.shopyyFinancialStatusMap[item.financial_status]
|
const finalcial_status = this.shopyyFinancialStatusMap[item.financial_status]
|
||||||
// 发货状态
|
// 发货状态
|
||||||
const fulfillment_status = this.shopyyFulfillmentStatusMap[item.fulfillment_status];
|
const fulfillment_status = this.fulfillmentStatusMap[item.fulfillment_status];
|
||||||
return {
|
return {
|
||||||
id: item.id || item.order_id,
|
id: item.id || item.order_id,
|
||||||
number: item.order_number || item.order_sn,
|
number: item.order_number || item.order_sn,
|
||||||
|
|
@ -367,7 +374,6 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
date_paid: typeof item.pay_at === 'number'
|
date_paid: typeof item.pay_at === 'number'
|
||||||
? item.pay_at === 0 ? null : new Date(item.pay_at * 1000).toISOString()
|
? item.pay_at === 0 ? null : new Date(item.pay_at * 1000).toISOString()
|
||||||
: null,
|
: null,
|
||||||
|
|
||||||
refunds: [],
|
refunds: [],
|
||||||
currency_symbol: (currencySymbols[item.currency] || '$') || '',
|
currency_symbol: (currencySymbols[item.currency] || '$') || '',
|
||||||
date_created:
|
date_created:
|
||||||
|
|
@ -387,6 +393,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
tracking_number: f.tracking_number || '',
|
tracking_number: f.tracking_number || '',
|
||||||
shipping_provider: f.tracking_company || '',
|
shipping_provider: f.tracking_company || '',
|
||||||
shipping_method: f.tracking_company || '',
|
shipping_method: f.tracking_company || '',
|
||||||
|
|
||||||
date_created: typeof f.created_at === 'number'
|
date_created: typeof f.created_at === 'number'
|
||||||
? new Date(f.created_at * 1000).toISOString()
|
? new Date(f.created_at * 1000).toISOString()
|
||||||
: f.created_at || '',
|
: f.created_at || '',
|
||||||
|
|
@ -400,11 +407,11 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
mapCreateOrderParams(data: Partial<UnifiedOrderDTO>): any {
|
mapCreateOrderParams(data: Partial<UnifiedOrderDTO>): ShopyyOrderCreateParams {
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
mapUpdateOrderParams(data: Partial<UnifiedOrderDTO>): any {
|
mapUpdateOrderParams(data: Partial<UnifiedOrderDTO>): ShopyyOrderUpdateParams {
|
||||||
// 构建 ShopYY 订单更新参数(仅包含传入的字段)
|
// 构建 ShopYY 订单更新参数(仅包含传入的字段)
|
||||||
const params: any = {};
|
const params: any = {};
|
||||||
|
|
||||||
|
|
@ -440,7 +447,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新账单地址
|
// 更新账单地址
|
||||||
params.billing_address = params.billing_address || {};
|
params.billing_address = params?.billing_address || {};
|
||||||
if (data.billing.first_name !== undefined) {
|
if (data.billing.first_name !== undefined) {
|
||||||
params.billing_address.first_name = data.billing.first_name;
|
params.billing_address.first_name = data.billing.first_name;
|
||||||
}
|
}
|
||||||
|
|
@ -534,9 +541,17 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return params;
|
return params;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getOrder(where: {id: string | number}): Promise<UnifiedOrderDTO> {
|
async getOrder(where: { id: string | number }): Promise<UnifiedOrderDTO> {
|
||||||
const data = await this.shopyyService.getOrder(this.site.id, String(where.id));
|
const data = await this.getOrders({
|
||||||
return this.mapPlatformToUnifiedOrder(data);
|
where: {
|
||||||
|
id: where.id,
|
||||||
|
},
|
||||||
|
page: 1,
|
||||||
|
per_page: 1,
|
||||||
|
})
|
||||||
|
return data.items[0] || null
|
||||||
|
// const data = await this.shopyyService.getOrder(this.site.id, String(where.id));
|
||||||
|
// return this.mapPlatformToUnifiedOrder(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getOrders(
|
async getOrders(
|
||||||
|
|
@ -557,13 +572,25 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
per_page,
|
per_page,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
mapGetAllOrdersParams(params: UnifiedSearchParamsDTO) :ShopyyGetAllOrdersParams{
|
||||||
|
|
||||||
|
const pay_at_min = dayjs(params.after || '').unix().toString();
|
||||||
|
const pay_at_max = dayjs(params.before || '').unix().toString();
|
||||||
|
|
||||||
|
return {
|
||||||
|
per_page: params.per_page || 100,
|
||||||
|
pay_at_min: pay_at_min,
|
||||||
|
pay_at_max: pay_at_max,
|
||||||
|
order_field: 'pay_at',
|
||||||
|
}
|
||||||
|
}
|
||||||
async getAllOrders(params?: UnifiedSearchParamsDTO): Promise<UnifiedOrderDTO[]> {
|
async getAllOrders(params?: UnifiedSearchParamsDTO): Promise<UnifiedOrderDTO[]> {
|
||||||
const data = await this.shopyyService.getAllOrders(this.site.id, params);
|
const normalizedParams = this.mapGetAllOrdersParams(params);
|
||||||
|
const data = await this.shopyyService.getAllOrders(this.site.id, normalizedParams);
|
||||||
return data.map(this.mapPlatformToUnifiedOrder.bind(this));
|
return data.map(this.mapPlatformToUnifiedOrder.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
async countOrders(where: Record<string,any>): Promise<number> {
|
async countOrders(where: Record<string, any>): Promise<number> {
|
||||||
// 使用最小分页只获取总数
|
// 使用最小分页只获取总数
|
||||||
const searchParams = {
|
const searchParams = {
|
||||||
where,
|
where,
|
||||||
|
|
@ -581,13 +608,13 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return this.mapPlatformToUnifiedOrder(createdOrder);
|
return this.mapPlatformToUnifiedOrder(createdOrder);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateOrder(where: {id: string | number}, data: Partial<UnifiedOrderDTO>): Promise<boolean> {
|
async updateOrder(where: { id: string | number }, data: Partial<UnifiedOrderDTO>): Promise<boolean> {
|
||||||
// 使用映射方法转换参数
|
// 使用映射方法转换参数
|
||||||
const requestParams = this.mapUpdateOrderParams(data);
|
const requestParams = this.mapUpdateOrderParams(data);
|
||||||
return await this.shopyyService.updateOrder(this.site, String(where.id), requestParams);
|
return await this.shopyyService.updateOrder(this.site, String(where.id), requestParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteOrder(where: {id: string | number}): Promise<boolean> {
|
async deleteOrder(where: { id: string | number }): Promise<boolean> {
|
||||||
return await this.shopyyService.deleteOrder(this.site, where.id);
|
return await this.shopyyService.deleteOrder(this.site, where.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -697,7 +724,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
name: item.name || item.title,
|
name: item.name || item.title,
|
||||||
type: String(item.product_type ?? ''),
|
type: String(item.product_type ?? ''),
|
||||||
status: mapProductStatus(item.status),
|
status: mapProductStatus(item.status),
|
||||||
sku: item.variant?.sku || '',
|
sku: item.variant?.sku || item.variant?.sku_code || '',
|
||||||
regular_price: String(item.variant?.price ?? ''),
|
regular_price: String(item.variant?.price ?? ''),
|
||||||
sale_price: String(item.special_price ?? ''),
|
sale_price: String(item.special_price ?? ''),
|
||||||
price: String(item.price ?? ''),
|
price: String(item.price ?? ''),
|
||||||
|
|
@ -726,7 +753,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
name: c.title || '',
|
name: c.title || '',
|
||||||
})),
|
})),
|
||||||
variations: item.variants?.map(this.mapPlatformToUnifiedVariation.bind(this)) || [],
|
variations: item.variants?.map(this.mapPlatformToUnifiedVariation.bind(this)) || [],
|
||||||
permalink: `${this.site.websiteUrl}/products/${item.handle}`,
|
permalink: `${this.site.websiteUrl}/products/${item.handle}`,
|
||||||
date_created:
|
date_created:
|
||||||
typeof item.created_at === 'number'
|
typeof item.created_at === 'number'
|
||||||
? new Date(item.created_at * 1000).toISOString()
|
? new Date(item.created_at * 1000).toISOString()
|
||||||
|
|
@ -862,8 +889,8 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return params;
|
return params;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getProduct(where: {id?: string | number, sku?: string}): Promise<UnifiedProductDTO> {
|
async getProduct(where: { id?: string | number, sku?: string }): Promise<UnifiedProductDTO> {
|
||||||
if(!where.id && !where.sku){
|
if (!where.id && !where.sku) {
|
||||||
throw new Error('必须传入 id 或 sku')
|
throw new Error('必须传入 id 或 sku')
|
||||||
}
|
}
|
||||||
if (where.id) {
|
if (where.id) {
|
||||||
|
|
@ -899,11 +926,11 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
per_page,
|
per_page,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
mapAllProductParams(params: UnifiedSearchParamsDTO): Partial<ShopyyAllProductQuery>{
|
mapAllProductParams(params: UnifiedSearchParamsDTO): Partial<ShopyyAllProductQuery> {
|
||||||
const mapped = {
|
const mapped = {
|
||||||
...params.where,
|
...params.where,
|
||||||
} as any
|
} as any
|
||||||
if(params.per_page){mapped.limit = params.per_page}
|
if (params.per_page) { mapped.limit = params.per_page }
|
||||||
return mapped
|
return mapped
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -917,7 +944,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
null,
|
null,
|
||||||
requestParams
|
requestParams
|
||||||
);
|
);
|
||||||
if(response.code !==0){
|
if (response.code !== 0) {
|
||||||
throw new Error(response.msg || '获取产品列表失败')
|
throw new Error(response.msg || '获取产品列表失败')
|
||||||
}
|
}
|
||||||
const { data = [] } = response;
|
const { data = [] } = response;
|
||||||
|
|
@ -932,7 +959,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return this.mapPlatformToUnifiedProduct(res);
|
return this.mapPlatformToUnifiedProduct(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateProduct(where: {id?: string | number, sku?: string}, data: Partial<UnifiedProductDTO>): Promise<boolean> {
|
async updateProduct(where: { id?: string | number, sku?: string }, data: Partial<UnifiedProductDTO>): Promise<boolean> {
|
||||||
let productId: string;
|
let productId: string;
|
||||||
if (where.id) {
|
if (where.id) {
|
||||||
productId = String(where.id);
|
productId = String(where.id);
|
||||||
|
|
@ -949,7 +976,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteProduct(where: {id?: string | number, sku?: string}): Promise<boolean> {
|
async deleteProduct(where: { id?: string | number, sku?: string }): Promise<boolean> {
|
||||||
let productId: string | number;
|
let productId: string | number;
|
||||||
if (where.id) {
|
if (where.id) {
|
||||||
productId = where.id;
|
productId = where.id;
|
||||||
|
|
@ -968,7 +995,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
// 通过sku获取产品详情的私有方法
|
// 通过sku获取产品详情的私有方法
|
||||||
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)
|
console.log('getProductBySku', response)
|
||||||
const product = response?.[0]
|
const product = response?.[0]
|
||||||
if (!product) {
|
if (!product) {
|
||||||
|
|
@ -1032,12 +1059,12 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return this.mapPlatformToUnifiedReview(createdReview);
|
return this.mapPlatformToUnifiedReview(createdReview);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateReview(where: {id: string | number}, data: any): Promise<UnifiedReviewDTO> {
|
async updateReview(where: { id: string | number }, data: any): Promise<UnifiedReviewDTO> {
|
||||||
const updatedReview = await this.shopyyService.updateReview(this.site, where.id, data);
|
const updatedReview = await this.shopyyService.updateReview(this.site, where.id, data);
|
||||||
return this.mapPlatformToUnifiedReview(updatedReview);
|
return this.mapPlatformToUnifiedReview(updatedReview);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteReview(where: {id: string | number}): Promise<boolean> {
|
async deleteReview(where: { id: string | number }): Promise<boolean> {
|
||||||
return await this.shopyyService.deleteReview(this.site, where.id);
|
return await this.shopyyService.deleteReview(this.site, where.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1099,10 +1126,11 @@ 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.sku || '',
|
name: variant.title || '',
|
||||||
sku: variant.sku || '',
|
sku: variant.sku || variant.sku_code || '',
|
||||||
regular_price: String(variant.price ?? ''),
|
regular_price: String(variant.price ?? ''),
|
||||||
sale_price: String(variant.special_price ?? ''),
|
sale_price: String(variant.special_price ?? ''),
|
||||||
price: String(variant.price ?? ''),
|
price: String(variant.price ?? ''),
|
||||||
|
|
@ -1193,7 +1221,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
async getWebhook(where: {id: string | number}): Promise<UnifiedWebhookDTO> {
|
async getWebhook(where: { id: string | number }): Promise<UnifiedWebhookDTO> {
|
||||||
const webhook = await this.shopyyService.getWebhook(this.site, where.id);
|
const webhook = await this.shopyyService.getWebhook(this.site, where.id);
|
||||||
return this.mapPlatformToUnifiedWebhook(webhook);
|
return this.mapPlatformToUnifiedWebhook(webhook);
|
||||||
}
|
}
|
||||||
|
|
@ -1219,12 +1247,12 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
return this.mapPlatformToUnifiedWebhook(createdWebhook);
|
return this.mapPlatformToUnifiedWebhook(createdWebhook);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateWebhook(where: {id: string | number}, data: UpdateWebhookDTO): Promise<UnifiedWebhookDTO> {
|
async updateWebhook(where: { id: string | number }, data: UpdateWebhookDTO): Promise<UnifiedWebhookDTO> {
|
||||||
const updatedWebhook = await this.shopyyService.updateWebhook(this.site, where.id, data);
|
const updatedWebhook = await this.shopyyService.updateWebhook(this.site, where.id, data);
|
||||||
return this.mapPlatformToUnifiedWebhook(updatedWebhook);
|
return this.mapPlatformToUnifiedWebhook(updatedWebhook);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteWebhook(where: {id: string | number}): Promise<boolean> {
|
async deleteWebhook(where: { id: string | number }): Promise<boolean> {
|
||||||
return await this.shopyyService.deleteWebhook(this.site, where.id);
|
return await this.shopyyService.deleteWebhook(this.site, where.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1274,7 +1302,7 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
page,
|
page,
|
||||||
limit,
|
limit,
|
||||||
}
|
}
|
||||||
if(params.orderBy){
|
if (params.orderBy) {
|
||||||
const [field, dir] = Object.entries(params.orderBy)[0];
|
const [field, dir] = Object.entries(params.orderBy)[0];
|
||||||
query.order_by = dir === 'desc' ? 'desc' : 'asc';
|
query.order_by = dir === 'desc' ? 'desc' : 'asc';
|
||||||
query.order_field = field
|
query.order_field = field
|
||||||
|
|
@ -1284,24 +1312,24 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
|
|
||||||
// 映射产品状态: publish -> 1, draft -> 0
|
// 映射产品状态: publish -> 1, draft -> 0
|
||||||
mapStatus = (status: string) => {
|
mapStatus = (status: string) => {
|
||||||
return status === 'publish' ? 1 : 0;
|
return status === 'publish' ? 1 : 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
// 映射库存状态: instock -> 1, outofstock -> 0
|
// 映射库存状态: instock -> 1, outofstock -> 0
|
||||||
mapStockStatus = (stockStatus: string) => {
|
mapStockStatus = (stockStatus: string) => {
|
||||||
return stockStatus === 'instock' ? 1 : 0;
|
return stockStatus === 'instock' ? 1 : 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
shopyyOrderStatusMap = {//订单状态 100 未完成;110 待处理;180 已完成(确认收货); 190 取消;
|
shopyyOrderStatusMap = {//订单状态 100 未完成;110 待处理;180 已完成(确认收货); 190 取消;
|
||||||
[100]: OrderStatus.PENDING, // 100 未完成 转为 pending
|
[100]: OrderStatus.PENDING, // 100 未完成 转为 pending
|
||||||
[110]: OrderStatus.PROCESSING, // 110 待处理 转为 processing
|
[110]: OrderStatus.PROCESSING, // 110 待处理 转为 processing
|
||||||
// 已发货
|
// 已发货
|
||||||
|
|
||||||
[180]: OrderStatus.COMPLETED, // 180 已完成(确认收货) 转为 completed
|
[180]: OrderStatus.COMPLETED, // 180 已完成(确认收货) 转为 completed
|
||||||
[190]: OrderStatus.CANCEL // 190 取消 转为 cancelled
|
[190]: OrderStatus.CANCEL // 190 取消 转为 cancelled
|
||||||
}
|
}
|
||||||
|
// 物流状态 300 未发货;310 部分发货;320 已发货;330(确认收货)
|
||||||
shopyyFulfillmentStatusMap = {
|
fulfillmentStatusMap = {
|
||||||
// 未发货
|
// 未发货
|
||||||
'300': OrderFulfillmentStatus.PENDING,
|
'300': OrderFulfillmentStatus.PENDING,
|
||||||
// 部分发货
|
// 部分发货
|
||||||
|
|
@ -1312,4 +1340,23 @@ export class ShopyyAdapter implements ISiteAdapter {
|
||||||
'330': OrderFulfillmentStatus.CANCELLED,
|
'330': OrderFulfillmentStatus.CANCELLED,
|
||||||
// 确认发货
|
// 确认发货
|
||||||
}
|
}
|
||||||
|
// 支付状态 200 待支付;210 支付中;220 部分支付;230 已支付;240 支付失败;250 部分退款;260 已退款 ;290 已取消;
|
||||||
|
financialStatusMap = {
|
||||||
|
// 待支付
|
||||||
|
'200': OrderPaymentStatus.PENDING,
|
||||||
|
// 支付中
|
||||||
|
'210': OrderPaymentStatus.PAYING,
|
||||||
|
// 部分支付
|
||||||
|
'220': OrderPaymentStatus.PARTIALLY_PAID,
|
||||||
|
// 已支付
|
||||||
|
'230': OrderPaymentStatus.PAID,
|
||||||
|
// 支付失败
|
||||||
|
'240': OrderPaymentStatus.FAILED,
|
||||||
|
// 部分退款
|
||||||
|
'250': OrderPaymentStatus.PARTIALLY_REFUNDED,
|
||||||
|
// 已退款
|
||||||
|
'260': OrderPaymentStatus.REFUNDED,
|
||||||
|
// 已取消
|
||||||
|
'290': OrderPaymentStatus.CANCELLED,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -17,6 +17,7 @@ import {
|
||||||
UnifiedVariationPaginationDTO,
|
UnifiedVariationPaginationDTO,
|
||||||
CreateReviewDTO,
|
CreateReviewDTO,
|
||||||
UpdateReviewDTO,
|
UpdateReviewDTO,
|
||||||
|
FulfillmentDTO,
|
||||||
} from '../dto/site-api.dto';
|
} from '../dto/site-api.dto';
|
||||||
import { UnifiedPaginationDTO, UnifiedSearchParamsDTO } from '../dto/api.dto';
|
import { UnifiedPaginationDTO, UnifiedSearchParamsDTO } from '../dto/api.dto';
|
||||||
import {
|
import {
|
||||||
|
|
@ -28,10 +29,15 @@ import {
|
||||||
WooWebhook,
|
WooWebhook,
|
||||||
WooOrderSearchParams,
|
WooOrderSearchParams,
|
||||||
WooProductSearchParams,
|
WooProductSearchParams,
|
||||||
|
WpMediaGetListParams,
|
||||||
|
WooFulfillment,
|
||||||
|
MetaDataFulfillment,
|
||||||
} from '../dto/woocommerce.dto';
|
} from '../dto/woocommerce.dto';
|
||||||
import { Site } from '../entity/site.entity';
|
import { Site } from '../entity/site.entity';
|
||||||
import { WPService } from '../service/wp.service';
|
import { WPService } from '../service/wp.service';
|
||||||
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
||||||
|
import { toArray, toNumber } from '../utils/trans.util';
|
||||||
|
import dayjs = require('dayjs');
|
||||||
|
|
||||||
export class WooCommerceAdapter implements ISiteAdapter {
|
export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
// 构造函数接收站点配置与服务实例
|
// 构造函数接收站点配置与服务实例
|
||||||
|
|
@ -249,13 +255,25 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
date_modified: item.date_modified ?? item.modified,
|
date_modified: item.date_modified ?? item.modified,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
mapMediaSearchParams(params: UnifiedSearchParamsDTO): Partial<WpMediaGetListParams> {
|
||||||
|
const page = params.page
|
||||||
|
const per_page = Number(params.per_page ?? 20);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...params.where,
|
||||||
|
page,
|
||||||
|
per_page,
|
||||||
|
// orderby,
|
||||||
|
// order,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// 媒体操作方法
|
// 媒体操作方法
|
||||||
async getMedia(params: UnifiedSearchParamsDTO): Promise<UnifiedPaginationDTO<UnifiedMediaDTO>> {
|
async getMedia(params: UnifiedSearchParamsDTO): Promise<UnifiedPaginationDTO<UnifiedMediaDTO>> {
|
||||||
// 获取媒体列表并映射为统一媒体DTO集合
|
// 获取媒体列表并映射为统一媒体DTO集合
|
||||||
const { items, total, totalPages, page, per_page } = await this.wpService.fetchMediaPaged(
|
const { items, total, totalPages, page, per_page } = await this.wpService.fetchMediaPaged(
|
||||||
this.site,
|
this.site,
|
||||||
params
|
this.mapMediaSearchParams(params)
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
items: items.map(this.mapPlatformToUnifiedMedia.bind(this)),
|
items: items.map(this.mapPlatformToUnifiedMedia.bind(this)),
|
||||||
|
|
@ -277,12 +295,12 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
throw new Error('Method not implemented.');
|
throw new Error('Method not implemented.');
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateMedia(where: {id: string | number}, data: any): Promise<any> {
|
async updateMedia(where: { id: string | number }, data: any): Promise<any> {
|
||||||
// 更新媒体信息
|
// 更新媒体信息
|
||||||
return await this.wpService.updateMedia(Number(this.site.id), Number(where.id), data);
|
return await this.wpService.updateMedia(Number(this.site.id), Number(where.id), data);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteMedia(where: {id: string | number}): Promise<boolean> {
|
async deleteMedia(where: { id: string | number }): Promise<boolean> {
|
||||||
// 删除媒体资源
|
// 删除媒体资源
|
||||||
await this.wpService.deleteMedia(Number(this.site.id), Number(where.id), true);
|
await this.wpService.deleteMedia(Number(this.site.id), Number(where.id), true);
|
||||||
return true;
|
return true;
|
||||||
|
|
@ -317,22 +335,11 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
// }
|
// }
|
||||||
const mapped: any = {
|
const mapped: any = {
|
||||||
...(params.search ? { search: params.search } : {}),
|
...(params.search ? { search: params.search } : {}),
|
||||||
// ...(orderBy ? { orderBy } : {}),
|
|
||||||
page,
|
page,
|
||||||
per_page,
|
per_page,
|
||||||
};
|
};
|
||||||
|
|
||||||
const toArray = (value: any): any[] => {
|
|
||||||
if (Array.isArray(value)) return value;
|
|
||||||
if (value === undefined || value === null) return [];
|
|
||||||
return String(value).split(',').map(v => v.trim()).filter(Boolean);
|
|
||||||
};
|
|
||||||
|
|
||||||
const toNumber = (value: any): number | undefined => {
|
|
||||||
if (value === undefined || value === null || value === '') return undefined;
|
|
||||||
const n = Number(value);
|
|
||||||
return Number.isFinite(n) ? n : undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
// 时间过滤参数
|
// 时间过滤参数
|
||||||
if (where.after ?? where.date_created_after ?? where.created_after) mapped.after = String(where.after ?? where.date_created_after ?? where.created_after);
|
if (where.after ?? where.date_created_after ?? where.created_after) mapped.after = String(where.after ?? where.date_created_after ?? where.created_after);
|
||||||
|
|
@ -343,8 +350,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
|
|
||||||
// 集合过滤参数
|
// 集合过滤参数
|
||||||
if (where.exclude) mapped.exclude = toArray(where.exclude);
|
if (where.exclude) mapped.exclude = toArray(where.exclude);
|
||||||
if (where.include) mapped.include = toArray(where.include);
|
if (where.ids || where.number || where.id || where.include) mapped.include = [...new Set([where.number, where.id, ...toArray(where.ids), ...toArray(where.include)])].filter(Boolean);
|
||||||
if (where.ids) mapped.include = toArray(where.ids);
|
|
||||||
if (toNumber(where.offset) !== undefined) mapped.offset = Number(where.offset);
|
if (toNumber(where.offset) !== undefined) mapped.offset = Number(where.offset);
|
||||||
if (where.parent ?? where.parentId) mapped.parent = toArray(where.parent ?? where.parentId);
|
if (where.parent ?? where.parentId) mapped.parent = toArray(where.parent ?? where.parentId);
|
||||||
if (where.parent_exclude ?? where.parentExclude) mapped.parent_exclude = toArray(where.parent_exclude ?? where.parentExclude);
|
if (where.parent_exclude ?? where.parentExclude) mapped.parent_exclude = toArray(where.parent_exclude ?? where.parentExclude);
|
||||||
|
|
@ -393,16 +399,17 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
mapPlatformToUnifiedOrder(item: WooOrder): UnifiedOrderDTO {
|
mapPlatformToUnifiedOrder(item: WooOrder): UnifiedOrderDTO {
|
||||||
// 将 WooCommerce 订单数据映射为统一订单DTO
|
// 将 WooCommerce 订单数据映射为统一订单DTO
|
||||||
// 包含账单地址与收货地址以及创建与更新时间
|
// 包含账单地址与收货地址以及创建与更新时间
|
||||||
|
|
||||||
// 映射物流追踪信息,将后端格式转换为前端期望的格式
|
// 映射物流追踪信息,将后端格式转换为前端期望的格式
|
||||||
const fulfillments = (item.fulfillments || []).map((track: any) => ({
|
const metaFulfillments: MetaDataFulfillment[] = item.meta_data?.find?.(_meta => _meta.key === "_wc_shipment_tracking_items")?.value || []
|
||||||
tracking_number: track.tracking_number || '',
|
const fulfillments = metaFulfillments.map((track) => {
|
||||||
shipping_provider: track.shipping_provider || '',
|
return ({
|
||||||
shipping_method: track.shipping_method || '',
|
tracking_id: track.tracking_id,
|
||||||
status: track.status || '',
|
tracking_number: track.tracking_number,
|
||||||
date_created: track.date_created || '',
|
tracking_product_code: track.tracking_product_code,
|
||||||
items: track.items || [],
|
shipping_provider: track.tracking_provider,
|
||||||
}));
|
date_created: dayjs(track.date_shipped).toString(),
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: item.id,
|
id: item.id,
|
||||||
|
|
@ -444,7 +451,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 订单操作方法
|
// 订单操作方法
|
||||||
async getOrder(where: {id: string | number}): Promise<UnifiedOrderDTO> {
|
async getOrder(where: { id: string | number }): Promise<UnifiedOrderDTO> {
|
||||||
// 获取单个订单详情
|
// 获取单个订单详情
|
||||||
const api = this.wpService.createApi(this.site, 'wc/v3');
|
const api = this.wpService.createApi(this.site, 'wc/v3');
|
||||||
const res = await api.get(`orders/${where.id}`);
|
const res = await api.get(`orders/${where.id}`);
|
||||||
|
|
@ -455,30 +462,8 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
const requestParams = this.mapOrderSearchParams(params);
|
const requestParams = this.mapOrderSearchParams(params);
|
||||||
const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged<any>(this.site, 'orders', requestParams);
|
const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged<any>(this.site, 'orders', requestParams);
|
||||||
|
|
||||||
// 并行获取所有订单的履行信息
|
|
||||||
const ordersWithFulfillments = await Promise.all(
|
|
||||||
items.map(async (order: any) => {
|
|
||||||
try {
|
|
||||||
// 获取订单的履行信息
|
|
||||||
const fulfillments = await this.getOrderFulfillments(order.id);
|
|
||||||
// 将履行信息添加到订单对象中
|
|
||||||
return {
|
|
||||||
...order,
|
|
||||||
fulfillments: fulfillments || []
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
// 如果获取履行信息失败,仍然返回订单,只是履行信息为空数组
|
|
||||||
console.error(`获取订单 ${order.id} 的履行信息失败:`, error);
|
|
||||||
return {
|
|
||||||
...order,
|
|
||||||
fulfillments: []
|
|
||||||
};
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
items: ordersWithFulfillments.map(this.mapPlatformToUnifiedOrder),
|
items: items.map(this.mapPlatformToUnifiedOrder),
|
||||||
total,
|
total,
|
||||||
totalPages,
|
totalPages,
|
||||||
page,
|
page,
|
||||||
|
|
@ -512,12 +497,12 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
return this.mapPlatformToUnifiedOrder(res.data);
|
return this.mapPlatformToUnifiedOrder(res.data);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateOrder(where: {id: string | number}, data: Partial<UnifiedOrderDTO>): Promise<boolean> {
|
async updateOrder(where: { id: string | number }, data: Partial<UnifiedOrderDTO>): Promise<boolean> {
|
||||||
// 更新订单并返回布尔结果
|
// 更新订单并返回布尔结果
|
||||||
return await this.wpService.updateOrder(this.site, String(where.id), data as any);
|
return await this.wpService.updateOrder(this.site, String(where.id), data as any);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteOrder(where: {id: string | number}): Promise<boolean> {
|
async deleteOrder(where: { id: string | number }): Promise<boolean> {
|
||||||
// 删除订单
|
// 删除订单
|
||||||
const api = this.wpService.createApi(this.site, 'wc/v3');
|
const api = this.wpService.createApi(this.site, 'wc/v3');
|
||||||
await api.delete(`orders/${where.id}`, { force: true });
|
await api.delete(`orders/${where.id}`, { force: true });
|
||||||
|
|
@ -528,54 +513,25 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
return await this.wpService.getFulfillments(this.site, String(orderId));
|
return await this.wpService.getFulfillments(this.site, String(orderId));
|
||||||
}
|
}
|
||||||
|
|
||||||
async createOrderFulfillment(orderId: string | number, data: {
|
async createOrderFulfillment(orderId: string | number, data: FulfillmentDTO): Promise<any> {
|
||||||
tracking_number: string;
|
const shipmentData: Partial<WooFulfillment> = {
|
||||||
shipping_provider: string;
|
tracking_provider: data.shipping_provider,
|
||||||
shipping_method?: string;
|
|
||||||
status?: string;
|
|
||||||
date_created?: string;
|
|
||||||
items?: Array<{
|
|
||||||
order_item_id: number;
|
|
||||||
quantity: number;
|
|
||||||
}>;
|
|
||||||
}): Promise<any> {
|
|
||||||
const shipmentData: any = {
|
|
||||||
shipping_provider: data.shipping_provider,
|
|
||||||
tracking_number: data.tracking_number,
|
tracking_number: data.tracking_number,
|
||||||
};
|
data_sipped: data.date_created,
|
||||||
|
// items: data.items,
|
||||||
if (data.shipping_method) {
|
|
||||||
shipmentData.shipping_method = data.shipping_method;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.status) {
|
|
||||||
shipmentData.status = data.status;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.date_created) {
|
|
||||||
shipmentData.date_created = data.date_created;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.items) {
|
|
||||||
shipmentData.items = data.items;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await this.wpService.createFulfillment(this.site, String(orderId), shipmentData);
|
const response = await this.wpService.createFulfillment(this.site, String(orderId), shipmentData);
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateOrderFulfillment(orderId: string | number, fulfillmentId: string, data: {
|
async updateOrderFulfillment(orderId: string | number, fulfillmentId: string, data: FulfillmentDTO): Promise<any> {
|
||||||
tracking_number?: string;
|
const shipmentData: Partial<WooFulfillment> = {
|
||||||
shipping_provider?: string;
|
tracking_provider: data.shipping_provider,
|
||||||
shipping_method?: string;
|
tracking_number: data.tracking_number,
|
||||||
status?: string;
|
data_sipped: data.date_created,
|
||||||
date_created?: string;
|
// items: data.items,
|
||||||
items?: Array<{
|
}
|
||||||
order_item_id: number;
|
return await this.wpService.updateFulfillment(this.site, String(orderId), fulfillmentId, shipmentData);
|
||||||
quantity: number;
|
|
||||||
}>;
|
|
||||||
}): Promise<any> {
|
|
||||||
return await this.wpService.updateFulfillment(this.site, String(orderId), fulfillmentId, data);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteOrderFulfillment(orderId: string | number, fulfillmentId: string): Promise<boolean> {
|
async deleteOrderFulfillment(orderId: string | number, fulfillmentId: string): Promise<boolean> {
|
||||||
|
|
@ -717,8 +673,8 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
return mapped;
|
return mapped;
|
||||||
}
|
}
|
||||||
|
|
||||||
mapCreateProductParams(data: Partial<UnifiedProductDTO>):Partial<WooProduct> {
|
mapCreateProductParams(data: Partial<UnifiedProductDTO>): Partial<WooProduct> {
|
||||||
const {id,...mapped}= this.mapUnifiedToPlatformProduct(data);
|
const { id, ...mapped } = this.mapUnifiedToPlatformProduct(data);
|
||||||
// 创建不带 id
|
// 创建不带 id
|
||||||
return mapped
|
return mapped
|
||||||
}
|
}
|
||||||
|
|
@ -871,28 +827,28 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// 判断是否是这个站点的sku
|
// 判断是否是这个站点的sku
|
||||||
isSiteSkuThisSite(sku: string,){
|
isSiteSkuThisSite(sku: string,) {
|
||||||
return sku.startsWith(this.site.skuPrefix+'-');
|
return sku.startsWith(this.site.skuPrefix + '-');
|
||||||
}
|
}
|
||||||
async getProduct(where: Partial<Pick<UnifiedProductDTO, 'id' | 'sku'>>): Promise<UnifiedProductDTO>{
|
async getProduct(where: Partial<Pick<UnifiedProductDTO, 'id' | 'sku'>>): Promise<UnifiedProductDTO> {
|
||||||
const { id, sku } = where;
|
const { id, sku } = where;
|
||||||
if(id) return this.getProductById(id);
|
if (id) return this.getProductById(id);
|
||||||
if(sku) return this.getProductBySku(sku);
|
if (sku) return this.getProductBySku(sku);
|
||||||
throw new Error('必须提供id或sku参数');
|
throw new Error('必须提供id或sku参数');
|
||||||
}
|
}
|
||||||
async getProductBySku(sku: string){
|
async getProductBySku(sku: string) {
|
||||||
// const api = this.wpService.createApi(this.site, 'wc/v3');
|
// const api = this.wpService.createApi(this.site, 'wc/v3');
|
||||||
// const res = await api.get(`products`,{
|
// const res = await api.get(`products`,{
|
||||||
// sku
|
// sku
|
||||||
// });
|
// });
|
||||||
// const product = res.data[0];
|
// const product = res.data[0];
|
||||||
const res = await this.wpService.getProducts(this.site,{
|
const res = await this.wpService.getProducts(this.site, {
|
||||||
sku,
|
sku,
|
||||||
page:1,
|
page: 1,
|
||||||
per_page:1,
|
per_page: 1,
|
||||||
});
|
});
|
||||||
const product = res?.items?.[0];
|
const product = res?.items?.[0];
|
||||||
if(!product) return null
|
if (!product) return null
|
||||||
return this.mapPlatformToUnifiedProduct(product);
|
return this.mapPlatformToUnifiedProduct(product);
|
||||||
}
|
}
|
||||||
// 产品操作方法
|
// 产品操作方法
|
||||||
|
|
@ -1003,7 +959,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
async updateProduct(where: Partial<Pick<UnifiedProductDTO, 'id' | 'sku'>>, data: Partial<UnifiedProductDTO>): Promise<boolean> {
|
async updateProduct(where: Partial<Pick<UnifiedProductDTO, 'id' | 'sku'>>, data: Partial<UnifiedProductDTO>): Promise<boolean> {
|
||||||
// 更新产品并返回统一产品DTO
|
// 更新产品并返回统一产品DTO
|
||||||
const product = await this.getProduct(where);
|
const product = await this.getProduct(where);
|
||||||
if(!product){
|
if (!product) {
|
||||||
throw new Error('产品不存在');
|
throw new Error('产品不存在');
|
||||||
}
|
}
|
||||||
const updateData = this.mapUpdateProductParams(data);
|
const updateData = this.mapUpdateProductParams(data);
|
||||||
|
|
@ -1014,7 +970,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
async deleteProduct(where: Partial<Pick<UnifiedProductDTO, 'id' | 'sku'>>): Promise<boolean> {
|
async deleteProduct(where: Partial<Pick<UnifiedProductDTO, 'id' | 'sku'>>): Promise<boolean> {
|
||||||
// 删除产品
|
// 删除产品
|
||||||
const product = await this.getProduct(where);
|
const product = await this.getProduct(where);
|
||||||
if(!product){
|
if (!product) {
|
||||||
throw new Error('产品不存在');
|
throw new Error('产品不存在');
|
||||||
}
|
}
|
||||||
const api = this.wpService.createApi(this.site, 'wc/v3');
|
const api = this.wpService.createApi(this.site, 'wc/v3');
|
||||||
|
|
@ -1419,12 +1375,12 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
const result = await this.wpService.getWebhooks(this.site, params);
|
const result = await this.wpService.getWebhooks(this.site, params);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
items: (result.items as WooWebhook[]).map(this.mapPlatformToUnifiedWebhook),
|
items: (result.items as WooWebhook[]).map(this.mapPlatformToUnifiedWebhook),
|
||||||
total: result.total,
|
total: result.total,
|
||||||
page: Number(params.page || 1),
|
page: Number(params.page || 1),
|
||||||
per_page: Number(params.per_page || 20),
|
per_page: Number(params.per_page || 20),
|
||||||
totalPages: result.totalPages,
|
totalPages: result.totalPages,
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(`Failed to get webhooks: ${error instanceof Error ? error.message : String(error)}`);
|
throw new Error(`Failed to get webhooks: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
}
|
}
|
||||||
|
|
@ -1442,7 +1398,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取单个 webhook 详情
|
// 获取单个 webhook 详情
|
||||||
async getWebhook(where: {id: string | number}): Promise<UnifiedWebhookDTO> {
|
async getWebhook(where: { id: string | number }): Promise<UnifiedWebhookDTO> {
|
||||||
try {
|
try {
|
||||||
const result = await this.wpService.getWebhook(this.site, where.id);
|
const result = await this.wpService.getWebhook(this.site, where.id);
|
||||||
return this.mapPlatformToUnifiedWebhook(result as WooWebhook);
|
return this.mapPlatformToUnifiedWebhook(result as WooWebhook);
|
||||||
|
|
|
||||||
|
|
@ -7,19 +7,25 @@ export default {
|
||||||
// dataSource: {
|
// dataSource: {
|
||||||
// default: {
|
// default: {
|
||||||
// host: '13.212.62.127',
|
// host: '13.212.62.127',
|
||||||
|
// port: '3306',
|
||||||
// username: 'root',
|
// username: 'root',
|
||||||
// password: 'Yoone!@.2025',
|
// password: 'Yoone!@.2025',
|
||||||
|
// database: 'inventory_v2',
|
||||||
|
// synchronize: true,
|
||||||
|
// logging: true,
|
||||||
// },
|
// },
|
||||||
// },
|
// },
|
||||||
// },
|
// },
|
||||||
typeorm: {
|
typeorm: {
|
||||||
dataSource: {
|
dataSource: {
|
||||||
default: {
|
default: {
|
||||||
host: 'localhost',
|
host: '13.212.62.127',
|
||||||
port: "23306",
|
port: "3306",
|
||||||
username: 'root',
|
username: 'root',
|
||||||
password: '12345678',
|
password: 'Yoone!@.2025',
|
||||||
database: 'inventory_v2',
|
database: 'inventory_v2',
|
||||||
|
synchronize: true,
|
||||||
|
logging: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -118,8 +118,7 @@ export class MainConfiguration {
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.logger.info('正在检查数据库是否存在...');
|
this.logger.info(`正在检查数据库是否存在...`+ JSON.stringify(typeormConfig));
|
||||||
|
|
||||||
// 初始化临时数据源
|
// 初始化临时数据源
|
||||||
await tempDataSource.initialize();
|
await tempDataSource.initialize();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,7 @@ export class DictController {
|
||||||
// 从上传的文件列表中获取第一个文件
|
// 从上传的文件列表中获取第一个文件
|
||||||
const file = files[0];
|
const file = files[0];
|
||||||
// 调用服务层方法处理XLSX文件
|
// 调用服务层方法处理XLSX文件
|
||||||
const result = await this.dictService.importDictsFromXLSX(file.data);
|
const result = await this.dictService.importDictsFromTable(file.data);
|
||||||
// 返回导入结果
|
// 返回导入结果
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -79,6 +79,31 @@ export class ProductController {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: '成功返回分组后的产品列表',
|
||||||
|
schema: {
|
||||||
|
type: 'object',
|
||||||
|
additionalProperties: {
|
||||||
|
type: 'array',
|
||||||
|
items: {
|
||||||
|
$ref: '#/components/schemas/Product',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@Get('/list/grouped')
|
||||||
|
async getProductListGrouped(
|
||||||
|
@Query() query: UnifiedSearchParamsDTO<ProductWhereFilter>
|
||||||
|
): Promise<any> {
|
||||||
|
try {
|
||||||
|
const data = await this.productService.getProductListGrouped(query);
|
||||||
|
return successResponse(data);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('获取分组产品列表失败', error);
|
||||||
|
return errorResponse(error?.message || error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ApiOkResponse({ type: ProductRes })
|
@ApiOkResponse({ type: ProductRes })
|
||||||
@Post('/')
|
@Post('/')
|
||||||
async createProduct(@Body() productData: CreateProductDTO) {
|
async createProduct(@Body() productData: CreateProductDTO) {
|
||||||
|
|
@ -117,7 +142,7 @@ export class ProductController {
|
||||||
const file = files?.[0];
|
const file = files?.[0];
|
||||||
if (!file) return errorResponse('未接收到上传文件');
|
if (!file) return errorResponse('未接收到上传文件');
|
||||||
|
|
||||||
const result = await this.productService.importProductsCSV(file);
|
const result = await this.productService.importProductsFromTable(file);
|
||||||
return successResponse(result);
|
return successResponse(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return errorResponse(error?.message || error);
|
return errorResponse(error?.message || error);
|
||||||
|
|
@ -750,4 +775,31 @@ export class ProductController {
|
||||||
return errorResponse(error?.message || error);
|
return errorResponse(error?.message || error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 获取所有产品,支持按品牌过滤
|
||||||
|
@ApiOkResponse({ description: '获取所有产品', type: ProductListRes })
|
||||||
|
@Get('/all')
|
||||||
|
async getAllProducts(@Query('brand') brand?: string) {
|
||||||
|
try {
|
||||||
|
const data = await this.productService.getAllProducts(brand);
|
||||||
|
return successResponse(data);
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error?.message || error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取按属性分组的产品,默认按强度划分
|
||||||
|
@ApiOkResponse({ description: '获取按属性分组的产品' })
|
||||||
|
@Get('/grouped')
|
||||||
|
async getGroupedProducts(
|
||||||
|
@Query('brand') brand?: string,
|
||||||
|
@Query('attribute') attribute: string = 'strength'
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const data = await this.productService.getProductsGroupedByAttribute(brand, attribute);
|
||||||
|
return successResponse(data);
|
||||||
|
} catch (error) {
|
||||||
|
return errorResponse(error?.message || error);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -79,7 +79,7 @@ export class StatisticsController {
|
||||||
|
|
||||||
@ApiOkResponse()
|
@ApiOkResponse()
|
||||||
@Get('/orderSource')
|
@Get('/orderSource')
|
||||||
async getOrderSorce(@Query() params) {
|
async getOrderSource(@Query() params) {
|
||||||
try {
|
try {
|
||||||
return successResponse(await this.statisticsService.getOrderSorce(params));
|
return successResponse(await this.statisticsService.getOrderSorce(params));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,8 @@ import { SiteService } from '../service/site.service';
|
||||||
import { OrderService } from '../service/order.service';
|
import { OrderService } from '../service/order.service';
|
||||||
import { SiteApiService } from '../service/site-api.service';
|
import { SiteApiService } from '../service/site-api.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Controller('/webhook')
|
@Controller('/webhook')
|
||||||
export class WebhookController {
|
export class WebhookController {
|
||||||
private secret = 'YOONE24kd$kjcdjflddd';
|
private secret = 'YOONE24kd$kjcdjflddd';
|
||||||
|
|
@ -177,20 +179,15 @@ export class WebhookController {
|
||||||
console.log('Unhandled event:', topic);
|
console.log('Unhandled event:', topic);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
code: 200,
|
code: 200,
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Webhook processed successfully',
|
message: 'Webhook processed successfully',
|
||||||
};
|
};
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
code: 403,
|
|
||||||
success: false,
|
|
||||||
message: 'Webhook verification failed',
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,30 @@ export class UnifiedSearchParamsDTO<Where=Record<string, any>> {
|
||||||
required: false,
|
required: false,
|
||||||
})
|
})
|
||||||
orderBy?: Record<string, 'asc' | 'desc'> | string;
|
orderBy?: Record<string, 'asc' | 'desc'> | string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: '分组字段,例如 "categoryId"',
|
||||||
|
type: 'string',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
groupBy?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shopyy获取所有订单参数DTO
|
||||||
|
*/
|
||||||
|
export class ShopyyGetAllOrdersParams {
|
||||||
|
@ApiProperty({ description: '每页数量', example: 100, required: false })
|
||||||
|
per_page?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '支付时间范围开始', example: '2023-01-01T00:00:00Z', required: false })
|
||||||
|
pay_at_min?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '支付时间范围结束', example: '2023-01-01T23:59:59Z', required: false })
|
||||||
|
pay_at_max?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '排序字段', example: 'id', required: false })
|
||||||
|
order_field?: string;//排序字段(默认id) id=订单ID updated_at=最后更新时间 pay_at=支付时间
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -19,15 +19,22 @@ export class ShipmentBookDTO {
|
||||||
@ApiProperty({ type: 'number', isArray: true })
|
@ApiProperty({ type: 'number', isArray: true })
|
||||||
@Rule(RuleType.array<number>().default([]))
|
@Rule(RuleType.array<number>().default([]))
|
||||||
orderIds?: number[];
|
orderIds?: number[];
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@Rule(RuleType.string())
|
||||||
|
shipmentPlatform: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ShipmentFeeBookDTO {
|
export class ShipmentFeeBookDTO {
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
shipmentPlatform: string;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
stockPointId: number;
|
stockPointId: number;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
sender: string;
|
sender: string;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
startPhone: string;
|
startPhone: string|any;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
startPostalCode: string;
|
startPostalCode: string;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
|
|
@ -63,6 +70,8 @@ export class ShipmentFeeBookDTO {
|
||||||
weight: number;
|
weight: number;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
weightUom: string;
|
weightUom: string;
|
||||||
|
@ApiProperty()
|
||||||
|
address_id: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class PaymentMethodDTO {
|
export class PaymentMethodDTO {
|
||||||
|
|
|
||||||
|
|
@ -59,6 +59,10 @@ export class CreateProductDTO {
|
||||||
@Rule(RuleType.number())
|
@Rule(RuleType.number())
|
||||||
categoryId?: number;
|
categoryId?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '分类名称', required: false })
|
||||||
|
@Rule(RuleType.string().optional())
|
||||||
|
categoryName?: string;
|
||||||
|
|
||||||
@ApiProperty({ description: '站点 SKU 列表', type: 'array', required: false })
|
@ApiProperty({ description: '站点 SKU 列表', type: 'array', required: false })
|
||||||
@Rule(RuleType.array().items(RuleType.string()).optional())
|
@Rule(RuleType.array().items(RuleType.string()).optional())
|
||||||
siteSkus?: string[];
|
siteSkus?: string[];
|
||||||
|
|
@ -86,7 +90,10 @@ export class CreateProductDTO {
|
||||||
@Rule(RuleType.number())
|
@Rule(RuleType.number())
|
||||||
promotionPrice?: number;
|
promotionPrice?: number;
|
||||||
|
|
||||||
|
// 产品图片URL
|
||||||
|
@ApiProperty({ description: '产品图片URL', example: 'https://example.com/image.jpg', required: false })
|
||||||
|
@Rule(RuleType.string().optional())
|
||||||
|
image?: string;
|
||||||
|
|
||||||
// 商品类型(默认 single; bundle 需手动设置组成)
|
// 商品类型(默认 single; bundle 需手动设置组成)
|
||||||
@ApiProperty({ description: '商品类型', enum: ['single', 'bundle'], default: 'single', required: false })
|
@ApiProperty({ description: '商品类型', enum: ['single', 'bundle'], default: 'single', required: false })
|
||||||
|
|
@ -139,6 +146,10 @@ export class UpdateProductDTO {
|
||||||
@Rule(RuleType.number())
|
@Rule(RuleType.number())
|
||||||
categoryId?: number;
|
categoryId?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '分类名称', required: false })
|
||||||
|
@Rule(RuleType.string().optional())
|
||||||
|
categoryName?: string;
|
||||||
|
|
||||||
@ApiProperty({ description: '站点 SKU 列表', type: 'array', required: false })
|
@ApiProperty({ description: '站点 SKU 列表', type: 'array', required: false })
|
||||||
@Rule(RuleType.array().items(RuleType.string()).optional())
|
@Rule(RuleType.array().items(RuleType.string()).optional())
|
||||||
siteSkus?: string[];
|
siteSkus?: string[];
|
||||||
|
|
@ -153,7 +164,10 @@ export class UpdateProductDTO {
|
||||||
@Rule(RuleType.number())
|
@Rule(RuleType.number())
|
||||||
promotionPrice?: number;
|
promotionPrice?: number;
|
||||||
|
|
||||||
|
// 产品图片URL
|
||||||
|
@ApiProperty({ description: '产品图片URL', example: 'https://example.com/image.jpg', required: false })
|
||||||
|
@Rule(RuleType.string().optional())
|
||||||
|
image?: string;
|
||||||
|
|
||||||
// 属性更新(可选, 支持增量替换指定字典的属性项)
|
// 属性更新(可选, 支持增量替换指定字典的属性项)
|
||||||
@ApiProperty({ description: '属性列表', type: 'array', required: false })
|
@ApiProperty({ description: '属性列表', type: 'array', required: false })
|
||||||
|
|
@ -228,6 +242,10 @@ export class BatchUpdateProductDTO {
|
||||||
@Rule(RuleType.number().optional())
|
@Rule(RuleType.number().optional())
|
||||||
promotionPrice?: number;
|
promotionPrice?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '产品图片URL', example: 'https://example.com/image.jpg', required: false })
|
||||||
|
@Rule(RuleType.string().optional())
|
||||||
|
image?: string;
|
||||||
|
|
||||||
@ApiProperty({ description: '属性列表', type: 'array', required: false })
|
@ApiProperty({ description: '属性列表', type: 'array', required: false })
|
||||||
@Rule(RuleType.array().optional())
|
@Rule(RuleType.array().optional())
|
||||||
attributes?: AttributeInputDTO[];
|
attributes?: AttributeInputDTO[];
|
||||||
|
|
@ -301,6 +319,8 @@ export interface ProductWhereFilter {
|
||||||
updatedAtStart?: string;
|
updatedAtStart?: string;
|
||||||
// 更新时间范围结束
|
// 更新时间范围结束
|
||||||
updatedAtEnd?: string;
|
updatedAtEnd?: string;
|
||||||
|
// TODO 使用 attributes 过滤
|
||||||
|
attributes?: Record<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -3,6 +3,7 @@ import {
|
||||||
UnifiedPaginationDTO,
|
UnifiedPaginationDTO,
|
||||||
} from './api.dto';
|
} from './api.dto';
|
||||||
import { Dict } from '../entity/dict.entity';
|
import { Dict } from '../entity/dict.entity';
|
||||||
|
import { Product } from '../entity/product.entity';
|
||||||
// export class UnifiedOrderWhere{
|
// export class UnifiedOrderWhere{
|
||||||
// []
|
// []
|
||||||
// }
|
// }
|
||||||
|
|
@ -18,6 +19,24 @@ export enum OrderFulfillmentStatus {
|
||||||
// 确认发货
|
// 确认发货
|
||||||
CONFIRMED,
|
CONFIRMED,
|
||||||
}
|
}
|
||||||
|
export enum OrderPaymentStatus {
|
||||||
|
// 待支付
|
||||||
|
PENDING,
|
||||||
|
// 支付中
|
||||||
|
PAYING,
|
||||||
|
// 部分支付
|
||||||
|
PARTIALLY_PAID,
|
||||||
|
// 已支付
|
||||||
|
PAID,
|
||||||
|
// 支付失败
|
||||||
|
FAILED,
|
||||||
|
// 部分退款
|
||||||
|
PARTIALLY_REFUNDED,
|
||||||
|
// 已退款
|
||||||
|
REFUNDED,
|
||||||
|
// 已取消
|
||||||
|
CANCELLED,
|
||||||
|
}
|
||||||
//
|
//
|
||||||
export class UnifiedProductWhere {
|
export class UnifiedProductWhere {
|
||||||
sku?: string;
|
sku?: string;
|
||||||
|
|
@ -288,17 +307,7 @@ export class UnifiedProductDTO {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
required: false,
|
required: false,
|
||||||
})
|
})
|
||||||
erpProduct?: {
|
erpProduct?: Product
|
||||||
id: number;
|
|
||||||
sku: string;
|
|
||||||
name: string;
|
|
||||||
nameCn?: string;
|
|
||||||
category?: any;
|
|
||||||
attributes?: any[];
|
|
||||||
components?: any[];
|
|
||||||
price: number;
|
|
||||||
promotionPrice: number;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UnifiedOrderRefundDTO {
|
export class UnifiedOrderRefundDTO {
|
||||||
|
|
@ -790,17 +799,20 @@ export class UpdateWebhookDTO {
|
||||||
|
|
||||||
|
|
||||||
export class FulfillmentItemDTO {
|
export class FulfillmentItemDTO {
|
||||||
@ApiProperty({ description: '订单项ID' })
|
@ApiProperty({ description: '订单项ID' ,required: false})
|
||||||
order_item_id: number;
|
order_item_id: number;
|
||||||
|
|
||||||
@ApiProperty({ description: '数量' })
|
@ApiProperty({ description: '数量' ,required:false})
|
||||||
quantity: number;
|
quantity: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class FulfillmentDTO {
|
export class FulfillmentDTO {
|
||||||
|
@ApiProperty({ description: '物流id', required: false })
|
||||||
|
tracking_id?: string;
|
||||||
@ApiProperty({ description: '物流单号', required: false })
|
@ApiProperty({ description: '物流单号', required: false })
|
||||||
tracking_number?: string;
|
tracking_number?: string;
|
||||||
|
@ApiProperty({ description: "物流产品代码" , required: false})
|
||||||
|
tracking_product_code?: string;
|
||||||
@ApiProperty({ description: '物流公司', required: false })
|
@ApiProperty({ description: '物流公司', required: false })
|
||||||
shipping_provider?: string;
|
shipping_provider?: string;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -121,7 +121,7 @@ export class UpdateSiteDTO {
|
||||||
skuPrefix?: string;
|
skuPrefix?: string;
|
||||||
|
|
||||||
// 区域
|
// 区域
|
||||||
@ApiProperty({ description: '区域' })
|
@ApiProperty({ description: '区域', required: false })
|
||||||
@Rule(RuleType.array().items(RuleType.string()).optional())
|
@Rule(RuleType.array().items(RuleType.string()).optional())
|
||||||
areas?: string[];
|
areas?: string[];
|
||||||
|
|
||||||
|
|
@ -133,6 +133,10 @@ export class UpdateSiteDTO {
|
||||||
@ApiProperty({ description: '站点网站URL', required: false })
|
@ApiProperty({ description: '站点网站URL', required: false })
|
||||||
@Rule(RuleType.string().optional())
|
@Rule(RuleType.string().optional())
|
||||||
websiteUrl?: string;
|
websiteUrl?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Webhook URL', required: false })
|
||||||
|
@Rule(RuleType.string().optional())
|
||||||
|
webhookUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class QuerySiteDTO {
|
export class QuerySiteDTO {
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,10 @@ export class OrderStatisticsParams {
|
||||||
@Rule(RuleType.number().allow(null))
|
@Rule(RuleType.number().allow(null))
|
||||||
siteId?: number;
|
siteId?: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@Rule(RuleType.array().allow(null))
|
||||||
|
country?: any[];
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
enum: ['all', 'first_purchase', 'repeat_purchase'],
|
enum: ['all', 'first_purchase', 'repeat_purchase'],
|
||||||
default: 'all',
|
default: 'all',
|
||||||
|
|
|
||||||
|
|
@ -369,18 +369,35 @@ export interface WooOrder {
|
||||||
date_created_gmt?: string;
|
date_created_gmt?: string;
|
||||||
date_modified?: string;
|
date_modified?: string;
|
||||||
date_modified_gmt?: string;
|
date_modified_gmt?: string;
|
||||||
// 物流追踪信息
|
}
|
||||||
fulfillments?: Array<{
|
export interface MetaDataFulfillment {
|
||||||
tracking_number?: string;
|
custom_tracking_link: string;
|
||||||
shipping_provider?: string;
|
custom_tracking_provider: string;
|
||||||
shipping_method?: string;
|
date_shipped: number;
|
||||||
status?: string;
|
source: string;
|
||||||
date_created?: string;
|
status_shipped: string;
|
||||||
items?: Array<{
|
tracking_id: string;
|
||||||
order_item_id?: number;
|
tracking_number: string;
|
||||||
quantity?: number;
|
tracking_product_code: string;
|
||||||
}>;
|
tracking_provider: string;
|
||||||
}>;
|
user_id: number;
|
||||||
|
}
|
||||||
|
// 这个是一个插件的物流追踪信息
|
||||||
|
// 接口:
|
||||||
|
export interface WooFulfillment {
|
||||||
|
data_sipped: string;
|
||||||
|
tracking_id: string;
|
||||||
|
tracking_link: string;
|
||||||
|
tracking_number: string;
|
||||||
|
tracking_provider: string;
|
||||||
|
}
|
||||||
|
// https://docs.zorem.com/docs/ast-free/developers/adding-tracking-info-to-orders/
|
||||||
|
export interface WooFulfillmentCreateParams {
|
||||||
|
order_id: string;
|
||||||
|
tracking_provider: string;
|
||||||
|
tracking_number: string;
|
||||||
|
date_shipped?: string;
|
||||||
|
status_shipped?: string;
|
||||||
}
|
}
|
||||||
export interface WooOrderRefund {
|
export interface WooOrderRefund {
|
||||||
id?: number;
|
id?: number;
|
||||||
|
|
@ -552,7 +569,8 @@ export interface WooOrderSearchParams {
|
||||||
order: string;
|
order: string;
|
||||||
orderby: string;
|
orderby: string;
|
||||||
parant: string[];
|
parant: string[];
|
||||||
status: (WooOrderStatusSearchParams)[];
|
parent_exclude: string[];
|
||||||
|
status: WooOrderStatusSearchParams[];
|
||||||
customer: number;
|
customer: number;
|
||||||
product: number;
|
product: number;
|
||||||
dp: number;
|
dp: number;
|
||||||
|
|
@ -616,6 +634,83 @@ export interface ListParams {
|
||||||
parant: string[];
|
parant: string[];
|
||||||
parent_exclude: string[];
|
parent_exclude: string[];
|
||||||
}
|
}
|
||||||
|
export interface WpMediaGetListParams {
|
||||||
|
// 请求范围,决定响应中包含的字段
|
||||||
|
// 默认: view
|
||||||
|
// 可选值: view, embed, edit
|
||||||
|
context?: 'view' | 'embed' | 'edit';
|
||||||
|
|
||||||
|
// 当前页码
|
||||||
|
// 默认: 1
|
||||||
|
page?: number;
|
||||||
|
|
||||||
|
// 每页最大返回数量
|
||||||
|
// 默认: 10
|
||||||
|
per_page?: number;
|
||||||
|
|
||||||
|
// 搜索字符串,限制结果匹配
|
||||||
|
search?: string;
|
||||||
|
|
||||||
|
// ISO8601格式日期,限制发布时间之后的结果
|
||||||
|
after?: string;
|
||||||
|
|
||||||
|
// ISO8601格式日期,限制修改时间之后的结果
|
||||||
|
modified_after?: string;
|
||||||
|
|
||||||
|
// 作者ID数组,限制结果集为特定作者
|
||||||
|
author?: number[];
|
||||||
|
|
||||||
|
// 作者ID数组,排除特定作者的结果
|
||||||
|
author_exclude?: number[];
|
||||||
|
|
||||||
|
// ISO8601格式日期,限制发布时间之前的结果
|
||||||
|
before?: string;
|
||||||
|
|
||||||
|
// ISO8601格式日期,限制修改时间之前的结果
|
||||||
|
modified_before?: string;
|
||||||
|
|
||||||
|
// ID数组,排除特定ID的结果
|
||||||
|
exclude?: number[];
|
||||||
|
|
||||||
|
// ID数组,限制结果集为特定ID
|
||||||
|
include?: number[];
|
||||||
|
|
||||||
|
// 结果集偏移量
|
||||||
|
offset?: number;
|
||||||
|
|
||||||
|
// 排序方向
|
||||||
|
// 默认: desc
|
||||||
|
// 可选值: asc, desc
|
||||||
|
order?: 'asc' | 'desc';
|
||||||
|
|
||||||
|
// 排序字段
|
||||||
|
// 默认: date
|
||||||
|
// 可选值: author, date, id, include, modified, parent, relevance, slug, include_slugs, title
|
||||||
|
orderby?: 'author' | 'date' | 'id' | 'include' | 'modified' | 'parent' | 'relevance' | 'slug' | 'include_slugs' | 'title';
|
||||||
|
|
||||||
|
// 父ID数组,限制结果集为特定父ID
|
||||||
|
parent?: number[];
|
||||||
|
|
||||||
|
// 父ID数组,排除特定父ID的结果
|
||||||
|
parent_exclude?: number[];
|
||||||
|
|
||||||
|
// 搜索的列名数组
|
||||||
|
search_columns?: string[];
|
||||||
|
|
||||||
|
// slug数组,限制结果集为特定slug
|
||||||
|
slug?: string[];
|
||||||
|
|
||||||
|
// 状态数组,限制结果集为特定状态
|
||||||
|
// 默认: inherit
|
||||||
|
status?: string[];
|
||||||
|
|
||||||
|
// 媒体类型,限制结果集为特定媒体类型
|
||||||
|
// 可选值: image, video, text, application, audio
|
||||||
|
media_type?: 'image' | 'video' | 'text' | 'application' | 'audio';
|
||||||
|
|
||||||
|
// MIME类型,限制结果集为特定MIME类型
|
||||||
|
mime_type?: string;
|
||||||
|
}
|
||||||
export enum WooContext {
|
export enum WooContext {
|
||||||
view,
|
view,
|
||||||
edit
|
edit
|
||||||
|
|
|
||||||
|
|
@ -106,7 +106,7 @@ export class Order {
|
||||||
@Expose()
|
@Expose()
|
||||||
cart_tax: number;
|
cart_tax: number;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({ type: "总金额"})
|
||||||
@Column('decimal', { precision: 10, scale: 2, default: 0 })
|
@Column('decimal', { precision: 10, scale: 2, default: 0 })
|
||||||
@Expose()
|
@Expose()
|
||||||
total: number;
|
total: number;
|
||||||
|
|
|
||||||
|
|
@ -22,22 +22,27 @@ export class OrderSale {
|
||||||
@Expose()
|
@Expose()
|
||||||
id?: number;
|
id?: number;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({ name:'原始订单ID' })
|
||||||
@Column()
|
@Column()
|
||||||
@Expose()
|
@Expose()
|
||||||
orderId: number; // 订单 ID
|
orderId: number; // 订单 ID
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({ name:'站点' })
|
||||||
@Column({ nullable: true })
|
@Column()
|
||||||
@Expose()
|
@Expose()
|
||||||
siteId: number; // 来源站点唯一标识
|
siteId: number; // 来源站点唯一标识
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({name: "原始订单 itemId"})
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
@Expose()
|
@Expose()
|
||||||
externalOrderItemId: string; // WooCommerce 订单item ID
|
externalOrderItemId: string; // WooCommerce 订单item ID
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({name: "父产品 ID"})
|
||||||
|
@Column({ nullable: true })
|
||||||
|
@Expose()
|
||||||
|
parentProductId?: number; // 父产品 ID 用于统计套餐 如果是单品则不记录
|
||||||
|
|
||||||
|
@ApiProperty({name: "产品 ID"})
|
||||||
@Column()
|
@Column()
|
||||||
@Expose()
|
@Expose()
|
||||||
productId: number;
|
productId: number;
|
||||||
|
|
@ -50,7 +55,7 @@ export class OrderSale {
|
||||||
@ApiProperty({ description: 'sku', type: 'string' })
|
@ApiProperty({ description: 'sku', type: 'string' })
|
||||||
@Expose()
|
@Expose()
|
||||||
@Column()
|
@Column()
|
||||||
sku: string;
|
sku: string;// 库存产品sku
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
@Column()
|
@Column()
|
||||||
|
|
@ -62,25 +67,40 @@ export class OrderSale {
|
||||||
@Expose()
|
@Expose()
|
||||||
isPackage: boolean;
|
isPackage: boolean;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({ description: '商品品类', type: 'string',nullable: true})
|
||||||
@Column({ default: false })
|
|
||||||
@Expose()
|
@Expose()
|
||||||
isYoone: boolean;
|
@Column({ nullable: true })
|
||||||
|
category?: string;
|
||||||
|
// TODO 这个其实还是直接保存 product 比较好
|
||||||
|
@ApiProperty({ description: '品牌', type: 'string',nullable: true})
|
||||||
|
@Expose()
|
||||||
|
@Column({ nullable: true })
|
||||||
|
brand?: string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({ description: '口味', type: 'string', nullable: true })
|
||||||
@Column({ default: false })
|
|
||||||
@Expose()
|
@Expose()
|
||||||
isZex: boolean;
|
@Column({ nullable: true })
|
||||||
|
flavor?: string;
|
||||||
|
|
||||||
@ApiProperty({ nullable: true })
|
@ApiProperty({ description: '湿度', type: 'string', nullable: true })
|
||||||
@Column({ type: 'int', nullable: true })
|
|
||||||
@Expose()
|
@Expose()
|
||||||
size: number | null; // 其实是 strength
|
@Column({ nullable: true })
|
||||||
|
humidity?: string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty({ description: '尺寸', type: 'string', nullable: true })
|
||||||
@Column({ default: false })
|
|
||||||
@Expose()
|
@Expose()
|
||||||
isYooneNew: boolean;
|
@Column({ nullable: true })
|
||||||
|
size?: string;
|
||||||
|
|
||||||
|
@ApiProperty({name: '强度', nullable: true })
|
||||||
|
@Column({ nullable: true })
|
||||||
|
@Expose()
|
||||||
|
strength: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '版本', type: 'string', nullable: true })
|
||||||
|
@Expose()
|
||||||
|
@Column({ nullable: true })
|
||||||
|
version?: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
example: '2022-12-12 11:11:11',
|
example: '2022-12-12 11:11:11',
|
||||||
|
|
@ -97,25 +117,4 @@ export class OrderSale {
|
||||||
@UpdateDateColumn()
|
@UpdateDateColumn()
|
||||||
@Expose()
|
@Expose()
|
||||||
updatedAt?: Date;
|
updatedAt?: Date;
|
||||||
|
|
||||||
// // === 自动计算逻辑 ===
|
|
||||||
// @BeforeInsert()
|
|
||||||
// @BeforeUpdate()
|
|
||||||
// setFlags() {
|
|
||||||
// if (!this.name) return;
|
|
||||||
// const lower = this.name.toLowerCase();
|
|
||||||
// this.isYoone = lower.includes('yoone');
|
|
||||||
// this.isZex = lower.includes('zex');
|
|
||||||
// this.isYooneNew = this.isYoone && lower.includes('new');
|
|
||||||
// let size: number | null = null;
|
|
||||||
// const sizes = [3, 6, 9, 12, 15, 18];
|
|
||||||
// for (const s of sizes) {
|
|
||||||
// if (lower.includes(s.toString())) {
|
|
||||||
// size = s;
|
|
||||||
// break;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// this.size = size;
|
|
||||||
// }
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,9 @@ export class Product {
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
description?: string;
|
description?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '图片URL', description: '产品图片URL' })
|
||||||
|
@Column({ nullable: true })
|
||||||
|
image?: string;
|
||||||
// 商品价格
|
// 商品价格
|
||||||
@ApiProperty({ description: '价格', example: 99.99 })
|
@ApiProperty({ description: '价格', example: 99.99 })
|
||||||
@Column({ type: 'decimal', precision: 10, scale: 2, default: 0 })
|
@Column({ type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||||
|
|
@ -70,6 +73,10 @@ export class Product {
|
||||||
@JoinColumn({ name: 'categoryId' })
|
@JoinColumn({ name: 'categoryId' })
|
||||||
category: Category;
|
category: Category;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '分类 ID', nullable: true, example: 1 })
|
||||||
|
@Column({ nullable: true })
|
||||||
|
categoryId?: number;
|
||||||
|
|
||||||
@ManyToMany(() => DictItem, dictItem => dictItem.products, {
|
@ManyToMany(() => DictItem, dictItem => dictItem.products, {
|
||||||
cascade: true,
|
cascade: true,
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -54,9 +54,9 @@ export class Shipment {
|
||||||
tracking_provider?: string;
|
tracking_provider?: string;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
@Column()
|
@Column({ nullable: true })
|
||||||
@Expose()
|
@Expose()
|
||||||
unique_id: string;
|
unique_id?: string;
|
||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
@Expose()
|
@Expose()
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,11 @@ export class ShippingAddress {
|
||||||
@Expose()
|
@Expose()
|
||||||
phone_number_country: string;
|
phone_number_country: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@Column()
|
||||||
|
@Expose()
|
||||||
|
email: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
example: '2022-12-12 11:11:11',
|
example: '2022-12-12 11:11:11',
|
||||||
description: '创建时间',
|
description: '创建时间',
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,86 @@
|
||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
Entity,
|
||||||
|
ManyToOne,
|
||||||
|
JoinColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { ApiProperty } from '@midwayjs/swagger';
|
||||||
|
import { Site } from './site.entity';
|
||||||
|
import { Product } from './product.entity';
|
||||||
|
|
||||||
|
@Entity('site_product')
|
||||||
|
export class SiteProduct {
|
||||||
|
@ApiProperty({
|
||||||
|
example: '12345',
|
||||||
|
description: '站点商品ID',
|
||||||
|
type: 'string',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@Column({ primary: true })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '站点ID' })
|
||||||
|
@Column()
|
||||||
|
siteId: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '商品ID' })
|
||||||
|
@Column({ nullable: true })
|
||||||
|
productId: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'sku'})
|
||||||
|
@Column()
|
||||||
|
sku: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '类型' })
|
||||||
|
@Column({ length: 16, default: 'single' })
|
||||||
|
type: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: '产品名称',
|
||||||
|
type: 'string',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@Column()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '产品图片' })
|
||||||
|
@Column({ default: '' })
|
||||||
|
image: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: '父商品ID', example: '12345' })
|
||||||
|
@Column({ nullable: true })
|
||||||
|
parentId: string;
|
||||||
|
|
||||||
|
// 站点关联
|
||||||
|
@ManyToOne(() => Site, site => site.id)
|
||||||
|
@JoinColumn({ name: 'siteId' })
|
||||||
|
site: Site;
|
||||||
|
|
||||||
|
// 商品关联
|
||||||
|
@ManyToOne(() => Product, product => product.id)
|
||||||
|
@JoinColumn({ name: 'productId' })
|
||||||
|
product: Product;
|
||||||
|
|
||||||
|
// 父商品关联
|
||||||
|
@ManyToOne(() => SiteProduct, siteProduct => siteProduct.id)
|
||||||
|
@JoinColumn({ name: 'parentId' })
|
||||||
|
parent: SiteProduct;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: '2022-12-12 11:11:11',
|
||||||
|
description: '创建时间',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: '2022-12-12 11:11:11',
|
||||||
|
description: '更新时间',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,40 @@
|
||||||
|
import { ILogger, Inject, Logger } from '@midwayjs/core';
|
||||||
|
import { IJob, Job } from '@midwayjs/cron';
|
||||||
|
import { LogisticsService } from '../service/logistics.service';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { Shipment } from '../entity/shipment.entity';
|
||||||
|
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||||
|
|
||||||
|
|
||||||
|
@Job({
|
||||||
|
cronTime: '0 0 12 * * *', // 每天12点执行
|
||||||
|
start: true
|
||||||
|
})
|
||||||
|
export class SyncTmsJob implements IJob {
|
||||||
|
@Logger()
|
||||||
|
logger: ILogger;
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
logisticsService: LogisticsService;
|
||||||
|
|
||||||
|
@InjectEntityModel(Shipment)
|
||||||
|
shipmentModel: Repository<Shipment>
|
||||||
|
|
||||||
|
async onTick() {
|
||||||
|
const shipments:Shipment[] = await this.shipmentModel.findBy({ tracking_provider: 'freightwaves',finished: false });
|
||||||
|
const results = await Promise.all(
|
||||||
|
shipments.map(async shipment => {
|
||||||
|
return await this.logisticsService.updateFreightwavesShipmentState(shipment);
|
||||||
|
})
|
||||||
|
)
|
||||||
|
this.logger.info(`更新运单状态完毕 ${JSON.stringify(results)}`);
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
onComplete(result: any) {
|
||||||
|
this.logger.info(`更新运单状态完成 ${result}`);
|
||||||
|
}
|
||||||
|
onError(error: any) {
|
||||||
|
this.logger.error(`更新运单状态失败 ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -21,7 +21,8 @@ export class CategoryService {
|
||||||
order: {
|
order: {
|
||||||
sort: 'DESC',
|
sort: 'DESC',
|
||||||
createdAt: 'DESC'
|
createdAt: 'DESC'
|
||||||
}
|
},
|
||||||
|
relations: ['attributes', 'attributes.attributeDict']
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,7 @@ export class DictService {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从XLSX文件导入字典
|
// 从XLSX文件导入字典
|
||||||
async importDictsFromXLSX(bufferOrPath: Buffer | string) {
|
async importDictsFromTable(bufferOrPath: Buffer | string) {
|
||||||
// 判断传入的是 Buffer 还是文件路径字符串
|
// 判断传入的是 Buffer 还是文件路径字符串
|
||||||
let buffer: Buffer;
|
let buffer: Buffer;
|
||||||
if (typeof bufferOrPath === 'string') {
|
if (typeof bufferOrPath === 'string') {
|
||||||
|
|
@ -93,7 +93,7 @@ export class DictService {
|
||||||
|
|
||||||
// 从XLSX文件导入字典项
|
// 从XLSX文件导入字典项
|
||||||
async importDictItemsFromXLSX(bufferOrPath: Buffer | string, dictId: number): Promise<BatchOperationResultDTO> {
|
async importDictItemsFromXLSX(bufferOrPath: Buffer | string, dictId: number): Promise<BatchOperationResultDTO> {
|
||||||
if(!dictId){
|
if (!dictId) {
|
||||||
throw new Error("引入失败, 请输入字典 ID")
|
throw new Error("引入失败, 请输入字典 ID")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -216,10 +216,10 @@ export class DictService {
|
||||||
|
|
||||||
// 如果提供了 dictId,则只返回该字典下的项
|
// 如果提供了 dictId,则只返回该字典下的项
|
||||||
if (params.dictId) {
|
if (params.dictId) {
|
||||||
return this.dictItemModel.find({ where });
|
return this.dictItemModel.find({ where, relations: ['dict'] });
|
||||||
}
|
}
|
||||||
// 否则,返回所有字典项
|
// 否则,返回所有字典项
|
||||||
return this.dictItemModel.find();
|
return this.dictItemModel.find({ relations: ['dict'] });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建新字典项
|
// 创建新字典项
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,332 @@
|
||||||
|
import { Inject, Provide } from '@midwayjs/core';
|
||||||
|
import axios from 'axios';
|
||||||
|
import * as crypto from 'crypto';
|
||||||
|
import dayjs = require('dayjs');
|
||||||
|
import utc = require('dayjs/plugin/utc');
|
||||||
|
import timezone = require('dayjs/plugin/timezone');
|
||||||
|
|
||||||
|
// 扩展dayjs功能
|
||||||
|
dayjs.extend(utc);
|
||||||
|
dayjs.extend(timezone);
|
||||||
|
|
||||||
|
// 全局参数配置接口
|
||||||
|
interface FreightwavesConfig {
|
||||||
|
appSecret: string;
|
||||||
|
apiBaseUrl: string;
|
||||||
|
partner: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 地址信息接口
|
||||||
|
interface Address {
|
||||||
|
name: string;
|
||||||
|
phone: string;
|
||||||
|
company: string;
|
||||||
|
countryCode: string;
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
address1: string;
|
||||||
|
address2: string;
|
||||||
|
postCode: string;
|
||||||
|
zoneCode?: string;
|
||||||
|
countryName: string;
|
||||||
|
cityName: string;
|
||||||
|
stateName: string;
|
||||||
|
companyName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 包裹尺寸接口
|
||||||
|
interface Dimensions {
|
||||||
|
length: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
lengthUnit: 'IN' | 'CM';
|
||||||
|
weight: number;
|
||||||
|
weightUnit: 'LB' | 'KG';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 包裹信息接口
|
||||||
|
interface Package {
|
||||||
|
dimensions: Dimensions;
|
||||||
|
currency: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 申报信息接口
|
||||||
|
interface Declaration {
|
||||||
|
boxNo: string;
|
||||||
|
sku: string;
|
||||||
|
cnname: string;
|
||||||
|
enname: string;
|
||||||
|
declaredPrice: number;
|
||||||
|
declaredQty: number;
|
||||||
|
material: string;
|
||||||
|
intendedUse: string;
|
||||||
|
cweight: number;
|
||||||
|
hsCode: string;
|
||||||
|
battery: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 费用试算请求接口
|
||||||
|
export interface RateTryRequest {
|
||||||
|
shipCompany: string;
|
||||||
|
partnerOrderNumber: string;
|
||||||
|
warehouseId?: string;
|
||||||
|
shipper: Address;
|
||||||
|
reciver: Address;
|
||||||
|
packages: Package[];
|
||||||
|
partner: string;
|
||||||
|
signService?: 0 | 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建订单请求接口
|
||||||
|
interface CreateOrderRequest extends RateTryRequest {
|
||||||
|
declaration: Declaration;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询订单请求接口
|
||||||
|
interface QueryOrderRequest {
|
||||||
|
partnerOrderNumber?: string;
|
||||||
|
shipOrderId?: string;
|
||||||
|
partner: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 修改订单请求接口
|
||||||
|
interface ModifyOrderRequest extends CreateOrderRequest {
|
||||||
|
shipOrderId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 订单退款请求接口
|
||||||
|
interface RefundOrderRequest {
|
||||||
|
shipOrderId: string;
|
||||||
|
partner: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 通用响应接口
|
||||||
|
interface FreightwavesResponse<T> {
|
||||||
|
code: string;
|
||||||
|
msg: string;
|
||||||
|
data: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 费用试算响应数据接口
|
||||||
|
interface RateTryResponseData {
|
||||||
|
shipCompany: string;
|
||||||
|
channelCode: string;
|
||||||
|
totalAmount: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建订单响应数据接口
|
||||||
|
interface CreateOrderResponseData {
|
||||||
|
msg: string;
|
||||||
|
data: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询订单响应数据接口
|
||||||
|
interface QueryOrderResponseData {
|
||||||
|
thirdOrderId: string;
|
||||||
|
shipCompany: string;
|
||||||
|
expressFinish: 0 | 1 | 2;
|
||||||
|
expressFailMsg: string;
|
||||||
|
expressOrder: {
|
||||||
|
mainTrackingNumber: string;
|
||||||
|
labelPath: string[];
|
||||||
|
totalAmount: number;
|
||||||
|
currency: string;
|
||||||
|
balance: number;
|
||||||
|
};
|
||||||
|
partnerOrderNumber: string;
|
||||||
|
shipOrderId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 修改订单响应数据接口
|
||||||
|
interface ModifyOrderResponseData extends CreateOrderResponseData { }
|
||||||
|
|
||||||
|
// 订单退款响应数据接口
|
||||||
|
interface RefundOrderResponseData { }
|
||||||
|
|
||||||
|
@Provide()
|
||||||
|
export class FreightwavesService {
|
||||||
|
@Inject() logger;
|
||||||
|
|
||||||
|
// 默认配置
|
||||||
|
private config: FreightwavesConfig = {
|
||||||
|
appSecret: 'gELCHguGmdTLo!zfihfM91hae8G@9Sz23Mh6pHrt',
|
||||||
|
apiBaseUrl: 'http://tms.freightwaves.ca:8901',
|
||||||
|
partner: '25072621035200000060'
|
||||||
|
};
|
||||||
|
|
||||||
|
// 初始化配置
|
||||||
|
setConfig(config: Partial<FreightwavesConfig>): void {
|
||||||
|
this.config = { ...this.config, ...config };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成签名
|
||||||
|
private generateSignature(body: any, date: string): string {
|
||||||
|
const bodyString = JSON.stringify(body);
|
||||||
|
const signatureStr = `${bodyString}${this.config.appSecret}${date}`;
|
||||||
|
return crypto.createHash('md5').update(signatureStr).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送请求
|
||||||
|
private async sendRequest<T>(url: string, data: any): Promise<FreightwavesResponse<T>> {
|
||||||
|
try {
|
||||||
|
// 设置请求头 - 使用太平洋时间 (America/Los_Angeles)
|
||||||
|
const date = dayjs().tz('America/Los_Angeles').format('YYYY-MM-DD HH:mm:ss');
|
||||||
|
const headers = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'requestDate': date,
|
||||||
|
'signature': this.generateSignature(data, date),
|
||||||
|
};
|
||||||
|
|
||||||
|
// 发送请求 - 临时禁用SSL证书验证以解决UNABLE_TO_VERIFY_LEAF_SIGNATURE错误
|
||||||
|
const response = await axios.post<FreightwavesResponse<T>>(
|
||||||
|
`${this.config.apiBaseUrl}${url}`,
|
||||||
|
data,
|
||||||
|
{
|
||||||
|
headers,
|
||||||
|
httpsAgent: new (require('https').Agent)({
|
||||||
|
rejectUnauthorized: false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// 记录响应信息
|
||||||
|
this.log(`Received response from: ${this.config.apiBaseUrl}${url}`, {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
data: response.data
|
||||||
|
});
|
||||||
|
|
||||||
|
// 处理响应
|
||||||
|
if (response.data.code !== '00000200') {
|
||||||
|
this.log(`Freightwaves API error: ${response.data.msg}`, { url, data, response: response.data });
|
||||||
|
throw new Error(response.data.msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
// 更详细的错误记录
|
||||||
|
if (error.response) {
|
||||||
|
// 请求已发送,服务器返回错误状态码
|
||||||
|
this.log(`Freightwaves API request failed with status: ${error.response.status}`, {
|
||||||
|
url,
|
||||||
|
data,
|
||||||
|
response: error.response.data,
|
||||||
|
status: error.response.status,
|
||||||
|
headers: error.response.headers
|
||||||
|
});
|
||||||
|
} else if (error.request) {
|
||||||
|
// 请求已发送,但没有收到响应
|
||||||
|
this.log(`Freightwaves API request no response received`, {
|
||||||
|
url,
|
||||||
|
data,
|
||||||
|
request: error.request
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// 请求配置时发生错误
|
||||||
|
this.log(`Freightwaves API request configuration error: ${error.message}`, {
|
||||||
|
url,
|
||||||
|
data,
|
||||||
|
error: error.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 费用试算
|
||||||
|
* @param params 费用试算参数
|
||||||
|
* @returns 费用试算结果
|
||||||
|
*/
|
||||||
|
async rateTry(params: Omit<RateTryRequest, 'partner'>): Promise<RateTryResponseData> {
|
||||||
|
const requestData: RateTryRequest = {
|
||||||
|
...params,
|
||||||
|
partner: this.config.partner,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendRequest<RateTryResponseData>('/shipService/order/rateTry', requestData);
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建订单
|
||||||
|
* @param params 创建订单参数
|
||||||
|
* @returns 创建订单结果
|
||||||
|
*/
|
||||||
|
async createOrder(params: Omit<CreateOrderRequest, 'partner'>): Promise<CreateOrderResponseData> {
|
||||||
|
const requestData: CreateOrderRequest = {
|
||||||
|
...params,
|
||||||
|
partner: this.config.partner,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendRequest<CreateOrderResponseData>('/shipService/order/createOrder', requestData);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询订单
|
||||||
|
* @param params 查询订单参数
|
||||||
|
* @returns 查询订单结果
|
||||||
|
*/
|
||||||
|
async queryOrder(params: Omit<QueryOrderRequest, 'partner'>): Promise<QueryOrderResponseData> {
|
||||||
|
const requestData: QueryOrderRequest = {
|
||||||
|
...params,
|
||||||
|
partner: this.config.partner,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendRequest<QueryOrderResponseData>('/shipService/order/queryOrder', requestData);
|
||||||
|
if (response.code !== '00000200') {
|
||||||
|
throw new Error(response.msg);
|
||||||
|
}
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修改订单
|
||||||
|
* @param params 修改订单参数
|
||||||
|
* @returns 修改订单结果
|
||||||
|
*/
|
||||||
|
async modifyOrder(params: Omit<ModifyOrderRequest, 'partner'>): Promise<ModifyOrderResponseData> {
|
||||||
|
const requestData: ModifyOrderRequest = {
|
||||||
|
...params,
|
||||||
|
partner: this.config.partner,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.sendRequest<ModifyOrderResponseData>('/shipService/order/modifyOrder', requestData);
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单退款
|
||||||
|
* @param params 订单退款参数
|
||||||
|
* @returns 订单退款结果
|
||||||
|
*/
|
||||||
|
async refundOrder(params: Omit<RefundOrderRequest, 'partner'>): Promise<RefundOrderResponseData> {
|
||||||
|
const requestData: RefundOrderRequest = {
|
||||||
|
...params,
|
||||||
|
partner: this.config.partner,
|
||||||
|
};
|
||||||
|
const response = await this.sendRequest<RefundOrderResponseData>('/shipService/order/refundOrder', requestData);
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 辅助日志方法,处理logger可能未定义的情况
|
||||||
|
* @param message 日志消息
|
||||||
|
* @param data 附加数据
|
||||||
|
*/
|
||||||
|
private log(message: string, data?: any) {
|
||||||
|
if (this.logger) {
|
||||||
|
this.logger.info(message, data);
|
||||||
|
} else {
|
||||||
|
// 如果logger未定义,使用console输出
|
||||||
|
if (data) {
|
||||||
|
console.log(message, data);
|
||||||
|
} else {
|
||||||
|
console.log(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -27,10 +27,12 @@ import { CanadaPostService } from './canadaPost.service';
|
||||||
import { OrderItem } from '../entity/order_item.entity';
|
import { OrderItem } from '../entity/order_item.entity';
|
||||||
import { OrderSale } from '../entity/order_sale.entity';
|
import { OrderSale } from '../entity/order_sale.entity';
|
||||||
import { UniExpressService } from './uni_express.service';
|
import { UniExpressService } from './uni_express.service';
|
||||||
|
import { FreightwavesService, RateTryRequest } from './freightwaves.service';
|
||||||
import { StockPoint } from '../entity/stock_point.entity';
|
import { StockPoint } from '../entity/stock_point.entity';
|
||||||
import { OrderService } from './order.service';
|
import { OrderService } from './order.service';
|
||||||
import { convertKeysFromCamelToSnake } from '../utils/object-transform.util';
|
import { convertKeysFromCamelToSnake } from '../utils/object-transform.util';
|
||||||
import { SiteService } from './site.service';
|
import { SiteService } from './site.service';
|
||||||
|
import { ShopyyService } from './shopyy.service';
|
||||||
|
|
||||||
@Provide()
|
@Provide()
|
||||||
export class LogisticsService {
|
export class LogisticsService {
|
||||||
|
|
@ -73,9 +75,15 @@ export class LogisticsService {
|
||||||
@Inject()
|
@Inject()
|
||||||
uniExpressService: UniExpressService;
|
uniExpressService: UniExpressService;
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
freightwavesService: FreightwavesService;
|
||||||
|
|
||||||
@Inject()
|
@Inject()
|
||||||
wpService: WPService;
|
wpService: WPService;
|
||||||
|
|
||||||
|
@Inject()
|
||||||
|
shopyyService: ShopyyService;
|
||||||
|
|
||||||
@Inject()
|
@Inject()
|
||||||
orderService: OrderService;
|
orderService: OrderService;
|
||||||
|
|
||||||
|
|
@ -126,8 +134,8 @@ export class LogisticsService {
|
||||||
const data = await this.uniExpressService.getOrderStatus(shipment.return_tracking_number);
|
const data = await this.uniExpressService.getOrderStatus(shipment.return_tracking_number);
|
||||||
console.log('updateShipmentState data:', data);
|
console.log('updateShipmentState data:', data);
|
||||||
// huo
|
// huo
|
||||||
if(data.status === 'FAIL'){
|
if (data.status === 'FAIL') {
|
||||||
throw new Error('获取运单状态失败,原因为'+ data.ret_msg)
|
throw new Error('获取运单状态失败,原因为' + data.ret_msg)
|
||||||
}
|
}
|
||||||
shipment.state = data.data[0].state;
|
shipment.state = data.data[0].state;
|
||||||
if (shipment.state in [203, 215, 216, 230]) { // todo,写常数
|
if (shipment.state in [203, 215, 216, 230]) { // todo,写常数
|
||||||
|
|
@ -141,6 +149,30 @@ export class LogisticsService {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//"expressFinish": 0, //是否快递创建完成(1:完成 0:未完成,需要轮询 2:失败)
|
||||||
|
async updateFreightwavesShipmentState(shipment: Shipment) {
|
||||||
|
try {
|
||||||
|
const data = await this.freightwavesService.queryOrder({ shipOrderId: shipment.order_id.toString() });
|
||||||
|
console.log('updateFreightwavesShipmentState data:', data);
|
||||||
|
// huo
|
||||||
|
if (data.expressFinish === 2) {
|
||||||
|
throw new Error('获取运单状态失败,原因为' + data.expressFailMsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.expressFinish === 0) {
|
||||||
|
shipment.state = '203';
|
||||||
|
shipment.finished = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.shipmentModel.save(shipment);
|
||||||
|
return shipment.state;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
// throw new Error(`更新运单状态失败 ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async updateShipmentStateById(id: number) {
|
async updateShipmentStateById(id: number) {
|
||||||
const shipment: Shipment = await this.shipmentModel.findOneBy({ id: id });
|
const shipment: Shipment = await this.shipmentModel.findOneBy({ id: id });
|
||||||
return this.updateShipmentState(shipment);
|
return this.updateShipmentState(shipment);
|
||||||
|
|
@ -247,8 +279,7 @@ export class LogisticsService {
|
||||||
|
|
||||||
shipmentRepo.remove(shipment);
|
shipmentRepo.remove(shipment);
|
||||||
|
|
||||||
const res = await this.uniExpressService.deleteShipment(shipment.return_tracking_number);
|
await this.uniExpressService.deleteShipment(shipment.return_tracking_number);
|
||||||
console.log('res', res.data); // todo
|
|
||||||
|
|
||||||
await orderRepo.save(order);
|
await orderRepo.save(order);
|
||||||
|
|
||||||
|
|
@ -278,7 +309,6 @@ export class LogisticsService {
|
||||||
console.log('同步到woocommerce失败', error);
|
console.log('同步到woocommerce失败', error);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error('删除运单失败');
|
throw new Error('删除运单失败');
|
||||||
|
|
@ -294,7 +324,16 @@ export class LogisticsService {
|
||||||
currency: 'CAD',
|
currency: 'CAD',
|
||||||
// item_description: data.sales, // todo: 货品信息
|
// item_description: data.sales, // todo: 货品信息
|
||||||
}
|
}
|
||||||
const resShipmentFee = await this.uniExpressService.getRates(reqBody);
|
let resShipmentFee: any;
|
||||||
|
if (data.shipmentPlatform === 'uniuni') {
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
|
|
@ -319,40 +358,10 @@ export class LogisticsService {
|
||||||
|
|
||||||
let resShipmentOrder;
|
let resShipmentOrder;
|
||||||
try {
|
try {
|
||||||
const stock_point = await this.stockPointModel.findOneBy({ id: data.stockPointId });
|
resShipmentOrder = await this.mepShipment(data, order);
|
||||||
const reqBody = {
|
|
||||||
sender: data.details.origin.contact_name,
|
|
||||||
start_phone: data.details.origin.phone_number,
|
|
||||||
start_postal_code: data.details.origin.address.postal_code.replace(/\s/g, ''),
|
|
||||||
pickup_address: data.details.origin.address.address_line_1,
|
|
||||||
pickup_warehouse: stock_point.upStreamStockPointId,
|
|
||||||
shipper_country_code: data.details.origin.address.country,
|
|
||||||
receiver: data.details.destination.contact_name,
|
|
||||||
city: data.details.destination.address.city,
|
|
||||||
province: data.details.destination.address.region,
|
|
||||||
country: data.details.destination.address.country,
|
|
||||||
postal_code: data.details.destination.address.postal_code.replace(/\s/g, ''),
|
|
||||||
delivery_address: data.details.destination.address.address_line_1,
|
|
||||||
receiver_phone: data.details.destination.phone_number.number,
|
|
||||||
receiver_email: data.details.destination.email_addresses,
|
|
||||||
// item_description: data.sales, // todo: 货品信息
|
|
||||||
length: data.details.packaging_properties.packages[0].measurements.cuboid.l,
|
|
||||||
width: data.details.packaging_properties.packages[0].measurements.cuboid.w,
|
|
||||||
height: data.details.packaging_properties.packages[0].measurements.cuboid.h,
|
|
||||||
dimension_uom: data.details.packaging_properties.packages[0].measurements.cuboid.unit,
|
|
||||||
weight: data.details.packaging_properties.packages[0].measurements.weight.value,
|
|
||||||
weight_uom: data.details.packaging_properties.packages[0].measurements.weight.unit,
|
|
||||||
currency: 'CAD',
|
|
||||||
custom_field: {
|
|
||||||
'order_id': order.externalOrderId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 添加运单
|
// 记录物流信息,并将订单状态转到完成,uniuni状态为SUCCESS,tms.freightwaves状态为00000200
|
||||||
resShipmentOrder = await this.uniExpressService.createShipment(reqBody);
|
if (resShipmentOrder.status === 'SUCCESS' || resShipmentOrder.code === '00000200') {
|
||||||
|
|
||||||
// 记录物流信息,并将订单状态转到完成
|
|
||||||
if (resShipmentOrder.status === 'SUCCESS') {
|
|
||||||
order.orderStatus = ErpOrderStatus.COMPLETED;
|
order.orderStatus = ErpOrderStatus.COMPLETED;
|
||||||
} else {
|
} else {
|
||||||
throw new Error('运单生成失败');
|
throw new Error('运单生成失败');
|
||||||
|
|
@ -363,49 +372,89 @@ export class LogisticsService {
|
||||||
await dataSource.transaction(async manager => {
|
await dataSource.transaction(async manager => {
|
||||||
const orderRepo = manager.getRepository(Order);
|
const orderRepo = manager.getRepository(Order);
|
||||||
const shipmentRepo = manager.getRepository(Shipment);
|
const shipmentRepo = manager.getRepository(Shipment);
|
||||||
const tracking_provider = 'UniUni'; // todo: id未确定,后写进常数
|
const tracking_provider = data.shipmentPlatform; // todo: id未确定,后写进常数
|
||||||
|
|
||||||
// 同步物流信息到woocommerce
|
// 同步物流信息到woocommerce
|
||||||
const site = await this.siteService.get(Number(order.siteId), true);
|
const site = await this.siteService.get(Number(order.siteId), true);
|
||||||
const res = await this.wpService.createFulfillment(site, order.externalOrderId, {
|
let co: any;
|
||||||
tracking_number: resShipmentOrder.data.tno,
|
let unique_id: any;
|
||||||
tracking_provider: tracking_provider,
|
let state: any;
|
||||||
});
|
if (data.shipmentPlatform === 'uniuni') {
|
||||||
|
co = resShipmentOrder.data.tno;
|
||||||
if (order.orderStatus === ErpOrderStatus.COMPLETED) {
|
unique_id = resShipmentOrder.data.uni_order_sn;
|
||||||
const shipment = await shipmentRepo.save({
|
state = resShipmentOrder.data.uni_status_code;
|
||||||
tracking_provider: tracking_provider,
|
} else {
|
||||||
tracking_id: res.data.tracking_id,
|
co = resShipmentOrder.data?.shipOrderId;
|
||||||
unique_id: resShipmentOrder.data.uni_order_sn,
|
unique_id = resShipmentOrder.data?.shipOrderId;
|
||||||
stockPointId: String(data.stockPointId), // todo
|
state = ErpOrderStatus.COMPLETED;
|
||||||
state: resShipmentOrder.data.uni_status_code,
|
|
||||||
return_tracking_number: resShipmentOrder.data.tno,
|
|
||||||
fee: data.details.shipmentFee,
|
|
||||||
order: order
|
|
||||||
});
|
|
||||||
order.shipmentId = shipment.id;
|
|
||||||
shipmentId = shipment.id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 同步订单状态到woocommerce
|
// 同步订单状态到woocommerce
|
||||||
if (order.status !== OrderStatus.COMPLETED) {
|
if (order.source_type != "shopyy") {
|
||||||
await this.wpService.updateOrder(site, order.externalOrderId, {
|
const res = await this.wpService.createFulfillment(site, order.externalOrderId, {
|
||||||
status: OrderStatus.COMPLETED,
|
tracking_number: co,
|
||||||
|
tracking_provider: tracking_provider,
|
||||||
});
|
});
|
||||||
order.status = OrderStatus.COMPLETED;
|
|
||||||
|
if (order.orderStatus === ErpOrderStatus.COMPLETED) {
|
||||||
|
const shipment = await shipmentRepo.save({
|
||||||
|
tracking_provider: tracking_provider,
|
||||||
|
tracking_id: res.data.tracking_id,
|
||||||
|
unique_id: unique_id,
|
||||||
|
stockPointId: String(data.stockPointId), // todo
|
||||||
|
state: state,
|
||||||
|
return_tracking_number: co,
|
||||||
|
fee: data.details.shipmentFee,
|
||||||
|
order: order
|
||||||
|
});
|
||||||
|
order.shipmentId = shipment.id;
|
||||||
|
shipmentId = shipment.id;
|
||||||
|
}
|
||||||
|
if (order.status !== OrderStatus.COMPLETED) {
|
||||||
|
await this.wpService.updateOrder(site, order.externalOrderId, {
|
||||||
|
status: OrderStatus.COMPLETED,
|
||||||
|
});
|
||||||
|
order.status = OrderStatus.COMPLETED;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (order.source_type === "shopyy") {
|
||||||
|
const res = await this.shopyyService.createFulfillment(site, order.externalOrderId, {
|
||||||
|
tracking_number: co,
|
||||||
|
tracking_company: resShipmentOrder.shipCompany,
|
||||||
|
carrier_code: resShipmentOrder.shipperOrderId,
|
||||||
|
});
|
||||||
|
if (order.orderStatus === ErpOrderStatus.COMPLETED) {
|
||||||
|
const shipment = await shipmentRepo.save({
|
||||||
|
tracking_provider: tracking_provider,
|
||||||
|
tracking_id: res.data.tracking_id,
|
||||||
|
unique_id: unique_id,
|
||||||
|
stockPointId: String(data.stockPointId), // todo
|
||||||
|
state: state,
|
||||||
|
return_tracking_number: co,
|
||||||
|
fee: data.details.shipmentFee,
|
||||||
|
order: order
|
||||||
|
});
|
||||||
|
order.shipmentId = shipment.id;
|
||||||
|
shipmentId = shipment.id;
|
||||||
|
}
|
||||||
|
if (order.status !== OrderStatus.COMPLETED) {
|
||||||
|
// shopyy未提供更新订单接口,暂不更新订单状态
|
||||||
|
// await this.shopyyService.updateOrder(site, order.externalOrderId, {
|
||||||
|
// status: OrderStatus.COMPLETED,
|
||||||
|
// });
|
||||||
|
order.status = OrderStatus.COMPLETED;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
order.orderStatus = ErpOrderStatus.COMPLETED;
|
order.orderStatus = ErpOrderStatus.COMPLETED;
|
||||||
|
|
||||||
await orderRepo.save(order);
|
await orderRepo.save(order);
|
||||||
}).catch(error => {
|
}).catch(error => {
|
||||||
transactionError = error
|
transactionError = error
|
||||||
|
throw new Error(`请求错误:${error}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (transactionError !== undefined) {
|
if (transactionError !== undefined) {
|
||||||
console.log('err', transactionError);
|
|
||||||
throw transactionError;
|
throw transactionError;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新产品发货信息
|
// 更新产品发货信息
|
||||||
this.orderService.updateOrderSales(order.id, sales);
|
this.orderService.updateOrderSales(order.id, sales);
|
||||||
|
|
||||||
|
|
@ -642,4 +691,190 @@ export class LogisticsService {
|
||||||
|
|
||||||
return { items, total, current, pageSize };
|
return { items, total, current, pageSize };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async mepShipment(data: ShipmentBookDTO, order: Order) {
|
||||||
|
try {
|
||||||
|
const stock_point = await this.stockPointModel.findOneBy({ id: data.stockPointId });
|
||||||
|
let resShipmentOrder;
|
||||||
|
|
||||||
|
if (data.shipmentPlatform === 'uniuni') {
|
||||||
|
const reqBody = {
|
||||||
|
sender: data.details.origin.contact_name,
|
||||||
|
start_phone: data.details.origin.phone_number,
|
||||||
|
start_postal_code: data.details.origin.address.postal_code.replace(/\s/g, ''),
|
||||||
|
pickup_address: data.details.origin.address.address_line_1,
|
||||||
|
pickup_warehouse: stock_point.upStreamStockPointId,
|
||||||
|
shipper_country_code: data.details.origin.address.country,
|
||||||
|
receiver: data.details.destination.contact_name,
|
||||||
|
city: data.details.destination.address.city,
|
||||||
|
province: data.details.destination.address.region,
|
||||||
|
country: data.details.destination.address.country,
|
||||||
|
postal_code: data.details.destination.address.postal_code.replace(/\s/g, ''),
|
||||||
|
delivery_address: data.details.destination.address.address_line_1,
|
||||||
|
receiver_phone: data.details.destination.phone_number.number,
|
||||||
|
receiver_email: data.details.destination.email_addresses,
|
||||||
|
// item_description: data.sales, // todo: 货品信息
|
||||||
|
length: data.details.packaging_properties.packages[0].measurements.cuboid.l,
|
||||||
|
width: data.details.packaging_properties.packages[0].measurements.cuboid.w,
|
||||||
|
height: data.details.packaging_properties.packages[0].measurements.cuboid.h,
|
||||||
|
dimension_uom: data.details.packaging_properties.packages[0].measurements.cuboid.unit,
|
||||||
|
weight: data.details.packaging_properties.packages[0].measurements.weight.value,
|
||||||
|
weight_uom: data.details.packaging_properties.packages[0].measurements.weight.unit,
|
||||||
|
currency: 'CAD',
|
||||||
|
custom_field: {
|
||||||
|
'order_id': order.externalOrderId // todo: 需要获取订单的externalOrderId
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// 添加运单
|
||||||
|
resShipmentOrder = await this.uniExpressService.createShipment(reqBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.shipmentPlatform === 'freightwaves') {
|
||||||
|
// 根据TMS系统对接说明文档格式化参数
|
||||||
|
const reqBody: any = {
|
||||||
|
shipCompany: 'UPSYYZ7000NEW',
|
||||||
|
partnerOrderNumber: order.siteId + '-' + order.externalOrderId,
|
||||||
|
warehouseId: '25072621030107400060',
|
||||||
|
shipper: {
|
||||||
|
name: data.details.origin.contact_name, // 姓名
|
||||||
|
phone: data.details.origin.phone_number.number, // 电话(提取number属性转换为字符串)
|
||||||
|
company: '', // 公司
|
||||||
|
countryCode: data.details.origin.address.country, // 国家Code
|
||||||
|
city: data.details.origin.address.city, // 城市
|
||||||
|
state: data.details.origin.address.region, // 州/省Code,两个字母缩写
|
||||||
|
address1: data.details.origin.address.address_line_1, // 详细地址
|
||||||
|
address2: '', // 详细地址2(Address类型中没有address_line_2属性)
|
||||||
|
postCode: data.details.origin.address.postal_code.replace(/\s/g, ''), // 邮编
|
||||||
|
countryName: data.details.origin.address.country, // 国家名称(Address类型中没有country_name属性,使用country代替)
|
||||||
|
cityName: data.details.origin.address.city, // 城市名称
|
||||||
|
stateName: data.details.origin.address.region, // 州/省名称
|
||||||
|
companyName: '' // 公司名称
|
||||||
|
},
|
||||||
|
reciver: {
|
||||||
|
name: data.details.destination.contact_name, // 姓名
|
||||||
|
phone: data.details.destination.phone_number.number, // 电话
|
||||||
|
company: '', // 公司
|
||||||
|
countryCode: data.details.destination.address.country, // 国家Code
|
||||||
|
city: data.details.destination.address.city, // 城市
|
||||||
|
state: data.details.destination.address.region, // 州/省Code,两个字母的缩写
|
||||||
|
address1: data.details.destination.address.address_line_1, // 详细地址
|
||||||
|
address2: '', // 详细地址2(Address类型中没有address_line_2属性)
|
||||||
|
postCode: data.details.destination.address.postal_code.replace(/\s/g, ''), // 邮编
|
||||||
|
countryName: data.details.destination.address.country, // 国家名称(Address类型中没有country_name属性,使用country代替)
|
||||||
|
cityName: data.details.destination.address.city, // 城市名称
|
||||||
|
stateName: data.details.destination.address.region, // 州/省名称
|
||||||
|
companyName: '' // 公司名称
|
||||||
|
},
|
||||||
|
packages: [
|
||||||
|
{
|
||||||
|
dimensions: {
|
||||||
|
length: data.details.packaging_properties.packages[0].measurements.cuboid.l, // 长
|
||||||
|
width: data.details.packaging_properties.packages[0].measurements.cuboid.w, // 宽
|
||||||
|
height: data.details.packaging_properties.packages[0].measurements.cuboid.h, // 高
|
||||||
|
lengthUnit: (data.details.packaging_properties.packages[0].measurements.cuboid.unit === 'cm' ? 'CM' : 'IN') as 'CM' | 'IN', // 长度单位(IN,CM)
|
||||||
|
weight: data.details.packaging_properties.packages[0].measurements.weight.value, // 重量
|
||||||
|
weightUnit: (data.details.packaging_properties.packages[0].measurements.weight.unit === 'kg' ? 'KG' : 'LB') as 'KG' | 'LB' // 重量单位(LB,KG)
|
||||||
|
},
|
||||||
|
currency: 'CAD', // 币种(默认CAD)
|
||||||
|
description: 'site:' + order.siteId + ' orderId:' + order.externalOrderId // 包裹描述(确保是字符串类型)
|
||||||
|
}
|
||||||
|
],
|
||||||
|
signService: 0
|
||||||
|
// 非跨境订单不需要declaration
|
||||||
|
// declaration: {
|
||||||
|
// "boxNo": "", //箱子编号
|
||||||
|
// "sku": "", //SKU
|
||||||
|
// "cnname": "", //中文名称
|
||||||
|
// "enname": "", //英文名称
|
||||||
|
// "declaredPrice": 1, //申报单价
|
||||||
|
// "declaredQty": 1, //申报数量
|
||||||
|
// "material": "", //材质
|
||||||
|
// "intendedUse": "", //用途
|
||||||
|
// "cweight": 1, //产品单重
|
||||||
|
// "hsCode": "", //海关编码
|
||||||
|
// "battery": "" //电池描述
|
||||||
|
// }
|
||||||
|
};
|
||||||
|
|
||||||
|
resShipmentOrder = await this.freightwavesService.createOrder(reqBody); // 创建订单
|
||||||
|
//tms只返回了物流订单号,需要查询一次来获取完整的物流信息
|
||||||
|
const queryRes = await this.freightwavesService.queryOrder({ shipOrderId: resShipmentOrder.shipOrderId }); // 查询订单
|
||||||
|
resShipmentOrder.push(queryRes);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resShipmentOrder;
|
||||||
|
} catch (error) {
|
||||||
|
console.log('物流订单处理失败:', error); // 使用console.log代替this.log
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将ShipmentFeeBookDTO转换为freightwaves的RateTryRequest格式
|
||||||
|
* @param data ShipmentFeeBookDTO数据
|
||||||
|
* @returns RateTryRequest格式的数据
|
||||||
|
*/
|
||||||
|
async convertToFreightwavesRateTry(data: ShipmentFeeBookDTO): Promise<Omit<RateTryRequest, 'partner'>> {
|
||||||
|
|
||||||
|
const shipments = await this.shippingAddressModel.findOne({
|
||||||
|
where: {
|
||||||
|
id: data.address_id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const address = shipments?.address;
|
||||||
|
// 转换为RateTryRequest格式
|
||||||
|
const r = {
|
||||||
|
shipCompany: 'UPSYYZ7000NEW', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成
|
||||||
|
warehouseId: '25072621030107400060', // 可选,使用stockPointId转换
|
||||||
|
shipper: {
|
||||||
|
name: data.sender, // 必填
|
||||||
|
phone: data.startPhone.phone, // 必填
|
||||||
|
company: address.country, // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
countryCode: data.shipperCountryCode, // 必填
|
||||||
|
city: address.city || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
state: address.region || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
address1: address.address_line_1, // 必填
|
||||||
|
address2: address.address_line_1 || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
postCode: data.startPostalCode, // 必填
|
||||||
|
countryName: address.country || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
cityName: address.city || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
stateName: address.region || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
companyName: address.country || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
},
|
||||||
|
reciver: {
|
||||||
|
name: data.receiver, // 必填
|
||||||
|
phone: data.receiverPhone, // 必填
|
||||||
|
company: address.country,// 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
countryCode: data.country, // 必填,使用country代替countryCode
|
||||||
|
city: data.city, // 必填
|
||||||
|
state: data.province, // 必填,使用province代替state
|
||||||
|
address1: data.deliveryAddress, // 必填
|
||||||
|
address2: data.deliveryAddress, // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
postCode: data.postalCode, // 必填
|
||||||
|
countryName: address.country, // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
cityName: data.city || '', // 必填,使用city代替cityName
|
||||||
|
stateName: data.province || '', // 必填,使用province代替stateName
|
||||||
|
companyName: address.country || '', // 必填,但ShipmentFeeBookDTO中缺少
|
||||||
|
},
|
||||||
|
packages: [
|
||||||
|
{
|
||||||
|
dimensions: {
|
||||||
|
length: data.length, // 必填
|
||||||
|
width: data.width, // 必填
|
||||||
|
height: data.height, // 必填
|
||||||
|
lengthUnit: (data.dimensionUom === 'IN' ? 'IN' : 'CM') as 'IN' | 'CM', // 必填,转换为有效的单位
|
||||||
|
weight: data.weight, // 必填
|
||||||
|
weightUnit: (data.weightUom === 'LBS' ? 'LB' : 'KG') as 'LB' | 'KG', // 必填,转换为有效的单位
|
||||||
|
},
|
||||||
|
currency: 'CAD', // 必填,但ShipmentFeeBookDTO中缺少,使用默认值
|
||||||
|
description: 'Package', // 必填,但ShipmentFeeBookDTO中缺少,使用默认值
|
||||||
|
},
|
||||||
|
],
|
||||||
|
signService: 0, // 可选,默认不使用签名服务
|
||||||
|
};
|
||||||
|
return r as any;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -141,7 +141,7 @@ 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 {
|
||||||
|
|
@ -150,7 +150,7 @@ export class OrderService {
|
||||||
where: { externalOrderId: String(order.id), siteId: siteId },
|
where: { externalOrderId: String(order.id), siteId: siteId },
|
||||||
});
|
});
|
||||||
if (!existingOrder) {
|
if (!existingOrder) {
|
||||||
console.log("数据库中不存在", order.id, '订单状态:', order.status)
|
this.logger.debug("数据库中不存在", order.id, '订单状态:', order.status)
|
||||||
}
|
}
|
||||||
// 同步单个订单
|
// 同步单个订单
|
||||||
await this.syncSingleOrder(siteId, order);
|
await this.syncSingleOrder(siteId, order);
|
||||||
|
|
@ -165,6 +165,7 @@ export class OrderService {
|
||||||
} else {
|
} else {
|
||||||
syncResult.created++;
|
syncResult.created++;
|
||||||
}
|
}
|
||||||
|
// console.log('updated', syncResult.updated, 'created:', syncResult.created)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 记录错误但不中断整个同步过程
|
// 记录错误但不中断整个同步过程
|
||||||
syncResult.errors.push({
|
syncResult.errors.push({
|
||||||
|
|
@ -174,7 +175,7 @@ export class OrderService {
|
||||||
syncResult.processed++;
|
syncResult.processed++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.logger.debug('syncOrders result', syncResult)
|
this.logger.info('同步完成', syncResult.updated, 'created:', syncResult.created)
|
||||||
return syncResult;
|
return syncResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -212,7 +213,7 @@ export class OrderService {
|
||||||
where: { externalOrderId: String(order.id), siteId: siteId },
|
where: { externalOrderId: String(order.id), siteId: siteId },
|
||||||
});
|
});
|
||||||
if (!existingOrder) {
|
if (!existingOrder) {
|
||||||
console.log("数据库不存在", siteId, "订单:", order.id, '订单状态:' + order.status)
|
this.logger.debug("数据库不存在", siteId, "订单:", order.id, '订单状态:' + order.status)
|
||||||
}
|
}
|
||||||
// 同步单个订单
|
// 同步单个订单
|
||||||
await this.syncSingleOrder(siteId, order, true);
|
await this.syncSingleOrder(siteId, order, true);
|
||||||
|
|
@ -326,13 +327,30 @@ export class OrderService {
|
||||||
this.logger.debug('订单状态为 AUTO_DRAFT,跳过处理', siteId, order.id)
|
this.logger.debug('订单状态为 AUTO_DRAFT,跳过处理', siteId, order.id)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 这里其实不用过滤不可编辑的行为,而是应在 save 中做判断
|
// 检查数据库中是否已存在该订单
|
||||||
// if(!order.is_editable && !forceUpdate){
|
const existingOrder = await this.orderModel.findOne({
|
||||||
// this.logger.debug('订单不可编辑,跳过处理', siteId, order.id)
|
where: { externalOrderId: String(order.id), siteId: siteId },
|
||||||
// return;
|
});
|
||||||
// }
|
// 自动更新订单状态(如果需要)
|
||||||
// 自动转换远程订单的状态(如果需要)
|
|
||||||
await this.autoUpdateOrderStatus(siteId, order);
|
await this.autoUpdateOrderStatus(siteId, order);
|
||||||
|
|
||||||
|
if (existingOrder) {
|
||||||
|
// 矫正数据库中的订单数据
|
||||||
|
const updateData: any = { status: order.status };
|
||||||
|
if (this.canUpdateErpStatus(existingOrder.orderStatus)) {
|
||||||
|
updateData.orderStatus = this.mapOrderStatus(order.status as any);
|
||||||
|
}
|
||||||
|
// 更新订单主数据
|
||||||
|
await this.orderModel.update({ externalOrderId: String(order.id), siteId: siteId }, updateData);
|
||||||
|
// 更新 fulfillments 数据
|
||||||
|
await this.saveOrderFulfillments({
|
||||||
|
siteId,
|
||||||
|
orderId: existingOrder.id,
|
||||||
|
externalOrderId: order.id,
|
||||||
|
fulfillments: fulfillments,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const externalOrderId = String(order.id);
|
||||||
// 这里的 saveOrder 已经包括了创建订单和更新订单
|
// 这里的 saveOrder 已经包括了创建订单和更新订单
|
||||||
let orderRecord: Order = await this.saveOrder(siteId, orderData);
|
let orderRecord: Order = await this.saveOrder(siteId, orderData);
|
||||||
// 如果订单从未完成变为完成状态,则更新库存
|
// 如果订单从未完成变为完成状态,则更新库存
|
||||||
|
|
@ -344,13 +362,12 @@ export class OrderService {
|
||||||
await this.updateStock(orderRecord);
|
await this.updateStock(orderRecord);
|
||||||
// 不再直接返回,继续执行后续的更新操作
|
// 不再直接返回,继续执行后续的更新操作
|
||||||
}
|
}
|
||||||
const externalOrderId = String(order.id);
|
|
||||||
const orderId = orderRecord.id;
|
const orderId = orderRecord.id;
|
||||||
// 保存订单项
|
// 保存订单项
|
||||||
await this.saveOrderItems({
|
await this.saveOrderItems({
|
||||||
siteId,
|
siteId,
|
||||||
orderId,
|
orderId,
|
||||||
externalOrderId,
|
externalOrderId: String(externalOrderId),
|
||||||
orderItems: line_items,
|
orderItems: line_items,
|
||||||
});
|
});
|
||||||
// 保存退款信息
|
// 保存退款信息
|
||||||
|
|
@ -711,54 +728,56 @@ export class OrderService {
|
||||||
await this.orderSaleModel.delete(currentOrderSale.map(v => v.id));
|
await this.orderSaleModel.delete(currentOrderSale.map(v => v.id));
|
||||||
}
|
}
|
||||||
if (!orderItem.sku) return;
|
if (!orderItem.sku) return;
|
||||||
// 从数据库查询产品,关联查询组件
|
|
||||||
const product = await this.productModel.findOne({
|
|
||||||
where: { siteSkus: Like(`%${orderItem.sku}%`) },
|
|
||||||
relations: ['components'],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!product) return;
|
// 从数据库查询产品,关联查询组件
|
||||||
|
const productDetail = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name });
|
||||||
|
|
||||||
|
if (!productDetail || !productDetail.quantity) return;
|
||||||
|
const { product, quantity } = productDetail
|
||||||
const componentDetails: { product: Product, quantity: number }[] = product.components?.length > 0 ? await Promise.all(product.components.map(async comp => {
|
const componentDetails: { product: Product, quantity: number }[] = product.components?.length > 0 ? await Promise.all(product.components.map(async comp => {
|
||||||
return {
|
return {
|
||||||
product: await this.productModel.findOne({
|
product: await this.productModel.findOne({
|
||||||
where: { sku: comp.sku },
|
where: { id: comp.productId },
|
||||||
relations: ['components','attributes'],
|
|
||||||
}),
|
}),
|
||||||
quantity: comp.quantity * orderItem.quantity,
|
quantity: comp.quantity * orderItem.quantity,
|
||||||
}
|
}
|
||||||
})) : [{ product, quantity: orderItem.quantity }]
|
})) : [{ product, quantity }]
|
||||||
|
|
||||||
const orderSales: OrderSale[] = componentDetails.map(componentDetail => {
|
const orderSales: OrderSale[] = componentDetails.map(componentDetail => {
|
||||||
if(!componentDetail.product) return null
|
if (!componentDetail.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,
|
externalOrderItemId: orderItem.externalOrderItemId,// 原始 itemId
|
||||||
|
parentProductId: product.id, // 父产品 ID 用于统计套餐 如果是单品则不记录
|
||||||
productId: componentDetail.product.id,
|
productId: componentDetail.product.id,
|
||||||
|
isPackage: product.type === 'bundle',// 这里是否是套餐取决于父产品
|
||||||
name: componentDetail.product.name,
|
name: componentDetail.product.name,
|
||||||
quantity: componentDetail.quantity * orderItem.quantity,
|
quantity: componentDetail.quantity * orderItem.quantity,
|
||||||
sku: componentDetail.product.sku,
|
sku: componentDetail.product.sku,
|
||||||
isPackage: componentDetail.product.type === 'bundle',
|
// 理论上直接存 product 的全部数据才是对的,因为这样我的数据才全面。
|
||||||
isYoone: attrsObj?.['brand']?.name === 'yoone',
|
brand: attrsObj?.['brand']?.name,
|
||||||
isZyn: attrsObj?.['brand']?.name === 'zyn',
|
version: attrsObj?.['version']?.name,
|
||||||
isZex: attrsObj?.['brand']?.name === 'zex',
|
strength: attrsObj?.['strength']?.name,
|
||||||
isYooneNew: attrsObj?.['brand']?.name === 'yoone' && attrsObj?.['version']?.name === 'new',
|
flavor: attrsObj?.['flavor']?.name,
|
||||||
size: this.extractNumberFromString(attrsObj?.['strength']?.name) || null,
|
humidity: attrsObj?.['humidity']?.name,
|
||||||
|
size: attrsObj?.['size']?.name,
|
||||||
|
category: componentDetail.product.category.name,
|
||||||
});
|
});
|
||||||
return orderSale
|
return orderSale
|
||||||
}).filter(v => v !== null)
|
}).filter(v => v !== null)
|
||||||
|
|
||||||
if (orderSales.length > 0) {
|
if (orderSales.length > 0) {
|
||||||
await this.orderSaleModel.save(orderSales);
|
await this.orderSaleModel.save(orderSales);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
extractNumberFromString(str: string): number {
|
// // extract stren
|
||||||
if (!str) return 0;
|
// extractNumberFromString(str: string): number {
|
||||||
|
// if (!str) return 0;
|
||||||
|
|
||||||
const num = parseInt(str, 10);
|
// const num = parseInt(str, 10);
|
||||||
return isNaN(num) ? 0 : num;
|
// return isNaN(num) ? 0 : num;
|
||||||
}
|
// }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 保存订单退款信息
|
* 保存订单退款信息
|
||||||
|
|
@ -1227,13 +1246,13 @@ export class OrderService {
|
||||||
parameters.push(siteId);
|
parameters.push(siteId);
|
||||||
}
|
}
|
||||||
if (startDate) {
|
if (startDate) {
|
||||||
sqlQuery += ` AND o.date_created >= ?`;
|
sqlQuery += ` AND o.date_paid >= ?`;
|
||||||
totalQuery += ` AND o.date_created >= ?`;
|
totalQuery += ` AND o.date_paid >= ?`;
|
||||||
parameters.push(startDate);
|
parameters.push(startDate);
|
||||||
}
|
}
|
||||||
if (endDate) {
|
if (endDate) {
|
||||||
sqlQuery += ` AND o.date_created <= ?`;
|
sqlQuery += ` AND o.date_paid <= ?`;
|
||||||
totalQuery += ` AND o.date_created <= ?`;
|
totalQuery += ` AND o.date_paid <= ?`;
|
||||||
parameters.push(endDate);
|
parameters.push(endDate);
|
||||||
}
|
}
|
||||||
// 支付方式筛选(使用参数化,避免SQL注入)
|
// 支付方式筛选(使用参数化,避免SQL注入)
|
||||||
|
|
@ -1321,7 +1340,7 @@ export class OrderService {
|
||||||
// 添加分页到主查询
|
// 添加分页到主查询
|
||||||
sqlQuery += `
|
sqlQuery += `
|
||||||
GROUP BY o.id
|
GROUP BY o.id
|
||||||
ORDER BY o.date_created DESC
|
ORDER BY o.date_paid DESC
|
||||||
LIMIT ? OFFSET ?
|
LIMIT ? OFFSET ?
|
||||||
`;
|
`;
|
||||||
parameters.push(pageSize, (current - 1) * pageSize);
|
parameters.push(pageSize, (current - 1) * pageSize);
|
||||||
|
|
@ -1460,7 +1479,7 @@ export class OrderService {
|
||||||
}
|
}
|
||||||
|
|
||||||
let itemSql = `
|
let itemSql = `
|
||||||
SELECT os.productId, os.name, SUM(os.quantity) AS totalQuantity, COUNT(DISTINCT os.orderId) AS totalOrders
|
SELECT os.productId, os.name, os.sku, SUM(os.quantity) AS totalQuantity, COUNT(DISTINCT os.orderId) AS totalOrders
|
||||||
FROM order_sale os
|
FROM order_sale os
|
||||||
INNER JOIN \`order\` o ON o.id = os.orderId
|
INNER JOIN \`order\` o ON o.id = os.orderId
|
||||||
WHERE o.date_paid BETWEEN ? AND ?
|
WHERE o.date_paid BETWEEN ? AND ?
|
||||||
|
|
@ -1482,7 +1501,7 @@ export class OrderService {
|
||||||
}
|
}
|
||||||
itemSql += nameCondition;
|
itemSql += nameCondition;
|
||||||
itemSql += `
|
itemSql += `
|
||||||
GROUP BY os.productId, os.name
|
GROUP BY os.productId, os.name, os.sku
|
||||||
ORDER BY totalQuantity DESC
|
ORDER BY totalQuantity DESC
|
||||||
LIMIT ? OFFSET ?
|
LIMIT ? OFFSET ?
|
||||||
`;
|
`;
|
||||||
|
|
@ -1539,7 +1558,6 @@ export class OrderService {
|
||||||
GROUP BY os.productId
|
GROUP BY os.productId
|
||||||
`;
|
`;
|
||||||
|
|
||||||
console.log('------3.5-----', pcSql, pcParams, exceptPackage);
|
|
||||||
const pcResults = await this.orderSaleModel.query(pcSql, pcParams);
|
const pcResults = await this.orderSaleModel.query(pcSql, pcParams);
|
||||||
|
|
||||||
const pcMap = new Map<number, any>();
|
const pcMap = new Map<number, any>();
|
||||||
|
|
@ -1572,14 +1590,14 @@ export class OrderService {
|
||||||
`;
|
`;
|
||||||
let yooneSql = `
|
let yooneSql = `
|
||||||
SELECT
|
SELECT
|
||||||
SUM(CASE WHEN os.isYoone = 1 AND os.size = 3 THEN os.quantity ELSE 0 END) AS yoone3Quantity,
|
SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '3mg' THEN os.quantity ELSE 0 END) AS yoone3Quantity,
|
||||||
SUM(CASE WHEN os.isYoone = 1 AND os.size = 6 THEN os.quantity ELSE 0 END) AS yoone6Quantity,
|
SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '6mg' THEN os.quantity ELSE 0 END) AS yoone6Quantity,
|
||||||
SUM(CASE WHEN os.isYoone = 1 AND os.size = 9 THEN os.quantity ELSE 0 END) AS yoone9Quantity,
|
SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '9mg' THEN os.quantity ELSE 0 END) AS yoone9Quantity,
|
||||||
SUM(CASE WHEN os.isYoone = 1 AND os.size = 12 THEN os.quantity ELSE 0 END) AS yoone12Quantity,
|
SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '12mg' THEN os.quantity ELSE 0 END) AS yoone12Quantity,
|
||||||
SUM(CASE WHEN os.isYooneNew = 1 AND os.size = 12 THEN os.quantity ELSE 0 END) AS yoone12QuantityNew,
|
SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '12mg' THEN os.quantity ELSE 0 END) AS yoone12QuantityNew,
|
||||||
SUM(CASE WHEN os.isYoone = 1 AND os.size = 15 THEN os.quantity ELSE 0 END) AS yoone15Quantity,
|
SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '15mg' THEN os.quantity ELSE 0 END) AS yoone15Quantity,
|
||||||
SUM(CASE WHEN os.isYoone = 1 AND os.size = 18 THEN os.quantity ELSE 0 END) AS yoone18Quantity,
|
SUM(CASE WHEN os.brand = 'yoone' AND os.strength = '18mg' THEN os.quantity ELSE 0 END) AS yoone18Quantity,
|
||||||
SUM(CASE WHEN os.isZex = 1 THEN os.quantity ELSE 0 END) AS zexQuantity
|
SUM(CASE WHEN os.brand = 'zex' THEN os.quantity ELSE 0 END) AS zexQuantity
|
||||||
FROM order_sale os
|
FROM order_sale os
|
||||||
INNER JOIN \`order\` o ON o.id = os.orderId
|
INNER JOIN \`order\` o ON o.id = os.orderId
|
||||||
WHERE o.date_paid BETWEEN ? AND ?
|
WHERE o.date_paid BETWEEN ? AND ?
|
||||||
|
|
@ -2507,7 +2525,7 @@ 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} (${item.sku || ''}) x ${item.quantity}`).join('; ');
|
const orderContent = items.map(item => `${item.name} x ${item.quantity}`).join('; ');
|
||||||
|
|
||||||
// 构建姓名地址
|
// 构建姓名地址
|
||||||
const shipping = order.shipping;
|
const shipping = order.shipping;
|
||||||
|
|
@ -2618,13 +2636,9 @@ export class OrderService {
|
||||||
if (!fs.existsSync(downloadsDir)) {
|
if (!fs.existsSync(downloadsDir)) {
|
||||||
fs.mkdirSync(downloadsDir, { recursive: true });
|
fs.mkdirSync(downloadsDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const filePath = path.join(downloadsDir, fileName);
|
const filePath = path.join(downloadsDir, fileName);
|
||||||
|
|
||||||
// 写入文件
|
// 写入文件
|
||||||
fs.writeFileSync(filePath, csvContent, 'utf8');
|
fs.writeFileSync(filePath, csvContent, 'utf8');
|
||||||
|
|
||||||
console.log(`数据已成功导出至 ${filePath}`);
|
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2635,11 +2649,83 @@ export class OrderService {
|
||||||
|
|
||||||
return csvContent;
|
return csvContent;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('导出CSV时出错:', error);
|
|
||||||
throw new Error(`导出CSV文件失败: ${error.message}`);
|
throw new Error(`导出CSV文件失败: ${error.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除每个分号前面一个左右括号和最后一个左右括号包含的内容(包括括号本身)
|
||||||
|
* @param str 输入字符串
|
||||||
|
* @returns 删除后的字符串
|
||||||
|
*/
|
||||||
|
removeLastParenthesesContent(str: string): string {
|
||||||
|
if (!str || typeof str !== 'string') {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 辅助函数:删除指定位置的括号对及其内容
|
||||||
|
const removeParenthesesAt = (s: string, leftIndex: number): string => {
|
||||||
|
if (leftIndex === -1) return s;
|
||||||
|
|
||||||
|
let rightIndex = -1;
|
||||||
|
let parenCount = 0;
|
||||||
|
|
||||||
|
for (let i = leftIndex; i < s.length; i++) {
|
||||||
|
const char = s[i];
|
||||||
|
if (char === '(') {
|
||||||
|
parenCount++;
|
||||||
|
} else if (char === ')') {
|
||||||
|
parenCount--;
|
||||||
|
if (parenCount === 0) {
|
||||||
|
rightIndex = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rightIndex !== -1) {
|
||||||
|
return s.substring(0, leftIndex) + s.substring(rightIndex + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. 处理每个分号前面的括号对
|
||||||
|
let result = str;
|
||||||
|
|
||||||
|
// 找出所有分号的位置
|
||||||
|
const semicolonIndices: number[] = [];
|
||||||
|
for (let i = 0; i < result.length; i++) {
|
||||||
|
if (result[i] === ';') {
|
||||||
|
semicolonIndices.push(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从后向前处理每个分号,避免位置变化影响后续处理
|
||||||
|
for (let i = semicolonIndices.length - 1; i >= 0; i--) {
|
||||||
|
const semicolonIndex = semicolonIndices[i];
|
||||||
|
|
||||||
|
// 从分号位置向前查找最近的左括号
|
||||||
|
let lastLeftParenIndex = -1;
|
||||||
|
for (let j = semicolonIndex - 1; j >= 0; j--) {
|
||||||
|
if (result[j] === '(') {
|
||||||
|
lastLeftParenIndex = j;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果找到左括号,删除该括号对及其内容
|
||||||
|
if (lastLeftParenIndex !== -1) {
|
||||||
|
result = removeParenthesesAt(result, lastLeftParenIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 处理整个字符串的最后一个括号对
|
||||||
|
let lastLeftParenIndex = result.lastIndexOf('(');
|
||||||
|
if (lastLeftParenIndex !== -1) {
|
||||||
|
result = removeParenthesesAt(result, lastLeftParenIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -8,16 +8,16 @@ import * as FormData from 'form-data';
|
||||||
import { SiteService } from './site.service';
|
import { SiteService } from './site.service';
|
||||||
import { Site } from '../entity/site.entity';
|
import { Site } from '../entity/site.entity';
|
||||||
import { UnifiedReviewDTO } from '../dto/site-api.dto';
|
import { UnifiedReviewDTO } from '../dto/site-api.dto';
|
||||||
import { ShopyyReview } from '../dto/shopyy.dto';
|
import { ShopyyGetOneOrderResult, ShopyyReview } from '../dto/shopyy.dto';
|
||||||
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
||||||
import { UnifiedSearchParamsDTO } from '../dto/api.dto';
|
import { UnifiedSearchParamsDTO, ShopyyGetAllOrdersParams } from '../dto/api.dto';
|
||||||
/**
|
/**
|
||||||
* ShopYY平台服务实现
|
* ShopYY平台服务实现
|
||||||
*/
|
*/
|
||||||
@Provide()
|
@Provide()
|
||||||
export class ShopyyService {
|
export class ShopyyService {
|
||||||
@Inject()
|
@Inject()
|
||||||
logger:ILogger;
|
logger: ILogger;
|
||||||
/**
|
/**
|
||||||
* 获取ShopYY评论列表
|
* 获取ShopYY评论列表
|
||||||
* @param site 站点配置
|
* @param site 站点配置
|
||||||
|
|
@ -184,9 +184,9 @@ export class ShopyyService {
|
||||||
*/
|
*/
|
||||||
public async fetchResourcePaged<T>(site: any, endpoint: string, params: Record<string, any> = {}) {
|
public async fetchResourcePaged<T>(site: any, endpoint: string, params: Record<string, any> = {}) {
|
||||||
const response = await this.request(site, endpoint, 'GET', null, params);
|
const response = await this.request(site, endpoint, 'GET', null, params);
|
||||||
return this.mapPageResponse<T>(response,params);
|
return this.mapPageResponse<T>(response, params);
|
||||||
}
|
}
|
||||||
mapPageResponse<T>(response:any,query: Record<string, any>){
|
mapPageResponse<T>(response: any, query: Record<string, any>) {
|
||||||
if (response?.code !== 0) {
|
if (response?.code !== 0) {
|
||||||
throw new Error(response?.msg)
|
throw new Error(response?.msg)
|
||||||
}
|
}
|
||||||
|
|
@ -272,7 +272,7 @@ export class ShopyyService {
|
||||||
const response = await this.request(site, `products/${productId}/variations/${variationId}`, 'GET');
|
const response = await this.request(site, `products/${productId}/variations/${variationId}`, 'GET');
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
mapOrderSearchParams(params: UnifiedSearchParamsDTO){
|
mapOrderSearchParams(params: UnifiedSearchParamsDTO) {
|
||||||
const { after, before, ...restParams } = params;
|
const { after, before, ...restParams } = params;
|
||||||
return {
|
return {
|
||||||
...restParams,
|
...restParams,
|
||||||
|
|
@ -288,7 +288,7 @@ export class ShopyyService {
|
||||||
* @param pageSize 每页数量
|
* @param pageSize 每页数量
|
||||||
* @returns 分页订单列表
|
* @returns 分页订单列表
|
||||||
*/
|
*/
|
||||||
async getOrders(site: any | number, page: number = 1, pageSize: number = 100, params: UnifiedSearchParamsDTO = {}): Promise<any> {
|
async getOrders(site: any | number, page: number = 1, pageSize: number = 3000, params: ShopyyGetAllOrdersParams = {}): Promise<any> {
|
||||||
// 如果传入的是站点ID,则获取站点配置
|
// 如果传入的是站点ID,则获取站点配置
|
||||||
const siteConfig = typeof site === 'number' ? await this.siteService.get(site) : site;
|
const siteConfig = typeof site === 'number' ? await this.siteService.get(site) : site;
|
||||||
|
|
||||||
|
|
@ -308,12 +308,11 @@ export class ShopyyService {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAllOrders(site: any | number, params: Record<string, any> = {}, maxPages: number = 10, concurrencyLimit: number = 100): Promise<any> {
|
async getAllOrders(site: any | number, params: ShopyyGetAllOrdersParams = {}, maxPages: number = 10, concurrencyLimit: number = 100): Promise<any> {
|
||||||
const firstPage = await this.getOrders(site, 1, 100);
|
const firstPage = await this.getOrders(site, 1, 100, params);
|
||||||
|
|
||||||
const { items: firstPageItems, totalPages} = firstPage;
|
const { items: firstPageItems, totalPages } = firstPage;
|
||||||
|
|
||||||
// const { page = 1, per_page = 100 } = params;
|
|
||||||
// 如果只有一页数据,直接返回
|
// 如果只有一页数据,直接返回
|
||||||
if (totalPages <= 1) {
|
if (totalPages <= 1) {
|
||||||
return firstPageItems;
|
return firstPageItems;
|
||||||
|
|
@ -334,7 +333,7 @@ export class ShopyyService {
|
||||||
// 创建当前批次的并发请求
|
// 创建当前批次的并发请求
|
||||||
for (let i = 0; i < batchSize; i++) {
|
for (let i = 0; i < batchSize; i++) {
|
||||||
const page = currentPage + i;
|
const page = currentPage + i;
|
||||||
const pagePromise = this.getOrders(site, page, 100)
|
const pagePromise = this.getOrders(site, page, 100, params)
|
||||||
.then(pageResult => pageResult.items)
|
.then(pageResult => pageResult.items)
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
console.error(`获取第 ${page} 页数据失败:`, error);
|
console.error(`获取第 ${page} 页数据失败:`, error);
|
||||||
|
|
@ -366,7 +365,7 @@ export class ShopyyService {
|
||||||
* @param orderId 订单ID
|
* @param orderId 订单ID
|
||||||
* @returns 订单详情
|
* @returns 订单详情
|
||||||
*/
|
*/
|
||||||
async getOrder(siteId: string, orderId: string): Promise<any> {
|
async getOrder(siteId: string, orderId: string): Promise<ShopyyGetOneOrderResult> {
|
||||||
const site = await this.siteService.get(Number(siteId));
|
const site = await this.siteService.get(Number(siteId));
|
||||||
|
|
||||||
// ShopYY API: GET /orders/{id}
|
// ShopYY API: GET /orders/{id}
|
||||||
|
|
@ -476,13 +475,16 @@ export class ShopyyService {
|
||||||
async createFulfillment(site: Site, orderId: string, data: any): Promise<any> {
|
async createFulfillment(site: Site, orderId: string, data: any): Promise<any> {
|
||||||
// ShopYY API: POST /orders/{id}/shipments
|
// ShopYY API: POST /orders/{id}/shipments
|
||||||
const fulfillmentData = {
|
const fulfillmentData = {
|
||||||
tracking_number: data.tracking_number,
|
data: [{
|
||||||
carrier_code: data.carrier_code,
|
order_number: orderId,
|
||||||
carrier_name: data.carrier_name,
|
tracking_company: data.tracking_company,
|
||||||
shipping_method: data.shipping_method
|
tracking_number: data.tracking_number,
|
||||||
|
carrier_code: data.carrier_code,
|
||||||
|
note: "note",
|
||||||
|
mode: ""
|
||||||
|
}]
|
||||||
};
|
};
|
||||||
|
const response = await this.request(site, `orders/fulfillments`, 'POST', fulfillmentData);
|
||||||
const response = await this.request(site, `orders/${orderId}/shipments`, 'POST', fulfillmentData);
|
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -495,7 +497,7 @@ export class ShopyyService {
|
||||||
*/
|
*/
|
||||||
async deleteFulfillment(site: any, orderId: string, fulfillmentId: string): Promise<boolean> {
|
async deleteFulfillment(site: any, orderId: string, fulfillmentId: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
// ShopYY API: DELETE /orders/{order_id}/shipments/{fulfillment_id}
|
// ShopYY API: DELETE /orders/fulfillments/{fulfillment_id}
|
||||||
await this.request(site, `orders/${orderId}/fulfillments/${fulfillmentId}`, 'DELETE');
|
await this.request(site, `orders/${orderId}/fulfillments/${fulfillmentId}`, 'DELETE');
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -648,7 +650,7 @@ export class ShopyyService {
|
||||||
const result = response.data;
|
const result = response.data;
|
||||||
|
|
||||||
// 转换 ShopYY 批量操作结果为统一格式
|
// 转换 ShopYY 批量操作结果为统一格式
|
||||||
const errors: Array<{identifier: string, error: string}> = [];
|
const errors: Array<{ identifier: string, error: string }> = [];
|
||||||
|
|
||||||
// 假设 ShopYY 返回格式与 WooCommerce 类似: { create: [...], update: [...], delete: [...] }
|
// 假设 ShopYY 返回格式与 WooCommerce 类似: { create: [...], update: [...], delete: [...] }
|
||||||
// 错误信息可能在每个项目的 error 字段中
|
// 错误信息可能在每个项目的 error 字段中
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import { SiteService } from './site.service';
|
||||||
import { WPService } from './wp.service';
|
import { WPService } from './wp.service';
|
||||||
import { ProductService } from './product.service';
|
import { ProductService } from './product.service';
|
||||||
import { UnifiedProductDTO } from '../dto/site-api.dto';
|
import { UnifiedProductDTO } from '../dto/site-api.dto';
|
||||||
|
import { Product } from '../entity/product.entity';
|
||||||
|
|
||||||
@Provide()
|
@Provide()
|
||||||
export class SiteApiService {
|
export class SiteApiService {
|
||||||
|
|
@ -52,7 +53,7 @@ export class SiteApiService {
|
||||||
* @param siteProduct 站点商品信息
|
* @param siteProduct 站点商品信息
|
||||||
* @returns 包含ERP产品信息的站点商品
|
* @returns 包含ERP产品信息的站点商品
|
||||||
*/
|
*/
|
||||||
async enrichSiteProductWithErpInfo(siteId: number, siteProduct: any): Promise<any> {
|
async enrichSiteProductWithErpInfo(siteId: number, siteProduct: UnifiedProductDTO): Promise<UnifiedProductDTO & { erpProduct?: Product }> {
|
||||||
if (!siteProduct || !siteProduct.sku) {
|
if (!siteProduct || !siteProduct.sku) {
|
||||||
return siteProduct;
|
return siteProduct;
|
||||||
}
|
}
|
||||||
|
|
@ -64,18 +65,7 @@ export class SiteApiService {
|
||||||
// 将ERP产品信息合并到站点商品中
|
// 将ERP产品信息合并到站点商品中
|
||||||
return {
|
return {
|
||||||
...siteProduct,
|
...siteProduct,
|
||||||
erpProduct: {
|
erpProduct,
|
||||||
id: erpProduct.id,
|
|
||||||
sku: erpProduct.sku,
|
|
||||||
name: erpProduct.name,
|
|
||||||
nameCn: erpProduct.nameCn,
|
|
||||||
category: erpProduct.category,
|
|
||||||
attributes: erpProduct.attributes,
|
|
||||||
components: erpProduct.components,
|
|
||||||
price: erpProduct.price,
|
|
||||||
promotionPrice: erpProduct.promotionPrice,
|
|
||||||
// 可以根据需要添加更多ERP产品字段
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 如果找不到对应的ERP产品,返回原始站点商品
|
// 如果找不到对应的ERP产品,返回原始站点商品
|
||||||
|
|
@ -90,7 +80,7 @@ export class SiteApiService {
|
||||||
* @param siteProducts 站点商品列表
|
* @param siteProducts 站点商品列表
|
||||||
* @returns 包含ERP产品信息的站点商品列表
|
* @returns 包含ERP产品信息的站点商品列表
|
||||||
*/
|
*/
|
||||||
async enrichSiteProductsWithErpInfo(siteId: number, siteProducts: any[]): Promise<any[]> {
|
async enrichSiteProductsWithErpInfo(siteId: number, siteProducts: UnifiedProductDTO[]): Promise<(UnifiedProductDTO & { erpProduct?: Product })[]> {
|
||||||
if (!siteProducts || !siteProducts.length) {
|
if (!siteProducts || !siteProducts.length) {
|
||||||
return siteProducts;
|
return siteProducts;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,19 @@ export class StatisticsService {
|
||||||
orderItemRepository: Repository<OrderItem>;
|
orderItemRepository: Repository<OrderItem>;
|
||||||
|
|
||||||
async getOrderStatistics(params: OrderStatisticsParams) {
|
async getOrderStatistics(params: OrderStatisticsParams) {
|
||||||
const { startDate, endDate, grouping, siteId } = params;
|
const { startDate, endDate, grouping, siteId, country } = params;
|
||||||
// const keywords = keyword ? keyword.split(' ').filter(Boolean) : [];
|
// const keywords = keyword ? keyword.split(' ').filter(Boolean) : [];
|
||||||
|
|
||||||
|
let siteIds = []
|
||||||
|
if (country) {
|
||||||
|
siteIds = await this.getSiteIds(country)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (siteId) {
|
||||||
|
siteIds.push(siteId)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const start = dayjs(startDate).format('YYYY-MM-DD');
|
const start = dayjs(startDate).format('YYYY-MM-DD');
|
||||||
const end = dayjs(endDate).add(1, 'd').format('YYYY-MM-DD');
|
const end = dayjs(endDate).add(1, 'd').format('YYYY-MM-DD');
|
||||||
let sql
|
let sql
|
||||||
|
|
@ -54,22 +65,24 @@ export class StatisticsService {
|
||||||
AND o.status IN('processing','completed')
|
AND o.status IN('processing','completed')
|
||||||
`;
|
`;
|
||||||
if (siteId) sql += ` AND o.siteId=${siteId}`;
|
if (siteId) sql += ` AND o.siteId=${siteId}`;
|
||||||
|
if (siteIds.length) sql += ` AND o.siteId IN (${siteIds.join(',')})`;
|
||||||
|
|
||||||
sql += `
|
sql += `
|
||||||
GROUP BY o.id, o.date_paid, o.customer_email, o.total, o.source_type, o.siteId, o.utm_source
|
GROUP BY o.id, o.date_paid, o.customer_email, o.total, o.source_type, o.siteId, o.utm_source
|
||||||
),
|
),
|
||||||
order_sales_summary AS (
|
order_sales_summary AS (
|
||||||
SELECT
|
SELECT
|
||||||
orderId,
|
orderId,
|
||||||
SUM(CASE WHEN name LIKE '%zyn%' THEN quantity ELSE 0 END) AS zyn_quantity,
|
SUM(CASE WHEN brand = 'zyn' THEN quantity ELSE 0 END) AS zyn_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' THEN quantity ELSE 0 END) AS yoone_quantity,
|
SUM(CASE WHEN brand = 'yoone' THEN quantity ELSE 0 END) AS yoone_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%zex%' THEN quantity ELSE 0 END) AS zex_quantity,
|
SUM(CASE WHEN brand = 'zex' THEN quantity ELSE 0 END) AS zex_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%3%' THEN quantity ELSE 0 END) AS yoone_3_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '3mg' THEN quantity ELSE 0 END) AS yoone_3_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%6%' THEN quantity ELSE 0 END) AS yoone_6_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '6mg' THEN quantity ELSE 0 END) AS yoone_6_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%9%' THEN quantity ELSE 0 END) AS yoone_9_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '9mg' THEN quantity ELSE 0 END) AS yoone_9_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%12%' THEN quantity ELSE 0 END) AS yoone_12_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '12mg' THEN quantity ELSE 0 END) AS yoone_12_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%15%' THEN quantity ELSE 0 END) AS yoone_15_quantity
|
SUM(CASE WHEN brand = 'yoone' AND strength = '15mg' THEN quantity ELSE 0 END) AS yoone_15_quantity
|
||||||
FROM order_sale
|
FROM order_sale
|
||||||
GROUP BY orderId
|
GROUP BY orderId
|
||||||
),
|
),
|
||||||
|
|
@ -247,22 +260,25 @@ export class StatisticsService {
|
||||||
LEFT JOIN order_item oi ON o.id = oi.orderId
|
LEFT JOIN order_item oi ON o.id = oi.orderId
|
||||||
WHERE o.date_paid IS NOT NULL
|
WHERE o.date_paid IS NOT NULL
|
||||||
AND o.date_paid >= '${start}' AND o.date_paid < '${end}'
|
AND o.date_paid >= '${start}' AND o.date_paid < '${end}'
|
||||||
AND o.status IN ('processing','completed')
|
AND o.status IN ('processing','completed')`;
|
||||||
|
if (siteId) sql += ` AND o.siteId=${siteId}`;
|
||||||
|
if (siteIds.length) sql += ` AND o.siteId IN (${siteIds.join(',')})`;
|
||||||
|
sql +=`
|
||||||
GROUP BY o.id, o.date_paid, o.customer_email, o.total, o.source_type, o.siteId, o.utm_source
|
GROUP BY o.id, o.date_paid, o.customer_email, o.total, o.source_type, o.siteId, o.utm_source
|
||||||
),
|
),
|
||||||
order_sales_summary AS (
|
order_sales_summary AS (
|
||||||
SELECT
|
SELECT
|
||||||
orderId,
|
orderId,
|
||||||
SUM(CASE WHEN name LIKE '%zyn%' THEN quantity ELSE 0 END) AS zyn_quantity,
|
SUM(CASE WHEN brand = 'zyn' THEN quantity ELSE 0 END) AS zyn_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' THEN quantity ELSE 0 END) AS yoone_quantity,
|
SUM(CASE WHEN brand = 'yoone' THEN quantity ELSE 0 END) AS yoone_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%zex%' THEN quantity ELSE 0 END) AS zex_quantity,
|
SUM(CASE WHEN brand = 'zex' THEN quantity ELSE 0 END) AS zex_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%3%' THEN quantity ELSE 0 END) AS yoone_3_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '3mg' THEN quantity ELSE 0 END) AS yoone_3_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%6%' THEN quantity ELSE 0 END) AS yoone_6_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '6mg' THEN quantity ELSE 0 END) AS yoone_6_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%9%' THEN quantity ELSE 0 END) AS yoone_9_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '9mg' THEN quantity ELSE 0 END) AS yoone_9_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%12%' THEN quantity ELSE 0 END) AS yoone_12_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '12mg' THEN quantity ELSE 0 END) AS yoone_12_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%15%' THEN quantity ELSE 0 END) AS yoone_15_quantity
|
SUM(CASE WHEN brand = 'yoone' AND strength = '15mg' THEN quantity ELSE 0 END) AS yoone_15_quantity
|
||||||
FROM order_sale
|
FROM order_sale
|
||||||
GROUP BY orderId
|
GROUP BY orderId
|
||||||
),
|
),
|
||||||
|
|
@ -440,22 +456,26 @@ export class StatisticsService {
|
||||||
LEFT JOIN order_item oi ON o.id = oi.orderId
|
LEFT JOIN order_item oi ON o.id = oi.orderId
|
||||||
WHERE o.date_paid IS NOT NULL
|
WHERE o.date_paid IS NOT NULL
|
||||||
AND o.date_paid >= '${start}' AND o.date_paid < '${end}'
|
AND o.date_paid >= '${start}' AND o.date_paid < '${end}'
|
||||||
|
`;
|
||||||
|
if (siteId) sql += ` AND o.siteId=${siteId}`;
|
||||||
|
if (siteIds.length) sql += ` AND o.siteId IN (${siteIds.join(',')})`;
|
||||||
|
sql +=`
|
||||||
AND o.status IN ('processing','completed')
|
AND o.status IN ('processing','completed')
|
||||||
GROUP BY o.id, o.date_paid, o.customer_email, o.total, o.source_type, o.siteId, o.utm_source
|
GROUP BY o.id, o.date_paid, o.customer_email, o.total, o.source_type, o.siteId, o.utm_source
|
||||||
),
|
),
|
||||||
order_sales_summary AS (
|
order_sales_summary AS (
|
||||||
SELECT
|
SELECT
|
||||||
orderId,
|
orderId,
|
||||||
SUM(CASE WHEN name LIKE '%zyn%' THEN quantity ELSE 0 END) AS zyn_quantity,
|
SUM(CASE WHEN brand = 'zyn' THEN quantity ELSE 0 END) AS zyn_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' THEN quantity ELSE 0 END) AS yoone_quantity,
|
SUM(CASE WHEN brand = 'yoone' THEN quantity ELSE 0 END) AS yoone_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%zex%' THEN quantity ELSE 0 END) AS zex_quantity,
|
SUM(CASE WHEN brand = 'zex' THEN quantity ELSE 0 END) AS zex_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND isPackage = 1 THEN quantity ELSE 0 END) AS yoone_G_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND isPackage = 0 THEN quantity ELSE 0 END) AS yoone_S_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%3%' THEN quantity ELSE 0 END) AS yoone_3_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '3mg' THEN quantity ELSE 0 END) AS yoone_3_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%6%' THEN quantity ELSE 0 END) AS yoone_6_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '6mg' THEN quantity ELSE 0 END) AS yoone_6_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%9%' THEN quantity ELSE 0 END) AS yoone_9_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '9mg' THEN quantity ELSE 0 END) AS yoone_9_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%12%' THEN quantity ELSE 0 END) AS yoone_12_quantity,
|
SUM(CASE WHEN brand = 'yoone' AND strength = '12mg' THEN quantity ELSE 0 END) AS yoone_12_quantity,
|
||||||
SUM(CASE WHEN name LIKE '%yoone%' AND name LIKE '%15%' THEN quantity ELSE 0 END) AS yoone_15_quantity
|
SUM(CASE WHEN brand = 'yoone' AND strength = '15mg' THEN quantity ELSE 0 END) AS yoone_15_quantity
|
||||||
FROM order_sale
|
FROM order_sale
|
||||||
GROUP BY orderId
|
GROUP BY orderId
|
||||||
),
|
),
|
||||||
|
|
@ -1314,7 +1334,14 @@ export class StatisticsService {
|
||||||
}
|
}
|
||||||
|
|
||||||
async getOrderSorce(params) {
|
async getOrderSorce(params) {
|
||||||
const sql = `
|
const { country } = params;
|
||||||
|
|
||||||
|
let siteIds = []
|
||||||
|
if (country) {
|
||||||
|
siteIds = await this.getSiteIds(country)
|
||||||
|
}
|
||||||
|
|
||||||
|
let sql = `
|
||||||
WITH cutoff_months AS (
|
WITH cutoff_months AS (
|
||||||
SELECT
|
SELECT
|
||||||
DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 7 MONTH), '%Y-%m') AS start_month,
|
DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 7 MONTH), '%Y-%m') AS start_month,
|
||||||
|
|
@ -1326,7 +1353,10 @@ export class StatisticsService {
|
||||||
DATE_FORMAT(MIN(date_paid), '%Y-%m') AS first_order_month,
|
DATE_FORMAT(MIN(date_paid), '%Y-%m') AS first_order_month,
|
||||||
SUM(total) AS first_order_total
|
SUM(total) AS first_order_total
|
||||||
FROM \`order\`
|
FROM \`order\`
|
||||||
WHERE status IN ('processing', 'completed')
|
WHERE status IN ('processing', 'completed')`;
|
||||||
|
if (siteIds.length!=0) sql += ` AND siteId IN ('${siteIds.join("','")}')`;
|
||||||
|
else sql += ` AND siteId IS NULL `;
|
||||||
|
sql += `
|
||||||
GROUP BY customer_email
|
GROUP BY customer_email
|
||||||
),
|
),
|
||||||
order_months AS (
|
order_months AS (
|
||||||
|
|
@ -1334,7 +1364,10 @@ export class StatisticsService {
|
||||||
customer_email,
|
customer_email,
|
||||||
DATE_FORMAT(date_paid, '%Y-%m') AS order_month
|
DATE_FORMAT(date_paid, '%Y-%m') AS order_month
|
||||||
FROM \`order\`
|
FROM \`order\`
|
||||||
WHERE status IN ('processing', 'completed')
|
WHERE status IN ('processing', 'completed')`;
|
||||||
|
if (siteIds.length!=0) sql += ` AND siteId IN ('${siteIds.join("','")}')`;
|
||||||
|
else sql += ` AND siteId IS NULL `;
|
||||||
|
sql += `
|
||||||
),
|
),
|
||||||
filtered_orders AS (
|
filtered_orders AS (
|
||||||
SELECT o.customer_email, o.order_month, u.first_order_month,u.first_order_total, c.start_month
|
SELECT o.customer_email, o.order_month, u.first_order_month,u.first_order_total, c.start_month
|
||||||
|
|
@ -1366,7 +1399,7 @@ export class StatisticsService {
|
||||||
ORDER BY order_month DESC, first_order_month_group
|
ORDER BY order_month DESC, first_order_month_group
|
||||||
`
|
`
|
||||||
|
|
||||||
const inactiveSql = `
|
let inactiveSql = `
|
||||||
WITH
|
WITH
|
||||||
cutoff_months AS (
|
cutoff_months AS (
|
||||||
SELECT
|
SELECT
|
||||||
|
|
@ -1381,7 +1414,10 @@ export class StatisticsService {
|
||||||
date_paid,
|
date_paid,
|
||||||
total
|
total
|
||||||
FROM \`order\`
|
FROM \`order\`
|
||||||
WHERE status IN ('processing', 'completed')
|
WHERE status IN ('processing', 'completed')`;
|
||||||
|
if (siteIds.length!=0) inactiveSql += ` AND siteId IN ('${siteIds.join("','")}')`;
|
||||||
|
else inactiveSql += ` AND siteId IS NULL `;
|
||||||
|
inactiveSql += `
|
||||||
),
|
),
|
||||||
|
|
||||||
filtered_users AS (
|
filtered_users AS (
|
||||||
|
|
@ -1524,4 +1560,13 @@ export class StatisticsService {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getSiteIds(country: any[]) {
|
||||||
|
const sql = `
|
||||||
|
SELECT DISTINCT sa.siteId as site_id FROM area a left join site_areas_area sa on a.id = sa.areaId WHERE a.code IN ('${country.join("','")}')
|
||||||
|
`
|
||||||
|
const res = await this.orderRepository.query(sql)
|
||||||
|
return res.map(item => item.site_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
/**
|
/**
|
||||||
*
|
* wp 接口参考:
|
||||||
* https://developer.wordpress.org/rest-api/reference/media/
|
* https://developer.wordpress.org/rest-api/reference/media/
|
||||||
|
* woocommerce:
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
import { Inject, Provide } from '@midwayjs/core';
|
import { Inject, Provide } from '@midwayjs/core';
|
||||||
import axios, { AxiosRequestConfig } from 'axios';
|
import axios, { AxiosRequestConfig } from 'axios';
|
||||||
|
|
@ -10,7 +12,7 @@ import { IPlatformService } from '../interface/platform.interface';
|
||||||
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto';
|
||||||
import * as FormData from 'form-data';
|
import * as FormData from 'form-data';
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import { WooProduct, WooVariation } from '../dto/woocommerce.dto';
|
import { WooProduct, WooVariation, WpMediaGetListParams } from '../dto/woocommerce.dto';
|
||||||
const MAX_PAGE_SIZE = 100;
|
const MAX_PAGE_SIZE = 100;
|
||||||
@Provide()
|
@Provide()
|
||||||
export class WPService implements IPlatformService {
|
export class WPService implements IPlatformService {
|
||||||
|
|
@ -1044,20 +1046,7 @@ export class WPService implements IPlatformService {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async fetchMediaPaged(site: any, params: Record<string, any> = {}) {
|
public async fetchMediaPaged(site: any, params: Partial<WpMediaGetListParams> = {}) {
|
||||||
const page = Number(params.page ?? 1);
|
|
||||||
const per_page = Number( params.per_page ?? 20);
|
|
||||||
const where = params.where && typeof params.where === 'object' ? params.where : {};
|
|
||||||
let orderby: string | undefined = params.orderby;
|
|
||||||
let order: 'asc' | 'desc' | undefined = params.orderDir as any;
|
|
||||||
if (!orderby && params.order && typeof params.order === 'object') {
|
|
||||||
const entries = Object.entries(params.order as Record<string, any>);
|
|
||||||
if (entries.length > 0) {
|
|
||||||
const [field, dir] = entries[0];
|
|
||||||
orderby = field;
|
|
||||||
order = String(dir).toLowerCase() === 'desc' ? 'desc' : 'asc';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const apiUrl = site.apiUrl;
|
const apiUrl = site.apiUrl;
|
||||||
const { consumerKey, consumerSecret } = site as any;
|
const { consumerKey, consumerSecret } = site as any;
|
||||||
const endpoint = 'wp/v2/media';
|
const endpoint = 'wp/v2/media';
|
||||||
|
|
@ -1066,17 +1055,21 @@ export class WPService implements IPlatformService {
|
||||||
const response = await axios.get(url, {
|
const response = await axios.get(url, {
|
||||||
headers: { Authorization: `Basic ${auth}` },
|
headers: { Authorization: `Basic ${auth}` },
|
||||||
params: {
|
params: {
|
||||||
...where,
|
...params,
|
||||||
...(params.search ? { search: params.search } : {}),
|
page: params.page ?? 1,
|
||||||
...(orderby ? { orderby } : {}),
|
per_page: params.per_page ?? 20,
|
||||||
...(order ? { order } : {}),
|
|
||||||
page,
|
|
||||||
per_page
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
// 检查是否有错误信息
|
||||||
|
if(response?.data?.message){
|
||||||
|
throw new Error(`获取${apiUrl}条媒体文件失败,原因为${response.data.message}`)
|
||||||
|
}
|
||||||
|
if(!Array.isArray(response.data)) {
|
||||||
|
throw new Error(`获取${apiUrl}条媒体文件失败,原因为返回数据不是数组`);
|
||||||
|
}
|
||||||
const total = Number(response.headers['x-wp-total'] || 0);
|
const total = Number(response.headers['x-wp-total'] || 0);
|
||||||
const totalPages = Number(response.headers['x-wp-totalpages'] || 0);
|
const totalPages = Number(response.headers['x-wp-totalpages'] || 0);
|
||||||
return { items: response.data, total, totalPages, page, per_page, page_size: per_page };
|
return { items: response.data, total, totalPages, page:params.page ?? 1, per_page: params.per_page ?? 20, page_size: params.per_page ?? 20 };
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 上传媒体文件
|
* 上传媒体文件
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
export const toArray = (value: any): any[] => {
|
||||||
|
if (Array.isArray(value)) return value;
|
||||||
|
if (value === undefined || value === null) return [];
|
||||||
|
return String(value).split(',').map(v => v.trim()).filter(Boolean);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const toNumber = (value: any): number | undefined => {
|
||||||
|
if (value === undefined || value === null || value === '') return undefined;
|
||||||
|
const n = Number(value);
|
||||||
|
return Number.isFinite(n) ? n : undefined;
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
// Test script for FreightwavesService createOrder method
|
||||||
|
|
||||||
|
const { FreightwavesService } = require('./dist/service/freightwaves.service');
|
||||||
|
|
||||||
|
async function testFreightwavesService() {
|
||||||
|
try {
|
||||||
|
// Create an instance of the FreightwavesService
|
||||||
|
const service = new FreightwavesService();
|
||||||
|
|
||||||
|
// Call the test method
|
||||||
|
console.log('Starting test for createOrder method...');
|
||||||
|
const result = await service.testQueryOrder();
|
||||||
|
|
||||||
|
console.log('Test completed successfully!');
|
||||||
|
console.log('Result:', result);
|
||||||
|
console.log('\nTo run the actual createOrder request:');
|
||||||
|
console.log('1. Uncomment the createOrder call in the testCreateOrder method');
|
||||||
|
console.log('2. Update the test-secret, test-partner-id with real credentials');
|
||||||
|
console.log('3. Run this script again');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Test failed:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run the test
|
||||||
|
testFreightwavesService();
|
||||||
Loading…
Reference in New Issue