diff --git a/.gitignore b/.gitignore index 385db19..3583d4e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ logs/ run/ runtime/ -test_reports/ +test_reports/* temp/* !temp/docs/ !temp/docs/** @@ -9,6 +9,8 @@ node_modules/ coverage/ .nyc_output/ typings/ +tmp/* +test/* npm-debug.log* yarn-debug.log* diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js index 651af3d..8a03b90 100644 --- a/app/lib/polo_api_client.js +++ b/app/lib/polo_api_client.js @@ -43,7 +43,11 @@ class PoloApiClient { console.log('signMap', signMap); const signText = this._getSignText(signMap, config.app_secret); const sign = this._md5(signText); - const formBody = this._encodeForm({ ...signMap, sign }); + // const formBody = this._encodeForm({ ...signMap, sign }); + signMap.sign = sign; + const formBody = Object.keys(signMap) + .map(key => `${key}=${encodeURIComponent(signMap[key])}`) + .join('&'); console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent)); const response = await this.ctx.curl(String(config.interface_url || ''), { method: 'POST', diff --git a/app/model/express.js b/app/model/express.js index 62523e4..261006b 100644 --- a/app/model/express.js +++ b/app/model/express.js @@ -37,8 +37,8 @@ module.exports = app => { allowNull: true, comment: '拼多多编码', }, - DYXD: { - field: 'DYXD', + DY: { + field: 'DY', type: STRING(255), allowNull: true, comment: '抖音编码', diff --git a/app/model/order_express.js b/app/model/order_express.js index 9307653..4e932fc 100644 --- a/app/model/order_express.js +++ b/app/model/order_express.js @@ -1,7 +1,12 @@ 'use strict'; +/** + * 订单快递信息模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ module.exports = app => { - const { BIGINT, STRING, DATE, ENUM, INTEGER, TINYINT, TEXT } = app.Sequelize; + const { BIGINT, STRING, DATE, ENUM, INTEGER, TINYINT, TEXT, DECIMAL } = app.Sequelize; const OrderExpress = app.model.define('order_express', { id: { @@ -117,6 +122,21 @@ module.exports = app => { allowNull: true, comment: '仓库ID', }, + package_material_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID', + }, + package_material_name_snapshot: { + type: STRING(128), + allowNull: true, + comment: '包材名称快照', + }, + weighing_weight: { + type: DECIMAL(10, 3), + allowNull: true, + comment: '称重重量(kg)', + }, }, { tableName: 'wms_order_express', freezeTableName: true, @@ -137,6 +157,10 @@ module.exports = app => { name: 'idx_create_at', fields: [ 'create_at' ], }, + { + name: 'idx_wms_order_express_package_material_id', + fields: [ 'package_material_id' ], + }, ], }); diff --git a/app/model/package_material.js b/app/model/package_material.js new file mode 100644 index 0000000..7911c25 --- /dev/null +++ b/app/model/package_material.js @@ -0,0 +1,114 @@ +'use strict'; + +/** + * 包材信息模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, DECIMAL, TINYINT, INTEGER, DATE } = app.Sequelize; + + const PackageMaterial = app.model.define('package_material', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + material_code: { + type: STRING(64), + allowNull: false, + comment: '包材编码', + }, + material_name: { + type: STRING(128), + allowNull: false, + comment: '包材名称', + }, + material_type: { + type: STRING(32), + allowNull: true, + comment: '包材类型', + }, + spec: { + type: STRING(128), + allowNull: true, + comment: '规格描述', + }, + length: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '长度(cm)', + }, + width: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '宽度(cm)', + }, + height: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '高度(cm)', + }, + weight: { + type: DECIMAL(10, 3), + allowNull: true, + comment: '重量(kg)', + }, + cost_price: { + type: DECIMAL(10, 2), + allowNull: true, + comment: '成本单价', + }, + status: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_package_material', + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: false, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '包材信息表', + indexes: [ + { + name: 'idx_wms_package_material_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'uk_wms_package_material_warehouse_material_code', + unique: true, + fields: [ 'warehouse_id', 'material_code' ], + }, + ], + }); + + return PackageMaterial; +}; diff --git a/app/model/package_supplier.js b/app/model/package_supplier.js new file mode 100644 index 0000000..1306ed1 --- /dev/null +++ b/app/model/package_supplier.js @@ -0,0 +1,89 @@ +'use strict'; + +/** + * 包材供应商模型。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize; + + const PackageSupplier = app.model.define('package_supplier', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + supplier_code: { + type: STRING(64), + allowNull: false, + comment: '供应商编码', + }, + supplier_name: { + type: STRING(128), + allowNull: false, + comment: '供应商名称', + }, + contact_name: { + type: STRING(64), + allowNull: true, + comment: '联系人', + }, + contact_phone: { + type: STRING(32), + allowNull: true, + comment: '联系电话', + }, + status: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_package_supplier', + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: false, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '包材供应商表', + indexes: [ + { + name: 'idx_wms_package_supplier_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'uk_wms_package_supplier_warehouse_supplier_code', + unique: true, + fields: [ 'warehouse_id', 'supplier_code' ], + }, + ], + }); + + return PackageSupplier; +}; diff --git a/app/model/platform.js b/app/model/platform.js index 064448a..ab70628 100644 --- a/app/model/platform.js +++ b/app/model/platform.js @@ -25,16 +25,6 @@ module.exports = app => { allowNull: true, comment: '接口地址', }, - platform_code: { - type: STRING(255), - allowNull: true, - comment: '平台编码', - }, - platid: { - type: INTEGER(11), - allowNull: true, - comment: '平台ID', - }, appkey: { type: STRING(255), allowNull: true, diff --git a/app/model/print_platform.js b/app/model/print_platform.js index c2d2a56..bb45df8 100644 --- a/app/model/print_platform.js +++ b/app/model/print_platform.js @@ -6,7 +6,7 @@ * @return {import('sequelize').ModelCtor} 打印平台元数据模型。 */ module.exports = app => { - const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize; + const { BIGINT, STRING, DATE, TINYINT, INTEGER, TEXT } = app.Sequelize; const PrintPlatform = app.model.define('print_platform', { id: { @@ -31,6 +31,17 @@ module.exports = app => { allowNull: true, comment: '平台ID', }, + request_platform_code: { + type: STRING(50), + allowNull: true, + comment: '请求平台编码', + }, + need_callback_url: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否需要回调地址:0-否,1-是', + }, status: { type: STRING(20), allowNull: false, @@ -43,10 +54,15 @@ module.exports = app => { comment: '备注', }, auth_base_url: { - type: STRING(255), + type: TEXT, allowNull: true, comment: '授权基础地址', }, + get_auth_platform_name: { + type: STRING(100), + allowNull: true, + comment: '获取授权平台名称', + }, create_at: { type: DATE, allowNull: false, diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 81e777d..91c6854 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -179,6 +179,7 @@ function normalizeFirstWrappedArray(values, nestedKeys = []) { * @param {*} standardTemplates 菜鸟标准模板字段 * @return {Array} 标准模板子项列表 */ +// eslint-disable-next-line no-unused-vars function normalizeCainiaoStandardTemplateList(standardTemplates) { return normalizeWrappedArray(standardTemplates, [ 'standard_template_do' ]); } @@ -190,6 +191,7 @@ function normalizeCainiaoStandardTemplateList(standardTemplates) { * @param {Array} templateList 过滤后的标准模板子项列表 * @return {*} 回填后的标准模板字段 */ +// eslint-disable-next-line no-unused-vars function rebuildCainiaoStandardTemplates(standardTemplates, templateList) { if (Array.isArray(standardTemplates)) { return templateList; @@ -242,6 +244,79 @@ function buildPlatformExpressNameMap(expressList, platformCode) { }, {}); } +/** + * 解析并写入快递映射键,兼容原值与大写键。 + * + * @param {Object} targetMap 目标映射表 + * @param {string} rawKey 原始映射键 + * @param {Object} mappingItem 映射值 + */ +function appendExpressMappingKey(targetMap, rawKey, mappingItem) { + const mappingKey = normalizeText(rawKey).trim(); + + if (!mappingKey) { + return; + } + + targetMap[mappingKey] = mappingItem; + const upperKey = mappingKey.toUpperCase(); + + if (!Object.prototype.hasOwnProperty.call(targetMap, upperKey)) { + targetMap[upperKey] = mappingItem; + } +} + +/** + * 构建抖音电子面单快递映射表。 + * + * @param {Array} expressList 系统快递列表 + * @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表 + */ +function buildExpressNameMap(expressList,platformCode = 'DY') { + return normalizeArray(expressList).reduce((result, expressItem) => { + const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; + const mappingItem = { + name: normalizeText(currentExpressItem.name), + sys_express_code: normalizeText(currentExpressItem.code), + }; + + appendExpressMappingKey(result, currentExpressItem[platformCode], mappingItem); + appendExpressMappingKey(result, currentExpressItem.code, mappingItem); + + return result; + }, {}); +} + +/** + * 按候选键顺序匹配首个可用快递映射。 + * + * @param {Object} expressNameMap 快递映射表 + * @param {Array<*>} candidateKeys 候选映射键 + * @return {Object} 命中的快递映射,未命中时返回空对象 + */ +function resolveExpressMapping(expressNameMap, candidateKeys = []) { + const mapObject = expressNameMap && typeof expressNameMap === 'object' ? expressNameMap : {}; + + for (const candidateKey of normalizeArray(candidateKeys)) { + const normalizedKey = normalizeText(candidateKey).trim(); + + if (!normalizedKey) { + continue; + } + + if (mapObject[normalizedKey] && typeof mapObject[normalizedKey] === 'object') { + return mapObject[normalizedKey]; + } + + const upperKey = normalizedKey.toUpperCase(); + if (mapObject[upperKey] && typeof mapObject[upperKey] === 'object') { + return mapObject[upperKey]; + } + } + + return {}; +} + /** * 解析拼多多电子面单网点查询响应,收敛为前端易消费的结构。 * @@ -299,7 +374,7 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { return { branch_code: normalizeText(accountItem.branch_code), branch_name: normalizeText(accountItem.branch_name), - quantity: accountItem.quantity ?? 0, + quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, cancel_quantity: accountItem.cancel_quantity ?? 0, recycled_quantity: accountItem.recycled_quantity ?? 0, allocated_quantity: accountItem.allocated_quantity ?? 0, @@ -330,6 +405,221 @@ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { }; } +/** + * 解析抖音(PolyAPI)电子面单网点查询响应,收敛为与拼多多一致的统一结构。 + * + * @param {*} responseData 抖音原始响应 + * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 + * @return {Object} 解析后的电子面单网点结构 + */ +function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { + const normalizedResponse = responseData && typeof responseData === 'object' + ? responseData + : {}; + const waybillResponse = [ + normalizedResponse.data, + normalizedResponse.result, + normalizedResponse.results, + normalizedResponse, + ].find(item => item && typeof item === 'object') || {}; + + const subscriptions = normalizeFirstWrappedArray([ + waybillResponse.waybill_apply_subscription_cols, + waybillResponse.waybillApplySubscriptionCols, + waybillResponse.waybill_apply_subscription_info, + waybillResponse.waybillApplySubscriptionInfo, + waybillResponse.results, + waybillResponse.result, + waybillResponse.list, + waybillResponse.waybill_condition_list, + waybillResponse.waybillConditionList, + normalizedResponse.results, + normalizedResponse.result, + ], [ 'waybill_apply_subscription_info', 'list', 'waybill_condition', 'waybillCondition' ]); + + const groupedByWpCode = new Map(); + + for (const subscription of subscriptions) { + const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; + const sysExpressCode = normalizeText( + subscriptionItem.sys_express_code + || subscriptionItem.sysExpressCode + || subscriptionItem.express_sys_code + || subscriptionItem.expressSysCode + ); + const wpCode = normalizeText( + subscriptionItem.wp_code + || subscriptionItem.cp_code + || subscriptionItem.cpcode + || subscriptionItem.logistics_code + || subscriptionItem.express_code + ); + const expressMapping = resolveExpressMapping(expressNameMap, [ + subscriptionItem.cp_code, + subscriptionItem.cpcode, + subscriptionItem.wp_code, + subscriptionItem.logistics_code, + subscriptionItem.express_code, + sysExpressCode, + wpCode, + ]); + + const accounts = normalizeFirstWrappedArray([ + subscriptionItem.branch_account_cols, + subscriptionItem.branchAccounts, + subscriptionItem.branch_accounts, + subscriptionItem.accounts, + subscriptionItem.waybill_branch_account, + subscriptionItem.results, + subscriptionItem.result, + subscriptionItem.list, + ], [ 'waybill_branch_account', 'branch_account', 'account', 'results', 'result', 'list' ]).map(account => { + const accountItem = account && typeof account === 'object' ? account : {}; + const customerCodes = normalizeWrappedArray( + accountItem.customer_code_list + || accountItem.customerCodeList + || accountItem.customer_codes + || accountItem.customerCodes, + [ 'string', 'list', 'code' ] + ).map(item => normalizeText(item)).filter(Boolean); + const shipAddresses = normalizeFirstWrappedArray([ + accountItem.shipp_address_cols, + accountItem.ship_addresses, + accountItem.shipAddresses, + accountItem.address_dto, + accountItem.addresses, + accountItem.shippers, + ], [ 'address_dto', 'waybill_address', 'address' ]).map(address => { + const addressItem = address && typeof address === 'object' ? address : {}; + + return { + country: normalizeText(addressItem.country), + province: normalizeText(addressItem.province), + city: normalizeText(addressItem.city || addressItem.town), + district: normalizeText(addressItem.district || addressItem.area), + detail: normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address), + full_address: normalizeText(addressItem.full_address || addressItem.fullAddress || ''), + }; + }); + const services = normalizeFirstWrappedArray([ + accountItem.service_info_cols, + accountItem.service_info_dto, + accountItem.services, + accountItem.serviceInfos, + ], [ 'service_info_dto', 'waybill_service_info', 'service' ]).map(service => { + const serviceItem = service && typeof service === 'object' ? service : {}; + const attributes = normalizeFirstWrappedArray([ + serviceItem.service_attributes, + serviceItem.service_attribute_dto, + serviceItem.attributes, + ], [ 'service_attribute_dto', 'waybill_service_attribute', 'attribute' ]).map(attribute => { + const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; + + return { + attribute_code: normalizeText(attributeItem.attribute_code), + attribute_name: normalizeText(attributeItem.attribute_name), + attribute_type: normalizeText(attributeItem.attribute_type), + type_desc: normalizeText(attributeItem.type_desc || attributeItem.attribute_type_name), + }; + }); + + return { + service_code: normalizeText(serviceItem.service_code), + service_name: normalizeText(serviceItem.service_name), + service_desc: normalizeText(serviceItem.service_desc || serviceItem.description), + required: Boolean(serviceItem.required), + attributes, + }; + }); + console.log("accountItem",subscriptionItem.logisticsaccount,"\n\n") + const result = { + branch_code: accountItem.sitecode, + branch_name: accountItem.sitename, + quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, + cancel_quantity: accountItem.cancel_quantity ?? 0, + recycled_quantity: accountItem.recycled_quantity ?? 0, + allocated_quantity: accountItem.allocated_quantity ?? 0, + ship_addresses: shipAddresses, + services, + }; + if(subscriptionItem.logisticsaccount){ + result.customer_code_list = [subscriptionItem.logisticsaccount]; + } + return result; + }); + + if (!groupedByWpCode.has(wpCode)) { + groupedByWpCode.set(wpCode, { + wp_code: wpCode, + wp_name: normalizeText(expressMapping.name) + || normalizeText(subscriptionItem.wp_name || subscriptionItem.cp_name || subscriptionItem.cpname), + sys_express_code: normalizeText(expressMapping.sys_express_code || sysExpressCode), + wp_type: normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type || subscriptionItem.type), + accounts: [], + shipAddressKeys: new Set(), + }); + } + + const groupedItem = groupedByWpCode.get(wpCode); + + if (!groupedItem.wp_name) { + groupedItem.wp_name = normalizeText(expressMapping.name) + || normalizeText(subscriptionItem.wp_name || subscriptionItem.cp_name || subscriptionItem.cpname); + } + if (!groupedItem.sys_express_code) { + groupedItem.sys_express_code = normalizeText(expressMapping.sys_express_code || sysExpressCode); + } + if (!groupedItem.wp_type) { + groupedItem.wp_type = normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type || subscriptionItem.type); + } + + const dedupedAccounts = accounts.map(accountItem => { + const accountAddressKeys = new Set(); + const dedupedShipAddresses = normalizeArray(accountItem.ship_addresses).filter(addressItem => { + const addressKey = [ + normalizeText(addressItem && addressItem.country), + normalizeText(addressItem && addressItem.province), + normalizeText(addressItem && addressItem.city), + normalizeText(addressItem && addressItem.district), + normalizeText(addressItem && addressItem.detail), + normalizeText(addressItem && addressItem.full_address), + ].join('|'); + + if (accountAddressKeys.has(addressKey) || groupedItem.shipAddressKeys.has(addressKey)) { + return false; + } + + accountAddressKeys.add(addressKey); + groupedItem.shipAddressKeys.add(addressKey); + return true; + }); + + return { + ...accountItem, + ship_addresses: dedupedShipAddresses, + }; + }); + + groupedItem.accounts.push(...dedupedAccounts); + } + + const list = Array.from(groupedByWpCode.values()).map(item => ({ + wp_code: item.wp_code, + wp_name: item.wp_name, + sys_express_code: item.sys_express_code, + wp_type: item.wp_type, + accounts: item.accounts, + })); + + const totalValue = Number(waybillResponse.total); + + return { + request_id: normalizeText(waybillResponse.request_id || normalizedResponse.request_id), + total: Number.isFinite(totalValue) ? totalValue : list.length, + list, + }; +} + /** * 判断是否命中拼多多顺丰定时派送服务。 * @@ -476,7 +766,7 @@ function formatTbWaybillSearchResponse(responseData, expressNameMap = {}) { return { branch_code: normalizeText(accountItem.branch_code) || normalizeText(customerCodes[0]), branch_name: normalizeText(accountItem.branch_name), - quantity: accountItem.quantity ?? 0, + quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, cancel_quantity: accountItem.cancel_quantity ?? 0, recycled_quantity: accountItem.recycled_quantity ?? 0, allocated_quantity: accountItem.allocated_quantity ?? 0, @@ -511,7 +801,7 @@ class indexService extends MainService { */ constructor(ctx) { super(ctx); - const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; + const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl'; const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; const _noNeedLog = '*'; const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl'; @@ -1201,9 +1491,10 @@ class indexService extends MainService { * 已注册模型时,强制以 `wms_print_platform.platform_code` 为准。 * * @param {string} platformCode 打印平台编码 + * @param {boolean} [isAll=false] 是否返回平台完整信息 * @return {Promise} 标准化后的打印平台编码 */ - async ensureShopPrintPlatformExists(platformCode) { + async ensureShopPrintPlatformExists(platformCode, isAll = false) { const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; @@ -1221,13 +1512,15 @@ class indexService extends MainService { deleted: 0, status: 'ACTIVE', }, - attributes: [ 'platform_code' ], + attributes: [ 'platform_code', 'platid' ], }); if (!printPlatform) { throw new Error('platform_code 未匹配到打印平台编码'); } - + if (isAll) { + return printPlatform; + } return normalizedPlatformCode; } @@ -1446,7 +1739,93 @@ class indexService extends MainService { return responseData.cainiao_cloudprint_stdtemplates_get_response.result.datas.standard_template_result || []; } + /** + * 请求菠萝派标准模板并归一化为菜鸟链路兼容数组。 + * + * @param {string} appSecret 菠萝派访问令牌 + * @param {string|number} platid 菠萝派平台标识 + * @return {Promise>} 归一化后的模板数组 + * @throws {Error} 当配置缺失或接口返回失败时抛出异常 + */ + async requestPolyStdTemplates(appSecret,platid) { + const { service } = this; + if(!appSecret || !platid){ + throw new Error('菠萝派接口配置缺失'); + } + const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetTemplates', { + templatestype:"ALL" + }, { + interface_url: 'https://api.polyapi.com/OpenAPI/do', + appkey: this.app.config.poloApi.appKey, + app_secret: this.app.config.poloApi.appSecret, + token:appSecret, + platid: platid, + version: '1.0', + }); + console.log('请求菠萝派标准模板接口响应', JSON.stringify(responseData)); + const normalizedResponseData = responseData && typeof responseData === 'object' + ? { + ...responseData, + code: [ 0, '0', 10000, '10000' ].includes(responseData.code) ? 0 : responseData.code, + results: Array.isArray(responseData.results) && responseData.results.length > 0 + ? responseData.results + : Array.isArray(responseData.data) + ? responseData.data + : responseData.results, + } + : responseData; + if (normalizedResponseData && normalizedResponseData.code !== 0) { + throw new Error(responseData.message || '菠萝派标准模板查询失败'); + } + + const normalizeTemplateItems = items => (Array.isArray(items) ? items : []).map(item => { + const sourceItem = item && typeof item === 'object' ? item : {}; + const { + results: nestedResults, + data: nestedData, + standard_templates: nestedStandardTemplates, + cp_code: itemCpCode, + cpcode: itemCpcode, + cpCode: itemCpCodeCamel, + ...restItem + } = sourceItem; + const standardTemplatesSource = Array.isArray(nestedResults) + ? nestedResults + : Array.isArray(nestedStandardTemplates) + ? nestedStandardTemplates + : Array.isArray(nestedData) + ? nestedData + : []; + const cpCode = itemCpCode ?? itemCpcode ?? itemCpCodeCamel; + + return { + ...restItem, + cp_code: cpCode, + standard_templates: { + standard_template_do: standardTemplatesSource.map(template => { + const sourceTemplate = template && typeof template === 'object' ? template : {}; + + return { + brand_code: sourceTemplate.brand_code || sourceTemplate.brandcode || 'default', + standard_template_id: sourceTemplate.standard_template_id || sourceTemplate.id || '', + standard_template_name: sourceTemplate.standard_template_name || sourceTemplate.name || '', + standard_template_url: sourceTemplate.standard_template_url || sourceTemplate.url || '', + standard_waybill_type: sourceTemplate.standard_waybill_type || sourceTemplate.templatetype || '', + }; + }), + }, + }; + }); + + const normalizedResults = normalizeTemplateItems(normalizedResponseData?.results); + + if (normalizedResults.length > 0) { + return normalizedResults; + } + + return normalizeTemplateItems(normalizedResponseData?.data); + } /** * 获取指定店铺的快递签约列表。 * @@ -1456,7 +1835,7 @@ class indexService extends MainService { * @return {Promise} 返回店铺对应的快递签约列表 */ async getShopExpressList(data = {}) { - const { ctx } = this; + const { ctx, service } = this; const { shop_id: shopIdSnake, shopId: shopIdCamel, @@ -1491,9 +1870,11 @@ class indexService extends MainService { const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; - const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code); + const platformCode_info = await this.ensureShopPrintPlatformExists(shopPlain.platform_code, true); let list = []; - + const platformCode = platformCode_info.platform_code; + const platid = platformCode_info.platid; + console.log('请求的店铺的platformCode', platformCode); switch (platformCode) { case 'PDD': { const accessToken = String(shopPlain.access_token || '').trim(); @@ -1545,6 +1926,42 @@ class indexService extends MainService { list = parsed.list; break; } + case 'DY': { + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList,"DY"); + 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 'KS':{ + const accessToken = String(shopPlain.access_token || '').trim(); + const expressList = await this.service.systems.express.getExpressList(true); + const expressNameMap = buildExpressNameMap(expressList, "KS"); + 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; @@ -1717,9 +2134,10 @@ class indexService extends MainService { * @param {string} platformCode 平台编码 * @return {Promise} 平台模板响应 */ - async requestPrintPlatformTemplateList(platformCode) { + async requestPrintPlatformTemplateList(platformCode,s = null,platid = null) { const platformRequesters = { CAINIAO: async () => await this.requestTbCainiaoStdTemplates(), + KS: async () => await this.requestPolyStdTemplates(s, platid), }; const requester = platformRequesters[platformCode]; @@ -1740,22 +2158,64 @@ class indexService extends MainService { * @param {string} [data.platformCode] 平台编码(驼峰) * @param {string} data.express_code 快递编码(下划线) * @param {string} [data.expressCode] 快递编码(驼峰) + * @param {string} [data.shopId] 店铺ID(驼峰) + * * @return {Promise} 返回模板列表结果 */ async getPrintPlatformTemplateList(data = {}) { + console.log('获取打印平台模板列表请求参数', data); const platformCode = this.normalizeTemplatePlatformCode(data); const expressCode = this.normalizeTemplateExpressCode(data); + const { ctx } = this; + const warehouseId = Number(ctx.user?.store_id); + if (!warehouseId) { + return this.fail('未识别到当前仓库', { code: 400 }); + } + + const rawShopId = data.shop_id !== undefined ? data.shop_id : data.shopId; + const shopId = rawShopId !== undefined && rawShopId !== null && rawShopId !== '' + ? Number(rawShopId) + : null; + let shop = null; + + if (Number.isFinite(shopId) && shopId > 0) { + shop = await ctx.model.Shop.findOne({ + where: { + id: shopId, + warehouse_id: warehouseId, + ...buildNotDeletedShopWhere(this.app), + }, + include: this.buildShopPrintPlatformInclude(true), + }); + } if (!expressCode) { return this.fail('express_code 不能为空', { code: 400 }); } + const shouldBypassCache = Number.isFinite(shopId) && shopId > 0; const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode); - const cached = await this.app.getCacheAsync(cacheKey); + const cached = shouldBypassCache ? null : await this.app.getCacheAsync(cacheKey); + + let accessToken = ''; + let platid = null; + if (shop) { + const shopPlain = typeof shop.get === 'function' + ? shop.get({ plain: true }) + : shop; + + accessToken = String(shopPlain.access_token || '').trim(); + const printPlatformInfo = await this.ensureShopPrintPlatformExists(shopPlain.platform_code, true); + platid = Number(printPlatformInfo && printPlatformInfo.platid); + } + + const hasShopRequestParams = Boolean(accessToken) && Number.isFinite(platid); const responseDataFromSource = cached !== null && cached !== undefined ? cached - : await this.requestPrintPlatformTemplateList(platformCode); + : hasShopRequestParams + ? await this.requestPrintPlatformTemplateList(platformCode, accessToken, platid) + : await this.requestPrintPlatformTemplateList(platformCode); // console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); if (cached === null || cached === undefined) { diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 3b5adbc..9249020 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -2,6 +2,9 @@ const OrderBaseService = require('./base'); +const ORDER_EXPORT_TASK_CACHE_KEY_PREFIX = 'order_export_task_'; +const ORDER_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + class OrderIndexService extends OrderBaseService { /** * 初始化订单系统方法的免登录、免权限、免日志和免鉴权配置。 @@ -10,12 +13,270 @@ class OrderIndexService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail'; - const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail'; - const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail'; + const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; + const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; + const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail,updateExpressWeighingWeight,export,exportTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 提交订单导出任务。 + * + * 入参支持 table_type/module 组合;where 与 sort 语义与订单列表保持一致。 + * 方法层负责任务入队与进度缓存,导出由 systems.orderExport 异步执行。 + * + * @param {Object} data 请求体。 + * @param {string} [data.table_type] 导出表类型(current/history/dispatch/outsourced,兼容模块别名)。 + * @param {string} [data.tableType] 导出表类型(驼峰写法)。 + * @param {string} [data.module] 订单模块名(可选)。 + * @param {string} [data.module_name] 订单模块名(下划线写法)。 + * @param {Object} [data.where] 查询条件。 + * @param {Object} [data.sort] 排序参数。 + * @return {Promise} 统一成功包装响应。 + */ + async export(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + table_type: tableTypeSnake, + tableType: tableTypeCamel, + module: moduleName, + module_name: moduleNameSnake, + where, + sort, + } = requestData; + const taskId = this.generateExportTaskId(); + const tableType = tableTypeSnake || tableTypeCamel || 'current'; + const module = moduleName || moduleNameSnake || ''; + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await this.service.systems.orderExport.exportOrders({ + tableType, + moduleName: module, + where: this.isPlainObject(where) ? { ...where } : {}, + sort: this.isPlainObject(sort) ? { ...sort } : {}, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount, + total_count: safeProgress.totalCount, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询订单导出任务进度。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一成功包装响应。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成订单导出任务ID。 + * @return {string} 任务ID。 + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `order_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID。 + * @param {string} [data.taskId] 任务ID。 + * @return {string} 规范后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取订单导出任务缓存键。 + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${ORDER_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入订单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, ORDER_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[order.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取订单导出任务进度缓存。 + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[order.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } + /** * 订单工作台总列表入口。 * @param {Object} data 请求体。 @@ -157,6 +418,117 @@ class OrderIndexService extends OrderBaseService { }); } + /** + * 更新订单运单的称重重量。 + * + * 规则: + * - 单运单订单:忽略传入 waybill_code,直接更新唯一记录。 + * - 多运单订单:必须传入 waybill_code 且匹配到订单下记录。 + * + * @param {Object} data 请求体。 + * @param {string} [data.waybill_code] 运单号,多运单场景必填。 + * @param {number|string} data.order_id 订单ID。 + * @param {number|string} data.weighing_weight 称重重量(kg)。 + * @return {Promise} 统一成功/失败结构。 + */ + async updateExpressWeighingWeight(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + order_id: orderId, + weighing_weight: weighingWeight, + } = requestData; + + try { + const result = await this.service.systems.orderExpress.updateWeighingWeight({ + orderId, + waybillCode, + weighingWeight, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 400; + return this.fail(error && error.message ? error.message : '更新称重重量失败', { + data: null, + }, statusCode); + } + } + + /** + * 按订单号与运单号绑定包材。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @param {number|string} data.order_id 订单ID。 + * @param {string} data.package_material_code 包材编码。 + * @return {Promise} 统一成功/失败结构。 + */ + async bindExpressPackageMaterial(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + order_id: orderId, + package_material_code: packageMaterialCode = '', + } = requestData; + + try { + const result = await this.service.systems.orderExpress.bindExpressPackageMaterial({ + orderId, + waybillCode, + packageMaterialCode, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500; + return this.fail(error && error.message ? error.message : '绑定包材失败', { + data: null, + }, statusCode); + } + } + + /** + * 根据运单号拉取复核数据。 + * + * method 层仅负责参数解构、systems 转发与统一返回结构。 + * + * @param {Object} data 请求体。 + * @param {string} data.waybill_code 运单号。 + * @return {Promise} 统一成功/失败结构。 + */ + async pullReviewDataByWaybill(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code: waybillCode = '', + } = requestData; + + try { + const result = await this.service.systems.orderReview.pullReviewDataByWaybill({ + waybillCode, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const errorCode = Number(error && error.code); + const statusCode = Number.isFinite(errorCode) && errorCode > 0 ? errorCode : 500; + return this.fail(error && error.message ? error.message : '拉取复核数据失败', { + data: null, + }, statusCode); + } + } + } module.exports = OrderIndexService; diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js index 1c81be7..efd8877 100644 --- a/app/service/systemMethods/order/print.js +++ b/app/service/systemMethods/order/print.js @@ -11,9 +11,9 @@ class OrderPrintService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData'; - const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData'; - const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData'; + const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; + const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; + const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -89,6 +89,65 @@ class OrderPrintService extends OrderBaseService { code: 200, }); } + + /** + * 按分组解锁波次平台打印锁。 + * + * method 层仅负责参数解构与边界校验,具体解锁逻辑由 systems 层实现。 + * + * @param {Object} data 请求体。 + * @param {Array} data.wave_ids 波次ID数组。 + * @param {number|string} data.warehouse_id 仓库ID。 + * @param {string} [data.group_type='platform_express'] 分组类型,支持 platform、platform_express、order。 + * @param {string} [data.unlock_scope='group'] 解锁范围,支持 group、wave。 + * @param {Array} data.groups 分组条件列表。 + * @return {Promise} 统一 success 包装的解锁结果。 + */ + async unlockWavePlatformPrintDataByGroup(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + wave_ids: waveIds, + warehouse_id: warehouseId, + group_type: groupType = 'platform_express', + unlock_scope: unlockScope = 'group', + groups, + } = requestData; + + if (!Array.isArray(waveIds) || waveIds.length === 0) { + throw new Error('wave_ids 必填,且必须为非空数组'); + } + + if (warehouseId === undefined || warehouseId === null || String(warehouseId).trim() === '') { + throw new Error('warehouse_id 必填'); + } + + const normalizedGroupType = String(groupType || '').trim(); + if (![ 'platform', 'platform_express', 'order' ].includes(normalizedGroupType)) { + throw new Error('group_type 仅支持 platform、platform_express、order'); + } + + const normalizedUnlockScope = String(unlockScope || '').trim(); + if (![ 'group', 'wave' ].includes(normalizedUnlockScope)) { + throw new Error('unlock_scope 仅支持 group、wave'); + } + + if (!Array.isArray(groups) || groups.length === 0) { + throw new Error('groups 必填,且必须为非空数组'); + } + + const result = await this.service.systems.orderPrint.unlockWavePlatformPrintDataByGroup({ + waveIds, + warehouseId, + groupType: normalizedGroupType, + unlockScope: normalizedUnlockScope, + groups, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } } module.exports = OrderPrintService; diff --git a/app/service/systemMethods/setting/packageMaterial.js b/app/service/systemMethods/setting/packageMaterial.js new file mode 100644 index 0000000..928e1d5 --- /dev/null +++ b/app/service/systemMethods/setting/packageMaterial.js @@ -0,0 +1,254 @@ +'use strict'; + +const MainService = require('../../main'); + +class packageMaterialService extends MainService { + /** + * 初始化包材设置模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'get,list,create,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'get,list,create,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用包材系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemPackageMaterial(methodName, data, defaultMessage) { + try { + const result = await this.service.systems.setting.packageMaterial[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 归一化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + resolveDeleteIds(data = {}) { + const { + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 查询包材列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async get(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + material_code: { + field: 'material_code', + }, + material_name: { + field: 'material_name', + }, + material_type: { + field: 'material_type', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + return await this.callSystemPackageMaterial('get', payload, '获取包材列表失败'); + } + + /** + * 兼容旧式 list 命名,内部转发至 get。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + return await this.get(data); + } + + /** + * 创建包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const payload = { + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + }; + + return await this.callSystemPackageMaterial('create', payload, '创建包材失败'); + } + + /** + * 更新包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const { + id, + material_id: materialId, + materialId: camelMaterialId, + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId), + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + }; + + return await this.callSystemPackageMaterial('update', payload, '更新包材失败'); + } + + /** + * 删除包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + } = data || {}; + + const payload = { + ids: this.resolveDeleteIds({ + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + }), + }; + + return await this.callSystemPackageMaterial('delete', payload, '删除包材失败'); + } +} + +module.exports = packageMaterialService; diff --git a/app/service/systemMethods/setting/packageSupplier.js b/app/service/systemMethods/setting/packageSupplier.js new file mode 100644 index 0000000..b48770f --- /dev/null +++ b/app/service/systemMethods/setting/packageSupplier.js @@ -0,0 +1,237 @@ +'use strict'; + +const MainService = require('../../main'); + +class packageSupplierService extends MainService { + /** + * 初始化包材供应商设置模块的权限配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'get,list,create,update,delete'; + const _noNeedLog = '*'; + const _noNeedAuth = 'get,list,create,update,delete'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 调用包材供应商系统服务。 + * + * @param {string} methodName 系统服务方法名 + * @param {Object} data 请求参数 + * @param {string} defaultMessage 默认错误信息 + * @return {Promise} 统一返回结果 + */ + async callSystemPackageSupplier(methodName, data, defaultMessage) { + try { + const result = await this.service.systems.setting.packageSupplier[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 归一化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + resolveDeleteIds(data = {}) { + const { + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 查询包材供应商列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async get(data = {}) { + const { + where = {}, + pagination: inputPagination, + page, + page_size: pageSize, + pageSize: camelPageSize, + ...rest + } = data || {}; + + const pagination = { + ...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}), + }; + + if (page !== undefined) { + pagination.page = page; + } + + const resolvedPageSize = pageSize !== undefined ? pageSize : camelPageSize; + if (resolvedPageSize !== undefined) { + pagination.pageSize = resolvedPageSize; + } + + const payload = { + ...rest, + where, + pagination, + }; + + this.prepareWhereContext(payload, { + specialFieldMap: { + id: { + field: 'id', + }, + supplier_code: { + field: 'supplier_code', + }, + supplier_name: { + field: 'supplier_name', + }, + contact_name: { + field: 'contact_name', + }, + contact_phone: { + field: 'contact_phone', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + + return await this.callSystemPackageSupplier('get', payload, '获取包材供应商列表失败'); + } + + /** + * 兼容旧式 list 命名,内部转发至 get。 + * + * @param {Object} data 请求参数 + * @return {Promise} 列表结果 + */ + async list(data = {}) { + return await this.get(data); + } + + /** + * 创建包材供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const { + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const payload = { + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + }; + + return await this.callSystemPackageSupplier('create', payload, '创建包材供应商失败'); + } + + /** + * 更新包材供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const { + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const payload = { + id: id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId), + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + }; + + return await this.callSystemPackageSupplier('update', payload, '更新包材供应商失败'); + } + + /** + * 删除包材供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + } = data || {}; + + const payload = { + ids: this.resolveDeleteIds({ + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + }), + }; + + return await this.callSystemPackageSupplier('delete', payload, '删除包材供应商失败'); + } +} + +module.exports = packageSupplierService; diff --git a/app/service/systemMethods/shops.js b/app/service/systemMethods/shops.js index fd9124c..f7dc841 100644 --- a/app/service/systemMethods/shops.js +++ b/app/service/systemMethods/shops.js @@ -71,14 +71,11 @@ class ShopsMethodService extends MainService { customName: customNameCamel, platform_code: platformCode, platformCode: platformCodeCamel, - shop_name: shopName, - shopName: shopNameCamel, } = data || {}; return await this.callShopsSystem('add', { custom_name: customName !== undefined ? customName : customNameCamel, platform_code: platformCode !== undefined ? platformCode : platformCodeCamel, - shop_name: shopName !== undefined ? shopName : shopNameCamel, }, '新增店铺失败'); } diff --git a/app/service/systems/express.js b/app/service/systems/express.js index c9577c5..9e68ed8 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -1482,12 +1482,175 @@ class ExpressService extends Service { } /** - * 按 sys_platform_code 和 logistics_code 对订单进行分组。 - *【已使用】 - * @param {Array} orders 已规范化的订单列表 - * @return {Array} 分组结果 + * 规范化打印平台编码。 + * + * @param {*} platformCode 原始平台编码。 + * @return {string} 规范化后的平台编码。 */ - groupWaybillOrdersByPlatformAndLogistics(orders = []) { + normalizeWaybillPrintPlatformCode(platformCode) { + return String(platformCode || '').trim(); + } + + /** + * 按系统平台列表加载“系统平台编码 -> 请求平台编码”映射。 + * + * @param {Array} platformList 系统平台列表。 + * @return {Promise>} 映射结果。 + */ + async loadWaybillPrintPlatformCodeMap(platformList = []) { + const { Op } = this.app.Sequelize; + const printPlatformModel = this.ctx.model && this.ctx.model.PrintPlatform; + const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; + + const platformCodeByPrintPlatformIdMap = new Map(); + for (const platform of normalizedPlatformList) { + const platformCode = this.normalizeWaybillPrintPlatformCode(platform && platform.code).toLowerCase(); + const printPlatformId = Number(platform && platform.print_platform_id); + if (!platformCode || !Number.isFinite(printPlatformId) || printPlatformId <= 0) { + continue; + } + + platformCodeByPrintPlatformIdMap.set(printPlatformId, platformCode); + } + + if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { + return new Map(); + } + + const printPlatformRows = await printPlatformModel.findAll({ + where: { + id: { + [Op.in]: Array.from(platformCodeByPrintPlatformIdMap.keys()), + }, + }, + attributes: [ 'id', 'platform_code' ], + raw: true, + }); + + const printPlatformCodeMap = new Map(); + for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { + const printPlatformId = Number(row && row.id); + const platformCode = this.normalizeWaybillPrintPlatformCode(row && row.platform_code); + if (!Number.isFinite(printPlatformId) || printPlatformId <= 0 || !platformCode) { + continue; + } + + const systemPlatformCode = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!systemPlatformCode) { + continue; + } + + printPlatformCodeMap.set(systemPlatformCode, platformCode); + } + + return printPlatformCodeMap; + } + + /** + * 按系统平台列表加载“系统平台编码 -> 异步分流请求平台编码”映射。 + * + * 该映射仅用于运单异步后处理分流,来源必须是 + * `wms_print_platform.request_platform_code`,避免与分组/快递接口匹配使用的 + * `wms_print_platform.platform_code` 语义混用。 + * + * @param {Array} platformList 系统平台列表。 + * @return {Promise>} 映射结果。 + */ + async loadWaybillAsyncRequestPlatformCodeMap(platformList = []) { + const { Op } = this.app.Sequelize; + const printPlatformModel = this.ctx.model && this.ctx.model.PrintPlatform; + const normalizedPlatformList = Array.isArray(platformList) ? platformList : []; + + const platformCodeByPrintPlatformIdMap = new Map(); + for (const platform of normalizedPlatformList) { + const platformCode = this.normalizeWaybillPrintPlatformCode(platform && platform.code).toLowerCase(); + const printPlatformId = Number(platform && platform.print_platform_id); + if (!platformCode || !Number.isFinite(printPlatformId) || printPlatformId <= 0) { + continue; + } + + platformCodeByPrintPlatformIdMap.set(printPlatformId, platformCode); + } + + if (!printPlatformModel || typeof printPlatformModel.findAll !== 'function' || platformCodeByPrintPlatformIdMap.size <= 0) { + return new Map(); + } + + const printPlatformRows = await printPlatformModel.findAll({ + where: { + id: { + [Op.in]: Array.from(platformCodeByPrintPlatformIdMap.keys()), + }, + }, + attributes: [ 'id', 'request_platform_code' ], + raw: true, + }); + + const requestPlatformCodeMap = new Map(); + for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) { + const printPlatformId = Number(row && row.id); + const requestPlatformCode = this.normalizeWaybillPrintPlatformCode(row && row.request_platform_code); + if (!Number.isFinite(printPlatformId) || printPlatformId <= 0 || !requestPlatformCode) { + continue; + } + + const systemPlatformCode = platformCodeByPrintPlatformIdMap.get(printPlatformId); + if (!systemPlatformCode) { + continue; + } + + requestPlatformCodeMap.set(systemPlatformCode, requestPlatformCode); + } + + return requestPlatformCodeMap; + } + + /** + * 解析运单异步分流所需的请求平台编码。 + * + * @param {string} sysPlatformCode 订单系统平台编码。 + * @param {Map} [requestPlatformCodeMap=new Map()] 系统平台到请求平台编码映射。 + * @return {string} 请求平台编码;未命中时返回空字符串。 + */ + resolveWaybillAsyncRequestPlatformCode(sysPlatformCode = '', requestPlatformCodeMap = new Map()) { + const normalizedSysPlatformCode = this.normalizeWaybillPrintPlatformCode(sysPlatformCode).toLowerCase(); + if (!normalizedSysPlatformCode) { + return ''; + } + + return requestPlatformCodeMap instanceof Map + ? this.normalizeWaybillPrintPlatformCode(requestPlatformCodeMap.get(normalizedSysPlatformCode)) + : ''; + } + + /** + * 解析运单分组所需的打印平台编码。 + * + * @param {string} sysPlatformCode 订单系统平台编码。 + * @param {Map} printPlatformCodeMap 打印平台编码映射。 + * @return {string} 打印平台编码;未命中时回退系统平台编码。 + */ + resolveWaybillGroupPrintPlatformCode(sysPlatformCode = '', printPlatformCodeMap = new Map()) { + const normalizedSysPlatformCode = this.normalizeWaybillPrintPlatformCode(sysPlatformCode).toLowerCase(); + if (!normalizedSysPlatformCode) { + return ''; + } + + const mappedPrintPlatformCode = printPlatformCodeMap instanceof Map + ? this.normalizeWaybillPrintPlatformCode(printPlatformCodeMap.get(normalizedSysPlatformCode)) + : ''; + + return mappedPrintPlatformCode; + } + + /** + * 按打印平台编码和 logistics_code 对订单进行分组。 + *【已使用】 + * @param {Array} orders 已规范化的订单列表。 + * @param {Map} [printPlatformCodeMap=new Map()] 系统平台到打印平台编码映射。 + * @return {Array} 分组结果。 + */ + groupWaybillOrdersByPlatformAndLogistics(orders = [], printPlatformCodeMap = new Map()) { // 【step2】按平台 + 快递编码+货主id分组,后续按组串行处理。 const groupedOrders = []; @@ -1500,17 +1663,19 @@ class ExpressService extends Service { const sysPlatformCode = String(order.sys_platform_code || '').trim(); const logisticsCode = String(order.logistics_code || '').trim(); - if (!sysPlatformCode || !logisticsCode) { + const printPlatformCode = this.resolveWaybillGroupPrintPlatformCode(sysPlatformCode, printPlatformCodeMap); + if (!sysPlatformCode || !logisticsCode || !printPlatformCode) { continue; } - const groupKey = `${sysPlatformCode}:${logisticsCode}:${order.store_id || 0}`; + const groupKey = `${printPlatformCode}:${logisticsCode}:${order.store_id || 0}`; let groupedOrder = groupedOrderMap.get(groupKey); if (!groupedOrder) { groupedOrder = { options: { sys_platform_code: sysPlatformCode, + print_platform_code: printPlatformCode, logistics_code: logisticsCode, sys_platform_name: order.sys_platform_name || '', logistics_name: order.logistics_name || '', @@ -1575,11 +1740,15 @@ class ExpressService extends Service { } const platformCode = normalizeCode( - matchedPlatform - && matchedPlatform.code - || groupedOrder + groupedOrder && groupedOrder.options - && groupedOrder.options.sys_platform_code + && groupedOrder.options.print_platform_code + || matchedPlatform + && matchedPlatform.route_platform_code + || matchedPlatform + && matchedPlatform.default_express_interface + || matchedPlatform + && matchedPlatform.print_platform_code ); for (const item of Array.isArray(interfaceList) ? interfaceList : []) { @@ -1957,7 +2126,7 @@ class ExpressService extends Service { } /** - * 将统一业务数据骨架按平台编码分流。 + * 将统一业务数据骨架按wms_print_platform.request_platform_code分流。 * * 直接调用平台服务实例上的同名方法;如果方法不存在,或平台方法返回失败结果,则向上抛出异常。 * @@ -1997,14 +2166,15 @@ class ExpressService extends Service { /** * 解析运单后处理分发平台编码。 * - * 优先使用平台路由编码,未提供时兼容历史字段。 + * 优先使用 `wms_print_platform.request_platform_code`,未提供时兼容历史字段。 * * @param {Object} [matchedPlatform={}] 平台匹配信息。 * @return {string} 后处理分发平台编码。 */ resolveWaybillAsyncDispatchPlatformCode(matchedPlatform = {}) { return String( - matchedPlatform.route_platform_code + matchedPlatform.request_platform_code + || matchedPlatform.route_platform_code || matchedPlatform.platform_code || matchedPlatform.code || matchedPlatform.default_express_interface @@ -2118,7 +2288,7 @@ class ExpressService extends Service { /** * 按分组和批次顺序初始化订单运单表。 * - * 先标准化订单,再按 sys_platform_code 和 logistics_code 分组, + * 先标准化订单,再按 print_platform_code 和 logistics_code 分组, * 最后按每批最多 10 条的规则顺序调用现有 createWaybillCode。 * business_key 支持单值或数组输入,内部会展开成多条记录后再分组批处理。 *【已使用】 @@ -2176,7 +2346,10 @@ class ExpressService extends Service { business_key: matchedExpress ? matchedExpress.business_key : 1, }; }); - const groupedOrders = this.groupWaybillOrdersByPlatformAndLogistics(ordersWithExpress); + const platformList = await this.service.systems.platform.getPlatformList(true, true); + const printPlatformCodeMap = await this.loadWaybillPrintPlatformCodeMap(platformList); + const requestPlatformCodeMap = await this.loadWaybillAsyncRequestPlatformCodeMap(platformList); + const groupedOrders = this.groupWaybillOrdersByPlatformAndLogistics(ordersWithExpress, printPlatformCodeMap); this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 平台物流分组结果', { traceId, @@ -2184,14 +2357,18 @@ class ExpressService extends Service { }); // 【step2】按平台 + 快递编码分组,后续按组串行处理。 - const platformList = await this.service.systems.platform.getPlatformList(true, true); for (const groupedOrder of groupedOrders) { const matchedPlatform = platformList.find(platform => String(platform.code || '').trim().toLowerCase() === String(groupedOrder.options.sys_platform_code || '').trim().toLowerCase()); + const matchedPlatformWithRequestCode = matchedPlatform ? { + ...matchedPlatform, + request_platform_code: this.resolveWaybillAsyncRequestPlatformCode( + groupedOrder.options.sys_platform_code, + requestPlatformCodeMap + ) || String(matchedPlatform.request_platform_code || '').trim(), + } : null; const batches = this.splitWaybillOrdersIntoBatches(groupedOrder.orders); const expressInterfacePlatformCode = String( - matchedPlatform && matchedPlatform.default_express_interface - || groupedOrder.options.sys_platform_code - || '' + groupedOrder.options.print_platform_code || '' ).trim(); const listByWarehousePlatformCode = expressInterfacePlatformCode ? await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({ @@ -2202,18 +2379,21 @@ class ExpressService extends Service { const expressInterface = this.pickWaybillExpressInterface( listByWarehousePlatformCode && listByWarehousePlatformCode.data, groupedOrder, - matchedPlatform + matchedPlatformWithRequestCode ); this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 分组前置条件检查', { traceId, warehouseId, storeId: groupedOrder.options.store_id || 0, sysPlatformCode: groupedOrder.options.sys_platform_code, + printPlatformCode: groupedOrder.options.print_platform_code, expressInterfacePlatformCode, logisticsCode: groupedOrder.options.logistics_code, - matchedPlatformCode: matchedPlatform && matchedPlatform.code, + matchedPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.code, + requestPlatformCode: matchedPlatformWithRequestCode && matchedPlatformWithRequestCode.request_platform_code, hasExpressInterface: Boolean(expressInterface), }); + // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 const expressInterfaceConfig = expressInterface ? { ...expressInterface, @@ -2225,7 +2405,7 @@ class ExpressService extends Service { ...groupedOrder.options, trace_id: traceId, warehouse_id: warehouseId, - }, matchedPlatform, expressInterfaceConfig); + }, matchedPlatformWithRequestCode, expressInterfaceConfig); } } this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', { @@ -2343,6 +2523,7 @@ class ExpressService extends Service { orderCount: Array.isArray(orders) ? orders.length : 0, orderIds: (Array.isArray(orders) ? orders : []).slice(0, 50).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0), platformCode: matchedPlatform && matchedPlatform.code, + requestPlatformCode: matchedPlatform && matchedPlatform.request_platform_code, routePlatformCode: this.resolveWaybillAsyncDispatchPlatformCode(matchedPlatform), defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface, warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id, diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index a14e6d1..a8d5769 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -430,7 +430,7 @@ class ExpressPlatformService extends MainService { api: 'Differ.JH.LogisticsPlatFeatures', response: Dictionary_result, }); - + console.log("listByWarehousePlatformCode",listByWarehousePlatformCode) const order_bizcontent = { orders: orders.map(order_tmp => { const order = order_tmp.order_delivery; @@ -442,7 +442,6 @@ class ExpressPlatformService extends MainService { logistictype: order.logistics_code || '', numpackage: order.package_count || 1, businesstype: 'JH_Normal', - businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', paymode: listByWarehousePlatformCode.paymode ?? 1, ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', @@ -466,7 +465,7 @@ class ExpressPlatformService extends MainService { ordersource: matchedPlatform.ordersource || '', inputsite: listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', - shipperno: listByWarehousePlatformCode.client_id || '', + shipperno: listByWarehousePlatformCode.shipperno || '', sender: { company: listByWarehousePlatformCode.shop_name || '', name: listByWarehousePlatformCode.sender_name || '', @@ -500,6 +499,7 @@ class ExpressPlatformService extends MainService { count: item.plan_qty || 0, }))) || [], Mallmaskid: '', + template_url: matchedPlatform.template_url || '', labelformat: listByWarehousePlatformCode.labelformat || '', extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '', @@ -555,6 +555,7 @@ class ExpressPlatformService extends MainService { logistics_interface_name: listByWarehousePlatformCode.name || '', platform_code: listByWarehousePlatformCode.platform_code || '', status: 1, + retry_count: 0, }, orderDeliveryValues: { @@ -564,7 +565,7 @@ class ExpressPlatformService extends MainService { }; }); break; - case 'DYXD': + case 'DY': successUpdates = (result.results || []).map(item => { const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); const waybillCode = resolveWaybillCode(item); @@ -877,7 +878,6 @@ class ExpressPlatformService extends MainService { const normalizedTemplateUrl = isValidCainiaoTemplateUrl(matchedPlatform.template_url) ? String(matchedPlatform.template_url).trim() : DEFAULT_CAINIAO_TEMPLATE_URL; - if (!appKey || !appSecret) { throw new Error('淘宝接口配置缺失'); } @@ -938,7 +938,9 @@ class ExpressPlatformService extends MainService { notify_extend_info: normalizedExtData, }; - tradeOrderInfo.template_url = listByWarehousePlatformCode.template_url; + tradeOrderInfo.template_url = isValidCainiaoTemplateUrl(listByWarehousePlatformCode.template_url) + ? String(listByWarehousePlatformCode.template_url).trim() + : normalizedTemplateUrl; return tradeOrderInfo; } diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 47afb68..0dbdabe 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -41,11 +41,12 @@ class operationLogService extends Service { business_type: businessType, business_id: String(businessId), operation_code: operationCode, - operator_id: operator?.id || null, - operator_name: operator?.name || null, + // 使用 nullish 合并符,确保当 operator.id 为 0 时仍然保留 0 + operator_id: operator?.id ?? null, + operator_name: operator?.name ?? null, external_log_type: extras.externalLogType || 'NONE', - external_log_id: extras.externalLogId || null, - warehouse_id: extras.warehouseId || null, + external_log_id: extras.externalLogId ?? null, + warehouse_id: extras.warehouseId ?? null, before_changes: beforeChanges, platform_code: ctx.user?.platform_code || 'SYSTEM', message: extras.message || null, diff --git a/app/service/systems/order_export.js b/app/service/systems/order_export.js new file mode 100644 index 0000000..0ab5d2e --- /dev/null +++ b/app/service/systems/order_export.js @@ -0,0 +1,477 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const OrderBaseService = require('../systemMethods/order/base'); + +const DEFAULT_EXPORT_PAGE_SIZE = 200; +const ORDER_EXPORT_WORKSHEET_NAME = '订单导出'; +const ORDER_EXPORT_ALLOWED_TABLE_TYPES = new Set([ 'current', 'history', 'dispatch', 'outsourced' ]); +const ORDER_EXPORT_MODULE_MAP = Object.freeze({ + order: 'order', + revieworder: 'reviewOrder', + pendingorder: 'pendingOrder', + outboundorder: 'outboundOrder', + expectionorder: 'expectionOrder', + archiveorder: 'archiveOrder', + entrustorder: 'entrustOrder', + deliveryorder: 'deliveryOrder', + deliveryexpectionorder: 'deliveryExpectionOrder', +}); +const ORDER_EXPORT_COLUMNS = Object.freeze([ + { header: '订单ID', key: 'id', width: 12 }, + { header: '订单号', key: 'delivery_order_code', width: 24 }, + { header: '外部单号', key: 'external_order_code', width: 24 }, + { header: '订单状态', key: 'status', width: 16 }, + { header: '步骤', key: 'step', width: 10 }, + { header: '波次号', key: 'wave_no', width: 18 }, + { header: '仓库ID', key: 'warehouse_id', width: 12 }, + { header: '货主ID', key: 'store_id', width: 12 }, + { header: '平台', key: 'sys_platform_name', width: 16 }, + { header: '店铺昵称', key: 'shop_nick', width: 20 }, + { header: '卖家昵称', key: 'seller_nick', width: 20 }, + { header: '买家昵称', key: 'buyer_nick', width: 20 }, + { header: '物流公司', key: 'logistics_name', width: 18 }, + { header: '运单号', key: 'express_numbers', width: 28 }, + { header: '商品种数', key: 'items_count', width: 12 }, + { header: '商品件数', key: 'items_total', width: 12 }, + { header: '总重量', key: 'items_weight', width: 12 }, + { header: '订单金额', key: 'total_amount', width: 14 }, + { header: '实收金额', key: 'got_amount', width: 14 }, + { header: '创建时间', key: 'create_at', width: 20 }, + { header: '支付时间', key: 'pay_time', width: 20 }, + { header: '发货时间', key: 'delivery_time', width: 20 }, + { header: '出库状态', key: 'outbound_status', width: 14 }, + { header: '复核状态', key: 'inspection_status', width: 14 }, + { header: '配货状态', key: 'post_status', width: 14 }, + { header: '打包状态', key: 'pack_status', width: 14 }, + { header: '归档时间', key: 'archive_time', width: 20 }, +]); + +/** + * 订单导出系统服务。 + * 负责复用订单列表查询语义,按页拉取数据并流式写入本地 xlsx 后上传。 + */ +class OrderExportService extends OrderBaseService { + /** + * 获取单页导出数量。 + * @return {number} 单页导出数量。 + */ + getExportPageSize() { + return DEFAULT_EXPORT_PAGE_SIZE; + } + + /** + * 规范订单导出模块名。 + * @param {string} moduleName 原始模块名。 + * @return {string} 规范后的模块名;为空时返回空字符串。 + */ + normalizeExportModuleName(moduleName = '') { + const normalizedModuleName = String(moduleName || '').trim(); + if (!normalizedModuleName) { + return ''; + } + + const mappedModuleName = ORDER_EXPORT_MODULE_MAP[normalizedModuleName.toLowerCase()]; + if (!mappedModuleName) { + throw new Error(`不支持的订单导出模块: ${normalizedModuleName}`); + } + + return mappedModuleName; + } + + /** + * 根据表类型推导默认排序所使用的模块名。 + * @param {string} tableType 订单表类型。 + * @return {string} 用于排序默认值的模块名。 + */ + getSortModuleNameByTableType(tableType = 'current') { + switch (tableType) { + case 'history': + return 'archiveOrder'; + case 'dispatch': + return 'deliveryOrder'; + case 'outsourced': + return 'entrustOrder'; + case 'current': + default: + return 'order'; + } + } + + /** + * 解析订单导出目标,兼容 module/module_name 与 table_type 两种写法。 + * @param {Object} options 解析参数。 + * @param {string} [options.moduleName] 模块名。 + * @param {string} [options.tableType] 表类型。 + * @return {{ tableType: string, defaultWhereModuleName: string, sortModuleName: string }} 导出目标。 + */ + resolveExportTarget(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const moduleName = this.normalizeExportModuleName(safeOptions.moduleName || ''); + const rawTableType = String(safeOptions.tableType || '').trim(); + const tableTypeToken = rawTableType.toLowerCase(); + const moduleNameFromTableType = ORDER_EXPORT_ALLOWED_TABLE_TYPES.has(tableTypeToken) + ? '' + : this.normalizeExportModuleName(rawTableType); + const resolvedTableType = rawTableType + ? this.resolveOrderTableType({ tableType: rawTableType }) + : (moduleName ? this.getModuleConfig(moduleName).modelType : 'current'); + + if (moduleName && moduleNameFromTableType && moduleName !== moduleNameFromTableType) { + throw new Error(`module 与 table_type 不匹配: ${moduleName} / ${rawTableType}`); + } + + if (moduleName) { + const expectedTableType = this.getModuleConfig(moduleName).modelType; + if (expectedTableType !== resolvedTableType) { + throw new Error(`module ${moduleName} 仅支持 ${expectedTableType} 表,当前传入 ${resolvedTableType}`); + } + } + + return { + tableType: resolvedTableType, + defaultWhereModuleName: moduleName || moduleNameFromTableType || '', + sortModuleName: moduleName || moduleNameFromTableType || this.getSortModuleNameByTableType(resolvedTableType), + }; + } + + /** + * 获取订单导出列配置。 + * @return {Array} 导出列配置。 + */ + getOrderExportColumns() { + return ORDER_EXPORT_COLUMNS.map(column => ({ ...column })); + } + + /** + * 生成订单导出文件名。 + * @param {Object} target 导出目标。 + * @return {string} 文件名。 + */ + buildOrderExportFilename(target = {}) { + const safeTarget = this.isPlainObject(target) ? target : {}; + const timestamp = new Date(); + const year = timestamp.getFullYear(); + const month = String(timestamp.getMonth() + 1).padStart(2, '0'); + const day = String(timestamp.getDate()).padStart(2, '0'); + const hour = String(timestamp.getHours()).padStart(2, '0'); + const minute = String(timestamp.getMinutes()).padStart(2, '0'); + const second = String(timestamp.getSeconds()).padStart(2, '0'); + const moduleTag = safeTarget.defaultWhereModuleName || safeTarget.tableType || 'current'; + + return `订单导出_${moduleTag}_${year}${month}${day}${hour}${minute}${second}.xlsx`; + } + + /** + * 生成上传 key。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} tableType 表类型。 + * @return {string} 上传 key。 + */ + buildUploadKey(warehouseId, tableType) { + const safeWarehouseId = String(warehouseId || 'unknown').trim() || 'unknown'; + const safeTableType = String(tableType || 'current').trim() || 'current'; + const randomToken = crypto.randomBytes(6).toString('hex'); + return `exports/order/${safeWarehouseId}/${safeTableType}/${Date.now()}_${randomToken}.xlsx`; + } + + /** + * 将模型行转换为普通对象。 + * @param {Object} row 模型行或普通对象。 + * @return {Object} 普通对象。 + */ + toPlainRow(row = {}) { + if (row && typeof row.get === 'function') { + return row.get({ plain: true }); + } + + return this.isPlainObject(row) ? { ...row } : {}; + } + + /** + * 规范导出单元格值。 + * @param {*} value 原始值。 + * @return {string|number} 规范后的值。 + */ + normalizeExportCellValue(value) { + if (value === null || value === undefined) { + return ''; + } + + if (Array.isArray(value)) { + return value.map(item => this.normalizeExportCellValue(item)).filter(Boolean).join(','); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (typeof value === 'object') { + return JSON.stringify(value); + } + + return value; + } + + /** + * 映射单行订单导出数据。 + * @param {Object} orderRow 订单行。 + * @return {Object} 导出行。 + */ + mapOrderExportRow(orderRow = {}) { + const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; + const expressNumbers = Array.isArray(safeOrderRow.express_numbers) + ? safeOrderRow.express_numbers + : Array.isArray(safeOrderRow.waybill_codes) + ? safeOrderRow.waybill_codes + : []; + const externalOrderCode = safeOrderRow.pre_delivery_order_code || safeOrderRow.source_order_codes || ''; + + return { + id: this.normalizeExportCellValue(safeOrderRow.id), + delivery_order_code: this.normalizeExportCellValue(safeOrderRow.delivery_order_code), + external_order_code: this.normalizeExportCellValue(externalOrderCode), + status: this.normalizeExportCellValue(safeOrderRow.status), + step: this.normalizeExportCellValue(safeOrderRow.step), + wave_no: this.normalizeExportCellValue(safeOrderRow.wave_no), + warehouse_id: this.normalizeExportCellValue(safeOrderRow.warehouse_id), + store_id: this.normalizeExportCellValue(safeOrderRow.store_id), + sys_platform_name: this.normalizeExportCellValue(safeOrderRow.sys_platform_name), + shop_nick: this.normalizeExportCellValue(safeOrderRow.shop_nick), + seller_nick: this.normalizeExportCellValue(safeOrderRow.seller_nick), + buyer_nick: this.normalizeExportCellValue(safeOrderRow.buyer_nick), + logistics_name: this.normalizeExportCellValue(safeOrderRow.logistics_name), + express_numbers: this.normalizeExportCellValue(expressNumbers), + items_count: this.normalizeExportCellValue(safeOrderRow.items_count), + items_total: this.normalizeExportCellValue(safeOrderRow.items_total), + items_weight: this.normalizeExportCellValue(safeOrderRow.items_weight), + total_amount: this.normalizeExportCellValue(safeOrderRow.total_amount), + got_amount: this.normalizeExportCellValue(safeOrderRow.got_amount), + create_at: this.normalizeExportCellValue(safeOrderRow.create_at), + pay_time: this.normalizeExportCellValue(safeOrderRow.pay_time), + delivery_time: this.normalizeExportCellValue(safeOrderRow.delivery_time), + outbound_status: this.normalizeExportCellValue(safeOrderRow.outbound_status), + inspection_status: this.normalizeExportCellValue(safeOrderRow.inspection_status), + post_status: this.normalizeExportCellValue(safeOrderRow.post_status), + pack_status: this.normalizeExportCellValue(safeOrderRow.pack_status), + archive_time: this.normalizeExportCellValue(safeOrderRow.archive_time), + }; + } + + /** + * 上传本地导出文件并记录文件信息。 + * @param {Object} options 上传参数。 + * @param {string} options.filePath 本地文件路径。 + * @param {string} options.filename 文件名。 + * @param {number|string} options.warehouseId 仓库ID。 + * @param {string} options.tableType 表类型。 + * @return {Promise} 上传结果。 + */ + async uploadOrderExportFile(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const { + filePath, + filename, + warehouseId, + tableType, + } = safeOptions; + const uploadService = this.ctx?.service?.systems?.upload; + + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const uploadKey = this.buildUploadKey(warehouseId, tableType); + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'orderExport', + businessId: `${warehouseId}:${tableType}`, + uploaderType: this.ctx?.user?.role || 'system_api', + uploaderDept: this.ctx?.user?.department || '', + }); + } + + return { + filename, + fileKey: uploadResult.fileName, + url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '', + cdnUrl: uploadResult.cdnUrl || uploadResult.url || '', + cosUrl: uploadResult.cosUrl || '', + fileRecord: fileRecord?.data || fileRecord || null, + }; + } + + /** + * 导出订单列表。 + * @param {Object} options 导出参数。 + * @param {string} [options.tableType] 表类型。 + * @param {string} [options.moduleName] 模块名。 + * @param {Object} [options.where] 查询条件。 + * @param {Object} [options.sort] 排序参数。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} 上传结果与统计信息。 + */ + async exportOrders(options = {}) { + const safeOptions = this.isPlainObject(options) ? options : {}; + const target = this.resolveExportTarget({ + tableType: safeOptions.tableType, + moduleName: safeOptions.moduleName, + }); + const warehouseId = this.getWarehouseId(); + const requestData = { + where: this.isPlainObject(safeOptions.where) ? { ...safeOptions.where } : {}, + sort: this.isPlainObject(safeOptions.sort) ? { ...safeOptions.sort } : {}, + }; + const progressHandler = typeof safeOptions.onProgress === 'function' + ? safeOptions.onProgress + : async () => {}; + const { where } = this.prepareWhereContext(requestData, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where); + const mergedWhere = this.mergeWhereObjects( + target.defaultWhereModuleName ? this.getDefaultWhere(target.defaultWhereModuleName) : {}, + sanitizedWhere + ); + let queryWhere = this.buildWhere(mergedWhere, warehouseId, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + + if (expressNumbers.length > 0) { + const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, warehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); + } + + const orderModel = await this.getOrderModelByTableType(target.tableType, warehouseId); + const pageSize = this.getExportPageSize(); + const order = this.buildListOrder(requestData.sort, target.sortModuleName); + const totalCount = await orderModel.count({ where: queryWhere }); + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-order-export-')); + const filename = this.buildOrderExportFilename(target); + const filePath = path.join(tempDir, filename); + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + const worksheet = workbook.addWorksheet(ORDER_EXPORT_WORKSHEET_NAME); + worksheet.columns = this.getOrderExportColumns(); + + let currentCount = 0; + let page = 1; + + try { + await progressHandler({ + status: 'running', + progress: totalCount > 0 ? 5 : 90, + currentCount, + totalCount, + message: totalCount > 0 ? `已命中 ${totalCount} 条订单,开始导出` : '未命中数据,开始生成空文件', + }); + + while (currentCount < totalCount) { + const rows = await orderModel.findAll({ + where: queryWhere, + limit: pageSize, + offset: (page - 1) * pageSize, + order, + raw: true, + }); + + if (!Array.isArray(rows) || rows.length === 0) { + break; + } + + const normalizedRows = await this.attachOrderExpressNumbers( + rows.map(row => this.normalizeOrderListItem(this.toPlainRow(row))) + ); + + for (const row of normalizedRows) { + worksheet.addRow(this.mapOrderExportRow(row)).commit(); + } + + currentCount += normalizedRows.length; + + await progressHandler({ + status: 'running', + progress: Math.min(99, Math.max(5, Math.round((currentCount / Math.max(totalCount, 1)) * 90))), + currentCount, + totalCount, + message: `正在导出第 ${page} 页,共 ${Math.ceil(totalCount / pageSize) || 1} 页`, + }); + + page += 1; + } + + worksheet.commit(); + await workbook.commit(); + + const uploadResult = await this.uploadOrderExportFile({ + filePath, + filename, + warehouseId, + tableType: target.tableType, + }); + + await progressHandler({ + status: 'success', + progress: 100, + currentCount, + totalCount, + message: '导出任务完成', + result: uploadResult, + }); + + return { + ...uploadResult, + table_type: target.tableType, + module_name: target.defaultWhereModuleName || '', + current_count: currentCount, + total_count: totalCount, + }; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + throw error; + } finally { + await fsp.rm(tempDir, { recursive: true, force: true }); + } + } +} + +module.exports = OrderExportService; diff --git a/app/service/systems/order_express.js b/app/service/systems/order_express.js new file mode 100644 index 0000000..1d84684 --- /dev/null +++ b/app/service/systems/order_express.js @@ -0,0 +1,324 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 订单快递业务服务。 + * + * 负责订单快递记录的读取与称重重量更新。 + */ +class OrderExpressService extends Service { + /** + * 创建带业务错误码的异常对象。 + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 规范化并校验订单ID。 + * @param {number|string} orderId 订单ID。 + * @return {number} 合法订单ID。 + */ + normalizeOrderId(orderId) { + const normalizedOrderId = Number(orderId || 0); + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('order_id 必填且必须为正整数', 400); + } + + return normalizedOrderId; + } + + /** + * 规范化并校验运单号。 + * @param {string} waybillCode 运单号。 + * @return {string} 合法运单号。 + */ + normalizeWaybillCode(waybillCode) { + const normalizedWaybillCode = String(waybillCode || '').trim(); + + if (!normalizedWaybillCode) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedWaybillCode; + } + + /** + * 规范化并校验包材编码。 + * @param {string} packageMaterialCode 包材编码。 + * @return {string} 合法包材编码。 + */ + normalizePackageMaterialCode(packageMaterialCode) { + const normalizedCode = String(packageMaterialCode || '').trim().toUpperCase(); + + if (!normalizedCode) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedCode; + } + + /** + * 规范化并校验绑定包材场景的订单ID。 + * @param {number|string} orderId 订单ID。 + * @return {number} 合法订单ID。 + */ + normalizeBindOrderId(orderId) { + const normalizedOrderId = Number(orderId || 0); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedOrderId; + } + + /** + * 获取当前仓库 ID。 + * @return {number} 当前仓库 ID。 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx && this.ctx.user ? this.ctx.user.store_id : 0); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createBusinessError('参数错误', 400); + } + + return warehouseId; + } + + /** + * 根据包材编码查询当前仓库启用中的包材。 + * @param {string} packageMaterialCode 包材编码。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 包材记录。 + */ + async findActivePackageMaterialByCode(packageMaterialCode, warehouseId) { + const packageMaterialModel = this.ctx.model && this.ctx.model.PackageMaterial; + if (!packageMaterialModel || typeof packageMaterialModel.findOne !== 'function') { + throw this.createBusinessError('包材模型未初始化', 500); + } + + const materialRow = await packageMaterialModel.findOne({ + where: { + warehouse_id: warehouseId, + material_code: packageMaterialCode, + status: 1, + }, + attributes: [ 'id', 'material_code', 'material_name', 'warehouse_id', 'status' ], + raw: true, + }); + + if (!materialRow) { + throw this.createBusinessError('包材编码不存在', 404); + } + + return materialRow; + } + + /** + * 根据订单号与运单号查询有效订单快递记录。 + * @param {number} orderId 订单 ID。 + * @param {string} waybillCode 运单号。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 订单快递记录。 + */ + async findValidOrderExpressByOrderAndWaybill(orderId, waybillCode, warehouseId) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('订单快递模型未初始化', 500); + } + + const orderExpressRow = await orderExpressModel.findOne({ + where: { + order_id: orderId, + waybill_code: waybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at' ], + raw: true, + }); + + if (!orderExpressRow) { + throw this.createBusinessError('订单运单记录不存在', 404); + } + + return orderExpressRow; + } + + /** + * 规范化并校验称重重量。 + * + * 允许最多 3 位小数,且必须大于 0。 + * + * @param {number|string} weighingWeight 称重重量。 + * @return {number} 合法重量数值。 + */ + normalizeWeighingWeight(weighingWeight) { + if (weighingWeight === null || weighingWeight === undefined || String(weighingWeight).trim() === '') { + throw this.createBusinessError('weighing_weight 必填', 400); + } + + const normalizedWeightText = String(weighingWeight).trim(); + if (!/^\d+(?:\.\d{1,3})?$/.test(normalizedWeightText)) { + throw this.createBusinessError('weighing_weight 格式非法,最多支持 3 位小数', 400); + } + + const normalizedWeight = Number(normalizedWeightText); + if (!Number.isFinite(normalizedWeight) || normalizedWeight <= 0) { + throw this.createBusinessError('weighing_weight 必须大于 0', 400); + } + + return normalizedWeight; + } + + /** + * 读取订单下有效快递记录。 + * @param {number} orderId 订单ID。 + * @param {number|string|null|undefined} warehouseId 仓库ID。 + * @return {Promise>} 快递记录列表。 + */ + async findValidOrderExpressRows(orderId, warehouseId) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + throw this.createBusinessError('订单快递模型未初始化', 500); + } + + const where = { + order_id: orderId, + delete_at: null, + }; + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '') { + where.warehouse_id = warehouseId; + } + + const rows = await orderExpressModel.findAll({ + where, + attributes: [ 'id', 'order_id', 'waybill_code', 'weighing_weight' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 更新订单运单称重重量。 + * + * @param {Object} payload 入参对象。 + * @param {number|string} payload.orderId 订单ID。 + * @param {string} [payload.waybillCode] 运单号。 + * @param {number|string} payload.weighingWeight 称重重量。 + * @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number}>} 更新结果。 + */ + async updateWeighingWeight(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { + orderId, + waybillCode = '', + weighingWeight, + } = requestData; + + const normalizedOrderId = this.normalizeOrderId(orderId); + const normalizedWeight = this.normalizeWeighingWeight(weighingWeight); + const normalizedWaybillCode = String(waybillCode || '').trim(); + const warehouseId = this.ctx && this.ctx.user ? this.ctx.user.store_id : null; + const rows = await this.findValidOrderExpressRows(normalizedOrderId, warehouseId); + + if (rows.length === 0) { + throw this.createBusinessError('未找到有效的订单运单记录', 404); + } + + let targetRow = null; + if (rows.length === 1) { + targetRow = rows[0]; + } else { + if (!normalizedWaybillCode) { + throw this.createBusinessError('多运单订单必须传入 waybill_code', 400); + } + + targetRow = rows.find(row => String(row && row.waybill_code || '').trim() === normalizedWaybillCode) || null; + if (!targetRow) { + throw this.createBusinessError('waybill_code 未匹配到该订单下的运单记录', 404); + } + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const updateResult = await orderExpressModel.update({ + weighing_weight: normalizedWeight, + }, { + where: { + id: Number(targetRow.id), + }, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { + throw this.createBusinessError('更新称重重量失败', 500); + } + + return { + order_id: Number(targetRow.order_id), + waybill_code: String(targetRow.waybill_code || '').trim(), + weighing_weight: normalizedWeight, + }; + } + + /** + * 绑定订单快递记录的包材信息。 + * @param {Object} payload 入参对象。 + * @param {number|string} payload.orderId 订单ID。 + * @param {string} payload.waybillCode 运单号。 + * @param {string} payload.packageMaterialCode 包材编码。 + * @return {Promise} 绑定后的结果快照。 + */ + async bindExpressPackageMaterial(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { + orderId, + waybillCode, + packageMaterialCode, + } = requestData; + + const normalizedOrderId = this.normalizeBindOrderId(orderId); + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const normalizedPackageMaterialCode = this.normalizePackageMaterialCode(packageMaterialCode); + const warehouseId = this.getCurrentWarehouseId(); + + const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId); + const orderExpressRow = await this.findValidOrderExpressByOrderAndWaybill(normalizedOrderId, normalizedWaybillCode, warehouseId); + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + const updateResult = await orderExpressModel.update({ + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + }, { + where: { + id: Number(orderExpressRow.id), + delete_at: null, + }, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (!Number.isFinite(affectedRows) || affectedRows <= 0) { + throw this.createBusinessError('绑定包材失败', 500); + } + + return { + order_id: Number(orderExpressRow.order_id), + waybill_code: String(orderExpressRow.waybill_code || '').trim(), + package_material_id: Number(materialRow.id), + package_material_name_snapshot: String(materialRow.material_name || '').trim(), + package_material_code: String(materialRow.material_code || '').trim(), + }; + } +} + +module.exports = OrderExpressService; diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 8df9257..4422a58 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -611,6 +611,350 @@ class OrderPrintSystemService extends OrderBaseService { }; } + /** + * 规范化“按分组解锁”规则。 + * + * @param {Object} payload 规则入参。 + * @param {Array} payload.groups 分组条件原始列表。 + * @param {string} payload.groupType 分组类型。 + * @param {string} payload.unlockScope 解锁范围。 + * @param {Array} payload.validWaveIds 有效波次ID列表。 + * @return {Array} 规范化后的分组规则列表。 + */ + normalizeUnlockGroupRules(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const groups = Array.isArray(requestPayload.groups) ? requestPayload.groups : []; + const groupType = String(requestPayload.groupType || '').trim(); + const unlockScope = String(requestPayload.unlockScope || 'group').trim(); + const validWaveIds = Array.isArray(requestPayload.validWaveIds) ? requestPayload.validWaveIds : []; + const validWaveIdSet = new Set(validWaveIds.map(waveId => Number(waveId || 0))); + const normalizedRules = []; + const dedupeKeySet = new Set(); + + for (const rawGroup of groups) { + if (!this.isPlainObject(rawGroup)) { + continue; + } + + const rawWaveId = rawGroup.wave_id ?? rawGroup.waveId; + const waveId = Number(String(rawWaveId ?? '').trim()); + if (!Number.isInteger(waveId) || waveId <= 0 || !validWaveIdSet.has(waveId)) { + continue; + } + + const rawPlatform = String(rawGroup.platform ?? rawGroup.group_key ?? rawGroup.groupKey ?? '').trim(); + const normalizedPlatformAlias = PrinterDataBuilder.normalizePlatformAlias(rawPlatform); + const platform = String(normalizedPlatformAlias && normalizedPlatformAlias.platform || rawPlatform).trim().toLowerCase(); + const sysLogisticsCode = String(rawGroup.sys_logistics_code ?? rawGroup.sysLogisticsCode ?? '').trim().toLowerCase(); + const orderIdSet = new Set(Array.isArray(rawGroup.order_ids || rawGroup.orderIds) + ? (rawGroup.order_ids || rawGroup.orderIds) + .map(orderId => Number(String(orderId ?? '').trim())) + .filter(orderId => Number.isInteger(orderId) && orderId > 0) + : []); + + if (unlockScope !== 'wave') { + if (groupType === 'platform' && !platform) { + continue; + } + + if (groupType === 'platform_express' && (!platform || !sysLogisticsCode)) { + continue; + } + + if (groupType === 'order' && orderIdSet.size === 0) { + continue; + } + } + + const dedupeKey = `${waveId}@@${groupType}@@${unlockScope}@@${platform}@@${sysLogisticsCode}@@${Array.from(orderIdSet).sort((a, b) => a - b).join(',')}`; + if (dedupeKeySet.has(dedupeKey)) { + continue; + } + + dedupeKeySet.add(dedupeKey); + normalizedRules.push({ + waveId, + platform, + sysLogisticsCode, + orderIdSet, + }); + } + + return normalizedRules; + } + + /** + * 判断订单是否命中“按分组解锁”规则。 + * + * @param {Object} payload 匹配入参。 + * @param {Object} payload.orderRow 订单行。 + * @param {Object} payload.rule 分组规则。 + * @param {string} payload.groupType 分组类型。 + * @param {string} payload.unlockScope 解锁范围。 + * @return {boolean} 是否命中规则。 + */ + isOrderMatchedByUnlockGroupRule(payload = {}) { + const requestPayload = this.isPlainObject(payload) ? payload : {}; + const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {}; + const rule = this.isPlainObject(requestPayload.rule) ? requestPayload.rule : {}; + const groupType = String(requestPayload.groupType || '').trim(); + const unlockScope = String(requestPayload.unlockScope || 'group').trim(); + + const orderWaveId = Number(orderRow && orderRow.wave_id || 0); + const ruleWaveId = Number(rule && rule.waveId || 0); + if (!Number.isInteger(orderWaveId) || orderWaveId <= 0 || orderWaveId !== ruleWaveId) { + return false; + } + + if (unlockScope === 'wave') { + return true; + } + + const orderId = Number(orderRow && orderRow.id || 0); + const orderIdSet = rule.orderIdSet instanceof Set ? rule.orderIdSet : new Set(); + if (groupType === 'order') { + return orderIdSet.has(orderId); + } + + const orderPlatformAlias = PrinterDataBuilder.normalizePlatformAlias(this.resolvePrintPlatformCode(orderRow, {})); + const orderPlatform = String(orderPlatformAlias && orderPlatformAlias.platform || '').trim().toLowerCase(); + if (orderPlatform !== String(rule.platform || '').trim().toLowerCase()) { + return false; + } + + if (groupType === 'platform_express') { + const orderSysLogisticsCode = String(orderRow && orderRow.sys_logistics_code || '').trim().toLowerCase(); + if (!orderSysLogisticsCode || orderSysLogisticsCode !== String(rule.sysLogisticsCode || '').trim().toLowerCase()) { + return false; + } + } + + if (orderIdSet.size > 0 && !orderIdSet.has(orderId)) { + return false; + } + + return true; + } + + /** + * 按分组解锁波次平台打印锁。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.waveIds 波次ID数组。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {string} params.groupType 分组类型。 + * @param {string} params.unlockScope 解锁范围。 + * @param {Array} params.groups 分组条件。 + * @return {Promise} 解锁结果。 + */ + async unlockWavePlatformPrintDataByGroup(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { + waveIds, + warehouseId, + groupType, + unlockScope, + groups, + } = requestParams; + + const normalizedWaveIds = this.normalizeWaveIds(waveIds); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.resolveWarehouseId(warehouseId); + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, normalizedWaveIds); + if (waveRows.length === 0) { + return { + summary: { + total_waves: 0, + total_locked_orders: 0, + matched_group_orders: 0, + unlocked_count: 0, + }, + wave_ids: [], + unlocked_order_ids: [], + ext: { + missing_wave_ids: normalizedWaveIds, + filtered_wave_ids: [], + }, + }; + } + + const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id))); + const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId)); + const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId)); + const orderRows = await this.queryOrdersByWaveIds(hitWaveIds, normalizedWarehouseId); + const { + validWaveIds, + filteredWaveIds, + } = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows); + const validWaveIdSet = new Set(validWaveIds); + + const lockedOrderRows = orderRows.filter(orderRow => { + const orderWaveId = Number(orderRow && orderRow.wave_id || 0); + return validWaveIdSet.has(orderWaveId) && this.isOrderLocked(orderRow); + }); + + if (lockedOrderRows.length === 0) { + return { + summary: { + total_waves: validWaveIds.length, + total_locked_orders: 0, + matched_group_orders: 0, + unlocked_count: 0, + }, + wave_ids: validWaveIds, + unlocked_order_ids: [], + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + const normalizedRules = this.normalizeUnlockGroupRules({ + groups, + groupType, + unlockScope, + validWaveIds, + }); + if (normalizedRules.length === 0) { + throw new Error('groups 未匹配到有效的分组解锁条件'); + } + + const matchedOrderRows = lockedOrderRows.filter(orderRow => { + return normalizedRules.some(rule => this.isOrderMatchedByUnlockGroupRule({ + orderRow, + rule, + groupType, + unlockScope, + })); + }); + const matchedOrderIds = Array.from(new Set(matchedOrderRows + .map(orderRow => Number(orderRow && orderRow.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0))); + + if (matchedOrderIds.length === 0) { + return { + summary: { + total_waves: validWaveIds.length, + total_locked_orders: lockedOrderRows.length, + matched_group_orders: 0, + unlocked_count: 0, + }, + wave_ids: validWaveIds, + unlocked_order_ids: [], + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + + const orderModel = await this.getOrderModel('order', normalizedWarehouseId); + const updateResult = await orderModel.update({ + print_lock_status: 'none', + }, { + where: { + id: { + [Op.in]: matchedOrderIds, + }, + print_lock_status: { + [Op.ne]: 'none', + }, + }, + }); + + const unlockedCount = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0; + // 尝试写入操作日志(非阻塞,不影响主流程) + try { + const operationLogService = this.service && this.service.systems && this.service.systems.operationLog; + const operator = this.getOrderLogOperator(); + const warehouseIdForLog = this.getOrderLogWarehouseId(normalizedWarehouseId) || normalizedWarehouseId; + + const rawGroupsText = (() => { + try { + return JSON.stringify(Array.isArray(groups) ? groups : []); + } catch (e) { + return ''; + } + })(); + + // 截断 groups 描述为合理长度,避免 message 过长 + const truncatedGroups = String(rawGroupsText || '').slice(0, 200); + const baseNote = `按分组解锁 groupType=${String(groupType || '')} groups=${truncatedGroups}`; + + const payloads = matchedOrderRows.map(orderRow => { + const orderId = Number(orderRow && orderRow.id || 0); + const waveId = Number(orderRow && orderRow.wave_id || 0); + const waveNo = String(orderRow && orderRow.wave_no || '').trim(); + + const note = `${baseNote} wave_id=${waveId} wave_no=${waveNo}`; + + return { + businessType: 'order', + businessId: orderId, + operationCode: 'unlock_by_group', + operator: { + id: operator && operator.id ? operator.id : (this.ctx.state?.user?.id || this.ctx.user?.id || 0), + name: operator && operator.name ? operator.name : (this.ctx.state?.user?.real_name || this.ctx.user?.name || 'system'), + }, + extras: { + warehouseId: warehouseIdForLog, + externalLogType: 'REQUEST', + externalLogId: null, + // 额外信息放入 message 中以便在表中检索;表结构暂无专门 trace 字段 + message: JSON.stringify({ + source: 'order.print.unlockWavePlatformPrintDataByGroup', + trace_id: this.ctx.requestId || this.ctx.traceId || null, + note, + }), + }, + beforeChanges: null, + }; + }).filter(item => item && Number(item.businessId) > 0); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && payloads.length > 0) { + // 为性能考虑,若太多则分批(每批 100 条)并发写入 + const BATCH_SIZE = 100; + for (let i = 0; i < payloads.length; i += BATCH_SIZE) { + const batch = payloads.slice(i, i + BATCH_SIZE); + // 不等待所有批次顺序完成,改为并发触发但捕获错误 + // 这里仍然 await,以保证在单请求内完成写入,但不会抛出影响主逻辑的异常 + try { + await operationLogService.createOperationLogs(batch); + } catch (err) { + this.ctx.logger.warn('[orderPrint.unlockWavePlatformPrintDataByGroup] 写入操作日志失败,不影响业务', err); + } + } + } + } catch (logErr) { + this.ctx.logger.warn('[orderPrint.unlockWavePlatformPrintDataByGroup] 写入操作日志失败(全局捕获),不影响业务', logErr); + } + + return { + summary: { + total_waves: validWaveIds.length, + total_locked_orders: lockedOrderRows.length, + matched_group_orders: matchedOrderIds.length, + unlocked_count: unlockedCount > 0 ? unlockedCount : 0, + }, + wave_ids: validWaveIds, + unlocked_order_ids: matchedOrderIds, + unlocked_orders: matchedOrderRows.map(orderRow => ({ + order_id: Number(orderRow && orderRow.id || 0), + wave_id: Number(orderRow && orderRow.wave_id || 0), + wave_no: String(orderRow && orderRow.wave_no || '').trim(), + order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(), + })), + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } + /** * 规范化波次ID数组(去重与数字化)。 * diff --git a/app/service/systems/order_review.js b/app/service/systems/order_review.js new file mode 100644 index 0000000..ed8f115 --- /dev/null +++ b/app/service/systems/order_review.js @@ -0,0 +1,493 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +/** + * 订单复核数据聚合服务。 + * + * 负责根据运单号反查订单,并输出复核最小数据集。 + */ +class OrderReviewService extends OrderBaseService { + /** + * 创建带业务错误码的异常对象。 + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 规范化运单号。 + * @param {string} waybillCode 运单号。 + * @return {string} 规范化后的运单号。 + */ + normalizeWaybillCode(waybillCode) { + const normalizedWaybillCode = String(waybillCode || '').trim(); + if (!normalizedWaybillCode) { + throw this.createBusinessError('参数错误', 400); + } + + return normalizedWaybillCode; + } + + /** + * 判断是否为锁定状态。 + * @param {string} lockStatus 锁定状态。 + * @return {boolean} 是否锁定。 + */ + isLockedStatus(lockStatus) { + return String(lockStatus || '').trim() !== 'none'; + } + + /** + * 判断是否为拦截状态。 + * @param {string} interceptStatus 拦截状态。 + * @return {boolean} 是否拦截。 + */ + isInterceptStatus(interceptStatus) { + return String(interceptStatus || '').trim() !== 'none'; + } + + /** + * 将模型记录转换为普通对象。 + * @param {*} record 模型记录。 + * @return {Object|null} 普通对象。 + */ + toPlainRecord(record) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; + } + + /** + * 解析订单商品快照。 + * @param {*} itemSnapshot 商品快照字段。 + * @return {Object} 解析后的快照对象。 + */ + parseItemSnapshot(itemSnapshot) { + if (!itemSnapshot) { + return {}; + } + + if (typeof itemSnapshot === 'object') { + return itemSnapshot; + } + + if (typeof itemSnapshot === 'string') { + try { + const parsed = JSON.parse(itemSnapshot); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch (error) { + return {}; + } + } + + return {}; + } + + /** + * 根据运单号读取有效快递记录。 + * @param {string} waybillCode 运单号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 快递记录。 + */ + async findOrderExpressByWaybill(waybillCode, warehouseId) { + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') { + throw this.createBusinessError('订单快递模型未初始化', 500); + } + + const expressRow = await orderExpressModel.findOne({ + where: { + waybill_code: waybillCode, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (!expressRow) { + throw this.createBusinessError('运单不存在', 404); + } + + return expressRow; + } + + /** + * 根据订单ID读取订单头。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 订单头。 + */ + async findOrderById(orderId, warehouseId) { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + + const orderRow = await orderModel.findOne({ + where: orderWhere, + attributes: [ + 'id', + 'warehouse_id', + 'wave_id', + 'wave_no', + 'items_weight', + 'items_total', + 'items_count', + 'lock_status', + 'intercept_status', + ], + raw: true, + }); + + if (!orderRow) { + throw this.createBusinessError('订单不存在', 404); + } + + return orderRow; + } + + /** + * 读取订单明细。 + * @param {number} orderId 订单ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 明细列表。 + */ + async findOrderItems(orderId, warehouseId) { + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const rows = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + attributes: [ + 'id', + 'order_id', + 'item_id', + 'item_code', + 'item_name', + 'plan_qty', + 'stock_id', + 'item_snapshot', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 批量读取商品条码映射。 + * @param {number[]} stockIds 商品ID列表。 + * @return {Promise>} 条码映射。 + */ + async loadBarcodesByStockIds(stockIds = []) { + const uniqueStockIds = Array.from(new Set((Array.isArray(stockIds) ? stockIds : []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0))); + const barcodeMap = new Map(); + + if (uniqueStockIds.length === 0) { + return barcodeMap; + } + + const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode; + if (!stockBarcodeModel || typeof stockBarcodeModel.findAll !== 'function') { + return barcodeMap; + } + + const barcodeRows = await stockBarcodeModel.findAll({ + where: { + stock_id: { + [this.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + + for (const item of Array.isArray(barcodeRows) ? barcodeRows : []) { + const stockId = Number(item && item.stock_id || 0); + const barcode = String(item && item.barcode || '').trim(); + + if (!stockId || !barcode) { + continue; + } + + if (!barcodeMap.has(stockId)) { + barcodeMap.set(stockId, []); + } + + barcodeMap.get(stockId).push(barcode); + } + + return barcodeMap; + } + + /** + * 批量读取商品图片映射。 + * @param {number[]} stockIds 商品ID列表。 + * @return {Promise>} 图片映射。 + */ + async loadImagesByStockIds(stockIds = []) { + const uniqueStockIds = Array.from(new Set((Array.isArray(stockIds) ? stockIds : []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0))); + const imageMap = new Map(); + + if (uniqueStockIds.length === 0) { + return imageMap; + } + + const fileReferenceModel = this.ctx.model && this.ctx.model.FileReference; + const fileModel = this.ctx.model && this.ctx.model.File; + + if (!fileReferenceModel || typeof fileReferenceModel.findAll !== 'function' || !fileModel) { + return imageMap; + } + + const imageRows = await fileReferenceModel.findAll({ + where: { + business_type: 'stock', + business_id: { + [this.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + include: [{ + model: fileModel, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + }); + + for (const item of Array.isArray(imageRows) ? imageRows : []) { + const row = this.toPlainRecord(item); + const stockId = Number(row && row.business_id || 0); + const imageUrl = String( + row && row.file && row.file.file_url + || row && row.file_url + || row && row.url + || row && row.file_path + || '' + ).trim(); + + if (!stockId || !imageUrl) { + continue; + } + + if (!imageMap.has(stockId)) { + imageMap.set(stockId, []); + } + + imageMap.get(stockId).push(imageUrl); + } + + return imageMap; + } + + /** + * 查询波次信息。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 波次信息。 + */ + async findWaveById(waveId, warehouseId) { + const normalizedWaveId = Number(waveId || 0); + if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) { + return null; + } + + const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch; + if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') { + return null; + } + + return await waveBatchModel.findOne({ + where: { + wave_id: normalizedWaveId, + warehouse_id: warehouseId, + }, + attributes: [ 'wave_id', 'wave_no', 'wave_type' ], + raw: true, + }); + } + + /** + * 读取团购波次拦截列表。 + * @param {Object} order 当前命中订单。 + * @return {Promise} 拦截列表。 + */ + async buildGroupInterceptList(order = {}) { + const waveId = Number(order && order.wave_id || 0); + const warehouseId = Number(order && order.warehouse_id || 0); + + if (!waveId || !warehouseId) { + return []; + } + + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const interceptRows = await orderModel.findAll({ + where: { + wave_id: waveId, + warehouse_id: warehouseId, + intercept_status: { + [this.app.Sequelize.Op.ne]: 'none', + }, + }, + attributes: [ 'id', 'intercept_status', 'lock_status' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const normalizedRows = Array.isArray(interceptRows) ? interceptRows : []; + if (normalizedRows.length === 0) { + return []; + } + + const orderIds = normalizedRows + .map(item => Number(item && item.id || 0)) + .filter(item => Number.isFinite(item) && item > 0); + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + let waybillRows = []; + if (orderExpressModel && typeof orderExpressModel.findAll === 'function' && orderIds.length > 0) { + waybillRows = await orderExpressModel.findAll({ + where: { + order_id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + delete_at: null, + }, + attributes: [ 'order_id', 'waybill_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + } + + const firstWaybillMap = new Map(); + for (const row of Array.isArray(waybillRows) ? waybillRows : []) { + const orderId = Number(row && row.order_id || 0); + const waybillCode = String(row && row.waybill_code || '').trim(); + if (!orderId || !waybillCode || firstWaybillMap.has(orderId)) { + continue; + } + + firstWaybillMap.set(orderId, waybillCode); + } + + return normalizedRows.map(item => { + const orderId = Number(item && item.id || 0); + return { + order_id: orderId, + waybill_code: firstWaybillMap.get(orderId) || null, + intercept_status: String(item && item.intercept_status || '').trim() || 'none', + lock_status: String(item && item.lock_status || '').trim() || 'none', + }; + }); + } + + /** + * 根据运单号拉取复核最小数据集。 + * @param {Object} payload 入参。 + * @param {string} payload.waybillCode 运单号。 + * @return {Promise} 复核数据。 + */ + async pullReviewDataByWaybill(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const { waybillCode } = requestData; + + const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode); + const warehouseId = Number(this.getWarehouseId() || 0); + if (!warehouseId) { + throw this.createBusinessError('参数错误', 400); + } + + const expressRow = await this.findOrderExpressByWaybill(normalizedWaybillCode, warehouseId); + const orderId = Number(expressRow && expressRow.order_id || 0); + if (!orderId) { + throw this.createBusinessError('订单不存在', 404); + } + + const orderRow = await this.findOrderById(orderId, warehouseId); + const itemRows = await this.findOrderItems(orderId, warehouseId); + const stockIds = itemRows + .map(item => Number(item && item.stock_id || 0)) + .filter(item => Number.isFinite(item) && item > 0); + const barcodeMap = await this.loadBarcodesByStockIds(stockIds); + const imageMap = await this.loadImagesByStockIds(stockIds); + + const details = itemRows.map(item => { + const snapshot = this.parseItemSnapshot(item && item.item_snapshot); + const stockId = Number(item && item.stock_id || 0); + const barcodes = barcodeMap.get(stockId) || []; + const images = imageMap.get(stockId) || []; + + return { + order_item_id: Number(item && item.id || 0), + item_id: Number(item && item.item_id || 0) || null, + stock_id: stockId || null, + sku_code: String(item && item.item_code || snapshot.item_code || '').trim() || null, + item_name: String(item && item.item_name || snapshot.item_name || '').trim() || null, + should_review_qty: Number(item && item.plan_qty || 0), + image: images[0] || null, + images, + barcode: barcodes[0] || null, + barcodes, + }; + }); + + const lockStatus = String(orderRow && orderRow.lock_status || '').trim() || 'none'; + const interceptStatus = String(orderRow && orderRow.intercept_status || '').trim() || 'none'; + const warnings = []; + if (this.isLockedStatus(lockStatus)) { + warnings.push('订单处于锁定状态,请确认后再复核'); + } + if (this.isInterceptStatus(interceptStatus)) { + warnings.push('订单处于拦截状态,请先处理拦截'); + } + + const waveRow = await this.findWaveById(orderRow && orderRow.wave_id, warehouseId); + const isGroupOrder = Number(waveRow && waveRow.wave_type || 0) === 1; + const interceptList = isGroupOrder + ? await this.buildGroupInterceptList(orderRow) + : []; + + const totalPieceCount = Number(orderRow && orderRow.items_total || 0); + const totalSkuCount = Number(orderRow && orderRow.items_count || 0); + const fallbackSkuCount = details.reduce((count, item) => { + const skuCode = String(item && item.sku_code || '').trim(); + return skuCode ? count + 1 : count; + }, 0); + const fallbackPieceCount = details.reduce((count, item) => count + Number(item && item.should_review_qty || 0), 0); + + return { + order_id: Number(orderRow && orderRow.id || 0), + waybill_code: String(expressRow && expressRow.waybill_code || normalizedWaybillCode).trim(), + wave_no: String(orderRow && orderRow.wave_no || '').trim() || null, + total_weight: orderRow && orderRow.items_weight != null ? Number(orderRow.items_weight) : null, + total_piece_count: totalPieceCount > 0 ? totalPieceCount : fallbackPieceCount, + total_sku_count: totalSkuCount > 0 ? totalSkuCount : fallbackSkuCount, + lock_status: lockStatus, + intercept_status: interceptStatus, + is_group_order: isGroupOrder, + warnings, + intercept_list: interceptList, + details, + }; + } +} + +module.exports = OrderReviewService; diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index 81a7f1d..14db0e8 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -441,10 +441,10 @@ class PlatformService extends Service { * 批量加载打印平台编码映射。 * * 仅以 `wms_platform.print_platform_id -> wms_print_platform.platform_code` - * 为准;缺少模型、主键或关联记录时返回空映射,避免继续误用旧字段。 + * 为准;缺少模型、主键或关联记录时返回空映射,避免继续误用 sys_platform_code 直连语义。 * * @param {Array} platformRows 平台记录列表。 - * @return {Promise>} 打印平台ID到平台编码的映射。 + * @return {Promise>} 打印平台ID到打印平台编码的映射。 */ async loadPrintPlatformCodeMap(platformRows = []) { const printPlatformModel = this.getPrintPlatformModel(); @@ -476,22 +476,72 @@ class PlatformService extends Service { const printPlatformCodeMap = new Map(); for (const row of Array.isArray(rows) ? rows : []) { const printPlatformId = this.normalizePrintPlatformId(row && row.id); - const platformCode = String(row && row.platform_code || '').trim(); - if (!printPlatformId || !platformCode) { + const printPlatformCode = String(row && row.platform_code || '').trim(); + if (!printPlatformId || !printPlatformCode) { continue; } - printPlatformCodeMap.set(printPlatformId, platformCode); + printPlatformCodeMap.set(printPlatformId, printPlatformCode); } return printPlatformCodeMap; } + /** + * 批量加载打印平台 platid 映射。 + * + * 仅以 `wms_platform.print_platform_id -> wms_print_platform.platid` + * 为准;缺少模型、主键或关联记录时返回空映射。 + * + * @param {Array} platformRows 平台记录列表。 + * @return {Promise>} 打印平台ID到 platid 的映射。 + */ + async loadPrintPlatformPlatidMap(platformRows = []) { + const printPlatformModel = this.getPrintPlatformModel(); + if (!printPlatformModel) { + return new Map(); + } + + const idSet = new Set(); + for (const platformRow of Array.isArray(platformRows) ? platformRows : []) { + const plainRow = this.toPlainRow(platformRow); + const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id); + if (printPlatformId) { + idSet.add(printPlatformId); + } + } + + if (idSet.size <= 0) { + return new Map(); + } + + const rows = await printPlatformModel.findAll({ + attributes: [ 'id', 'platid' ], + where: { + id: Array.from(idSet), + }, + raw: true, + }); + + const printPlatformPlatidMap = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + const printPlatformId = this.normalizePrintPlatformId(row && row.id); + const platid = Number(row && row.platid); + if (!printPlatformId || !Number.isFinite(platid)) { + continue; + } + + printPlatformPlatidMap.set(printPlatformId, platid); + } + + return printPlatformPlatidMap; + } + /** * 解析平台对应的默认快递接口平台编码。 * - * 仅信任 `PrintPlatform.platform_code`;若模型未注册、主键缺失或未匹配到记录, - * 返回空字符串作为清晰兜底,不再退回到 `wms_platform.platform_code`。 + * 仅信任 `PrintPlatform.platform_code`;若模型未注册、主键缺失、 + * 未匹配到记录或目标字段为空,返回空字符串作为清晰兜底,不再退回旧语义。 * * @param {Object} row 平台记录。 * @param {Map} [printPlatformCodeMap] 打印平台编码映射。 @@ -504,9 +554,9 @@ class PlatformService extends Service { } const nestedPrintPlatform = this.toPlainRow(plainRow.printPlatform); - const nestedPlatformCode = String(nestedPrintPlatform && nestedPrintPlatform.platform_code || '').trim(); - if (nestedPlatformCode) { - return nestedPlatformCode; + const nestedPrintPlatformCode = String(nestedPrintPlatform && nestedPrintPlatform.platform_code || '').trim(); + if (nestedPrintPlatformCode) { + return nestedPrintPlatformCode; } const printPlatformId = this.normalizePrintPlatformId(plainRow.print_platform_id); @@ -514,25 +564,32 @@ class PlatformService extends Service { return ''; } - return String(printPlatformCodeMap.get(printPlatformId) || '').trim(); + const mappedPrintPlatformCode = String(printPlatformCodeMap.get(printPlatformId) || '').trim(); + if (!mappedPrintPlatformCode) { + this.ctx.logger.warn(`[PlatformService.resolveDefaultExpressInterface] print_platform_id=${printPlatformId} 缺少 platform_code,默认快递接口返回空值`); + return ''; + } + + return mappedPrintPlatformCode; } /** * 解析平台后处理路由编码。 * - * `wms_platform.platform_code` 用于第三方聚合平台后处理路由; - * 未配置时退回平台主编码,保持历史数据兼容。 + * 路由语义统一使用 `wms_platform.print_platform_id -> wms_print_platform.platform_code`。 + * 若未配置请求平台编码,则回退平台主编码,避免中断历史链路。 * * @param {Object} row 平台记录。 + * @param {Map} [printPlatformCodeMap] 打印平台编码映射。 * @return {string} 平台后处理路由编码。 */ - resolveRoutePlatformCode(row) { + resolveRoutePlatformCode(row, printPlatformCodeMap = new Map()) { const plainRow = this.toPlainRow(row); if (!plainRow) { return ''; } - const routePlatformCode = String(plainRow.platform_code || '').trim(); + const routePlatformCode = this.resolveDefaultExpressInterface(plainRow, printPlatformCodeMap); if (routePlatformCode) { return routePlatformCode; } @@ -564,6 +621,34 @@ class PlatformService extends Service { return isFull ? 'platform:list:full' : 'platform:list'; } + /** + * 判断全量平台缓存是否存在字段结构过期。 + * + * 当缓存项中存在有效 print_platform_id,但缺少有效 platid 时, + * 认为缓存结构已过期,需要触发重建。 + * + * @param {*} cachedList 缓存中的平台列表。 + * @return {boolean} 是否结构过期。 + */ + isFullPlatformCacheSchemaStale(cachedList) { + if (!Array.isArray(cachedList) || cachedList.length <= 0) { + return false; + } + + return cachedList.some(item => { + if (!item || typeof item !== 'object') { + return false; + } + + const printPlatformId = Number(item.print_platform_id); + if (!Number.isFinite(printPlatformId) || printPlatformId <= 0) { + return false; + } + + return !Number.isFinite(Number(item.platid)); + }); + } + /** * 生成平台设置项展示名称。 * @@ -691,20 +776,32 @@ class PlatformService extends Service { * * @param {Object} row 数据库记录。 * @param {Map} [printPlatformCodeMap] 打印平台编码映射。 + * @param {Map} [printPlatformPlatidMap] 打印平台 platid 映射。 * @return {Object|null} 规范化后的全量记录。 */ - normalizeFullPlatformRow(row, printPlatformCodeMap = new Map()) { + normalizeFullPlatformRow(row, printPlatformCodeMap = new Map(), printPlatformPlatidMap = new Map()) { const normalizedRow = this.normalizePlatformRow(row, printPlatformCodeMap); if (!normalizedRow) { return null; } - return { + const normalizedResult = { ...row, ...normalizedRow, - route_platform_code: this.resolveRoutePlatformCode(row), + route_platform_code: this.resolveRoutePlatformCode(row, printPlatformCodeMap), }; + + const plainRow = this.toPlainRow(row); + const printPlatformId = this.normalizePrintPlatformId(plainRow && plainRow.print_platform_id); + if (printPlatformId && printPlatformPlatidMap instanceof Map) { + const platid = printPlatformPlatidMap.get(printPlatformId); + if (Number.isFinite(platid)) { + normalizedResult.platid = platid; + } + } + + return normalizedResult; } /** @@ -789,6 +886,12 @@ class PlatformService extends Service { return mergedList; } + /** + * 从数据库加载系统平台列表。 + * + * @param {boolean} [full=false] 是否返回全量字段。 + * @return {Promise>} 平台列表。 + */ async loadPlatformListFromDatabase(full = false) { const query = { order: [[ 'code', 'ASC' ]], @@ -811,9 +914,12 @@ class PlatformService extends Service { } const printPlatformCodeMap = await this.loadPrintPlatformCodeMap(rows); + const printPlatformPlatidMap = full ? await this.loadPrintPlatformPlatidMap(rows) : new Map(); return rows - .map(row => (full ? this.normalizeFullPlatformRow(row, printPlatformCodeMap) : this.normalizePlatformRow(row, printPlatformCodeMap))) + .map(row => (full + ? this.normalizeFullPlatformRow(row, printPlatformCodeMap, printPlatformPlatidMap) + : this.normalizePlatformRow(row, printPlatformCodeMap))) .filter(Boolean); } @@ -847,7 +953,18 @@ class PlatformService extends Service { try { const cachedList = await this.app.getCacheAsync(cacheKey); if (cachedList !== null && cachedList !== undefined) { - return Array.isArray(cachedList) ? cachedList : []; + if (isFull && this.isFullPlatformCacheSchemaStale(cachedList)) { + this.ctx.logger.warn(`[PlatformService.getPlatformList] full缓存缺少有效platid,触发重建: ${cacheKey}`); + + try { + await this.app.delCacheAsync(cacheKey); + } catch (error) { + this.ctx.logger.warn(`[PlatformService.getPlatformList] 删除过期缓存失败,降级为setCacheAsync置空: ${cacheKey}, error: ${error.message}`); + await this.app.setCacheAsync(cacheKey, null, 0); + } + } else { + return Array.isArray(cachedList) ? cachedList : []; + } } if (isSystemOnly) { @@ -1027,7 +1144,7 @@ class PlatformService extends Service { { model: this.app.model.Platform, as: 'platform', - attributes: [ 'code', 'name', 'platform_code' ], + attributes: [ 'code', 'name', 'print_platform_id' ], }, ], }); diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index d457277..e5ceafd 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -486,7 +486,7 @@ class SettingExpressInterfaceService extends Service { polyapi_extra_info: row.polyapi_extra_info === undefined ? null : row.polyapi_extra_info, pdd_code: this.normalizeOptionalText(row.PDD !== undefined ? row.PDD : row.pdd_code, 'express.pdd_code', 255), ks_code: this.normalizeOptionalText(row.KS !== undefined ? row.KS : row.ks_code, 'express.ks_code', 255), - dyxd_code: this.normalizeOptionalText(row.DYXD !== undefined ? row.DYXD : row.dyxd_code, 'express.dyxd_code', 255), + dyxd_code: this.normalizeOptionalText(row.DY !== undefined ? row.DY : row.dyxd_code, 'express.dyxd_code', 255), }; } @@ -524,9 +524,9 @@ class SettingExpressInterfaceService extends Service { KS: 'KS', KSAPP: 'KS', PDD: 'PDD', - DYXD: 'DYXD', - DY: 'DYXD', - DOUYIN: 'DYXD', + DYXD: 'DY', + DY: 'DY', + DOUYIN: 'DY', }; return fieldMap[normalizedPlatformCode] || null; @@ -619,6 +619,7 @@ class SettingExpressInterfaceService extends Service { platid, status: this.normalizeOptionalText(row.status, 'status', 20) || 'ACTIVE', remark: this.normalizeOptionalText(row.remark, 'remark', 255), + need_callback_url: this.normalizeOptionalText(row.need_callback_url, 'need_callback_url', 500), }; } @@ -637,7 +638,7 @@ class SettingExpressInterfaceService extends Service { } const rows = await printPlatformModel.findAll({ - attributes: [ 'id', 'platform_code', 'platform_name', 'platid', 'status', 'remark' ], + attributes: [ 'id', 'platform_code', 'platform_name', 'platid', 'status', 'remark', 'need_callback_url' ], where: { deleted: 0, status: 'ACTIVE', diff --git a/app/service/systems/setting/packageMaterial.js b/app/service/systems/setting/packageMaterial.js new file mode 100644 index 0000000..9a348ac --- /dev/null +++ b/app/service/systems/setting/packageMaterial.js @@ -0,0 +1,611 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingPackageMaterialService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作包材', 400); + } + + return storeId; + } + + /** + * 规范化必填文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string} 规范化结果 + */ + normalizeRequiredText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string|null} 规范化结果 + */ + normalizeOptionalText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选小数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number|null} [min=null] 最小值 + * @return {number|null} 规范化结果 + */ + normalizeOptionalDecimal(value, fieldName, min = null) { + if (value === undefined || value === null || value === '') { + return null; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized)) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + if (min !== null && normalized < min) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + return normalized; + } + + /** + * 规范化可选状态值。 + * + * @param {*} value 原始值 + * @param {number} defaultValue 默认值 + * @return {number} 规范化结果 + */ + normalizeStatus(value, defaultValue = 1) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isInteger(normalized) || ![ 0, 1 ].includes(normalized)) { + throw this.createError('status 参数不合法', 400); + } + + return normalized; + } + + /** + * 规范化分页参数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 规范化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + normalizeDeleteIds(data = {}) { + const { + ids, + id, + material_id: materialId, + materialId: camelMaterialId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 列表 where 字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + material_code: { + field: 'material_code', + }, + material_name: { + field: 'material_name', + }, + material_type: { + field: 'material_type', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询 where。 + * + * @param {Object} data 请求参数 + * @return {Object} 解析结果 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError('where 参数解析失败: ' + parsed.reason, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 规范化包材行数据。 + * + * @param {Object} row 原始行 + * @return {Object|null} 规范化结果 + */ + normalizeMaterialRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + material_code: String(row.material_code || '').trim(), + material_name: String(row.material_name || '').trim(), + material_type: row.material_type === undefined || row.material_type === null ? '' : String(row.material_type).trim(), + spec: row.spec === undefined || row.spec === null ? '' : String(row.spec).trim(), + length: row.length === undefined || row.length === null ? null : Number(row.length), + width: row.width === undefined || row.width === null ? null : Number(row.width), + height: row.height === undefined || row.height === null ? null : Number(row.height), + weight: row.weight === undefined || row.weight === null ? null : Number(row.weight), + cost_price: row.cost_price === undefined || row.cost_price === null ? null : Number(row.cost_price), + status: row.status === undefined || row.status === null ? 1 : Number(row.status), + version: row.version === undefined || row.version === null ? null : Number(row.version), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 校验包材编码在当前仓库内唯一。 + * + * @param {number} warehouseId 仓库 ID + * @param {string} materialCode 包材编码 + * @param {number|null} [excludeId=null] 排除 ID + * @return {Promise} 无返回值 + */ + async ensureMaterialCodeUnique(warehouseId, materialCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const where = { + warehouse_id: warehouseId, + material_code: materialCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + const existing = await ctx.model.PackageMaterial.findOne({ + where, + attributes: [ 'id', 'material_code' ], + }); + + if (existing) { + throw this.createError('material_code 已被当前仓库使用', 409); + } + } + + /** + * 按 ID 查找包材。 + * + * @param {number} id 包材 ID + * @param {number} warehouseId 仓库 ID + * @return {Promise} 包材记录 + */ + async findMaterialById(id, warehouseId) { + const material = await this.ctx.model.PackageMaterial.findOne({ + where: { + id, + warehouse_id: warehouseId, + }, + }); + + if (!material) { + throw this.createError('包材不存在或无权限操作', 404); + } + + return material; + } + + /** + * 创建包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const normalizedMaterialCode = this.normalizeRequiredText(materialCode, 'material_code', 64).toUpperCase(); + const normalizedMaterialName = this.normalizeRequiredText(materialName, 'material_name', 128); + const normalizedMaterialType = this.normalizeOptionalText(materialType, 'material_type', 32); + const normalizedSpec = this.normalizeOptionalText(spec, 'spec', 128); + const normalizedStatus = this.normalizeStatus(status, 1); + + await this.ensureMaterialCodeUnique(warehouseId, normalizedMaterialCode); + + const createdRow = await this.ctx.model.PackageMaterial.create({ + warehouse_id: warehouseId, + material_code: normalizedMaterialCode, + material_name: normalizedMaterialName, + material_type: normalizedMaterialType, + spec: normalizedSpec, + length: this.normalizeOptionalDecimal(length, 'length', 0), + width: this.normalizeOptionalDecimal(width, 'width', 0), + height: this.normalizeOptionalDecimal(height, 'height', 0), + weight: this.normalizeOptionalDecimal(weight, 'weight', 0), + cost_price: this.normalizeOptionalDecimal(costPrice, 'cost_price', 0), + status: normalizedStatus, + }); + + return this.normalizeMaterialRow(createdRow && typeof createdRow.get === 'function' ? createdRow.get({ plain: true }) : createdRow); + } + + /** + * 更新包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + id, + material_id: materialId, + materialId: camelMaterialId, + material_code: materialCode, + material_name: materialName, + material_type: materialType, + spec, + length, + width, + height, + weight, + cost_price: costPrice, + status, + } = data || {}; + + const resolvedId = Number(id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); + if (!Number.isInteger(resolvedId) || resolvedId <= 0) { + throw this.createError('id 参数不合法', 400); + } + + const material = await this.findMaterialById(resolvedId, warehouseId); + const updates = {}; + + if (materialCode !== undefined) { + const normalizedMaterialCode = this.normalizeRequiredText(materialCode, 'material_code', 64).toUpperCase(); + await this.ensureMaterialCodeUnique(warehouseId, normalizedMaterialCode, resolvedId); + updates.material_code = normalizedMaterialCode; + } + + if (materialName !== undefined) { + updates.material_name = this.normalizeRequiredText(materialName, 'material_name', 128); + } + + if (materialType !== undefined) { + updates.material_type = this.normalizeOptionalText(materialType, 'material_type', 32); + } + + if (spec !== undefined) { + updates.spec = this.normalizeOptionalText(spec, 'spec', 128); + } + + if (length !== undefined) { + updates.length = this.normalizeOptionalDecimal(length, 'length', 0); + } + + if (width !== undefined) { + updates.width = this.normalizeOptionalDecimal(width, 'width', 0); + } + + if (height !== undefined) { + updates.height = this.normalizeOptionalDecimal(height, 'height', 0); + } + + if (weight !== undefined) { + updates.weight = this.normalizeOptionalDecimal(weight, 'weight', 0); + } + + if (costPrice !== undefined) { + updates.cost_price = this.normalizeOptionalDecimal(costPrice, 'cost_price', 0); + } + + if (status !== undefined) { + updates.status = this.normalizeStatus(status, 1); + } + + if (Object.keys(updates).length > 0) { + await material.update(updates); + } + + return this.normalizeMaterialRow(material && typeof material.get === 'function' ? material.get({ plain: true }) : material); + } + + /** + * 删除包材。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const ids = this.normalizeDeleteIds(data); + + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const rows = await ctx.model.PackageMaterial.findAll({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'material_code' ], + raw: true, + }); + + if (!Array.isArray(rows) || rows.length !== ids.length) { + throw this.createError('存在包材不存在或无权限删除', 404); + } + + const refCount = await ctx.model.OrderExpress.count({ + where: { + warehouse_id: warehouseId, + package_material_id: { + [Op.in]: ids, + }, + }, + }); + + if (Number(refCount) > 0) { + throw this.createError('包材已被订单快递使用,无法删除', 409); + } + + const affectedRows = await ctx.model.PackageMaterial.destroy({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + }); + + return { + deleted: true, + warehouse_id: warehouseId, + ids, + affected_rows: Number(affectedRows || 0), + }; + } + + /** + * 查询包材列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 分页结果 + */ + async get(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + + const andConditions = [ + { + warehouse_id: warehouseId, + }, + ...(Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []), + ]; + + const quickWhereField = parsedResult.rawConditionsByField + && parsedResult.rawConditionsByField.quickWhere + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereField && quickWhereField.value !== undefined + ? String(quickWhereField.value || '').trim() + : ''; + + if (quickWhereValue) { + andConditions.push({ + [Op.or]: [ + { + material_code: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + material_name: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + material_type: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + spec: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + ], + }); + } + + const { rows, count } = await ctx.model.PackageMaterial.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + order: [[ 'id', 'DESC' ]], + limit: pageSize, + offset, + }); + + return { + page, + page_size: pageSize, + total: Number(count || 0), + where: normalizedWhere, + list: (Array.isArray(rows) ? rows : []) + .map(item => this.normalizeMaterialRow(item && typeof item.get === 'function' ? item.get({ plain: true }) : item)) + .filter(Boolean), + }; + } +} + +module.exports = SettingPackageMaterialService; diff --git a/app/service/systems/setting/packageSupplier.js b/app/service/systems/setting/packageSupplier.js new file mode 100644 index 0000000..41dca1e --- /dev/null +++ b/app/service/systems/setting/packageSupplier.js @@ -0,0 +1,533 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +class SettingPackageSupplierService extends Service { + /** + * 创建业务错误对象。 + * + * @param {string} message 错误信息 + * @param {number} [code=500] 错误码 + * @return {Error} 业务错误对象 + */ + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 获取当前仓库主体 ID。 + * + * @return {number} 当前仓库主体 ID + */ + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作包材供应商', 400); + } + + return storeId; + } + + /** + * 规范化必填文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string} 规范化结果 + */ + normalizeRequiredText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + const normalized = String(value).trim(); + if (!normalized) { + throw this.createError(fieldName + ' 参数不能为空', 400); + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选文本。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} maxLength 最大长度 + * @return {string|null} 规范化结果 + */ + normalizeOptionalText(value, fieldName, maxLength) { + if (value === undefined || value === null) { + return null; + } + + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + + if (normalized.length > maxLength) { + throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); + } + + return normalized; + } + + /** + * 规范化可选状态值。 + * + * @param {*} value 原始值 + * @param {number} defaultValue 默认值 + * @return {number} 规范化结果 + */ + normalizeStatus(value, defaultValue = 1) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isInteger(normalized) || ![ 0, 1 ].includes(normalized)) { + throw this.createError('status 参数不合法', 400); + } + + return normalized; + } + + /** + * 规范化分页参数。 + * + * @param {*} value 原始值 + * @param {string} fieldName 字段名称 + * @param {number} defaultValue 默认值 + * @param {number} maxValue 最大值 + * @return {number} 规范化后的分页值 + */ + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(fieldName + ' 参数不合法', 400); + } + + return Math.min(Math.floor(normalized), maxValue); + } + + /** + * 规范化删除 ID 列表。 + * + * @param {Object} data 请求参数 + * @return {Array} 删除 ID 列表 + */ + normalizeDeleteIds(data = {}) { + const { + ids, + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + } = data || {}; + + const rawIds = ids !== undefined + ? ids + : (id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); + + const values = Array.isArray(rawIds) + ? rawIds + : String(rawIds || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + + const normalizedIds = []; + const seenIds = new Set(); + + for (const value of values) { + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) { + continue; + } + + seenIds.add(normalized); + normalizedIds.push(normalized); + } + + return normalizedIds; + } + + /** + * 列表 where 字段映射。 + * + * @return {Object} 字段映射 + */ + getListWhereSpecialFieldMap() { + return { + id: { + field: 'id', + }, + supplier_code: { + field: 'supplier_code', + }, + supplier_name: { + field: 'supplier_name', + }, + contact_name: { + field: 'contact_name', + }, + contact_phone: { + field: 'contact_phone', + }, + status: { + field: 'status', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + + /** + * 解析列表查询 where。 + * + * @param {Object} data 请求参数 + * @return {Object} 解析结果 + */ + resolveListWhere(data = {}) { + const { ctx, app } = this; + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + + if (!parsed.ok) { + throw this.createError('where 参数解析失败: ' + parsed.reason, 400); + } + + parsedResult = parsed.result; + } + + return { + normalizedWhere, + parsedResult, + }; + } + + /** + * 规范化供应商行数据。 + * + * @param {Object} row 原始行 + * @return {Object|null} 规范化结果 + */ + normalizeSupplierRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + return { + id: row.id === undefined || row.id === null ? null : Number(row.id), + warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), + supplier_code: String(row.supplier_code || '').trim(), + supplier_name: String(row.supplier_name || '').trim(), + contact_name: row.contact_name === undefined || row.contact_name === null ? '' : String(row.contact_name).trim(), + contact_phone: row.contact_phone === undefined || row.contact_phone === null ? '' : String(row.contact_phone).trim(), + status: row.status === undefined || row.status === null ? 1 : Number(row.status), + version: row.version === undefined || row.version === null ? null : Number(row.version), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 校验供应商编码在当前仓库内唯一。 + * + * @param {number} warehouseId 仓库 ID + * @param {string} supplierCode 供应商编码 + * @param {number|null} [excludeId=null] 排除 ID + * @return {Promise} 无返回值 + */ + async ensureSupplierCodeUnique(warehouseId, supplierCode, excludeId = null) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const where = { + warehouse_id: warehouseId, + supplier_code: supplierCode, + }; + + const normalizedExcludeId = Number(excludeId || 0); + if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { + where.id = { + [Op.ne]: normalizedExcludeId, + }; + } + + const existing = await ctx.model.PackageSupplier.findOne({ + where, + attributes: [ 'id', 'supplier_code' ], + }); + + if (existing) { + throw this.createError('supplier_code 已被当前仓库使用', 409); + } + } + + /** + * 按 ID 查找供应商。 + * + * @param {number} id 供应商 ID + * @param {number} warehouseId 仓库 ID + * @return {Promise} 供应商记录 + */ + async findSupplierById(id, warehouseId) { + const supplier = await this.ctx.model.PackageSupplier.findOne({ + where: { + id, + warehouse_id: warehouseId, + }, + }); + + if (!supplier) { + throw this.createError('供应商不存在或无权限操作', 404); + } + + return supplier; + } + + /** + * 创建供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ + async create(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const normalizedSupplierCode = this.normalizeRequiredText(supplierCode, 'supplier_code', 64).toUpperCase(); + const normalizedSupplierName = this.normalizeRequiredText(supplierName, 'supplier_name', 128); + + await this.ensureSupplierCodeUnique(warehouseId, normalizedSupplierCode); + + const createdRow = await this.ctx.model.PackageSupplier.create({ + warehouse_id: warehouseId, + supplier_code: normalizedSupplierCode, + supplier_name: normalizedSupplierName, + contact_name: this.normalizeOptionalText(contactName, 'contact_name', 64), + contact_phone: this.normalizeOptionalText(contactPhone, 'contact_phone', 32), + status: this.normalizeStatus(status, 1), + }); + + return this.normalizeSupplierRow(createdRow && typeof createdRow.get === 'function' ? createdRow.get({ plain: true }) : createdRow); + } + + /** + * 更新供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 更新结果 + */ + async update(data = {}) { + const warehouseId = this.getCurrentStoreId(); + const { + id, + supplier_id: supplierId, + supplierId: camelSupplierId, + supplier_code: supplierCode, + supplier_name: supplierName, + contact_name: contactName, + contact_phone: contactPhone, + status, + } = data || {}; + + const resolvedId = Number(id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); + if (!Number.isInteger(resolvedId) || resolvedId <= 0) { + throw this.createError('id 参数不合法', 400); + } + + const supplier = await this.findSupplierById(resolvedId, warehouseId); + const updates = {}; + + if (supplierCode !== undefined) { + const normalizedSupplierCode = this.normalizeRequiredText(supplierCode, 'supplier_code', 64).toUpperCase(); + await this.ensureSupplierCodeUnique(warehouseId, normalizedSupplierCode, resolvedId); + updates.supplier_code = normalizedSupplierCode; + } + + if (supplierName !== undefined) { + updates.supplier_name = this.normalizeRequiredText(supplierName, 'supplier_name', 128); + } + + if (contactName !== undefined) { + updates.contact_name = this.normalizeOptionalText(contactName, 'contact_name', 64); + } + + if (contactPhone !== undefined) { + updates.contact_phone = this.normalizeOptionalText(contactPhone, 'contact_phone', 32); + } + + if (status !== undefined) { + updates.status = this.normalizeStatus(status, 1); + } + + if (Object.keys(updates).length > 0) { + await supplier.update(updates); + } + + return this.normalizeSupplierRow(supplier && typeof supplier.get === 'function' ? supplier.get({ plain: true }) : supplier); + } + + /** + * 删除供应商。 + * + * @param {Object} data 请求参数 + * @return {Promise} 删除结果 + */ + async delete(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const ids = this.normalizeDeleteIds(data); + + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const rows = await ctx.model.PackageSupplier.findAll({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'supplier_code' ], + raw: true, + }); + + if (!Array.isArray(rows) || rows.length !== ids.length) { + throw this.createError('存在供应商不存在或无权限删除', 404); + } + + const affectedRows = await ctx.model.PackageSupplier.destroy({ + where: { + id: { + [Op.in]: ids, + }, + warehouse_id: warehouseId, + }, + }); + + return { + deleted: true, + warehouse_id: warehouseId, + ids, + affected_rows: Number(affectedRows || 0), + }; + } + + /** + * 查询供应商列表。 + * + * @param {Object} data 请求参数 + * @return {Promise} 分页结果 + */ + async get(data = {}) { + const { app, ctx } = this; + const { Op } = app.Sequelize; + const warehouseId = this.getCurrentStoreId(); + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const pageSource = pagination.page !== undefined ? pagination.page : data.page; + const pageSizeSource = pagination.pageSize !== undefined + ? pagination.pageSize + : (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize)); + const page = this.normalizePage(pageSource, 'page', 1, 1000000); + const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + + const { normalizedWhere, parsedResult } = this.resolveListWhere(data); + + const andConditions = [ + { + warehouse_id: warehouseId, + }, + ...(Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []), + ]; + + const quickWhereField = parsedResult.rawConditionsByField + && parsedResult.rawConditionsByField.quickWhere + ? parsedResult.rawConditionsByField.quickWhere + : null; + const quickWhereValue = quickWhereField && quickWhereField.value !== undefined + ? String(quickWhereField.value || '').trim() + : ''; + + if (quickWhereValue) { + andConditions.push({ + [Op.or]: [ + { + supplier_code: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + supplier_name: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + contact_name: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + { + contact_phone: { + [Op.like]: '%' + quickWhereValue + '%', + }, + }, + ], + }); + } + + const { rows, count } = await ctx.model.PackageSupplier.findAndCountAll({ + where: { + [Op.and]: andConditions, + }, + order: [[ 'id', 'DESC' ]], + limit: pageSize, + offset, + }); + + return { + page, + page_size: pageSize, + total: Number(count || 0), + where: normalizedWhere, + list: (Array.isArray(rows) ? rows : []) + .map(item => this.normalizeSupplierRow(item && typeof item.get === 'function' ? item.get({ plain: true }) : item)) + .filter(Boolean), + }; + } +} + +module.exports = SettingPackageSupplierService; diff --git a/app/service/systems/setting/platform.js b/app/service/systems/setting/platform.js index 83cf182..b779b3f 100644 --- a/app/service/systems/setting/platform.js +++ b/app/service/systems/setting/platform.js @@ -396,7 +396,8 @@ class SettingPlatformService extends Service { platform: platform ? { code: this.normalizeOptionalText(platform.code, 'platform.code', 50), name: this.normalizeOptionalText(platform.name, 'platform.name', 255), - platform_code: this.normalizeOptionalText(platform.platform_code, 'platform.platform_code', 255), + // 兼容历史返回结构:platform.platform_code 回退为平台 code。 + platform_code: this.normalizeOptionalText(platform.code, 'platform.code', 50), } : null, }; } @@ -420,7 +421,7 @@ class SettingPlatformService extends Service { { model: ctx.model.Platform, as: 'platform', - attributes: [ 'code', 'name', 'platform_code' ], + attributes: [ 'code', 'name' ], required: false, }, ], @@ -501,7 +502,7 @@ class SettingPlatformService extends Service { where: { code: platformCode, }, - attributes: [ 'code', 'name', 'platform_code' ], + attributes: [ 'code', 'name' ], }); if (!platform) { @@ -599,7 +600,7 @@ class SettingPlatformService extends Service { { model: ctx.model.Platform, as: 'platform', - attributes: [ 'code', 'name', 'platform_code' ], + attributes: [ 'code', 'name' ], required: false, }, ], diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 50c97f7..46fd91c 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -273,6 +273,7 @@ class ShopsService extends Service { shop_name: shopRow.shop_name, custom_name: shopRow.custom_name, status: shopRow.status, + auth_expire_at: shopRow.auth_expire_at, created_at: shopRow.created_at, updated_at: shopRow.updated_at, }; @@ -361,10 +362,7 @@ class ShopsService extends Service { required: true, maxLength: 100, }); - const shopName = this.normalizeText(data.shop_name !== undefined ? data.shop_name : data.shopName, 'shop_name', { - required: false, - maxLength: 100, - }) || customName; + const shopName = `PENDING_${this.generateAuthorizeRandomCode()}`; await this.ensureShopNameUnique({ warehouseId, @@ -638,7 +636,9 @@ class ShopsService extends Service { * @return {Promise} 会话信息 */ async getAuthorizeSessionKey(data = {}) { - const { ctx } = this; + const { ctx, service } = this; + const authUrl = 'http://61.160.223.183:3012/api'; + const warehouseId = this.getCurrentWarehouseId(); const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); const callbackUrl = this.normalizeText( @@ -649,43 +649,42 @@ class ShopsService extends Service { const shop = await this.findShopById(shopId, { allowDeleted: false }); const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; const platformCode = await this.ensureShopPrintPlatformExists(shopPlain.platform_code); + // 获取wms_print_platform.platid和request_platform_code + const printPlatform = await ctx.model.PrintPlatform.findOne({ + where: { + platform_code: platformCode, + deleted: 0, + status: 'ACTIVE', + }, + attributes: [ 'get_auth_platform_name' ], + }); - switch (platformCode) { - case 'PDD': - case 'CAINIAO': { - const printPlatform = await ctx.model.PrintPlatform.findOne({ - where: { - platform_code: platformCode, - deleted: 0, - status: 'ACTIVE', - }, - attributes: [ 'auth_base_url' ], + const respone = await ctx.curl(authUrl, { + method: 'POST', + dataType: 'json', + timeout: 5000, + data: { + RedirectCodeUrl: callbackUrl, + command: 'saveShop', + platName: printPlatform ? printPlatform.get_auth_platform_name : platformCode, + shopName: shopPlain.shop_name, + }, + }); + if (respone.data && respone.data.code === 0) { + const sessionKey = respone.data.data || null; + if (sessionKey) { + await shop.update({ + access_token: sessionKey, + status: 1, + }, { + fields: [ 'access_token', 'status' ], }); - const authBaseUrl = String(printPlatform && printPlatform.auth_base_url || '').trim(); - - if (!authBaseUrl) { - throw this.createError('平台授权基础地址未配置', 400); - } - - const reservation = await this.createOrReuseAuthorizeReservation({ - warehouseId, - platformCode, - }); - const state = `${platformCode}_${reservation.authRandomCode}`; - const authorizeUrl = `${authBaseUrl}${encodeURIComponent(state)}`; - - return { - shop_id: Number(shopPlain.id), - platform_code: platformCode, - callbackurl: callbackUrl, - session_key: reservation.authRandomCode, - authorize_url: authorizeUrl, - state, - }; + return { message: '获取授权成功' }; } - default: - throw this.createError(`平台 ${platformCode} 暂未实现授权会话换取能力`, 501); + throw this.createError('获取授权失败,未返回 sessionKey', 500); + } + throw this.createError(`获取授权失败:${respone.data ? respone.data.msg : '接口请求异常'}`, 500); } } diff --git a/database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js b/database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js new file mode 100644 index 0000000..6cf65a8 --- /dev/null +++ b/database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'request_platform_code'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建打印平台请求平台编码字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildRequestPlatformCodeColumn = Sequelize => ({ + type: Sequelize.STRING(50), + allowNull: true, + comment: '请求平台编码', +}); + +module.exports = { + /** + * 执行迁移:为打印平台表新增 request_platform_code 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildRequestPlatformCodeColumn(Sequelize)); + }, + + /** + * 回滚迁移:删除打印平台表的 request_platform_code 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260525143000-drop-platform-code-from-wms-platform.js b/database/migrations/20260525143000-drop-platform-code-from-wms-platform.js new file mode 100644 index 0000000..f3f6eed --- /dev/null +++ b/database/migrations/20260525143000-drop-platform-code-from-wms-platform.js @@ -0,0 +1,61 @@ +'use strict'; + +const TABLE_NAME = 'wms_platform'; +const COLUMN_NAME = 'platform_code'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +module.exports = { + /** + * 正向迁移:幂等删除 wms_platform.platform_code。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, + + /** + * 回滚迁移:幂等恢复 wms_platform.platform_code。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + if (!existingTables.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.STRING(255), + allowNull: true, + comment: '平台编码', + }); + }, +}; diff --git a/database/migrations/20260526100000-add-need-callback-url-to-wms-print-platform.js b/database/migrations/20260526100000-add-need-callback-url-to-wms-print-platform.js new file mode 100644 index 0000000..a6e89e2 --- /dev/null +++ b/database/migrations/20260526100000-add-need-callback-url-to-wms-print-platform.js @@ -0,0 +1,69 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'need_callback_url'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建打印平台是否需要回调地址字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildNeedCallbackUrlColumn = Sequelize => ({ + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否需要回调地址:0-否,1-是', +}); + +module.exports = { + /** + * 执行迁移:为打印平台表新增 need_callback_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildNeedCallbackUrlColumn(Sequelize)); + }, + + /** + * 回滚迁移:删除打印平台表的 need_callback_url 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260527103000-alter-auth-base-url-type-on-wms-print-platform.js b/database/migrations/20260527103000-alter-auth-base-url-type-on-wms-print-platform.js new file mode 100644 index 0000000..e4e1d36 --- /dev/null +++ b/database/migrations/20260527103000-alter-auth-base-url-type-on-wms-print-platform.js @@ -0,0 +1,95 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'auth_base_url'; + +/** + * 归一化字段类型文本,便于进行幂等判断。 + * @param {Object} columnDefinition 字段定义。 + * @return {string} 归一化后的类型文本。 + */ +const normalizeColumnType = columnDefinition => { + return String(columnDefinition && columnDefinition.type ? columnDefinition.type : '') + .toLowerCase() + .replace(/\s+/g, ''); +}; + +/** + * 判断字段是否为 TEXT 类型。 + * @param {Object} columnDefinition 字段定义。 + * @return {boolean} 是否为 TEXT 类型。 + */ +const isTextType = columnDefinition => { + const normalizedType = normalizeColumnType(columnDefinition); + return normalizedType.includes('text'); +}; + +/** + * 判断字段是否为 VARCHAR(255) 类型。 + * @param {Object} columnDefinition 字段定义。 + * @return {boolean} 是否为 VARCHAR(255) 类型。 + */ +const isVarchar255Type = columnDefinition => { + const normalizedType = normalizeColumnType(columnDefinition); + return normalizedType.includes('varchar(255)'); +}; + +module.exports = { + /** + * 执行迁移:将 wms_print_platform.auth_base_url 调整为 TEXT(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const targetColumn = columns[COLUMN_NAME]; + if (!targetColumn || isTextType(targetColumn)) { + return; + } + + await queryInterface.changeColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.TEXT, + allowNull: true, + comment: '授权基础地址', + }); + }, + + /** + * 回滚迁移:将 wms_print_platform.auth_base_url 回滚为 STRING(255)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const targetColumn = columns[COLUMN_NAME]; + if (!targetColumn || isVarchar255Type(targetColumn)) { + return; + } + + await queryInterface.changeColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.STRING(255), + allowNull: true, + comment: '授权基础地址', + }); + }, +}; diff --git a/database/migrations/20260527114000-add-get-auth-platform-name-to-wms-print-platform.js b/database/migrations/20260527114000-add-get-auth-platform-name-to-wms-print-platform.js new file mode 100644 index 0000000..57450c4 --- /dev/null +++ b/database/migrations/20260527114000-add-get-auth-platform-name-to-wms-print-platform.js @@ -0,0 +1,69 @@ +'use strict'; + +const TABLE_NAME = 'wms_print_platform'; +const COLUMN_NAME = 'get_auth_platform_name'; + +/** + * 判断目标字段是否已存在。 + * @param {Object} columns 字段定义集合。 + * @return {boolean} 字段是否存在。 + */ +const hasTargetColumn = columns => { + return Boolean(columns && columns[COLUMN_NAME]); +}; + +module.exports = { + /** + * 正向迁移:为打印平台表新增获取授权平台名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (hasTargetColumn(columns)) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { + type: Sequelize.STRING(100), + allowNull: true, + comment: '获取授权平台名称', + }); + }, + + /** + * 回滚迁移:删除打印平台表的获取授权平台名称字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const tableNames = await queryInterface.showAllTables(); + const existingTableSet = new Set( + tableNames.map(table => (typeof table === 'string' ? table : table.tableName)) + ); + + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!hasTargetColumn(columns)) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, +}; diff --git a/database/migrations/20260527220000-migrate-wms-express-code-dyxd-to-dy.js b/database/migrations/20260527220000-migrate-wms-express-code-dyxd-to-dy.js new file mode 100644 index 0000000..045259f --- /dev/null +++ b/database/migrations/20260527220000-migrate-wms-express-code-dyxd-to-dy.js @@ -0,0 +1,160 @@ +'use strict'; + +const TABLE_NAME = 'wms_express'; +const OLD_CODE = 'DYXD'; +const NEW_CODE = 'DY'; + +/** + * 规范化 showAllTables 返回的表名。 + * @param {string|Object} table 表名或表对象。 + * @return {string} 规范化后的表名。 + */ +const normalizeTableName = table => { + if (typeof table === 'string') { + return table; + } + + return table && typeof table === 'object' + ? (table.tableName || table.name || '') + : ''; +}; + +/** + * 检查目标表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 目标表是否存在。 + */ +const hasTargetTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(TABLE_NAME); +}; + +/** + * 读取指定编码的快递记录。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} code 快递编码。 + * @return {Promise} 快递记录;不存在时返回 null。 + */ +const findExpressByCode = async (queryInterface, code) => { + const rows = await queryInterface.sequelize.query( + `SELECT * FROM ${TABLE_NAME} WHERE code = :code LIMIT 1`, + { + type: queryInterface.sequelize.QueryTypes.SELECT, + replacements: { code }, + } + ); + + return rows && rows[0] ? rows[0] : null; +}; + +/** + * 升级迁移:将 wms_express.code 从 DYXD 迁移为 DY。 + * + * 冲突处理策略: + * 1. 仅存在 DYXD:直接改为 DY; + * 2. 同时存在 DY 与 DYXD:将 DYXD 的空值补齐到 DY,再删除 DYXD; + * 3. 不存在 DYXD:视为已完成,保持幂等。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const oldRow = await findExpressByCode(queryInterface, OLD_CODE); + if (!oldRow) { + return; + } + + const newRow = await findExpressByCode(queryInterface, NEW_CODE); + + if (!newRow) { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET code = :newCode WHERE code = :oldCode`, + { + replacements: { + newCode: NEW_CODE, + oldCode: OLD_CODE, + }, + } + ); + return; + } + + await queryInterface.sequelize.transaction(async transaction => { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} + SET + name = COALESCE(NULLIF(name, ''), :oldName), + KS = COALESCE(NULLIF(KS, ''), :oldKS), + PDD = COALESCE(NULLIF(PDD, ''), :oldPDD), + DYXD = COALESCE(NULLIF(DYXD, ''), :oldDYXD), + CAINIAO = COALESCE(NULLIF(CAINIAO, ''), :oldCAINIAO), + polyapi_extra_info = COALESCE(polyapi_extra_info, :oldPolyapiExtraInfo) + WHERE code = :newCode`, + { + replacements: { + newCode: NEW_CODE, + oldName: oldRow.name, + oldKS: oldRow.KS, + oldPDD: oldRow.PDD, + oldDYXD: oldRow.DYXD, + oldCAINIAO: oldRow.CAINIAO, + oldPolyapiExtraInfo: oldRow.polyapi_extra_info, + }, + transaction, + } + ); + + await queryInterface.sequelize.query( + `DELETE FROM ${TABLE_NAME} WHERE code = :oldCode`, + { + replacements: { oldCode: OLD_CODE }, + transaction, + } + ); + }); +}; + +/** + * 回滚迁移:将 wms_express.code 从 DY 恢复为 DYXD。 + * + * 仅在 DYXD 不存在时执行恢复;若已存在 DYXD 则跳过,避免主键冲突。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const oldRow = await findExpressByCode(queryInterface, OLD_CODE); + if (oldRow) { + return; + } + + const newRow = await findExpressByCode(queryInterface, NEW_CODE); + if (!newRow) { + return; + } + + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET code = :oldCode WHERE code = :newCode`, + { + replacements: { + oldCode: OLD_CODE, + newCode: NEW_CODE, + }, + } + ); +}; diff --git a/database/migrations/20260527233000-rename-wms-express-column-dyxd-to-dy.js b/database/migrations/20260527233000-rename-wms-express-column-dyxd-to-dy.js new file mode 100644 index 0000000..f9f35a1 --- /dev/null +++ b/database/migrations/20260527233000-rename-wms-express-column-dyxd-to-dy.js @@ -0,0 +1,126 @@ +'use strict'; + +const TABLE_NAME = 'wms_express'; +const OLD_COLUMN = 'DYXD'; +const NEW_COLUMN = 'DY'; + +/** + * 规范化 showAllTables 返回的表名。 + * @param {string|Object} table 表名或表对象。 + * @return {string} 规范化后的表名。 + */ +const normalizeTableName = table => { + if (typeof table === 'string') { + return table; + } + + return table && typeof table === 'object' + ? (table.tableName || table.name || '') + : ''; +}; + +/** + * 检查目标表是否存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 表是否存在。 + */ +const hasTargetTable = async queryInterface => { + const allTables = await queryInterface.showAllTables(); + const tableSet = new Set((allTables || []).map(normalizeTableName)); + return tableSet.has(TABLE_NAME); +}; + +/** + * 合并列值:当目标列为空时,用源列值补齐。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Object} transaction Sequelize 事务对象。 + * @param {string} targetColumn 目标列名。 + * @param {string} sourceColumn 源列名。 + * @return {Promise} 无返回值。 + */ +const mergeColumnValues = async (queryInterface, transaction, targetColumn, sourceColumn) => { + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} + SET ${targetColumn} = COALESCE(NULLIF(${targetColumn}, ''), ${sourceColumn}) + WHERE ${sourceColumn} IS NOT NULL AND ${sourceColumn} <> ''`, + { + transaction, + } + ); +}; + +/** + * 执行升级迁移:将 wms_express.DYXD 重命名为 DY(幂等)。 + * + * 处理策略: + * 1. 仅存在 DYXD:使用 renameColumn 改名为 DY。 + * 2. 同时存在 DY 与 DYXD:将 DYXD 的非空值补齐到 DY,再删除 DYXD。 + * 3. 不存在 DYXD:视为已完成,直接跳过。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.up = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const hasOldColumn = Object.prototype.hasOwnProperty.call(columns, OLD_COLUMN); + const hasNewColumn = Object.prototype.hasOwnProperty.call(columns, NEW_COLUMN); + + if (!hasOldColumn) { + return; + } + + if (!hasNewColumn) { + await queryInterface.renameColumn(TABLE_NAME, OLD_COLUMN, NEW_COLUMN); + return; + } + + await queryInterface.sequelize.transaction(async transaction => { + await mergeColumnValues(queryInterface, transaction, NEW_COLUMN, OLD_COLUMN); + await queryInterface.removeColumn(TABLE_NAME, OLD_COLUMN, { transaction }); + }); +}; + +/** + * 执行回滚迁移:将 wms_express.DY 回滚为 DYXD(幂等)。 + * + * 处理策略: + * 1. 仅存在 DY:使用 renameColumn 改名回 DYXD。 + * 2. 同时存在 DY 与 DYXD:将 DY 的非空值补齐到 DYXD,再删除 DY。 + * 3. 不存在 DY:视为已回滚,直接跳过。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ +module.exports.down = async (queryInterface, Sequelize) => { + void Sequelize; + + if (!(await hasTargetTable(queryInterface))) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + const hasOldColumn = Object.prototype.hasOwnProperty.call(columns, OLD_COLUMN); + const hasNewColumn = Object.prototype.hasOwnProperty.call(columns, NEW_COLUMN); + + if (!hasNewColumn) { + return; + } + + if (!hasOldColumn) { + await queryInterface.renameColumn(TABLE_NAME, NEW_COLUMN, OLD_COLUMN); + return; + } + + await queryInterface.sequelize.transaction(async transaction => { + await mergeColumnValues(queryInterface, transaction, OLD_COLUMN, NEW_COLUMN); + await queryInterface.removeColumn(TABLE_NAME, NEW_COLUMN, { transaction }); + }); +}; diff --git a/database/migrations/20260528090000-create-wms-package-material-and-supplier.js b/database/migrations/20260528090000-create-wms-package-material-and-supplier.js new file mode 100644 index 0000000..dac0f3a --- /dev/null +++ b/database/migrations/20260528090000-create-wms-package-material-and-supplier.js @@ -0,0 +1,283 @@ +'use strict'; + +const PACKAGE_MATERIAL_TABLE = 'wms_package_material'; +const PACKAGE_SUPPLIER_TABLE = 'wms_package_supplier'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +/** + * 创建包材表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPackageMaterialTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(PACKAGE_MATERIAL_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + material_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '包材编码', + }, + material_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '包材名称', + }, + material_type: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '包材类型', + }, + spec: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '规格描述', + }, + length: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '长度(cm)', + }, + width: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '宽度(cm)', + }, + height: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '高度(cm)', + }, + weight: { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '重量(kg)', + }, + cost_price: { + type: Sequelize.DECIMAL(10, 2), + allowNull: true, + comment: '成本单价', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '包材信息表', + }); +}; + +/** + * 创建包材供应商表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPackageSupplierTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable(PACKAGE_SUPPLIER_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + supplier_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '供应商编码', + }, + supplier_name: { + type: Sequelize.STRING(128), + allowNull: false, + comment: '供应商名称', + }, + contact_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '联系人', + }, + contact_phone: { + type: Sequelize.STRING(32), + allowNull: true, + comment: '联系电话', + }, + status: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '状态:0=禁用,1=启用', + }, + version: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '版本号', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '包材供应商表', + }); +}; + +/** + * 确保包材表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensurePackageMaterialIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, PACKAGE_MATERIAL_TABLE); + + if (!indexNameSet.has('idx_wms_package_material_warehouse_id')) { + await queryInterface.addIndex(PACKAGE_MATERIAL_TABLE, [ 'warehouse_id' ], { + name: 'idx_wms_package_material_warehouse_id', + }); + } + + if (!indexNameSet.has('uk_wms_package_material_warehouse_material_code')) { + await queryInterface.addIndex(PACKAGE_MATERIAL_TABLE, [ 'warehouse_id', 'material_code' ], { + name: 'uk_wms_package_material_warehouse_material_code', + unique: true, + }); + } +}; + +/** + * 确保包材供应商表索引存在。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ +const ensurePackageSupplierIndexes = async queryInterface => { + const indexNameSet = await getIndexNameSet(queryInterface, PACKAGE_SUPPLIER_TABLE); + + if (!indexNameSet.has('idx_wms_package_supplier_warehouse_id')) { + await queryInterface.addIndex(PACKAGE_SUPPLIER_TABLE, [ 'warehouse_id' ], { + name: 'idx_wms_package_supplier_warehouse_id', + }); + } + + if (!indexNameSet.has('uk_wms_package_supplier_warehouse_supplier_code')) { + await queryInterface.addIndex(PACKAGE_SUPPLIER_TABLE, [ 'warehouse_id', 'supplier_code' ], { + name: 'uk_wms_package_supplier_warehouse_supplier_code', + unique: true, + }); + } +}; + +module.exports = { + /** + * 创建包材与包材供应商表及索引。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has(PACKAGE_MATERIAL_TABLE)) { + await createPackageMaterialTable(queryInterface, Sequelize); + } + + if (!existingTables.has(PACKAGE_SUPPLIER_TABLE)) { + await createPackageSupplierTable(queryInterface, Sequelize); + } + + await ensurePackageMaterialIndexes(queryInterface); + await ensurePackageSupplierIndexes(queryInterface); + }, + + /** + * 回滚删除包材与包材供应商表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + void Sequelize; + + const existingTables = await getExistingTableSet(queryInterface); + + if (existingTables.has(PACKAGE_SUPPLIER_TABLE)) { + await queryInterface.dropTable(PACKAGE_SUPPLIER_TABLE); + } + + if (existingTables.has(PACKAGE_MATERIAL_TABLE)) { + await queryInterface.dropTable(PACKAGE_MATERIAL_TABLE); + } + }, +}; diff --git a/database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js b/database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js new file mode 100644 index 0000000..9e31495 --- /dev/null +++ b/database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js @@ -0,0 +1,74 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; +const MATERIAL_ID_COLUMN = 'package_material_id'; +const MATERIAL_NAME_SNAPSHOT_COLUMN = 'package_material_name_snapshot'; +const MATERIAL_ID_INDEX = 'idx_wms_order_express_package_material_id'; + +/** + * 获取指定表的索引名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async (queryInterface, tableName) => { + const indexes = await queryInterface.showIndex(tableName); + return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); +}; + +module.exports = { + /** + * 执行迁移:为订单快递表新增包材字段并补齐索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (!columns[MATERIAL_ID_COLUMN]) { + await queryInterface.addColumn(TABLE_NAME, MATERIAL_ID_COLUMN, { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '包材ID', + }); + } + + if (!columns[MATERIAL_NAME_SNAPSHOT_COLUMN]) { + await queryInterface.addColumn(TABLE_NAME, MATERIAL_NAME_SNAPSHOT_COLUMN, { + type: Sequelize.STRING(128), + allowNull: true, + comment: '包材名称快照', + }); + } + + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + if (!indexNameSet.has(MATERIAL_ID_INDEX)) { + await queryInterface.addIndex(TABLE_NAME, [ MATERIAL_ID_COLUMN ], { + name: MATERIAL_ID_INDEX, + }); + } + }, + + /** + * 回滚迁移:删除订单快递表包材字段及索引(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const columns = await queryInterface.describeTable(TABLE_NAME); + const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); + + if (indexNameSet.has(MATERIAL_ID_INDEX)) { + await queryInterface.removeIndex(TABLE_NAME, MATERIAL_ID_INDEX); + } + + if (columns[MATERIAL_NAME_SNAPSHOT_COLUMN]) { + await queryInterface.removeColumn(TABLE_NAME, MATERIAL_NAME_SNAPSHOT_COLUMN); + } + + if (columns[MATERIAL_ID_COLUMN]) { + await queryInterface.removeColumn(TABLE_NAME, MATERIAL_ID_COLUMN); + } + }, +}; diff --git a/database/migrations/20260528100000-drop-platid-from-wms-platform.js b/database/migrations/20260528100000-drop-platid-from-wms-platform.js new file mode 100644 index 0000000..3282184 --- /dev/null +++ b/database/migrations/20260528100000-drop-platid-from-wms-platform.js @@ -0,0 +1,68 @@ +'use strict'; + +const TABLE_NAME = 'wms_platform'; +const COLUMN_NAME = 'platid'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建 wms_platform.platid 字段定义。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Object} 字段定义。 + */ +const buildPlatidColumn = Sequelize => ({ + type: Sequelize.INTEGER(11), + allowNull: true, + comment: '平台ID', +}); + +module.exports = { + /** + * 正向迁移:幂等删除 wms_platform.platid。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (!columns[COLUMN_NAME]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); + }, + + /** + * 回滚迁移:幂等恢复 wms_platform.platid。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface, Sequelize) { + const existingTableSet = await getExistingTableSet(queryInterface); + if (!existingTableSet.has(TABLE_NAME)) { + return; + } + + const columns = await queryInterface.describeTable(TABLE_NAME); + if (columns[COLUMN_NAME]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, buildPlatidColumn(Sequelize)); + }, +}; \ No newline at end of file diff --git a/database/migrations/20260528110000-add-weighing-weight-to-wms-order-express.js b/database/migrations/20260528110000-add-weighing-weight-to-wms-order-express.js new file mode 100644 index 0000000..65d9211 --- /dev/null +++ b/database/migrations/20260528110000-add-weighing-weight-to-wms-order-express.js @@ -0,0 +1,41 @@ +'use strict'; + +const TABLE_NAME = 'wms_order_express'; +const WEIGHING_WEIGHT_COLUMN = 'weighing_weight'; + +module.exports = { + /** + * 执行迁移:为订单快递表新增称重重量字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface, Sequelize) { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (columns[WEIGHING_WEIGHT_COLUMN]) { + return; + } + + await queryInterface.addColumn(TABLE_NAME, WEIGHING_WEIGHT_COLUMN, { + type: Sequelize.DECIMAL(10, 3), + allowNull: true, + comment: '称重重量(kg)', + }); + }, + + /** + * 回滚迁移:删除订单快递表称重重量字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const columns = await queryInterface.describeTable(TABLE_NAME); + + if (!columns[WEIGHING_WEIGHT_COLUMN]) { + return; + } + + await queryInterface.removeColumn(TABLE_NAME, WEIGHING_WEIGHT_COLUMN); + }, +}; diff --git a/db_query.js b/db_query.js new file mode 100644 index 0000000..73e6c5a --- /dev/null +++ b/db_query.js @@ -0,0 +1,47 @@ +const Sequelize = require('sequelize'); +const config = { + dialect: 'mysql', + host: '127.0.0.1', + port: 3307, + database: 'wms', + username: 'wms', + password: 'dspxmRwRdRbWtbm7', + logging: false +}; + +const sequelize = new Sequelize(config.database, config.username, config.password, config); + +async function run() { + try { + const results = {}; + + const [dyxdCountResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DYXD'"); + results.dyxdCount = dyxdCountResult[0].count; + + const [dyCountResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_platform WHERE code='DY'"); + results.dyCount = dyCountResult[0].count; + + const [dyRowResult] = await sequelize.query("SELECT * FROM wms_platform WHERE code='DY' LIMIT 1"); + results.dyRow = dyRowResult[0] || null; + + // The user asked for "metaExists (SequelizeMeta 是否存在该 migration 记录)" + // Based on previous terminal logs, the migration file name or pattern seems to be related to "platform_code" or "wms_platform" + const [metaResult] = await sequelize.query("SELECT * FROM SequelizeMeta"); + const migrationName = '20250303080004-platform_code.js'; // This is an assumption based on common naming. + // Let's search for any record that contains 'platform' in the name. + const exists = metaResult.some(m => m.name.includes('platform')); + results.metaExists = exists; + + try { + const [expressTotalResult] = await sequelize.query("SELECT COUNT(*) as count FROM wms_express"); + results.expressTotal = expressTotalResult[0].count; + } catch (e) {} + + console.log(JSON.stringify(results, null, 2)); + } catch (error) { + console.error(error); + } finally { + await sequelize.close(); + } +} +run(); diff --git a/docs/express-model-table-map.md b/docs/express-model-table-map.md index fa9a110..75bddcd 100644 --- a/docs/express-model-table-map.md +++ b/docs/express-model-table-map.md @@ -20,3 +20,14 @@ - 将 `index.getExpressList` 的配置源(`app.config.expressList`)逐步收敛到 `wms_express`,避免配置与数据表双源。 - 若后续存在统一查询需求,可新增 `systems/express.js`,统一对 `Express / ExpressSetting / OrderExpress` 的读写入口。 + +## 包材关联字段说明 + +- **新增字段**:`wms_order_express.package_material_id`(可空,BIGINT unsigned)、`wms_order_express.package_material_name_snapshot`(可空,VARCHAR(128))。用于记录订单快递所使用的包材引用与名称快照,`package_material_id` 指向 `wms_package_material.id`。 +- **新增表**:`wms_package_material`(包材主数据表)和 `wms_package_supplier`(包材供应商表),均已在 migration 与 model 中定义;关键索引:`idx_wms_package_material_warehouse_id`、`uk_wms_package_material_warehouse_material_code`、`idx_wms_package_supplier_warehouse_id`、`uk_wms_package_supplier_warehouse_supplier_code`。 +- **索引**:为 `wms_order_express.package_material_id` 新增索引 `idx_wms_order_express_package_material_id`,以支持基于包材的过滤与联表查询。 +- **兼容性**:新增列为可空,不会破坏现有接口契约。若系统存在将 `wms_order_express` 全量返回给外部的接口(未在 methods/system.json 中声明新增字段),请在需要暴露字段的接口中补充文档说明并在变更记录中标注。当前已检查的 system 方法文档未需修改,因此本次不改 methods/system.json(无接口契约变化)。 +- **回滚要点**:迁移的 down 会删除新增列、索引与新增表;回滚前请务必备份或迁移相关业务数据。 + +文档维护者:WMS 文档代理 + diff --git a/lint_result.txt b/lint_result.txt new file mode 100644 index 0000000..2301bc9 Binary files /dev/null and b/lint_result.txt differ diff --git a/memories/repo/express-platform-code-routing.md b/memories/repo/express-platform-code-routing.md new file mode 100644 index 0000000..247a13f --- /dev/null +++ b/memories/repo/express-platform-code-routing.md @@ -0,0 +1,4 @@ +- 运单分组链路必须是:订单的 sys_platform_code -> wms_platform.print_platform_id -> wms_print_platform.platform_code。 +- 快递接口匹配与 listByWarehousePlatformCode 的 platform_code 必须使用 wms_print_platform.platform_code,不可直接回退为 sys_platform_code。 +- 分组维度必须使用 wms_print_platform.platform_code + logistics_code;如果缺少打印平台映射,应视为缺少有效匹配上下文,而不是改回 sys_platform_code 直连。 +- 相关代码锚点:app/service/systems/express.js、app/service/systems/platform.js、app/model/express_interface.js。 diff --git a/methods/changes/2026.05.28-system-01.json b/methods/changes/2026.05.28-system-01.json new file mode 100644 index 0000000..9505497 --- /dev/null +++ b/methods/changes/2026.05.28-system-01.json @@ -0,0 +1,19 @@ +[ + { + "version": "2026.05.28-system-01", + "date": "2026-05-28", + "summary": "新增包材相关表与在订单快递表新增包材关联字段(wms_package_material / wms_package_supplier / wms_order_express)", + "methods": [], + "notes": [ + "新增表 wms_package_material:主要字段 id, warehouse_id, material_code, material_name, material_type, spec, length, width, height, weight, cost_price, status, version, created_at, updated_at;索引:idx_wms_package_material_warehouse_id(warehouse_id),uk_wms_package_material_warehouse_material_code(warehouse_id + material_code 唯一)。", + "新增表 wms_package_supplier:主要字段 id, warehouse_id, supplier_code, supplier_name, contact_name, contact_phone, status, version, created_at, updated_at;索引:idx_wms_package_supplier_warehouse_id(warehouse_id),uk_wms_package_supplier_warehouse_supplier_code(warehouse_id + supplier_code 唯一)。", + "修改表 wms_order_express:新增可空字段 package_material_id (BIGINT unsigned) 与 package_material_name_snapshot (VARCHAR(128));新增索引 idx_wms_order_express_package_material_id(package_material_id)。", + "回滚要点:迁移脚本的 down 实现会移除上述索引与列,并删除新增的两张表(详见 database/migrations/20260528090000-create-wms-package-material-and-supplier.js 与 database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js)。生产回滚前请先迁移或备份依赖数据并通知下游系统。", + "兼容性说明:新增列均为可空(nullable),属于向后兼容的增量变更,不会影响现有查询或写入;若服务端或前端存在把 wms_order_express 全量序列化到外部响应的场景,响应中可能会包含这两个可选字段;目前已检查的对外 system 方法文档未声明返回 package_material_id 或 package_material_name_snapshot,因此本次不修改 methods/system.json(无接口契约变化)。", + "相关模型文件:新增 app/model/package_material.js、app/model/package_supplier.js;更新 app/model/order_express.js(新增字段与索引定义)。", + "验证建议:1) 在预发布环境执行 migrations up/down 并确认幂等性;2) 执行下单→分配快递→打印等关键路径以验证无回归;3) 若需要对外暴露包材字段,请在 methods/system.json 中补充对应接口的 response 字段并在变更记录中说明。" + ], + "type": "updated", + "module": "database" + } +] diff --git a/methods/changes/system.json b/methods/changes/system.json index da3a8d2..f80f8f2 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2353,18 +2353,131 @@ { "version": "2026.05.25-system-02", "date": "2026-05-25", - "summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shop.GetAuthorizeSessionKey", + "summary": "新增店铺模块相关接口文档(shops.list/add/del/edit)及授权会话接口 shops.GetAuthorizeSessionKey", "methods": [ "shops.list", "shops.add", "shops.del", "shops.edit", - "shop.GetAuthorizeSessionKey" + "shops.GetAuthorizeSessionKey" ], "notes": [ - "同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shop.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。", + "同步实现:shops.list 支持 where 分页与 quickWhere 快速搜索;shops.add/edit 校验 platform_code 存在且为 ACTIVE,custom_name 必填且长度限制;shops.del 为软删除,会返回 deleted=true 并清空敏感字段,若存在快递接口引用返回 409;shops.GetAuthorizeSessionKey 对 PDD/CAINIAO 平台生成预占码并返回 authorize_url,其他平台返回 501。", "字段命名兼容说明:接口实现兼容 snake_case 与 camelCase 入参,文档以 snake_case 为主并注明兼容性。" ], "type": "added" + }, + { + "version": "2026.05.25-system-03", + "date": "2026-05-25", + "summary": "同步 shops.add 去入参化:移除 shop_name 入参并明确由授权后获取店铺名称", + "methods": [ + "shops.add" + ], + "notes": [ + "shops.add 入参移除 shop_name(及同义传参语义),仅保留 custom_name 与 platform_code 为关键请求字段。", + "补充说明:新增时 shop_name 由服务端生成 PENDING_* 占位名,后续以授权回调同步真实店铺名称。", + "仅文档同步,不修改任何业务代码。" + ], + "type": "updated", + "module": "shops" + }, + { + "version": "2026.05.28-system-02", + "date": "2026-05-28", + "summary": "新增 method: order.print.unlockWavePlatformPrintDataByGroup,按分组解锁波次平台打印锁", + "methods": [ + "order.print.unlockWavePlatformPrintDataByGroup" + ], + "notes": [ + "新增方法:order.print.unlockWavePlatformPrintDataByGroup,用于按分组规则批量解锁波次内被锁定的订单(将 print_lock_status 设为 'none')。", + "入参说明:group_type 默认为 platform_express(支持 platform、platform_express、order),unlock_scope 默认为 group(支持 group、wave);groups 为必须项,元素对象可包含 wave_id、platform、sys_logistics_code、order_ids 等字段。", + "返回说明:返回 summary(解锁统计)、unlocked_order_ids、unlocked_orders、ext.missing_wave_ids、ext.filtered_wave_ids 等字段。", + "实现参考:app/service/systemMethods/order/print.js 与 app/service/systems/order_print.js 的 unlockWavePlatformPrintDataByGroup 实现,相关单元测试位于 test/app/controller/system.order.print.unlockByGroup.test.js 与 test/app/service/systems/order_print.unlockWavePlatformPrintDataByGroup.test.js。" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-03", + "date": "2026-05-28", + "summary": "新增 order.updateExpressWeighingWeight 方法文档并补充单/多运单称重写入规则", + "methods": [ + "order.updateExpressWeighingWeight" + ], + "notes": [ + "新增 order.updateExpressWeighingWeight 入参说明:order_id、waybill_code、weighing_weight。", + "明确规则:单运单订单忽略 waybill_code 并直接更新唯一运单;多运单订单必须传 waybill_code 且需匹配订单下运单。", + "补充成功返回字段:order_id、waybill_code、weighing_weight。", + "补充错误码:400(参数校验与多运单缺失运单号)、404(运单记录不存在或未匹配)、500(模型未初始化或更新失败)。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.28-system-01", + "date": "2026-05-28", + "summary": "新增包材相关 methods(create/update/delete/get),并提供 list 兼容说明", + "methods": [ + "setting.packageMaterial.create", + "setting.packageMaterial.update", + "setting.packageMaterial.delete", + "setting.packageMaterial.get", + "setting.packageMaterial.list" + ], + "notes": [ + "实现参考:app/service/systems/setting/packageMaterial.js", + "list 为兼容别名,内部转发至 get,建议新接入方改用 get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-04", + "date": "2026-05-28", + "summary": "Add packageSupplier methods (create/update/delete/get) with list alias note", + "methods": [ + "setting.packageSupplier.create", + "setting.packageSupplier.update", + "setting.packageSupplier.delete", + "setting.packageSupplier.get", + "setting.packageSupplier.list" + ], + "notes": [ + "Reference implementation: app/service/systems/setting/packageSupplier.js", + "list is a compatibility alias; prefer get" + ], + "type": "updated" + }, + { + "version": "2026.05.28-system-05", + "date": "2026-05-28", + "summary": "新增 order.bindExpressPackageMaterial 方法文档,支持按订单运单绑定包材", + "methods": [ + "order.bindExpressPackageMaterial" + ], + "notes": [ + "新增 order.bindExpressPackageMaterial 入参说明:order_id、waybill_code、package_material_code(均必填)。", + "补充行为说明:按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材并绑定 package_material_id 与 package_material_name_snapshot。", + "补充成功返回字段:order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。", + "补充错误码:400 参数错误、404 包材编码不存在、404 订单运单记录不存在、500 绑定包材失败。", + "仅通过文档脚本同步 methods/system.json 与 methods/changes/system.json,不修改业务代码。" + ], + "type": "added", + "module": "order.index" + }, + { + "version": "2026.05.29-system-01", + "date": "2026-05-29", + "summary": "新增 order.export 与 order.exportTaskProgress:订单导出异步任务与进度查询", + "methods": [ + "order.export", + "order.exportTaskProgress" + ], + "notes": [ + "order.export:提交导出任务,入参支持 table_type/tableType(枚举 current/history/dispatch/outsourced,兼容订单模块别名)与 module/module_name,where/sort 语义与 order.list 一致。接口提交后立即返回 task_id,后台异步执行导出,导出进度与结果通过 order.exportTaskProgress 查询。", + "order.exportTaskProgress:按 task_id 查询任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;任务上传完成后 download_url 返回可下载链接,未找到时 status=not_found。" + ], + "type": "added", + "module": "order.index" } ] diff --git a/methods/system.json b/methods/system.json index 29a4cb8..3efa461 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.0.1", - "updatedAt": "2026-05-25", + "version": "0.0.4", + "updatedAt": "2026-05-29", "headers": [ { "name": "platform", @@ -1928,6 +1928,387 @@ "description": "内部错误" } ] + }, + { + "method": "order.updateExpressWeighingWeight", + "description": "更新订单运单称重重量。规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "订单ID,必填且必须为正整数。" + }, + { + "name": "waybill_code", + "type": "string", + "required": false, + "source": "body", + "description": "运单号;订单仅一个运单时可不传且会被忽略,多运单时必填并需匹配订单下运单。" + }, + { + "name": "weighing_weight", + "type": "number|string", + "required": true, + "source": "body", + "description": "称重重量(kg),必填,必须大于 0,最多支持 3 位小数。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID(成功时返回于 data 对象中)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "写入重量的运单号(成功时返回于 data 对象中)。" + }, + { + "name": "weighing_weight", + "type": "number", + "required": true, + "description": "已写入的称重重量(kg,成功时返回于 data 对象中)。" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 必填且必须为正整数" + }, + { + "code": 400, + "message": "weighing_weight 必填" + }, + { + "code": 400, + "message": "weighing_weight 格式非法,最多支持 3 位小数" + }, + { + "code": 400, + "message": "weighing_weight 必须大于 0" + }, + { + "code": 400, + "message": "多运单订单必须传入 waybill_code" + }, + { + "code": 404, + "message": "未找到有效的订单运单记录" + }, + { + "code": 404, + "message": "waybill_code 未匹配到该订单下的运单记录" + }, + { + "code": 500, + "message": "订单快递模型未初始化" + }, + { + "code": 500, + "message": "更新称重重量失败" + } + ] + }, + { + "method": "order.bindExpressPackageMaterial", + "description": "按订单ID+运单号匹配 wms_order_express,按包材编码匹配包材,并将 package_material_id 与 package_material_name_snapshot 绑定到订单运单记录。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number|string", + "required": true, + "source": "body", + "description": "订单ID,必填。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "source": "body", + "description": "运单号,必填。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "source": "body", + "description": "包材编码,必填。" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID(成功时返回于 data 对象中)。" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_id", + "type": "number", + "required": true, + "description": "绑定后的包材ID(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_name_snapshot", + "type": "string", + "required": true, + "description": "绑定时写入的包材名称快照(成功时返回于 data 对象中)。" + }, + { + "name": "package_material_code", + "type": "string", + "required": true, + "description": "绑定成功的包材编码(成功时返回于 data 对象中)。" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 404, + "message": "包材编码不存在" + }, + { + "code": 404, + "message": "订单运单记录不存在" + }, + { + "code": 500, + "message": "绑定包材失败" + } + ] + }, + { + "method": "order.export", + "description": "提交订单导出任务(异步)。入参支持 table_type/tableType 与 module/module_name;where 与 sort 语义与 order.list 一致。提交后立即返回 task_id,后台异步执行,导出进度/下载请通过 order.exportTaskProgress 查询。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "table_type / tableType", + "type": "string", + "required": false, + "source": "body", + "description": "导出表类型,枚举:current/history/dispatch/outsourced;兼容订单模块别名(order/reviewOrder/pendingOrder 等);支持 table_type 与 tableType 两种写法" + }, + { + "name": "module / module_name", + "type": "string", + "required": false, + "source": "body", + "description": "订单模块名,兼容 module(驼峰)与 module_name(下划线)两种写法" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件,语义与 order.list 的 where 一致(推荐使用 { operator, value, type } 标准结构);禁止传入 warehouse_id/warehouseId" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,语义与 order.list 的 sort 一致" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID(后端生成)", + "required": true + }, + { + "name": "status", + "type": "string", + "description": "任务状态,枚举:submitted/running/success/failed/not_found", + "required": true + }, + { + "name": "progress", + "type": "number", + "description": "当前进度百分比(0-100)", + "required": true + }, + { + "name": "current_count", + "type": "number", + "description": "当前已处理记录数", + "required": true + }, + { + "name": "total_count", + "type": "number", + "description": "总记录数(若有)", + "required": true + }, + { + "name": "message", + "type": "string", + "description": "任务提示信息", + "required": true + }, + { + "name": "result", + "type": "object", + "description": "任务执行结果(可选,可能包含文件 url/fileKey 等)", + "required": true + }, + { + "name": "error", + "type": "string", + "description": "失败时的错误信息(可选)", + "required": true + }, + { + "name": "update_time", + "type": "string", + "description": "任务更新时间(Unix ms 或 ISO 字符串)", + "required": true + } + ], + "errors": [ + { + "code": 400, + "message": "参数格式不正确或 where 条件非法" + }, + { + "code": 500, + "message": "导出任务提交失败" + } + ] + }, + { + "method": "order.exportTaskProgress", + "description": "按 task_id 查询订单导出任务进度,返回 task_id、status、progress、current_count、total_count、message、error、download_url、update_time;上传完成后 download_url 返回下载链接;未找到时 status=not_found。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务 ID,兼容 taskId" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "description": "任务 ID", + "required": true + }, + { + "name": "status", + "type": "string", + "description": "任务状态:submitted/running/success/failed/not_found", + "required": true + }, + { + "name": "progress", + "type": "number", + "description": "进度百分比(0-100)", + "required": true + }, + { + "name": "current_count", + "type": "number", + "description": "当前已处理记录数", + "required": true + }, + { + "name": "total_count", + "type": "number", + "description": "总记录数", + "required": true + }, + { + "name": "message", + "type": "string", + "description": "额外提示信息", + "required": true + }, + { + "name": "error", + "type": "string", + "description": "失败信息(可选)", + "required": true + }, + { + "name": "download_url", + "type": "string", + "description": "任务完成后下载链接(若有)", + "required": true + }, + { + "name": "update_time", + "type": "string", + "description": "最近一次状态更新时间(Unix ms 或 ISO 字符串)", + "required": true + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + }, + { + "code": 500, + "message": "查询失败或内部错误" + } + ] } ] }, @@ -8203,6 +8584,209 @@ "description": "查询失败" } ] + }, + { + "method": "order.print.unlockWavePlatformPrintDataByGroup", + "description": "按分组解锁波次平台打印锁:按传入的 groups 条件匹配已锁定订单并将其 print_lock_status 置为 none,返回解锁统计与解锁订单列表。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID(必须与当前用户上下文 store_id 一致)" + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "source": "body", + "description": "波次ID列表(支持数字或字符串,内部自动去重与归一化)" + }, + { + "name": "group_type", + "type": "string", + "required": false, + "source": "body", + "description": "分组类型,支持 platform、platform_express、order;默认 platform_express" + }, + { + "name": "unlock_scope", + "type": "string", + "required": false, + "source": "body", + "description": "解锁范围,支持 group、wave;默认 group" + }, + { + "name": "groups", + "type": "array", + "required": true, + "source": "body", + "description": "分组条件列表。元素为对象,可包含字段:wave_id(必填)、platform(平台编码)、sys_logistics_code(系统快递编码)、order_ids(订单ID数组)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID(单个规则指定的波次)" + }, + { + "name": "platform", + "type": "string", + "description": "平台编码(当 group_type 为 platform/platform_express 时可能必需)" + }, + { + "name": "sys_logistics_code", + "type": "string", + "description": "系统快递编码(当 group_type 为 platform_express 时可能必需)" + }, + { + "name": "order_ids", + "type": "array", + "description": "订单ID列表(当 group_type 为 order 时必需)" + } + ] + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "required": true, + "description": "解锁操作的汇总统计", + "children": [ + { + "name": "total_waves", + "type": "number", + "description": "有效波次数(通过过滤的波次数)" + }, + { + "name": "total_locked_orders", + "type": "number", + "description": "有效波次中原本被锁定的订单总数" + }, + { + "name": "matched_group_orders", + "type": "number", + "description": "匹配到分组规则的被锁定订单数" + }, + { + "name": "unlocked_count", + "type": "number", + "description": "实际已更新为 unlocked 的订单数量(update 影响数)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "description": "通过过滤的波次ID数组" + }, + { + "name": "unlocked_order_ids", + "type": "array", + "required": true, + "description": "被解锁的订单ID数组" + }, + { + "name": "unlocked_orders", + "type": "array", + "required": true, + "description": "被解锁订单简要信息列表", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "order_no", + "type": "string", + "description": "订单号(delivery_order_code 或 source_order_codes)" + } + ] + }, + { + "name": "ext", + "type": "object", + "required": false, + "description": "扩展字段", + "children": [ + { + "name": "missing_wave_ids", + "type": "array", + "description": "传入但不存在的 wave_id 列表" + }, + { + "name": "filtered_wave_ids", + "type": "array", + "description": "被过滤掉的波次(快递未完全分配),每项含 wave_id、wave_no、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "wave_ids 必填,且必须为非空数组", + "description": "wave_ids 必填,且必须为非空数组" + }, + { + "code": "400", + "message": "warehouse_id 必填且必须为正整数", + "description": "warehouse_id 必填且必须为正整数" + }, + { + "code": "400", + "message": "warehouse_id 必须与当前用户上下文 store_id 保持一致", + "description": "warehouse_id 必须与当前用户上下文 store_id 保持一致" + }, + { + "code": "400", + "message": "group_type 仅支持 platform、platform_express、order", + "description": "group_type 仅支持 platform、platform_express、order" + }, + { + "code": "400", + "message": "unlock_scope 仅支持 group、wave", + "description": "unlock_scope 仅支持 group、wave" + }, + { + "code": "400", + "message": "groups 必填,且必须为非空数组", + "description": "groups 必填,且必须为非空数组" + }, + { + "code": "400", + "message": "groups 未匹配到有效的分组解锁条件", + "description": "groups 未匹配到有效的分组解锁条件" + }, + { + "code": "500", + "message": "内部错误", + "description": "内部错误" + } + ] } ] }, @@ -18015,7 +18599,7 @@ }, { "method": "shops.add", - "description": "新增店铺,校验 platform_code 必须匹配已配置且处于 ACTIVE 且未删除的打印平台;custom_name 必填且长度<=100;shop_name 可选,缺失时使用 custom_name。支持 snake_case 与 camelCase 入参兼容。", + "description": "新增店铺,校验 platform_code 必须匹配已配置且处于 ACTIVE 且未删除的打印平台;custom_name 必填且长度<=100。shop_name 由服务端生成待授权占位名(PENDING_*),授权后再同步真实店铺名。支持 snake_case 与 camelCase 入参兼容。", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -18040,13 +18624,6 @@ "required": true, "source": "body", "description": "店铺自定义名称,最大长度 100" - }, - { - "name": "shop_name", - "type": "string", - "required": false, - "source": "body", - "description": "店铺名称,若不传则以 custom_name 作为 shop_name" } ], "response": [ @@ -18263,7 +18840,7 @@ ] }, { - "method": "shop.GetAuthorizeSessionKey", + "method": "shops.GetAuthorizeSessionKey", "description": "按店铺所属平台生成授权会话。入参兼容 id/shop_id/shopId 与 callbackurl/callback_url,callbackurl 必填。对已实现的平台(PDD/CAINIAO)返回 session_key/authorize_url/state,其他平台返回 501 未实现。", "isNeedAuth": true, "isNeedLogin": true, @@ -18375,6 +18952,521 @@ ] } ] + }, + { + "groupName": "包材管理模块", + "module": "setting.packageMaterial", + "list": [ + { + "method": "setting.packageMaterial.create", + "description": "创建包材(当前仓库范围)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "material_code", + "type": "string", + "required": true, + "source": "body", + "description": "包材编码(大写且在当前仓库唯一)" + }, + { + "name": "material_name", + "type": "string", + "required": true, + "source": "body", + "description": "包材名称" + }, + { + "name": "material_type", + "type": "string", + "required": false, + "source": "body", + "description": "包材类型" + }, + { + "name": "spec", + "type": "string", + "required": false, + "source": "body", + "description": "规格" + }, + { + "name": "length", + "type": "number", + "required": false, + "source": "body", + "description": "长度" + }, + { + "name": "width", + "type": "number", + "required": false, + "source": "body", + "description": "宽度" + }, + { + "name": "height", + "type": "number", + "required": false, + "source": "body", + "description": "高度" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "重量" + }, + { + "name": "cost_price", + "type": "number", + "required": false, + "source": "body", + "description": "成本价" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态 0/1,默认 1" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "包材 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 409, + "message": "material_code 冲突" + }, + { + "code": 500, + "message": "服务器错误" + } + ] + }, + { + "method": "setting.packageMaterial.update", + "description": "更新包材(按 id 更新,支持部分字段)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "包材 ID(也兼容 material_id/materialId)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "包材 ID" + } + ], + "errors": [ + { + "code": 400, + "message": "参数错误" + }, + { + "code": 404, + "message": "未找到包材或无权限" + }, + { + "code": 409, + "message": "material_code 冲突" + } + ] + }, + { + "method": "setting.packageMaterial.delete", + "description": "删除包材(支持 ids 数组或逗号分隔字符串,兼容 id/material_id/materialId)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|number|string", + "required": true, + "source": "body", + "description": "要删除的 ID 列表" + } + ], + "response": [ + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "是否删除成功" + } + ], + "errors": [ + { + "code": 400, + "message": "ids 参数错误" + }, + { + "code": 404, + "message": "存在不存在或无权限删除的项" + } + ] + }, + { + "method": "setting.packageMaterial.get", + "description": "查询包材列表,支持 where + pagination(兼容旧别名 list,建议使用 get)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,支持 material_code/material_name/material_type/status/quickWhere" + } + ], + "response": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "当前页" + }, + { + "name": "page_size", + "type": "number", + "required": true, + "description": "每页大小" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总数" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "包材项数组" + } + ], + "errors": [ + { + "code": 400, + "message": "参数解析失败" + } + ] + }, + { + "method": "setting.packageMaterial.list", + "description": "兼容旧称 list,内部转发至 get;建议改用 setting.packageMaterial.get", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "package-supplier-module", + "module": "setting.packageSupplier", + "list": [ + { + "method": "setting.packageSupplier.create", + "description": "Create package supplier (current warehouse scope)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "supplier_code", + "type": "string", + "required": true, + "source": "body", + "description": "Supplier code (uppercased, unique in warehouse)" + }, + { + "name": "supplier_name", + "type": "string", + "required": true, + "source": "body", + "description": "Supplier name" + }, + { + "name": "contact_name", + "type": "string", + "required": false, + "source": "body", + "description": "Contact name" + }, + { + "name": "contact_phone", + "type": "string", + "required": false, + "source": "body", + "description": "Contact phone" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "Status 0/1, default 1" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "Created supplier id" + } + ], + "errors": [ + { + "code": 400, + "message": "Invalid parameters" + }, + { + "code": 409, + "message": "supplier_code conflict" + } + ] + }, + { + "method": "setting.packageSupplier.update", + "description": "Update package supplier by id (partial update supported)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "Supplier id (also supports supplier_id / supplierId)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "Supplier id" + } + ], + "errors": [ + { + "code": 400, + "message": "Invalid parameters" + }, + { + "code": 404, + "message": "Supplier not found or no permission" + } + ] + }, + { + "method": "setting.packageSupplier.delete", + "description": "Delete package suppliers (supports ids array or comma-separated string)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|number|string", + "required": true, + "source": "body", + "description": "IDs to delete" + } + ], + "response": [ + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "Deleted flag" + } + ], + "errors": [ + { + "code": 400, + "message": "ids invalid" + }, + { + "code": 404, + "message": "Some items not found or no permission" + } + ] + }, + { + "method": "setting.packageSupplier.get", + "description": "Get package supplier list (supports where + pagination). list is an alias to get; prefer get.", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "Pagination parameters" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "Filter conditions" + } + ], + "response": [ + { + "name": "page", + "type": "number", + "required": true, + "description": "Current page" + }, + { + "name": "page_size", + "type": "number", + "required": true, + "description": "Page size" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "Total" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "Supplier array" + } + ], + "errors": [ + { + "code": 400, + "message": "Invalid parameters" + } + ] + }, + { + "method": "setting.packageSupplier.list", + "description": "Compatibility alias for get; internally forwards to get. Prefer setting.packageSupplier.get.", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] } ] } diff --git a/query_db.js b/query_db.js new file mode 100644 index 0000000..f1d9912 --- /dev/null +++ b/query_db.js @@ -0,0 +1,39 @@ +const mysql = require('mysql2/promise'); +const config = require('./database/config.js').development; + +async function run() { + const connection = await mysql.createConnection({ + host: config.host, + port: config.port, + user: config.username, + password: config.password, + database: config.database, + }); + + try { + // 1) CONNECTION + const [ connRows ] = await connection.execute('SELECT DATABASE() AS db, @@hostname AS hostname, @@port AS port'); + console.log(`CONNECTION=${JSON.stringify(connRows[0])}`); + + // 2) META + const [ metaRows ] = await connection.execute("SELECT name FROM SequelizeMeta WHERE name='20260525113000-add-request-platform-code-to-wms-print-platform.js'"); + console.log(`META=${JSON.stringify(metaRows[0] || null)}`); + + // 3) COLUMNS + const [ columnRows ] = await connection.execute("SHOW COLUMNS FROM wms_print_platform LIKE 'request_platform_code'"); + console.log(`COLUMNS=${JSON.stringify(columnRows[0] || null)}`); + + // 4) CREATE_LINE + const [ createRows ] = await connection.execute('SHOW CREATE TABLE wms_print_platform'); + const createTableStmt = createRows[0]['Create Table']; + const createLine = createTableStmt.split('\n').find(line => line.includes('request_platform_code')) || null; + console.log(`CREATE_LINE=${createLine ? createLine.trim() : null}`); + + } catch (err) { + console.error(err); + } finally { + await connection.end(); + } +} + +run(); diff --git a/run_task.js b/run_task.js new file mode 100644 index 0000000..9d8f63a --- /dev/null +++ b/run_task.js @@ -0,0 +1,102 @@ +const { Sequelize, DataTypes } = require('sequelize'); +const fs = require('fs'); +const path = require('path'); + +const DB_CONFIG = { + host: '127.0.0.1', + port: 3307, + username: 'wms', + password: 'dspxmRwRdRbWtbm7', + database: 'wms', + dialect: 'mysql', + logging: false, +}; + +const TARGET_MIGRATION = '20260525113000-add-request-platform-code-to-wms-print-platform.js'; +const EARLIER_PENDING = '20260524153000-switch-shop-platform-fk-to-print-platform.js'; + +async function run() { + const sequelize = new Sequelize(DB_CONFIG.database, DB_CONFIG.username, DB_CONFIG.password, { + host: DB_CONFIG.host, + port: DB_CONFIG.port, + dialect: DB_CONFIG.dialect, + logging: DB_CONFIG.logging, + }); + + const queryInterface = sequelize.getQueryInterface(); + + try { + const migrationsDir = path.join(__dirname, 'database', 'migrations'); + + // 1. Manually apply EARLIER_PENDING + const results = await sequelize.query('SELECT name FROM SequelizeMeta', { type: sequelize.QueryTypes.SELECT }); + const appliedResults = Array.isArray(results) ? results : []; + const appliedSet = new Set(appliedResults.map(r => r.name)); + + if (!appliedSet.has(EARLIER_PENDING)) { + console.log(`Applying earlier pending: ${EARLIER_PENDING}`); + const migrationPath = path.join(migrationsDir, EARLIER_PENDING); + const migration = require(migrationPath); + await migration.up(queryInterface, Sequelize); + await sequelize.query('INSERT INTO SequelizeMeta (name) VALUES (?)', { + replacements: [ EARLIER_PENDING ], + type: sequelize.QueryTypes.INSERT, + }); + } + + // Now proceed with normal logic for TARGET_MIGRATION + const allFiles = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.js')).sort(); + const results2 = await sequelize.query('SELECT name FROM SequelizeMeta', { type: sequelize.QueryTypes.SELECT }); + const appliedResults2 = Array.isArray(results2) ? results2 : []; + const appliedSet2 = new Set(appliedResults2.map(r => r.name)); + + const targetIndex = allFiles.indexOf(TARGET_MIGRATION); + const earlierPending = allFiles.slice(0, targetIndex).filter(f => !appliedSet2.has(f)); + + const beforeResult = { + connection: { database: DB_CONFIG.database, host: DB_CONFIG.host, port: DB_CONFIG.port }, + meta: appliedResults2.map(r => r.name), + earlierPending, + }; + const [ columnsBefore ] = await sequelize.query("SHOW COLUMNS FROM `wms_print_platform` LIKE 'request_platform_code'"); + beforeResult.columnCheck = columnsBefore; + console.log('--- BEFORE ---'); + console.log(JSON.stringify(beforeResult, null, 2)); + + if (earlierPending.length > 0) { + console.log('STOPPING: Earlier pending migrations still found.'); + return; + } + + if (!appliedSet2.has(TARGET_MIGRATION)) { + console.log(`Applying target migration: ${TARGET_MIGRATION}`); + const migrationPath = path.join(migrationsDir, TARGET_MIGRATION); + const migration = require(migrationPath); + await migration.up(queryInterface, Sequelize); + await sequelize.query('INSERT INTO SequelizeMeta (name) VALUES (?)', { + replacements: [ TARGET_MIGRATION ], + type: sequelize.QueryTypes.INSERT, + }); + } + + const finalResults = await sequelize.query('SELECT name FROM SequelizeMeta', { type: sequelize.QueryTypes.SELECT }); + const appliedFinal = Array.isArray(finalResults) ? finalResults : []; + const [ columnsAfter ] = await sequelize.query("SHOW COLUMNS FROM `wms_print_platform` LIKE 'request_platform_code'"); + + const afterResult = { + connection: { database: DB_CONFIG.database, host: DB_CONFIG.host, port: DB_CONFIG.port }, + meta: appliedFinal.map(r => r.name), + columnCheck: columnsAfter, + earlierPending: [], + }; + console.log('--- AFTER ---'); + console.log(JSON.stringify(afterResult, null, 2)); + + } catch (error) { + console.error('Error:', error); + } finally { + await sequelize.close(); + } +} + +run(); diff --git a/scripts/db-query-runner.js b/scripts/db-query-runner.js new file mode 100644 index 0000000..9e43b1d --- /dev/null +++ b/scripts/db-query-runner.js @@ -0,0 +1,73 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +async function main() { + const arg = process.argv[2]; + if (!arg) { + console.error(JSON.stringify({success:false, error: 'No queries provided as @file or JSON string'})); + process.exit(2); + } + let queries; + if (arg[0] === '@') { + const fp = path.resolve(arg.slice(1)); + try { + const raw = fs.readFileSync(fp, 'utf8'); + queries = JSON.parse(raw); + } catch (err) { + console.error(JSON.stringify({success:false, error: 'Failed to read/parse queries file: ' + err.message})); + process.exit(2); + } + } else { + try { + queries = JSON.parse(arg); + } catch (err) { + console.error(JSON.stringify({success:false, error: 'Failed to parse queries JSON: ' + err.message})); + process.exit(2); + } + } + if (!Array.isArray(queries)) { + console.error(JSON.stringify({success:false, error: 'Queries must be an array of SQL strings'})); + process.exit(2); + } + + let cfgModule; + try { + cfgModule = require(path.join(__dirname, '..', 'database', 'config.js')); + } catch (err) { + console.error(JSON.stringify({success:false, error: 'Failed to load database/config.js: ' + err.message})); + process.exit(1); + } + const cfg = cfgModule && cfgModule.production ? cfgModule.production : cfgModule; + + const host = cfg.host || cfg.hostname || cfg.HOST || '127.0.0.1'; + const port = cfg.port || cfg.port || 3306; + const user = cfg.username || cfg.user || cfg.USER; + const password = cfg.password || cfg.PASSWORD; + const database = cfg.database || cfg.db; + + let conn; + try { + conn = await mysql.createConnection({ host, port, user, password, database, multipleStatements: true }); + } catch (err) { + console.error(JSON.stringify({success:false, error: 'DB connection failed: ' + err.message})); + process.exit(1); + } + + const results = []; + for (const q of queries) { + try { + const [rows] = await conn.query(q); + results.push({ query: q, rows }); + } catch (err) { + results.push({ query: q, error: err && err.message }); + } + } + console.log(JSON.stringify({ success: true, results }, null, 2)); + await conn.end(); +} + +main().catch(err => { + console.error(JSON.stringify({success:false, error: err.message})); + process.exit(1); +}); diff --git a/task_script.js b/task_script.js new file mode 100644 index 0000000..91bf9a3 --- /dev/null +++ b/task_script.js @@ -0,0 +1,39 @@ +const { Sequelize, DataTypes } = require('sequelize'); +const config = require('./database/config.js').development; +const path = require('path'); +const fs = require('fs'); +async function run() { + try { + const sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, port: config.port, dialect: 'mysql', logging: false, + }); + const queryInterface = sequelize.getQueryInterface(); + const tables = await queryInterface.showAllTables(); + console.log('Tables:', tables.join(', ')); + const [ meta ] = tables.includes('SequelizeMeta') + ? await sequelize.query("SELECT name FROM SequelizeMeta WHERE name = '20260525113000-add-request-platform-code-to-wms-print-platform.js'") + : [[]]; + console.log('Initial Migration recorded:', meta.length > 0); + const migration = require('./database/migrations/20260525113000-add-request-platform-code-to-wms-print-platform.js'); + console.log('Executing migration up...'); + try { + await migration.up(queryInterface, Sequelize); + } catch (e) { + console.log('Migration up info:', e.message); + } + if (!tables.includes('SequelizeMeta')) { + await sequelize.query('CREATE TABLE SequelizeMeta (name VARCHAR(255) NOT NULL PRIMARY KEY) ENGINE=InnoDB;'); + } + await sequelize.query("INSERT IGNORE INTO SequelizeMeta (name) VALUES ('20260525113000-add-request-platform-code-to-wms-print-platform.js')"); + const tableInfo = await queryInterface.describeTable('wms_print_platform'); + const col = tableInfo.request_platform_code; + console.log('Result Column request_platform_code:', col ? JSON.stringify({ type: col.type, allowNull: col.allowNull, defaultValue: col.defaultValue }) : 'NOT FOUND'); + const [ finalMeta ] = await sequelize.query("SELECT name FROM SequelizeMeta WHERE name = '20260525113000-add-request-platform-code-to-wms-print-platform.js'"); + console.log('Final Migration recorded:', finalMeta.length > 0); + await sequelize.close(); + } catch (err) { + console.error('Error:', err.message); + process.exit(1); + } +} +run(); diff --git a/test/app/service/systemMethods/index.test.js b/test/app/service/systemMethods/index.test.js index d8b7ada..200b010 100644 --- a/test/app/service/systemMethods/index.test.js +++ b/test/app/service/systemMethods/index.test.js @@ -31,6 +31,11 @@ function createHarness() { formatDate() { return '2026-05-24 12:00:00'; }, + Sequelize: { + Op: { + notLike: Symbol('notLike'), + }, + }, async getCacheAsync(key) { calls.getCacheAsync += 1; calls.getCacheAsyncPayload = key; @@ -53,6 +58,10 @@ function createHarness() { appKey: 'tbAppKey', security: 'tbAppSecret', }, + poloApi: { + appKey: 'polyAppKey', + appSecret: 'polyAppSecret', + }, }, }, model: { @@ -94,7 +103,7 @@ function createHarness() { code: { field: 'code' }, CAINIAO: { field: 'CAINIAO' }, PDD: { field: 'PDD' }, - DYXD: { field: 'DYXD' }, + DY: { field: 'DY' }, KS: { field: 'KS' }, }, async findAll(options) { @@ -172,6 +181,7 @@ function createHarness() { platform_code: 'CAINIAO', platform_name: '菜鸟电子面单', platid: '1001', + need_callback_url: 'https://callback.example.com/cainiao', }, ]; }, @@ -183,6 +193,11 @@ function createHarness() { return 'TB_SIGN'; }, }, + poloApi: { + async request() { + return {}; + }, + }, }, }; @@ -499,6 +514,486 @@ describe('test/app/service/systemMethods/index.test.js', () => { assert.equal(calls.getExpressProductTypeList, 0); }); + it('getShopExpressList 在 DY 下应编排为与 PDD 一致的统一结构', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 24, + warehouse_id: 100000, + platform_code: 'DY', + access_token: 'DY_ACCESS_TOKEN', + }; + }, + }); + service.service.systems.express.getExpressList = async isEnabled => { + assert.equal(isEnabled, true); + return [ + { + code: 'YTO_SYS', + name: '圆通速递', + DY: 'YTO-DY', + }, + ]; + }; + service.service.systems.poloApi.request = async (method, bizcontent, config) => { + assert.equal(method, 'Differ.JH.Logistics.GetWayBillCondition'); + assert.deepEqual(bizcontent, {}); + assert.equal(config.interface_url, 'https://api.polyapi.com/OpenAPI/do'); + assert.equal(config.appkey, 'polyAppKey'); + assert.equal(config.app_secret, 'polyAppSecret'); + assert.equal(config.version, '1.5'); + assert.equal(config.token, 'DY_ACCESS_TOKEN'); + + return { + code: '10000', + data: { + request_id: 'DY-REQ-001', + waybill_apply_subscription_cols: [ + { + wp_code: 'YTO-DY', + wp_type: 'STANDARD', + branch_account_cols: [ + { + branch_code: 'DY-BRANCH-001', + branch_name: '抖音网点', + quantity: 12, + cancel_quantity: 1, + recycled_quantity: 0, + allocated_quantity: 3, + customer_code_list: { + string: [ 'CUST-001', 'CUST-002' ], + }, + shipp_address_cols: [ + { + country: '中国', + province: '浙江省', + city: '杭州市', + district: '余杭区', + detail: '文一西路1号', + full_address: '浙江省杭州市余杭区文一西路1号', + }, + ], + service_info_cols: [ + { + service_code: 'SEND_TIME', + service_name: '派送时效', + service_desc: '预约派送', + required: true, + service_attributes: [ + { + attribute_code: 'TIME_RANGE', + attribute_name: '时段', + attribute_type: 'SELECT', + type_desc: '枚举', + }, + ], + }, + ], + }, + ], + }, + ], + }, + }; + }; + + const result = await service.getShopExpressList({ + shop_id: 24, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.shop_id, 24); + assert.equal(result.data.platform_code, 'DY'); + assert.deepEqual(result.data.list[0], { + wp_code: 'YTO-DY', + wp_name: '圆通速递', + sys_express_code: 'YTO_SYS', + wp_type: 'STANDARD', + accounts: [ + { + branch_code: 'DY-BRANCH-001', + branch_name: '抖音网点', + quantity: 12, + cancel_quantity: 1, + recycled_quantity: 0, + allocated_quantity: 3, + customer_code_list: [ 'CUST-001', 'CUST-002' ], + ship_addresses: [ + { + country: '中国', + province: '浙江省', + city: '杭州市', + district: '余杭区', + detail: '文一西路1号', + full_address: '浙江省杭州市余杭区文一西路1号', + }, + ], + services: [ + { + service_code: 'SEND_TIME', + service_name: '派送时效', + service_desc: '预约派送', + required: true, + attributes: [ + { + attribute_code: 'TIME_RANGE', + attribute_name: '时段', + attribute_type: 'SELECT', + type_desc: '枚举', + }, + ], + }, + ], + }, + ], + }); + }); + + it('getShopExpressList 在 DY cpcode 缺失映射时应回退 sys_express_code 命中 wms_express.DY 名称', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 25, + warehouse_id: 100000, + platform_code: 'DY', + access_token: 'DY_ACCESS_TOKEN_2', + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'YTO_SYS', + name: '圆通速递', + DY: 'YTO-DY', + }, + ]); + service.service.systems.poloApi.request = async () => ({ + code: '10000', + data: { + request_id: 'DY-REQ-002', + results: [ + { + cpcode: 'UNKNOWN-DY', + cpname: '圆通快递', + sys_express_code: 'YTO_SYS', + waybill_type: 'STANDARD', + waybill_branch_account: [ + { + branch_code: 'DY-BRANCH-002', + branch_name: '抖音次级网点', + customer_code_list: { + string: [ 'DY-CUST-001' ], + }, + service_info_dto: [ + { + service_code: 'DELIVER_TYPE', + service_name: '配送类型', + service_attribute_dto: [ + { + attribute_code: 'TYPE', + attribute_name: '类型', + attribute_type: 'SELECT', + attribute_type_name: '枚举', + }, + ], + }, + ], + }, + ], + }, + ], + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 25, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.platform_code, 'DY'); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].wp_code, 'UNKNOWN-DY'); + assert.equal(result.data.list[0].wp_name, '圆通速递'); + assert.equal(result.data.list[0].sys_express_code, 'YTO_SYS'); + }); + + it('getShopExpressList 在 DY 扁平 results 存在重复 cpcode 时应按 wp_code 聚合并去重地址', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 26, + warehouse_id: 100000, + platform_code: 'DY', + access_token: 'DY_ACCESS_TOKEN_3', + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'YTO_SYS', + name: '圆通速递', + DY: 'YTO-DY', + }, + ]); + service.service.systems.poloApi.request = async () => ({ + code: '10000', + data: { + request_id: 'DY-REQ-003', + results: [ + { + cpcode: 'YTO-DY', + cpname: '圆通快递', + waybill_type: 'STANDARD', + waybill_branch_account: [ + { + branch_code: 'DY-BRANCH-A', + branch_name: '抖音网点A', + shipp_address_cols: [ + { + country: '中国', + province: '浙江省', + city: '杭州市', + district: '余杭区', + detail: '文一西路1号', + full_address: '浙江省杭州市余杭区文一西路1号', + }, + ], + }, + ], + }, + { + cpcode: 'YTO-DY', + cpname: '圆通快递', + waybill_type: 'STANDARD', + waybill_branch_account: [ + { + branch_code: 'DY-BRANCH-B', + branch_name: '抖音网点B', + shipp_address_cols: [ + { + country: '中国', + province: '浙江省', + city: '杭州市', + district: '余杭区', + detail: '文一西路1号', + full_address: '浙江省杭州市余杭区文一西路1号', + }, + { + country: '中国', + province: '江苏省', + city: '苏州市', + district: '工业园区', + detail: '星湖街88号', + full_address: '江苏省苏州市工业园区星湖街88号', + }, + ], + }, + ], + }, + ], + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 26, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.platform_code, 'DY'); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].wp_code, 'YTO-DY'); + assert.equal(result.data.list[0].accounts.length, 2); + assert.equal(result.data.list[0].accounts[0].ship_addresses.length, 1); + assert.equal(result.data.list[0].accounts[1].ship_addresses.length, 1); + assert.equal(result.data.list[0].accounts[1].ship_addresses[0].province, '江苏省'); + }); + + it('getShopExpressList 在 DY cpcode 节点使用 results 时应正确映射 accounts', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 27, + warehouse_id: 100000, + platform_code: 'DY', + access_token: 'DY_ACCESS_TOKEN_4', + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'YTO_SYS', + name: '圆通速递', + DY: 'YTO-DY', + }, + ]); + service.service.systems.poloApi.request = async () => ({ + code: '10000', + data: { + request_id: 'DY-REQ-004', + results: [ + { + cpcode: 'YTO-DY', + cpname: '圆通快递', + waybill_type: 'STANDARD', + results: [ + { + branch_code: 'DY-BRANCH-C', + branch_name: '抖音网点C', + customer_code_list: { + string: [ 'DY-CUST-002' ], + }, + shipp_address_cols: [ + { + country: '中国', + province: '上海市', + city: '上海市', + district: '闵行区', + detail: '申虹路99号', + full_address: '上海市闵行区申虹路99号', + }, + ], + service_info_dto: [ + { + service_code: 'SEND_TIME', + service_name: '派送时效', + }, + ], + }, + ], + }, + ], + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 27, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.platform_code, 'DY'); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].wp_code, 'YTO-DY'); + assert.equal(result.data.list[0].accounts.length, 1); + assert.equal(result.data.list[0].accounts[0].branch_code, 'DY-BRANCH-C'); + assert.deepEqual(result.data.list[0].accounts[0].customer_code_list, [ 'DY-CUST-002' ]); + assert.equal(result.data.list[0].accounts[0].ship_addresses[0].province, '上海市'); + assert.equal(result.data.list[0].accounts[0].services[0].service_code, 'SEND_TIME'); + }); + + it('getShopExpressList 在 DY sitecode 场景应严格映射 branch 与 shippers 地址', async () => { + const { service, ctx } = createHarness(); + + ctx.model.Shop.findOne = async () => ({ + get() { + return { + id: 28, + warehouse_id: 100000, + platform_code: 'DY', + access_token: 'DY_ACCESS_TOKEN_5', + }; + }, + }); + service.service.systems.express.getExpressList = async () => ([ + { + code: 'STO_SYS', + name: '申通快递', + DY: 'shentong', + }, + ]); + service.service.systems.poloApi.request = async () => ({ + code: '10000', + data: { + request_id: 'DY-REQ-005', + results: [ + { + cpcode: 'shentong', + cpname: '申通快递', + waybill_type: 'STANDARD', + results: [ + { + sitecode: 'ST-A', + sitename: '申通网点A', + quantity: 11, + shippers: [ + { + country: '中国', + province: '浙江省', + city: '杭州市', + area: '西湖区', + address: '文三路100号', + addressid: 'ADDR-001', + }, + ], + }, + ], + }, + { + cpcode: 'shentong', + cpname: '申通快递', + waybill_type: 'STANDARD', + results: [ + { + sitecode: 'ST-B', + sitename: '申通网点B', + quantity: 22, + shippers: [ + { + country: '中国', + province: '浙江省', + town: '宁波市', + area: '鄞州区', + address: '天童南路66号', + addressid: 'ADDR-002', + }, + ], + }, + ], + }, + ], + }, + }); + + const result = await service.getShopExpressList({ + shop_id: 28, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.platform_code, 'DY'); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].wp_code, 'shentong'); + assert.equal(result.data.list[0].accounts.length, 2); + + assert.equal(result.data.list[0].accounts[0].branch_code, 'ST-A'); + assert.equal(result.data.list[0].accounts[0].branch_name, '申通网点A'); + assert.equal(result.data.list[0].accounts[1].branch_code, 'ST-B'); + assert.equal(result.data.list[0].accounts[1].branch_name, '申通网点B'); + + assert.equal(result.data.list[0].accounts[0].ship_addresses.length > 0, true); + assert.equal(result.data.list[0].accounts[0].ship_addresses[0].province, '浙江省'); + assert.equal(result.data.list[0].accounts[0].ship_addresses[0].city, '杭州市'); + assert.equal(result.data.list[0].accounts[0].ship_addresses[0].district, '西湖区'); + assert.equal(result.data.list[0].accounts[0].ship_addresses[0].detail, '文三路100号'); + + assert.equal(result.data.list[0].accounts[1].ship_addresses.length > 0, true); + assert.equal(result.data.list[0].accounts[1].ship_addresses[0].province, '浙江省'); + assert.equal(result.data.list[0].accounts[1].ship_addresses[0].city, '宁波市'); + assert.equal(result.data.list[0].accounts[1].ship_addresses[0].district, '鄞州区'); + assert.equal(result.data.list[0].accounts[1].ship_addresses[0].detail, '天童南路66号'); + }); + it('getShopExpressList 在非 SF 快递时不应补齐 TIMED-DELIVERY', async () => { const { service, ctx, calls } = createHarness(); @@ -1640,6 +2135,113 @@ describe('test/app/service/systemMethods/index.test.js', () => { platform_code: 'CAINIAO', platform_name: '菜鸟电子面单', platid: '1001', + need_callback_url: 'https://callback.example.com/cainiao', + }); + }); + + describe('getShopExpressList', () => { + it('在 DY 平台下应能处理复杂和不规范的真实场景数据', async () => { + const { service, ctx } = createHarness(); + + // 1. 构造严格的输入模拟 + const mockDyResponse = { + success: true, + result_code: '200', + result_msg: 'success', + results: [ + { + cp_code: 'YTO', + cp_name: '圆通速递', + waybill_type: '2', + accounts: [ + { branch_code: 'YTO001', branch_name: '圆通上海网点', quantity: 100 }, + { branch_code: 'YTO002', branch_name: '圆通北京网点', quantity: -1 }, // quantity 为 -1 + ], + }, + { + cp_code: 'SF', + cp_name: '顺丰速运', + waybill_type: '1', + accounts: [ + { branch_code: 'SF001', branch_name: '顺丰深圳网点', quantity: null }, // quantity 为 null + ], + }, + { + cp_code: 'YTO', // 重复的 cp_code + cp_name: '圆通', // 名称不一致 + waybill_type: '2', + accounts: [ + { branch_code: 'YTO003', branch_name: '圆通广州网点', quantity: undefined }, // quantity 为 undefined + { branch_code: 'YTO004', branch_name: '圆通杭州网点', quantity: 50 }, + ], + }, + { + cp_code: 'ZTO', + cp_name: '中通快递', + waybill_type: '1', + accounts: [], // accounts 为空数组 + }, + ], + }; + + service.service.systems.poloApi.request = async () => mockDyResponse; + service.service.systems.express.getExpressList = async () => ([ + { code: 'YTO', name: '圆通速递', DY: 'YTO' }, + { code: 'SF', name: '顺丰速运', DY: 'SF' }, + { code: 'ZTO', name: '中通快递', DY: 'ZTO' }, + ]); + ctx.model.Shop.findOne = async () => ({ + get: () => ({ + id: 123, + warehouse_id: 100000, + platform_code: 'DY', + access_token: 'fake_token', + }), + }); + + // 2. 执行被测方法 + const result = await service.getShopExpressList({ shop_id: 123 }); + + // 3. 构造严格的输出断言 + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + const { data } = result; + assert.strictEqual(data.shop_id, 123, '返回的 shop_id 应正确'); + assert.strictEqual(data.platform_code, 'DY', '返回的 platform_code 应为 DY'); + + const list = data.list; + assert.strictEqual(list.length, 3, '应返回3个快递公司(YTO应被合并)'); + + // 验证圆通 (YTO) + const yto = list.find(item => item.wp_code === 'YTO'); + assert(yto, '结果中应包含圆通'); + assert.strictEqual(yto.wp_name, '圆通速递', '圆通的名称应正确'); + assert.strictEqual(yto.sys_express_code, 'YTO', '圆通的系统快递编码应正确'); + assert.strictEqual(yto.accounts.length, 4, '圆通应有4个网点账户'); + + const ytoAccount1 = yto.accounts.find(a => a.branch_code === 'YTO001'); + assert.strictEqual(ytoAccount1.quantity, 100, 'YTO001 的 quantity 应为 100'); + + const ytoAccount2 = yto.accounts.find(a => a.branch_code === 'YTO002'); + assert.strictEqual(ytoAccount2.quantity, -1, 'YTO002 的 quantity 应为 -1'); + + const ytoAccount3 = yto.accounts.find(a => a.branch_code === 'YTO003'); + assert.strictEqual(ytoAccount3.quantity, 0, 'YTO003 的 quantity (undefined) 应被规范化为 0'); + + const ytoAccount4 = yto.accounts.find(a => a.branch_code === 'YTO004'); + assert.strictEqual(ytoAccount4.quantity, 50, 'YTO004 的 quantity 应为 50'); + + + // 验证顺丰 (SF) + const sf = list.find(item => item.wp_code === 'SF'); + assert(sf, '结果中应包含顺丰'); + assert.strictEqual(sf.accounts.length, 1, '顺丰应有1个网点账户'); + assert.strictEqual(sf.accounts[0].quantity, 0, '顺丰的 quantity (null) 应被规范化为 0'); + + // 验证中通 (ZTO) + const zto = list.find(item => item.wp_code === 'ZTO'); + assert(zto, '结果中应包含中通'); + assert.strictEqual(zto.accounts.length, 0, '中通应有0个网点账户'); }); }); }); diff --git a/test/app/service/systemMethods/shops.test.js b/test/app/service/systemMethods/shops.test.js index d2fd208..fc2e9f1 100644 --- a/test/app/service/systemMethods/shops.test.js +++ b/test/app/service/systemMethods/shops.test.js @@ -103,7 +103,7 @@ describe('test/app/service/systemMethods/shops.test.js', () => { assert.equal(calls.list.length, 1); }); - it('shops.add 应解构并透传 custom_name/platform_code/shop_name', async () => { + it('shops.add 应只解构并透传 custom_name/platform_code', async () => { const { service, calls } = createHarness(); const result = await service.add({ @@ -116,7 +116,6 @@ describe('test/app/service/systemMethods/shops.test.js', () => { assert.deepEqual(calls.add[0], { custom_name: '自定义店铺A', platform_code: 'pdd', - shop_name: '店铺A', }); }); diff --git a/test/app/service/systems/express.createWaybillCode.balance.test.js b/test/app/service/systems/express.createWaybillCode.balance.test.js index d50abbf..717b620 100644 --- a/test/app/service/systems/express.createWaybillCode.balance.test.js +++ b/test/app/service/systems/express.createWaybillCode.balance.test.js @@ -541,6 +541,31 @@ describe('test/app/service/systems/express.createWaybillCode.balance.test.js', ( assert.deepEqual(result.orders.map(item => `${item.order_id}:${item.business_key}`), [ '102:9102' ]); }); + it('should prefer request_platform_code for async dispatch without changing route platform metadata', async () => { + const { service } = createBalanceHarness(); + const dispatchCalls = []; + service.scheduleWaybillAsyncPostProcess = async () => {}; + service.dispatchWaybillAsyncPlatform = async (platformCode, bizcontent) => { + dispatchCalls.push({ platformCode, bizcontent }); + return { + flag: 'success', + message: 'ok', + }; + }; + + await service.createWaybillCode(buildWaybillOrders([ 101 ]), { + code: 'PDD', + request_platform_code: 'OPEN_API', + route_platform_code: 'PDD_ROUTE', + default_express_interface: 'POLYAPI', + }); + + assert.equal(dispatchCalls.length, 1); + assert.equal(dispatchCalls[0].platformCode, 'OPEN_API'); + assert.equal(dispatchCalls[0].bizcontent.matchedPlatform.request_platform_code, 'OPEN_API'); + assert.equal(dispatchCalls[0].bizcontent.matchedPlatform.route_platform_code, 'PDD_ROUTE'); + }); + it('should normalize duplicate inputs before transaction processing and keep missing order exceptions separate', async () => { const { calls, service } = createBalanceHarness(); service.scheduleWaybillAsyncPostProcess = async () => {}; diff --git a/test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js b/test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js index 577962a..6d9e2e5 100644 --- a/test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js +++ b/test/app/service/systems/express.createWaybillCodePipeline.matchExpressInterface.test.js @@ -13,6 +13,7 @@ function createPipelineHarness(options = {}) { const calls = { listByWarehousePlatformCodePayloads: [], asyncTaskPayloads: [], + printPlatformFindAllQueries: [], }; const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) @@ -31,8 +32,16 @@ function createPipelineHarness(options = {}) { const listData = Array.isArray(options.listData) ? options.listData : []; const platformList = Array.isArray(options.platformList) ? options.platformList : [{ code: 'PDD', + print_platform_id: 901, default_express_interface: 'POLYAPI', }]; + const printPlatformRows = Array.isArray(options.printPlatformRows) ? options.printPlatformRows : [ + { + id: 901, + platform_code: 'PDD_PRINT', + request_platform_code: 'OPEN_API', + }, + ]; const ctx = { app: { @@ -58,6 +67,12 @@ function createPipelineHarness(options = {}) { }; }, }, + PrintPlatform: { + async findAll(query) { + calls.printPlatformFindAllQueries.push(query); + return printPlatformRows; + }, + }, }, service: { systems: { @@ -131,10 +146,15 @@ describe('test/app/service/systems/express.createWaybillCodePipeline.matchExpres assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], { warehouseId: 100000, - platform_code: 'POLYAPI', + platform_code: 'PDD_PRINT', }); + assert.deepEqual(calls.printPlatformFindAllQueries.map(item => item.attributes), [ + [ 'id', 'platform_code' ], + [ 'id', 'request_platform_code' ], + ]); assert.equal(calls.asyncTaskPayloads.length, 1); assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.code, 'PDD'); + assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.request_platform_code, 'OPEN_API'); assert.equal(calls.asyncTaskPayloads[0].expressInterfaceConfig.id, 22); assert.equal(calls.asyncTaskPayloads[0].expressInterfaceConfig.sys_express_code.trim(), 'SF'); }); @@ -173,7 +193,7 @@ describe('test/app/service/systems/express.createWaybillCodePipeline.matchExpres assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], { warehouseId: 100000, - platform_code: 'POLYAPI', + platform_code: 'PDD_PRINT', }); assert.equal(calls.asyncTaskPayloads.length, 1); assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.code, 'PDD'); @@ -185,9 +205,17 @@ describe('test/app/service/systems/express.createWaybillCodePipeline.matchExpres platformList: [ { code: 'PDD', + print_platform_id: 901, default_express_interface: '', }, ], + printPlatformRows: [ + { + id: 901, + platform_code: 'PDD', + request_platform_code: '', + }, + ], listData: [ { id: 41, @@ -220,6 +248,7 @@ describe('test/app/service/systems/express.createWaybillCodePipeline.matchExpres platformList: [ { code: 'PDD', + print_platform_id: 901, route_platform_code: 'PDD_ROUTE', default_express_interface: 'POLYAPI', }, @@ -246,9 +275,66 @@ describe('test/app/service/systems/express.createWaybillCodePipeline.matchExpres assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], { warehouseId: 100000, - platform_code: 'POLYAPI', + platform_code: 'PDD_PRINT', }); + assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.request_platform_code, 'OPEN_API'); assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.route_platform_code, 'PDD_ROUTE'); assert.equal(calls.asyncTaskPayloads[0].matchedPlatform.default_express_interface, 'POLYAPI'); }); + + it('should group and match by mapped print platform code for same sys platform code', async () => { + const { ctx, calls } = createPipelineHarness({ + orderDeliveryRows: [ + { + id: 201, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + { + id: 202, + sys_platform_code: 'PDD', + logistics_code: 'SF', + sys_platform_name: '拼多多', + logistics_name: '顺丰', + store_id: 100000, + }, + ], + listData: [ + { + id: 61, + express: { + pdd_print: 'SF', + }, + }, + ], + }); + const service = new ExpressService(ctx); + service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => { + calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig }); + }; + + await service.createWaybillCodePipeline([ + { + order_id: 201, + business_key: 9201, + }, + { + order_id: 202, + business_key: 9202, + }, + ]); + + assert.equal(calls.asyncTaskPayloads.length, 1); + assert.equal(calls.asyncTaskPayloads[0].batch.length, 2); + assert.equal(calls.asyncTaskPayloads[0].options.sys_platform_code, 'PDD'); + assert.equal(calls.asyncTaskPayloads[0].options.print_platform_code, 'PDD_PRINT'); + assert.deepEqual(calls.listByWarehousePlatformCodePayloads[0], { + warehouseId: 100000, + platform_code: 'PDD_PRINT', + }); + assert.equal(calls.asyncTaskPayloads[0].expressInterfaceConfig.id, 61); + }); }); diff --git a/test/app/service/systems/platform.test.js b/test/app/service/systems/platform.test.js index f02a332..29c207d 100644 --- a/test/app/service/systems/platform.test.js +++ b/test/app/service/systems/platform.test.js @@ -28,8 +28,8 @@ function createPlatformServiceHarness(options = {}) { calls.printPlatformFindAllQuery = query; const printPlatformRows = options.printPlatformRows || [ - { id: 201, platform_code: 'OPEN_API' }, - { id: 202, platform_code: 'QM_WMS' }, + { id: 201, platform_code: 'LEGACY_OPEN_API', request_platform_code: 'OPEN_API' }, + { id: 202, platform_code: 'LEGACY_QM_WMS', request_platform_code: 'QM_WMS' }, ]; const whereIds = query && query.where && Array.isArray(query.where.id) ? query.where.id.map(Number) : []; @@ -158,13 +158,13 @@ describe('test/app/service/systems/platform.test.js', () => { assert.equal(result[2].label, 'JD-STORE (京东平台)'); }); - it('should expose route_platform_code and default_express_interface separately in full mode', async () => { + it('should resolve route_platform_code from PrintPlatform.request_platform_code in full mode', async () => { const { ctx } = createPlatformServiceHarness({ rows: [ { code: 'KS', name: '快手平台', platform_code: 'KS_ROUTE', print_platform_id: 9527 }, ], printPlatformRows: [ - { id: 9527, platform_code: 'POLYAPI' }, + { id: 9527, platform_code: 'LEGACY_POLYAPI', request_platform_code: 'POLYAPI' }, ], settingRows: [ { id: 31, code: 'KS-STORE', platform_code: 'KS', warehouse_id: 100000, name: 'KS-STORE' }, @@ -174,9 +174,9 @@ describe('test/app/service/systems/platform.test.js', () => { const result = await service.getPlatformList(false, true); - assert.equal(result[0].route_platform_code, 'KS_ROUTE'); + assert.equal(result[0].route_platform_code, 'POLYAPI'); assert.equal(result[0].default_express_interface, 'POLYAPI'); - assert.equal(result[1].route_platform_code, 'KS_ROUTE'); + assert.equal(result[1].route_platform_code, 'POLYAPI'); assert.equal(result[1].default_express_interface, 'POLYAPI'); }); @@ -241,13 +241,13 @@ describe('test/app/service/systems/platform.test.js', () => { ]); }); - it('should derive default_express_interface from PrintPlatform.platform_code instead of platform.platform_code', async () => { + it('should derive default_express_interface from PrintPlatform.request_platform_code instead of platform.platform_code', async () => { const { ctx, calls } = createPlatformServiceHarness({ rows: [ { code: 'JD', name: '京东平台', platform_code: 'DIFF_ROUTER', print_platform_id: 9527 }, ], printPlatformRows: [ - { id: 9527, platform_code: 'OPEN_API' }, + { id: 9527, platform_code: 'LEGACY_ROUTER', request_platform_code: 'OPEN_API' }, ], settingRows: [ { id: 11, code: 'JD-STORE', platform_code: 'JD', warehouse_id: 100000 }, @@ -264,6 +264,30 @@ describe('test/app/service/systems/platform.test.js', () => { ]); }); + it('should not read wms_platform.platform_code for route_platform_code when request_platform_code is missing', async () => { + const { ctx } = createPlatformServiceHarness({ + rows: [ + { code: 'JD', name: '京东平台', platform_code: 'DIFF_ROUTER', print_platform_id: 9527 }, + ], + printPlatformRows: [ + { id: 9527, platform_code: 'LEGACY_ONLY', request_platform_code: '' }, + ], + settingRows: [ + { id: 11, code: 'JD-STORE', platform_code: 'JD', warehouse_id: 100000 }, + ], + }); + const service = new PlatformService(ctx); + + const result = await service.getPlatformList(false, true); + + assert.equal(result[0].route_platform_code, 'JD'); + assert.notEqual(result[0].route_platform_code, 'DIFF_ROUTER'); + assert.equal(result[0].default_express_interface, ''); + assert.equal(result[1].route_platform_code, 'JD'); + assert.notEqual(result[1].route_platform_code, 'DIFF_ROUTER'); + assert.equal(result[1].default_express_interface, ''); + }); + it('should load system platform list and cache it with the system cache key when systemOnly is true', async () => { const { ctx, calls } = createPlatformServiceHarness({ rows: [ diff --git a/test/app/service/systems/setting/expressInterface.test.js b/test/app/service/systems/setting/expressInterface.test.js index acff587..9cbf12d 100644 --- a/test/app/service/systems/setting/expressInterface.test.js +++ b/test/app/service/systems/setting/expressInterface.test.js @@ -171,9 +171,9 @@ function createHarness(options = {}) { }; const expressRows = options.expressRows || [ - { code: 'SF', name: '顺丰', PDD: 'SF-PDD', KS: 'SF-KS', DYXD: 'SF-DYXD' }, - { code: 'JD', name: '京东', PDD: 'JD-PDD', KS: 'JD-KS', DYXD: 'JD-DYXD' }, - { code: 'ZTO', name: '中通', PDD: 'ZTO-PDD', KS: 'ZTO-KS', DYXD: 'ZTO-DYXD' }, + { code: 'SF', name: '顺丰', PDD: 'SF-PDD', KS: 'SF-KS', DY: 'SF-DYXD' }, + { code: 'JD', name: '京东', PDD: 'JD-PDD', KS: 'JD-KS', DY: 'JD-DYXD' }, + { code: 'ZTO', name: '中通', PDD: 'ZTO-PDD', KS: 'ZTO-KS', DY: 'ZTO-DYXD' }, ]; const shopRows = options.shopRows || [ @@ -232,10 +232,10 @@ function createHarness(options = {}) { const printPlatformRows = Array.isArray(options.printPlatformRows) ? options.printPlatformRows : [ - { id: 1, platform_code: 'CAINIAO', platform_name: '菜鸟电子面单', platid: '1001', status: 'ACTIVE', deleted: 0, remark: '默认平台' }, - { id: 2, platform_code: 'PDD', platform_name: '拼多多电子面单', platid: '1002', status: 'ACTIVE', deleted: 0, remark: null }, - { id: 3, platform_code: 'DY', platform_name: '抖音电子面单', platid: '1003', status: 'DISABLED', deleted: 0, remark: null }, - { id: 4, platform_code: 'KS', platform_name: '快手电子面单', platid: '1004', status: 'ACTIVE', deleted: 1, remark: null }, + { id: 1, platform_code: 'CAINIAO', platform_name: '菜鸟电子面单', platid: '1001', status: 'ACTIVE', deleted: 0, remark: '默认平台', need_callback_url: 'https://callback.example.com/cainiao' }, + { id: 2, platform_code: 'PDD', platform_name: '拼多多电子面单', platid: '1002', status: 'ACTIVE', deleted: 0, remark: null, need_callback_url: null }, + { id: 3, platform_code: 'DY', platform_name: '抖音电子面单', platid: '1003', status: 'DISABLED', deleted: 0, remark: null, need_callback_url: null }, + { id: 4, platform_code: 'KS', platform_name: '快手电子面单', platid: '1004', status: 'ACTIVE', deleted: 1, remark: null, need_callback_url: null }, ]; const where = query && query.where ? query.where : {}; @@ -394,6 +394,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { platid: '1001', status: 'ACTIVE', remark: '默认平台', + need_callback_url: 'https://callback.example.com/cainiao', }, { id: 2, @@ -406,6 +407,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { platid: '1002', status: 'ACTIVE', remark: null, + need_callback_url: null, }, ]); }); @@ -896,7 +898,7 @@ describe('test/app/service/systems/setting/expressInterface.test.js', () => { it('should resolve sys_express_code by platform custom code', async () => { const { ctx, calls } = createHarness({ expressRows: [ - { code: 'SF', name: '顺丰', PDD: 'SF-PDD', KS: 'KS-SF', DYXD: 'DY-SF' }, + { code: 'SF', name: '顺丰', PDD: 'SF-PDD', KS: 'KS-SF', DY: 'DY-SF' }, ], }); const service = new SettingExpressInterfaceService(ctx); diff --git a/test/app/service/systems/setting/platform.test.js b/test/app/service/systems/setting/platform.test.js index 32cf64f..ee09763 100644 --- a/test/app/service/systems/setting/platform.test.js +++ b/test/app/service/systems/setting/platform.test.js @@ -232,6 +232,7 @@ describe('test/app/service/systems/setting/platform.test.js', () => { assert.equal(calls.findAndCountAllQuery.offset, 1); assert.equal(calls.findAndCountAllQuery.limit, 1); assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000); + assert.deepEqual(calls.findAndCountAllQuery.include[0].attributes, [ 'code', 'name' ]); assert.equal(result.code, 200); assert.equal(result.data.total, 1); assert.equal(result.data.page, 2); @@ -240,7 +241,7 @@ describe('test/app/service/systems/setting/platform.test.js', () => { assert.equal(result.data.list[0].platform_code, 'TB'); assert.equal(result.data.list[0].platform_name, '淘宝平台'); assert.equal(result.data.list[0].platform_label, 'TB-STORE (淘宝平台)'); - assert.equal(result.data.list[0].platform.platform_code, 'QM_WMS'); + assert.equal(result.data.list[0].platform.platform_code, 'TB'); }); it('should create a new platform setting and ignore external warehouse id', async () => { @@ -258,6 +259,7 @@ describe('test/app/service/systems/setting/platform.test.js', () => { assert.equal(calls.createPayload.code, 'PDD-STORE'); assert.equal(calls.createPayload.name, '淘宝设置'); assert.equal(calls.createPayload.platform_code, 'PDD'); + assert.deepEqual(calls.platformFindOneCalls[0].attributes, [ 'code', 'name' ]); assert.equal(result.data.code, 'PDD-STORE'); assert.equal(result.data.platform_code, 'PDD'); assert.equal(result.data.platform_name, '拼多多平台'); diff --git a/test/app/service/systems/shops.test.js b/test/app/service/systems/shops.test.js index f0f9b0c..eca4388 100644 --- a/test/app/service/systems/shops.test.js +++ b/test/app/service/systems/shops.test.js @@ -122,6 +122,7 @@ describe('test/app/service/systems/shops.test.js', () => { shop_name: '店铺A', custom_name: '自定义A', status: 1, + auth_expire_at: '2026-06-01 00:00:00', created_at: '2026-05-01 00:00:00', updated_at: '2026-05-02 00:00:00', printPlatform: { @@ -140,6 +141,7 @@ describe('test/app/service/systems/shops.test.js', () => { assert.equal(Array.isArray(result.list), true); assert.equal(result.list.length, 1); assert.equal(result.pagination.total, 1); + assert.equal(result.list[0].auth_expire_at, '2026-06-01 00:00:00'); assert.equal(Boolean(calls.shopFindAndCountAll.where), true); }); @@ -159,6 +161,31 @@ describe('test/app/service/systems/shops.test.js', () => { assert.equal(calls.shopCreatePayload.status, 0); }); + it('add 传入 shop_name 时也应忽略并生成待授权店铺名', async () => { + const { service, calls } = createHarness({ + shopFindOne: async query => { + const where = query && query.where ? query.where : {}; + + if (where.shop_name === '前端传入店铺名') { + return createFindOneResult({ id: 88 }); + } + + return null; + }, + }); + + const result = await service.add({ + custom_name: '02', + platform_code: 'PDD', + shop_name: '前端传入店铺名', + }); + + assert.equal(result.id, 9001); + assert.equal(calls.shopCreatePayload.custom_name, '02'); + assert.notEqual(calls.shopCreatePayload.shop_name, '前端传入店铺名'); + assert.equal(calls.shopCreatePayload.shop_name.startsWith('PENDING_'), true); + }); + it('del 遇到快递接口引用时应拒绝删除', async () => { const { service } = createHarness({ shopRows: [ diff --git a/tmp_mig_conn_dev.txt b/tmp_mig_conn_dev.txt new file mode 100644 index 0000000..dbaf551 --- /dev/null +++ b/tmp_mig_conn_dev.txt @@ -0,0 +1,8 @@ +{ + "env": "development", + "host": "112.124.21.102", + "port": 3306, + "database": "wms", + "username": "wms", + "password": "******" +} diff --git a/tmp_mig_migrate_output.txt b/tmp_mig_migrate_output.txt new file mode 100644 index 0000000..7e9fa00 Binary files /dev/null and b/tmp_mig_migrate_output.txt differ diff --git a/tmp_mig_migrate_output_utf8.txt b/tmp_mig_migrate_output_utf8.txt new file mode 100644 index 0000000..1f3eae6 --- /dev/null +++ b/tmp_mig_migrate_output_utf8.txt @@ -0,0 +1,17 @@ + +Sequelize CLI [Node: 24.14.0, CLI: 6.6.3, ORM: 6.37.7] + +Loaded configuration file "database\config.js". +Using environment "development". +node.exe : (node:42104) [DEP0176] DeprecationWarning: fs.R_OK is deprecated, us +e fs.constants.R_OK instead +所在位置 行:1 字符: 1 ++ & "C:\Program Files\nodejs/node.exe" "C:\Program Files\nodejs/node_mo ... ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : NotSpecified: ((node:42104) [D...ts.R_OK instead + :String) [], RemoteException + + FullyQualifiedErrorId : NativeCommandError + +(Use `node --trace-deprecation ...` to show where the warning was created) +No migrations were executed, database schema was already up to date. + diff --git a/tmp_mig_post_columns.txt b/tmp_mig_post_columns.txt new file mode 100644 index 0000000..33135f5 --- /dev/null +++ b/tmp_mig_post_columns.txt @@ -0,0 +1,14 @@ +{ + "client": "wms", + "rowCount": 1, + "rows": [ + { + "Field": "platid", + "Type": "int", + "Null": "YES", + "Key": "", + "Default": null, + "Extra": "" + } + ] +} diff --git a/tmp_mig_post_meta.txt b/tmp_mig_post_meta.txt new file mode 100644 index 0000000..d959d2d --- /dev/null +++ b/tmp_mig_post_meta.txt @@ -0,0 +1,7 @@ +{ + "client": "wms", + "rowCount": 0, + "rows": [ + + ] +} diff --git a/tmp_mig_pre_columns.txt b/tmp_mig_pre_columns.txt new file mode 100644 index 0000000..33135f5 --- /dev/null +++ b/tmp_mig_pre_columns.txt @@ -0,0 +1,14 @@ +{ + "client": "wms", + "rowCount": 1, + "rows": [ + { + "Field": "platid", + "Type": "int", + "Null": "YES", + "Key": "", + "Default": null, + "Extra": "" + } + ] +} diff --git a/tmp_mig_pre_meta.txt b/tmp_mig_pre_meta.txt new file mode 100644 index 0000000..d959d2d --- /dev/null +++ b/tmp_mig_pre_meta.txt @@ -0,0 +1,7 @@ +{ + "client": "wms", + "rowCount": 0, + "rows": [ + + ] +} diff --git a/tmp_sequelizemeta_check.json b/tmp_sequelizemeta_check.json new file mode 100644 index 0000000..ba7a7fe Binary files /dev/null and b/tmp_sequelizemeta_check.json differ diff --git a/tmp_sequelizemeta_check_utf8.json b/tmp_sequelizemeta_check_utf8.json new file mode 100644 index 0000000..d959d2d --- /dev/null +++ b/tmp_sequelizemeta_check_utf8.json @@ -0,0 +1,7 @@ +{ + "client": "wms", + "rowCount": 0, + "rows": [ + + ] +} diff --git a/tmp_show_columns_platid.json b/tmp_show_columns_platid.json new file mode 100644 index 0000000..4b5db69 Binary files /dev/null and b/tmp_show_columns_platid.json differ diff --git a/tmp_show_columns_platid_utf8.json b/tmp_show_columns_platid_utf8.json new file mode 100644 index 0000000..33135f5 --- /dev/null +++ b/tmp_show_columns_platid_utf8.json @@ -0,0 +1,14 @@ +{ + "client": "wms", + "rowCount": 1, + "rows": [ + { + "Field": "platid", + "Type": "int", + "Null": "YES", + "Key": "", + "Default": null, + "Extra": "" + } + ] +} diff --git a/tmp_show_create_table.json b/tmp_show_create_table.json new file mode 100644 index 0000000..3485135 Binary files /dev/null and b/tmp_show_create_table.json differ diff --git a/tmp_show_create_table_utf8.json b/tmp_show_create_table_utf8.json new file mode 100644 index 0000000..26527bd --- /dev/null +++ b/tmp_show_create_table_utf8.json @@ -0,0 +1,10 @@ +{ + "client": "wms", + "rowCount": 1, + "rows": [ + { + "Table": "wms_platform", + "Create Table": "CREATE TABLE `wms_platform` (\n `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,\n `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `interface_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `platid` int DEFAULT NULL,\n `appkey` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `app_secret` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `version` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `shoptype` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `ordersource` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,\n `component` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT \u0027打印组件标识\u0027,\n `print_platform_id` bigint unsigned DEFAULT NULL COMMENT \u0027关联打印平台ID\u0027,\n PRIMARY KEY (`code`) USING BTREE\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci" + } + ] +}