Compare commits

..

2 Commits
main ... main

Author SHA1 Message Date
tikkhun 2b66970cc3 fix: 修正日期字段类型及处理逻辑
将woocommerce.dto.ts中的date_shipped字段类型从number改为string
统一各适配器中的日期处理逻辑,使用dayjs进行标准化转换
移除order.service.ts中冗余的日期转换代码
2026-01-30 19:06:33 +08:00
tikkhun e657578ef1 fix(service): 修改客户服务中的默认排序顺序
将默认排序从 orders ASC 改为 orders DESC 以符合业务需求
2026-01-30 16:34:48 +08:00
11 changed files with 194 additions and 377 deletions

View File

@ -388,15 +388,14 @@ export class ShopyyAdapter implements ISiteAdapter {
item.last_modified || item.last_modified ||
(typeof item.updated_at === 'string' ? item.updated_at : ''), (typeof item.updated_at === 'string' ? item.updated_at : ''),
fulfillment_status, fulfillment_status,
fulfillments: item.fulfillments?.map?.((f) => ({ fulfillments: item.fulfillments?.map?.((fulfillment) => ({
id: f.id, id: fulfillment.id,
tracking_number: f.tracking_number || '', tracking_number: fulfillment.tracking_number || '',
shipping_provider: f.tracking_company || '', shipping_provider: fulfillment.tracking_company || '',
shipping_method: f.tracking_company || '', shipping_method: fulfillment.tracking_company || '',
date_created: typeof fulfillment.created_at === 'number'
date_created: typeof f.created_at === 'number' ? dayjs(fulfillment.created_at * 1000).toISOString()
? new Date(f.created_at * 1000).toISOString() : dayjs(fulfillment.created_at || '').toISOString(),
: f.created_at || '',
// status: f.payment_tracking_status // status: f.payment_tracking_status
})) || [], })) || [],
raw: item, raw: item,

View File

@ -407,7 +407,7 @@ export class WooCommerceAdapter implements ISiteAdapter {
tracking_number: track.tracking_number, tracking_number: track.tracking_number,
tracking_product_code: track.tracking_product_code, tracking_product_code: track.tracking_product_code,
shipping_provider: track.tracking_provider, shipping_provider: track.tracking_provider,
date_created: dayjs(track.date_shipped).toString(), date_created: dayjs(Number(track.date_shipped)*1000).toISOString(),
}) })
}); });

View File

@ -42,7 +42,6 @@ import DictSeeder from '../db/seeds/dict.seeder';
import CategorySeeder from '../db/seeds/category.seeder'; import CategorySeeder from '../db/seeds/category.seeder';
import CategoryAttributeSeeder from '../db/seeds/category_attribute.seeder'; import CategoryAttributeSeeder from '../db/seeds/category_attribute.seeder';
import { SiteSku } from '../entity/site-sku.entity'; import { SiteSku } from '../entity/site-sku.entity';
import { logisticsAlias } from '../entity/logistics_alias.entity';
export default { export default {
// use for cookie sign key, should change to your own and keep security // use for cookie sign key, should change to your own and keep security
@ -89,7 +88,6 @@ export default {
Area, Area,
CategoryAttribute, CategoryAttribute,
Category, Category,
logisticsAlias,
], ],
synchronize: true, synchronize: true,
logging: false, logging: false,

View File

@ -25,7 +25,7 @@ export class ShipmentBookDTO {
shipmentPlatform: string; shipmentPlatform: string;
@ApiProperty() @ApiProperty()
@Rule(RuleType.any()) @Rule(RuleType.string())
courierCompany: string; courierCompany: string;
} }

View File

