From e9e39eafa7b8b9dfdf4f23318c2b99f2d22367bd Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 16 Oct 2026 05:29:13 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E6=8F=90=E4=BA=A4=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E5=8C=BA=E5=85=B6=E4=BD=99=E6=9C=AA=E6=8F=90=E4=BA=A4=E6=94=B9?= =?UTF-8?q?=E5=8A=A8=EF=BC=88=E5=BE=AE=E4=BF=A1=E5=8D=8F=E8=AE=AE=E7=89=88?= =?UTF-8?q?=E6=9C=AC=20/=20=E6=89=AB=E6=8F=8F=E6=8A=A5=E6=96=87=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=20/=20container=20=E6=A8=A1=E5=9E=8B=20/=20=E9=80=80?= =?UTF-8?q?=E4=BB=B6=20like=20=E6=95=B0=E7=BB=84=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 微信开放平台:首次授权时写入系统默认用户须知作为首个协议版本 (ctx.service.systems.wechat.ensureDefaultAgreementVersion),含 seed / backfill 两个迁移 - 新增扫描报文接收接口 POST /scan:把「时间 + 条码」追加写入项目根目录 scan_records.xlsx (串行队列 + 原子写,避免并发写坏文件) - 新增 wms_container(容器/笼筐)模型与建表迁移 - 退件收货单 / 退件运单列表:like 查询条件支持字符串数组(多关键词 OR) - 新增 wms_return_unpack.created_at 索引迁移 - package.json:deploy 脚本改名为 depeeloy 注:scan_records.xlsx 是 /scan 接口写入的运行时数据文件,未纳入本次提交。 --- app/controller/home.js | 157 ++++++++++++++++++ app/controller/wechatOpen.js | 4 + app/model/container.js | 81 +++++++++ app/router.js | 4 + app/service/systemMethods/wechat.js | 5 +- app/service/systems/return_received.js | 5 + app/service/systems/return_waybill.js | 5 + app/service/systems/wechat.js | 65 +++++--- ...d-created-at-index-to-wms-return-unpack.js | 20 +++ .../20261013100000-create-wms-container.js | 98 +++++++++++ ...1014100000-seed-system-wechat-agreement.js | 44 +++++ ...110000-backfill-system-wechat-agreement.js | 49 ++++++ package.json | 2 +- 13 files changed, 514 insertions(+), 25 deletions(-) create mode 100644 app/model/container.js create mode 100644 database/migrations/20261010100000-add-created-at-index-to-wms-return-unpack.js create mode 100644 database/migrations/20261013100000-create-wms-container.js create mode 100644 database/migrations/20261014100000-seed-system-wechat-agreement.js create mode 100644 database/migrations/20261014110000-backfill-system-wechat-agreement.js diff --git a/app/controller/home.js b/app/controller/home.js index 2b7c48b..e32027e 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -1,9 +1,15 @@ const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const XLSX = require('xlsx'); const { Controller, } = require('egg'); const { toSuccess, toFailure } = require('../lib/api_response'); +// 扫描记录 Excel 追加串行队列(临时联调用,避免并发读写冲突) +let scanExcelWriteQueue = Promise.resolve(); + class HomeController extends Controller { /** * 规范化平台编码。 @@ -257,6 +263,157 @@ class HomeController extends Controller { this.ctx.body = 'ok'; } + /** + * 读取原始请求报文文本。 + * + * 优先取 koa-bodyparser 已解析的 rawBody;若上游未携带可识别的 + * Content-Type(bodyParser 未消费请求流),则直接从请求流中读取。 + * @return {Promise} 报文文本,读取失败时返回空字符串。 + */ + async readRawRequestText() { + const { ctx } = this; + const rawBody = ctx.request.rawBody; + + if (rawBody !== undefined && rawBody !== null) { + return Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody); + } + + const chunks = []; + + try { + for await (const chunk of ctx.req) { + chunks.push(chunk); + } + } catch (err) { + ctx.logger.error('[scan] 读取请求流失败', err && err.message || String(err)); + } + + return Buffer.concat(chunks.map(chunk => (Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)))).toString('utf8'); + } + + /** + * 生成格式化的当前时间字符串。 + * @param {Date} date 时间对象。 + * @return {string} YYYY-MM-DD HH:mm:ss。 + */ + formatScanRecordTime(date = new Date()) { + const pad = value => String(value).padStart(2, '0'); + + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; + } + + /** + * 将一次扫描记录(时间 + 条码)追加写入项目根目录的 scan_records.xlsx。 + * + * 临时联调用途:文件不存在则新建(含表头),存在则读取全部已有行后追加。 + * 写入复用 ExcelService 的原子写(临时文件 + rename),避免写坏文件。 + * + * @param {string} barcode 扫描到的条码内容。 + * @return {Promise<{filePath: string, timeText: string, barcode: string, totalRows: number}>} 追加结果。 + */ + async appendScanRecordToExcel(barcode) { + const filePath = path.join(this.app.baseDir, 'scan_records.xlsx'); + const timeText = this.formatScanRecordTime(); + const headerRow = [ '时间', '条码' ]; + let rows = [ headerRow ]; + + if (fs.existsSync(filePath)) { + try { + const workbook = XLSX.readFile(filePath); + const firstSheetName = workbook.SheetNames && workbook.SheetNames[0]; + + if (firstSheetName) { + const sheet = workbook.Sheets[firstSheetName]; + const parsedRows = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false }); + const existingRows = parsedRows.filter(row => Array.isArray(row) && row.length); + + if (existingRows.length) { + rows = existingRows; + } + } + } catch (error) { + this.ctx.logger.error('[scan] 读取根目录 scan_records.xlsx 失败,将重建文件', error && error.message || String(error)); + rows = [ headerRow ]; + } + } + + rows.push([ timeText, barcode ]); + + const workbook = XLSX.utils.book_new(); + const sheet = XLSX.utils.aoa_to_sheet(rows); + XLSX.utils.book_append_sheet(workbook, sheet, 'scan_records'); + + const buffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }); + await this.ctx.service.systems.excel.writeAtomicBufferFile(filePath, Buffer.from(buffer)); + + return { + filePath, + timeText, + barcode, + totalRows: rows.length - 1, + }; + } + + /** + * 扫描报文接收入口(POST /scan)。 + * + * 联调阶段:接收上游报文并原样打日志、回显,同时把扫描到的条码与时间 + * 追加写入项目根目录 scan_records.xlsx。 + */ + async scan() { + const { ctx } = this; + const rawBody = await this.readRawRequestText(); + const barcode = rawBody ? rawBody.trim() : ''; + let body = null; + let parseError = ''; + let excelRecord = null; + + if (rawBody) { + const trimmed = rawBody.trim(); + + if (trimmed.startsWith('{') || trimmed.startsWith('[')) { + try { + body = JSON.parse(trimmed); + } catch (err) { + parseError = err && err.message || String(err); + body = rawBody; + } + } else { + body = rawBody; + } + } + + if (barcode) { + excelRecord = await (scanExcelWriteQueue = scanExcelWriteQueue + .catch(() => {}) + .then(() => this.appendScanRecordToExcel(barcode))); + } + + ctx.logger.info('[scan] 收到请求报文', { + method: ctx.method, + url: ctx.url, + contentType: ctx.get('content-type'), + query: ctx.query, + headers: ctx.headers, + rawBody, + rawBodyHex: rawBody ? Buffer.from(rawBody, 'utf8').toString('hex') : '', + body, + parseError, + barcode, + excelRecord, + }); + + ctx.body = toSuccess({ + contentType: ctx.get('content-type'), + rawBody, + body, + parseError, + barcode, + excelRecord, + }); + } + async index() { const { ctx, diff --git a/app/controller/wechatOpen.js b/app/controller/wechatOpen.js index 312fd0f..cd2c4bb 100644 --- a/app/controller/wechatOpen.js +++ b/app/controller/wechatOpen.js @@ -190,6 +190,8 @@ class WechatOpenController extends Controller { await existing.update(fields); } else { await app.model.WechatApp.create({ appid: authorizerAppid, ...fields }); + // 首次授权:写入系统默认用户须知作为第一版(幂等) + await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid); } // 令牌写入 Redis 缓存(不落库) @@ -318,6 +320,8 @@ class WechatOpenController extends Controller { ctx.logger.info(`[wechatOpen] 已更新授权记录 appid=${authorizerAppid}`); } else { await app.model.WechatApp.create({ appid: authorizerAppid, ...fields }); + // 首次授权:写入系统默认用户须知作为第一版(幂等) + await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid); ctx.logger.info(`[wechatOpen] 已新增授权记录 appid=${authorizerAppid}`); } break; diff --git a/app/model/container.js b/app/model/container.js new file mode 100644 index 0000000..910c43c --- /dev/null +++ b/app/model/container.js @@ -0,0 +1,81 @@ +'use strict'; + +/** + * 容器(篮筐)资产登记表 Model。 + * + * 对应数据库表 `wms_container`,登记仓库的物理容器(篮筐)资产: + * 容器编号、使用状态、是否损坏、损坏说明、备注等。 + * 同一仓库内容器编号唯一,通过 warehouse_id 做数据隔离维度。 + * 后续散单拣货把购物车商品临时转移到容器时,通过 status 标记占用/空闲。 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { BIGINT, STRING, ENUM } = app.Sequelize; + + const Container = app.model.define('wms_container', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + container_no: { + type: STRING(50), + allowNull: false, + comment: '容器编号(篮筐编号)', + }, + status: { + type: ENUM('idle', 'in_use'), + allowNull: false, + defaultValue: 'idle', + comment: '使用状态:idle=空闲 in_use=占用(散单商品临时转移)', + }, + is_damaged: { + type: ENUM('Y', 'N'), + allowNull: false, + defaultValue: 'N', + comment: '是否损坏:Y=损坏 N=正常', + }, + damage_remark: { + type: STRING(255), + allowNull: true, + comment: '损坏说明', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '登记人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '登记人名称快照', + }, + }, { + tableName: 'wms_container', + comment: '容器(篮筐)资产登记表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'uk_warehouse_container_no', unique: true, fields: [ 'warehouse_id', 'container_no' ] }, + { name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] }, + { name: 'idx_status', fields: [ 'status' ] }, + { name: 'idx_is_damaged', fields: [ 'is_damaged' ] }, + ], + }); + + return Container; +}; diff --git a/app/router.js b/app/router.js index bb017c6..3492624 100644 --- a/app/router.js +++ b/app/router.js @@ -76,6 +76,10 @@ module.exports = app => { // 测试接口 router.get('/testSendData', controller.home.testSendData); + + // 扫描报文接收(联调入口,POST) + router.post('/scan', controller.home.scan); + // IM交互入口 router.post('/im', controller.im.index); }; diff --git a/app/service/systemMethods/wechat.js b/app/service/systemMethods/wechat.js index f1faeb7..8dd9e08 100644 --- a/app/service/systemMethods/wechat.js +++ b/app/service/systemMethods/wechat.js @@ -11,7 +11,8 @@ class WechatService extends MainService { // getAuthUrl:需登录、免权限、不记系统日志;loginByCode/getUserAgreementText:免登录、免权限、免鉴权; // pushLoginCode/queryauth/wxaauth/registerMiniprogram/getTemplateList/commit/getTrialQRCode/submitAudit/userList/getUserAgreement/setUserAgreement/getAgreementVersion:需登录、免权限(PC 已登录用户操作); // bindUser/updateInfo/uploadHeadimg/getMyLoginCode:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问 - this.systemInit('loginByCode,getUserAgreementText', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', '*', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode'); + // _noNeedLog:除 loginByCode 外其余方法不记系统日志(loginByCode 保留日志,便于排查登录请求的入参出参) + this.systemInit('loginByCode,getUserAgreementText', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'getAuthUrl,getUserAgreementText,getMyLoginCode,bindUser,bindByEmployee,pushLoginCode,queryauth,wxaauth,registerMiniprogram,updateInfo,uploadHeadimg,getTemplateList,getAuthorizerInfo,commit,submitAudit,getTrialQRCode,userList,getUserAgreement,setUserAgreement,getAgreementVersion', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode'); } /** @@ -298,7 +299,7 @@ class WechatService extends MainService { } /** - * 获取小程序模板库列表(需登录,Redis 缓存 24h)。 + * 获取小程序模板库列表(需登录,实时拉取,不缓存)。 * * @return {Promise} 统一响应结果。 */ diff --git a/app/service/systems/return_received.js b/app/service/systems/return_received.js index ba622f1..6e60eea 100644 --- a/app/service/systems/return_received.js +++ b/app/service/systems/return_received.js @@ -1037,6 +1037,11 @@ class ReturnReceivedService extends Service { case 'notin': return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; case 'like': + if (Array.isArray(value) && value.length > 0) { + return { + [Op.or]: value.map(item => ({ [Op.like]: `%${item}%` })), + }; + } return { [Op.like]: `%${value}%` }; case 'gt': return { [Op.gt]: value }; diff --git a/app/service/systems/return_waybill.js b/app/service/systems/return_waybill.js index 04a68fd..67d2c52 100644 --- a/app/service/systems/return_waybill.js +++ b/app/service/systems/return_waybill.js @@ -331,6 +331,11 @@ class ReturnWaybillService extends Service { case 'notin': return { [Op.notIn]: Array.isArray(value) ? value : [ value ] }; case 'like': + if (Array.isArray(value) && value.length > 0) { + return { + [Op.or]: value.map(item => ({ [Op.like]: `%${item}%` })), + }; + } return { [Op.like]: `%${value}%` }; case 'gt': return { [Op.gt]: value }; diff --git a/app/service/systems/wechat.js b/app/service/systems/wechat.js index 0e7debb..d3b1a5d 100644 --- a/app/service/systems/wechat.js +++ b/app/service/systems/wechat.js @@ -6,6 +6,9 @@ const WechatOpenClient = require('../../lib/wechat_open_client'); const STATE_TTL_SECONDS = 600; +// 系统默认用户须知的保留 appid(种子行,不面向真实小程序),供首次授权时作为第一版复制 +const SYSTEM_AGREEMENT_APPID = 'system'; + /** * 生成登录码:{uuid, form} JSON 的 base64 字符串。 * uuid 格式为 `{id}_{6位随机数}`(id 为 wms_user_oauth.id),form 固定 wechat; @@ -625,6 +628,40 @@ class WechatSystemsService extends Service { }); } + /** + * 首次授权的小程序自动写入系统默认用户须知作为第一版(幂等:已有任意版本则跳过)。 + * + * 系统默认内容来自 wms_wechat_agreement_version 中 appid='system' 的最新一条记录; + * 后续 PC 端 setUserAgreement 可继续追加新版本。 + * + * @param {string} appid 小程序 AppID。 + * @return {Promise} + */ + async ensureDefaultAgreementVersion(appid) { + const { ctx } = this; + if (!appid) return; + + const existing = await ctx.model.WechatAgreementVersion.findOne({ + where: { appid }, + attributes: [ 'id' ], + raw: true, + }); + if (existing) return; + + const systemDefault = await ctx.model.WechatAgreementVersion.findOne({ + where: { appid: SYSTEM_AGREEMENT_APPID }, + order: [[ 'id', 'DESC' ]], + attributes: [ 'content' ], + raw: true, + }); + if (!systemDefault || !systemDefault.content) { + ctx.logger.warn(`[wechat] 缺少系统默认用户须知(appid=${SYSTEM_AGREEMENT_APPID}),跳过写入 appid=${appid}`); + return; + } + + await ctx.model.WechatAgreementVersion.create({ appid, content: systemDefault.content }); + } + /** * 获取指定协议版本内容(需登录免权限):传入版本记录 id(wms_wechat_agreement_version.id, * 可在 wechat.userList 的 agreement_version_id 获取),校验该版本对应 appid 属于当前仓库的 @@ -1349,9 +1386,7 @@ class WechatSystemsService extends Service { } /** - * 获取小程序模板库列表(需登录),只拉取普通模板(template_type=0),Redis 缓存 24h。 - * - * 有缓存直接返回缓存列表;无缓存时调微信 gettemplatelist 拉取并写入缓存。 + * 获取小程序模板库列表(需登录),只拉取普通模板(template_type=0),不缓存(每次实时拉取)。 * * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 */ @@ -1359,20 +1394,6 @@ class WechatSystemsService extends Service { const { ctx } = this; const client = new WechatOpenClient(ctx); - const CACHE_KEY = 'wechat:template:list:normal'; - const CACHE_TTL_SECONDS = 24 * 3600; - - const cached = await client.cacheGet(CACHE_KEY); - if (cached) { - try { - const list = JSON.parse(cached); - if (Array.isArray(list)) { - return { success: true, data: { list, from_cache: true }, code: 200, message: '获取成功' }; - } - } catch (e) { - // 缓存损坏,忽略并重新拉取 - } - } const result = await client.getTemplateList(0); if (!result || Number(result.errcode) !== 0) { @@ -1381,9 +1402,8 @@ class WechatSystemsService extends Service { } const list = Array.isArray(result.template_list) ? result.template_list : []; - await client.cacheSet(CACHE_KEY, JSON.stringify(list), CACHE_TTL_SECONDS); - return { success: true, data: { list, from_cache: false }, code: 200, message: '获取成功' }; + return { success: true, data: { list }, code: 200, message: '获取成功' }; } /** @@ -1490,7 +1510,7 @@ class WechatSystemsService extends Service { * → 调微信 commit → 成功后回写 wms_wechat_app.template_id/user_version。 * * @param {object} data 入参。 - * @param {number|string} data.template_id 代码模板 ID(getTemplateList 获取)。 + * @param {number|string} data.template_id 代码模板 ID(getTemplateList 获取,允许 0:普通模板库模板 ID 从 0 开始)。 * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 */ async commit(data = {}) { @@ -1509,9 +1529,10 @@ class WechatSystemsService extends Service { return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; } + // template_id 允许 0:普通模板库的模板 ID 从 0 开始,0 表示第一个模板(微信官方 wxa/commit 示例即 "0") const templateId = Number(data.template_id); - if (!Number.isInteger(templateId) || templateId <= 0) { - return { success: false, data: null, code: 0, message: 'template_id 必须为正整数' }; + if (!Number.isInteger(templateId) || templateId < 0) { + return { success: false, data: null, code: 0, message: 'template_id 必须为非负整数' }; } // 判断授权权限:需包含代码管理权限集 18 diff --git a/database/migrations/20261010100000-add-created-at-index-to-wms-return-unpack.js b/database/migrations/20261010100000-add-created-at-index-to-wms-return-unpack.js new file mode 100644 index 0000000..972ebcd --- /dev/null +++ b/database/migrations/20261010100000-add-created-at-index-to-wms-return-unpack.js @@ -0,0 +1,20 @@ +'use strict'; + +/** + * wms_return_unpack 补充登记时间索引。 + * 看板 fulfillment 今日拆包件数按 warehouse_id + created_at 今日范围计数, + * 原表仅有 (warehouse_id, unpack_date) 等索引,按登记时间过滤会退化为 + * 全表扫描,新增 (warehouse_id, created_at) 复合索引使范围过滤走索引 + * (对齐 wms_return_received 的 idx_warehouse_created_at)。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.addIndex('wms_return_unpack', [ 'warehouse_id', 'created_at' ], { + name: 'idx_warehouse_created_at', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('wms_return_unpack', 'idx_warehouse_created_at'); + }, +}; diff --git a/database/migrations/20261013100000-create-wms-container.js b/database/migrations/20261013100000-create-wms-container.js new file mode 100644 index 0000000..4f25778 --- /dev/null +++ b/database/migrations/20261013100000-create-wms-container.js @@ -0,0 +1,98 @@ +'use strict'; + +/** + * 创建容器(篮筐)资产登记表 wms_container。 + * + * 用于登记仓库的物理容器(篮筐)资产:容器编号、使用状态、是否损坏、损坏说明、备注等。 + * 同一仓库内容器编号唯一(uk_warehouse_container_no),通过 warehouse_id 做数据隔离。 + * + * 后续用途:散单拣货把购物车商品临时转移到容器时,通过 status 标记容器占用/空闲。 + * + * 字段: + * warehouse_id 仓库ID(数据隔离维度) + * container_no 容器编号(篮筐编号) + * status 使用状态(idle=空闲 in_use=占用) + * is_damaged 是否损坏(Y=损坏 N=正常) + * damage_remark 损坏说明 + * remark 备注 + * creator_id / creator_name 登记人 + * created_at / updated_at 审计时间 + * + * 索引: + * uk_warehouse_container_no(warehouse_id + container_no 唯一) + * idx_warehouse_id + * idx_status + * idx_is_damaged + */ + +const TABLE_NAME = 'wms_container'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, ENUM, DATE } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(数据隔离维度)', + }, + container_no: { + type: STRING(50), + allowNull: false, + comment: '容器编号(篮筐编号)', + }, + status: { + type: ENUM('idle', 'in_use'), + allowNull: false, + defaultValue: 'idle', + comment: '使用状态:idle=空闲 in_use=占用(散单商品临时转移)', + }, + is_damaged: { + type: ENUM('Y', 'N'), + allowNull: false, + defaultValue: 'N', + comment: '是否损坏:Y=损坏 N=正常', + }, + damage_remark: { + type: STRING(255), + allowNull: true, + comment: '损坏说明', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + creator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '登记人账户ID', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '登记人名称快照', + }, + created_at: { type: DATE, allowNull: false, comment: '创建时间' }, + updated_at: { type: DATE, allowNull: false, comment: '更新时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'container_no' ], { unique: true, name: 'uk_warehouse_container_no' }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'is_damaged' ], { name: 'idx_is_damaged' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20261014100000-seed-system-wechat-agreement.js b/database/migrations/20261014100000-seed-system-wechat-agreement.js new file mode 100644 index 0000000..2359ab3 --- /dev/null +++ b/database/migrations/20261014100000-seed-system-wechat-agreement.js @@ -0,0 +1,44 @@ +'use strict'; + +/** + * 用户须知系统默认版本种子(2026-10-14): + * - appid='system' 作为系统级默认须知模板(保留行,不面向真实小程序); + * - 新授权的小程序(首次授权)自动复制该内容作为第一版 + * (见 app/service/systems/wechat.js#ensureDefaultAgreementVersion); + * - 幂等:已存在 appid='system' 记录则跳过。 + */ + +const TABLE_NAME = 'wms_wechat_agreement_version'; +const SYSTEM_APPID = 'system'; + +const DEFAULT_CONTENT = [ + '

