From 3f5fb6adbabbf9e52fb9b1a2827708c4626b7dc2 Mon Sep 17 00:00:00 2001 From: tikkhun Date: Thu, 8 Jan 2026 20:40:12 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=87=8D=E6=9E=84=E7=AB=99=E7=82=B9API?= =?UTF-8?q?=E9=80=82=E9=85=8D=E5=99=A8=E6=8E=A5=E5=8F=A3=E5=B9=B6=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E5=A4=9A=E5=B9=B3=E5=8F=B0=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refactor(adapter): 重构适配器接口结构,分离不同实体的映射方法 feat(product): 增强产品同步功能,支持通过SKU查找和更新 fix(order): 修复订单同步和履约相关的问题 feat(template): 改进SKU模板逻辑,支持按分类属性排序 chore: 移除未使用的媒体控制器和相关代码 --- package-lock.json | 17 - src/adapter/shopyy.adapter.ts | 1313 +++++++++++------ src/adapter/woocommerce.adapter.ts | 1763 +++++++++++++---------- src/controller/media.controller.ts | 79 - src/controller/product.controller.ts | 43 +- src/controller/site-api.controller.ts | 88 +- src/controller/webhook.controller.ts | 97 +- src/db/seeds/template.seeder.ts | 39 +- src/dto/shopyy.dto.ts | 94 +- src/dto/site-api.dto.ts | 8 + src/dto/woocommerce.dto.ts | 4 +- src/entity/dict.entity.ts | 4 + src/entity/product.entity.ts | 3 - src/interface/site-adapter.interface.ts | 468 ++++-- src/job/sync_shipment.job.ts | 12 +- src/service/order.service.ts | 2 +- src/service/product.service.ts | 118 +- src/service/shopyy.service.ts | 43 +- src/service/site-api.service.ts | 67 +- src/service/wp.service.ts | 10 +- src/transformer/database.transformer.ts | 1 + src/transformer/file.transformer.ts | 1 + src/transformer/shopyy.transformer.ts | 0 src/transformer/woocommerce.adpater.ts | 8 + 24 files changed, 2576 insertions(+), 1706 deletions(-) delete mode 100644 src/controller/media.controller.ts create mode 100644 src/transformer/database.transformer.ts create mode 100644 src/transformer/file.transformer.ts create mode 100644 src/transformer/shopyy.transformer.ts create mode 100644 src/transformer/woocommerce.adpater.ts diff --git a/package-lock.json b/package-lock.json index e207cd1..405c79b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -523,23 +523,6 @@ "node": ">=18" } }, - "node_modules/@faker-js/faker": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/@faker-js/faker/-/faker-10.1.0.tgz", - "integrity": "sha512-C3mrr3b5dRVlKPJdfrAXS8+dq+rq8Qm5SNRazca0JKgw1HQERFmrVb0towvMmw5uu8hHKNiQasMaR/tydf3Zsg==", - "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": { "version": "3.0.0", "resolved": "https://registry.npmmirror.com/@hapi/bourne/-/bourne-3.0.0.tgz", diff --git a/src/adapter/shopyy.adapter.ts b/src/adapter/shopyy.adapter.ts index 10c51fb..cba2c5a 100644 --- a/src/adapter/shopyy.adapter.ts +++ b/src/adapter/shopyy.adapter.ts @@ -17,19 +17,26 @@ import { UnifiedAddressDTO, UnifiedShippingLineDTO, OrderFulfillmentStatus, - FulfillmentDTO + FulfillmentDTO, + CreateReviewDTO, + CreateVariationDTO, + UpdateReviewDTO, } from '../dto/site-api.dto'; import { UnifiedPaginationDTO, UnifiedSearchParamsDTO, } from '../dto/api.dto'; import { + ShopyyAllProductQuery, ShopyyCustomer, ShopyyOrder, + ShopyyOrderQuery, ShopyyProduct, + ShopyyProductQuery, ShopyyVariant, ShopyyWebhook, } from '../dto/shopyy.dto'; import { OrderStatus, } from '../enums/base.enum'; +import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto'; export class ShopyyAdapter implements ISiteAdapter { shopyyFinancialStatusMap= { '200': '待支付', @@ -42,117 +49,184 @@ export class ShopyyAdapter implements ISiteAdapter { '290':"已取消", } constructor(private site: any, private shopyyService: ShopyyService) { - this.mapCustomer = this.mapCustomer.bind(this); - this.mapProduct = this.mapProduct.bind(this); - this.mapVariation = this.mapVariation.bind(this); - this.mapOrder = this.mapOrder.bind(this); - this.mapMedia = this.mapMedia.bind(this); - // this.mapSubscription = this.mapSubscription.bind(this); + this.mapPlatformToUnifiedCustomer = this.mapPlatformToUnifiedCustomer.bind(this); + this.mapPlatformToUnifiedProduct = this.mapPlatformToUnifiedProduct.bind(this); + this.mapPlatformToUnifiedVariation = this.mapPlatformToUnifiedVariation.bind(this); + this.mapPlatformToUnifiedOrder = this.mapPlatformToUnifiedOrder.bind(this); + this.mapPlatformToUnifiedMedia = this.mapPlatformToUnifiedMedia.bind(this); + // this.mapPlatformToUnifiedSubscription = this.mapPlatformToUnifiedSubscription.bind(this); } - mapMedia(item: any): UnifiedMediaDTO { + // ========== 客户映射方法 ========== + mapPlatformToUnifiedCustomer(item: ShopyyCustomer): UnifiedCustomerDTO { + // 处理多地址结构 + const addresses = item.addresses || []; + const defaultAddress = item.default_address || (addresses.length > 0 ? addresses[0] : {}); + + // 尝试从地址列表中获取billing和shipping + // 如果没有明确区分,默认使用默认地址或第一个地址 + const billingAddress = defaultAddress; + const shippingAddress = defaultAddress; + + const billing = { + first_name: billingAddress.first_name || item.first_name || '', + last_name: billingAddress.last_name || item.last_name || '', + fullname: billingAddress.name || `${billingAddress.first_name || item.first_name || ''} ${billingAddress.last_name || item.last_name || ''}`.trim(), + company: billingAddress.company || '', + email: item.email || '', + phone: billingAddress.phone || item.contact || '', + address_1: billingAddress.address1 || '', + address_2: billingAddress.address2 || '', + city: billingAddress.city || '', + state: billingAddress.province || '', + postcode: billingAddress.zip || '', + country: billingAddress.country_name || billingAddress.country_code || item.country?.country_name || '' + }; + + const shipping = { + first_name: shippingAddress.first_name || item.first_name || '', + last_name: shippingAddress.last_name || item.last_name || '', + fullname: shippingAddress.name || `${shippingAddress.first_name || item.first_name || ''} ${shippingAddress.last_name || item.last_name || ''}`.trim(), + company: shippingAddress.company || '', + address_1: shippingAddress.address1 || '', + address_2: shippingAddress.address2 || '', + city: shippingAddress.city || '', + state: shippingAddress.province || '', + postcode: shippingAddress.zip || '', + country: shippingAddress.country_name || shippingAddress.country_code || item.country?.country_name || '' + }; + + return { + id: item.id || item.customer_id, + orders: Number(item.orders_count ?? item.order_count ?? item.orders ?? 0), + total_spend: Number(item.total_spent ?? item.total_spend_amount ?? item.total_spend_money ?? 0), + first_name: item.first_name || item.firstname || '', + last_name: item.last_name || item.lastname || '', + fullname: item.fullname || item.customer_name || `${item.first_name || item.firstname || ''} ${item.last_name || item.lastname || ''}`.trim(), + email: item.email || item.customer_email || '', + phone: item.contact || billing.phone || item.phone || '', + billing, + shipping, + date_created: + typeof item.created_at === 'number' + ? new Date(item.created_at * 1000).toISOString() + : (typeof item.created_at === 'string' ? item.created_at : item.date_added || ''), + date_modified: + typeof item.updated_at === 'number' + ? new Date(item.updated_at * 1000).toISOString() + : (typeof item.updated_at === 'string' ? item.updated_at : item.date_updated || ''), + raw: item, + }; + } + + mapUnifiedToPlatformCustomer(data: Partial) { + return data + } + + async getCustomer(where: {id?: string | number,email?: string,phone?: string}): Promise { + if(!where.id && !where.email && !where.phone){ + throw new Error('必须传入 id 或 email 或 phone') + } + const customer = await this.shopyyService.getCustomer(this.site, where.id); + return this.mapPlatformToUnifiedCustomer(customer); + } + + async getCustomers(params: UnifiedSearchParamsDTO): Promise> { + const { items, total, totalPages, page, per_page } = + await this.shopyyService.fetchCustomersPaged(this.site, params); + return { + items: items.map(this.mapPlatformToUnifiedCustomer.bind(this)), + total, + totalPages, + page, + per_page + }; + } + + async getAllCustomers(params?: UnifiedSearchParamsDTO): Promise { + // Shopyy getAllCustomers 暂未实现 + throw new Error('Shopyy getAllCustomers 暂未实现'); + } + + async createCustomer(data: Partial): Promise { + const createdCustomer = await this.shopyyService.createCustomer(this.site, data); + return this.mapPlatformToUnifiedCustomer(createdCustomer); + } + + async updateCustomer(where: {id: string | number}, data: Partial): Promise { + const updatedCustomer = await this.shopyyService.updateCustomer(this.site, where.id, data); + return this.mapPlatformToUnifiedCustomer(updatedCustomer); + } + + async deleteCustomer(where: {id: string | number}): Promise { + return await this.shopyyService.deleteCustomer(this.site, where.id); + } + + batchProcessCustomers?(data: BatchOperationDTO): Promise { + throw new Error('Method not implemented.'); + } + + // ========== 媒体映射方法 ========== + mapPlatformToUnifiedMedia(data: any): UnifiedMediaDTO { // 映射媒体项目 return { - id: item.id, - date_created: item.created_at, - date_modified: item.updated_at, - source_url: item.src, - title: item.alt || '', + id: data.id, + date_created: data.created_at, + date_modified: data.updated_at, + source_url: data.src, + title: data.alt || '', media_type: '', // Shopyy API未提供,暂时留空 mime_type: '', // Shopyy API未提供,暂时留空 }; } + mapUnifiedToPlatformMedia(data: Partial) { + return data + } + + async getMedia( + params: UnifiedSearchParamsDTO + ): Promise> { + const requestParams = this.mapMediaSearchParams(params); + const { items, total, totalPages, page, per_page } = await this.shopyyService.fetchResourcePaged( + this.site, + 'media', // Shopyy的媒体API端点可能需要调整 + requestParams + ); + return { + items: items.map(this.mapPlatformToUnifiedMedia.bind(this)), + total, + totalPages, + page, + per_page, + }; + } + + async getAllMedia(params?: UnifiedSearchParamsDTO): Promise { + // Shopyy getAllMedia 暂未实现 + throw new Error('Shopyy getAllMedia 暂未实现'); + } + + async createMedia(file: any): Promise { + const createdMedia = await this.shopyyService.createMedia(this.site, file); + return this.mapPlatformToUnifiedMedia(createdMedia); + } + + async updateMedia(where: {id: string | number}, data: any): Promise { + const updatedMedia = await this.shopyyService.updateMedia(this.site, where.id, data); + return this.mapPlatformToUnifiedMedia(updatedMedia); + } + + async deleteMedia(where: {id: string | number}): Promise { + return await this.shopyyService.deleteMedia(this.site, where.id); + } + mapMediaSearchParams(params: UnifiedSearchParamsDTO): any { - const { search, page, per_page } = params; - const shopyyParams: any = { - page: page || 1, - limit: per_page || 10, - }; - - if (search) { - shopyyParams.query = search; - } - - return shopyyParams; + return this.mapSearchParams(params) } - mapProduct(item: ShopyyProduct & { permalink?: string }): UnifiedProductDTO { - // 映射产品状态 - function mapProductStatus(status: number) { - return status === 1 ? 'publish' : 'draft'; - } - return { - id: item.id, - name: item.name || item.title, - type: String(item.product_type ?? ''), - status: mapProductStatus(item.status), - sku: item.variant?.sku || '', - regular_price: String(item.variant?.price ?? ''), - sale_price: String(item.special_price ?? ''), - price: String(item.price ?? ''), - stock_status: item.inventory_tracking === 1 ? 'instock' : 'outofstock', - stock_quantity: item.inventory_quantity, - images: (item.images || []).map((img: any) => ({ - id: img.id || 0, - src: img.src, - name: '', - alt: img.alt || '', - // 排序 - position: img.position || '', - })), - attributes: (item.options || []).map(option => ({ - id: option.id || 0, - name: option.option_name || '', - options: (option.values || []).map(value => value.option_value || ''), - })), - tags: (item.tags || []).map((t: any) => ({ - id: t.id || 0, - name: t.name || '', - })), - // shopyy叫做专辑 - categories: item.collections.map((c: any) => ({ - id: c.id || 0, - name: c.title || '', - })), - variations: item.variants?.map(this.mapVariation.bind(this)) || [], - permalink: item.permalink, - date_created: - typeof item.created_at === 'number' - ? new Date(item.created_at * 1000).toISOString() - : String(item.created_at ?? ''), - date_modified: - typeof item.updated_at === 'number' - ? new Date(item.updated_at * 1000).toISOString() - : String(item.updated_at ?? ''), - raw: item, - }; - } - - mapVariation(variant: ShopyyVariant): UnifiedProductVariationDTO { - // 映射变体 - return { - id: variant.id, - name: variant.sku || '', - sku: variant.sku || '', - regular_price: String(variant.price ?? ''), - sale_price: String(variant.special_price ?? ''), - price: String(variant.price ?? ''), - stock_status: - variant.inventory_tracking === 1 ? 'instock' : 'outofstock', - stock_quantity: variant.inventory_quantity, - }; - } - - shopyyOrderStatusMap = {//订单状态 100 未完成;110 待处理;180 已完成(确认收货); 190 取消; - [100]: OrderStatus.PENDING, // 100 未完成 转为 pending - [110]: OrderStatus.PROCESSING, // 110 待处理 转为 processing - // 已发货 - - [180]: OrderStatus.COMPLETED, // 180 已完成(确认收货) 转为 completed - [190]: OrderStatus.CANCEL // 190 取消 转为 cancelled - } - mapOrder(item: ShopyyOrder): UnifiedOrderDTO { + // ========== 订单映射方法 ========== + mapPlatformToUnifiedOrder(item: ShopyyOrder): UnifiedOrderDTO { // 提取账单和送货地址 如果不存在则为空对象 const billing = (item as any).billing_address || {}; const shipping = (item as any).shipping_address || {}; @@ -321,185 +395,162 @@ export class ShopyyAdapter implements ISiteAdapter { raw: item, }; } - shopyyFulfillmentStatusMap = { - // 未发货 - '300': OrderFulfillmentStatus.PENDING, - // 部分发货 - '310': OrderFulfillmentStatus.PARTIALLY_FULFILLED, - // 已发货 - '320': OrderFulfillmentStatus.FULFILLED, - // 已取消 - '330': OrderFulfillmentStatus.CANCELLED, - // 确认发货 + + mapUnifiedToPlatformOrder(data: Partial) { + return data } - mapCustomer(item: ShopyyCustomer): UnifiedCustomerDTO { - // 处理多地址结构 - const addresses = item.addresses || []; - const defaultAddress = item.default_address || (addresses.length > 0 ? addresses[0] : {}); - - // 尝试从地址列表中获取billing和shipping - // 如果没有明确区分,默认使用默认地址或第一个地址 - const billingAddress = defaultAddress; - const shippingAddress = defaultAddress; - - const billing = { - first_name: billingAddress.first_name || item.first_name || '', - last_name: billingAddress.last_name || item.last_name || '', - fullname: billingAddress.name || `${billingAddress.first_name || item.first_name || ''} ${billingAddress.last_name || item.last_name || ''}`.trim(), - company: billingAddress.company || '', - email: item.email || '', - phone: billingAddress.phone || item.contact || '', - address_1: billingAddress.address1 || '', - address_2: billingAddress.address2 || '', - city: billingAddress.city || '', - state: billingAddress.province || '', - postcode: billingAddress.zip || '', - country: billingAddress.country_name || billingAddress.country_code || item.country?.country_name || '' - }; - - const shipping = { - first_name: shippingAddress.first_name || item.first_name || '', - last_name: shippingAddress.last_name || item.last_name || '', - fullname: shippingAddress.name || `${shippingAddress.first_name || item.first_name || ''} ${shippingAddress.last_name || item.last_name || ''}`.trim(), - company: shippingAddress.company || '', - address_1: shippingAddress.address1 || '', - address_2: shippingAddress.address2 || '', - city: shippingAddress.city || '', - state: shippingAddress.province || '', - postcode: shippingAddress.zip || '', - country: shippingAddress.country_name || shippingAddress.country_code || item.country?.country_name || '' - }; - - return { - id: item.id || item.customer_id, - orders: Number(item.orders_count ?? item.order_count ?? item.orders ?? 0), - total_spend: Number(item.total_spent ?? item.total_spend_amount ?? item.total_spend_money ?? 0), - first_name: item.first_name || item.firstname || '', - last_name: item.last_name || item.lastname || '', - fullname: item.fullname || item.customer_name || `${item.first_name || item.firstname || ''} ${item.last_name || item.lastname || ''}`.trim(), - email: item.email || item.customer_email || '', - phone: item.contact || billing.phone || item.phone || '', - billing, - shipping, - date_created: - typeof item.created_at === 'number' - ? new Date(item.created_at * 1000).toISOString() - : (typeof item.created_at === 'string' ? item.created_at : item.date_added || ''), - date_modified: - typeof item.updated_at === 'number' - ? new Date(item.updated_at * 1000).toISOString() - : (typeof item.updated_at === 'string' ? item.updated_at : item.date_updated || ''), - raw: item, - }; + mapCreateOrderParams(data: Partial): any { + return data } - async getProducts( - params: UnifiedSearchParamsDTO - ): Promise> { - const response = await this.shopyyService.fetchResourcePaged( - this.site, - 'products/list', - params - ); - const { items = [], total, totalPages, page, per_page } = response; - const finalItems = items.map((item) => ({ - ...item, - permalink: `${this.site.websiteUrl}/products/${item.handle}`, - })).map(this.mapProduct.bind(this)) - return { - items: finalItems as UnifiedProductDTO[], - total, - totalPages, - page, - per_page, - }; - } + mapUpdateOrderParams(data: Partial): any { + // 构建 ShopYY 订单更新参数(仅包含传入的字段) + const params: any = {}; - async getAllProducts(params?: UnifiedSearchParamsDTO): Promise { - // Shopyy getAllProducts 暂未实现 - throw new Error('Shopyy getAllProducts 暂未实现'); - } - - async getProduct(id: string | number): Promise { - // 使用ShopyyService获取单个产品 - const product = await this.shopyyService.getProduct(this.site, id); - return this.mapProduct(product); - } - - async createProduct(data: Partial): Promise { - const res = await this.shopyyService.createProduct(this.site, data); - return this.mapProduct(res); - } - - async updateProduct(id: string | number, data: Partial): Promise { - // Shopyy update returns boolean? - // shopyyService.updateProduct returns boolean. - // So I can't return the updated product. - // I have to fetch it again or return empty/input. - // Since getProduct is missing, I'll return input data as UnifiedProductDTO (mock). - await this.shopyyService.updateProduct(this.site, String(id), data); - return true; - } - - async updateVariation(productId: string | number, variationId: string | number, data: any): Promise { - await this.shopyyService.updateVariation(this.site, String(productId), String(variationId), data); - return { ...data, id: variationId }; - } - - async getOrderNotes(orderId: string | number): Promise { - return await this.shopyyService.getOrderNotes(this.site, orderId); - } - - async createOrderNote(orderId: string | number, data: any): Promise { - return await this.shopyyService.createOrderNote(this.site, orderId, data); - } - - async deleteProduct(id: string | number): Promise { - // Use batch delete - await this.shopyyService.batchProcessProducts(this.site, { delete: [id] }); - return true; - } - - async batchProcessProducts( - data: { create?: any[]; update?: any[]; delete?: Array } - ): Promise { - return await this.shopyyService.batchProcessProducts(this.site, data); - } - mapUnifiedOrderQueryToShopyyQuery(params: UnifiedSearchParamsDTO) { - const { where = {} as any, ...restParams } = params || {} - const statusMap = { - 'pending': '100', // 100 未完成 - 'processing': '110', // 110 待处理 - 'completed': "180", // 180 已完成(确认收货) - 'cancelled': '190', // 190 取消 + // 仅当字段存在时才添加到更新参数中 + if (data.status !== undefined) { + // 映射订单状态 + const statusMap = { + [OrderStatus.PENDING]: 100, // pending -> 100 未完成 + [OrderStatus.PROCESSING]: 110, // processing -> 110 待处理 + [OrderStatus.COMPLETED]: 180, // completed -> 180 已完成 + [OrderStatus.CANCEL]: 190 // cancel -> 190 取消 + }; + params.status = statusMap[data.status] || 100; } - const normalizedParams: any = { - ...restParams, + + if (data.payment_method !== undefined) { + params.payment_method = data.payment_method; } - if (where) { - normalizedParams.where = { - ...where, + + if (data.billing) { + // 更新客户信息 + if (data.billing.first_name !== undefined) { + params.firstname = data.billing.first_name; } - if (where.status) { - normalizedParams.where.status = statusMap[where.status]; + if (data.billing.last_name !== undefined) { + params.lastname = data.billing.last_name; + } + if (data.billing.email !== undefined) { + params.email = data.billing.email; + } + if (data.billing.phone !== undefined) { + params.phone = data.billing.phone; + } + + // 更新账单地址 + params.billing_address = params.billing_address || {}; + if (data.billing.first_name !== undefined) { + params.billing_address.first_name = data.billing.first_name; + } + if (data.billing.last_name !== undefined) { + params.billing_address.last_name = data.billing.last_name; + } + if (data.billing.company !== undefined) { + params.billing_address.company = data.billing.company; + } + if (data.billing.address_1 !== undefined) { + params.billing_address.address1 = data.billing.address_1; + } + if (data.billing.address_2 !== undefined) { + params.billing_address.address2 = data.billing.address_2; + } + if (data.billing.city !== undefined) { + params.billing_address.city = data.billing.city; + } + if (data.billing.state !== undefined) { + params.billing_address.province = data.billing.state; + } + if (data.billing.postcode !== undefined) { + params.billing_address.zip = data.billing.postcode; + } + if (data.billing.country !== undefined) { + params.billing_address.country_code = data.billing.country; } } - return normalizedParams + + if (data.shipping) { + // 更新送货地址 + params.shipping_address = params.shipping_address || {}; + if (data.shipping.first_name !== undefined) { + params.shipping_address.first_name = data.shipping.first_name; + } + if (data.shipping.last_name !== undefined) { + params.shipping_address.last_name = data.shipping.last_name; + } + if (data.shipping.company !== undefined) { + params.shipping_address.company = data.shipping.company; + } + if (data.shipping.address_1 !== undefined) { + params.shipping_address.address1 = data.shipping.address_1; + } + if (data.shipping.address_2 !== undefined) { + params.shipping_address.address2 = data.shipping.address_2; + } + if (data.shipping.city !== undefined) { + params.shipping_address.city = data.shipping.city; + } + if (data.shipping.state !== undefined) { + params.shipping_address.province = data.shipping.state; + } + if (data.shipping.postcode !== undefined) { + params.shipping_address.zip = data.shipping.postcode; + } + if (data.shipping.country !== undefined) { + params.shipping_address.country_code = data.shipping.country; + } + if (data.shipping.phone !== undefined) { + params.shipping_address.phone = data.shipping.phone; + } + } + + // 更新订单项 + if (data.line_items && data.line_items.length > 0) { + params.products = data.line_items.map((item: UnifiedOrderLineItemDTO) => ({ + product_id: item.product_id, + quantity: item.quantity, + // price: item.price || '0.00', + sku: item.sku || '', + })); + } + + // 更新物流信息 + if (data.shipping_lines && data.shipping_lines.length > 0) { + const shippingLine = data.shipping_lines[0]; + if (shippingLine.method_title !== undefined) { + params.shipping_method = shippingLine.method_title; + } + if (shippingLine.total !== undefined) { + params.shipping_price = shippingLine.total; + } + } + + // // 更新备注信息 + // if (data.note !== undefined) { + // params.note = data.note; + // } + + return params; + } + + async getOrder(where: {id: string | number}): Promise { + const data = await this.shopyyService.getOrder(this.site.id, String(where.id)); + return this.mapPlatformToUnifiedOrder(data); } async getOrders( params: UnifiedSearchParamsDTO ): Promise> { - const normalizedParams = this.mapUnifiedOrderQueryToShopyyQuery(params); - const { items, total, totalPages, page, per_page } = - await this.shopyyService.fetchResourcePaged( - this.site, - 'orders', - normalizedParams - ); + // 转换订单查询参数 + const normalizedParams = this.mapOrderSearchParams(params); + const { items, total, totalPages, page, per_page } = await this.shopyyService.fetchResourcePaged( + this.site, + 'orders', + normalizedParams + ); return { - items: items.map(this.mapOrder.bind(this)), + items: items.map(this.mapPlatformToUnifiedOrder.bind(this)), total, totalPages, page, @@ -509,68 +560,43 @@ export class ShopyyAdapter implements ISiteAdapter { async getAllOrders(params?: UnifiedSearchParamsDTO): Promise { const data = await this.shopyyService.getAllOrders(this.site.id, params); - return data.map(this.mapOrder.bind(this)); + return data.map(this.mapPlatformToUnifiedOrder.bind(this)); } - async getOrder(id: string | number): Promise { - const data = await this.shopyyService.getOrder(this.site.id, String(id)); - return this.mapOrder(data); + async countOrders(where: Record): Promise { + // 使用最小分页只获取总数 + const searchParams = { + where, + page: 1, + per_page: 1, + } + const data = await this.getOrders(searchParams); + return data.total || 0; } async createOrder(data: Partial): Promise { - const createdOrder = await this.shopyyService.createOrder(this.site, data); - return this.mapOrder(createdOrder); + // 使用映射方法转换参数 + const requestParams = this.mapCreateOrderParams(data); + const createdOrder = await this.shopyyService.createOrder(this.site, requestParams); + return this.mapPlatformToUnifiedOrder(createdOrder); } - async updateOrder(id: string | number, data: Partial): Promise { - return await this.shopyyService.updateOrder(this.site, String(id), data); + async updateOrder(where: {id: string | number}, data: Partial): Promise { + // 使用映射方法转换参数 + const requestParams = this.mapUpdateOrderParams(data); + return await this.shopyyService.updateOrder(this.site, String(where.id), requestParams); } - async deleteOrder(id: string | number): Promise { - return await this.shopyyService.deleteOrder(this.site, id); + async deleteOrder(where: {id: string | number}): Promise { + return await this.shopyyService.deleteOrder(this.site, where.id); } - async fulfillOrder(orderId: string | number, data: { - tracking_number?: string; - shipping_provider?: string; - shipping_method?: string; - items?: Array<{ - order_item_id: number; - quantity: number; - }>; - }): Promise { - // 订单履行(发货) - try { - // 判断是否为部分发货(包含 items) - if (data.items && data.items.length > 0) { - // 部分发货 - const partShipData = { - order_number: String(orderId), - note: data.shipping_method || '', - tracking_company: data.shipping_provider || '', - tracking_number: data.tracking_number || '', - courier_code: '1', // 默认快递公司代码 - products: data.items.map(item => ({ - quantity: item.quantity, - order_product_id: String(item.order_item_id) - })) - }; - return await this.shopyyService.partFulfillOrder(this.site, partShipData); - } else { - // 批量发货(完整发货) - const batchShipData = { - order_number: String(orderId), - tracking_company: data.shipping_provider || '', - tracking_number: data.tracking_number || '', - courier_code: 1, // 默认快递公司代码 - note: data.shipping_method || '', - mode: null // 新增模式 - }; - return await this.shopyyService.batchFulfillOrders(this.site, batchShipData); - } - } catch (error) { - throw new Error(`履行失败: ${error.message}`); - } + async getOrderNotes(orderId: string | number): Promise { + return await this.shopyyService.getOrderNotes(this.site, orderId); + } + + async createOrderNote(orderId: string | number, data: any): Promise { + return await this.shopyyService.createOrderNote(this.site, orderId, data); } async cancelFulfillment(orderId: string | number, data: { @@ -594,25 +620,14 @@ export class ShopyyAdapter implements ISiteAdapter { cancelled_at: new Date().toISOString() }; } catch (error) { - throw new Error(`取消履行失败: ${error.message}`); + throw new Error(`履行失败: ${error.message}`); } } - /** - * 获取订单履行信息 - * @param orderId 订单ID - * @returns 履行信息列表 - */ async getOrderFulfillments(orderId: string | number): Promise { return await this.shopyyService.getFulfillments(this.site, String(orderId)); } - /** - * 创建订单履行信息 - * @param orderId 订单ID - * @param data 履行数据 - * @returns 创建结果 - */ async createOrderFulfillment(orderId: string | number, data: FulfillmentDTO): Promise { // 调用 Shopyy Service 的 createFulfillment 方法 const fulfillmentData = { @@ -625,13 +640,6 @@ export class ShopyyAdapter implements ISiteAdapter { return await this.shopyyService.createFulfillment(this.site, String(orderId), fulfillmentData); } - /** - * 更新订单履行信息 - * @param orderId 订单ID - * @param fulfillmentId 履行ID - * @param data 更新数据 - * @returns 更新结果 - */ async updateOrderFulfillment(orderId: string | number, fulfillmentId: string, data: { tracking_number?: string; tracking_provider?: string; @@ -641,62 +649,360 @@ export class ShopyyAdapter implements ISiteAdapter { return await this.shopyyService.updateFulfillment(this.site, String(orderId), fulfillmentId, data); } - /** - * 删除订单履行信息 - * @param orderId 订单ID - * @param fulfillmentId 履行ID - * @returns 删除结果 - */ async deleteOrderFulfillment(orderId: string | number, fulfillmentId: string): Promise { return await this.shopyyService.deleteFulfillment(this.site, String(orderId), fulfillmentId); } - async getSubscriptions( - params: UnifiedSearchParamsDTO - ): Promise> { - throw new Error('Shopyy does not support subscriptions.'); + batchProcessOrders?(data: BatchOperationDTO): Promise { + throw new Error('Method not implemented.'); } - async getAllSubscriptions(params?: UnifiedSearchParamsDTO): Promise { - // Shopyy getAllSubscriptions 暂未实现 - throw new Error('Shopyy getAllSubscriptions 暂未实现'); + mapOrderSearchParams(params: UnifiedSearchParamsDTO): Partial { + // 首先使用通用参数转换 + const baseParams = this.mapSearchParams(params); + + // 订单状态映射 + const statusMap = { + 'pending': '100', // 100 未完成 + 'processing': '110', // 110 待处理 + 'completed': "180", // 180 已完成(确认收货) + 'cancelled': '190', // 190 取消 + }; + + // 如果有状态参数,进行特殊映射 + if (baseParams.status) { + const unifiedStatus = baseParams.status + if (statusMap[unifiedStatus]) { + baseParams.status = statusMap[unifiedStatus]; + } + } + + // 处理ID参数 + if (baseParams.id) { + baseParams.ids = baseParams.id; + delete baseParams.id; + } + + return baseParams; } - async getMedia( + // ========== 产品映射方法 ========== + mapPlatformToUnifiedProduct(item: ShopyyProduct): UnifiedProductDTO { + // 映射产品状态 + function mapProductStatus(status: number) { + return status === 1 ? 'publish' : 'draft'; + } + return { + id: item.id, + name: item.name || item.title, + type: String(item.product_type ?? ''), + status: mapProductStatus(item.status), + sku: item.variant?.sku || '', + regular_price: String(item.variant?.price ?? ''), + sale_price: String(item.special_price ?? ''), + price: String(item.price ?? ''), + stock_status: item.inventory_tracking === 1 ? 'instock' : 'outofstock', + stock_quantity: item.inventory_quantity, + images: (item.images || []).map((img: any) => ({ + id: img.id || 0, + src: img.src, + name: '', + alt: img.alt || '', + // 排序 + position: img.position || '', + })), + attributes: (item.options || []).map(option => ({ + id: option.id || 0, + name: option.option_name || '', + options: (option.values || []).map(value => value.option_value || ''), + })), + tags: (item.tags || []).map((t: any) => ({ + id: t.id || 0, + name: t.name || '', + })), + // shopyy叫做专辑 + categories: item.collections.map((c: any) => ({ + id: c.id || 0, + name: c.title || '', + })), + variations: item.variants?.map(this.mapPlatformToUnifiedVariation.bind(this)) || [], + permalink: `${this.site.websiteUrl}/products/${item.handle}`, + date_created: + typeof item.created_at === 'number' + ? new Date(item.created_at * 1000).toISOString() + : String(item.created_at ?? ''), + date_modified: + typeof item.updated_at === 'number' + ? new Date(item.updated_at * 1000).toISOString() + : String(item.updated_at ?? ''), + raw: item, + }; + } + + mapUnifiedToPlatformProduct(data: Partial) { + return data + } + + mapCreateProductParams(data: Partial): Partial { + // 构建 ShopYY 产品创建参数 + const params: any = { + name: data.name || '', + product_type: data.type || 1, // 默认简单产品 + status: this.mapStatus(data.status || 'publish'), + price: data.price || '0.00', + special_price: data.sale_price || '', + inventory_tracking: data.stock_quantity !== undefined ? 1 : 0, + inventory_quantity: data.stock_quantity || 0, + }; + + // 添加变体信息 + if (data.variations && data.variations.length > 0) { + params.variants = data.variations.map((variation: UnifiedProductVariationDTO) => ({ + sku: variation.sku || '', + price: variation.price || '0.00', + special_price: variation.sale_price || '', + inventory_tracking: variation.stock_quantity !== undefined ? 1 : 0, + inventory_quantity: variation.stock_quantity || 0, + })); + } + + // 添加图片信息 + if (data.images && data.images.length > 0) { + params.images = data.images.map((image: any) => ({ + src: image.src, + alt: image.alt || '', + position: image.position || 0, + })); + } + + // 添加标签信息 + if (data.tags && data.tags.length > 0) { + params.tags = data.tags.map((tag: any) => tag.name || ''); + } + + // 添加分类信息 + if (data.categories && data.categories.length > 0) { + params.collections = data.categories.map((category: any) => ({ + // id: category.id, + title: category.name, + })); + } + + return params; + } + + mapUpdateProductParams(data: Partial): any { + // 映射产品状态: publish -> 1, draft -> 0 + const mapStatus = (status: string) => { + return status === 'publish' ? 1 : 0; + }; + + // 构建 ShopYY 产品更新参数(仅包含传入的字段) + const params: any = {}; + + // 仅当字段存在时才添加到更新参数中 + if (data.name !== undefined) params.name = data.name; + if (data.type !== undefined) params.product_type = data.type; + if (data.status !== undefined) params.status = mapStatus(data.status); + if (data.price !== undefined) params.price = data.price; + if (data.sale_price !== undefined) params.special_price = data.sale_price; + if (data.sku !== undefined) params.sku = data.sku; + if (data.stock_quantity !== undefined) { + params.inventory_tracking = 1; + params.inventory_quantity = data.stock_quantity; + } + if (data.stock_status !== undefined) { + params.inventory_tracking = 1; + params.inventory_quantity = data.stock_status === 'instock' ? (data.stock_quantity || 1) : 0; + } + + // 添加变体信息(如果存在) + if (data.variations && data.variations.length > 0) { + params.variants = data.variations.map((variation: UnifiedProductVariationDTO) => { + const variationParams: any = {}; + if (variation.id !== undefined) variationParams.id = variation.id; + if (variation.sku !== undefined) variationParams.sku = variation.sku; + if (variation.price !== undefined) variationParams.price = variation.price; + if (variation.sale_price !== undefined) variationParams.special_price = variation.sale_price; + if (variation.stock_quantity !== undefined) { + variationParams.inventory_tracking = 1; + variationParams.inventory_quantity = variation.stock_quantity; + } + if (variation.stock_status !== undefined) { + variationParams.inventory_tracking = 1; + variationParams.inventory_quantity = variation.stock_status === 'instock' ? (variation.stock_quantity || 1) : 0; + } + return variationParams; + }); + } + + // 添加图片信息(如果存在) + if (data.images && data.images.length > 0) { + params.images = data.images.map((image: any) => ({ + id: image.id, + src: image.src, + alt: image.alt || '', + position: image.position || 0, + })); + } + + // 添加标签信息(如果存在) + if (data.tags && data.tags.length > 0) { + params.tags = data.tags.map((tag: any) => tag.name || ''); + } + + // 添加分类信息(如果存在) + if (data.categories && data.categories.length > 0) { + params.collections = data.categories.map((category: any) => ({ + id: category.id, + title: category.name, + })); + } + + return params; + } + + async getProduct(where: {id?: string | number, sku?: string}): Promise { + if(!where.id && !where.sku){ + throw new Error('必须传入 id 或 sku') + } + if (where.id) { + // 使用ShopyyService获取单个产品 + const product = await this.shopyyService.getProduct(this.site, where.id); + return this.mapPlatformToUnifiedProduct(product); + } else if (where.sku) { + // 通过sku获取产品 + return this.getProductBySku(where.sku); + } + } + + async getProducts( params: UnifiedSearchParamsDTO - ): Promise> { - const requestParams = this.mapMediaSearchParams(params); - const { items, total, totalPages, page, per_page } = await this.shopyyService.fetchResourcePaged( + ): Promise> { + // 转换搜索参数 + const requestParams = this.mapProductQuery(params); + const response = await this.shopyyService.fetchResourcePaged( this.site, - 'media', // Shopyy的媒体API端点可能需要调整 + 'products/list', requestParams ); + const { items = [], total, totalPages, page, per_page } = response; + const finalItems = items.map((item) => ({ + ...item, + permalink: `${this.site.websiteUrl}/products/${item.handle}`, + })).map(this.mapPlatformToUnifiedProduct.bind(this)) return { - items: items.map(this.mapMedia.bind(this)), + items: finalItems as UnifiedProductDTO[], total, totalPages, page, per_page, }; } - - async getAllMedia(params?: UnifiedSearchParamsDTO): Promise { - // Shopyy getAllMedia 暂未实现 - throw new Error('Shopyy getAllMedia 暂未实现'); + mapAllProductParams(params: UnifiedSearchParamsDTO): Partial{ + const mapped = { + ...params.where, + } as any + if(params.per_page){mapped.limit = params.per_page} + return mapped } - async createMedia(file: any): Promise { - const createdMedia = await this.shopyyService.createMedia(this.site, file); - return this.mapMedia(createdMedia); + async getAllProducts(params?: UnifiedSearchParamsDTO): Promise { + // 转换搜索参数 + const requestParams = this.mapAllProductParams(params); + const response = await this.shopyyService.request( + this.site, + 'products', + 'GET', + null, + requestParams + ); + if(response.code !==0){ + throw new Error(response.msg || '获取产品列表失败') + } + const { data = [] } = response; + const finalItems = data.map(this.mapPlatformToUnifiedProduct.bind(this)) + return finalItems } - async updateMedia(id: string | number, data: any): Promise { - const updatedMedia = await this.shopyyService.updateMedia(this.site, id, data); - return this.mapMedia(updatedMedia); + async createProduct(data: Partial): Promise { + // 使用映射方法转换参数 + const requestParams = this.mapCreateProductParams(data); + const res = await this.shopyyService.createProduct(this.site, requestParams); + return this.mapPlatformToUnifiedProduct(res); } - async deleteMedia(id: string | number): Promise { - return await this.shopyyService.deleteMedia(this.site, id); + async updateProduct(where: {id?: string | number, sku?: string}, data: Partial): Promise { + let productId: string; + if (where.id) { + productId = String(where.id); + } else if (where.sku) { + // 通过sku获取产品ID + const product = await this.getProductBySku(where.sku); + productId = String(product.id); + } else { + throw new Error('必须提供id或sku参数'); + } + // 使用映射方法转换参数 + const requestParams = this.mapUpdateProductParams(data); + await this.shopyyService.updateProduct(this.site, productId, requestParams); + return true; + } + + async deleteProduct(where: {id?: string | number, sku?: string}): Promise { + let productId: string | number; + if (where.id) { + productId = where.id; + } else if (where.sku) { + // 通过sku获取产品ID + const product = await this.getProductBySku(where.sku); + productId = product.id; + } else { + throw new Error('必须提供id或sku参数'); + } + // Use batch delete + await this.shopyyService.batchProcessProducts(this.site, { delete: [productId] }); + return true; + } + + // 通过sku获取产品详情的私有方法 + private async getProductBySku(sku: string): Promise { + // 使用Shopyy API的搜索功能通过sku查询产品 + const response = await this.getAllProducts({ where: {sku} }); + console.log('getProductBySku', response) + const product = response?.[0] + if (!product) { + throw new Error(`未找到sku为${sku}的产品`); + } + return product + } + + async batchProcessProducts( + data: { create?: any[]; update?: any[]; delete?: Array } + ): Promise { + return await this.shopyyService.batchProcessProducts(this.site, data); + } + + mapProductQuery(query: UnifiedSearchParamsDTO): ShopyyProductQuery { + return this.mapSearchParams(query) + } + + mapAllProductQuery(query: UnifiedSearchParamsDTO): ShopyyProductQuery { + return this.mapSearchParams(query) + } + + // ========== 评论映射方法 ========== + + mapUnifiedToPlatformReview(data: Partial) { + return data + } + + mapCreateReviewParams(data: CreateReviewDTO) { + return data + } + + mapUpdateReviewParams(data: UpdateReviewDTO) { + return data } async getReviews( @@ -708,7 +1014,7 @@ export class ShopyyAdapter implements ISiteAdapter { requestParams ); return { - items: items.map(this.mapReview), + items: items.map(this.mapPlatformToUnifiedReview), total, totalPages, page, @@ -721,12 +1027,21 @@ export class ShopyyAdapter implements ISiteAdapter { throw new Error('Shopyy getAllReviews 暂未实现'); } - async getReview(id: string | number): Promise { - const review = await this.shopyyService.getReview(this.site, id); - return this.mapReview(review); + async createReview(data: any): Promise { + const createdReview = await this.shopyyService.createReview(this.site, data); + return this.mapPlatformToUnifiedReview(createdReview); } - mapReview(review: any): UnifiedReviewDTO { + async updateReview(where: {id: string | number}, data: any): Promise { + const updatedReview = await this.shopyyService.updateReview(this.site, where.id, data); + return this.mapPlatformToUnifiedReview(updatedReview); + } + + async deleteReview(where: {id: string | number}): Promise { + return await this.shopyyService.deleteReview(this.site, where.id); + } + + mapPlatformToUnifiedReview(review: any): UnifiedReviewDTO { // 将ShopYY评论数据映射到统一评论DTO格式 return { id: review.id || review.review_id, @@ -758,42 +1073,135 @@ export class ShopyyAdapter implements ISiteAdapter { shopyyParams.status = where.status; } - // if (product_id) { - // shopyyParams.product_id = product_id; - // } - return shopyyParams; } - async createReview(data: any): Promise { - const createdReview = await this.shopyyService.createReview(this.site, data); - return this.mapReview(createdReview); + // ========== 订阅映射方法 ========== + mapPlatformToUnifiedSubscription(data: any): UnifiedSubscriptionDTO { + return data } - async updateReview(id: string | number, data: any): Promise { - const updatedReview = await this.shopyyService.updateReview(this.site, id, data); - return this.mapReview(updatedReview); + mapUnifiedToPlatformSubscription(data: Partial) { + return data } - async deleteReview(id: string | number): Promise { - return await this.shopyyService.deleteReview(this.site, id); + async getSubscriptions( + params: UnifiedSearchParamsDTO + ): Promise> { + throw new Error('Shopyy does not support subscriptions.'); } - // Webhook相关方法 - mapWebhook(item: ShopyyWebhook): UnifiedWebhookDTO { + async getAllSubscriptions(params?: UnifiedSearchParamsDTO): Promise { + // Shopyy getAllSubscriptions 暂未实现 + throw new Error('Shopyy getAllSubscriptions 暂未实现'); + } + + // ========== 产品变体映射方法 ========== + mapPlatformToUnifiedVariation(variant: ShopyyVariant): UnifiedProductVariationDTO { + // 映射变体 return { - id: item.id, - name: item.webhook_name || `Webhook-${item.id}`, - topic: item.event_code || '', - delivery_url: item.url || '', - status: 'active', + id: variant.id, + name: variant.sku || '', + sku: variant.sku || '', + regular_price: String(variant.price ?? ''), + sale_price: String(variant.special_price ?? ''), + price: String(variant.price ?? ''), + stock_status: + variant.inventory_tracking === 1 ? 'instock' : 'outofstock', + stock_quantity: variant.inventory_quantity, }; } + mapUnifiedToPlatformVariation(data: Partial) { + return data + } + + mapCreateVariationParams(data: CreateVariationDTO) { + return data + } + + mapUpdateVariationParams(data: Partial): any { + // 构建 ShopYY 变体更新参数(仅包含传入的字段) + const params: any = {}; + + // 仅当字段存在时才添加到更新参数中 + if (data.id !== undefined) { + params.id = data.id; + } + if (data.sku !== undefined) { + params.sku = data.sku; + } + if (data.price !== undefined) { + params.price = data.price; + } + if (data.sale_price !== undefined) { + params.special_price = data.sale_price; + } + + // 处理库存信息 + if (data.stock_quantity !== undefined) { + params.inventory_tracking = 1; + params.inventory_quantity = data.stock_quantity; + } + if (data.stock_status !== undefined) { + params.inventory_tracking = 1; + params.inventory_quantity = data.stock_status === 'instock' ? (data.stock_quantity || 1) : 0; + } + + return params; + } + + async getVariation(productId: string | number, variationId: string | number): Promise { + throw new Error('Shopyy getVariation 暂未实现'); + } + + async getVariations(productId: string | number, params: UnifiedSearchParamsDTO): Promise { + throw new Error('Shopyy getVariations 暂未实现'); + } + + async getAllVariations(productId: string | number, params?: UnifiedSearchParamsDTO): Promise { + throw new Error('Shopyy getAllVariations 暂未实现'); + } + + async createVariation(productId: string | number, data: any): Promise { + throw new Error('Shopyy createVariation 暂未实现'); + } + + async updateVariation(productId: string | number, variationId: string | number, data: Partial): Promise { + // 使用映射方法转换参数 + const requestParams = this.mapUpdateVariationParams(data); + await this.shopyyService.updateVariation(this.site, String(productId), String(variationId), requestParams); + return { ...data, id: variationId }; + } + + async deleteVariation(productId: string | number, variationId: string | number): Promise { + throw new Error('Shopyy deleteVariation 暂未实现'); + } + + // ========== Webhook映射方法 ========== + + + mapUnifiedToPlatformWebhook(data: Partial) { + return data + } + + mapCreateWebhookParams(data: CreateWebhookDTO) { + return data + } + + mapUpdateWebhookParams(data: UpdateWebhookDTO) { + return data + } + + async getWebhook(where: {id: string | number}): Promise { + const webhook = await this.shopyyService.getWebhook(this.site, where.id); + return this.mapPlatformToUnifiedWebhook(webhook); + } + async getWebhooks(params: UnifiedSearchParamsDTO): Promise { const { items, total, totalPages, page, per_page } = await this.shopyyService.getWebhooks(this.site, params); return { - items: items.map(this.mapWebhook), + items: items.map(this.mapPlatformToUnifiedWebhook), total, totalPages, page, @@ -806,25 +1214,31 @@ export class ShopyyAdapter implements ISiteAdapter { throw new Error('Shopyy getAllWebhooks 暂未实现'); } - async getWebhook(id: string | number): Promise { - const webhook = await this.shopyyService.getWebhook(this.site, id); - return this.mapWebhook(webhook); - } - async createWebhook(data: CreateWebhookDTO): Promise { const createdWebhook = await this.shopyyService.createWebhook(this.site, data); - return this.mapWebhook(createdWebhook); + return this.mapPlatformToUnifiedWebhook(createdWebhook); } - async updateWebhook(id: string | number, data: UpdateWebhookDTO): Promise { - const updatedWebhook = await this.shopyyService.updateWebhook(this.site, id, data); - return this.mapWebhook(updatedWebhook); + async updateWebhook(where: {id: string | number}, data: UpdateWebhookDTO): Promise { + const updatedWebhook = await this.shopyyService.updateWebhook(this.site, where.id, data); + return this.mapPlatformToUnifiedWebhook(updatedWebhook); } - async deleteWebhook(id: string | number): Promise { - return await this.shopyyService.deleteWebhook(this.site, id); + async deleteWebhook(where: {id: string | number}): Promise { + return await this.shopyyService.deleteWebhook(this.site, where.id); } + mapPlatformToUnifiedWebhook(item: ShopyyWebhook): UnifiedWebhookDTO { + return { + id: item.id, + name: item.webhook_name || `Webhook-${item.id}`, + topic: item.event_code || '', + delivery_url: item.url || '', + status: 'active', + }; + } + + // ========== 站点/其他方法 ========== async getLinks(): Promise> { // ShopYY站点的管理后台链接通常基于apiUrl构建 const url = this.site.websiteUrl @@ -844,59 +1258,58 @@ export class ShopyyAdapter implements ISiteAdapter { return links; } - async getCustomers(params: UnifiedSearchParamsDTO): Promise> { - const { items, total, totalPages, page, per_page } = - await this.shopyyService.fetchCustomersPaged(this.site, params); - return { - items: items.map(this.mapCustomer.bind(this)), - total, - totalPages, + // ========== 辅助方法 ========== + /** + * 通用搜索参数转换方法,处理 where 和 orderBy 的转换 + * 将统一的搜索参数转换为 ShopYY API 所需的参数格式 + */ + mapSearchParams(params: UnifiedSearchParamsDTO): any { + // 处理分页参数 + const page = Number(params.page || 1); + const limit = Number(params.per_page ?? 20); + + // 处理 where 条件 + const query: any = { + ...(params.where || {}), page, - per_page - }; + limit, + } + if(params.orderBy){ + const [field, dir] = Object.entries(params.orderBy)[0]; + query.order_by = dir === 'desc' ? 'desc' : 'asc'; + query.order_field = field + } + return query; } - async getAllCustomers(params?: UnifiedSearchParamsDTO): Promise { - // Shopyy getAllCustomers 暂未实现 - throw new Error('Shopyy getAllCustomers 暂未实现'); + // 映射产品状态: publish -> 1, draft -> 0 + mapStatus = (status: string) => { + return status === 'publish' ? 1 : 0; + }; + + // 映射库存状态: instock -> 1, outofstock -> 0 + mapStockStatus = (stockStatus: string) => { + return stockStatus === 'instock' ? 1 : 0; + }; + + shopyyOrderStatusMap = {//订单状态 100 未完成;110 待处理;180 已完成(确认收货); 190 取消; + [100]: OrderStatus.PENDING, // 100 未完成 转为 pending + [110]: OrderStatus.PROCESSING, // 110 待处理 转为 processing + // 已发货 + + [180]: OrderStatus.COMPLETED, // 180 已完成(确认收货) 转为 completed + [190]: OrderStatus.CANCEL // 190 取消 转为 cancelled } - async getCustomer(id: string | number): Promise { - const customer = await this.shopyyService.getCustomer(this.site, id); - return this.mapCustomer(customer); + shopyyFulfillmentStatusMap = { + // 未发货 + '300': OrderFulfillmentStatus.PENDING, + // 部分发货 + '310': OrderFulfillmentStatus.PARTIALLY_FULFILLED, + // 已发货 + '320': OrderFulfillmentStatus.FULFILLED, + // 已取消 + '330': OrderFulfillmentStatus.CANCELLED, + // 确认发货 } - - async createCustomer(data: Partial): Promise { - const createdCustomer = await this.shopyyService.createCustomer(this.site, data); - return this.mapCustomer(createdCustomer); - } - - async updateCustomer(id: string | number, data: Partial): Promise { - const updatedCustomer = await this.shopyyService.updateCustomer(this.site, id, data); - return this.mapCustomer(updatedCustomer); - } - - async deleteCustomer(id: string | number): Promise { - return await this.shopyyService.deleteCustomer(this.site, id); - } - - async getVariations(productId: string | number, params: UnifiedSearchParamsDTO): Promise { - throw new Error('Shopyy getVariations 暂未实现'); - } - - async getAllVariations(productId: string | number, params?: UnifiedSearchParamsDTO): Promise { - throw new Error('Shopyy getAllVariations 暂未实现'); - } - - async getVariation(productId: string | number, variationId: string | number): Promise { - throw new Error('Shopyy getVariation 暂未实现'); - } - - async createVariation(productId: string | number, data: any): Promise { - throw new Error('Shopyy createVariation 暂未实现'); - } - - async deleteVariation(productId: string | number, variationId: string | number): Promise { - throw new Error('Shopyy deleteVariation 暂未实现'); - } -} +} \ No newline at end of file diff --git a/src/adapter/woocommerce.adapter.ts b/src/adapter/woocommerce.adapter.ts index c407780..3627c22 100644 --- a/src/adapter/woocommerce.adapter.ts +++ b/src/adapter/woocommerce.adapter.ts @@ -15,6 +15,8 @@ import { UpdateVariationDTO, UnifiedProductVariationDTO, UnifiedVariationPaginationDTO, + CreateReviewDTO, + UpdateReviewDTO, } from '../dto/site-api.dto'; import { UnifiedPaginationDTO, UnifiedSearchParamsDTO } from '../dto/api.dto'; import { @@ -29,202 +31,281 @@ import { } from '../dto/woocommerce.dto'; import { Site } from '../entity/site.entity'; import { WPService } from '../service/wp.service'; +import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto'; export class WooCommerceAdapter implements ISiteAdapter { // 构造函数接收站点配置与服务实例 constructor(private site: Site, private wpService: WPService) { - this.mapProduct = this.mapProduct.bind(this); - this.mapReview = this.mapReview.bind(this); - this.mapCustomer = this.mapCustomer.bind(this); - this.mapMedia = this.mapMedia.bind(this); - this.mapOrder = this.mapOrder.bind(this); - this.mapWebhook = this.mapWebhook.bind(this); + this.mapPlatformToUnifiedProduct = this.mapPlatformToUnifiedProduct.bind(this); + this.mapPlatformToUnifiedReview = this.mapPlatformToUnifiedReview.bind(this); + this.mapPlatformToUnifiedCustomer = this.mapPlatformToUnifiedCustomer.bind(this); + this.mapPlatformToUnifiedMedia = this.mapPlatformToUnifiedMedia.bind(this); + this.mapPlatformToUnifiedOrder = this.mapPlatformToUnifiedOrder.bind(this); + this.mapPlatformToUnifiedWebhook = this.mapPlatformToUnifiedWebhook.bind(this); + } + mapUnifiedToPlatformCustomer(data: Partial) { + return data + } + batchProcessProducts?(data: BatchOperationDTO): Promise { + throw new Error('Method not implemented.'); + } + mapCreateVariationParams(data: CreateVariationDTO) { + throw new Error('Method not implemented.'); + } + mapUpdateVariationParams(data: UpdateVariationDTO) { + throw new Error('Method not implemented.'); } - // 映射 WooCommerce webhook 到统一格式 - mapWebhook(webhook: WooWebhook): UnifiedWebhookDTO { + // ========== 客户映射方法 ========== + + mapPlatformToUnifiedCustomer(item: WooCustomer): UnifiedCustomerDTO { + // 将 WooCommerce 客户数据映射为统一客户DTO + // 包含基础信息地址信息与时间信息 return { - id: webhook.id.toString(), - name: webhook.name, - status: webhook.status, - topic: webhook.topic, - delivery_url: webhook.delivery_url, - secret: webhook.secret, - api_version: webhook.api_version, - date_created: webhook.date_created, - date_modified: webhook.date_modified, - // metadata: webhook.meta_data || [], + id: item.id, + avatar: item.avatar_url, + email: item.email, + orders: Number(item.orders ?? 0), + total_spend: Number(item.total_spent ?? 0), + first_name: item.first_name, + last_name: item.last_name, + username: item.username, + phone: item.billing?.phone || item.shipping?.phone, + billing: item.billing, + shipping: item.shipping, + date_created: item.date_created, + date_modified: item.date_modified, + raw: item, }; } - // 获取站点的 webhooks 列表 - async getWebhooks(params: UnifiedSearchParamsDTO): Promise { - try { - const result = await this.wpService.getWebhooks(this.site, params); - - return { - items: (result.items as WooWebhook[]).map(this.mapWebhook), - total: result.total, - page: Number(params.page || 1), - per_page: Number(params.per_page || 20), - totalPages: result.totalPages, - }; - } catch (error) { - throw new Error(`Failed to get webhooks: ${error instanceof Error ? error.message : String(error)}`); - } - } - - // 获取所有webhooks - async getAllWebhooks(params?: UnifiedSearchParamsDTO): Promise { - try { - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const webhooks = await this.wpService.sdkGetAll(api, 'webhooks', params); - return webhooks.map((webhook: any) => this.mapWebhook(webhook)); - } catch (error) { - throw new Error(`Failed to get all webhooks: ${error instanceof Error ? error.message : String(error)}`); - } - } - - // 获取单个 webhook 详情 - async getWebhook(id: string | number): Promise { - try { - const result = await this.wpService.getWebhook(this.site, id); - return this.mapWebhook(result as WooWebhook); - } catch (error) { - throw new Error(`Failed to get webhook: ${error instanceof Error ? error.message : String(error)}`); - } - } - - // 创建新的 webhook - async createWebhook(data: CreateWebhookDTO): Promise { - try { - const params = { - name: data.name, - status: 'active', // 默认状态为活跃 - topic: data.topic, - delivery_url: data.delivery_url, - secret: data.secret, - api_version: data.api_version || 'wp/v2', - }; - const result = await this.wpService.createWebhook(this.site, params); - return this.mapWebhook(result as WooWebhook); - } catch (error) { - throw new Error(`Failed to create webhook: ${error instanceof Error ? error.message : String(error)}`); - } - } - - // 更新现有的 webhook - async updateWebhook(id: string | number, data: UpdateWebhookDTO): Promise { - try { - const params = { - ...(data.name ? { name: data.name } : {}), - ...(data.status ? { status: data.status } : {}), - ...(data.topic ? { topic: data.topic } : {}), - ...(data.delivery_url ? { delivery_url: data.delivery_url } : {}), - ...(data.secret ? { secret: data.secret } : {}), - ...(data.api_version ? { api_version: data.api_version } : {}), - }; - const result = await this.wpService.updateWebhook(this.site, id, params); - return this.mapWebhook(result as WooWebhook); - } catch (error) { - throw new Error(`Failed to update webhook: ${error instanceof Error ? error.message : String(error)}`); - } - } - - // 删除指定的 webhook - async deleteWebhook(id: string | number): Promise { - try { - await this.wpService.deleteWebhook(this.site, id); - return true; - } catch (error) { - throw new Error(`Failed to delete webhook: ${error instanceof Error ? error.message : String(error)}`); - } - } - - async getLinks(): Promise> { - const baseUrl = this.site.apiUrl; - const links = [ - { title: '访问网站', url: baseUrl }, - { title: '管理后台', url: `${baseUrl}/wp-admin/` }, - { title: '订单管理', url: `${baseUrl}/wp-admin/edit.php?post_type=shop_order` }, - { title: '产品管理', url: `${baseUrl}/wp-admin/edit.php?post_type=product` }, - { title: '客户管理', url: `${baseUrl}/wp-admin/users.php` }, - { title: '插件管理', url: `${baseUrl}/wp-admin/plugins.php` }, - { title: '主题管理', url: `${baseUrl}/wp-admin/themes.php` }, - { title: 'WooCommerce设置', url: `${baseUrl}/wp-admin/admin.php?page=wc-settings` }, - { title: 'WooCommerce报告', url: `${baseUrl}/wp-admin/admin.php?page=wc-reports` }, - ]; - return links; - } - - createMedia(file: any): Promise { - throw new Error('Method not implemented.'); - } - batchProcessOrders?(data: { create?: any[]; update?: any[]; delete?: Array; }): Promise { - throw new Error('Method not implemented.'); - } - batchProcessCustomers?(data: { create?: any[]; update?: any[]; delete?: Array; }): Promise { - throw new Error('Method not implemented.'); - } - - - - mapProductSearchParams(params: UnifiedSearchParamsDTO): Partial { + mapCustomerSearchParams(params: UnifiedSearchParamsDTO): Record { const page = Number(params.page ?? 1); const per_page = Number(params.per_page ?? 20); const where = params.where && typeof params.where === 'object' ? params.where : {}; + const mapped: any = { ...(params.search ? { search: params.search } : {}), - ...(where.status ? { status: where.status } : {}), page, per_page, }; + // 处理orderBy参数,转换为WooCommerce API的order和orderby格式 + if (params.orderBy) { + // 支持字符串格式 "field:desc" 或对象格式 { "field": "desc" } + if (typeof params.orderBy === 'string') { + const [field, direction = 'desc'] = params.orderBy.split(':'); + mapped.orderby = field; + mapped.order = direction.toLowerCase() === 'asc' ? 'asc' : 'desc'; + } else if (typeof params.orderBy === 'object') { + const entries = Object.entries(params.orderBy); + if (entries.length > 0) { + const [field, direction] = entries[0]; + mapped.orderby = field; + mapped.order = direction === 'asc' ? 'asc' : 'desc'; + } + } + } + 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); }; - if (where.search_fields ?? where.searchFields) mapped.search_fields = toArray(where.search_fields ?? where.searchFields); - if (where.after ?? where.date_created_after ?? where.created_after) mapped.after = String(where.after ?? where.date_created_after ?? where.created_after); - if (where.before ?? where.date_created_before ?? where.created_before) mapped.before = String(where.before ?? where.date_created_before ?? where.created_before); - if (where.modified_after ?? where.date_modified_after) mapped.modified_after = String(where.modified_after ?? where.date_modified_after); - if (where.modified_before ?? where.date_modified_before) mapped.modified_before = String(where.modified_before ?? where.date_modified_before); - if (where.dates_are_gmt ?? where.datesAreGmt) mapped.dates_are_gmt = Boolean(where.dates_are_gmt ?? where.datesAreGmt); - if (where.exclude ?? where.exclude_ids ?? where.excludedIds) mapped.exclude = toArray(where.exclude ?? where.exclude_ids ?? where.excludedIds); - if (where.include ?? where.ids) mapped.include = toArray(where.include ?? where.ids); - if (where.offset !== undefined) mapped.offset = Number(where.offset); - 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.slug) mapped.slug = String(where.slug); - if (!mapped.status && (where.status || where.include_status || where.exclude_status || where.includeStatus || where.excludeStatus)) { - if (where.include_status ?? where.includeStatus) mapped.include_status = String(where.include_status ?? where.includeStatus); - if (where.exclude_status ?? where.excludeStatus) mapped.exclude_status = String(where.exclude_status ?? where.excludeStatus); - if (where.status) mapped.status = String(where.status); - } - if (where.type) mapped.type = String(where.type); - if (where.include_types ?? where.includeTypes) mapped.include_types = String(where.include_types ?? where.includeTypes); - if (where.exclude_types ?? where.excludeTypes) mapped.exclude_types = String(where.exclude_types ?? where.excludeTypes); - if (where.sku) mapped.sku = String(where.sku); - if (where.featured ?? where.isFeatured) mapped.featured = Boolean(where.featured ?? where.isFeatured); - if (where.category ?? where.categoryId) mapped.category = String(where.category ?? where.categoryId); - if (where.tag ?? where.tagId) mapped.tag = String(where.tag ?? where.tagId); - if (where.shipping_class ?? where.shippingClass) mapped.shipping_class = String(where.shipping_class ?? where.shippingClass); - if (where.attribute ?? where.attributeName) mapped.attribute = String(where.attribute ?? where.attributeName); - if (where.attribute_term ?? where.attributeTermId ?? where.attributeTerm) mapped.attribute_term = String(where.attribute_term ?? where.attributeTermId ?? where.attributeTerm); - if (where.tax_class ?? where.taxClass) mapped.tax_class = String(where.tax_class ?? where.taxClass); - if (where.on_sale ?? where.onSale) mapped.on_sale = Boolean(where.on_sale ?? where.onSale); - if (where.min_price ?? where.minPrice) mapped.min_price = String(where.min_price ?? where.minPrice); - if (where.max_price ?? where.maxPrice) mapped.max_price = String(where.max_price ?? where.maxPrice); - if (where.stock_status ?? where.stockStatus) mapped.stock_status = String(where.stock_status ?? where.stockStatus); - if (where.virtual !== undefined) mapped.virtual = Boolean(where.virtual); - if (where.downloadable !== undefined) mapped.downloadable = Boolean(where.downloadable); + 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.exclude) mapped.exclude = toArray(where.exclude); + if (where.include) mapped.include = toArray(where.include); + if (where.ids) mapped.include = toArray(where.ids); + if (toNumber(where.offset) !== undefined) mapped.offset = Number(where.offset); + + if (where.email) mapped.email = String(where.email); + const roleSource = where.role; + if (roleSource !== undefined) mapped.role = String(roleSource); return mapped; } + // 客户操作方法 + async getCustomer(where: Partial>): Promise { + const api = this.wpService.createApi(this.site, 'wc/v3'); + // 根据提供的条件构建查询参数 + let endpoint: string; + if (where.id) { + endpoint = `customers/${where.id}`; + } else if (where.email) { + // 使用邮箱查询客户 + const res = await api.get('customers', { params: { email: where.email } }); + if (!res.data || res.data.length === 0) { + throw new Error('Customer not found'); + } + return this.mapPlatformToUnifiedCustomer(res.data[0]); + } else if (where.phone) { + // 使用电话查询客户 + const res = await api.get('customers', { params: { search: where.phone } }); + if (!res.data || res.data.length === 0) { + throw new Error('Customer not found'); + } + return this.mapPlatformToUnifiedCustomer(res.data[0]); + } else { + throw new Error('Must provide at least one of id, email, or phone'); + } + const res = await api.get(endpoint); + return this.mapPlatformToUnifiedCustomer(res.data); + } + + async getCustomers(params: UnifiedSearchParamsDTO): Promise> { + const requestParams = this.mapCustomerSearchParams(params); + const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged( + this.site, + 'customers', + requestParams + ); + return { + items: items.map((i: any) => this.mapPlatformToUnifiedCustomer(i)), + total, + totalPages, + page, + per_page, + + }; + } + + async getAllCustomers(params?: UnifiedSearchParamsDTO): Promise { + // 使用sdkGetAll获取所有客户数据,不受分页限制 + const api = this.wpService.createApi(this.site, 'wc/v3'); + + // 处理orderBy参数,转换为WooCommerce API需要的格式 + const requestParams = this.mapCustomerSearchParams(params || {}); + + const customers = await this.wpService.sdkGetAll(api, 'customers', requestParams); + return customers.map((customer: any) => this.mapPlatformToUnifiedCustomer(customer)); + } + + async createCustomer(data: Partial): Promise { + const api = this.wpService.createApi(this.site, 'wc/v3'); + const res = await api.post('customers', data); + return this.mapPlatformToUnifiedCustomer(res.data); + } + + async updateCustomer(where: Partial>, data: Partial): Promise { + const api = this.wpService.createApi(this.site, 'wc/v3'); + let customerId: string | number; + + // 先根据条件获取客户ID + if (where.id) { + customerId = where.id; + } else { + // 如果没有提供ID,则先查询客户 + const customer = await this.getCustomer(where); + customerId = customer.id; + } + + const res = await api.put(`customers/${customerId}`, data); + return this.mapPlatformToUnifiedCustomer(res.data); + } + + async deleteCustomer(where: Partial>): Promise { + const api = this.wpService.createApi(this.site, 'wc/v3'); + let customerId: string | number; + + // 先根据条件获取客户ID + if (where.id) { + customerId = where.id; + } else { + // 如果没有提供ID,则先查询客户 + const customer = await this.getCustomer(where); + customerId = customer.id; + } + + await api.delete(`customers/${customerId}`, { force: true }); + return true; + } + + // ========== 媒体映射方法 ========== + mapUnifiedToPlatformMedia(data: Partial) { + return data; + } + + mapPlatformToUnifiedMedia(item: WpMedia): UnifiedMediaDTO { + // 将 WordPress 媒体数据映射为统一媒体DTO + // 兼容不同字段命名的时间信息 + return { + id: item.id, + title: + typeof item.title === 'string' + ? item.title + : item.title?.rendered || '', + media_type: item.media_type, + mime_type: item.mime_type, + source_url: item.source_url, + date_created: item.date_created ?? item.date, + date_modified: item.date_modified ?? item.modified, + }; + } + + // 媒体操作方法 + async getMedia(params: UnifiedSearchParamsDTO): Promise> { + // 获取媒体列表并映射为统一媒体DTO集合 + const { items, total, totalPages, page, per_page } = await this.wpService.fetchMediaPaged( + this.site, + params + ); + return { + items: items.map(this.mapPlatformToUnifiedMedia.bind(this)), + total, + totalPages, + page, + per_page, + }; + } + + async getAllMedia(params?: UnifiedSearchParamsDTO): Promise { + // 使用sdkGetAll获取所有媒体数据,不受分页限制 + const api = this.wpService.createApi(this.site, 'wc/v3'); + const media = await this.wpService.sdkGetAll(api, 'media', params); + return media.map((mediaItem: any) => this.mapPlatformToUnifiedMedia(mediaItem)); + } + + createMedia(file: any): Promise { + throw new Error('Method not implemented.'); + } + + async updateMedia(where: {id: string | number}, data: any): Promise { + // 更新媒体信息 + return await this.wpService.updateMedia(Number(this.site.id), Number(where.id), data); + } + + async deleteMedia(where: {id: string | number}): Promise { + // 删除媒体资源 + await this.wpService.deleteMedia(Number(this.site.id), Number(where.id), true); + return true; + } + + async convertMediaToWebp(ids: Array): Promise<{ converted: any[]; failed: any[] }> { + // 函数说明 调用服务层将站点的指定媒体批量转换为 webp 并上传 + const result = await this.wpService.convertMediaToWebp(Number(this.site.id), ids); + return result as any; + } + + // ========== 订单映射方法 ========== + mapUnifiedToPlatformOrder(data: Partial) { + return data; + } + + mapCreateOrderParams(data: Partial) { + return data; + } + mapUpdateOrderParams(data: Partial) { + return data; + } + mapOrderSearchParams(params: UnifiedSearchParamsDTO): Partial { // 计算分页参数 const page = Number(params.page ?? 1); @@ -293,147 +374,6 @@ export class WooCommerceAdapter implements ISiteAdapter { return mapped; } - mapCustomerSearchParams(params: UnifiedSearchParamsDTO): Record { - const page = Number(params.page ?? 1); - const per_page = Number(params.per_page ?? 20); - const where = params.where && typeof params.where === 'object' ? params.where : {}; - - - const mapped: any = { - ...(params.search ? { search: params.search } : {}), - page, - per_page, - }; - - // 处理orderBy参数,转换为WooCommerce API的order和orderby格式 - if (params.orderBy) { - // 支持字符串格式 "field:desc" 或对象格式 { "field": "desc" } - if (typeof params.orderBy === 'string') { - const [field, direction = 'desc'] = params.orderBy.split(':'); - mapped.orderby = field; - mapped.order = direction.toLowerCase() === 'asc' ? 'asc' : 'desc'; - } else if (typeof params.orderBy === 'object') { - const entries = Object.entries(params.orderBy); - if (entries.length > 0) { - const [field, direction] = entries[0]; - mapped.orderby = field; - mapped.order = direction === 'asc' ? 'asc' : 'desc'; - } - } - } - - 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.exclude) mapped.exclude = toArray(where.exclude); - if (where.include) mapped.include = toArray(where.include); - if (where.ids) mapped.include = toArray(where.ids); - if (toNumber(where.offset) !== undefined) mapped.offset = Number(where.offset); - - if (where.email) mapped.email = String(where.email); - const roleSource = where.role; - if (roleSource !== undefined) mapped.role = String(roleSource); - - return mapped; - } - - mapProduct(item: WooProduct): UnifiedProductDTO { - // 将 WooCommerce 产品数据映射为统一产品DTO - // 保留常用字段与时间信息以便前端统一展示 - // https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#product-properties - - // 映射变体数据 - const mappedVariations = item.variations && Array.isArray(item.variations) - ? item.variations - .filter((variation: any) => typeof variation !== 'number') // 过滤掉数字类型的变体ID - .map((variation: any) => { - // 将变体属性转换为统一格式 - const mappedAttributes = variation.attributes && Array.isArray(variation.attributes) - ? variation.attributes.map((attr: any) => ({ - id: attr.id, - name: attr.name || '', - position: attr.position, - visible: attr.visible, - variation: attr.variation, - option: attr.option || '' // 变体属性使用 option 而不是 options - })) - : []; - - // 映射变体图片 - const mappedImage = variation.image - ? { - id: variation.image.id, - src: variation.image.src, - name: variation.image.name, - alt: variation.image.alt, - } - : undefined; - - return { - id: variation.id, - name: variation.name || item.name, // 如果变体没有名称,使用父产品名称 - sku: variation.sku || '', - regular_price: String(variation.regular_price || ''), - sale_price: String(variation.sale_price || ''), - price: String(variation.price || ''), - stock_status: variation.stock_status || 'outofstock', - stock_quantity: variation.stock_quantity || 0, - attributes: mappedAttributes, - image: mappedImage - }; - }) - : []; - - return { - id: item.id, - date_created: item.date_created, - date_modified: item.date_modified, - type: item.type, // simple grouped external variable - status: item.status, // draft pending private publish - sku: item.sku, - name: item.name, - //价格 - regular_price: item.regular_price, - sale_price: item.sale_price, - price: item.price, - stock_status: item.stock_status, - stock_quantity: item.stock_quantity, - images: (item.images || []).map((img: any) => ({ - id: img.id, - src: img.src, - name: img.name, - alt: img.alt, - })), - categories: (item.categories || []).map((c: any) => ({ - id: c.id, - name: c.name, - })), - tags: (item.tags || []).map((t: any) => ({ - id: t.id, - name: t.name, - })), - attributes: (item.attributes || []).map(attr => ({ - id: attr.id, - name: attr.name || '', - position: attr.position, - visible: attr.visible, - variation: attr.variation, - options: attr.options || [] - })), - variations: mappedVariations, - permalink: item.permalink, - raw: item, - }; - } private buildFullAddress(addr: any): string { if (!addr) return ''; const name = addr.fullname || `${addr.first_name || ''} ${addr.last_name || ''}`.trim(); @@ -449,7 +389,8 @@ export class WooCommerceAdapter implements ISiteAdapter { addr.phone ].filter(Boolean).join(', '); } - mapOrder(item: WooOrder): UnifiedOrderDTO { + + mapPlatformToUnifiedOrder(item: WooOrder): UnifiedOrderDTO { // 将 WooCommerce 订单数据映射为统一订单DTO // 包含账单地址与收货地址以及创建与更新时间 @@ -502,190 +443,17 @@ export class WooCommerceAdapter implements ISiteAdapter { }; } - mapSubscription(item: WooSubscription): UnifiedSubscriptionDTO { - // 将 WooCommerce 订阅数据映射为统一订阅DTO - // 若缺少创建时间则回退为开始时间 - return { - id: item.id, - status: item.status, - customer_id: item.customer_id, - billing_period: item.billing_period, - billing_interval: item.billing_interval, - date_created: item.date_created ?? item.start_date, - date_modified: item.date_modified, - start_date: item.start_date, - next_payment_date: item.next_payment_date, - line_items: item.line_items, - raw: item, - }; + // 订单操作方法 + async getOrder(where: {id: string | number}): Promise { + // 获取单个订单详情 + const api = this.wpService.createApi(this.site, 'wc/v3'); + const res = await api.get(`orders/${where.id}`); + return this.mapPlatformToUnifiedOrder(res.data); } - mapMedia(item: WpMedia): UnifiedMediaDTO { - // 将 WordPress 媒体数据映射为统一媒体DTO - // 兼容不同字段命名的时间信息 - return { - id: item.id, - title: - typeof item.title === 'string' - ? item.title - : item.title?.rendered || '', - media_type: item.media_type, - mime_type: item.mime_type, - source_url: item.source_url, - date_created: item.date_created ?? item.date, - date_modified: item.date_modified ?? item.modified, - }; - } - - async getProducts( - params: UnifiedSearchParamsDTO - ): Promise> { - // 获取产品列表并使用统一分页结构返回 - const requestParams = this.mapProductSearchParams(params); - const { items, total, totalPages, page, per_page } = - await this.wpService.fetchResourcePaged( - this.site, - 'products', - requestParams - ); - - // 对于类型为 variable 的产品,需要加载完整的变体数据 - const productsWithVariations = await Promise.all( - items.map(async (item: any) => { - // 如果产品类型是 variable 且有变体 ID 列表,则加载完整的变体数据 - if (item.type === 'variable' && item.variations && Array.isArray(item.variations) && item.variations.length > 0) { - try { - // 批量获取该产品的所有变体数据 - const variations = await this.wpService.sdkGetAll( - (this.wpService as any).createApi(this.site, 'wc/v3'), - `products/${item.id}/variations` - ); - // 将完整的变体数据添加到产品对象中 - item.variations = variations; - } catch (error) { - // 如果获取变体失败,保持原有的 ID 数组 - console.error(`获取产品 ${item.id} 的变体数据失败:`, error); - } - } - return item; - }) - ); - - return { - items: productsWithVariations.map(this.mapProduct), - total, - totalPages, - page, - per_page, - - }; - } - - async getAllProducts(params?: UnifiedSearchParamsDTO): Promise { - // 使用sdkGetAll获取所有产品数据,不受分页限制 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const products = await this.wpService.sdkGetAll(api, 'products', params); - - // 对于类型为 variable 的产品,需要加载完整的变体数据 - const productsWithVariations = await Promise.all( - products.map(async (product: any) => { - // 如果产品类型是 variable 且有变体 ID 列表,则加载完整的变体数据 - if (product.type === 'variable' && product.variations && Array.isArray(product.variations) && product.variations.length > 0) { - try { - // 批量获取该产品的所有变体数据 - const variations = await this.wpService.sdkGetAll( - api, - `products/${product.id}/variations` - ); - // 将完整的变体数据添加到产品对象中 - product.variations = variations; - } catch (error) { - // 如果获取变体失败,保持原有的 ID 数组 - console.error(`获取产品 ${product.id} 的变体数据失败:`, error); - } - } - return product; - }) - ); - - return productsWithVariations.map((product: any) => this.mapProduct(product)); - } - - async getProduct(id: string | number): Promise { - // 获取单个产品详情并映射为统一产品DTO - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const res = await api.get(`products/${id}`); - const product = res.data; - - // 如果产品类型是 variable 且有变体 ID 列表,则加载完整的变体数据 - if (product.type === 'variable' && product.variations && Array.isArray(product.variations) && product.variations.length > 0) { - try { - // 批量获取该产品的所有变体数据 - const variations = await this.wpService.sdkGetAll( - api, - `products/${product.id}/variations` - ); - // 将完整的变体数据添加到产品对象中 - product.variations = variations; - } catch (error) { - // 如果获取变体失败,保持原有的 ID 数组 - console.error(`获取产品 ${product.id} 的变体数据失败:`, error); - } - } - - return this.mapProduct(product); - } - - async createProduct(data: Partial): Promise { - // 创建产品并返回统一产品DTO - const res = await this.wpService.createProduct(this.site, data); - return this.mapProduct(res); - } - - async updateProduct(id: string | number, data: Partial): Promise { - // 更新产品并返回统一产品DTO - const res = await this.wpService.updateProduct(this.site, String(id), data as any); - return res - } - - async getOrderNotes(orderId: string | number): Promise { - // 获取订单备注列表 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const res = await api.get(`orders/${orderId}/notes`); - return res.data; - } - - async createOrderNote(orderId: string | number, data: any): Promise { - // 创建订单备注 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const res = await api.post(`orders/${orderId}/notes`, data); - return res.data; - } - - async deleteProduct(id: string | number): Promise { - // 删除产品 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - try { - await api.delete(`products/${id}`, { force: true }); - return true; - } catch (e) { - return false; - } - } - - async batchProcessProducts( - data: { create?: any[]; update?: any[]; delete?: Array } - ): Promise { - // 批量处理产品增删改 - return await this.wpService.batchProcessProducts(this.site, data); - } - - async getOrders( - params: UnifiedSearchParamsDTO - ): Promise> { + async getOrders(params: UnifiedSearchParamsDTO): Promise> { const requestParams = this.mapOrderSearchParams(params); - const { items, total, totalPages, page, per_page } = - await this.wpService.fetchResourcePaged(this.site, 'orders', requestParams); + const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged(this.site, 'orders', requestParams); // 并行获取所有订单的履行信息 const ordersWithFulfillments = await Promise.all( @@ -710,7 +478,7 @@ export class WooCommerceAdapter implements ISiteAdapter { ); return { - items: ordersWithFulfillments.map(this.mapOrder), + items: ordersWithFulfillments.map(this.mapPlatformToUnifiedOrder), total, totalPages, page, @@ -718,296 +486,41 @@ export class WooCommerceAdapter implements ISiteAdapter { }; } - async getOrder(id: string | number): Promise { - // 获取单个订单详情 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const res = await api.get(`orders/${id}`); - return this.mapOrder(res.data); - } - async getAllOrders(params?: UnifiedSearchParamsDTO): Promise { // 使用sdkGetAll获取所有订单数据,不受分页限制 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); + const api = this.wpService.createApi(this.site, 'wc/v3'); const orders = await this.wpService.sdkGetAll(api, 'orders', params); - return orders.map((order: any) => this.mapOrder(order)); + return orders.map((order: any) => this.mapPlatformToUnifiedOrder(order)); + } + + async countOrders(where: Record): Promise { + // 使用最小分页只获取总数 + const searchParams: UnifiedSearchParamsDTO = { + where, + page: 1, + per_page: 1, + }; + const requestParams = this.mapOrderSearchParams(searchParams); + const { total } = await this.wpService.fetchResourcePaged(this.site, 'orders', requestParams); + return total || 0; } async createOrder(data: Partial): Promise { // 创建订单并返回统一订单DTO - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); + const api = this.wpService.createApi(this.site, 'wc/v3'); const res = await api.post('orders', data); - return this.mapOrder(res.data); + return this.mapPlatformToUnifiedOrder(res.data); } - async updateOrder(id: string | number, data: Partial): Promise { + async updateOrder(where: {id: string | number}, data: Partial): Promise { // 更新订单并返回布尔结果 - return await this.wpService.updateOrder(this.site, String(id), data as any); + return await this.wpService.updateOrder(this.site, String(where.id), data as any); } - async deleteOrder(id: string | number): Promise { + async deleteOrder(where: {id: string | number}): Promise { // 删除订单 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - await api.delete(`orders/${id}`, { force: true }); - return true; - } - - async fulfillOrder(orderId: string | number, data: { - tracking_number?: string; - shipping_provider?: string; - shipping_method?: string; - items?: Array<{ - order_item_id: number; - quantity: number; - }>; - }): Promise { - throw new Error('暂无实现') - // 订单履行(发货) - // const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - - // try { - // // 更新订单状态为已完成 - // await api.put(`orders/${orderId}`, { status: 'completed' }); - - // // 如果提供了物流信息,添加到订单备注 - // if (data.tracking_number || data.shipping_provider) { - // const note = `订单已发货${data.tracking_number ? `,物流单号:${data.tracking_number}` : ''}${data.shipping_provider ? `,物流公司:${data.shipping_provider}` : ''}`; - // await api.post(`orders/${orderId}/notes`, { note, customer_note: true }); - // } - - // return { - // success: true, - // order_id: orderId, - // fulfillment_id: `fulfillment_${orderId}_${Date.now()}`, - // tracking_number: data.tracking_number, - // shipping_provider: data.shipping_provider, - // fulfilled_at: new Date().toISOString() - // }; - // } catch (error) { - // throw new Error(`履行失败: ${error.message}`); - // } - } - - async cancelFulfillment(orderId: string | number, data: { - reason?: string; - shipment_id?: string; - }): Promise { - throw new Error('暂未实现') - // 取消订单履行 - // const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - - // try { - // // 将订单状态改回处理中 - // await api.put(`orders/${orderId}`, { status: 'processing' }); - - // // 添加取消履行的备注 - // const note = `订单履行已取消${data.reason ? `,原因:${data.reason}` : ''}`; - // await api.post(`orders/${orderId}/notes`, { note, customer_note: true }); - - // return { - // success: true, - // order_id: orderId, - // shipment_id: data.shipment_id, - // reason: data.reason, - // cancelled_at: new Date().toISOString() - // }; - // } catch (error) { - // throw new Error(`取消履行失败: ${error.message}`); - // } - } - - async getSubscriptions( - params: UnifiedSearchParamsDTO - ): Promise> { - // 获取订阅列表并映射为统一订阅DTO集合 - const { items, total, totalPages, page, per_page } = - await this.wpService.fetchResourcePaged( - this.site, - 'subscriptions', - params - ); - return { - items: items.map(this.mapSubscription), - total, - totalPages, - page, - per_page, - - }; - } - - async getAllSubscriptions(params?: UnifiedSearchParamsDTO): Promise { - // 使用sdkGetAll获取所有订阅数据,不受分页限制 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const subscriptions = await this.wpService.sdkGetAll(api, 'subscriptions', params); - return subscriptions.map((subscription: any) => this.mapSubscription(subscription)); - } - - async getMedia( - params: UnifiedSearchParamsDTO - ): Promise> { - // 获取媒体列表并映射为统一媒体DTO集合 - const { items, total, totalPages, page, per_page } = await this.wpService.fetchMediaPaged( - this.site, - params - ); - return { - items: items.map(this.mapMedia.bind(this)), - total, - totalPages, - page, - per_page, - }; - } - - async getAllMedia(params?: UnifiedSearchParamsDTO): Promise { - // 使用sdkGetAll获取所有媒体数据,不受分页限制 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const media = await this.wpService.sdkGetAll(api, 'media', params); - return media.map((mediaItem: any) => this.mapMedia(mediaItem)); - } - - mapReview(item: any): UnifiedReviewDTO & { raw: any } { - // 将 WooCommerce 评论数据映射为统一评论DTO - return { - id: item.id, - product_id: item.product_id, - author: item.reviewer, - email: item.reviewer_email, - content: item.review, - rating: item.rating, - status: item.status, - date_created: item.date_created, - raw: item - }; - } - - async getReviews( - params: UnifiedSearchParamsDTO - ): Promise { - // 获取评论列表并使用统一分页结构返回 - const requestParams = this.mapProductSearchParams(params); - const { items, total, totalPages, page, per_page } = - await this.wpService.fetchResourcePaged( - this.site, - 'products/reviews', - requestParams - ); - return { - items: items.map(this.mapReview.bind(this)), - total, - totalPages, - page, - per_page, - }; - } - - async getAllReviews(params?: UnifiedSearchParamsDTO): Promise { - // 使用sdkGetAll获取所有评论数据,不受分页限制 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const reviews = await this.wpService.sdkGetAll(api, 'products/reviews', params); - return reviews.map((review: any) => this.mapReview(review)); - } - - async createReview(data: any): Promise { - const res = await this.wpService.createReview(this.site, data); - return this.mapReview(res); - } - - async updateReview(id: number, data: any): Promise { - const res = await this.wpService.updateReview(this.site, id, data); - return this.mapReview(res); - } - - async deleteReview(id: number): Promise { - return await this.wpService.deleteReview(this.site, id); - } - - async deleteMedia(id: string | number): Promise { - // 删除媒体资源 - await this.wpService.deleteMedia(Number(this.site.id), Number(id), true); - return true; - } - - async updateMedia(id: string | number, data: any): Promise { - // 更新媒体信息 - return await this.wpService.updateMedia(Number(this.site.id), Number(id), data); - } - - async convertMediaToWebp(ids: Array): Promise<{ converted: any[]; failed: any[] }> { - // 函数说明 调用服务层将站点的指定媒体批量转换为 webp 并上传 - const result = await this.wpService.convertMediaToWebp(Number(this.site.id), ids); - return result as any; - } - - mapCustomer(item: WooCustomer): UnifiedCustomerDTO { - // 将 WooCommerce 客户数据映射为统一客户DTO - // 包含基础信息地址信息与时间信息 - return { - id: item.id, - avatar: item.avatar_url, - email: item.email, - orders: Number(item.orders ?? 0), - total_spend: Number(item.total_spent ?? 0), - first_name: item.first_name, - last_name: item.last_name, - username: item.username, - phone: item.billing?.phone || item.shipping?.phone, - billing: item.billing, - shipping: item.shipping, - date_created: item.date_created, - date_modified: item.date_modified, - raw: item, - }; - } - async getCustomers(params: UnifiedSearchParamsDTO): Promise> { - const requestParams = this.mapCustomerSearchParams(params); - const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged( - this.site, - 'customers', - requestParams - ); - return { - items: items.map((i: any) => this.mapCustomer(i)), - total, - totalPages, - page, - per_page, - - }; - } - - async getAllCustomers(params?: UnifiedSearchParamsDTO): Promise { - // 使用sdkGetAll获取所有客户数据,不受分页限制 - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - - // 处理orderBy参数,转换为WooCommerce API需要的格式 - const requestParams = this.mapCustomerSearchParams(params || {}); - - const customers = await this.wpService.sdkGetAll(api, 'customers', requestParams); - return customers.map((customer: any) => this.mapCustomer(customer)); - } - - async getCustomer(id: string | number): Promise { - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const res = await api.get(`customers/${id}`); - return this.mapCustomer(res.data); - } - - async createCustomer(data: Partial): Promise { - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const res = await api.post('customers', data); - return this.mapCustomer(res.data); - } - - async updateCustomer(id: string | number, data: Partial): Promise { - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - const res = await api.put(`customers/${id}`, data); - return this.mapCustomer(res.data); - } - - async deleteCustomer(id: string | number): Promise { - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); - await api.delete(`customers/${id}`, { force: true }); + const api = this.wpService.createApi(this.site, 'wc/v3'); + await api.delete(`orders/${where.id}`, { force: true }); return true; } @@ -1069,6 +582,582 @@ export class WooCommerceAdapter implements ISiteAdapter { return await this.wpService.deleteFulfillment(this.site, String(orderId), fulfillmentId); } + async getOrderNotes(orderId: string | number): Promise { + // 获取订单备注列表 + const api = this.wpService.createApi(this.site, 'wc/v3'); + const res = await api.get(`orders/${orderId}/notes`); + return res.data; + } + + async createOrderNote(orderId: string | number, data: any): Promise { + // 创建订单备注 + const api = this.wpService.createApi(this.site, 'wc/v3'); + const res = await api.post(`orders/${orderId}/notes`, data); + return res.data; + } + + async cancelFulfillment(orderId: string | number, data: { + reason?: string; + shipment_id?: string; + }): Promise { + throw new Error('暂未实现'); + // 取消订单履行 + // const api = this.wpService.createApi(this.site, 'wc/v3'); + + // try { + // // 将订单状态改回处理中 + // await api.put(`orders/${orderId}`, { status: 'processing' }); + + // // 添加取消履行的备注 + // const note = `订单履行已取消${data.reason ? `,原因:${data.reason}` : ''}`; + // await api.post(`orders/${orderId}/notes`, { note, customer_note: true }); + + // return { + // success: true, + // order_id: orderId, + // shipment_id: data.shipment_id, + // reason: data.reason, + // cancelled_at: new Date().toISOString() + // }; + // } catch (error) { + // throw new Error(`取消履行失败: ${error.message}`); + // } + } + + // ========== 产品映射方法 ========== + mapUnifiedToPlatformProduct(data: Partial): Partial { + // 将统一产品DTO映射为WooCommerce产品数据 + // 基本字段映射 + const mapped: Partial = { + id: data.id as number, + name: data.name, + type: data.type, + status: data.status, + sku: data.sku, + regular_price: data.regular_price, + sale_price: data.sale_price, + price: data.price, + stock_status: data.stock_status as 'instock' | 'outofstock' | 'onbackorder', + stock_quantity: data.stock_quantity, + // 映射更多WooCommerce产品特有的字段 + // featured: data.featured, + // catalog_visibility: data.catalog_visibility, + // date_on_sale_from: data.date_on_sale_from, + // date_on_sale_to: data.date_on_sale_to, + // virtual: data.virtual, + // downloadable: data.downloadable, + // description: data.description, + // short_description: data.short_description, + // slug: data.slug, + // manage_stock: data.manage_stock, + // backorders: data.backorders as 'no' | 'notify' | 'yes', + // sold_individually: data.sold_individually, + // weight: data.weight, + // dimensions: data.dimensions, + // shipping_class: data.shipping_class, + // tax_class: data.tax_class, + }; + + // 映射图片数据 + if (data.images && Array.isArray(data.images)) { + mapped.images = data.images.map(img => ({ + id: img.id as number, + src: img.src, + name: img.name, + alt: img.alt, + })); + } + + // 映射分类数据 + if (data.categories && Array.isArray(data.categories)) { + mapped.categories = data.categories.map(cat => ({ + // id: cat.id as number, //TODO + name: cat.name, + })); + } + + // 映射标签数据 + // TODO tags 应该可以设置 + // if (data.tags && Array.isArray(data.tags)) { + // mapped.tags = data.tags.map(tag => { + // return ({ + // // id: tag.id as number, + // name: tag.name, + // }); + // }); + // } + + // 映射属性数据 + if (data.attributes && Array.isArray(data.attributes)) { + mapped.attributes = data.attributes.map(attr => ({ + // id 由于我们这个主要用来存,所以不映射 id + name: attr.name, + visible: attr.visible, + variation: attr.variation, + options: attr.options + })); + } + + // 映射变体数据(注意:WooCommerce API 中变体通常通过单独的端点处理) + // 这里只映射变体的基本信息,具体创建/更新变体需要额外处理 + if (data.variations && Array.isArray(data.variations)) { + // 对于WooProduct类型,variations字段只存储变体ID + mapped.variations = data.variations.map(variation => variation.id as number); + } + + // 映射下载数据(如果产品是可下载的) + // if (data.downloads && Array.isArray(data.downloads)) { + // mapped.downloads = data.downloads.map(download => ({ + // id: download.id as number, + // name: download.name, + // file: download.file, + // })); + // } + + return mapped; + } + + mapCreateProductParams(data: Partial):Partial { + const {id,...mapped}= this.mapUnifiedToPlatformProduct(data); + // 创建不带 id + return mapped + } + mapUpdateProductParams(data: Partial): Partial { + return this.mapUnifiedToPlatformProduct(data); + } + + mapProductSearchParams(params: UnifiedSearchParamsDTO): Partial { + const page = Number(params.page ?? 1); + const per_page = Number(params.per_page ?? 20); + const where = params.where && typeof params.where === 'object' ? params.where : {}; + + const mapped: any = { + ...(params.search ? { search: params.search } : {}), + ...(where.status ? { status: where.status } : {}), + 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); + }; + + if (where.search_fields ?? where.searchFields) mapped.search_fields = toArray(where.search_fields ?? where.searchFields); + if (where.after ?? where.date_created_after ?? where.created_after) mapped.after = String(where.after ?? where.date_created_after ?? where.created_after); + if (where.before ?? where.date_created_before ?? where.created_before) mapped.before = String(where.before ?? where.date_created_before ?? where.created_before); + if (where.modified_after ?? where.date_modified_after) mapped.modified_after = String(where.modified_after ?? where.date_modified_after); + if (where.modified_before ?? where.date_modified_before) mapped.modified_before = String(where.modified_before ?? where.date_modified_before); + if (where.dates_are_gmt ?? where.datesAreGmt) mapped.dates_are_gmt = Boolean(where.dates_are_gmt ?? where.datesAreGmt); + if (where.exclude ?? where.exclude_ids ?? where.excludedIds) mapped.exclude = toArray(where.exclude ?? where.exclude_ids ?? where.excludedIds); + if (where.include ?? where.ids) mapped.include = toArray(where.include ?? where.ids); + if (where.offset !== undefined) mapped.offset = Number(where.offset); + 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.slug) mapped.slug = String(where.slug); + if (!mapped.status && (where.status || where.include_status || where.exclude_status || where.includeStatus || where.excludeStatus)) { + if (where.include_status ?? where.includeStatus) mapped.include_status = String(where.include_status ?? where.includeStatus); + if (where.exclude_status ?? where.excludeStatus) mapped.exclude_status = String(where.exclude_status ?? where.excludeStatus); + if (where.status) mapped.status = String(where.status); + } + if (where.type) mapped.type = String(where.type); + if (where.include_types ?? where.includeTypes) mapped.include_types = String(where.include_types ?? where.includeTypes); + if (where.exclude_types ?? where.excludeTypes) mapped.exclude_types = String(where.exclude_types ?? where.excludeTypes); + if (where.sku) mapped.sku = String(where.sku); + if (where.featured ?? where.isFeatured) mapped.featured = Boolean(where.featured ?? where.isFeatured); + if (where.category ?? where.categoryId) mapped.category = String(where.category ?? where.categoryId); + if (where.tag ?? where.tagId) mapped.tag = String(where.tag ?? where.tagId); + if (where.shipping_class ?? where.shippingClass) mapped.shipping_class = String(where.shipping_class ?? where.shippingClass); + if (where.attribute ?? where.attributeName) mapped.attribute = String(where.attribute ?? where.attributeName); + if (where.attribute_term ?? where.attributeTermId ?? where.attributeTerm) mapped.attribute_term = String(where.attribute_term ?? where.attributeTermId ?? where.attributeTerm); + if (where.tax_class ?? where.taxClass) mapped.tax_class = String(where.tax_class ?? where.taxClass); + if (where.on_sale ?? where.onSale) mapped.on_sale = Boolean(where.on_sale ?? where.onSale); + if (where.min_price ?? where.minPrice) mapped.min_price = String(where.min_price ?? where.minPrice); + if (where.max_price ?? where.maxPrice) mapped.max_price = String(where.max_price ?? where.maxPrice); + if (where.stock_status ?? where.stockStatus) mapped.stock_status = String(where.stock_status ?? where.stockStatus); + if (where.virtual !== undefined) mapped.virtual = Boolean(where.virtual); + if (where.downloadable !== undefined) mapped.downloadable = Boolean(where.downloadable); + + return mapped; + } + + mapPlatformToUnifiedProduct(data: WooProduct): UnifiedProductDTO { + // 将 WooCommerce 产品数据映射为统一产品DTO + // 保留常用字段与时间信息以便前端统一展示 + // https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#product-properties + + // 映射变体数据 + const mappedVariations = data.variations && Array.isArray(data.variations) + ? data.variations + .filter((variation: any) => typeof variation !== 'number') // 过滤掉数字类型的变体ID + .map((variation: any) => { + // 将变体属性转换为统一格式 + const mappedAttributes = variation.attributes && Array.isArray(variation.attributes) + ? variation.attributes.map((attr: any) => ({ + id: attr.id, + name: attr.name || '', + position: attr.position, + visible: attr.visible, + variation: attr.variation, + option: attr.option || '' // 变体属性使用 option 而不是 options + })) + : []; + + // 映射变体图片 + const mappedImage = variation.image + ? { + id: variation.image.id, + src: variation.image.src, + name: variation.image.name, + alt: variation.image.alt, + } + : undefined; + + return { + id: variation.id, + name: variation.name || data.name, // 如果变体没有名称,使用父产品名称 + sku: variation.sku || '', + regular_price: String(variation.regular_price || ''), + sale_price: String(variation.sale_price || ''), + price: String(variation.price || ''), + stock_status: variation.stock_status || 'outofstock', + stock_quantity: variation.stock_quantity || 0, + attributes: mappedAttributes, + image: mappedImage + }; + }) + : []; + + return { + id: data.id, + date_created: data.date_created, + date_modified: data.date_modified, + type: data.type, // simple grouped external variable + status: data.status, // draft pending private publish + sku: data.sku, + name: data.name, + //价格 + regular_price: data.regular_price, + sale_price: data.sale_price, + price: data.price, + stock_status: data.stock_status, + stock_quantity: data.stock_quantity, + images: (data.images || []).map((img: any) => ({ + id: img.id, + src: img.src, + name: img.name, + alt: img.alt, + })), + categories: (data.categories || []).map((c: any) => ({ + id: c.id, + name: c.name, + })), + tags: (data.tags || []).map((t: any) => ({ + id: t.id, + name: t.name, + })), + attributes: (data.attributes || []).map(attr => ({ + id: attr.id, + name: attr.name || '', + position: attr.position, + visible: attr.visible, + variation: attr.variation, + options: attr.options || [] + })), + variations: mappedVariations, + permalink: data.permalink, + raw: data, + }; + } + // 判断是否是这个站点的sku + isSiteSkuThisSite(sku: string,){ + return sku.startsWith(this.site.skuPrefix+'-'); + } + async getProduct(where: Partial>): Promise{ + const { id, sku } = where; + if(id) return this.getProductById(id); + if(sku) return this.getProductBySku(sku); + throw new Error('必须提供id或sku参数'); + } + async getProductBySku(sku: string){ + // const api = this.wpService.createApi(this.site, 'wc/v3'); + // const res = await api.get(`products`,{ + // sku + // }); + // const product = res.data[0]; + const res = await this.wpService.getProducts(this.site,{ + sku, + page:1, + per_page:1, + }); + const product = res?.items?.[0]; + if(!product) return null + return this.mapPlatformToUnifiedProduct(product); + } + // 产品操作方法 + async getProductById(id: string | number): Promise { + // 获取单个产品详情并映射为统一产品DTO + const api = this.wpService.createApi(this.site, 'wc/v3'); + + const res = await api.get(`products/${id}`); + const product = res.data; + + // 如果产品类型是 variable 且有变体 ID 列表,则加载完整的变体数据 + if (product.type === 'variable' && product.variations && Array.isArray(product.variations) && product.variations.length > 0) { + try { + // 批量获取该产品的所有变体数据 + const variations = await this.wpService.sdkGetAll( + api, + `products/${product.id}/variations` + ); + // 将完整的变体数据添加到产品对象中 + product.variations = variations; + } catch (error) { + // 如果获取变体失败,保持原有的 ID 数组 + console.error(`获取产品 ${product.id} 的变体数据失败:`, error); + } + } + + return this.mapPlatformToUnifiedProduct(product); + } + + async getProducts(params: UnifiedSearchParamsDTO): Promise> { + // 获取产品列表并使用统一分页结构返回 + const requestParams = this.mapProductSearchParams(params); + const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged( + this.site, + 'products', + requestParams + ); + + // 对于类型为 variable 的产品,需要加载完整的变体数据 + const productsWithVariations = await Promise.all( + items.map(async (item: any) => { + // 如果产品类型是 variable 且有变体 ID 列表,则加载完整的变体数据 + if (item.type === 'variable' && item.variations && Array.isArray(item.variations) && item.variations.length > 0) { + try { + // 批量获取该产品的所有变体数据 + const variations = await this.wpService.sdkGetAll( + this.wpService.createApi(this.site, 'wc/v3'), + `products/${item.id}/variations` + ); + // 将完整的变体数据添加到产品对象中 + item.variations = variations; + } catch (error) { + // 如果获取变体失败,保持原有的 ID 数组 + console.error(`获取产品 ${item.id} 的变体数据失败:`, error); + } + } + return item; + }) + ); + + return { + items: productsWithVariations.map(this.mapPlatformToUnifiedProduct), + total, + totalPages, + page, + per_page, + + }; + } + + async getAllProducts(params?: UnifiedSearchParamsDTO): Promise { + // 使用sdkGetAll获取所有产品数据,不受分页限制 + const api = this.wpService.createApi(this.site, 'wc/v3'); + const products = await this.wpService.sdkGetAll(api, 'products', params); + + // 对于类型为 variable 的产品,需要加载完整的变体数据 + const productsWithVariations = await Promise.all( + products.map(async (product: any) => { + // 如果产品类型是 variable 且有变体 ID 列表,则加载完整的变体数据 + if (product.type === 'variable' && product.variations && Array.isArray(product.variations) && product.variations.length > 0) { + try { + // 批量获取该产品的所有变体数据 + const variations = await this.wpService.sdkGetAll( + api, + `products/${product.id}/variations` + ); + // 将完整的变体数据添加到产品对象中 + product.variations = variations; + } catch (error) { + // 如果获取变体失败,保持原有的 ID 数组 + console.error(`获取产品 ${product.id} 的变体数据失败:`, error); + } + } + return product; + }) + ); + + return productsWithVariations.map((product: any) => this.mapPlatformToUnifiedProduct(product)); + } + + async createProduct(data: Partial): Promise { + // 创建产品并返回统一产品DTO + const createData = this.mapCreateProductParams(data); + const res = await this.wpService.createProduct(this.site, createData); + return this.mapPlatformToUnifiedProduct(res); + } + + async updateProduct(where: Partial>, data: Partial): Promise { + // 更新产品并返回统一产品DTO + const product = await this.getProduct(where); + if(!product){ + throw new Error('产品不存在'); + } + const updateData = this.mapUpdateProductParams(data); + const res = await this.wpService.updateProduct(this.site, String(product.id), updateData as any); + return res; + } + + async deleteProduct(where: Partial>): Promise { + // 删除产品 + const product = await this.getProduct(where); + if(!product){ + throw new Error('产品不存在'); + } + const api = this.wpService.createApi(this.site, 'wc/v3'); + try { + await api.delete(`products/${product.id}`, { force: true }); + return true; + } catch (e) { + return false; + } + } + + // ========== 评论映射方法 ========== + + mapUnifiedToPlatformReview(data: Partial) { + return data; + } + + mapCreateReviewParams(data: CreateReviewDTO) { + return data; + } + mapUpdateReviewParams(data: UpdateReviewDTO) { + return data; + } + + mapPlatformToUnifiedReview(item: any): UnifiedReviewDTO { + // 将 WooCommerce 评论数据映射为统一评论DTO + return { + id: item.id, + product_id: item.product_id, + author: item.reviewer, + email: item.reviewer_email, + content: item.review, + rating: item.rating, + status: item.status, + date_created: item.date_created, + date_modified: item.date_modified, + }; + } + + // 评论操作方法 + async getReviews(params: UnifiedSearchParamsDTO): Promise { + // 获取评论列表并使用统一分页结构返回 + const requestParams = this.mapProductSearchParams(params); + const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged( + this.site, + 'products/reviews', + requestParams + ); + return { + items: items.map(this.mapPlatformToUnifiedReview.bind(this)), + total, + totalPages, + page, + per_page, + }; + } + + async getAllReviews(params?: UnifiedSearchParamsDTO): Promise { + // 使用sdkGetAll获取所有评论数据,不受分页限制 + const api = this.wpService.createApi(this.site, 'wc/v3'); + const reviews = await this.wpService.sdkGetAll(api, 'products/reviews', params); + return reviews.map((review: any) => this.mapPlatformToUnifiedReview(review)); + } + + async createReview(data: CreateReviewDTO): Promise { + const res = await this.wpService.createReview(this.site, data); + return this.mapPlatformToUnifiedReview(res); + } + + async updateReview(where: Partial>, data: UpdateReviewDTO): Promise { + const { id } = where; + if (!id) { + throw new Error('必须提供评论ID'); + } + const res = await this.wpService.updateReview(this.site, Number(id), data); + return this.mapPlatformToUnifiedReview(res); + } + + async deleteReview(where: Partial>): Promise { + const { id } = where; + if (!id) { + throw new Error('必须提供评论ID'); + } + return await this.wpService.deleteReview(this.site, Number(id)); + } + + // ========== 订阅映射方法 ========== + mapUnifiedToPlatformSubscription(data: Partial) { + return data; + } + + mapPlatformToUnifiedSubscription(item: WooSubscription): UnifiedSubscriptionDTO { + // 将 WooCommerce 订阅数据映射为统一订阅DTO + // 若缺少创建时间则回退为开始时间 + return { + id: item.id, + status: item.status, + customer_id: item.customer_id, + billing_period: item.billing_period, + billing_interval: item.billing_interval, + date_created: item.date_created ?? item.start_date, + date_modified: item.date_modified, + start_date: item.start_date, + next_payment_date: item.next_payment_date, + line_items: item.line_items, + raw: item, + }; + } + + // 订阅操作方法 + async getSubscriptions(params: UnifiedSearchParamsDTO): Promise> { + // 获取订阅列表并映射为统一订阅DTO集合 + const { items, total, totalPages, page, per_page } = await this.wpService.fetchResourcePaged( + this.site, + 'subscriptions', + params + ); + return { + items: items.map(this.mapPlatformToUnifiedSubscription), + total, + totalPages, + page, + per_page, + + }; + } + + async getAllSubscriptions(params?: UnifiedSearchParamsDTO): Promise { + // 使用sdkGetAll获取所有订阅数据,不受分页限制 + const api = this.wpService.createApi(this.site, 'wc/v3'); + const subscriptions = await this.wpService.sdkGetAll(api, 'subscriptions', params); + return subscriptions.map((subscription: any) => this.mapPlatformToUnifiedSubscription(subscription)); + } + + // ========== 变体映射方法 ========== + mapPlatformToUnifiedVariation(data: any): UnifiedProductVariationDTO { + // 使用mapVariation方法来实现统一的变体映射逻辑 + return this.mapVariation(data); + } + mapUnifiedToPlatformVariation(data: Partial) { + return data; + } + // 映射 WooCommerce 变体到统一格式 mapVariation(variation: any, productName?: string): UnifiedProductVariationDTO { // 将变体属性转换为统一格式 @@ -1119,6 +1208,7 @@ export class WooCommerceAdapter implements ISiteAdapter { }; } + // 变体操作方法 // 获取产品变体列表 async getVariations(productId: string | number, params: UnifiedSearchParamsDTO): Promise { try { @@ -1145,7 +1235,7 @@ export class WooCommerceAdapter implements ISiteAdapter { // 获取所有产品变体 async getAllVariations(productId: string | number, params?: UnifiedSearchParamsDTO): Promise { try { - const api = (this.wpService as any).createApi(this.site, 'wc/v3'); + const api = this.wpService.createApi(this.site, 'wc/v3'); const variations = await this.wpService.sdkGetAll(api, `products/${productId}/variations`, params); // 获取产品名称用于变体显示 @@ -1293,5 +1383,142 @@ export class WooCommerceAdapter implements ISiteAdapter { throw new Error(`删除产品变体失败: ${error instanceof Error ? error.message : String(error)}`); } } -} + // ========== 网络钩子映射方法 ========== + mapUnifiedToPlatformWebhook(data: Partial) { + return data; + } + + mapCreateWebhookParams(data: CreateWebhookDTO) { + return data; + } + mapUpdateWebhookParams(data: UpdateWebhookDTO) { + return data; + } + + // 映射 WooCommerce webhook 到统一格式 + mapPlatformToUnifiedWebhook(webhook: WooWebhook): UnifiedWebhookDTO { + return { + id: webhook.id.toString(), + name: webhook.name, + status: webhook.status, + topic: webhook.topic, + delivery_url: webhook.delivery_url, + secret: webhook.secret, + api_version: webhook.api_version, + date_created: webhook.date_created, + date_modified: webhook.date_modified, + // metadata: webhook.meta_data || [], + }; + } + + // 网络钩子操作方法 + // 获取站点的 webhooks 列表 + async getWebhooks(params: UnifiedSearchParamsDTO): Promise { + try { + const result = await this.wpService.getWebhooks(this.site, params); + + return { + items: (result.items as WooWebhook[]).map(this.mapPlatformToUnifiedWebhook), + total: result.total, + page: Number(params.page || 1), + per_page: Number(params.per_page || 20), + totalPages: result.totalPages, + }; + } catch (error) { + throw new Error(`Failed to get webhooks: ${error instanceof Error ? error.message : String(error)}`); + } + } + + // 获取所有webhooks + async getAllWebhooks(params?: UnifiedSearchParamsDTO): Promise { + try { + const api = this.wpService.createApi(this.site, 'wc/v3'); + const webhooks = await this.wpService.sdkGetAll(api, 'webhooks', params); + return webhooks.map((webhook: any) => this.mapPlatformToUnifiedWebhook(webhook)); + } catch (error) { + throw new Error(`Failed to get all webhooks: ${error instanceof Error ? error.message : String(error)}`); + } + } + + // 获取单个 webhook 详情 + async getWebhook(where: {id: string | number}): Promise { + try { + const result = await this.wpService.getWebhook(this.site, where.id); + return this.mapPlatformToUnifiedWebhook(result as WooWebhook); + } catch (error) { + throw new Error(`Failed to get webhook: ${error instanceof Error ? error.message : String(error)}`); + } + } + + // 创建新的 webhook + async createWebhook(data: CreateWebhookDTO): Promise { + try { + const params = { + name: data.name, + status: 'active', // 默认状态为活跃 + topic: data.topic, + delivery_url: data.delivery_url, + secret: data.secret, + api_version: data.api_version || 'wp/v2', + }; + const result = await this.wpService.createWebhook(this.site, params); + return this.mapPlatformToUnifiedWebhook(result as WooWebhook); + } catch (error) { + throw new Error(`Failed to create webhook: ${error instanceof Error ? error.message : String(error)}`); + } + } + + // 更新现有的 webhook + async updateWebhook(where: Partial>, data: UpdateWebhookDTO): Promise { + try { + const params = { + ...(data.name ? { name: data.name } : {}), + ...(data.status ? { status: data.status } : {}), + ...(data.topic ? { topic: data.topic } : {}), + ...(data.delivery_url ? { delivery_url: data.delivery_url } : {}), + ...(data.secret ? { secret: data.secret } : {}), + ...(data.api_version ? { api_version: data.api_version } : {}), + }; + const result = await this.wpService.updateWebhook(this.site, where.id, params); + return this.mapPlatformToUnifiedWebhook(result as WooWebhook); + } catch (error) { + throw new Error(`Failed to update webhook: ${error instanceof Error ? error.message : String(error)}`); + } + } + + // 删除指定的 webhook + async deleteWebhook(where: Partial>): Promise { + try { + await this.wpService.deleteWebhook(this.site, where.id); + return true; + } catch (error) { + throw new Error(`Failed to delete webhook: ${error instanceof Error ? error.message : String(error)}`); + } + } + + // ========== 其他方法 ========== + async getLinks(): Promise> { + const baseUrl = this.site.apiUrl; + const links = [ + { title: '访问网站', url: baseUrl }, + { title: '管理后台', url: `${baseUrl}/wp-admin/` }, + { title: '订单管理', url: `${baseUrl}/wp-admin/edit.php?post_type=shop_order` }, + { title: '产品管理', url: `${baseUrl}/wp-admin/edit.php?post_type=product` }, + { title: '客户管理', url: `${baseUrl}/wp-admin/users.php` }, + { title: '插件管理', url: `${baseUrl}/wp-admin/plugins.php` }, + { title: '主题管理', url: `${baseUrl}/wp-admin/themes.php` }, + { title: 'WooCommerce设置', url: `${baseUrl}/wp-admin/admin.php?page=wc-settings` }, + { title: 'WooCommerce报告', url: `${baseUrl}/wp-admin/admin.php?page=wc-reports` }, + ]; + return links; + } + + batchProcessOrders?(data: BatchOperationDTO): Promise { + throw new Error('Method not implemented.'); + } + + batchProcessCustomers?(data: BatchOperationDTO): Promise { + throw new Error('Method not implemented.'); + } +} diff --git a/src/controller/media.controller.ts b/src/controller/media.controller.ts deleted file mode 100644 index cafd85f..0000000 --- a/src/controller/media.controller.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Controller, Get, Inject, Query, Post, Del, Param, Files, Fields, Body } from '@midwayjs/core'; -import { WPService } from '../service/wp.service'; -import { successResponse, errorResponse } from '../utils/response.util'; - -@Controller('/media') -export class MediaController { - @Inject() - wpService: WPService; - - @Get('/list') - async list( - @Query('siteId') siteId: number, - @Query('page') page: number = 1, - @Query('pageSize') pageSize: number = 20 - ) { - try { - if (!siteId) { - return errorResponse('siteId is required'); - } - const result = await this.wpService.getMedia(siteId, page, pageSize); - return successResponse(result); - } catch (error) { - return errorResponse(error.message); - } - } - - @Post('/upload') - async upload(@Fields() fields, @Files() files) { - try { - const siteId = fields.siteId; - if (!siteId) { - return errorResponse('siteId is required'); - } - if (!files || files.length === 0) { - return errorResponse('file is required'); - } - const file = files[0]; - const result = await this.wpService.createMedia(siteId, file); - return successResponse(result); - } catch (error) { - return errorResponse(error.message); - } - } - - @Post('/update/:id') - async update(@Param('id') id: number, @Body() body) { - try { - const siteId = body.siteId; - if (!siteId) { - return errorResponse('siteId is required'); - } - // 过滤出需要更新的字段 - const { title, caption, description, alt_text } = body; - const data: any = {}; - if (title !== undefined) data.title = title; - if (caption !== undefined) data.caption = caption; - if (description !== undefined) data.description = description; - if (alt_text !== undefined) data.alt_text = alt_text; - - const result = await this.wpService.updateMedia(siteId, id, data); - return successResponse(result); - } catch (error) { - return errorResponse(error.message); - } - } - - @Del('/:id') - async delete(@Param('id') id: number, @Query('siteId') siteId: number, @Query('force') force: boolean = true) { - try { - if (!siteId) { - return errorResponse('siteId is required'); - } - const result = await this.wpService.deleteMedia(siteId, id, force); - return successResponse(result); - } catch (error) { - return errorResponse(error.message); - } - } -} diff --git a/src/controller/product.controller.ts b/src/controller/product.controller.ts index aef81f8..c263d16 100644 --- a/src/controller/product.controller.ts +++ b/src/controller/product.controller.ts @@ -698,10 +698,10 @@ export class ProductController { // 从站点同步产品到本地 @ApiOkResponse({ description: '从站点同步产品到本地', type: ProductRes }) @Post('/sync-from-site') - async syncProductFromSite(@Body() body: { siteId: number; siteProductId: string | number }) { + async syncProductFromSite(@Body() body: { siteId: number; siteProductId: string | number ,sku: string}) { try { - const { siteId, siteProductId } = body; - const product = await this.productService.syncProductFromSite(siteId, siteProductId); + const { siteId, siteProductId, sku } = body; + const product = await this.productService.syncProductFromSite(siteId, siteProductId, sku); return successResponse(product); } catch (error) { return errorResponse(error?.message || error); @@ -713,25 +713,26 @@ export class ProductController { @Post('/batch-sync-from-site') async batchSyncFromSite(@Body() body: { siteId: number; siteProductIds: (string | number)[] }) { try { - const { siteId, siteProductIds } = body; - const result = await this.productService.batchSyncFromSite(siteId, siteProductIds); - // 将服务层返回的结果转换为统一格式 - const errors = result.errors.map((error: string) => { - // 提取产品ID部分作为标识符 - const match = error.match(/站点产品ID (\d+) /); - const identifier = match ? match[1] : 'unknown'; - return { - identifier: identifier, - error: error - }; - }); + throw new Error('批量同步产品到本地暂未实现'); + // const { siteId, siteProductIds } = body; + // const result = await this.productService.batchSyncFromSite(siteId, siteProductIds.map((id) => ({ siteProductId: id, sku: '' }))); + // // 将服务层返回的结果转换为统一格式 + // const errors = result.errors.map((error: string) => { + // // 提取产品ID部分作为标识符 + // const match = error.match(/站点产品ID (\d+) /); + // const identifier = match ? match[1] : 'unknown'; + // return { + // identifier: identifier, + // error: error + // }; + // }); - return successResponse({ - total: siteProductIds.length, - processed: result.synced + errors.length, - synced: result.synced, - errors: errors - }); + // return successResponse({ + // total: siteProductIds.length, + // processed: result.synced + errors.length, + // synced: result.synced, + // errors: errors + // }); } catch (error) { return errorResponse(error?.message || error); } diff --git a/src/controller/site-api.controller.ts b/src/controller/site-api.controller.ts index 9f69b87..00d8285 100644 --- a/src/controller/site-api.controller.ts +++ b/src/controller/site-api.controller.ts @@ -7,7 +7,6 @@ import { CancelFulfillmentDTO, CreateReviewDTO, CreateWebhookDTO, - FulfillmentDTO, UnifiedCustomerDTO, UnifiedCustomerPaginationDTO, UnifiedMediaPaginationDTO, @@ -106,7 +105,7 @@ export class SiteApiController { this.logger.debug(`[Site API] 更新评论开始, siteId: ${siteId}, id: ${id}, body: ${JSON.stringify(body)}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.updateReview(id, body); + const data = await adapter.updateReview({ id }, body); this.logger.debug(`[Site API] 更新评论成功, siteId: ${siteId}, id: ${id}`); return successResponse(data); } catch (error) { @@ -124,7 +123,7 @@ export class SiteApiController { this.logger.debug(`[Site API] 删除评论开始, siteId: ${siteId}, id: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.deleteReview(id); + const data = await adapter.deleteReview({ id }); this.logger.debug(`[Site API] 删除评论成功, siteId: ${siteId}, id: ${id}`); return successResponse(data); } catch (error) { @@ -160,7 +159,7 @@ export class SiteApiController { this.logger.debug(`[Site API] 获取单个webhook开始, siteId: ${siteId}, id: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.getWebhook(id); + const data = await adapter.getWebhook({ id }); this.logger.debug(`[Site API] 获取单个webhook成功, siteId: ${siteId}, id: ${id}`); return successResponse(data); } catch (error) { @@ -199,7 +198,7 @@ export class SiteApiController { this.logger.debug(`[Site API] 更新webhook开始, siteId: ${siteId}, id: ${id}, body: ${JSON.stringify(body)}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.updateWebhook(id, body); + const data = await adapter.updateWebhook({ id }, body); this.logger.debug(`[Site API] 更新webhook成功, siteId: ${siteId}, id: ${id}`); return successResponse(data); } catch (error) { @@ -217,7 +216,7 @@ export class SiteApiController { this.logger.debug(`[Site API] 删除webhook开始, siteId: ${siteId}, id: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.deleteWebhook(id); + const data = await adapter.deleteWebhook({ id }); this.logger.debug(`[Site API] 删除webhook成功, siteId: ${siteId}, id: ${id}`); return successResponse(data); } catch (error) { @@ -327,7 +326,7 @@ export class SiteApiController { if (site.type === 'woocommerce') { const page = query.page || 1; const perPage = (query.per_page) || 100; - const res = await this.siteApiService.wpService.getProducts(site, page, perPage); + const res = await this.siteApiService.wpService.getProducts(site, { page, per_page: perPage }); const header = ['id', 'name', 'type', 'status', 'sku', 'regular_price', 'sale_price', 'stock_status', 'stock_quantity']; const rows = (res.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 toCsvValue = (val: any) => { @@ -360,7 +359,7 @@ export class SiteApiController { this.logger.info(`[Site API] 获取单个产品开始, siteId: ${siteId}, productId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.getProduct(id); + const data = await adapter.getProduct({ id }); // 如果获取到商品数据,则增强ERP产品信息 if (data) { @@ -485,7 +484,7 @@ export class SiteApiController { this.logger.info(`[Site API] 更新产品开始, siteId: ${siteId}, productId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.updateProduct(id, body); + const data = await adapter.updateProduct({ id }, body); this.logger.info(`[Site API] 更新产品成功, siteId: ${siteId}, productId: ${id}`); return successResponse(data); } catch (error) { @@ -540,7 +539,7 @@ export class SiteApiController { this.logger.info(`[Site API] 删除产品开始, siteId: ${siteId}, productId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const success = await adapter.deleteProduct(id); + const success = await adapter.deleteProduct({ id }); this.logger.info(`[Site API] 删除产品成功, siteId: ${siteId}, productId: ${id}`); return successResponse(success); } catch (error) { @@ -585,7 +584,7 @@ export class SiteApiController { for (const item of body.update) { try { const id = item.id; - const data = await adapter.updateProduct(id, item); + const data = await adapter.updateProduct({ id }, item); updated.push(data); } catch (e) { errors.push({ @@ -598,7 +597,7 @@ export class SiteApiController { if (body.delete?.length) { for (const id of body.delete) { try { - const ok = await adapter.deleteProduct(id); + const ok = await adapter.deleteProduct({ id }); if (ok) deleted.push(id); else errors.push({ identifier: String(id), @@ -672,6 +671,26 @@ export class SiteApiController { } } + @Get('/:siteId/orders/count') + @ApiOkResponse({ type: Object }) + async countOrders( + @Param('siteId') siteId: number, + @Query() query: any + ) { + this.logger.info(`[Site API] 获取订单总数开始, siteId: ${siteId}`); + try { + + + const adapter = await this.siteApiService.getAdapter(siteId); + const total = await adapter.countOrders(query); + this.logger.info(`[Site API] 获取订单总数成功, siteId: ${siteId}, total: ${total}`); + return successResponse({ total }); + } catch (error) { + this.logger.error(`[Site API] 获取订单总数失败, siteId: ${siteId}, 错误信息: ${error.message}`); + return errorResponse(error.message); + } + } + @Get('/:siteId/customers/:customerId/orders') @ApiOkResponse({ type: UnifiedOrderPaginationDTO }) async getCustomerOrders( @@ -752,7 +771,7 @@ export class SiteApiController { this.logger.info(`[Site API] 获取单个订单开始, siteId: ${siteId}, orderId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.getOrder(id); + const data = await adapter.getOrder({ id }); this.logger.info(`[Site API] 获取单个订单成功, siteId: ${siteId}, orderId: ${id}`); return successResponse(data); } catch (error) { @@ -824,7 +843,7 @@ export class SiteApiController { this.logger.info(`[Site API] 更新订单开始, siteId: ${siteId}, orderId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const ok = await adapter.updateOrder(id, body); + const ok = await adapter.updateOrder({ id }, body); this.logger.info(`[Site API] 更新订单成功, siteId: ${siteId}, orderId: ${id}`); return successResponse(ok); } catch (error) { @@ -842,7 +861,7 @@ export class SiteApiController { this.logger.info(`[Site API] 删除订单开始, siteId: ${siteId}, orderId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const ok = await adapter.deleteOrder(id); + const ok = await adapter.deleteOrder({ id }); this.logger.info(`[Site API] 删除订单成功, siteId: ${siteId}, orderId: ${id}`); return successResponse(ok); } catch (error) { @@ -882,7 +901,7 @@ export class SiteApiController { for (const item of body.update) { try { const id = item.id; - const ok = await adapter.updateOrder(id, item); + const ok = await adapter.updateOrder({ id }, item); if (ok) updated.push(item); else errors.push({ identifier: String(item.id || 'unknown'), @@ -899,7 +918,7 @@ export class SiteApiController { if (body.delete?.length) { for (const id of body.delete) { try { - const ok = await adapter.deleteOrder(id); + const ok = await adapter.deleteOrder({ id }); if (ok) deleted.push(id); else errors.push({ identifier: String(id), @@ -966,25 +985,6 @@ export class SiteApiController { } } - @Post('/:siteId/orders/:id/fulfill') - @ApiOkResponse({ type: Object }) - async fulfillOrder( - @Param('siteId') siteId: number, - @Param('id') id: string, - @Body() body: FulfillmentDTO - ) { - this.logger.info(`[Site API] 订单履约开始, siteId: ${siteId}, orderId: ${id}`); - try { - const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.fulfillOrder(id, body); - this.logger.info(`[Site API] 订单履约成功, siteId: ${siteId}, orderId: ${id}`); - return successResponse(data); - } catch (error) { - this.logger.error(`[Site API] 订单履约失败, siteId: ${siteId}, orderId: ${id}, 错误信息: ${error.message}`); - return errorResponse(error.message); - } - } - @Post('/:siteId/orders/:id/cancel-fulfill') @ApiOkResponse({ type: Object }) async cancelFulfillment( @@ -1050,13 +1050,13 @@ export class SiteApiController { } } - @Get('/:siteId/orders/:orderId/trackings') + @Get('/:siteId/orders/:orderId/fulfillments') @ApiOkResponse({ type: Object }) - async getOrderTrackings( + async getOrderFulfillments( @Param('siteId') siteId: number, @Param('orderId') orderId: string ) { - this.logger.info(`[Site API] 获取订单物流跟踪信息开始, siteId: ${siteId}, orderId: ${orderId}`); + this.logger.info(`[Site API] 获取订单履约信息开始, siteId: ${siteId}, orderId: ${orderId}`); try { const adapter = await this.siteApiService.getAdapter(siteId); const data = await adapter.getOrderFulfillments(orderId); @@ -1435,7 +1435,7 @@ export class SiteApiController { this.logger.info(`[Site API] 获取单个客户开始, siteId: ${siteId}, customerId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.getCustomer(id); + const data = await adapter.getCustomer({ id }); this.logger.info(`[Site API] 获取单个客户成功, siteId: ${siteId}, customerId: ${id}`); return successResponse(data); } catch (error) { @@ -1507,7 +1507,7 @@ export class SiteApiController { this.logger.info(`[Site API] 更新客户开始, siteId: ${siteId}, customerId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const data = await adapter.updateCustomer(id, body); + const data = await adapter.updateCustomer({ id }, body); this.logger.info(`[Site API] 更新客户成功, siteId: ${siteId}, customerId: ${id}`); return successResponse(data); } catch (error) { @@ -1525,7 +1525,7 @@ export class SiteApiController { this.logger.info(`[Site API] 删除客户开始, siteId: ${siteId}, customerId: ${id}`); try { const adapter = await this.siteApiService.getAdapter(siteId); - const success = await adapter.deleteCustomer(id); + const success = await adapter.deleteCustomer({ id }); this.logger.info(`[Site API] 删除客户成功, siteId: ${siteId}, customerId: ${id}`); return successResponse(success); } catch (error) { @@ -1561,7 +1561,7 @@ export class SiteApiController { for (const item of body.update) { try { const id = item.id; - const data = await adapter.updateCustomer(id, item); + const data = await adapter.updateCustomer({ id }, item); updated.push(data); } catch (e) { failed.push({ action: 'update', item, error: (e as any).message }); @@ -1571,7 +1571,7 @@ export class SiteApiController { if (body.delete?.length) { for (const id of body.delete) { try { - const ok = await adapter.deleteCustomer(id); + const ok = await adapter.deleteCustomer({ id }); if (ok) deleted.push(id); else failed.push({ action: 'delete', id, error: 'delete failed' }); } catch (e) { diff --git a/src/controller/webhook.controller.ts b/src/controller/webhook.controller.ts index 37fcc5a..41ef422 100644 --- a/src/controller/webhook.controller.ts +++ b/src/controller/webhook.controller.ts @@ -9,10 +9,13 @@ import { } from '@midwayjs/decorator'; import { Context } from '@midwayjs/koa'; import * as crypto from 'crypto'; - + import { SiteService } from '../service/site.service'; import { OrderService } from '../service/order.service'; -import { SiteApiService } from '../service/site-api.service'; + +import { + UnifiedOrderDTO, +} from '../dto/site-api.dto'; @Controller('/webhook') export class WebhookController { @@ -28,11 +31,9 @@ export class WebhookController { @Logger() logger: ILogger; - + @Inject() private readonly siteService: SiteService; - @Inject() - private readonly siteApiService: SiteApiService; // 移除配置中的站点数组,来源统一改为数据库 @@ -48,7 +49,7 @@ export class WebhookController { @Query('siteId') siteIdStr: string, @Headers() header: any ) { - console.log(`webhook woocommerce`, siteIdStr, body, header) + console.log(`webhook woocommerce`, siteIdStr, body,header) const signature = header['x-wc-webhook-signature']; const topic = header['x-wc-webhook-topic']; const source = header['x-wc-webhook-source']; @@ -78,44 +79,43 @@ export class WebhookController { .update(rawBody) .digest('base64'); try { - if (hash !== signature) { + if (hash === signature) { + switch (topic) { + case 'product.created': + case 'product.updated': + // 不再写入本地,平台事件仅确认接收 + break; + case 'product.deleted': + // 不再写入本地,平台事件仅确认接收 + break; + case 'order.created': + case 'order.updated': + await this.orderService.syncSingleOrder(siteId, body); + break; + case 'order.deleted': + break; + case 'customer.created': + break; + case 'customer.updated': + break; + case 'customer.deleted': + break; + default: + console.log('Unhandled event:', body.event); + } + + return { + code: 200, + success: true, + message: 'Webhook processed successfully', + }; + } else { return { code: 403, success: false, message: 'Webhook verification failed', }; } - const adapter = await this.siteApiService.getAdapter(siteId); - switch (topic) { - case 'product.created': - case 'product.updated': - // 不再写入本地,平台事件仅确认接收 - break; - case 'product.deleted': - // 不再写入本地,平台事件仅确认接收 - break; - case 'order.created': - case 'order.updated': - const order = adapter.mapOrder(body) - await this.orderService.syncSingleOrder(siteId, order); - break; - case 'order.deleted': - break; - case 'customer.created': - break; - case 'customer.updated': - break; - case 'customer.deleted': - break; - default: - console.log('Unhandled event:', body.event); - - return { - code: 200, - success: true, - message: 'Webhook processed successfully', - }; - } } catch (error) { console.log(error); } @@ -130,10 +130,23 @@ export class WebhookController { @Query('signature') signature: string, @Headers() header: any ) { - console.log(`webhook shoppy`, siteIdStr, body, header) const topic = header['x-oemsaas-event-type']; - // const source = header['x-oemsaas-shop-domain']; + // const source = header['x-oemsaas-shop-domain']; const siteId = Number(siteIdStr); + const bodys = new UnifiedOrderDTO(); + Object.assign(bodys, body); + // 从数据库获取站点配置 + const site = await this.siteService.get(siteId, true); + + // if (!site || !source?.includes(site.websiteUrl)) { + if (!site) { + console.log('domain not match'); + return { + code: HttpStatus.BAD_REQUEST, + success: false, + message: 'domain not match', + }; + } if (!signature) { return { @@ -149,7 +162,6 @@ export class WebhookController { // .createHmac('sha256', this.secret) // .update(rawBody) // .digest('base64'); - const adapter = await this.siteApiService.getAdapter(siteId); try { if (this.secret === signature) { switch (topic) { @@ -162,8 +174,7 @@ export class WebhookController { break; case 'orders/create': case 'orders/update': - const order = adapter.mapOrder(body) - await this.orderService.syncSingleOrder(siteId, order); + await this.orderService.syncSingleOrder(siteId, bodys); break; case 'orders/delete': break; diff --git a/src/db/seeds/template.seeder.ts b/src/db/seeds/template.seeder.ts index f12a208..c531f73 100644 --- a/src/db/seeds/template.seeder.ts +++ b/src/db/seeds/template.seeder.ts @@ -23,19 +23,38 @@ export default class TemplateSeeder implements Seeder { const templates = [ { name: 'product.sku', - value: "<%= [it.category.shortName].concat(it.attributes.map(a => a.shortName)).join('-') %>", + value: `<% + // 按分类判断属性排序逻辑 + if (it.category.name === 'nicotine-pouches') { + // 1. 定义 nicotine-pouches 专属的属性固定顺序 + const fixedOrder = ['brand','category', 'flavor', 'strength', 'humidity']; + sortedAttrShortNames = fixedOrder.map(attrKey => { + if(attrKey === 'category') return it.category.shortName + // 排序 + const matchedAttr = it.attributes.find(a => a?.dict?.name === attrKey); + return matchedAttr ? matchedAttr.shortName : ''; + }).filter(Boolean); // 移除空值,避免多余的 "-" + } else { + // 非目标分类,保留 attributes 原有顺序 + sortedAttrShortNames = it.attributes.map(a => a.shortName); + } + + // 4. 拼接分类名 + 排序后的属性名 + %><%= sortedAttrShortNames.join('-') %><% +%>`, description: '产品SKU模板', testData: JSON.stringify({ - category: { - shortName: 'CAT', + "category": { + "name": "nicotine-pouches", + "shortName": "NP" }, - attributes: [ - { shortName: 'BR' }, - { shortName: 'FL' }, - { shortName: '10MG' }, - { shortName: 'DRY' }, - ], - }), + "attributes": [ + { "dict": {"name": "brand"},"shortName": "YOONE" }, + { "dict": {"name": "flavor"},"shortName": "FL" }, + { "dict": {"name": "strength"},"shortName": "10MG" }, + { "dict": {"name": "humidity"},"shortName": "DRY" } + ] +}), }, { name: 'product.title', diff --git a/src/dto/shopyy.dto.ts b/src/dto/shopyy.dto.ts index 2bcbca7..009d6ce 100644 --- a/src/dto/shopyy.dto.ts +++ b/src/dto/shopyy.dto.ts @@ -4,6 +4,53 @@ export interface ShopyyTag { id?: number; name?: string; } +export interface ShopyyProductQuery { + page: string; + limit: string; +} +/** + * Shopyy 全量商品查询参数类 + * 用于封装获取 Shopyy 商品列表时的各种筛选和分页条件 + * 参考文档: https://www.apizza.net/project/e114fb8e628e0f604379f5b26f0d8330/browse + */ +export class ShopyyAllProductQuery { + /** 分页大小,限制返回的商品数量 */ + limit?: string; + /** 起始ID,用于分页,返回ID大于该值的商品 */ + since_id?: string; + /** 商品ID,精确匹配单个商品 */ + id?: string; + /** 商品标题,支持模糊查询 */ + title?: string; + /** 商品状态,例如:上架、下架、删除等(具体值参考 Shopyy 接口文档) */ + status?: string; + /** 商品SKU编码,库存保有单位,精确或模糊匹配 */ + sku?: string; + /** 商品SPU编码,标准化产品单元,用于归类同款商品 */ + spu?: string; + /** 商品分类ID,筛选指定分类下的商品 */ + collection_id?: string; + /** 变体价格最小值,筛选变体价格大于等于该值的商品 */ + variant_price_min?: string; + /** 变体价格最大值,筛选变体价格小于等于该值的商品 */ + variant_price_max?: string; + /** 变体划线价(原价)最小值,筛选变体划线价大于等于该值的商品 */ + variant_compare_at_price_min?: string; + /** 变体划线价(原价)最大值,筛选变体划线价小于等于该值的商品 */ + variant_compare_at_price_max?: string; + /** 变体重量最小值,筛选变体重量大于等于该值的商品(单位参考接口文档) */ + variant_weight_min?: string; + /** 变体重量最大值,筛选变体重量小于等于该值的商品(单位参考接口文档) */ + variant_weight_max?: string; + /** 商品创建时间最小值,格式参考接口文档(如:YYYY-MM-DD HH:mm:ss) */ + created_at_min?: string; + /** 商品创建时间最大值,格式参考接口文档(如:YYYY-MM-DD HH:mm:ss) */ + created_at_max?: string; + /** 商品更新时间最小值,格式参考接口文档(如:YYYY-MM-DD HH:mm:ss) */ + updated_at_min?: string; + /** 商品更新时间最大值,格式参考接口文档(如:YYYY-MM-DD HH:mm:ss) */ + updated_at_max?: string; +} // 产品类型 export interface ShopyyProduct { // 产品主键 @@ -83,6 +130,42 @@ export interface ShopyyVariant { position?: number | string; sku_code?: string; } +// +// 订单查询参数类型 +export interface ShopyyOrderQuery { + // 订单ID集合 多个ID用','联接 例:1,2,3 + ids?: string; + // 订单状态 100 未完成;110 待处理;180 已完成(确认收货); 190 取消; + status?: string; + // 物流状态 300 未发货;310 部分发货;320 已发货;330(确认收货) + fulfillment_status?: string; + // 支付状态 200 待支付;210 支付中;220 部分支付;230 已支付;240 支付失败;250 部分退款;260 已退款 ;290 已取消; + financial_status?: string; + // 支付时间 下限值 + pay_at_min?: string; + // 支付时间 上限值 + pay_at_max?: string; + // 创建开始时间 + created_at_min?: number; + // 创建结束时间 + created_at_max?: number; + // 更新时间开始 + updated_at_min?: string; + // 更新时间结束 + updated_at_max?: string; + // 起始ID + since_id?: string; + // 页码 + page?: string; + // 每页条数 + limit?: string; + // 排序字段(默认id) id=订单ID updated_at=最后更新时间 pay_at=支付时间 + order_field?: string; + // 排序方式(默认desc) desc=降序 asc=升序 + order_by?: string; + // 订单列表类型 + group?: string; +} // 订单类型 export interface ShopyyOrder { @@ -209,17 +292,18 @@ export interface ShopyyOrder { // 物流回传时间 payment_tracking_at?: number; // 商品 - products?: Array<{ + products?: Array<{ // 订单商品表 id - order_product_id?: number; + order_product_id?: number; // 数量 - quantity?: number; + quantity?: number; // 更新时间 - updated_at?: number; + updated_at?: number; // 创建时间 created_at?: number; // 发货商品表 id - id?: number }>; + id?: number + }>; }>; shipping_zone_plans?: Array<{ shipping_price?: number | string; diff --git a/src/dto/site-api.dto.ts b/src/dto/site-api.dto.ts index a93f125..faee539 100644 --- a/src/dto/site-api.dto.ts +++ b/src/dto/site-api.dto.ts @@ -2,6 +2,7 @@ import { ApiProperty } from '@midwayjs/swagger'; import { UnifiedPaginationDTO, } from './api.dto'; +import { Dict } from '../entity/dict.entity'; // export class UnifiedOrderWhere{ // [] // } @@ -17,6 +18,11 @@ export enum OrderFulfillmentStatus { // 确认发货 CONFIRMED, } +// +export class UnifiedProductWhere { + sku?: string; + [prop:string]:any +} export class UnifiedTagDTO { // 标签DTO用于承载统一标签数据 @ApiProperty({ description: '标签ID' }) @@ -137,6 +143,8 @@ export class UnifiedProductAttributeDTO { @ApiProperty({ description: '变体属性值(单个值)', required: false }) option?: string; + // 这个是属性的父级字典项 + dict?: Dict; } export class UnifiedProductVariationDTO { diff --git a/src/dto/woocommerce.dto.ts b/src/dto/woocommerce.dto.ts index 3150a78..f562d64 100644 --- a/src/dto/woocommerce.dto.ts +++ b/src/dto/woocommerce.dto.ts @@ -117,9 +117,9 @@ export interface WooProduct { // 购买备注 purchase_note?: string; // 分类列表 - categories?: Array<{ id: number; name?: string; slug?: string }>; + categories?: Array<{ id?: number; name?: string; slug?: string }>; // 标签列表 - tags?: Array<{ id: number; name?: string; slug?: string }>; + tags?: Array<{ id?: number; name?: string; slug?: string }>; // 菜单排序 menu_order?: number; // 元数据 diff --git a/src/entity/dict.entity.ts b/src/entity/dict.entity.ts index dc0d9af..15776da 100644 --- a/src/entity/dict.entity.ts +++ b/src/entity/dict.entity.ts @@ -29,6 +29,10 @@ export class Dict { @OneToMany(() => DictItem, item => item.dict) items: DictItem[]; + // 排序 + @Column({ default: 0, comment: '排序' }) + sort: number; + // 是否可删除 @Column({ default: true, comment: '是否可删除' }) deletable: boolean; diff --git a/src/entity/product.entity.ts b/src/entity/product.entity.ts index ea763ec..1d7b296 100644 --- a/src/entity/product.entity.ts +++ b/src/entity/product.entity.ts @@ -65,9 +65,6 @@ export class Product { @Column({ type: 'decimal', precision: 10, scale: 2, default: 0 }) promotionPrice: number; - - - // 分类关联 @ManyToOne(() => Category, category => category.products) @JoinColumn({ name: 'categoryId' }) diff --git a/src/interface/site-adapter.interface.ts b/src/interface/site-adapter.interface.ts index 9baf0c7..f290517 100644 --- a/src/interface/site-adapter.interface.ts +++ b/src/interface/site-adapter.interface.ts @@ -20,51 +20,70 @@ import { UnifiedPaginationDTO, UnifiedSearchParamsDTO } from '../dto/api.dto'; import { BatchOperationDTO, BatchOperationResultDTO } from '../dto/batch.dto'; export interface ISiteAdapter { - mapOrder(order: any): UnifiedOrderDTO; - mapWebhook(webhook:any):UnifiedWebhookDTO; - mapProduct(product:any): UnifiedProductDTO; - mapReview(data: any): UnifiedReviewDTO; - mapCustomer(data: any): UnifiedCustomerDTO; - mapMedia(data: any): UnifiedMediaDTO; + // ========== 客户映射方法 ========== /** - * 获取产品列表 + * 将平台客户数据转换为统一客户数据格式 + * @param data 平台特定客户数据 + * @returns 统一客户数据格式 */ - getProducts(params: UnifiedSearchParamsDTO): Promise>; + mapPlatformToUnifiedCustomer(data: any): UnifiedCustomerDTO; /** - * 获取所有产品 + * 将统一客户数据格式转换为平台客户数据 + * @param data 统一客户数据格式 + * @returns 平台特定客户数据 */ - getAllProducts(params?: UnifiedSearchParamsDTO): Promise; + mapUnifiedToPlatformCustomer(data: Partial): any; /** - * 获取单个产品 + * 获取单个客户 */ - getProduct(id: string | number): Promise; + getCustomer(where: Partial>): Promise; /** - * 获取订单列表 + * 获取客户列表 */ - getOrders(params: UnifiedSearchParamsDTO): Promise>; + getCustomers(params: UnifiedSearchParamsDTO): Promise>; /** - * 获取所有订单 + * 获取所有客户 */ - getAllOrders(params?: UnifiedSearchParamsDTO): Promise; + getAllCustomers(params?: UnifiedSearchParamsDTO): Promise; /** - * 获取单个订单 + * 创建客户 */ - getOrder(id: string | number): Promise; + createCustomer(data: Partial): Promise; /** - * 获取订阅列表 + * 更新客户 */ - getSubscriptions(params: UnifiedSearchParamsDTO): Promise>; + updateCustomer(where: Partial>, data: Partial): Promise; /** - * 获取所有订阅 + * 删除客户 */ - getAllSubscriptions(params?: UnifiedSearchParamsDTO): Promise; + deleteCustomer(where: Partial>): Promise; + + /** + * 批量处理客户 + */ + batchProcessCustomers?(data: BatchOperationDTO): Promise; + + // ========== 媒体映射方法 ========== + /** + * 将平台媒体数据转换为统一媒体数据格式 + * @param data 平台特定媒体数据 + * @returns 统一媒体数据格式 + */ + mapPlatformToUnifiedMedia(data: any): UnifiedMediaDTO; + + /** + * 将统一媒体数据格式转换为平台媒体数据 + * @param data 统一媒体数据格式 + * @returns 平台特定媒体数据 + */ + mapUnifiedToPlatformMedia(data: Partial): any; /** * 获取媒体列表 @@ -81,75 +100,69 @@ export interface ISiteAdapter { */ createMedia(file: any): Promise; + // ========== 订单映射方法 ========== /** - * 获取评论列表 + * 将平台订单数据转换为统一订单数据格式 + * @param data 平台特定订单数据 + * @returns 统一订单数据格式 */ - getReviews(params: UnifiedSearchParamsDTO): Promise>; + mapPlatformToUnifiedOrder(data: any): UnifiedOrderDTO; /** - * 获取所有评论 + * 将统一订单数据格式转换为平台订单数据 + * @param data 统一订单数据格式 + * @returns 平台特定订单数据 */ - getAllReviews(params?: UnifiedSearchParamsDTO): Promise; + mapUnifiedToPlatformOrder(data: Partial): any; /** - * 创建评论 + * 将统一订单创建参数转换为平台订单创建参数 + * @param data 统一订单创建参数 + * @returns 平台订单创建参数 */ - createReview(data: CreateReviewDTO): Promise; + mapCreateOrderParams(data: Partial): any; /** - * 更新评论 + * 将统一订单更新参数转换为平台订单更新参数 + * @param data 统一订单更新参数 + * @returns 平台订单更新参数 */ - updateReview(id: number, data: UpdateReviewDTO): Promise; + mapUpdateOrderParams(data: Partial): any; /** - * 删除评论 + * 获取单个订单 */ - deleteReview(id: number): Promise; + getOrder(where: Partial>): Promise; /** - * 创建产品 + * 获取订单列表 */ - createProduct(data: Partial): Promise; + getOrders(params: UnifiedSearchParamsDTO): Promise>; /** - * 更新产品 + * 获取所有订单 */ - updateProduct(id: string | number, data: Partial): Promise; + getAllOrders(params?: UnifiedSearchParamsDTO): Promise; /** - * 删除产品 + * 获取订单总数 */ - deleteProduct(id: string | number): Promise; + countOrders(params: Record): Promise; /** - * 获取产品变体列表 + * 创建订单 */ - getVariations(productId: string | number, params: UnifiedSearchParamsDTO): Promise; + createOrder(data: Partial): Promise; /** - * 获取所有产品变体 + * 更新订单 */ - getAllVariations(productId: string | number, params?: UnifiedSearchParamsDTO): Promise; + updateOrder(where: Partial>, data: Partial): Promise; /** - * 获取单个产品变体 + * 删除订单 */ - getVariation(productId: string | number, variationId: string | number): Promise; - - /** - * 创建产品变体 - */ - createVariation(productId: string | number, data: CreateVariationDTO): Promise; - - /** - * 更新产品变体 - */ - updateVariation(productId: string | number, variationId: string | number, data: UpdateVariationDTO): Promise; - - /** - * 删除产品变体 - */ - deleteVariation(productId: string | number, variationId: string | number): Promise; + deleteOrder(where: Partial>): Promise; /** * 获取订单备注 @@ -161,71 +174,6 @@ export interface ISiteAdapter { */ createOrderNote(orderId: string | number, data: any): Promise; - batchProcessProducts?(data: BatchOperationDTO): Promise; - - createOrder(data: Partial): Promise; - updateOrder(id: string | number, data: Partial): Promise; - deleteOrder(id: string | number): Promise; - - batchProcessOrders?(data: BatchOperationDTO): Promise; - - getCustomers(params: UnifiedSearchParamsDTO): Promise>; - getAllCustomers(params?: UnifiedSearchParamsDTO): Promise; - getCustomer(id: string | number): Promise; - createCustomer(data: Partial): Promise; - updateCustomer(id: string | number, data: Partial): Promise; - deleteCustomer(id: string | number): Promise; - - batchProcessCustomers?(data: BatchOperationDTO): Promise; - - /** - * 获取webhooks列表 - */ - getWebhooks(params: UnifiedSearchParamsDTO): Promise; - - /** - * 获取所有webhooks - */ - getAllWebhooks(params?: UnifiedSearchParamsDTO): Promise; - - /** - * 获取单个webhook - */ - getWebhook(id: string | number): Promise; - - /** - * 创建webhook - */ - createWebhook(data: CreateWebhookDTO): Promise; - - /** - * 更新webhook - */ - updateWebhook(id: string | number, data: UpdateWebhookDTO): Promise; - - /** - * 删除webhook - */ - deleteWebhook(id: string | number): Promise; - - /** - * 获取站点链接列表 - */ - getLinks(): Promise>; - - /** - * 订单履行(发货) - */ - fulfillOrder(orderId: string | number, data: { - tracking_number?: string; - shipping_provider?: string; - shipping_method?: string; - items?: Array<{ - order_item_id: number; - quantity: number; - }>; - }): Promise; - /** * 取消订单履行 */ @@ -273,4 +221,276 @@ export interface ISiteAdapter { * 删除订单履行信息 */ deleteOrderFulfillment(orderId: string | number, fulfillmentId: string): Promise; + + /** + * 批量处理订单 + */ + batchProcessOrders?(data: BatchOperationDTO): Promise; + + // ========== 产品映射方法 ========== + /** + * 将平台产品数据转换为统一产品数据格式 + * @param data 平台特定产品数据 + * @returns 统一产品数据格式 + */ + mapPlatformToUnifiedProduct(data: any): UnifiedProductDTO; + + /** + * 将统一产品数据格式转换为平台产品数据 + * @param data 统一产品数据格式 + * @returns 平台特定产品数据 + */ + mapUnifiedToPlatformProduct(data: Partial): any; + + /** + * 将统一产品创建参数转换为平台产品创建参数 + * @param data 统一产品创建参数 + * @returns 平台产品创建参数 + */ + mapCreateProductParams(data: Partial): any; + + /** + * 将统一产品更新参数转换为平台产品更新参数 + * @param data 统一产品更新参数 + * @returns 平台产品更新参数 + */ + mapUpdateProductParams(data: Partial): any; + + /** + * 获取单个产品 + */ + getProduct(where: Partial>): Promise; + + /** + * 获取产品列表 + */ + getProducts(params: UnifiedSearchParamsDTO): Promise>; + + /** + * 获取所有产品 + */ + getAllProducts(params?: UnifiedSearchParamsDTO): Promise; + + /** + * 创建产品 + */ + createProduct(data: Partial): Promise; + + /** + * 更新产品 + */ + updateProduct(where: Partial>, data: Partial): Promise; + + /** + * 删除产品 + */ + deleteProduct(where: Partial>): Promise; + + /** + * 批量处理产品 + */ + batchProcessProducts?(data: BatchOperationDTO): Promise; + + // ========== 评论映射方法 ========== + /** + * 将平台评论数据转换为统一评论数据格式 + * @param data 平台特定评论数据 + * @returns 统一评论数据格式 + */ + mapPlatformToUnifiedReview(data: any): UnifiedReviewDTO; + + /** + * 将统一评论数据格式转换为平台评论数据 + * @param data 统一评论数据格式 + * @returns 平台特定评论数据 + */ + mapUnifiedToPlatformReview(data: Partial): any; + + /** + * 将统一评论创建参数转换为平台评论创建参数 + * @param data 统一评论创建参数 + * @returns 平台评论创建参数 + */ + mapCreateReviewParams(data: CreateReviewDTO): any; + + /** + * 将统一评论更新参数转换为平台评论更新参数 + * @param data 统一评论更新参数 + * @returns 平台评论更新参数 + */ + mapUpdateReviewParams(data: UpdateReviewDTO): any; + + /** + * 获取评论列表 + */ + getReviews(params: UnifiedSearchParamsDTO): Promise>; + + /** + * 获取所有评论 + */ + getAllReviews(params?: UnifiedSearchParamsDTO): Promise; + + /** + * 创建评论 + */ + createReview(data: CreateReviewDTO): Promise; + + /** + * 更新评论 + */ + updateReview(where: Partial>, data: UpdateReviewDTO): Promise; + + /** + * 删除评论 + */ + deleteReview(where: Partial>): Promise; + + // ========== 订阅映射方法 ========== + /** + * 将平台订阅数据转换为统一订阅数据格式 + * @param data 平台特定订阅数据 + * @returns 统一订阅数据格式 + */ + mapPlatformToUnifiedSubscription(data: any): UnifiedSubscriptionDTO; + + /** + * 将统一订阅数据格式转换为平台订阅数据 + * @param data 统一订阅数据格式 + * @returns 平台特定订阅数据 + */ + mapUnifiedToPlatformSubscription(data: Partial): any; + + /** + * 获取订阅列表 + */ + getSubscriptions(params: UnifiedSearchParamsDTO): Promise>; + + /** + * 获取所有订阅 + */ + getAllSubscriptions(params?: UnifiedSearchParamsDTO): Promise; + + // ========== 产品变体映射方法 ========== + /** + * 将平台产品变体数据转换为统一产品变体数据格式 + * @param data 平台特定产品变体数据 + * @returns 统一产品变体数据格式 + */ + mapPlatformToUnifiedVariation(data: any): UnifiedProductVariationDTO; + + /** + * 将统一产品变体数据格式转换为平台产品变体数据 + * @param data 统一产品变体数据格式 + * @returns 平台特定产品变体数据 + */ + mapUnifiedToPlatformVariation(data: Partial): any; + + /** + * 将统一产品变体创建参数转换为平台产品变体创建参数 + * @param data 统一产品变体创建参数 + * @returns 平台产品变体创建参数 + */ + mapCreateVariationParams(data: CreateVariationDTO): any; + + /** + * 将统一产品变体更新参数转换为平台产品变体更新参数 + * @param data 统一产品变体更新参数 + * @returns 平台产品变体更新参数 + */ + mapUpdateVariationParams(data: UpdateVariationDTO): any; + + /** + * 获取单个产品变体 + */ + getVariation(productId: string | number, variationId: string | number): Promise; + + /** + * 获取产品变体列表 + */ + getVariations(productId: string | number, params: UnifiedSearchParamsDTO): Promise; + + /** + * 获取所有产品变体 + */ + getAllVariations(productId: string | number, params?: UnifiedSearchParamsDTO): Promise; + + /** + * 创建产品变体 + */ + createVariation(productId: string | number, data: CreateVariationDTO): Promise; + + /** + * 更新产品变体 + */ + updateVariation(productId: string | number, variationId: string | number, data: UpdateVariationDTO): Promise; + + /** + * 删除产品变体 + */ + deleteVariation(productId: string | number, variationId: string | number): Promise; + + // ========== Webhook映射方法 ========== + /** + * 将平台Webhook数据转换为统一Webhook数据格式 + * @param data 平台特定Webhook数据 + * @returns 统一Webhook数据格式 + */ + mapPlatformToUnifiedWebhook(data: any): UnifiedWebhookDTO; + + /** + * 将统一Webhook数据格式转换为平台Webhook数据 + * @param data 统一Webhook数据格式 + * @returns 平台特定Webhook数据 + */ + mapUnifiedToPlatformWebhook(data: Partial): any; + + /** + * 将统一Webhook创建参数转换为平台Webhook创建参数 + * @param data 统一Webhook创建参数 + * @returns 平台Webhook创建参数 + */ + mapCreateWebhookParams(data: CreateWebhookDTO): any; + + /** + * 将统一Webhook更新参数转换为平台Webhook更新参数 + * @param data 统一Webhook更新参数 + * @returns 平台Webhook更新参数 + */ + mapUpdateWebhookParams(data: UpdateWebhookDTO): any; + + /** + * 获取单个webhook + */ + getWebhook(where: Partial>): Promise; + + /** + * 获取webhooks列表 + */ + getWebhooks(params: UnifiedSearchParamsDTO): Promise; + + /** + * 获取所有webhooks + */ + getAllWebhooks(params?: UnifiedSearchParamsDTO): Promise; + + /** + * 创建webhook + */ + createWebhook(data: CreateWebhookDTO): Promise; + + /** + * 更新webhook + */ + updateWebhook(where: Partial>, data: UpdateWebhookDTO): Promise; + + /** + * 删除webhook + */ + deleteWebhook(where: Partial>): Promise; + + // ========== 站点/其他方法 ========== + /** + * 获取站点链接列表 + */ + getLinks(): Promise>; } diff --git a/src/job/sync_shipment.job.ts b/src/job/sync_shipment.job.ts index c532844..94707d9 100644 --- a/src/job/sync_shipment.job.ts +++ b/src/job/sync_shipment.job.ts @@ -75,10 +75,14 @@ export class SyncUniuniShipmentJob implements IJob{ '255': 'Gateway_To_Gateway_Transit' }; async onTick() { - const shipments:Shipment[] = await this.shipmentModel.findBy({ finished: false }); - shipments.forEach(shipment => { - this.logisticsService.updateShipmentState(shipment); - }); + try { + const shipments:Shipment[] = await this.shipmentModel.findBy({ finished: false }); + shipments.forEach(shipment => { + this.logisticsService.updateShipmentState(shipment); + }); + } catch (error) { + this.logger.error(`更新运单状态失败 ${error.message}`); + } } onComplete(result: any) { diff --git a/src/service/order.service.ts b/src/service/order.service.ts index 5c5e47f..1aa19bd 100644 --- a/src/service/order.service.ts +++ b/src/service/order.service.ts @@ -202,7 +202,7 @@ export class OrderService { try { // 调用 WooCommerce API 获取订单 const adapter = await this.siteApiService.getAdapter(siteId); - const order = await adapter.getOrder(orderId); + const order = await adapter.getOrder({ id: orderId }); // 检查订单是否已存在,以区分创建和更新 const existingOrder = await this.orderModel.findOne({ diff --git a/src/service/product.service.ts b/src/service/product.service.ts index bbde5d9..384eca8 100644 --- a/src/service/product.service.ts +++ b/src/service/product.service.ts @@ -28,7 +28,7 @@ import { StockPoint } from '../entity/stock_point.entity'; import { StockService } from './stock.service'; import { TemplateService } from './template.service'; -import { SyncOperationResultDTO, UnifiedSearchParamsDTO } from '../dto/api.dto'; +import { BatchErrorItem, BatchOperationResult, SyncOperationResultDTO, UnifiedSearchParamsDTO } from '../dto/api.dto'; import { UnifiedProductDTO } from '../dto/site-api.dto'; import { ProductSiteSkuDTO, SyncProductToSiteDTO } from '../dto/site-sync.dto'; import { Category } from '../entity/category.entity'; @@ -225,7 +225,7 @@ export class ProductService { where: { sku, }, - relations: ['category', 'attributes', 'attributes.dict', 'siteSkus'] + relations: ['category', 'attributes', 'attributes.dict'] }); } @@ -1440,7 +1440,7 @@ export class ProductService { // 解析属性字段(分号分隔多值) const parseList = (v: string) => (v ? String(v).split(';').map(s => s.trim()).filter(Boolean) : []); - + // 将属性解析为 DTO 输入 const attributes: any[] = []; @@ -1455,6 +1455,9 @@ export class ProductService { } } + // 处理分类字段 + const category = val(rec.category); + return { sku, name: val(rec.name), @@ -1464,6 +1467,7 @@ export class ProductService { promotionPrice: num(rec.promotionPrice), type: val(rec.type), siteSkus: rec.siteSkus ? String(rec.siteSkus).split(',').map(s => s.trim()).filter(Boolean) : undefined, + category, // 添加分类字段 attributes: attributes.length > 0 ? attributes : undefined, } as any; @@ -1483,10 +1487,15 @@ export class ProductService { if (data.price !== undefined) dto.price = Number(data.price); if (data.promotionPrice !== undefined) dto.promotionPrice = Number(data.promotionPrice); - if (data.categoryId !== undefined) dto.categoryId = Number(data.categoryId); + // 处理分类字段 + if (data.categoryId !== undefined) { + dto.categoryId = Number(data.categoryId); + } else if (data.category) { + // 如果是字符串,需要后续在createProduct中处理 + dto.attributes = [...(dto.attributes || []), { dictName: 'category', title: data.category }]; + } // 默认值和特殊处理 - dto.attributes = Array.isArray(data.attributes) ? data.attributes : []; // 如果有组件信息,透传 @@ -1508,7 +1517,13 @@ export class ProductService { if (data.price !== undefined) dto.price = Number(data.price); if (data.promotionPrice !== undefined) dto.promotionPrice = Number(data.promotionPrice); - if (data.categoryId !== undefined) dto.categoryId = Number(data.categoryId); + // 处理分类字段 + if (data.categoryId !== undefined) { + dto.categoryId = Number(data.categoryId); + } else if (data.category) { + // 如果是字符串,需要后续在updateProduct中处理 + dto.attributes = [...(dto.attributes || []), { dictName: 'category', title: data.category }]; + } if (data.type !== undefined) dto.type = data.type; if (data.attributes !== undefined) dto.attributes = data.attributes; @@ -1548,8 +1563,8 @@ export class ProductService { esc(p.price), esc(p.promotionPrice), esc(p.type), - esc(p.description), + esc(p.category ? p.category.name || p.category.title : ''), // 添加分类字段 ]; // 属性数据 @@ -1575,9 +1590,9 @@ export class ProductService { // 导出所有产品为 CSV 文本 async exportProductsCSV(): Promise { - // 查询所有产品及其属性(包含字典关系)和组成 + // 查询所有产品及其属性(包含字典关系)、组成和分类 const products = await this.productModel.find({ - relations: ['attributes', 'attributes.dict', 'components'], + relations: ['attributes', 'attributes.dict', 'components', 'category'], order: { id: 'ASC' }, }); @@ -1612,8 +1627,8 @@ export class ProductService { 'price', 'promotionPrice', 'type', - 'description', + 'category', ]; // 动态属性表头 @@ -1640,7 +1655,7 @@ export class ProductService { } // 从 CSV 导入产品;存在则更新,不存在则创建 - async importProductsCSV(file: any): Promise<{ created: number; updated: number; errors: string[] }> { + async importProductsCSV(file: any): Promise { let buffer: Buffer; if (Buffer.isBuffer(file)) { buffer = file; @@ -1676,19 +1691,19 @@ export class ProductService { console.log('First record keys:', Object.keys(records[0])); } } catch (e: any) { - return { created: 0, updated: 0, errors: [`CSV 解析失败:${e?.message || e}`] }; + throw new Error(`CSV 解析失败:${e?.message || e}`) } let created = 0; let updated = 0; - const errors: string[] = []; + const errors: BatchErrorItem[] = []; // 逐条处理记录 for (const rec of records) { try { const data = this.transformCsvRecordToData(rec); if (!data) { - errors.push('缺少 SKU 的记录已跳过'); + errors.push({ identifier: data.sku, error: '缺少 SKU 的记录已跳过'}); continue; } const { sku } = data; @@ -1708,11 +1723,11 @@ export class ProductService { updated += 1; } } catch (e: any) { - errors.push(`产品${rec?.sku}导入失败:${e?.message || String(e)}`); + errors.push({ identifier: '' + rec.sku, error: `产品${rec?.sku}导入失败:${e?.message || String(e)}`}); } } - return { created, updated, errors }; + return { total: records.length, processed: records.length - errors.length, created, updated, errors }; } // 将库存记录的 sku 添加到产品单品中 @@ -1831,9 +1846,7 @@ export class ProductService { } // 将本地产品转换为站点API所需格式 - const unifiedProduct = await this.convertLocalProductToUnifiedProduct(localProduct, params.siteSku); - - + const unifiedProduct = await this.mapLocalToUnifiedProduct(localProduct, params.siteSku); // 调用站点API的upsertProduct方法 try { @@ -1842,7 +1855,7 @@ export class ProductService { await this.bindSiteSkus(localProduct.id, [unifiedProduct.sku]); return result; } catch (error) { - throw new Error(`同步产品到站点失败: ${error.message}`); + throw new Error(`同步产品到站点失败: ${error?.response?.data?.message??error.message}`); } } @@ -1869,9 +1882,6 @@ export class ProductService { siteSku: item.siteSku }); - // 然后绑定站点SKU - await this.bindSiteSkus(item.productId, [item.siteSku]); - results.synced++; results.processed++; } catch (error) { @@ -1892,30 +1902,23 @@ export class ProductService { * @param siteProductId 站点产品ID * @returns 同步后的本地产品 */ - async syncProductFromSite(siteId: number, siteProductId: string | number): Promise { + async syncProductFromSite(siteId: number, siteProductId: string | number, sku: string): Promise { + const adapter = await this.siteApiService.getAdapter(siteId); + const siteProduct = await adapter.getProduct({ id: siteProductId }); // 从站点获取产品信息 - const siteProduct = await this.siteApiService.getProductFromSite(siteId, siteProductId); if (!siteProduct) { throw new Error(`站点产品 ID ${siteProductId} 不存在`); } - - // 检查是否已存在相同SKU的本地产品 - let localProduct = null; - if (siteProduct.sku) { - try { - localProduct = await this.findProductBySku(siteProduct.sku); - } catch (error) { - // 产品不存在,继续创建 - } - } - // 将站点产品转换为本地产品格式 - const productData = await this.convertSiteProductToLocalProduct(siteProduct); - - if (localProduct) { + const productData = await this.mapUnifiedToLocalProduct(siteProduct); + return await this.upsertProduct({sku}, productData); + } + async upsertProduct(where: Partial>, productData: any) { + const existingProduct = await this.productModel.findOne({ where: where}); + if (existingProduct) { // 更新现有产品 const updateData: UpdateProductDTO = productData; - return await this.updateProduct(localProduct.id, updateData); + return await this.updateProduct(existingProduct.id, updateData); } else { // 创建新产品 const createData: CreateProductDTO = productData; @@ -1929,18 +1932,18 @@ export class ProductService { * @param siteProductIds 站点产品ID数组 * @returns 批量同步结果 */ - async batchSyncFromSite(siteId: number, siteProductIds: (string | number)[]): Promise<{ synced: number, errors: string[] }> { + async batchSyncFromSite(siteId: number, data: Array<{siteProductId:string, sku: string}>): Promise<{ synced: number, errors: string[] }> { const results = { synced: 0, errors: [] }; - for (const siteProductId of siteProductIds) { + for (const item of data) { try { - await this.syncProductFromSite(siteId, siteProductId); + await this.syncProductFromSite(siteId, item.siteProductId, item.sku); results.synced++; } catch (error) { - results.errors.push(`站点产品ID ${siteProductId} 同步失败: ${error.message}`); + results.errors.push(`站点产品ID ${item.siteProductId} 同步失败: ${error.message}`); } } @@ -1952,7 +1955,7 @@ export class ProductService { * @param siteProduct 站点产品对象 * @returns 本地产品数据 */ - private async convertSiteProductToLocalProduct(siteProduct: any): Promise { + private async mapUnifiedToLocalProduct(siteProduct: any): Promise { const productData: any = { sku: siteProduct.sku, name: siteProduct.name, @@ -2015,18 +2018,20 @@ export class ProductService { * @param localProduct 本地产品对象 * @returns 统一产品对象 */ - private async convertLocalProductToUnifiedProduct(localProduct: Product,siteSku?: string): Promise> { + private async mapLocalToUnifiedProduct(localProduct: Product,siteSku?: string): Promise> { + const tags = localProduct.attributes?.map(a => ({name: a.name})) || []; // 将本地产品数据转换为UnifiedProductDTO格式 const unifiedProduct: any = { id: localProduct.id ? String(localProduct.id) : undefined, // 如果产品已存在,使用现有ID - name: localProduct.nameCn || localProduct.name || localProduct.sku, - type: 'simple', // 默认类型,可以根据实际需要调整 + name: localProduct.name, + type: localProduct.type === 'single'? 'simple' : 'bundle', // 默认类型,可以根据实际需要调整 status: 'publish', // 默认状态,可以根据实际需要调整 - sku: siteSku || await this.templateService.render('site.product.sku', { sku: localProduct.sku }), + sku: siteSku || await this.templateService.render('site.product.sku', { product: localProduct, sku: localProduct.sku }), regular_price: String(localProduct.price || 0), sale_price: String(localProduct.promotionPrice || localProduct.price || 0), price: String(localProduct.price || 0), - // stock_status: localProduct.stockQuantity && localProduct.stockQuantity > 0 ? 'instock' : 'outofstock', + // TODO 库存暂时无法同步 + // stock_status: localProduct.components && localProduct.stockQuantity > 0 ? 'instock' : 'outofstock', // stock_quantity: localProduct.stockQuantity || 0, // images: localProduct.images ? localProduct.images.map(img => ({ // id: img.id, @@ -2034,25 +2039,24 @@ export class ProductService { // name: img.name || '', // alt: img.alt || '' // })) : [], - tags: [], + tags, categories: localProduct.category ? [{ id: localProduct.category.id, name: localProduct.category.name }] : [], attributes: localProduct.attributes ? localProduct.attributes.map(attr => ({ - id: attr.id, - name: attr.name, - position: 0, + id: attr.dict.id, + name: attr.dict.name, + position: attr.dict.sort || 0, visible: true, variation: false, - options: [attr.value] + options: [attr.name] })) : [], variations: [], date_created: localProduct.createdAt ? new Date(localProduct.createdAt).toISOString() : new Date().toISOString(), date_modified: localProduct.updatedAt ? new Date(localProduct.updatedAt).toISOString() : new Date().toISOString(), raw: { - localProductId: localProduct.id, - localProductSku: localProduct.sku + ...localProduct } }; diff --git a/src/service/shopyy.service.ts b/src/service/shopyy.service.ts index d083e2f..0081f55 100644 --- a/src/service/shopyy.service.ts +++ b/src/service/shopyy.service.ts @@ -1,3 +1,6 @@ +/** + * https://www.apizza.net/project/e114fb8e628e0f604379f5b26f0d8330/browse + */ import { ILogger, Inject, Provide } from '@midwayjs/core'; import axios, { AxiosRequestConfig } from 'axios'; import * as fs from 'fs'; @@ -155,7 +158,7 @@ export class ShopyyService { * @param params 请求参数 * @returns 响应数据 */ - private async request(site: any, endpoint: string, method: string = 'GET', data: any = null, params: any = null): Promise { + async request(site: any, endpoint: string, method: string = 'GET', data: any = null, params: any = null): Promise { const url = this.buildURL(site.apiUrl, endpoint); const headers = this.buildHeaders(site); @@ -180,41 +183,19 @@ export class ShopyyService { * 通用分页获取资源 */ public async fetchResourcePaged(site: any, endpoint: string, params: Record = {}) { - const page = Number(params.page || 1); - const limit = 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); - if (entries.length > 0) { - const [field, dir] = entries[0]; - orderby = field; - order = String(dir).toLowerCase() === 'desc' ? 'desc' : 'asc'; - } - } - // 映射统一入参到平台入参 - const requestParams = { - ...where, - ...(params.search ? { search: params.search } : {}), - ...(params.status ? { status: params.status } : {}), - ...(orderby ? { orderby } : {}), - ...(order ? { order } : {}), - page, - limit - }; - this.logger.debug('ShopYY API请求分页参数:'+ JSON.stringify(requestParams)); - const response = await this.request(site, endpoint, 'GET', null, requestParams); + const response = await this.request(site, endpoint, 'GET', null, params); + return this.mapPageResponse(response,params); + } + mapPageResponse(response:any,query: Record){ if (response?.code !== 0) { throw new Error(response?.msg) } - return { items: (response.data.list || []) as T[], total: response.data?.paginate?.total || 0, totalPages: response.data?.paginate?.pageTotal || 0, - page: response.data?.paginate?.current || requestParams.page, - per_page: response.data?.paginate?.pagesize || requestParams.limit, + page: response.data?.paginate?.current || query.page, + per_page: response.data?.paginate?.pagesize || query.limit, }; } @@ -225,13 +206,13 @@ export class ShopyyService { * @param pageSize 每页数量 * @returns 分页产品列表 */ - async getProducts(site: any, page: number = 1, pageSize: number = 100): Promise { + async getProducts(site: any, page: number = 1, pageSize: number = 100, where: Record = {}): Promise { // ShopYY API: GET /products // 通过 fields 参数指定需要返回的字段,确保 handle 等关键信息被包含 const response = await this.request(site, 'products', 'GET', null, { page, page_size: pageSize, - fields: 'id,name,sku,handle,status,type,stock_status,stock_quantity,images,regular_price,sale_price,tags,variations' + ...where }); return { diff --git a/src/service/site-api.service.ts b/src/service/site-api.service.ts index c57a899..46d8ee4 100644 --- a/src/service/site-api.service.ts +++ b/src/service/site-api.service.ts @@ -1,4 +1,4 @@ -import { Inject, Provide } from '@midwayjs/core'; +import { ILogger, Inject, Provide } from '@midwayjs/core'; import { ShopyyAdapter } from '../adapter/shopyy.adapter'; import { WooCommerceAdapter } from '../adapter/woocommerce.adapter'; import { ISiteAdapter } from '../interface/site-adapter.interface'; @@ -22,6 +22,9 @@ export class SiteApiService { @Inject() productService: ProductService; + @Inject() + logger: ILogger; + async getAdapter(siteId: number): Promise { const site = await this.siteService.get(siteId, true); if (!site) { @@ -39,7 +42,7 @@ export class SiteApiService { } return new ShopyyAdapter(site, this.shopyyService); } - + throw new Error(`Unsupported site type: ${site.type}`); } @@ -57,7 +60,7 @@ export class SiteApiService { try { // 使用站点SKU查询对应的ERP产品 const erpProduct = await this.productService.findProductBySiteSku(siteProduct.sku); - + // 将ERP产品信息合并到站点商品中 return { ...siteProduct, @@ -108,38 +111,27 @@ export class SiteApiService { */ async upsertProduct(siteId: number, product: Partial): Promise { const adapter = await this.getAdapter(siteId); - - // 首先尝试查找产品 - if (product.id) { - try { - // 尝试获取产品以确认它是否存在 - const existingProduct = await adapter.getProduct(product.id); - if (existingProduct) { - // 产品存在,执行更新 - return await adapter.updateProduct(product.id, product); - } - } catch (error) { - // 如果获取产品失败,可能是因为产品不存在,继续执行创建逻辑 - console.log(`产品 ${product.id} 不存在,将创建新产品:`, error.message); - } - } else if (product.sku) { - // 如果没有提供ID但提供了SKU,尝试通过SKU查找产品 - try { - // 尝试搜索具有相同SKU的产品 - const searchResult = await adapter.getProducts({ where: { sku: product.sku } }); - if (searchResult.items && searchResult.items.length > 0) { - const existingProduct = searchResult.items[0]; - // 找到现有产品,更新它 - return await adapter.updateProduct(existingProduct.id, product); - } - } catch (error) { - // 搜索失败,继续执行创建逻辑 - console.log(`通过SKU搜索产品失败:`, error.message); - } - } + // 首先尝试查找产品 + if (!product.sku) { + throw new Error('产品SKU不能为空'); + } + // 尝试搜索具有相同SKU的产品 + let existingProduct + try { + + existingProduct = await adapter.getProduct({ sku: product.sku }); + } catch (error) { + this.logger.error(`[Site API] 查找产品失败, siteId: ${siteId}, sku: ${product.sku}, 错误信息: ${error.message}`); + existingProduct = null + } + if (existingProduct) { + // 找到现有产品,更新它 + return await adapter.updateProduct({ id: existingProduct.id }, product); + } // 产品不存在,执行创建 return await adapter.createProduct(product); + } /** @@ -189,17 +181,6 @@ export class SiteApiService { return await adapter.getProducts(params); } - /** - * 从站点获取单个产品 - * @param siteId 站点ID - * @param productId 产品ID - * @returns 站点产品 - */ - async getProductFromSite(siteId: number, productId: string | number): Promise { - const adapter = await this.getAdapter(siteId); - return await adapter.getProduct(productId); - } - /** * 从站点获取所有产品 * @param siteId 站点ID diff --git a/src/service/wp.service.ts b/src/service/wp.service.ts index c7faa02..14cf044 100644 --- a/src/service/wp.service.ts +++ b/src/service/wp.service.ts @@ -44,7 +44,7 @@ export class WPService implements IPlatformService { * @param site 站点配置 * @param namespace API 命名空间,默认 wc/v3;订阅推荐 wcs/v1 */ - private createApi(site: any, namespace: WooCommerceRestApiVersion = 'wc/v3') { + public createApi(site: any, namespace: WooCommerceRestApiVersion = 'wc/v3') { return new WooCommerceRestApi({ url: site.apiUrl, consumerKey: site.consumerKey, @@ -240,9 +240,11 @@ export class WPService implements IPlatformService { return allData; } - async getProducts(site: any, page: number = 1, pageSize: number = 100): Promise { + async getProducts(site: any, params: Record = {}): Promise { const api = this.createApi(site, 'wc/v3'); - return await this.sdkGetPage(api, 'products', { page, per_page: pageSize }); + const page = params.page ?? 1; + const per_page = params.per_page ?? params.pageSize ?? 100; + return await this.sdkGetPage(api, 'products', { ...params, page, per_page }); } async getProduct(site: any, id: number): Promise { @@ -254,7 +256,7 @@ export class WPService implements IPlatformService { // 导出 WooCommerce 产品为特殊CSV(平台特性) async exportProductsCsvSpecial(site: any, page: number = 1, pageSize: number = 100): Promise { - const list = await this.getProducts(site, 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 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'); diff --git a/src/transformer/database.transformer.ts b/src/transformer/database.transformer.ts new file mode 100644 index 0000000..619ef04 --- /dev/null +++ b/src/transformer/database.transformer.ts @@ -0,0 +1 @@ +// 从 unified 到 数据库需要有个转换流程 diff --git a/src/transformer/file.transformer.ts b/src/transformer/file.transformer.ts new file mode 100644 index 0000000..b85ee23 --- /dev/null +++ b/src/transformer/file.transformer.ts @@ -0,0 +1 @@ +// 文件转换 diff --git a/src/transformer/shopyy.transformer.ts b/src/transformer/shopyy.transformer.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/transformer/woocommerce.adpater.ts b/src/transformer/woocommerce.adpater.ts new file mode 100644 index 0000000..e5b5c67 --- /dev/null +++ b/src/transformer/woocommerce.adpater.ts @@ -0,0 +1,8 @@ +import { UnifiedOrderDTO } from "../dto/site-api.dto"; + +export class ShipmentAdapter { + // 用于导出物流需要的数据 + mapFromOrder(order: UnifiedOrderDTO): any { + return order; + } +} \ No newline at end of file -- 2.40.1