From 4beefcd22cfef288ed07ad0d6c01b0ddb9f7d753 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 30 May 2026 17:30:17 +0800 Subject: [PATCH] feat(print,docs,migrations): add notifyLock, order export, express fields and related docs notifyLock method + logs print.send logs order export methods + docs express model fields SPH/XHS/DW/JD + migration platform_shop_id migration notifyLock docs order export docs --- app/model/express.js | 24 ++ app/model/express_interface.js | 5 + app/service/systemMethods/index.js | 40 +++ app/service/systemMethods/print.js | 338 +++++++++++++++++- .../systemMethods/setting/expressInterface.js | 5 + app/service/systems/express_platform.js | 2 +- .../systems/setting/expressInterface.js | 18 +- ...110000-add-sph-xhs-dw-jd-to-wms-express.js | 78 ++++ ...atform-shop-id-to-wms-express-interface.js | 46 +++ methods/changes/system.json | 17 + methods/system.json | 144 +++++++- script/verify-migration.cjs | 48 +++ .../service/systemMethods/print.send.test.js | 85 ++++- .../setting/expressInterface.test.js | 2 + .../systems/setting/expressInterface.test.js | 36 +- 15 files changed, 865 insertions(+), 23 deletions(-) create mode 100644 database/migrations/20260529110000-add-sph-xhs-dw-jd-to-wms-express.js create mode 100644 database/migrations/20260530100000-add-platform-shop-id-to-wms-express-interface.js create mode 100644 script/verify-migration.cjs diff --git a/app/model/express.js b/app/model/express.js index 261006b..3da646e 100644 --- a/app/model/express.js +++ b/app/model/express.js @@ -49,6 +49,30 @@ module.exports = app => { allowNull: true, comment: '菜鸟编码', }, + SPH: { + field: 'SPH', + type: STRING(255), + allowNull: true, + comment: 'SPH编码', + }, + XHS: { + field: 'XHS', + type: STRING(255), + allowNull: true, + comment: '小红书编码', + }, + DW: { + field: 'DW', + type: STRING(255), + allowNull: true, + comment: 'DW编码', + }, + JD: { + field: 'JD', + type: STRING(255), + allowNull: true, + comment: '京东编码', + }, }, { tableName: 'wms_express', freezeTableName: true, diff --git a/app/model/express_interface.js b/app/model/express_interface.js index 7d93bae..85a4ed7 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -46,6 +46,11 @@ module.exports = app => { allowNull: true, comment: '店铺ID', }, + platform_shop_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '平台店铺ID', + }, sender_name: { type: STRING(50), allowNull: true, diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 91c6854..ec720d6 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -545,6 +545,9 @@ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { if(subscriptionItem.logisticsaccount){ result.customer_code_list = [subscriptionItem.logisticsaccount]; } + if(subscriptionItem.shopid){ + result.platform_shop_id = subscriptionItem.shopid; + } return result; }); @@ -1962,6 +1965,43 @@ class indexService extends MainService { list = parsed.list; break; } + case 'SPH':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, "SPH"); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { + }, { + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); + list = parsed.list; + break; + } + case 'XHS':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, "XHS"); + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { + }, { + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + platid, + version: '1.5', + token: accessToken, + }); + console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); + const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); + list = parsed.list; + break; + } + default: list = []; break; diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 1cf549f..5fb7b10 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -18,7 +18,7 @@ class PrintService extends MainService { // 初始化免登录、免权限、免日志、免认证等配置 const _noNeedLogin = ''; const _noNeedRight = '*'; - const _noNeedLog = ''; + const _noNeedLog = 'notifyLock,notify_lock'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); this.defaultComponents = [ @@ -1381,6 +1381,321 @@ class PrintService extends MainService { return Array.from(orderIdSet); } + /** + * 从通知锁定入参中提取订单ID。 + * + * 优先使用 order_ids/orderIds;为空时回退使用 waveGroups 提取。 + * + * @param {Object} payload 通知锁定入参。 + * @param {Array} [payload.order_ids] 订单ID列表(推荐)。 + * @param {Array} [payload.orderIds] 兼容驼峰订单ID列表。 + * @param {Array} [payload.waveGroups] 波次分组。 + * @param {Object} [payload.data] 兼容 print.send 结构的数据体。 + * @return {{orderIds:Array,orderIdsCount:number,waveGroupsCount:number,source:string}} 提取结果。 + */ + extractOrderIdsFromNotifyLockPayload(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; + const directOrderIds = this.normalizeOrderIds(Array.isArray(normalizedPayload.order_ids) + ? normalizedPayload.order_ids + : (Array.isArray(normalizedPayload.orderIds) ? normalizedPayload.orderIds : [])); + const waveGroups = Array.isArray(normalizedPayload.waveGroups) + ? normalizedPayload.waveGroups + : (Array.isArray(data.waveGroups) ? data.waveGroups : []); + const waveGroupOrderIds = this.collectOrderIdsFromWaveGroups(waveGroups); + const hasDirectOrderIds = directOrderIds.length > 0; + const orderIds = hasDirectOrderIds ? directOrderIds : waveGroupOrderIds; + + return { + orderIds, + orderIdsCount: orderIds.length, + waveGroupsCount: waveGroups.length, + source: hasDirectOrderIds ? 'order_ids' : 'waveGroups', + }; + } + + /** + * 构建 notifyLock 的轻量日志摘要,避免落库超大对象。 + * + * @param {Object} payload notifyLock 原始入参。 + * @param {Object} extracted 已提取摘要信息。 + * @param {Array} [extracted.orderIds] 订单ID列表。 + * @param {number} [extracted.orderIdsCount] 订单数量。 + * @param {number} [extracted.waveGroupsCount] 波次数量。 + * @param {string} [extracted.source] 订单来源标识。 + * @return {Object} 轻量可落库摘要。 + */ + buildNotifyLockInputSummary(payload = {}, extracted = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; + const orderIds = Array.isArray(extracted.orderIds) ? extracted.orderIds : []; + const orderIdsCount = Number(extracted.orderIdsCount || orderIds.length || 0); + const waveGroupsCount = Number(extracted.waveGroupsCount || 0); + const source = String(extracted.source || '').trim(); + const requestCode = normalizedPayload.requestCode + ? String(normalizedPayload.requestCode).slice(0, 128) + : (normalizedPayload.request_code ? String(normalizedPayload.request_code).slice(0, 128) : ''); + + return { + action: 'notifyLock', + source, + order_ids_count: orderIdsCount, + order_ids_sample: orderIds.slice(0, 100), + wave_groups_count: waveGroupsCount, + request_code: requestCode, + payload_keys: Object.keys(normalizedPayload).slice(0, 20), + data_keys: Object.keys(data).slice(0, 20), + has_data: Object.keys(data).length > 0, + }; + } + + /** + * 获取打印相关订单操作日志的操作人信息。 + * + * 取值优先级:ctx.state.user -> ctx.user,字段优先尝试 employees/operator/id 与 name。 + * + * @return {{id:string|null,name:string}} 操作人信息。 + */ + getPrintOrderOperationOperator() { + const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' + ? this.ctx.state.user + : null; + const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object' + ? this.ctx.user + : null; + const user = stateUser || ctxUser || {}; + + const rawOperatorId = user.employees_id ?? user.operator_id ?? user.id; + const rawOperatorName = user.employees_name + ?? user.operator_name + ?? user.real_name + ?? user.name; + + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : (String(rawOperatorId).trim() || null); + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : (String(rawOperatorName).trim() || 'system'); + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 按订单ID批量写入打印相关订单操作日志。 + * + * 日志写入失败不会中断主流程,仅记录 warn/error。 + * + * @param {Object} payload 写入参数。 + * @param {Array} payload.orderIds 订单ID列表。 + * @param {string} payload.source 来源标识(如 print.send/print.notifyLock)。 + * @param {string} payload.message 日志消息。 + * @param {string} [payload.operationCode='ORDER_PRINT'] 操作编码。 + * @return {Promise} 无返回值。 + */ + async writePrintOrderOperationLogsByOrderIds(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); + if (orderIds.length === 0) { + return; + } + + const source = String(normalizedPayload.source || '').trim() || 'print.send'; + const message = String(normalizedPayload.message || '').trim() || `${source} 执行完成`; + const operationCode = String(normalizedPayload.operationCode || '').trim() || 'ORDER_PRINT'; + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + const operationLogService = this.ctx + && this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.operationLog; + + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + this.ctx.logger.warn('[print.operationLog] operationLog 批量写入服务不可用,跳过日志写入', { + source, + orderIdsCount: orderIds.length, + }); + return; + } + + const operator = this.getPrintOrderOperationOperator(); + const payloads = orderIds.map(orderId => ({ + businessType: 'order', + businessId: orderId, + operationCode, + operator, + extras: { + warehouseId, + message, + }, + })); + + try { + const results = await operationLogService.createOperationLogs(payloads); + if (!Array.isArray(results)) { + return; + } + for (let index = 0; index < payloads.length; index++) { + if (results[index]) { + continue; + } + this.ctx.logger.warn('[print.operationLog] 订单操作日志写入失败,不影响主流程', { + source, + orderId: payloads[index].businessId, + operationCode, + }); + } + } catch (error) { + this.ctx.logger.error('[print.operationLog] 批量写入订单操作日志异常,不影响主流程', { + source, + orderIdsCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + /** + * 通知锁定接口:仅执行订单锁定流程,不发送打印任务。 + * + * @param {Object} data 入参。 + * @param {Array} [data.order_ids] 订单ID列表(推荐)。 + * @param {Array} [data.orderIds] 兼容驼峰订单ID列表。 + * @param {Array} [data.waveGroups] 波次分组(兼容 print.send 轻量版本)。 + * @param {Object} [data.data] 兼容 print.send 的 data 包装。 + * @return {Promise} 统一 success/fail 返回结构。 + */ + async notifyLock(data = {}) { + const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0); + const { + orderIds, + orderIdsCount, + waveGroupsCount, + source, + } = this.extractOrderIdsFromNotifyLockPayload(data); + + const notifyLockInputSummary = this.buildNotifyLockInputSummary(data, { + orderIds, + orderIdsCount, + waveGroupsCount, + source, + }); + + let printRecord = null; + try { + printRecord = await this.ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({ + warehouse_id: warehouseId, + computer_id: 0, + printer: 'notifyLock', + type: 'notify_lock', + data: notifyLockInputSummary, + request_code: notifyLockInputSummary.request_code || null, + })); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 创建失败', { + warehouseId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + + if (orderIdsCount === 0) { + if (printRecord && typeof printRecord.update === 'function') { + try { + await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: '未提取到有效订单ID,请传入 order_ids 或 waveGroups', + failCode: 'NOTIFY_LOCK_INVALID_INPUT', + })); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { + warehouseId, + printId: printRecord.id, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + } + return this.fail('未提取到有效订单ID,请传入 order_ids 或 waveGroups', { + code: 400, + locked_count: 0, + order_ids_count: 0, + wave_groups_count: waveGroupsCount, + }); + } + + const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({ + warehouseId, + orderIds, + }); + + if (!lockResult.success) { + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds, + source: 'print.notifyLock', + message: `通知锁定执行失败,原因=${lockResult.errorMessage || '未知错误'}`, + }); + if (printRecord && typeof printRecord.update === 'function') { + try { + await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ + errorMessage: lockResult.errorMessage || '未知错误', + failCode: 'NOTIFY_LOCK_FAILED', + })); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { + warehouseId, + printId: printRecord.id, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + } + return this.fail(`订单锁定失败:${lockResult.errorMessage || '未知错误'}`, { + code: 500, + locked_count: 0, + order_ids_count: orderIdsCount, + order_ids: orderIds, + }); + } + + if (printRecord && typeof printRecord.update === 'function') { + try { + await printRecord.update(this.buildSentPrintRecordUpdatePayload()); + } catch (error) { + this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', { + warehouseId, + printId: printRecord.id, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + } + } + + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds, + source: 'print.notifyLock', + message: `通知锁定执行成功,locked_count=${lockResult.lockedCount}`, + }); + + return this.success('ok', { + code: 0, + locked_count: lockResult.lockedCount, + order_ids_count: orderIdsCount, + order_ids: orderIds, + source, + }); + } + + /** + * notifyLock 的 snake_case 兼容别名。 + * + * @param {Object} data 入参。 + * @return {Promise} 与 notifyLock 一致的返回结构。 + */ + async notify_lock(data = {}) { + return this.notifyLock(data); + } + /** * 在打印发送成功后批量锁定订单。 * @@ -1826,6 +2141,11 @@ class PrintService extends MainService { }); } catch (error) { const sendDurationMs = Date.now() - sendStartAt; + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`, + }); this.ctx.logger.error('[print.send] sendToComputer 调用失败', { ...batchSummary, printId: currentPrintRecord.id, @@ -1852,6 +2172,11 @@ class PrintService extends MainService { } const sendDurationMs = Date.now() - sendStartAt; if (sendResult.status !== 'success') { + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送失败,原因=${sendResult.error || '打印服务返回失败'}`, + }); this.ctx.logger.error('[print.send] sendToComputer 调用失败', { ...batchSummary, printId: currentPrintRecord.id, @@ -1896,6 +2221,11 @@ class PrintService extends MainService { provider: providerTaskId, }); } catch (error) { + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`, + }); await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({ errorMessage: error && error.message ? error.message : `${error}`, })); @@ -1941,6 +2271,12 @@ class PrintService extends MainService { }); } + await this.writePrintOrderOperationLogsByOrderIds({ + orderIds: batchOrderIds, + source: 'print.send', + message: `批次发送结束成功,print_id=${currentPrintRecord.id},order_count=${batchOrderIds.length}`, + }); + this.ctx.logger.info('[print.send] 平台快递组发送结束', { ...batchSummary, printId: currentPrintRecord.id, diff --git a/app/service/systemMethods/setting/expressInterface.js b/app/service/systemMethods/setting/expressInterface.js index 7ffa20e..2f19a4f 100644 --- a/app/service/systemMethods/setting/expressInterface.js +++ b/app/service/systemMethods/setting/expressInterface.js @@ -232,6 +232,8 @@ class expressInterfaceService extends MainService { templateUrl: camelTemplateUrl, ext_data: extData, extData: camelExtData, + platform_shop_id: platformShopId, + platformShopId: camelPlatformShopId, ...rest } = data || {}; @@ -273,6 +275,9 @@ class expressInterfaceService extends MainService { if (extData !== undefined || camelExtData !== undefined) { payload.ext_data = extData !== undefined ? extData : camelExtData; } + if (platformShopId !== undefined || camelPlatformShopId !== undefined) { + payload.platform_shop_id = platformShopId !== undefined ? platformShopId : camelPlatformShopId; + } return await this.callSystemExpressInterface('update', payload, '更新快递接口失败'); } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index a8d5769..f89a55e 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -455,7 +455,7 @@ class ExpressPlatformService extends MainService { volume: Number(order.volume) || 0, ispickup: listByWarehousePlatformCode.ispickup ?? 0, producttype: listByWarehousePlatformCode.product_type || '', - Sipshopid: listByWarehousePlatformCode.shop_id || '', + Sipshopid: listByWarehousePlatformCode.platform_shop_id || '', sys_express_code: listByWarehousePlatformCode.sys_express_code || '', platform_code: listByWarehousePlatformCode.platform_code || '', cpcode: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)[listByWarehousePlatformCode.platform_code] || '', diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index e5ceafd..291d54b 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -723,6 +723,7 @@ class SettingExpressInterfaceService extends Service { sys_express_code: this.normalizeOptionalText(row.sys_express_code, 'sys_express_code', 50), warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), shop_id: row.shop_id === undefined || row.shop_id === null ? null : Number(row.shop_id), + platform_shop_id: row.platform_shop_id === undefined || row.platform_shop_id === null ? null : Number(row.platform_shop_id), platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20), sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50), sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11), @@ -1058,7 +1059,7 @@ class SettingExpressInterfaceService extends Service { }, include: this.getInterfaceInclude(), attributes: [ - 'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_code', + 'id', 'name', 'express_code', 'warehouse_id', 'shop_id', 'platform_shop_id', 'platform_code', 'sys_express_code', 'sender_name', 'sender_tel', 'weight', 'viewer', 'client_id', 'is_share', 'province_name', 'city_name', 'district_name', 'site_code', @@ -1272,6 +1273,8 @@ class SettingExpressInterfaceService extends Service { || Object.prototype.hasOwnProperty.call(data, 'weightType'); const hasShopId = Object.prototype.hasOwnProperty.call(data, 'shop_id') || Object.prototype.hasOwnProperty.call(data, 'shopId'); + const hasPlatformShopId = Object.prototype.hasOwnProperty.call(data, 'platform_shop_id') + || Object.prototype.hasOwnProperty.call(data, 'platformShopId'); const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer'); const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id') || Object.prototype.hasOwnProperty.call(data, 'clientId'); @@ -1301,7 +1304,7 @@ class SettingExpressInterfaceService extends Service { if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode && !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType - && !hasShopId + && !hasShopId && !hasPlatformShopId && !hasViewer && !hasClientId && !hasIsPickup && !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName && !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode @@ -1380,6 +1383,17 @@ class SettingExpressInterfaceService extends Service { updates.token = shopBinding.token; } + if (hasPlatformShopId) { + updates.platform_shop_id = this.normalizeInteger( + data.platform_shop_id !== undefined ? data.platform_shop_id : data.platformShopId, + 'platform_shop_id', + { + allowEmpty: true, + min: 1, + } + ); + } + if (hasViewer) { updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50); } diff --git a/database/migrations/20260529110000-add-sph-xhs-dw-jd-to-wms-express.js b/database/migrations/20260529110000-add-sph-xhs-dw-jd-to-wms-express.js new file mode 100644 index 0000000..08a8dfa --- /dev/null +++ b/database/migrations/20260529110000-add-sph-xhs-dw-jd-to-wms-express.js @@ -0,0 +1,78 @@ +'use strict'; + +/** + * 为快递基础信息表新增 SPH/XHS/DW/JD 编码字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 SPH/XHS/DW/JD 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.SPH) { + await queryInterface.addColumn(tableName, 'SPH', { + type: Sequelize.STRING(255), + allowNull: true, + comment: 'SPH编码', + }); + } + + if (!columns.XHS) { + await queryInterface.addColumn(tableName, 'XHS', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '小红书编码', + }); + } + + if (!columns.DW) { + await queryInterface.addColumn(tableName, 'DW', { + type: Sequelize.STRING(255), + allowNull: true, + comment: 'DW编码', + }); + } + + if (!columns.JD) { + await queryInterface.addColumn(tableName, 'JD', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '京东编码', + }); + } + }, + + /** + * 回滚迁移:删除 SPH/XHS/DW/JD 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.SPH) { + await queryInterface.removeColumn(tableName, 'SPH'); + } + + if (columns.XHS) { + await queryInterface.removeColumn(tableName, 'XHS'); + } + + if (columns.DW) { + await queryInterface.removeColumn(tableName, 'DW'); + } + + if (columns.JD) { + await queryInterface.removeColumn(tableName, 'JD'); + } + }, +}; diff --git a/database/migrations/20260530100000-add-platform-shop-id-to-wms-express-interface.js b/database/migrations/20260530100000-add-platform-shop-id-to-wms-express-interface.js new file mode 100644 index 0000000..0fb4099 --- /dev/null +++ b/database/migrations/20260530100000-add-platform-shop-id-to-wms-express-interface.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为快递接口配置表新增平台店铺 ID 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增平台店铺 ID 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.platform_shop_id) { + return; + } + + await queryInterface.addColumn(tableName, 'platform_shop_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '平台店铺ID', + }); + }, + + /** + * 回滚迁移:删除平台店铺 ID 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.platform_shop_id) { + return; + } + + await queryInterface.removeColumn(tableName, 'platform_shop_id'); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index f80f8f2..ec9436d 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2479,5 +2479,22 @@ ], "type": "added", "module": "order.index" + }, + { + "version": "2026.05.30-system-01", + "date": "2026-05-30", + "summary": "新增 print.notifyLock(及 notify_lock 兼容别名),并补充 print.send 写入订单操作日志的行为说明", + "methods": [ + "print.notifyLock", + "print.notify_lock", + "print.send" + ], + "notes": [ + "新增 print.notifyLock:入参支持 order_ids/orderIds、waveGroups、data.waveGroups(至少一类提供订单 ID);仅执行订单锁定流程,不发送打印任务;写打印任务日志 + 订单操作日志;返回 locked_count、order_ids_count、order_ids、source;错误:无有效订单ID(400)、锁定失败(500)。", + "补充 print.send 文档:说明接口在执行打印任务记录的同时会写入订单操作日志(记录打印相关操作)。", + "新增兼容别名 print.notify_lock:文档说明等价转调到 print.notifyLock。" + ], + "type": "updated", + "module": "print" } ] diff --git a/methods/system.json b/methods/system.json index 3efa461..37a0995 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.0.4", - "updatedAt": "2026-05-29", + "version": "0.0.5", + "updatedAt": "2026-05-30", "headers": [ { "name": "platform", @@ -8796,7 +8796,7 @@ "list": [ { "method": "print.send", - "description": "发送打印任务到打印电脑,并记录打印单。说明:当 type=express 时,接口按 data.waveGroups(来源于 order.print.getWavePlatformPrintData 返回的 data.waveGroups)进行处理,按 waveGroups -> platforms 串行处理,每个平台+快递 组分别发送;返回沿用现有简要风格,不返回明细。", + "description": "发送打印任务到打印电脑,并记录打印单。说明:当 type=express 时,接口按 data.waveGroups(来源于 order.print.getWavePlatformPrintData 返回的 data.waveGroups)进行处理,按 waveGroups -> platforms 串行处理,每个平台+快递 组分别发送;返回沿用现有简要风格,不返回明细。接口在记录打印单的同时,也会写入订单操作日志(记录打印相关操作)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8896,32 +8896,36 @@ { "name": "flag", "type": "string", + "required": false, "description": "全局调用结果标识,成功时为 success,失败时为 failure" }, { "name": "code", "type": "number", + "required": false, "description": "业务状态码;成功时为 200,失败时通常为 1001 或 504" }, { "name": "message", "type": "string", + "required": false, "description": "返回信息" }, { "name": "printId", "type": "number", + "required": false, "description": "打印记录 ID;任务入库成功后返回,失败时若已生成记录也会返回。接口在 express 场景下不返回明细结果,只给出调用结果摘要。" } ], "errors": [ { - "code": "1001", - "description": "不支持的打印类型" + "code": 1001, + "message": "不支持的打印类型" }, { - "code": "504", - "description": "打印任务发送失败(如打印机不存在、打印机脱机、打印服务通讯失败)" + "code": 504, + "message": "打印任务发送失败(如打印机不存在、打印机脱机、打印服务通讯失败)" } ] }, @@ -9742,6 +9746,132 @@ "message": "内部错误" } ] + }, + { + "method": "print.notifyLock", + "description": "仅执行订单锁定流程,不发送打印任务;记录打印任务日志并写入订单操作日志。兼容别名:print.notify_lock(等价转调)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids", + "type": "array", + "required": false, + "source": "body", + "description": "订单 ID 数组(与 orderIds 互为别名)。至少需提供 order_ids/orderIds/waveGroups/data.waveGroups 中的一类以提取订单 ID。", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单 ID" + } + ] + }, + { + "name": "orderIds", + "type": "array", + "required": false, + "source": "body", + "description": "订单 ID 数组(驼峰兼容,等同于 order_ids)。", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单 ID" + } + ] + }, + { + "name": "waveGroups", + "type": "array", + "required": false, + "source": "body", + "description": "波次分组结构(可从中提取订单 ID,参考 order.print.getWavePlatformPrintData 返回的 waveGroups)。", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次 ID" + } + ] + }, + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "兼容包装对象;若传入 data.waveGroups,可从中提取订单 ID。", + "children": [ + { + "name": "waveGroups", + "type": "array", + "required": false, + "description": "同上,来自 order.print.getWavePlatformPrintData 的 data.waveGroups 结构。" + } + ] + } + ], + "response": [ + { + "name": "locked_count", + "type": "number", + "required": false, + "description": "成功锁定的订单数量" + }, + { + "name": "order_ids_count", + "type": "number", + "required": false, + "description": "请求中识别出的订单 ID 数量" + }, + { + "name": "order_ids", + "type": "array", + "required": false, + "description": "本次尝试锁定的订单 ID 列表" + }, + { + "name": "source", + "type": "string", + "required": false, + "description": "操作来源标识(可选,若后端返回则提供具体来源)" + } + ], + "errors": [ + { + "code": 400, + "message": "无有效订单ID(order_ids/orderIds/waveGroups/data.waveGroups 均未提供或均无有效订单)" + }, + { + "code": 500, + "message": "订单锁定失败" + } + ] + }, + { + "method": "print.notify_lock", + "description": "兼容别名(等价转调到 print.notifyLock);建议使用 print.notifyLock。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] } ] }, diff --git a/script/verify-migration.cjs b/script/verify-migration.cjs new file mode 100644 index 0000000..17cfc2a --- /dev/null +++ b/script/verify-migration.cjs @@ -0,0 +1,48 @@ +'use strict'; +const Sequelize = require('sequelize'); +const args = process.argv.slice(2); +if (args.length < 2) { + console.error('USAGE: node script/verify-migration.cjs [columnsCommaSeparated]'); + process.exit(2); +} +const migrationName = args[0]; +const tableName = args[1]; +const columns = (args[2] || '').split(',').filter(Boolean); +(async () => { + try { + const dbConfigAll = require('../database/config.js'); + const dbConfig = dbConfigAll.production; + const sequelize = new Sequelize(dbConfig.database, dbConfig.username, dbConfig.password, { + host: dbConfig.host, + port: dbConfig.port, + dialect: dbConfig.dialect || 'mysql', + logging: false, + }); + await sequelize.authenticate(); + const [metaRows] = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [migrationName] }); + const metaExists = metaRows && metaRows.length > 0; + let columnsResult = null; + try { + const [cols] = await sequelize.query(`SHOW FULL COLUMNS FROM \`${tableName}\``); + columnsResult = {}; + for (const c of cols) { + columnsResult[c.Field] = { Type: c.Type, Null: c.Null, Comment: c.Comment, Default: c.Default }; + } + } catch (e) { + // table may not exist + } + const checkColumns = {}; + if (columnsResult) { + for (const col of columns) { + checkColumns[col] = !!columnsResult[col]; + } + } + const result = { migration: migrationName, migrationRecorded: !!metaExists, table: tableName, columnsExist: checkColumns, rawColumns: columnsResult ? Object.keys(columnsResult) : null }; + console.log(JSON.stringify(result)); + await sequelize.close(); + process.exit(0); + } catch (e) { + console.error('VERIFY_ERROR', e && e.message ? e.message : e); + process.exit(3); + } +})(); diff --git a/test/app/service/systemMethods/print.send.test.js b/test/app/service/systemMethods/print.send.test.js index 1b7d4c8..831a06a 100644 --- a/test/app/service/systemMethods/print.send.test.js +++ b/test/app/service/systemMethods/print.send.test.js @@ -26,6 +26,7 @@ function createContext(options = {}) { redisGetKeys: [], platformFindAllWheres: [], orderDeliveryLockUpdates: [], + operationLogCreatePayloads: [], }; const state = { @@ -273,16 +274,16 @@ function createContext(options = {}) { return printStation; }, }, - Platform: { + PrintPlatform: { async findAll(query) { calls.platformFindAllWheres.push(query && query.where ? query.where : {}); - const codeList = query && query.where && Array.isArray(query.where.code) - ? query.where.code + const codeList = query && query.where && Array.isArray(query.where.platform_code) + ? query.where.platform_code : []; - return codeList.map(code => ({ - code, - component: Object.prototype.hasOwnProperty.call(platformComponents, code) - ? platformComponents[code] + return codeList.map(platformCode => ({ + platform_code: platformCode, + platform_name: Object.prototype.hasOwnProperty.call(platformComponents, platformCode) + ? platformComponents[platformCode] : '', })); }, @@ -308,6 +309,12 @@ function createContext(options = {}) { sendToComputer, }, }, + operationLog: { + async createOperationLogs(payloads) { + calls.operationLogCreatePayloads.push(payloads); + return payloads.map(() => true); + }, + }, }, }, }; @@ -653,7 +660,7 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { assert.equal(calls.printRecordCreatePayloads.length, 1); assert.deepEqual(calls.sendOrderMarks, [ 'ONLY-CAINIAO' ]); assert.equal(calls.platformFindAllWheres.length, 1); - assert.deepEqual(calls.platformFindAllWheres[0].code, [ 'cainiao' ]); + assert.deepEqual(calls.platformFindAllWheres[0].platform_code, [ 'cainiao' ]); assert.deepEqual(calls.redisGetKeys, [ 'printer:PC-STATION-001:name:菜鸟:status' ]); }); @@ -850,6 +857,68 @@ describe('test/app/service/systemMethods/print.send.test.js', () => { const printStatusUpdate = calls.orderDeliveryLockUpdates.find(item => item && item.payload && item.payload.print_status === 'fin'); assert.ok(printStatusUpdate); assert.deepEqual(printStatusUpdate.query.where.id, [ 101, 102 ]); + + assert.equal(calls.operationLogCreatePayloads.length, 1); + assert.equal(calls.operationLogCreatePayloads[0].length, 2); + assert.equal(calls.operationLogCreatePayloads[0][0].businessType, 'order'); + assert.equal(calls.operationLogCreatePayloads[0][0].operationCode, 'ORDER_PRINT'); + assert.match(calls.operationLogCreatePayloads[0][0].extras.message, /批次发送结束成功/); + }); + + it('type=express 批次失败且有订单ID时应写失败订单操作日志', async () => { + const { ctx, calls } = createContext({ + sendToComputer: async payload => { + calls.sendToComputerPayloads.push(payload); + return { + status: 'failure', + error: '模拟发送失败', + }; + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + requestCode: 'REQ-LOG-FAIL-ORDER', + printStationId: 101, + data: { + waveGroups: [ + { + wave_id: 1, + wave_no: 'WAVE-LOG-FAIL-1', + platforms: [ + { + platform: 'cainiao', + sys_logistics_code: 'STO', + order_ids: [ 501, 502 ], + orders: [ + { + order_id: 501, + print_data: { + documentID: 'DOC-LOG-FAIL-1', + contents: [ + { + marker: 'LOG-FAIL-1', + }, + ], + }, + }, + ], + }, + ], + }, + ], + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 504); + assert.equal(calls.operationLogCreatePayloads.length, 1); + assert.equal(calls.operationLogCreatePayloads[0].length, 2); + assert.equal(calls.operationLogCreatePayloads[0][0].businessId, 501); + assert.equal(calls.operationLogCreatePayloads[0][1].businessId, 502); + assert.match(calls.operationLogCreatePayloads[0][0].extras.message, /批次发送失败/); + assert.match(calls.operationLogCreatePayloads[0][0].extras.message, /模拟发送失败/); }); it('type=express 前批次成功后批次失败时应保持成功批次 print_status 回写', async () => { diff --git a/test/app/service/systemMethods/setting/expressInterface.test.js b/test/app/service/systemMethods/setting/expressInterface.test.js index c70efae..4710438 100644 --- a/test/app/service/systemMethods/setting/expressInterface.test.js +++ b/test/app/service/systemMethods/setting/expressInterface.test.js @@ -192,6 +192,7 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = id: 11, name: '顺丰接口-更新', token: 'token-2', + platformShopId: '8899', sys_express_code: 'SF', weight_type: 3, address: '深圳市南山区', @@ -236,6 +237,7 @@ describe('test/app/service/systemMethods/setting/expressInterface.test.js', () = id: 11, name: '顺丰接口-更新', token: 'token-2', + platform_shop_id: '8899', sys_express_code: 'SF', weight_type: 3, address: '深圳市南山区', diff --git a/test/app/service/systems/setting/expressInterface.test.js b/test/app/service/systems/setting/expressInterface.test.js index 9cbf12d..f80ccf7 100644 --- a/test/app/service/systems/setting/expressInterface.test.js +++ b/test/app/service/systems/setting/expressInterface.test.js @@ -55,6 +55,7 @@ function createHarness(options = {}) { name: '顺丰接口', express_code: 'SF', platform_code: 'TB', + platform_shop_id: 20001, express_platform_id: 1, weight_type: 2, express: { @@ -146,6 +147,7 @@ function createHarness(options = {}) { sys_express_code: {}, warehouse_id: {}, shop_id: {}, + platform_shop_id: {}, sender_name: {}, sender_tel: {}, weight: {}, @@ -433,6 +435,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { express_code: 'SF', sys_express_code: 'SF', platform_code: 'TB', + platform_shop_id: 30001, express_platform_id: 1, express: { code: 'SF', @@ -496,6 +499,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { assert.equal(result.data.page_size, 1); assert.equal(result.data.list[0].name, '顺丰接口'); assert.equal(result.data.list[0].platform_code, 'TB'); + assert.equal(result.data.list[0].platform_shop_id, 30001); assert.equal(result.data.list[0].sys_express_code, 'SF'); assert.equal(result.data.list[0].template_url, 'https://example.com/template/list'); assert.equal(result.data.list[0].is_system_express_code, 1); @@ -975,15 +979,39 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { }); assert.equal(calls.shopFindOneCalls.length, 1); - assert.deepEqual(calls.shopFindOneCalls[0].where, { - id: 301, - warehouse_id: 100000, - }); + assert.equal(calls.shopFindOneCalls[0].where.id, 301); + assert.equal(calls.shopFindOneCalls[0].where.warehouse_id, 100000); assert.equal(calls.updatePayload.updates.shop_id, 301); assert.equal(calls.updatePayload.updates.token, 'shop-access-token-301'); assert.equal(result.data.shop_id, 301); }); + it('should normalize empty platform_shop_id to null when updating', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + platform_shop_id: '', + }); + + assert.equal(calls.updatePayload.updates.platform_shop_id, null); + assert.equal(result.data.platform_shop_id, null); + }); + + it('should normalize numeric platform_shop_id when updating', async () => { + const { ctx, calls } = createHarness(); + const service = new SettingExpressInterfaceService(ctx); + + const result = await service.update({ + id: 11, + platform_shop_id: '20088', + }); + + assert.equal(calls.updatePayload.updates.platform_shop_id, 20088); + assert.equal(result.data.platform_shop_id, 20088); + }); + it('should clear token when shop_id is cleared', async () => { const { ctx, calls } = createHarness(); const service = new SettingExpressInterfaceService(ctx);