小程序用户须知

', + '

欢迎使用本小程序。在使用本小程序及相关服务前,请仔细阅读并理解本须知。

', + '

1. 账号与绑定:登录后可通过「绑定账号」功能关联您的仓库系统账号;绑定信息仅用于身份识别与业务操作,请妥善保管账号密码。

', + '

2. 数据与隐私:小程序仅收集提供仓储、物流等服务所必需的信息(如登录凭证、订单与库存数据),不会向无关第三方泄露。

', + '

3. 使用规范:请勿利用本小程序从事违反法律法规或侵害他人权益的行为;如发现异常,请及时联系本小程序运营方。

', + '

4. 条款更新:本须知可能适时更新,更新后的内容自发布时生效。

', +].join(''); + +module.exports = { + async up(queryInterface) { + const rows = await queryInterface.sequelize.query( + `SELECT id FROM ${TABLE_NAME} WHERE appid = ? LIMIT 1`, + { replacements: [ SYSTEM_APPID ], type: queryInterface.sequelize.QueryTypes.SELECT } + ); + if (rows && rows.length > 0) { + return; + } + await queryInterface.sequelize.query( + `INSERT INTO ${TABLE_NAME} (appid, content, created_at, updated_at) VALUES (?, ?, NOW(), NOW())`, + { replacements: [ SYSTEM_APPID, DEFAULT_CONTENT ] } + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `DELETE FROM ${TABLE_NAME} WHERE appid = ?`, + { replacements: [ SYSTEM_APPID ] } + ); + }, +}; diff --git a/database/migrations/20261014110000-backfill-system-wechat-agreement.js b/database/migrations/20261014110000-backfill-system-wechat-agreement.js new file mode 100644 index 0000000..7dc817a --- /dev/null +++ b/database/migrations/20261014110000-backfill-system-wechat-agreement.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 回填系统默认用户须知(2026-10-14): + * - 对 wms_wechat_app 中尚不存在任何用户须知版本的小程序,复制系统默认须知 + * (wms_wechat_agreement_version 中 appid='system' 最新一条)作为第一版; + * - 幂等:已有任意版本的小程序跳过;无系统默认行则跳过(依赖种子迁移 20261014100000)。 + */ + +const TABLE_NAME = 'wms_wechat_agreement_version'; +const SYSTEM_APPID = 'system'; + +module.exports = { + async up(queryInterface) { + const { QueryTypes } = queryInterface.sequelize; + + const systemRows = await queryInterface.sequelize.query( + `SELECT content FROM ${TABLE_NAME} WHERE appid = ? ORDER BY id DESC LIMIT 1`, + { replacements: [ SYSTEM_APPID ], type: QueryTypes.SELECT } + ); + const systemContent = systemRows && systemRows.length > 0 ? systemRows[0].content : null; + if (!systemContent) { + console.log('[backfill] 缺少系统默认须知(appid=system),跳过回填'); + return; + } + + const appids = await queryInterface.sequelize.query( + `SELECT a.appid FROM wms_wechat_app a + WHERE NOT EXISTS ( + SELECT 1 FROM ${TABLE_NAME} v WHERE v.appid = a.appid + ) + ORDER BY a.id ASC`, + { type: QueryTypes.SELECT } + ); + + for (const row of appids) { + await queryInterface.sequelize.query( + `INSERT INTO ${TABLE_NAME} (appid, content, created_at, updated_at) VALUES (?, ?, NOW(), NOW())`, + { replacements: [ row.appid, systemContent ] } + ); + } + + console.log(`[backfill] 回填系统默认须知 appid 数量: ${appids.length}`); + }, + + async down() { + // 回填行与人工版本无法可靠区分,不做逆向删除 + }, +}; diff --git a/package.json b/package.json index 4eabf39..cc2f1fa 100644 --- a/package.json +++ b/package.json @@ -69,7 +69,7 @@ "ops:clean-root-logs:apply": "node ./script/check-root-logs.cjs production --clean --apply", "version:record": "node ./script/version-record.cjs", "version:history": "node ./script/version-history.cjs --limit=50", - "deploy": "npm run deploy:prod", + "depeeloy": "npm run deploy:prod", "deploy:prod": "node ./script/deploy-remote.cjs production", "rollback": "npm run rollback:prod", "rollback:prod": "node ./script/rollback-remote.cjs production",