@ -373,7 +373,7 @@ export interface WooOrder {
export interface MetaDataFulfillment { export interface MetaDataFulfillment {
custom_tracking_link: string; custom_tracking_link: string;
custom_tracking_provider: string; custom_tracking_provider: string;
date_shipped: number; date_shipped: string;
source: string; source: string;
status_shipped: string; status_shipped: string;
tracking_id: string; tracking_id: string;

View File

@ -1,34 +0,0 @@
import { ApiProperty } from '@midwayjs/swagger';
import { Entity, CreateDateColumn, UpdateDateColumn, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('logistics_alias')
export class logisticsAlias {
@PrimaryGeneratedColumn()
id: number;
@ApiProperty({ type: 'string' })
@Column()
logistics_company: string
@ApiProperty({ type: 'string' })
@Column()
logistics_alias: string
@ApiProperty({ type: 'string' })
@Column()
platform: string
// 是否可删除
@Column({ default: true, comment: '是否可删除' })
deletable: boolean;
// 创建时间
@CreateDateColumn()
createdAt: Date;
// 更新时间
@UpdateDateColumn()
updatedAt: Date;
}

View File

@ -1,96 +0,0 @@
import { Inject, Provide } from '@midwayjs/core';
import axios from 'axios';
import dayjs = require('dayjs');
import utc = require('dayjs/plugin/utc');
import timezone = require('dayjs/plugin/timezone');
// 扩展dayjs功能
dayjs.extend(utc);
dayjs.extend(timezone);
// Wintopay 物流更新请求接口
interface LogisticsUpdateRequest {
trade_id: string; // 订单的流水号
track_number: string; // 物流单号
track_brand: string; // 物流公司编号
}
// Wintopay 物流更新响应接口
interface LogisticsUpdateResponse {
code: string;
message: string;
data: {
trade_id: string;
track_brand: string;
track_number: string;
time: number;
};
error: any;
request_id: string;
}
@Provide()
export class WintopayService {
@Inject() logger;
// 默认配置
private config = {
//测试环境配置,在生产环境记得换掉
apiBaseUrl: 'https://stage-merchant-api.wintopay.com',
Authorization: 'Bearer kV8w1er8dFw9p9g2kb0mer398hD8hfWk',
};
// 发送请求
private async sendRequest<T>(url: string, data: any): Promise<T> {
try {
const headers = {
'Content-Type': 'application/json',
'Authorization': this.config.Authorization,
};
// 发送请求 - 临时禁用SSL证书验证以解决UNABLE_TO_VERIFY_LEAF_SIGNATURE错误
const response = await axios.post<T>(
`${this.config.apiBaseUrl}${url}`,
data,
{
headers,
httpsAgent: new (require('https').Agent)({
rejectUnauthorized: false
})
}
);
return response.data;
} catch (error) {
this.logger.error('Wintopay API请求失败:', error);
throw error;
}
}
/**
*
* @param params
* @returns
*/
async logisticsUpdate(params: LogisticsUpdateRequest): Promise<LogisticsUpdateResponse> {
try {
this.logger.info('开始更新物流信息:', params);
const response = await this.sendRequest<LogisticsUpdateResponse>('/v1/logistics/update', params);
this.logger.info('物流更新成功:', response);
return response;
} catch (error: any) {
this.logger.error('物流更新失败:', error);
// 处理API返回的错误
if (error.response?.data) {
throw new Error(`物流更新失败: ${error.response.data.message || '未知错误'}`);
}
throw new Error(`物流更新请求失败: ${error.message || '网络错误'}`);
}
}
}

View File

@ -327,20 +327,17 @@ export class LogisticsService {
let resShipmentFee: any; let resShipmentFee: any;
if (data.shipmentPlatform === 'uniuni') { if (data.shipmentPlatform === 'uniuni') {
resShipmentFee = await this.uniExpressService.getRates(reqBody); resShipmentFee = await this.uniExpressService.getRates(reqBody);
if (resShipmentFee.status !== 'SUCCESS') {
throw new Error(resShipmentFee.ret_msg);
}
return resShipmentFee.data.totalAfterTax * 100;
} else if (data.shipmentPlatform === 'freightwaves') { } else if (data.shipmentPlatform === 'freightwaves') {
const fre_reqBody = await this.convertToFreightwavesRateTry(data); const fre_reqBody = await this.convertToFreightwavesRateTry(data);
resShipmentFee = await this.freightwavesService.rateTry(fre_reqBody); resShipmentFee = await this.freightwavesService.rateTry(fre_reqBody);
return resShipmentFee.totalAmount * 100;
} else { } else {
throw new Error('不支持的运单平台'); throw new Error('不支持的运单平台');
} }
if (resShipmentFee.status !== 'SUCCESS') {
throw new Error(resShipmentFee.ret_msg);
}
return resShipmentFee.data.totalAfterTax * 100;
} catch (e) { } catch (e) {
throw e; throw e;
} }
@ -363,7 +360,12 @@ export class LogisticsService {
try { try {
resShipmentOrder = await this.mepShipment(data, order); resShipmentOrder = await this.mepShipment(data, order);
// 记录物流信息,并将订单状态转到完成,uniuni状态为SUCCESStms.freightwaves状态为00000200
if (resShipmentOrder.status === 'SUCCESS' || resShipmentOrder.code === '00000200') {
order.orderStatus = ErpOrderStatus.COMPLETED; order.orderStatus = ErpOrderStatus.COMPLETED;
} else {
throw new Error('运单生成失败');
}
const dataSource = this.dataSourceManager.getDataSource('default'); const dataSource = this.dataSourceManager.getDataSource('default');
let transactionError = undefined; let transactionError = undefined;
let shipmentId = undefined; let shipmentId = undefined;
@ -382,8 +384,8 @@ export class LogisticsService {
unique_id = resShipmentOrder.data.uni_order_sn; unique_id = resShipmentOrder.data.uni_order_sn;
state = resShipmentOrder.data.uni_status_code; state = resShipmentOrder.data.uni_status_code;
} else { } else {
co = resShipmentOrder.shipOrderId; co = resShipmentOrder.data?.shipOrderId;
unique_id = resShipmentOrder.shipOrderId; unique_id = resShipmentOrder.data?.shipOrderId;
state = ErpOrderStatus.COMPLETED; state = ErpOrderStatus.COMPLETED;
} }
@ -726,20 +728,14 @@ export class LogisticsService {
}; };
// 添加运单 // 添加运单
resShipmentOrder = await this.uniExpressService.createShipment(reqBody); resShipmentOrder = await this.uniExpressService.createShipment(reqBody);
// 记录物流信息,并将订单状态转到完成,uniuni状态为SUCCESStms.freightwaves状态为00000200
if (resShipmentOrder.status !== 'SUCCESS') {
throw new Error('运单生成失败');
}
} }
if (data.shipmentPlatform === 'freightwaves') { if (data.shipmentPlatform === 'freightwaves') {
// 根据TMS系统对接说明文档格式化参数 // 根据TMS系统对接说明文档格式化参数
const reqBody: any = { const reqBody: any = {
// shipCompany: 'UPSYYZ7000NEW', // shipCompany: 'UPSYYZ7000NEW',
shipCompany: data.courierCompany, shipCompany: data.courierCompany || "",
partnerOrderNumber: order.siteId + '-' + order.externalOrderId, partnerOrderNumber: order.siteId + '-1-' + order.externalOrderId,
warehouseId: '25072621030107400060', warehouseId: '25072621030107400060',
shipper: { shipper: {
name: data.details.origin.contact_name, // 姓名 name: data.details.origin.contact_name, // 姓名
@ -837,7 +833,7 @@ export class LogisticsService {
// 转换为RateTryRequest格式 // 转换为RateTryRequest格式
const r = { const r = {
//shipCompany: 'UPSYYZ7000NEW', // 必填但ShipmentFeeBookDTO中缺少 //shipCompany: 'UPSYYZ7000NEW', // 必填但ShipmentFeeBookDTO中缺少
shipCompany: data.courierCompany, shipCompany: data.courierCompany || "",
partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成 partnerOrderNumber: `order-${Date.now()}`, // 必填,使用时间戳生成
warehouseId: '25072621030107400060', // 可选使用stockPointId转换 warehouseId: '25072621030107400060', // 可选使用stockPointId转换
shipper: { shipper: {

View File

@ -42,7 +42,6 @@ import { UnifiedOrderDTO } from '../dto/site-api.dto';
import { CustomerService } from './customer.service'; import { CustomerService } from './customer.service';
import { ProductService } from './product.service'; import { ProductService } from './product.service';
import { Site } from '../entity/site.entity'; import { Site } from '../entity/site.entity';
import { logisticsAlias } from '../entity/logistics_alias.entity';
@Provide() @Provide()
export class OrderService { export class OrderService {
@ -55,9 +54,6 @@ export class OrderService {
@InjectEntityModel(Order) @InjectEntityModel(Order)
orderModel: Repository<Order>; orderModel: Repository<Order>;
@InjectEntityModel(logisticsAlias)
logisticsAliasModel: Repository<logisticsAlias>;
@InjectEntityModel(User) @InjectEntityModel(User)
userModel: Repository<User>; userModel: Repository<User>;
@ -634,7 +630,7 @@ export class OrderService {
await this.saveOrderItem(entity); await this.saveOrderItem(entity);
// 为每个订单项创建对应的销售项(OrderSale) // 为每个订单项创建对应的销售项(OrderSale)
const site = await this.siteService.get(siteId); const site = await this.siteService.get(siteId);
await this.saveOrderSale(entity, site); await this.saveOrderSale(entity,site);
} }
} }
@ -724,7 +720,7 @@ export class OrderService {
*/ */
// TODO 这里存的是库存商品实际 // TODO 这里存的是库存商品实际
// 所以叫做 orderInventoryItems 可能更合适 // 所以叫做 orderInventoryItems 可能更合适
async saveOrderSale(orderItem: OrderItem, site: Site) { async saveOrderSale(orderItem: OrderItem,site:Site) {
const currentOrderSale = await this.orderSaleModel.find({ const currentOrderSale = await this.orderSaleModel.find({
where: { where: {
siteId: orderItem.siteId, siteId: orderItem.siteId,
@ -737,13 +733,14 @@ export class OrderService {
if (!orderItem.sku) return; if (!orderItem.sku) return;
// 从数据库查询产品,关联查询组件 // 从数据库查询产品,关联查询组件
const componentDetails = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name }, orderItem.quantity, site); const componentDetails = await this.productService.getComponentDetailFromSiteSku({ sku: orderItem.sku, name: orderItem.name }, site);
if (!componentDetails?.length) { if(!componentDetails?.length){
return return
} }
const orderSales: OrderSale[] = componentDetails.map(({ product, parentProduct, quantity }) => { const orderSales: OrderSale[] = componentDetails.map(({product, parentProduct, quantity}) => {
if (!product) return null if (!product) return null
console.log('product',product)
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,
@ -1058,13 +1055,6 @@ export class OrderService {
// 删除原始 ID // 删除原始 ID
delete item.id; delete item.id;
// 转换时间戳为日期格式
if (item.date_created && typeof item.date_created === 'number') {
item.date_created = new Date(item.date_created * 1000);
} else if (item.date_created && typeof item.date_created === 'string') {
item.date_created = new Date(item.date_created);
}
// 创建履约实体 // 创建履约实体
const fulfillment = plainToClass(OrderFulfillment, item); const fulfillment = plainToClass(OrderFulfillment, item);
@ -2458,18 +2448,18 @@ export class OrderService {
*/ */
// TODO // TODO
async exportOrder(ids: number[]) { async exportOrder(ids: number[]) {
// 日期 订单号 姓名地址 邮箱 号码 盒数 换盒数 换货内容 快递号 商品1 数量1 商品2 数量2... // 日期 订单号 姓名地址 邮箱 号码 订单内容 盒数 换盒数 换货内容 快递号
interface ExportData { interface ExportData {
'日期': string; '日期': string;
'订单号': string; '订单号': string;
'姓名地址': string; '姓名地址': string;
'邮箱': string; '邮箱': string;
'号码': string; '号码': string;
'订单内容': string;
'盒数': number; '盒数': number;
'换盒数': number; '换盒数': number;
'换货内容': string; '换货内容': string;
'快递号': string; '快递号': string;
[key: string]: any; // 支持动态添加的商品和数量列
} }
try { try {
@ -2516,15 +2506,6 @@ export class OrderService {
return acc; return acc;
}, {} as Record<number, OrderItem[]>); }, {} as Record<number, OrderItem[]>);
// 计算最大商品数量
let maxItemsCount = 0;
orders.forEach(order => {
const items = orderItemsByOrderId[order.id] || [];
if (items.length > maxItemsCount) {
maxItemsCount = items.length;
}
});
// 构建导出数据 // 构建导出数据
const exportDataList: ExportData[] = orders.map(order => { const exportDataList: ExportData[] = orders.map(order => {
// 获取订单的订单项 // 获取订单的订单项
@ -2533,6 +2514,9 @@ export class OrderService {
// 计算总盒数 // 计算总盒数
const boxCount = items.reduce((total, item) => total + item.quantity, 0); const boxCount = items.reduce((total, item) => total + item.quantity, 0);
// 构建订单内容
const orderContent = items.map(item => `${item.name} x ${item.quantity}`).join('; ');
// 构建姓名地址 // 构建姓名地址
const shipping = order.shipping; const shipping = order.shipping;
const billing = order.billing; const billing = order.billing;
@ -2557,32 +2541,18 @@ export class OrderService {
const exchangeBoxCount = 0; const exchangeBoxCount = 0;
const exchangeContent = ''; const exchangeContent = '';
// 构建基础数据对象 return {
const baseData: ExportData = {
'日期': order.date_created?.toISOString().split('T')[0] || '', '日期': order.date_created?.toISOString().split('T')[0] || '',
'订单号': order.externalOrderId || '', '订单号': order.externalOrderId || '',
'姓名地址': nameAddress, '姓名地址': nameAddress,
'邮箱': order.customer_email || '', '邮箱': order.customer_email || '',
'号码': phone, '号码': phone,
'订单内容': orderContent,
'盒数': boxCount, '盒数': boxCount,
'换盒数': exchangeBoxCount, '换盒数': exchangeBoxCount,
'换货内容': exchangeContent, '换货内容': exchangeContent,
'快递号': trackingNumber '快递号': trackingNumber
}; };
// 添加商品和数量列
items.forEach((item, index) => {
baseData[`商品${index + 1}`] = item.name;
baseData[`数量${index + 1}`] = item.quantity;
});
// 填充空值,确保所有行的列数一致
for (let i = items.length; i < maxItemsCount; i++) {
baseData[`商品${i + 1}`] = '';
baseData[`数量${i + 1}`] = '';
}
return baseData;
}); });
// 返回CSV字符串内容给前端 // 返回CSV字符串内容给前端
@ -2870,11 +2840,6 @@ export class OrderService {
chargeback: headers.indexOf('拒付') chargeback: headers.indexOf('拒付')
}; };
const logisticsAliases = await this.logisticsAliasModel.find();
// 构建物流公司别名映射
const logisticsAliasMap = new Map(logisticsAliases.map(alias => [alias.logistics_alias, alias.logistics_company]));
// 遍历数据行 // 遍历数据行
for (let i = 0; i < dataRows.length; i++) { for (let i = 0; i < dataRows.length; i++) {
const row = dataRows[i]; const row = dataRows[i];
@ -2886,11 +2851,9 @@ export class OrderService {
} }
try { try {
let orderNumbers = orderNumber; let orderNumbers="";
// 确保 orderNumber 是字符串类型 if (orderNumber.includes('_')&&orderNumber.includes('-')) {
const orderNumberStr = String(orderNumber); orderNumbers = orderNumber.split('_')[0].toString();
if (orderNumberStr.includes('_') && orderNumberStr.includes('-')) {
orderNumbers = orderNumberStr.split('_')[0].toString();
orderNumbers = orderNumbers.split('-')[1]; orderNumbers = orderNumbers.split('-')[1];
} }
// 通过订单号查询订单 // 通过订单号查询订单
@ -2901,11 +2864,9 @@ export class OrderService {
if (fulfillments && fulfillments.length > 0) { if (fulfillments && fulfillments.length > 0) {
const fulfillment = fulfillments[0]; // 假设每个订单只有一个物流信息 const fulfillment = fulfillments[0]; // 假设每个订单只有一个物流信息
const shipping_provider = logisticsAliasMap.get(fulfillment.shipping_provider);
// 回填物流信息 // 回填物流信息
if (columnIndices.logisticsCompany !== -1) { if (columnIndices.logisticsCompany !== -1) {
row[columnIndices.logisticsCompany] = shipping_provider || ''; row[columnIndices.logisticsCompany] = fulfillment.shipping_provider || '';
} }
if (columnIndices.trackingNumber !== -1) { if (columnIndices.trackingNumber !== -1) {
row[columnIndices.trackingNumber] = fulfillment.tracking_number || ''; row[columnIndices.trackingNumber] = fulfillment.tracking_number || '';

View File

@ -1785,14 +1785,8 @@ export class ProductService {
attributes: attributes.length > 0 ? attributes : undefined, attributes: attributes.length > 0 ? attributes : undefined,
} }
} }
isMixedSku(sku: string) { // 获取库存单品列表
const splitSKu = sku.split('-') async getComponentDetailFromSiteSku(siteProduct: { sku: string, name?: string }, site: Site): Promise<{ product: Product,parentProduct?: Product, quantity: number }[]> {
const last = splitSKu[splitSKu.length - 1]
const second = splitSKu[splitSKu.length - 2]
// 这里判断 second 是否是数字
return sku.includes('-MX-') || sku.includes('-Mixed-') || /^\d+$/.test(second) && /^\d+$/.test(last)
}
async getComponentDetailFromSiteSku(siteProduct: { sku: string, name: string }, quantity: number = 1, site: Site): Promise<{ product: Product, parentProduct?: Product, quantity: number }[]> {
if (!siteProduct.sku) { if (!siteProduct.sku) {
throw new Error('siteSku 不能为空') throw new Error('siteSku 不能为空')
} }
@ -1801,20 +1795,21 @@ export class ProductService {
if (!product) return if (!product) return
if (!product?.components?.length) { if(!product?.components?.length){
return [{ return [{
product, product,
quantity quantity:1
}] }]
} }
return await Promise.all(product.components.map(async comp => { return await Promise.all(product.components.map(async comp => {
return { return {
product: await this.productModel.findOne({ product: await this.productModel.findOne({
where: { id: comp.productId }, where: { sku: comp.sku },
relations: ['category', 'attributes', 'attributes.dict', 'components']
}), }),
parentProduct: product, // 这里得记录一下他的爸爸用来记录 parentProduct: product, // 这里得记录一下他的爸爸用来记录
quantity: comp.quantity * quantity, quantity: comp.quantity,
} }
})) }))
} }
@ -2155,7 +2150,7 @@ export class ProductService {
.leftJoinAndSelect('product.components', 'components') .leftJoinAndSelect('product.components', 'components')
.leftJoinAndSelect('product.siteSkus', 'siteSku') .leftJoinAndSelect('product.siteSkus', 'siteSku')
.where('siteSku.sku LIKE :siteSku', { siteSku: `%${siteSku}%` }) .where('siteSku.sku LIKE :siteSku', { siteSku: `%${siteSku}%` })
.orWhere('product.sku = :siteSku', { siteSku }); .orWhere('product.sku = :siteSku', { siteSku })
if (site) { if (site) {
queryBuilder.orWhere('product.sku = :processedSku', { queryBuilder.orWhere('product.sku = :processedSku', {

View File

@ -75,7 +75,7 @@ export class WPService implements IPlatformService {
} }
const data = res.data as T[]; const data = res.data as T[];
const totalPages = Number(res.headers?.['x-wp-totalpages'] ?? 1); const totalPages = Number(res.headers?.['x-wp-totalpages'] ?? 1);
const total = Number(res.headers?.['x-wp-total'] ?? 1) const total = Number(res.headers?.['x-wp-total']?? 1)
return { items: data, total, totalPages, page, per_page, page_size: per_page }; return { items: data, total, totalPages, page, per_page, page_size: per_page };
} }
@ -206,7 +206,7 @@ export class WPService implements IPlatformService {
const auth = Buffer.from(`${consumerKey}:${consumerSecret}`).toString( const auth = Buffer.from(`${consumerKey}:${consumerSecret}`).toString(
'base64' 'base64'
); );
console.log(`!!!wpApiUrl, consumerKey, consumerSecret, auth`, site.apiUrl, consumerKey, consumerSecret, auth) console.log(`!!!wpApiUrl, consumerKey, consumerSecret, auth`,site.apiUrl, consumerKey, consumerSecret, auth)
let hasMore = true; let hasMore = true;
while (hasMore) { while (hasMore) {
const config: AxiosRequestConfig = { const config: AxiosRequestConfig = {
@ -259,8 +259,8 @@ export class WPService implements IPlatformService {
// 导出 WooCommerce 产品为特殊CSV(平台特性) // 导出 WooCommerce 产品为特殊CSV(平台特性)
async exportProductsCsvSpecial(site: any, page: number = 1, pageSize: number = 100): Promise<string> { async exportProductsCsvSpecial(site: any, page: number = 1, pageSize: number = 100): Promise<string> {
const list = await this.getProducts(site, { page, per_page: pageSize }); const list = await this.getProducts(site, { page, per_page: pageSize });
const header = ['id', 'name', 'type', 'status', 'sku', 'regular_price', 'sale_price', 'stock_status', 'stock_quantity']; const header = ['id','name','type','status','sku','regular_price','sale_price','stock_status','stock_quantity'];
const rows = (list.items || []).map((p: any) => [p.id, p.name, p.type, p.status, p.sku, p.regular_price, p.sale_price, p.stock_status, p.stock_quantity]); const rows = (list.items || []).map((p: any) => [p.id,p.name,p.type,p.status,p.sku,p.regular_price,p.sale_price,p.stock_status,p.stock_quantity]);
const csv = [header.join(','), ...rows.map(r => r.map(v => String(v ?? '')).join(','))].join('\n'); const csv = [header.join(','), ...rows.map(r => r.map(v => String(v ?? '')).join(','))].join('\n');
return csv; return csv;
} }
@ -289,7 +289,7 @@ export class WPService implements IPlatformService {
const res = await api.get(`orders/${orderId}`); const res = await api.get(`orders/${orderId}`);
return res.data as Record<string, any>; return res.data as Record<string, any>;
} }
async getOrders(siteId: number, params: Record<string, any> = {}): Promise<Record<string, any>[]> { async getOrders(siteId: number,params: Record<string, any> = {}): Promise<Record<string, any>[]> {
const site = await this.siteService.get(siteId); const site = await this.siteService.get(siteId);
const api = this.createApi(site, 'wc/v3'); const api = this.createApi(site, 'wc/v3');
return await this.sdkGetAll<Record<string, any>>(api, 'orders', params); return await this.sdkGetAll<Record<string, any>>(api, 'orders', params);
@ -805,7 +805,7 @@ export class WPService implements IPlatformService {
const result = response.data; const result = response.data;
// 转换 WooCommerce 批量操作结果为统一格式 // 转换 WooCommerce 批量操作结果为统一格式
const errors: Array<{ identifier: string, error: string }> = []; const errors: Array<{identifier: string, error: string}> = [];
// WooCommerce 返回格式: { create: [...], update: [...], delete: [...] } // WooCommerce 返回格式: { create: [...], update: [...], delete: [...] }
// 错误信息可能在每个项目的 error 字段中 // 错误信息可能在每个项目的 error 字段中
@ -1046,7 +1046,7 @@ export class WPService implements IPlatformService {
}; };
} }
public async fetchMediaPaged(site: any, params: Partial<WpMediaGetListParams> = {}) { public async fetchMediaPaged(site: any, params: Partial<WpMediaGetListParams> = {}) {
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';
@ -1061,15 +1061,15 @@ export class WPService implements IPlatformService {
} }
}); });
// 检查是否有错误信息 // 检查是否有错误信息
if (response?.data?.message) { if(response?.data?.message){
throw new Error(`获取${apiUrl}条媒体文件失败,原因为${response.data.message}`) throw new Error(`获取${apiUrl}条媒体文件失败,原因为${response.data.message}`)
} }
if (!Array.isArray(response.data)) { if(!Array.isArray(response.data)) {
throw new Error(`获取${apiUrl}条媒体文件失败,原因为返回数据不是数组`); 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: params.page ?? 1, per_page: params.per_page ?? 20, page_size: params.per_page ?? 20 }; return { items: response.data, total, totalPages, page:params.page ?? 1, per_page: params.per_page ?? 20, page_size: params.per_page ?? 20 };
} }
/** /**
* *
@ -1205,12 +1205,10 @@ export class WPService implements IPlatformService {
throw new Error('source_url 不存在'); throw new Error('source_url 不存在');
} }
// 下载源文件为 Buffer // 下载源文件为 Buffer
const resp = await axios.get(srcUrl, { const resp = await axios.get(srcUrl, { responseType: 'arraybuffer', timeout: 30000,
responseType: 'arraybuffer', timeout: 30000,
headers: { headers: {
'User-Agent': 'Mozilla/5.0 (compatible; Node.js Axios)', 'User-Agent': 'Mozilla/5.0 (compatible; Node.js Axios)',
} } });
});
const inputBuffer = Buffer.from(resp.data); const inputBuffer = Buffer.from(resp.data);
// 条件判断 如果下载的 Buffer 为空则抛出错误 // 条件判断 如果下载的 Buffer 为空则抛出错误
if (!inputBuffer || inputBuffer.length === 0) { if (!inputBuffer || inputBuffer.length === 0) {