diff --git a/app/model/express_interface.js b/app/model/express_interface.js index f9dd3fe..b31e991 100644 --- a/app/model/express_interface.js +++ b/app/model/express_interface.js @@ -52,7 +52,7 @@ module.exports = app => { comment: '平台店铺ID', }, template_id: { - type: BIGINT(20).UNSIGNED, + type: STRING(50), allowNull: true, comment: '模板ID', }, diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 8073a08..690818c 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -28,9 +28,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,parseAddress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -2039,6 +2039,7 @@ class PendingOrderService extends OrderBaseService { logisticsName: String(requestData.logistics_name || '').trim(), isUrgency: [ 'Y', 'N' ].includes(requestData.is_urgency) ? requestData.is_urgency : 'N', invoiceFlag: [ 'Y', 'N' ].includes(requestData.invoice_flag) ? requestData.invoice_flag : 'N', + shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim(), receiverInfo: { name, mobile, @@ -2071,7 +2072,7 @@ class PendingOrderService extends OrderBaseService { } // 重复订单视为错误(与原逻辑保持一致) - if (result.message === '订单已存在') { + if (result.message === '订单已存在' || (result.data && result.data.deliveryOrderId)) { throw new Error(`订单号 ${deliveryOrderCode} 已存在`); } @@ -2089,6 +2090,157 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 下载创建订单导入模板。 + * + * 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。 + * + * @return {Promise} 统一 success 包装,含 base64 字符串与文件名。 + */ + async downloadCreateTemplate() { + const ExcelJS = require('exceljs'); + const workbook = new ExcelJS.Workbook(); + const sheet = workbook.addWorksheet('创建订单导入模板'); + + const columns = [ + // 必填 + { header: '*订单号', key: 'delivery_order_code', width: 24 }, + { header: '*收件人姓名', key: 'name', width: 16 }, + { header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 }, + { header: '*详细地址', key: 'detail_address', width: 36 }, + { header: '*商品编码', key: 'item_code', width: 20 }, + { header: '*计划数量', key: 'plan_qty', width: 12 }, + // 非必填 + { header: '货主ID', key: 'store_id', width: 12 }, + { header: '电话', key: 'tel', width: 16 }, + { header: '省份', key: 'province', width: 12 }, + { header: '城市', key: 'city', width: 12 }, + { header: '区/县', key: 'area', width: 12 }, + { header: '镇/街道', key: 'town', width: 12 }, + { header: '邮编', key: 'zip_code', width: 12 }, + { header: '快递编码', key: 'logistics_code', width: 16 }, + { header: '快递名称', key: 'logistics_name', width: 16 }, + { header: '系统平台编码', key: 'sys_platform_code', width: 16 }, + { header: '来源平台编码', key: 'source_platform_code', width: 16 }, + { header: '来源订单号', key: 'source_order_codes', width: 20 }, + { header: '订单类型', key: 'order_type', width: 14 }, + { header: '是否紧急(Y/N)', key: 'is_urgency', width: 16 }, + { header: '是否需要发票(Y/N)', key: 'invoice_flag', width: 18 }, + { header: '商品名称', key: 'item_name', width: 24 }, + { header: '行号', key: 'order_line_no', width: 10 }, + { header: '实际价格', key: 'actual_price', width: 12 }, + { header: '店铺名称', key: 'shop_nick', width: 20 }, + ]; + + sheet.columns = columns; + + const headerRow = sheet.getRow(1); + headerRow.eachCell((cell, colNumber) => { + const col = columns[colNumber - 1]; + const isRequired = col && col.header.startsWith('*'); + cell.font = { bold: true, color: { argb: 'FF000000' } }; + cell.fill = { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: isRequired ? 'FFFFC000' : 'FFD9D9D9' }, + }; + cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true }; + cell.border = { + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' }, + }; + }); + headerRow.height = 36; + + sheet.addRow({ + delivery_order_code: 'ORD20260421001', + store_id: 1, + name: '张三', + mobile: '13800138000', + tel: '', + detail_address: 'XX路XX号', + province: '广东省', + city: '深圳市', + area: '南山区', + town: '', + zip_code: '518000', + logistics_code: 'STO', + logistics_name: '申通快递', + sys_platform_code: 'TB', + source_platform_code: '', + source_order_codes: '', + order_type: '', + is_urgency: 'N', + invoice_flag: 'N', + item_code: 'SKU001', + item_name: '商品A', + plan_qty: 2, + order_line_no: '1', + actual_price: 9.90, + shop_nick: '', + }); + + sheet.addRow({ + delivery_order_code: 'ORD20260421001', + store_id: 1, + name: '张三', + mobile: '13800138000', + tel: '', + detail_address: 'XX路XX号', + province: '广东省', + city: '深圳市', + area: '南山区', + town: '', + zip_code: '518000', + logistics_code: 'STO', + logistics_name: '申通快递', + sys_platform_code: 'TB', + source_platform_code: '', + source_order_codes: '', + order_type: '', + is_urgency: 'N', + invoice_flag: 'N', + item_code: 'SKU002', + item_name: '商品B', + plan_qty: 1, + order_line_no: '2', + actual_price: 19.90, + shop_nick: '', + }); + + const noteSheet = workbook.addWorksheet('填写说明'); + noteSheet.getColumn(1).width = 80; + const notes = [ + '【填写说明】', + '1. 带 * 的列为必填项,表头背景为橙色。', + '2. 每一行代表一条商品明细;同一订单的多个商品,订单号(delivery_order_code)必须相同。', + '3. 同一订单的所有行中,订单头信息(收件人、地址等)取第一行的值,后续行可省略但不影响解析。', + '4. mobile 和 tel 至少填写一项。', + '5. 计划数量(plan_qty)必须为正整数。', + '6. 是否紧急、是否需要发票只接受 Y 或 N(大写),不填默认 N。', + '7. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动补充;不填货主ID时,系统会从当前登录用户的上下文自动获取。', + '8. 同一文件内,相同订单号只会创建一个订单,不会重复创建。', + ]; + notes.forEach((note, i) => { + const row = noteSheet.getRow(i + 1); + row.getCell(1).value = note; + if (i === 0) { + row.getCell(1).font = { bold: true, size: 13 }; + } + }); + + const buffer = await workbook.xlsx.writeBuffer(); + const base64 = Buffer.from(buffer).toString('base64'); + + return this.success('ok', { + base64, + filename: '创建订单导入模板.xlsx', + mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + } + } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/pickCart.js b/app/service/systemMethods/pickCart.js index 3f9ac10..64479c6 100644 --- a/app/service/systemMethods/pickCart.js +++ b/app/service/systemMethods/pickCart.js @@ -293,6 +293,7 @@ class PickCartService extends MainService { const result = await service.systems.pickCart.codeDuplicateCheck({ cartCode, excludeCartId, + warehouseId: this.getWarehouseId(), }); return this.success('ok', { data: result, diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 0c94204..1512fd3 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1260,6 +1260,32 @@ class DeliveryOrderService extends Service { items_str_length: items_str.length, items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''), }); + } else if (lineData.length > 0) { + // MANUAL 降级:stockQuantityMap 为空时,从 lineData 直接计算统计 + stock_count = lineData.length; + item_total_count = lineData.reduce((sum, ld) => sum + (Number(ld.plan_qty) || 0), 0); + total_weight = 0; + // items_str 用 item_id 作为标识 + const itemEntries = new Map(); + for (const ld of lineData) { + const iid = Number(ld.item_id) || 0; + const qty = Number(ld.plan_qty) || 0; + itemEntries.set(iid, (itemEntries.get(iid) || 0) + qty); + } + items_str = Array.from(itemEntries.entries()) + .sort(([a], [b]) => a - b) + .map(([iid, qty]) => `${iid}+${qty}`) + .join('|'); + source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); + + ctx.logger.debug('[订单统计信息-MANUAL降级]', { + orderId, + stock_count, + item_total_count, + total_weight, + items_str_length: items_str.length, + items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''), + }); } if (errors.length > 0) { diff --git a/app/service/systems/express.js b/app/service/systems/express.js index faec8a3..e7d38a1 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -740,11 +740,14 @@ class ExpressService extends Service { const expressCode = String(row.express_code || '').trim(); const expressItem = expressMap instanceof Map ? expressMap.get(expressCode) : null; - const label = this.buildMergedExpressLabel(code, expressItem); + const settingName = String(row.name || '').trim(); + const label = settingName + ? `${code} (${settingName})` + : this.buildMergedExpressLabel(code, expressItem); return { code, - name: label, + name: settingName || code, value: code, label, is_system_setting: true, @@ -775,6 +778,7 @@ class ExpressService extends Service { const where = { warehouse_id: normalizedWarehouseId, + deleted_at: null, }; if (normalizedExpressCode) { diff --git a/app/service/systems/setting/express.js b/app/service/systems/setting/express.js index 30a05f1..aa4590f 100644 --- a/app/service/systems/setting/express.js +++ b/app/service/systems/setting/express.js @@ -71,11 +71,46 @@ class SettingExpressService extends Service { /** * 清理当前仓库快递列表缓存。 * + * 优先通过 Redis keys 通配扫描删除所有 express:list* 变体, + * 若 Redis 不可用则降级为逐键删除已知命名键,确保核心缓存必清。 + * * @param {number|string} warehouseId 仓库主体ID * @return {Promise} */ async clearExpressListCache(warehouseId) { - await this.deleteCacheByKey(this.getExpressListCacheKey(warehouseId)); + const { app, ctx } = this; + + // 优先:Redis 通配扫描删除所有 express:list* 变体 + try { + const redisClient = app.redis && typeof app.redis.get === 'function' + ? app.redis.get('cache') + : null; + if (redisClient && typeof redisClient.keys === 'function') { + const matchedKeys = await redisClient.keys('express:list*'); + if (Array.isArray(matchedKeys) && matchedKeys.length > 0) { + await redisClient.del(...matchedKeys); + } + } + } catch (err) { + if (ctx && ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn( + '[clearExpressListCache] Redis keys 扫描失败,降级为已知键删除: %s', + err.message + ); + } + } + + // 降级:删除已知命名的缓存键 + const normalizedWarehouseId = Number(warehouseId || 0); + const knownKeys = [ + 'express:list', + 'express:list:system', + 'express:list:system:normal', + ]; + if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) { + knownKeys.push(`express:list:${normalizedWarehouseId}`); + } + await Promise.all(knownKeys.map(k => this.deleteCacheByKey(k))); } /** diff --git a/app/service/systems/setting/expressInterface.js b/app/service/systems/setting/expressInterface.js index 7cbefae..ff4ebfc 100644 --- a/app/service/systems/setting/expressInterface.js +++ b/app/service/systems/setting/expressInterface.js @@ -730,7 +730,7 @@ class SettingExpressInterfaceService extends Service { warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id), shop_id: row.shop_id === undefined || row.shop_id === null ? null : Number(row.shop_id), platform_shop_id: row.platform_shop_id === undefined || row.platform_shop_id === null ? null : Number(row.platform_shop_id), - template_id: row.template_id === undefined || row.template_id === null ? null : Number(row.template_id), + template_id: this.normalizeOptionalText(row.template_id, 'template_id', 50), paymode: row.paymode === undefined || row.paymode === null ? null : Number(row.paymode), brandno: this.normalizeOptionalText(row.brandno, 'brandno', 255), providertype: this.normalizeOptionalText(row.providertype, 'providertype', 50), @@ -1215,10 +1215,14 @@ class SettingExpressInterfaceService extends Service { allowEmpty: true, min: 1, }), - template_id: this.normalizeInteger(data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', { - allowEmpty: true, - min: 1, - }), + template_id: (() => { + const normalizedTemplateId = this.normalizeOptionalText( + data.template_id !== undefined ? data.template_id : data.templateId, + 'template_id', + 50 + ); + return normalizedTemplateId === '' ? null : normalizedTemplateId; + })(), paymode: this.normalizeInteger(data.paymode !== undefined ? data.paymode : data.payMode, 'paymode', { allowEmpty: true, }), @@ -1443,14 +1447,12 @@ class SettingExpressInterfaceService extends Service { } if (hasTemplateId) { - updates.template_id = this.normalizeInteger( + const normalizedTemplateId = this.normalizeOptionalText( data.template_id !== undefined ? data.template_id : data.templateId, 'template_id', - { - allowEmpty: true, - min: 1, - } + 50 ); + updates.template_id = normalizedTemplateId === '' ? null : normalizedTemplateId; } if (hasPaymode) { diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index cb809f5..8586576 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -3080,8 +3080,10 @@ class stockStoreService extends Service { } /** * 快捷搜索仓库商品并补全库存管理标记。 + * 支持多词 OR 搜索:使用中英文逗号 `,` `,`、换行 `\n`、回车 `\r` 分隔多个关键词, + * 任意一个词在 item_code、item_name、goods_code 或条形码中命中即返回该商品。 * @param {Object} data 请求体 - * @param {string} [data.keyword] 搜索关键字 + * @param {string} [data.keyword] 搜索关键字,支持多词以逗号/换行分隔进行 OR 匹配 * @param {number|string} [data.store_id] 货主ID * @param {boolean} [data.with_stock=false] 是否返回关联库存数据 * @param {boolean} [data.is_batch=false] with_stock=true 时是否按批次返回 @@ -3107,40 +3109,79 @@ class stockStoreService extends Service { // 准备关联查询的条件 const includeConditions = []; - // 如果有搜索关键词,创建搜索条件 + // 如果有搜索关键词,按分隔符拆分为多个词进行 OR 匹配 if (keyword && keyword.trim()) { - const searchKeyword = `%${keyword.trim()}%`; + // 按分隔符拆词:中英文逗号、换行、回车、管道符、空格 + const keywords = keyword + .split(/[,\n\r,\|\s]+/) + .map(k => k.trim()) + .filter(k => k.length > 0); - // 先构建主表的搜索条件 - const stockWarehouseConditions = { - [Op.or]: [ - { item_code: { [Op.like]: searchKeyword } }, - { item_name: { [Op.like]: searchKeyword } }, - { goods_code: { [Op.like]: searchKeyword } }, - ], - }; + if (keywords.length === 1) { + // 单个词,保持原逻辑 + const searchKeyword = `%${keywords[0]}%`; - // 添加条形码关联查询条件 - includeConditions.push({ - model: app.model.StockBarcode, - as: 'barcodes', - attributes: [ 'barcode' ], - required: false, // 使用LEFT JOIN - where: { - barcode: { [Op.like]: searchKeyword }, - }, - }); + const stockWarehouseConditions = { + [Op.or]: [ + { item_code: { [Op.like]: searchKeyword } }, + { item_name: { [Op.like]: searchKeyword } }, + { goods_code: { [Op.like]: searchKeyword } }, + ], + }; - // 合并搜索条件 - whereCondition[Op.or] = [ - stockWarehouseConditions, - // 如果barcodes表有匹配的记录,则也返回该商品 - { - '$barcodes.barcode$': { [Op.like]: searchKeyword }, - }, - ]; - } else { - // 如果没有关键词,也包含barcodes关联(但不需要where条件) + includeConditions.push({ + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + where: { + barcode: { [Op.like]: searchKeyword }, + }, + }); + + whereCondition[Op.or] = [ + stockWarehouseConditions, + { + '$barcodes.barcode$': { [Op.like]: searchKeyword }, + }, + ]; + } else if (keywords.length > 1) { + // 多个词,OR 包装:每个词在 item_code/item_name/goods_code/barcode 任一命中即可 + const stockWarehouseConditions = { + [Op.or]: keywords.flatMap(kw => { + const like = `%${kw}%`; + return [ + { item_code: { [Op.like]: like } }, + { item_name: { [Op.like]: like } }, + { goods_code: { [Op.like]: like } }, + ]; + }), + }; + + includeConditions.push({ + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + where: { + [Op.or]: keywords.map(kw => ({ + barcode: { [Op.like]: `%${kw}%` }, + })), + }, + }); + + whereCondition[Op.or] = [ + stockWarehouseConditions, + ...keywords.map(kw => ({ + '$barcodes.barcode$': { [Op.like]: `%${kw}%` }, + })), + ]; + } + // keywords.length === 0 时不加搜索条件,走 else 分支 + } + + if (!includeConditions.some(c => c.as === 'barcodes')) { + // 如果没有关键词或关键词全为空,也包含 barcodes 关联(但不需要 where 条件) includeConditions.push({ model: app.model.StockBarcode, as: 'barcodes', diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 2d996be..7bb3df9 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -2301,6 +2301,8 @@ class InventoryService extends Service { delete row.stock.store_stock; delete row.stock.is_batch_mgmt; } + // 货主名称提升到根层级,便于前端直接使用 + row.store_name = row.stock?.store_name || null; row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; @@ -2401,6 +2403,8 @@ class InventoryService extends Service { delete row.stock.store_stock; delete row.stock.is_batch_mgmt; } + // 货主名称提升到根层级,便于前端直接使用 + row.store_name = row.stock?.store_name || null; row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : ''; row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : ''; row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; diff --git a/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js new file mode 100644 index 0000000..8bfea14 --- /dev/null +++ b/database/migrations/20260606-remove-unique-platform-code-from-express-setting.js @@ -0,0 +1,102 @@ +'use strict'; + +const TABLE_NAME = 'wms_express_setting'; +const UNIQUE_INDEX_NAME = 'platform_code'; +const NEW_INDEX_NAME = 'idx_express_warehouse'; +const FK_NAME = 'wms_express_setting_ibfk_1'; + +/** + * 检查指定表中是否存在指定名称的索引(通过 SHOW INDEX 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} indexName 索引名。 + * @returns {Promise} 索引是否存在。 + */ +const hasIndex = async (queryInterface, tableName, indexName) => { + const [rows] = await queryInterface.sequelize.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`, + { replacements: { indexName } } + ); + return rows && rows.length > 0; +}; + +/** + * 检查指定外键约束是否存在(通过 information_schema 做幂等判断)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @param {string} constraintName 约束名。 + * @returns {Promise} 外键是否存在。 + */ +const hasForeignKey = async (queryInterface, tableName, constraintName) => { + const [rows] = await queryInterface.sequelize.query( + `SELECT CONSTRAINT_NAME + FROM information_schema.TABLE_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = DATABASE() + AND TABLE_NAME = :tableName + AND CONSTRAINT_NAME = :constraintName + AND CONSTRAINT_TYPE = 'FOREIGN KEY'`, + { replacements: { tableName, constraintName } } + ); + return rows && rows.length > 0; +}; + +module.exports = { + /** + * 正向迁移:先删除外键依赖,再删除唯一索引,最后添加普通索引替代。 + * 原因:同一系统快递编码(express_code)允许对应多个自定义编码(code), + * 原 UNIQUE KEY `platform_code` ON (`express_code`, `warehouse_id`) 约束过紧, + * 且该索引被外键 `wms_express_setting_ibfk_1`(express_code → wms_express.code)依赖。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @returns {Promise} 无返回值。 + */ + async up(queryInterface) { + // 1. 先删除依赖该索引的外键约束 + if (await hasForeignKey(queryInterface, TABLE_NAME, FK_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP FOREIGN KEY \`${FK_NAME}\`;` + ); + } + + // 2. 删除原来的唯一索引 + if (await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${UNIQUE_INDEX_NAME}\`;` + ); + } + + // 3. 添加普通索引替代(用于查询性能) + if (!(await hasIndex(queryInterface, TABLE_NAME, NEW_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${NEW_INDEX_NAME}\` (express_code, warehouse_id);` + ); + } + }, + + /** + * 回滚迁移:恢复唯一索引与外键约束。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @returns {Promise} 无返回值。 + */ + async down(queryInterface) { + // 1. 删除替代的普通索引 + if (await hasIndex(queryInterface, TABLE_NAME, NEW_INDEX_NAME)) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${NEW_INDEX_NAME}\`;` + ); + } + + // 2. 恢复唯一索引(幂等:已存在则跳过) + if (!(await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD UNIQUE INDEX \`${UNIQUE_INDEX_NAME}\` (express_code, warehouse_id);` + ); + } + + // 3. 恢复外键约束(幂等:已存在则跳过) + if (!(await hasForeignKey(queryInterface, TABLE_NAME, FK_NAME))) { + await queryInterface.sequelize.query( + `ALTER TABLE \`${TABLE_NAME}\` ADD CONSTRAINT \`${FK_NAME}\` FOREIGN KEY (express_code) REFERENCES wms_express (code);` + ); + } + }, +}; diff --git a/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js b/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js new file mode 100644 index 0000000..decfcc8 --- /dev/null +++ b/database/migrations/20260606000000-change-template-id-to-varchar-wms-express-interface.js @@ -0,0 +1,62 @@ +'use strict'; + +/** + * 将快递接口配置表的 template_id 列从 BIGINT 改为 VARCHAR(50), + * 以支持快手等平台返回的字符串模板 ID(如 "EBSTO11")。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:将 template_id 列类型从 BIGINT 改为 VARCHAR(50)(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + // 如果已经是 VARCHAR 类型则跳过(幂等) + if (columns.template_id.type && String(columns.template_id.type).toUpperCase().includes('VARCHAR')) { + return; + } + + await queryInterface.changeColumn(tableName, 'template_id', { + type: Sequelize.STRING(50), + allowNull: true, + comment: '模板ID', + }); + }, + + /** + * 回滚迁移:将 template_id 列类型从 VARCHAR(50) 改回 BIGINT(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + const tableName = 'wms_express_interface'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.template_id) { + return; + } + + // 如果已经是 BIGINT 类型则跳过(幂等) + if (columns.template_id.type && String(columns.template_id.type).toUpperCase().includes('BIGINT')) { + return; + } + + await queryInterface.changeColumn(tableName, 'template_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '模板ID', + }); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 75edba2..5c1d9b6 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2845,5 +2845,48 @@ "订单列表接口输出中新增 recheck_status 字段,类型 string,可选值 none/fin" ], "type": "updated" + }, + { + "version": "2026.06.06-system-01", + "date": "2026-06-06", + "summary": "恢复 order.pendingOrder.downloadCreateTemplate:方法仍存在于代码中,取消 deprecated 标记,完善文档描述", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "order.pendingOrder.downloadCreateTemplate 方法在 pendingOrder.js 中仍存在(line 2099),此前被误标记为 deprecated。", + "取消 status: 'deprecated' 标记,恢复为 active 状态。", + "移除 description 中的'(已作废)'后缀。", + "完善 description:说明模板包含必填列(橙色背景)、可选列(灰色背景)、示例数据行和填写说明工作表。", + "补充 response 字段说明:filename 和 mime 为固定值。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-01", + "date": "2026-06-07", + "summary": "order.pendingOrder.createOrder 文档新增 shop_nick 入参(店铺名称,可选,最大长度200)", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "在 order.pendingOrder.createOrder 的 request params 中新增 shop_nick 字段(string,非必填),对应代码实现中 shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim()。", + "shop_nick 已在 COPY_FIELDS 白名单中(pendingOrder.js L1738),仅文档缺失,本次为补齐。" + ], + "type": "updated" + }, + { + "version": "2026.06.07-system-02", + "date": "2026-06-07", + "summary": "order.pendingOrder.downloadCreateTemplate:模板新增 shop_nick 列(店铺名称),store_id/province/city/area 标注为非必填", + "methods": [ + "order.pendingOrder.downloadCreateTemplate" + ], + "notes": [ + "模板新增 shop_nick(店铺名称)列,非必填。", + "明确标注 store_id(货主ID)、province(省份)、city(城市)、area(区/县)为非必填列。", + "响应文档中新增 shop_nick 字段说明。" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index 5170308..7672209 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.4.0", - "updatedAt": "2026-06-05", + "version": "0.3.5", + "updatedAt": "2026-06-07", "headers": [ { "name": "platform", @@ -3612,6 +3612,13 @@ "source": "body", "description": "来源订单号" }, + { + "name": "shop_nick", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(自定义),最大长度 200" + }, { "name": "order_type", "type": "string", @@ -3687,43 +3694,6 @@ "province/city/area 为必填项,空值返回 400" ] }, - { - "method": "order.pendingOrder.downloadCreateTemplate", - "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为附件下载。表头中标注 * 的列为必填项,多行相同订单号的行组成一个完整订单。(已作废)", - "status": "deprecated", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [ - { - "name": "base64", - "type": "string", - "required": true, - "description": "base64 编码的 xlsx 文件内容" - }, - { - "name": "filename", - "type": "string", - "required": true, - "description": "建议保存的文件名" - }, - { - "name": "mime", - "type": "string", - "required": true, - "description": "文件 MIME 类型" - } - ], - "errors": [] - }, { "method": "order.pendingOrder.importOrdersFromExcel", "description": "通过 Excel 文件批量创建订单。接受 base64 编码的 xlsx 内容,按订单号分组,每组创建一个订单(step 由货主策略决定)。每行代表一条商品明细;同一订单号的多行组成一个完整订单,头信息取每组第一行。(已作废)", @@ -19972,7 +19942,7 @@ ] }, { - "groupName": "order.wave", + "groupName": "订单模块", "module": "order", "list": [ { @@ -20035,6 +20005,48 @@ "message": "查询失败" } ] + }, + { + "method": "order.pendingOrder.downloadCreateTemplate", + "description": "下载创建订单的 Excel 导入模板。返回 base64 编码的 xlsx 文件,前端解码后作为 .xlsx 附件下载。表头中标注 * 的列为必填项(橙色背景),可选列为灰色背景,包含示例数据行和填写说明工作表。多行相同订单号的行组成一个完整订单,每行代表一条商品明细。模板必填列:订单号(delivery_order_code)、收件人姓名(name)、手机号(mobile)、详细地址(detail_address)、商品编码(item_code)、计划数量(plan_qty);非必填列含:货主ID(store_id)、省份(province)、城市(city)、区/县(area)、店铺名称(shop_nick)等。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "base64", + "type": "string", + "required": true, + "description": "base64 编码的 xlsx 文件内容" + }, + { + "name": "filename", + "type": "string", + "required": true, + "description": "建议保存的文件名,固定为 创建订单导入模板.xlsx" + }, + { + "name": "mime", + "type": "string", + "required": true, + "description": "文件 MIME 类型,固定为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + }, + { + "name": "shop_nick", + "type": "string", + "required": false, + "description": "模板中新增的店铺名称列(非必填),用于标识订单所属店铺" + } + ], + "errors": [] } ] },