diff --git a/.github/agents/发布.agent.md b/.github/agents/发布.agent.md index 7e1ff09..9baa21f 100644 --- a/.github/agents/发布.agent.md +++ b/.github/agents/发布.agent.md @@ -33,10 +33,12 @@ model: GPT-5 mini (copilot) 4. **AI 严禁展示或复述** 其中的 `host`、`username`、`privateKeyPath` 等敏感信息 5. 发布完成后,必须通过可验证命令确认结果,再报告结论 6. 若用户只要求协助,不主动改写本地 SSH 配置或远端敏感文件 +7. **发布前必须检查迁移状态**:若有 pending 迁移,必须先完成迁移再发布代码 +8. **迁移回退需用户明确确认**:执行 `db:migrate:undo` 前必须告知数据丢失风险并获得用户确认,不得主动触发 ## 推荐执行顺序 -### 发布前 +### 第一步:发布前检查 ```powershell npm run setup:hooks @@ -44,26 +46,60 @@ npm run deploy:precheck npm run deploy:verify ``` -### 正式发布 +### 第二步:检查数据库迁移状态 + +```powershell +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production +``` + +- 若有 `down`(pending)条目:记录迁移文件名,继续执行第三步 +- 若全部 `up`:跳过第三步,直接执行第四步 + +### 第三步:执行数据库迁移(有 pending 时) + +```powershell +$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production +``` + +**执行前必须**: +- 确认生产库已有完整备份(快照或 mysqldump) +- 记录本次执行的迁移文件名(用于回退参考) +- 迁移成功后再执行代码发布 + +### 第四步:发布代码 ```powershell npm run deploy:prod ``` -### 发布后验证 +### 第五步:发布后验证 ```powershell npm run deploy:version npm run deploy:verify ``` -### 回退 +### 回退流程 + +**代码回退**(不影响数据库): ```powershell npm run rollback:prod npm run rollback:prod -- --backup=backup-20260324123045.tar.gz ``` +**数据库迁移回退**(高风险,需用户明确确认): + +```powershell +# 回退最近一次迁移 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo --migrations-path database/migrations --env production + +# 回退到指定迁移 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo:all --to 20260504000000-baseline.js --migrations-path database/migrations --env production +``` + +> ⚠️ **迁移回退警告**:`db:migrate:undo` 可能造成数据丢失(如 DROP COLUMN)。代码回退后如无数据异常,**不建议执行迁移回退**。只有在用户明确确认并了解风险后才可执行。 + ## 固定命令入口 ```powershell diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md index ea2f2ec..03a045e 100644 --- a/.github/agents/数据库.agent.md +++ b/.github/agents/数据库.agent.md @@ -30,17 +30,19 @@ model : GPT-5 mini (copilot) 1. **所有数据库查询优先使用** `script/db-query.ps1` 2. **对非测试仓库数据默认只允许只读查询**:`SELECT` / `SHOW` / `DESC` / `EXPLAIN` 3. **禁止对非测试仓库执行** `UPDATE` / `DELETE` / `INSERT` **等写操作** -4. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作** -5. 如用户已明确说明是测试仓且允许写操作: +4. **禁止直接执行任何 DDL 语句**:`ALTER TABLE` / `CREATE TABLE` / `DROP TABLE` / `ADD COLUMN` / `DROP COLUMN` / `ADD INDEX` / `DROP INDEX` 等均不得直接在数据库执行,无论是测试仓还是生产仓 +5. **所有 schema 变更必须通过迁移文件完成**:在 `database/migrations/` 下新建迁移文件,文件名格式为 `YYYYMMDDHHmmss-描述.js`,通过 `npx sequelize-cli db:migrate` 执行 +6. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作** +7. 如用户已明确说明是测试仓且允许写操作: - 必须先生成影响范围确认 SQL(`COUNT(*) + 同 WHERE 条件`) - 明确告知风险 - 获得用户确认后再执行 -6. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认 -7. 做接口排障时,优先链路: +8. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认 +9. 做接口排障时,优先链路: - 先定位 `app/model` / `service` / `controller` - 再给 SQL - 最后执行验证并输出根因 -8. 输出要求: +10. 输出要求: - 所有回复必须以 `[DB]` 开头 - 优先给结论、关键字段和下一步建议 @@ -91,6 +93,56 @@ powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Q - 报错连接失败(超时/拒绝访问) - 检查数据库 IP、端口、用户名密码、网络白名单 +## Schema 变更规范(迁移文件强制要求) + +**所有对数据库结构的变更(包括开发和生产)必须通过 Sequelize 迁移文件完成,禁止直接执行 DDL。** + +### 迁移文件规范 + +- 位置:`database/migrations/YYYYMMDDHHmmss-描述.js` +- 命名:时间戳 + 短横线 + 英文描述,例如 `20260504120000-add-remark-to-wms-order.js` +- 结构:必须同时实现 `up`(变更)和 `down`(回滚) + +### 迁移文件模板 + +```js +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // 在此写变更 SQL,例如: + await queryInterface.addColumn('wms_order', 'remark', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: '备注', + }); + }, + + async down(queryInterface, Sequelize) { + // 在此写回滚 SQL,例如: + await queryInterface.removeColumn('wms_order', 'remark'); + }, +}; +``` + +### 执行命令 + +```powershell +# 本地执行 +npx sequelize-cli db:migrate --migrations-path database/migrations + +# 生产执行 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production + +# 查看状态 +$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production +``` + +### 同步 Model 文件 + +执行迁移后,必须同步更新对应的 `app/model/*.js` 文件,保持 Model 定义与数据库结构一致。 + ## 结论 数据库相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“数据库相关必须使用 `wms-db-agent`”这一条约束。 diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md index 6f37e86..d8fdb78 100644 --- a/.github/agents/文档.agent.md +++ b/.github/agents/文档.agent.md @@ -11,7 +11,7 @@ model: GPT-5 mini (copilot) ## 适用范围 - 项目根目录:`D:\wms` -- 主要文档目录:`methods/`、`docs/` +- 主要文档目录:`methods/` - 常用文档文件:`AI_TOOLBOX.md`、`AI_METHOD_ROUTING.md`、`README.md` ## 何时必须使用本 Agent @@ -37,7 +37,7 @@ model: GPT-5 mini (copilot) - 错误码变化 - 公共请求头变化 - 鉴权方式变化 - - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** + - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** - 明确禁止直接手动编辑或提交 `methods/*.json` 与 `methods/changes/*.json` 文件。 - 任何 PR 中直接修改这类文件的变更将被视为违规并可能被退回。所有对 methods JSON 的写入必须通过脚本完成,命令为 `npm run doc:api:update -- --spec=`(不可绕过)。 - 正式写入前**必须**先执行 `npm run doc:api:update -- --spec= --dry-run` 进行验证;dry-run 不做写入,仅输出差异和校验结果。 diff --git a/SequelizeMeta.sql b/SequelizeMeta.sql new file mode 100644 index 0000000..ecc8b54 --- /dev/null +++ b/SequelizeMeta.sql @@ -0,0 +1,2755 @@ +/* + Navicat MySQL Data Transfer + + Source Server : wms + Source Server Type : MySQL + Source Server Version : 50744 + Source Host : 112.124.21.102:3306 + Source Schema : wms + + Target Server Type : MySQL + Target Server Version : 50744 + File Encoding : 65001 + + Date: 04/05/2026 22:27:02 +*/ + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- Table structure for SequelizeMeta +-- ---------------------------- +DROP TABLE IF EXISTS `SequelizeMeta`; +CREATE TABLE `SequelizeMeta` ( + `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`name`) USING BTREE, + UNIQUE INDEX `name`(`name`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_account +-- ---------------------------- +DROP TABLE IF EXISTS `wms_account`; +CREATE TABLE `wms_account` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号ID', + `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名', + `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号', + `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '邮箱', + `password_hash` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '密码哈希', + `real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '真实姓名', + `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '状态:0-封号,1-启用', + `last_login_at` datetime(0) NULL DEFAULT NULL COMMENT '最后登录时间', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `salt` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码盐', + `deleted_at` datetime(0) NULL DEFAULT NULL, + `last_login_ip` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_username`(`username`) USING BTREE, + INDEX `idx_phone`(`phone`) USING BTREE, + INDEX `idx_email`(`email`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 42 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '平台账号表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_account_platform_active +-- ---------------------------- +DROP TABLE IF EXISTS `wms_account_platform_active`; +CREATE TABLE `wms_account_platform_active` ( + `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '账号ID', + `employee_id` bigint(20) UNSIGNED NOT NULL COMMENT '账号仓库角色关联ID', + `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台编码(web、pda、mini、app等)', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + UNIQUE INDEX `uk_account_platform`(`account_id`, `platform_code`) USING BTREE, + UNIQUE INDEX `uk_account_store_role_platform`(`employee_id`, `platform_code`) USING BTREE, + INDEX `idx_account_id`(`account_id`) USING BTREE, + INDEX `idx_platform_code`(`platform_code`) USING BTREE, + INDEX `idx_account_store_role_id`(`employee_id`) USING BTREE, + CONSTRAINT `fk_apa_account` FOREIGN KEY (`account_id`) REFERENCES `wms_account` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT, + CONSTRAINT `fk_apa_account_store_role` FOREIGN KEY (`employee_id`) REFERENCES `wms_account_store_employee` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '账号平台激活状态表(无主键,使用组合唯一索引)' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_account_store_employee +-- ---------------------------- +DROP TABLE IF EXISTS `wms_account_store_employee`; +CREATE TABLE `wms_account_store_employee` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '关联ID', + `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '账号ID', + `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态:0-已解除,1-有效', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '工号的真实姓名', + `deleted_at` datetime(0) NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_account_warehouse_role`(`account_id`, `store_id`) USING BTREE, + INDEX `idx_account_id`(`account_id`) USING BTREE, + INDEX `idx_warehouse_id`(`store_id`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE, + CONSTRAINT `fk_wms_awr_account` FOREIGN KEY (`account_id`) REFERENCES `wms_account` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT, + CONSTRAINT `fk_wms_awr_store` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 76 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '账号仓库角色关联表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_api_app +-- ---------------------------- +DROP TABLE IF EXISTS `wms_api_app`; +CREATE TABLE `wms_api_app` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '应用ID', + `app_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '应用名称', + `interface_type_id` int(10) UNSIGNED NOT NULL COMMENT '接口类型ID', + `contract_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '合约ID,关联wms_store_warehouse.id(货主接口使用)', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID(仓库接口使用)', + `self_app_key` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '自身AppKey(开放接口使用,系统生成)', + `self_app_secret` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '自身AppSecret(开放接口使用,系统生成)', + `self_ip_whitelist` json NULL COMMENT '自身IP白名单', + `callback_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'API回调通知URL', + `qimen_app_key` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门对方AppKey', + `qimen_customer_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门客户ID', + `qimen_warehouse_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门仓库编码', + `api_version` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '1.0' COMMENT 'API版本', + `sign_method` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'md5' COMMENT '签名方法', + `rate_limit` int(11) NULL DEFAULT 1000 COMMENT '速率限制(次/分钟)', + `timeout_seconds` int(11) NULL DEFAULT 30 COMMENT '超时时间(秒)', + `contact_person` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系人', + `contact_phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系电话', + `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '邮箱', + `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `deleted_at` timestamp(0) NULL DEFAULT NULL COMMENT '删除时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_app_name_interface`(`app_name`, `interface_type_id`) USING BTREE, + UNIQUE INDEX `uk_self_app_key`(`self_app_key`) USING BTREE, + UNIQUE INDEX `uk_interface_warehouse`(`qimen_app_key`, `qimen_customer_id`) USING BTREE, + INDEX `fk_wms_api_app_contract`(`contract_id`) USING BTREE, + INDEX `uk_interface_contract`(`interface_type_id`, `contract_id`) USING BTREE, + CONSTRAINT `fk_wms_api_app_contract` FOREIGN KEY (`contract_id`) REFERENCES `wms_store_warehouse` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, + CONSTRAINT `wms_api_app_ibfk_1` FOREIGN KEY (`interface_type_id`) REFERENCES `wms_interface_type` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 21 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'API应用表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_embargo_policies +-- ---------------------------- +DROP TABLE IF EXISTS `wms_embargo_policies`; +CREATE TABLE `wms_embargo_policies` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `policy_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '策略名称', + `status` enum('ACTIVE','INACTIVE','PENDING','EXPIRED') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'PENDING' COMMENT '状态', + `embargo_scope` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '禁运范围(数组)', + `start_date` date NOT NULL COMMENT '生效开始日期', + `end_date` date NULL DEFAULT NULL COMMENT '结束日期', + `is_permanent` tinyint(1) NULL DEFAULT 0 COMMENT '是否永久有效', + `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '策略描述', + `created_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人', + `updated_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '更新人', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0), + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE, + INDEX `idx_dates`(`start_date`, `end_date`) USING BTREE, + INDEX `idx_created_at`(`created_at`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + CONSTRAINT `wms_embargo_policies_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '禁运策略主表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_employee_role +-- ---------------------------- +DROP TABLE IF EXISTS `wms_employee_role`; +CREATE TABLE `wms_employee_role` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `employee_id` bigint(20) UNSIGNED NOT NULL, + `role_id` bigint(20) UNSIGNED NOT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_employee_role`(`employee_id`, `role_id`) USING BTREE, + INDEX `idx_employee_id`(`employee_id`) USING BTREE, + INDEX `role_id`(`role_id`) USING BTREE, + CONSTRAINT `wms_employee_role_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `wms_account_store_employee` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `wms_employee_role_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `wms_role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB AUTO_INCREMENT = 163 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_entry_items +-- ---------------------------- +DROP TABLE IF EXISTS `wms_entry_items`; +CREATE TABLE `wms_entry_items` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `order_id` bigint(20) UNSIGNED NOT NULL, + `out_biz_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `order_line_no` bigint(20) UNSIGNED NULL DEFAULT NULL, + `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `item_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `count` int(12) NULL DEFAULT NULL, + `inventory_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `stock_id` bigint(20) NULL DEFAULT NULL, + `received_quantity` int(12) NOT NULL DEFAULT 0 COMMENT '已收货数量', + `confirm_quantity` int(12) NULL DEFAULT NULL COMMENT '已提交数量', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `order_id`(`order_id`, `order_line_no`) USING BTREE, + INDEX `stock_id`(`stock_id`) USING BTREE, + CONSTRAINT `wms_entry_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `wms_entry_order` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT `wms_entry_items_ibfk_2` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 281 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_entry_order +-- ---------------------------- +DROP TABLE IF EXISTS `wms_entry_order`; +CREATE TABLE `wms_entry_order` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '入库单ID', + `entry_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '入库单号', + `order_type` enum('SCRK','LYRK','CCRK','CGRK','DBRK','QTRK','B2BRK','XNRK') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务类型', + `purchase_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '采购单号', + `total_order_lines` int(11) NULL DEFAULT 0 COMMENT '单据总行数', + `order_create_time` datetime(0) NULL DEFAULT NULL COMMENT '订单创建时间', + `expect_start_time` datetime(0) NULL DEFAULT NULL COMMENT '预期到货时间', + `expect_end_time` datetime(0) NULL DEFAULT NULL COMMENT '最迟预期到货时间', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '运单号', + `supplier_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '供应商编码', + `supplier_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '供应商名称', + `source_type` enum('WMS','API','QM') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'API' COMMENT '来源类型', + `order_status` enum('PENDING','CONFIRMED','PARTIAL_RECEIVED','COMPLETED','CANCELLED','CREATED','CREATING') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'PENDING' COMMENT '订单状态', + `sync_status` enum('PENDING','SUCCESS','FAILED') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'PENDING' COMMENT '同步状态', + `sync_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '同步返回信息', + `is_enabled` tinyint(1) NULL DEFAULT 1 COMMENT '是否启用', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库id', + `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主id', + `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'ERP备注', + `store_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货主名称快照', + `warehouse_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '仓库名称快照', + `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `qimen_owner_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门货主code', + `qimen_warehouse_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '奇门仓库code', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_entry_order_code`(`entry_order_code`, `warehouse_id`, `store_id`) USING BTREE, + INDEX `idx_order_type`(`order_type`) USING BTREE, + INDEX `idx_order_status`(`order_status`) USING BTREE, + INDEX `idx_sync_status`(`sync_status`) USING BTREE, + INDEX `idx_source`(`source_type`) USING BTREE, + INDEX `idx_create_time`(`order_create_time`) USING BTREE, + INDEX `wms_entry_order_ibfk_2`(`store_id`) USING BTREE, + INDEX `wms_entry_order_ibfk_1`(`warehouse_id`) USING BTREE, + INDEX `id`(`id`, `warehouse_id`, `store_id`) USING BTREE, + CONSTRAINT `wms_entry_order_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `wms_entry_order_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 217 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '入库单主表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_express +-- ---------------------------- +DROP TABLE IF EXISTS `wms_express`; +CREATE TABLE `wms_express` ( + `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `KS` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `polyapi_extra_info` json NULL, + `PDD` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `DYXD` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `polyapi_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '聚合接口代码', + PRIMARY KEY (`code`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_express_interface +-- ---------------------------- +DROP TABLE IF EXISTS `wms_express_interface`; +CREATE TABLE `wms_express_interface` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '接口名称', + `express_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '快递编码', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库编码', + `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台编码', + `sender_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人', + `sender_tel` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件电话', + `weight` int(11) NULL DEFAULT NULL COMMENT '排序', + `token` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '令牌', + `viewer` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '验视员', + `client_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '客户id', + `is_share` tinyint(1) NULL DEFAULT 0 COMMENT '是否分享接口', + `share_id` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '分享id', + `can_use_count` int(11) NULL DEFAULT 0 COMMENT '可用数量', + `province_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人省份', + `city_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人城市', + `district_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人区/县', + `town_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人镇', + `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '寄件人地址', + `site_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '网点编码', + `product_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '产品编码', + `shop_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '平台店铺', + `sys_express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '系统快递编码', + `weight_type` int(10) NOT NULL DEFAULT 0 COMMENT '重量类型', + `ispickup` int(11) NULL DEFAULT 0, + `shipperno` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '月结卡号', + PRIMARY KEY (`id`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `sys_express_code`(`sys_express_code`) USING BTREE, + INDEX `platform_code`(`platform_code`) USING BTREE, + CONSTRAINT `wms_express_interface_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT `wms_express_interface_ibfk_2` FOREIGN KEY (`sys_express_code`) REFERENCES `wms_express` (`code`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_express_interface_ibfk_3` FOREIGN KEY (`platform_code`) REFERENCES `wms_platform` (`code`) ON DELETE RESTRICT ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_express_print_record +-- ---------------------------- +DROP TABLE IF EXISTS `wms_express_print_record`; +CREATE TABLE `wms_express_print_record` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `express_id` bigint(20) NOT NULL COMMENT '快递记录ID(关联order_express表)', + `order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '订单ID', + `express_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '快递单号', + `platform` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '电商平台', + `template_id` bigint(20) NOT NULL COMMENT '使用的模板ID', + `template_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '模板URL(冗余存储)', + `printer_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印机名称', + `printer_config_id` bigint(20) NULL DEFAULT NULL COMMENT '打印机配置ID', + `print_data` json NOT NULL COMMENT '打印数据(JSON格式)', + `encrypted_data` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '加密数据', + `signature` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '签名', + `add_data` json NULL COMMENT '附加数据(如寄件人信息)', + `custom_data` json NULL COMMENT '自定义数据(商品信息等)', + `print_status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'PENDING' COMMENT '打印状态:PENDING-待打印,PRINTING-打印中,SUCCESS-打印成功,FAILED-打印失败,RETRY-重试中', + `print_count` int(11) NULL DEFAULT 0 COMMENT '打印次数', + `last_print_time` datetime(0) NULL DEFAULT NULL COMMENT '最后一次打印时间', + `next_retry_time` datetime(0) NULL DEFAULT NULL COMMENT '下次重试时间', + `request_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印请求ID', + `document_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '文档ID', + `batch_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印批次号', + `print_result` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '打印结果(成功/失败信息)', + `error_message` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '错误信息', + `print_cost_time` int(11) NULL DEFAULT NULL COMMENT '打印耗时(毫秒)', + `create_interface` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建接口', + `print_interface` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印接口', + `operator_id` bigint(20) NULL DEFAULT NULL COMMENT '操作员ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `print_time` datetime(0) NULL DEFAULT NULL COMMENT '实际打印时间', + `update_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_express_print`(`express_id`, `print_status`) USING BTREE, + UNIQUE INDEX `uk_request_id`(`request_id`) USING BTREE, + INDEX `idx_order_id`(`order_id`) USING BTREE, + INDEX `idx_express_no`(`express_no`) USING BTREE, + INDEX `idx_platform`(`platform`) USING BTREE, + INDEX `idx_print_status`(`print_status`) USING BTREE, + INDEX `idx_create_time`(`create_time`) USING BTREE, + INDEX `idx_batch_no`(`batch_no`) USING BTREE, + INDEX `idx_template_id`(`template_id`) USING BTREE, + INDEX `idx_printer_config_id`(`printer_config_id`) USING BTREE, + INDEX `idx_print_time`(`print_time`) USING BTREE, + INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '快递打印记录表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_express_product_type +-- ---------------------------- +DROP TABLE IF EXISTS `wms_express_product_type`; +CREATE TABLE `wms_express_product_type` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '产品名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流编码', + `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '产品编码', + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 25 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_express_setting +-- ---------------------------- +DROP TABLE IF EXISTS `wms_express_setting`; +CREATE TABLE `wms_express_setting` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '系统快递编码', + `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '自设编码', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库id', + `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '别名', + `deleted_at` datetime(0) NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `platform_code`(`express_code`, `warehouse_id`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_warehouse_deleted_at`(`warehouse_id`, `deleted_at`) USING BTREE, + CONSTRAINT `wms_express_setting_ibfk_1` FOREIGN KEY (`express_code`) REFERENCES `wms_express` (`code`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_express_setting_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_fast_where +-- ---------------------------- +DROP TABLE IF EXISTS `wms_fast_where`; +CREATE TABLE `wms_fast_where` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `label` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '条件/组名称', + `value` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '查询条件,json需要序列化', + `pid` int(11) NULL DEFAULT NULL COMMENT '父级id,方便树结构', + `icon` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'icon编码', + `type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '查询类别', + `created_at` datetime(0) NULL DEFAULT NULL, + `updated_at` datetime(0) NULL DEFAULT NULL, + `deleted_at` datetime(0) NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 39 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_file +-- ---------------------------- +DROP TABLE IF EXISTS `wms_file`; +CREATE TABLE `wms_file` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '文件唯一ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID(核心统计维度)', + `file_key` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '存储路径/对象键(如cos/2024/03/file.jpg)', + `file_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '完整访问URL', + `file_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '原始文件名', + `file_size` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件大小(字节)', + `file_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '文件类型:inventory_image, delivery_note, inspection_video', + `mime_type` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT 'MIME类型', + `md5_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '文件MD5(去重依据)', + `sha1_hash` char(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '文件SHA1(二次校验)', + `storage_mode` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'cos' COMMENT '存储方式:cos/oss/local', + `storage_class` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'standard' COMMENT '存储级别:standard/ia/archive', + `uploader_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '上传者ID(用户ID/员工工号)', + `uploader_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '上传者姓名(快照)', + `uploader_dept` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '上传者部门(快照)', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `is_deleted` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT '软删除标记', + `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `deleted_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '删除操作人', + `expire_time` datetime(0) NULL DEFAULT NULL COMMENT '过期时间,Null为永不过期', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_file_key`(`file_key`) USING BTREE COMMENT '存储路径唯一', + UNIQUE INDEX `uk_md5_hash`(`md5_hash`, `warehouse_id`) USING BTREE COMMENT '文件内容去重', + INDEX `idx_warehouse`(`warehouse_id`) USING BTREE COMMENT '仓库维度查询', + INDEX `idx_uploader`(`uploader_id`) USING BTREE COMMENT '上传者查询', + INDEX `idx_created`(`created_at`) USING BTREE COMMENT '时间范围查询', + INDEX `idx_type_warehouse`(`file_type`, `warehouse_id`) USING BTREE COMMENT '业务类型统计', + INDEX `idx_warehouse_file_size`(`warehouse_id`, `file_size`) USING BTREE, + CONSTRAINT `wms_file_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 115111 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS文件资源中枢表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_file_reference +-- ---------------------------- +DROP TABLE IF EXISTS `wms_file_reference`; +CREATE TABLE `wms_file_reference` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `file_id` bigint(20) UNSIGNED NOT NULL COMMENT '文件ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID(冗余,优化查询)', + `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务类型:sku_image/packing_list/inspection_report', + `business_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务ID(如SKU编码、出库单号)', + `display_order` smallint(5) UNSIGNED NULL DEFAULT 0 COMMENT '显示顺序', + `created_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '关联创建者', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_business_file`(`business_type`, `business_id`, `file_id`) USING BTREE, + INDEX `idx_file_id`(`file_id`) USING BTREE COMMENT '文件反查业务', + INDEX `idx_warehouse_business`(`warehouse_id`, `business_type`) USING BTREE COMMENT '业务维度查询', + INDEX `idx_business`(`business_id`) USING BTREE COMMENT '业务ID查询', + CONSTRAINT `fk_reference_file` FOREIGN KEY (`file_id`) REFERENCES `wms_file` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, + CONSTRAINT `wms_file_reference_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 97042 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS文件业务关联表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_i18n_keys +-- ---------------------------- +DROP TABLE IF EXISTS `wms_i18n_keys`; +CREATE TABLE `wms_i18n_keys` ( + `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, + `key_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '国际化键名(英文)', + `project` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'wms' COMMENT '项目标识', + `module` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '模块: inventory/order/shipment/user', + `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '键值描述', + `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态: 1-启用 0-禁用', + `created_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人', + `updated_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新人', + `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), + `updated_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_wms_key_project`(`key_name`, `project`) USING BTREE, + INDEX `idx_wms_project_module`(`project`, `module`) USING BTREE, + INDEX `idx_wms_status`(`status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 261 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'WMS国际化键值表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_i18n_translations +-- ---------------------------- +DROP TABLE IF EXISTS `wms_i18n_translations`; +CREATE TABLE `wms_i18n_translations` ( + `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, + `key_id` int(10) UNSIGNED NOT NULL COMMENT '键ID', + `language` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '语言代码', + `translation` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '翻译内容,NULL表示未翻译', + `translation_status` tinyint(4) NOT NULL DEFAULT 0 COMMENT '0-未翻译 1-待审核 2-已审核', + `auto_generated` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否自动生成: 0-手动 1-自动', + `translator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '翻译人员/系统', + `reviewed_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '审核人', + `reviewed_at` timestamp(0) NULL DEFAULT NULL COMMENT '审核时间', + `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0), + `updated_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_wms_key_language`(`key_id`, `language`) USING BTREE, + INDEX `idx_wms_key_id`(`key_id`) USING BTREE, + INDEX `idx_wms_language_status`(`language`, `translation_status`) USING BTREE, + INDEX `idx_wms_auto_generated`(`auto_generated`) USING BTREE, + CONSTRAINT `fk_wms_translation_key` FOREIGN KEY (`key_id`) REFERENCES `wms_i18n_keys` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 890 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'WMS国际化翻译表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_interface_type +-- ---------------------------- +DROP TABLE IF EXISTS `wms_interface_type`; +CREATE TABLE `wms_interface_type` ( + `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '接口类型ID', + `interface_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '接口编码,唯一标识', + `interface_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '接口名称', + `interface_category` enum('QM_WMS','OPEN_API') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '接口类别:QM_WMS-奇门仓储, OPEN_API-开放接口', + `entry_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '入口链接', + `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '接口描述', + `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `is_store` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否是货主的接口', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_interface_code`(`interface_code`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '接口类型表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_location_space +-- ---------------------------- +DROP TABLE IF EXISTS `wms_location_space`; +CREATE TABLE `wms_location_space` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '仓位ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `zone_id` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '所属分区ID', + `location_type_id` int(10) UNSIGNED NOT NULL COMMENT '仓位类型ID', + `space_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '仓位编码', + `custom_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '自定义名称', + `custom_barcode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '自定义条码', + `row_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '排号', + `column_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '列号', + `level_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '层号', + `cell_no` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '格号', + `length` decimal(8, 2) NULL DEFAULT NULL COMMENT '长度(cm)', + `width` decimal(8, 2) NULL DEFAULT NULL COMMENT '宽度(cm)', + `height` decimal(8, 2) NULL DEFAULT NULL COMMENT '高度(cm)', + `volume` decimal(10, 2) NULL DEFAULT NULL COMMENT '体积(m³)', + `max_weight` decimal(10, 2) NULL DEFAULT NULL COMMENT '最大承重(kg)', + `space_status` enum('AVAILABLE','OCCUPIED','RESERVED','MAINTENANCE','DISABLED') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'AVAILABLE' COMMENT '仓位状态', + `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', + `current_sku_count` int(11) NULL DEFAULT 0 COMMENT '当前SKU种类数', + `current_quantity` int(11) NULL DEFAULT 0 COMMENT '当前库存数量', + `current_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '当前重量(kg)', + `current_volume` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '当前体积(m³)', + `created_by` bigint(20) NULL DEFAULT NULL COMMENT '创建人', + `updated_by` bigint(20) NULL DEFAULT NULL COMMENT '更新人', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0), + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), + `deleted_at` datetime(0) NULL DEFAULT NULL, + `pick_sequence` int(10) NULL DEFAULT NULL COMMENT '拣货顺序', + `pick_zone_id` int(10) NULL DEFAULT NULL COMMENT '所属拣货分区ID', + `is_preferred_pick` tinyint(1) NULL DEFAULT 0 COMMENT '是否优先拣货位', + `distance_from_start` int(11) NULL DEFAULT NULL COMMENT '距起始点距离(mm)', + `pick_time_estimate` int(11) NULL DEFAULT 0 COMMENT '预估拣货时间(秒)', + `pick_priority` tinyint(3) NULL DEFAULT 50 COMMENT '拣货优先级(1-100)', + `last_picked_at` datetime(0) NULL DEFAULT NULL COMMENT '最后拣货时间', + `pick_count` int(11) NULL DEFAULT 0 COMMENT '拣货次数', + `relative_x` decimal(8, 2) NULL DEFAULT NULL COMMENT '在货架内的X坐标(cm)', + `relative_y` decimal(8, 2) NULL DEFAULT NULL COMMENT '在货架内的Y坐标(cm)', + `relative_z` decimal(8, 2) NULL DEFAULT NULL COMMENT '在货架内的Z坐标(cm)', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_warehouse_space_code`(`warehouse_id`, `space_code`, `deleted_at`) USING BTREE, + UNIQUE INDEX `uk_custom_barcode`(`custom_barcode`, `warehouse_id`, `deleted_at`) USING BTREE, + INDEX `idx_warehouse_zone`(`warehouse_id`, `zone_id`) USING BTREE, + INDEX `idx_location_type`(`location_type_id`) USING BTREE, + INDEX `idx_space_status`(`space_status`) USING BTREE, + INDEX `idx_is_enabled`(`is_enabled`) USING BTREE, + INDEX `idx_row_column_level`(`row_no`, `column_no`, `level_no`) USING BTREE, + INDEX `fk_location_space_zone`(`zone_id`) USING BTREE, + INDEX `idx_pick_sequence`(`warehouse_id`, `pick_sequence`, `space_status`) USING BTREE, + INDEX `idx_pick_priority`(`pick_priority`, `space_status`) USING BTREE, + INDEX `idx_last_picked`(`last_picked_at`) USING BTREE, + INDEX `idx_pick_zone`(`pick_zone_id`) USING BTREE, + CONSTRAINT `fk_location_space_type` FOREIGN KEY (`location_type_id`) REFERENCES `wms_location_type` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, + CONSTRAINT `fk_location_space_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 26885 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓位格子表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_location_type +-- ---------------------------- +DROP TABLE IF EXISTS `wms_location_type`; +CREATE TABLE `wms_location_type` ( + `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '类型ID', + `type_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '类型编码', + `type_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '类型名称', + `temperature_zone` enum('NORMAL','COLD','FROZEN','DANGEROUS') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'NORMAL' COMMENT '温区', + `is_active` tinyint(1) NOT NULL DEFAULT 1, + `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0), + `allow_allocation` tinyint(1) NULL DEFAULT NULL COMMENT '是否允许分配储位', + `allow_transfer_out` tinyint(1) NULL DEFAULT NULL COMMENT '是否允许移出', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_type_code`(`type_code`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + CONSTRAINT `wms_location_type_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '库位类型表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_location_zone +-- ---------------------------- +DROP TABLE IF EXISTS `wms_location_zone`; +CREATE TABLE `wms_location_zone` ( + `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '分区ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `zone_code` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分区编码(最多5位字母或数字)', + `zone_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '分区名称', + `zone_type` enum('warehouse','area','rack','pick_start') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '分区类型:warehouse-仓库, area-库区, rack-货架, pick_start-起始拣货点', + `parent_id` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '父分区ID', + `is_active` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', + `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '软删除时间', + `x` int(11) NOT NULL COMMENT '左下角x坐标(mm)', + `y` int(11) NOT NULL COMMENT '左下角y坐标(mm)', + `z` int(11) NOT NULL COMMENT '左下角z坐标(mm)', + `length` int(11) NOT NULL COMMENT '长度(mm)', + `width` int(11) NOT NULL COMMENT '宽度(mm)', + `height` int(11) NOT NULL COMMENT '高度(mm)', + `rack_columns` tinyint(3) UNSIGNED NULL DEFAULT 1 COMMENT '货架列数(1-255)', + `rack_rows` tinyint(3) UNSIGNED NULL DEFAULT NULL COMMENT '货架层数', + `rack_levels` tinyint(3) UNSIGNED NULL DEFAULT NULL COMMENT '货架分格数', + `direction` enum('north','south','east','west') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货架朝向', + `color` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '#3B82F6' COMMENT '显示颜色,#RRGGBB格式', + `cell_width` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '货架的长度', + `cell_height` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '货架的高度', + `cell_length` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '货架的深度', + `path_sequence` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '拣货路径排序序号', + `pick_distance` int(11) NULL DEFAULT NULL COMMENT '距离起始点的拣货距离(mm)', + `neighbor_zone_ids` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '相邻分区ID列表(JSON数组,用于路径规划)', + `is_passable` tinyint(1) NULL DEFAULT 1 COMMENT '是否可通行(用于障碍物标记)', + `zone_category` enum('storage','operational','obstacle') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'storage' COMMENT '区域分类:storage-存储区, operational-操作区, obstacle-障碍区', + `aisles` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货架的第几列设置为通道', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_warehouse_zone_code`(`warehouse_id`, `zone_code`, `deleted_at`) USING BTREE, + INDEX `idx_warehouse_parent`(`warehouse_id`, `parent_id`) USING BTREE, + INDEX `idx_deleted_at`(`deleted_at`) USING BTREE, + INDEX `idx_zone_type`(`zone_type`) USING BTREE, + INDEX `idx_is_active`(`is_active`) USING BTREE, + INDEX `fk_location_zone_parent`(`parent_id`) USING BTREE, + INDEX `idx_path_sequence`(`warehouse_id`, `path_sequence`, `is_active`) USING BTREE, + INDEX `idx_zone_category`(`zone_category`) USING BTREE, + INDEX `idx_pick_distance`(`warehouse_id`, `pick_distance`) USING BTREE, + CONSTRAINT `fk_location_zone_parent` FOREIGN KEY (`parent_id`) REFERENCES `wms_location_zone` (`id`) ON DELETE SET NULL ON UPDATE RESTRICT, + CONSTRAINT `fk_location_zone_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 158 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '库位分区表(支持软删除)' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_notification_send_log +-- ---------------------------- +DROP TABLE IF EXISTS `wms_notification_send_log`; +CREATE TABLE `wms_notification_send_log` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `trace_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '通知追踪ID', + `webhook_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT 'Webhook 配置ID', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '触发主体ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `owner_store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `business_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '业务名称', + `event` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '事件名', + `hook_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'Webhook 类型', + `hook_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'Webhook 地址', + `request_payload` json NULL COMMENT '请求载荷', + `response_payload` json NULL COMMENT '返回载荷', + `http_status` int(11) NULL DEFAULT NULL COMMENT 'HTTP 状态码', + `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'failed' COMMENT '发送状态', + `error_message` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '失败原因', + `retry_count` int(11) NOT NULL DEFAULT 0 COMMENT '重试次数', + `created_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '创建人', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_notification_send_log_trace_id`(`trace_id`) USING BTREE, + INDEX `idx_notification_send_log_event_status`(`event`, `status`) USING BTREE, + INDEX `idx_notification_send_log_webhook_id`(`webhook_id`) USING BTREE, + INDEX `idx_notification_send_log_created_at`(`created_at`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '统一通知发送失败日志表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_notification_webhook +-- ---------------------------- +DROP TABLE IF EXISTS `wms_notification_webhook`; +CREATE TABLE `wms_notification_webhook` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '主体ID,对应 wms_store.id', + `hook_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'Webhook 名称', + `hook_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Webhook 类型,用于分派不同消息结构处理类,如 dingtalk、wecom、feishu、custom', + `hook_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Webhook 链接地址', + `events` json NULL COMMENT '订阅事件列表', + `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用', + `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注', + `created_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '创建人', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_notification_webhook_store_type_url`(`store_id`, `hook_type`, `hook_url`) USING BTREE, + INDEX `idx_notification_webhook_store_id`(`store_id`) USING BTREE, + INDEX `idx_notification_webhook_hook_type`(`hook_type`) USING BTREE, + INDEX `idx_notification_webhook_status`(`status`) USING BTREE, + INDEX `idx_notification_webhook_store_type`(`store_id`, `hook_type`) USING BTREE, + CONSTRAINT `wms_notification_webhook_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '外部通知 WebHook 配置表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_operation_log +-- ---------------------------- +DROP TABLE IF EXISTS `wms_operation_log`; +CREATE TABLE `wms_operation_log` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '业务类型: product, order, stock, wave, express,storage', + `business_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '业务ID', + `operation_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '操作编码', + `operator_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人ID(用户ID/系统ID)', + `operator_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人名称', + `external_log_type` enum('REQUEST','API','QIMEN','NONE') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'NONE' COMMENT '外部日志类型', + `external_log_id` bigint(20) NULL DEFAULT NULL COMMENT '外部日志ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `before_changes` json NULL COMMENT '关键变更字段', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `platform_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作平台', + `message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '写入的消息', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_business_operation`(`business_type`, `business_id`, `id`) USING BTREE, + INDEX `idx_business_type_id_time`(`business_type`, `business_id`, `created_at`) USING BTREE, + INDEX `idx_operation_code_time`(`operation_code`, `created_at`) USING BTREE, + INDEX `idx_operator_time`(`operator_id`, `created_at`) USING BTREE, + INDEX `idx_warehouse_time`(`warehouse_id`, `created_at`) USING BTREE, + INDEX `idx_external_log`(`external_log_type`, `external_log_id`) USING BTREE, + INDEX `idx_created_at`(`created_at`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 495311 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'WMS业务操作日志表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery`; +CREATE TABLE `wms_order_delivery` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `create_at` datetime(0) NULL DEFAULT NULL, + `delete_at` datetime(0) NULL DEFAULT NULL, + `updated_at` datetime(0) NULL DEFAULT NULL, + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','intercepting','intercepted') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'pedding', + `name` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET ujis COLLATE ujis_japanese_ci NULL DEFAULT '' COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `id_number` int(11) NULL DEFAULT NULL, + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '拦截状态机', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `delivery_order_code`(`delivery_order_code`, `warehouse_id`) USING BTREE, + INDEX `store_id`(`store_id`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + CONSTRAINT `wms_order_delivery_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_order_delivery_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_100000 +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_100000`; +CREATE TABLE `wms_order_delivery_100000` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_100000_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_current_store_id`(`store_id`) USING BTREE, + INDEX `idx_100000_current_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_100000_current_items`(`items`(50)) USING BTREE, + INDEX `idx_100000_current_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_100000_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_current_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_100000_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 120874 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单常用表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_100000_dispatch +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_100000_dispatch`; +CREATE TABLE `wms_order_delivery_100000_dispatch` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `dispatch_lane` enum('m4','m5') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_100000_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_current_store_id`(`store_id`) USING BTREE, + INDEX `idx_100000_current_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_dispatch_100000_dispatch_lane`(`dispatch_lane`, `status`) USING BTREE, + INDEX `idx_100000_current_items`(`items`(50)) USING BTREE, + INDEX `idx_100000_current_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_100000_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_current_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_100000_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 120067 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单配送域(M4/M5)影子表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_100000_history +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_100000_history`; +CREATE TABLE `wms_order_delivery_100000_history` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `archive_time` datetime(0) NULL DEFAULT NULL COMMENT '归档时间', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_100000_history_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_history_store_id`(`store_id`) USING BTREE, + INDEX `idx_100000_history_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_100000_history_items`(`items`(50)) USING BTREE, + INDEX `idx_100000_history_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_100000_history_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_history_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_100000_history_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE, + INDEX `idx_100000_history_archive_time`(`archive_time`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单历史表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_100000_outsourced +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_100000_outsourced`; +CREATE TABLE `wms_order_delivery_100000_outsourced` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_100000_outsourced_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_outsourced_store_id`(`store_id`) USING BTREE, + INDEX `idx_100000_outsourced_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_100000_outsourced_items`(`items`(50)) USING BTREE, + INDEX `idx_100000_outsourced_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_100000_outsourced_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_100000_outsourced_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_100000_outsourced_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000发货单外仓表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_1000028 +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_1000028`; +CREATE TABLE `wms_order_delivery_1000028` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_1000028_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_current_store_id`(`store_id`) USING BTREE, + INDEX `idx_1000028_current_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_1000028_current_items`(`items`(50)) USING BTREE, + INDEX `idx_1000028_current_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_1000028_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_current_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_1000028_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单常用表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_1000028_dispatch +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_1000028_dispatch`; +CREATE TABLE `wms_order_delivery_1000028_dispatch` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `dispatch_lane` enum('m4','m5') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'm4' COMMENT '配送工作台子域(M4正常/M5异常)', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '波次号,空字符串表示未分配', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_1000028_current_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_current_store_id`(`store_id`) USING BTREE, + INDEX `idx_1000028_current_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_dispatch_1000028_dispatch_lane`(`dispatch_lane`, `status`) USING BTREE, + INDEX `idx_1000028_current_items`(`items`(50)) USING BTREE, + INDEX `idx_1000028_current_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_1000028_current_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_current_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_1000028_current_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单配送域(M4/M5)影子表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_1000028_history +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_1000028_history`; +CREATE TABLE `wms_order_delivery_1000028_history` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `archive_time` datetime(0) NULL DEFAULT NULL COMMENT '归档时间', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_1000028_history_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_history_store_id`(`store_id`) USING BTREE, + INDEX `idx_1000028_history_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_1000028_history_items`(`items`(50)) USING BTREE, + INDEX `idx_1000028_history_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_1000028_history_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_history_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_1000028_history_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE, + INDEX `idx_1000028_history_archive_time`(`archive_time`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单历史表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_delivery_1000028_outsourced +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_delivery_1000028_outsourced`; +CREATE TABLE `wms_order_delivery_1000028_outsourced` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货单号', + `pre_delivery_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单号', + `pre_delivery_order_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '预发货单ID', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单类型', + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库编码', + `order_flag` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '订单标记', + `source_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台编码', + `source_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '来源平台名称', + `sys_platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台编码', + `sys_platform_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统平台名称', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `updated_at` datetime(0) NULL DEFAULT NULL COMMENT '更新时间', + `place_order_time` datetime(0) NULL DEFAULT NULL COMMENT '店铺创建订单时间', + `pay_time` datetime(0) NULL DEFAULT NULL COMMENT '支付时间', + `pay_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '支付单号', + `service_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '集包服务编码', + `operator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'ERP审核人', + `operate_time` datetime(0) NULL DEFAULT NULL COMMENT 'ERP审核时间', + `delivery_time` datetime(0) NULL DEFAULT NULL COMMENT '发货时间', + `shop_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '店铺名称', + `seller_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '卖家名称', + `buyer_nick` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '买家名称', + `total_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单总金额', + `item_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '商品总金额', + `discount_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '订单折扣金额', + `freight` decimal(18, 2) NULL DEFAULT NULL COMMENT '快递费用', + `ar_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '应收金额', + `got_amount` decimal(18, 2) NULL DEFAULT NULL COMMENT '已收金额', + `service_fee` decimal(18, 2) NULL DEFAULT NULL COMMENT 'COD服务费', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司编码', + `logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '物流公司名称', + `sys_logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司编码', + `sys_logistics_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统物流公司名称', + `express_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '面单号前置', + `logistics_area_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', + `delivery_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '发货服务类型', + `is_urgency` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否紧急', + `invoice_flag` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'N' COMMENT '是否需要发票', + `status` enum('pedding','created','cancel','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'created' COMMENT '订单状态', + `name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人姓名', + `zip_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '收件人邮编', + `tel` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人电话', + `mobile` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人移动电话', + `email` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '收件人邮箱', + `country_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '国家编码', + `province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '省份', + `city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '城市', + `area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '区', + `town` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '镇', + `detail_address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '详细地址', + `id_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '证件类型', + `id_number` int(11) NULL DEFAULT NULL COMMENT '证件号码', + `oaid` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT 'OAID', + `sync_status` enum('padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'padding' COMMENT '同步状态', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID', + `from_key` int(11) NULL DEFAULT NULL COMMENT '来源键', + `items` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '商品JSON字符串', + `items_count` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品种类数', + `items_total` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '商品总数', + `items_weight` decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)', + `items_hash` char(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'MD5哈希值(32位)', + `items_crc` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'CRC32校验码', + `wave_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '波次ID,0表示未分配', + `post_status` enum('padding','fin','timeout','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配快递号状态机', + `storage_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '分配储位状态机', + `pick_status` enum('padding','fin','error','none') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拣货状态机', + `pack_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打包状态机', + `inspection_status` enum('none','padding','running','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '检验状态机', + `step` int(10) NOT NULL DEFAULT 0 COMMENT '订单步骤:0未审核,1已审核,2处理中,3驳回/异常,4配送中,5已完成,9已关闭', + `print_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '打印状态机', + `claim_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '领取状态机', + `outbound_status` enum('none','padding','fin','timeout','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '出库状态机', + `lock_status` enum('none','warehouse','store') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '锁定状态机', + `intercept_status` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '拦截状态机', + `source_order_codes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '来源订单号集合', + `weight_type` int(11) NOT NULL DEFAULT 0 COMMENT '重量类型:0常规、1轻货、2重货、3冷链', + `sended_status` enum('none','padding','fin','error') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'none' COMMENT '发货状态机', + `create_channel` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'MANUAL' COMMENT '创建来源渠道', + `basket_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '筐号', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_1000028_outsourced_delivery_code`(`delivery_order_code`, `store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_outsourced_store_id`(`store_id`) USING BTREE, + INDEX `idx_1000028_outsourced_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_1000028_outsourced_items`(`items`(50)) USING BTREE, + INDEX `idx_1000028_outsourced_items_hash`(`items_hash`) USING BTREE, + INDEX `idx_1000028_outsourced_hash_crc`(`items_hash`, `items_crc`, `warehouse_id`) USING BTREE, + INDEX `idx_1000028_outsourced_wave`(`status`, `wave_id`) USING BTREE, + INDEX `idx_1000028_outsourced_statuses`(`status`, `post_status`, `pick_status`, `pack_status`, `outbound_status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028发货单外仓表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_express +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_express`; +CREATE TABLE `wms_order_express` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `waybill_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '运单号', + `order_id` bigint(20) NULL DEFAULT NULL COMMENT '订单id', + `create_at` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '软删除时间', + `is_galaxy_receive` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否已揽收', + `is_back` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否退回收到', + `is_intercept` enum('Y','N') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否已拦截', + `logistics_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递编码', + `logistics_interface_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '使用的快递接口id', + `logistics_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递名称', + `logistics_interface_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '使用的快递接口名称', + `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '平台编码', + `business_key` int(3) NULL DEFAULT NULL COMMENT '业务编码', + `status` bigint(20) UNSIGNED NULL DEFAULT 0 COMMENT '状态0-已冻结新建,1-已完成创建,大于1为回收时间戳', + `retry_count` tinyint(3) NULL DEFAULT NULL COMMENT '重试次数', + `printinfo` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `signature` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `encryptprintinfo` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `encryptedtoken` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `order_id`(`order_id`, `business_key`, `status`, `warehouse_id`) USING BTREE, + INDEX `waybill_code`(`waybill_code`) USING BTREE, + INDEX `create_at`(`create_at`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + CONSTRAINT `wms_order_express_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 156 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_express_print_data +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_express_print_data`; +CREATE TABLE `wms_order_express_print_data` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `express_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `data` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `create_at` datetime(0) NULL DEFAULT NULL, + `delete_at` datetime(0) NULL DEFAULT NULL, + `update_at` datetime(0) NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `express_id`(`express_id`) USING BTREE, + CONSTRAINT `wms_order_express_print_data_ibfk_1` FOREIGN KEY (`express_id`) REFERENCES `wms_order_express` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_items +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_items`; +CREATE TABLE `wms_order_items` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `actual_price` decimal(18, 2) NOT NULL, + `retail_price` decimal(18, 2) NULL DEFAULT NULL, + `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `item_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `plan_qty` int(11) NULL DEFAULT NULL, + `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `extend_props` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `order_id`(`order_id`, `item_id`) USING BTREE, + CONSTRAINT `wms_order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `wms_order_delivery` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_items_100000 +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_items_100000`; +CREATE TABLE `wms_order_items_100000` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', + `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', + `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', + `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '外部编码', + `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '库存类型', + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品编码', + `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', + `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品名称', + `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '订单行号', + `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货主编码', + `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', + `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '源订单编码', + `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '子源订单编码', + `extend_props` json NULL COMMENT '扩展属性(JSON格式)', + `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', + `created_at` datetime(0) NOT NULL, + `updated_at` datetime(0) NOT NULL, + `item_snapshot` json NULL COMMENT '商品快照', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_100000_order_id`(`order_id`) USING BTREE, + INDEX `idx_100000_item_id`(`item_id`) USING BTREE, + INDEX `idx_100000_item_code`(`item_code`) USING BTREE, + INDEX `idx_100000_source_order_code`(`source_order_code`) USING BTREE, + INDEX `idx_100000_stock_id`(`stock_id`) USING BTREE, + INDEX `idx_100000_owner_code`(`owner_code`) USING BTREE, + INDEX `idx_100000_order_item`(`order_id`, `item_id`) USING BTREE, + INDEX `idx_100000_created_at`(`created_at`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 106818 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '仓库100000订单商品常用表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_items_100000_dispatch +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_items_100000_dispatch`; +CREATE TABLE `wms_order_items_100000_dispatch` ( + `id` bigint(20) UNSIGNED NOT NULL, + `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', + `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', + `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', + `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '外部编码', + `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库存类型', + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品编码', + `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', + `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品名称', + `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单行号', + `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货主编码', + `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', + `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '源订单编码', + `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '子源订单编码', + `extend_props` json NULL COMMENT '扩展属性(JSON格式)', + `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', + `created_at` datetime(0) NOT NULL, + `updated_at` datetime(0) NOT NULL, + `item_snapshot` json NULL COMMENT '商品快照', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_100000_order_id`(`order_id`) USING BTREE, + INDEX `idx_100000_item_id`(`item_id`) USING BTREE, + INDEX `idx_100000_item_code`(`item_code`) USING BTREE, + INDEX `idx_100000_source_order_code`(`source_order_code`) USING BTREE, + INDEX `idx_100000_stock_id`(`stock_id`) USING BTREE, + INDEX `idx_100000_owner_code`(`owner_code`) USING BTREE, + INDEX `idx_100000_order_item`(`order_id`, `item_id`) USING BTREE, + INDEX `idx_100000_created_at`(`created_at`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000订单商品配送表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_items_100000_history +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_items_100000_history`; +CREATE TABLE `wms_order_items_100000_history` ( + `id` bigint(20) UNSIGNED NOT NULL, + `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', + `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', + `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', + `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '外部编码', + `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库存类型', + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品编码', + `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', + `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品名称', + `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单行号', + `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货主编码', + `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', + `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '源订单编码', + `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '子源订单编码', + `extend_props` json NULL COMMENT '扩展属性(JSON格式)', + `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', + `created_at` datetime(0) NOT NULL, + `updated_at` datetime(0) NOT NULL, + `archive_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '归档时间', + `item_snapshot` json NULL COMMENT '商品快照', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_100000_order_id`(`order_id`) USING BTREE, + INDEX `idx_100000_item_id`(`item_id`) USING BTREE, + INDEX `idx_100000_item_code`(`item_code`) USING BTREE, + INDEX `idx_100000_source_order_code`(`source_order_code`) USING BTREE, + INDEX `idx_100000_stock_id`(`stock_id`) USING BTREE, + INDEX `idx_100000_owner_code`(`owner_code`) USING BTREE, + INDEX `idx_100000_order_item`(`order_id`, `item_id`) USING BTREE, + INDEX `idx_100000_created_at`(`created_at`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库100000订单商品历史表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_order_items_1000028 +-- ---------------------------- +DROP TABLE IF EXISTS `wms_order_items_1000028`; +CREATE TABLE `wms_order_items_1000028` ( + `id` bigint(20) UNSIGNED NOT NULL, + `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '订单ID', + `actual_price` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '实际价格', + `retail_price` decimal(18, 2) NULL DEFAULT NULL COMMENT '零售价格', + `ext_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '外部编码', + `inventory_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库存类型', + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品编码', + `item_id` bigint(20) NULL DEFAULT NULL COMMENT '商品ID', + `item_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品名称', + `order_line_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单行号', + `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '货主编码', + `plan_qty` int(11) NULL DEFAULT NULL COMMENT '计划数量', + `source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '源订单编码', + `sub_source_order_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '子源订单编码', + `extend_props` json NULL COMMENT '扩展属性(JSON格式)', + `stock_id` bigint(20) NULL DEFAULT NULL COMMENT '库存ID', + `item_snapshot` json NULL COMMENT '商品快照', + `created_at` datetime(0) NOT NULL, + `updated_at` datetime(0) NOT NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_1000028_order_id`(`order_id`) USING BTREE, + INDEX `idx_1000028_item_id`(`item_id`) USING BTREE, + INDEX `idx_1000028_item_code`(`item_code`) USING BTREE, + INDEX `idx_1000028_source_order_code`(`source_order_code`) USING BTREE, + INDEX `idx_1000028_stock_id`(`stock_id`) USING BTREE, + INDEX `idx_1000028_owner_code`(`owner_code`) USING BTREE, + INDEX `idx_1000028_order_item`(`order_id`, `item_id`) USING BTREE, + INDEX `idx_1000028_created_at`(`created_at`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '仓库1000028订单商品常用表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_permission +-- ---------------------------- +DROP TABLE IF EXISTS `wms_permission`; +CREATE TABLE `wms_permission` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '路由路径', + `component` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '组件路径', + `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '路由名称', + `redirect` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '重定向路径', + `meta_title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '页面标题', + `meta_icon` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图标', + `hidden` tinyint(1) NULL DEFAULT 0 COMMENT '是否隐藏(0:显示,1:隐藏)', + `always_show` tinyint(1) NULL DEFAULT 0 COMMENT '是否始终显示', + `parent_id` int(11) NULL DEFAULT NULL COMMENT '父级ID(根节点为NULL)', + `sort` int(11) NULL DEFAULT 0 COMMENT '排序', + `status` tinyint(1) NULL DEFAULT 1 COMMENT '状态(0:禁用,1:启用)', + `created_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), + `update_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), + `type` enum('web_pages','pda_pages','btns','api','miniprogram_pages','block') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'web_pages' COMMENT '设备类型(1:电脑端,2:小程序,3:手持设备,4:管理后台)', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `name`(`name`, `type`) USING BTREE, + INDEX `idx_parent_id`(`parent_id`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE, + CONSTRAINT `fk_wms_permission_parent` FOREIGN KEY (`parent_id`) REFERENCES `wms_permission` (`id`) ON DELETE SET NULL ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 353 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '权限路由表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_picking +-- ---------------------------- +DROP TABLE IF EXISTS `wms_picking`; +CREATE TABLE `wms_picking` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `order_id` bigint(20) UNSIGNED NOT NULL COMMENT '订单ID', + `order_item_id` bigint(20) UNSIGNED NOT NULL COMMENT '订单明细ID', + `storage_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库存记录ID', + `space_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库位ID', + `space_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库位名称', + `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'pending' COMMENT '状态', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `quantity` int(11) NULL DEFAULT NULL, + `deleted_at` datetime(0) NULL DEFAULT NULL, + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_wms_picking_order_id`(`order_id`) USING BTREE, + INDEX `idx_wms_picking_order_item_id`(`order_item_id`) USING BTREE, + INDEX `idx_wms_picking_storage_id`(`storage_id`) USING BTREE, + INDEX `idx_wms_picking_space_id`(`space_id`) USING BTREE, + INDEX `idx_wms_picking_status`(`status`) USING BTREE, + INDEX `idx_wms_picking_order_item_space`(`order_item_id`, `space_id`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + CONSTRAINT `wms_picking_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 486 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '订单储位分配表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_picking_strategy +-- ---------------------------- +DROP TABLE IF EXISTS `wms_picking_strategy`; +CREATE TABLE `wms_picking_strategy` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '策略ID', + `strategy_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '策略名称', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `strategy_type` tinyint(4) NOT NULL COMMENT '策略类型:1-散单 2-团购', + `status` tinyint(4) NULL DEFAULT 1 COMMENT '状态:1-启用 0-停用', + `order_min_sku` int(11) NULL DEFAULT 1 COMMENT '订单最小SKU种类数', + `order_max_sku` int(11) NULL DEFAULT 999 COMMENT '订单最大SKU种类数', + `order_min_qty` int(11) NULL DEFAULT 1 COMMENT '订单最小商品总数', + `order_max_qty` int(11) NULL DEFAULT 999 COMMENT '订单最大商品总数', + `min_same_structure` int(11) NULL DEFAULT 1 COMMENT '最小相同结构订单数', + `max_same_structure` int(11) NULL DEFAULT 999 COMMENT '最大相同结构订单数', + `require_same_express` tinyint(1) NULL DEFAULT 0 COMMENT '是否要求相同快递', + `allow_cross_owner` tinyint(1) NULL DEFAULT 1 COMMENT '是否允许跨货主', + `batch_mode` tinyint(4) NOT NULL COMMENT '拣货模式:1-单品单件 2-先拣后分 3-边拣边分 4-边拣边分H型 5-播种墙 6-流利架', + `batch_max_orders` int(11) NULL DEFAULT 20 COMMENT '批次最大订单数', + `batch_max_skus` int(11) NULL DEFAULT 50 COMMENT '批次最大SKU总数', + `group_batch_max_orders` int(11) NULL DEFAULT 1 COMMENT '团购批次最大订单数(相同结构)', + `allowed_owners` json NULL COMMENT '允许的货主ID列表', + `allowed_expresses` json NULL COMMENT '允许的快递编码列表', + `allowed_provinces` json NULL COMMENT '允许的省份列表', + `allowed_platforms` json NULL COMMENT '允许的平台列表', + `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '策略描述', + `creator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人姓名', + `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), + `update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0), + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_warehouse_type`(`warehouse_id`, `strategy_type`, `status`) USING BTREE, + INDEX `idx_batch_mode`(`batch_mode`, `strategy_type`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '拣货策略配置表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_platform +-- ---------------------------- +DROP TABLE IF EXISTS `wms_platform`; +CREATE TABLE `wms_platform` ( + `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `interface_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `platform_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `platid` int(11) NULL DEFAULT NULL, + `appkey` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `app_secret` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `version` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `shoptype` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `ordersource` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + PRIMARY KEY (`code`) USING BTREE +) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_platform_print_config +-- ---------------------------- +DROP TABLE IF EXISTS `wms_platform_print_config`; +CREATE TABLE `wms_platform_print_config` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `platform` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台名称', + `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台代码', + `print_port` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '打印服务端口', + `print_url` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印服务URL', + `protocol_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'WEBSOCKET' COMMENT '协议类型:WEBSOCKET,HTTP', + `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'ACTIVE' COMMENT '状态:ACTIVE-启用,DISABLED-禁用', + `retry_count` int(11) NULL DEFAULT 3 COMMENT '重试次数', + `timeout_seconds` int(11) NULL DEFAULT 30 COMMENT '超时时间(秒)', + `description` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '描述', + `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `update_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_platform`(`platform`) USING BTREE, + INDEX `idx_platform_code`(`platform_code`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '平台打印端口配置表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_platfrom_setting +-- ---------------------------- +DROP TABLE IF EXISTS `wms_platfrom_setting`; +CREATE TABLE `wms_platfrom_setting` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `platform_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `warehouse_id` bigint(20) UNSIGNED NOT NULL, + `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '别名', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `platform_code`(`platform_code`, `warehouse_id`) USING BTREE, + UNIQUE INDEX `code`(`code`, `warehouse_id`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + CONSTRAINT `wms_platfrom_setting_ibfk_1` FOREIGN KEY (`platform_code`) REFERENCES `wms_platform` (`code`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_platfrom_setting_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_print_computer +-- ---------------------------- +DROP TABLE IF EXISTS `wms_print_computer`; +CREATE TABLE `wms_print_computer` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `status` int(1) NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_print_items +-- ---------------------------- +DROP TABLE IF EXISTS `wms_print_items`; +CREATE TABLE `wms_print_items` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '业务类型', + `platform` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '平台', + `field_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字段名(显示名称)', + `field_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字段代码(英文标识)', + `field_type` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '字段类型', + `is_table` tinyint(1) NULL DEFAULT 0 COMMENT '是否渲染为表格:0-否,1-是', + `table_config` json NULL COMMENT '表格配置', + `group_field` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分组字段', + `group_label` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分组标题', + `group_sort` int(11) NULL DEFAULT 0 COMMENT '分组排序', + `required` tinyint(1) NULL DEFAULT 0 COMMENT '是否必填:0-否,1-是', + `default_value` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '默认值', + `sort_order` int(11) NULL DEFAULT 0 COMMENT '排序序号', + `regex_pattern` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '正则验证规则', + `max_length` int(11) NULL DEFAULT NULL COMMENT '最大长度', + `min_length` int(11) NULL DEFAULT NULL COMMENT '最小长度', + `options` json NULL COMMENT '选项(用于下拉框等)', + `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '字段描述', + `status` tinyint(1) NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用', + `created_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人', + `updated_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '更新人', + `created_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_business_platform_field`(`business_type`, `platform`, `field_code`) USING BTREE, + INDEX `idx_business_type`(`business_type`) USING BTREE, + INDEX `idx_platform`(`platform`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 144 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印项配置表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_print_log +-- ---------------------------- +DROP TABLE IF EXISTS `wms_print_log`; +CREATE TABLE `wms_print_log` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `print_record_id` bigint(20) NOT NULL COMMENT '打印记录ID', + `log_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '日志类型:CONNECT-连接,PRINT-打印,RETRY-重试,ERROR-错误,SUCCESS-成功', + `log_level` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'INFO' COMMENT '日志级别:INFO,WARN,ERROR', + `log_content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '日志内容', + `request_data` json NULL COMMENT '请求数据', + `response_data` json NULL COMMENT '响应数据', + `websocket_status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'WebSocket状态', + `error_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '错误代码', + `ip_address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'IP地址', + `user_agent` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户代理', + `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_print_record`(`print_record_id`) USING BTREE, + INDEX `idx_log_type`(`log_type`) USING BTREE, + INDEX `idx_create_time`(`create_time`) USING BTREE, + INDEX `idx_error_code`(`error_code`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印日志表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_print_record +-- ---------------------------- +DROP TABLE IF EXISTS `wms_print_record`; +CREATE TABLE `wms_print_record` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `computer_id` bigint(20) UNSIGNED NOT NULL COMMENT '电脑ID', + `printer` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '打印机名称/标识', + `type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '打印类型', + `data` json NULL COMMENT '打印数据(JSON格式)', + `status` enum('pending','sent','success','failed') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'pending' COMMENT '打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败', + `error_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '错误信息', + `sent_time` datetime(0) NULL DEFAULT NULL COMMENT '发送时间', + `print_time` datetime(0) NULL DEFAULT NULL COMMENT '打印完成时间', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `logs` json NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_computer_id`(`computer_id`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE, + INDEX `idx_created_at`(`created_at`) USING BTREE, + INDEX `idx_sent_time`(`sent_time`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 358 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印记录表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_print_station_express +-- ---------------------------- +DROP TABLE IF EXISTS `wms_print_station_express`; +CREATE TABLE `wms_print_station_express` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增主键ID', + `print_station_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '打印台ID,关联wms_print_stations表的print_station_id', + `express_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '快递ID', + `express_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '快递名称,冗余字段,便于查询', + `printer_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '绑定的打印机名称', + `creator_id` bigint(20) UNSIGNED NOT NULL COMMENT '创建人工号ID', + `creator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '创建人名称', + `create_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `update_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '软删除标记:0-未删除,1-已删除', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_print_station_express`(`print_station_id`, `express_id`, `deleted`) USING BTREE, + INDEX `idx_print_station_id`(`print_station_id`) USING BTREE, + INDEX `idx_express_id`(`express_id`) USING BTREE, + INDEX `idx_creator_id`(`creator_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '打印台快递-打印机绑定关系表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_print_stations +-- ---------------------------- +DROP TABLE IF EXISTS `wms_print_stations`; +CREATE TABLE `wms_print_stations` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增主键ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '打印台名称', + `computer_id` int(11) NOT NULL COMMENT '打印电脑ID', + `custom_barcode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '自定义编码', + `creator_id` bigint(20) UNSIGNED NOT NULL COMMENT '创建人工号ID', + `creator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '创建人名称', + `create_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `update_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '软删除标记:0-未删除,1-已删除', + `default_printer_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '默认打印机名称', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_computer_id`(`computer_id`) USING BTREE, + INDEX `idx_name`(`name`) USING BTREE, + INDEX `idx_custom_barcode`(`custom_barcode`) USING BTREE, + INDEX `idx_creator_id`(`creator_id`) USING BTREE, + INDEX `idx_create_at`(`create_at`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '打印台信息表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_print_template +-- ---------------------------- +DROP TABLE IF EXISTS `wms_print_template`; +CREATE TABLE `wms_print_template` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `template_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '模板名称', + `platform` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '所属平台(抖音、拼多多、快手等)', + `template_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '模板类型:STANDARD-标准模板,CUSTOM-自定义模板', + `template_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '模板URL地址', + `template_content` json NULL COMMENT '模板内容(JSON格式)', + `page_width` int(11) NULL DEFAULT 76 COMMENT '页面宽度(mm)', + `page_height` int(11) NULL DEFAULT 130 COMMENT '页面高度(mm)', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '关联仓库ID', + `is_default` tinyint(1) NULL DEFAULT 0 COMMENT '是否默认模板:0-否,1-是', + `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'ACTIVE' COMMENT '状态:ACTIVE-启用,DISABLED-禁用', + `create_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `update_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `business_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '类型', + `delete_at` date NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_platform_template`(`platform`, `template_type`, `warehouse_id`, `business_type`, `delete_at`) USING BTREE, + INDEX `idx_platform`(`platform`) USING BTREE, + INDEX `idx_warehouse`(`warehouse_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '打印模板配置表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_prohibited_type +-- ---------------------------- +DROP TABLE IF EXISTS `wms_prohibited_type`; +CREATE TABLE `wms_prohibited_type` ( + `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `type_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '类型名称', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID(关联wms_store.id,NULL表示系统预设)', + `is_system_preset` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否系统预设', + `sort_order` int(11) NULL DEFAULT 0 COMMENT '排序', + `created_by` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '创建人', + `updated_by` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '更新人', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_type_warehouse`(`type_name`, `warehouse_id`) USING BTREE, + INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_is_system`(`is_system_preset`) USING BTREE, + CONSTRAINT `fk_prohibited_type_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '违禁品类型表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_qimen_apps +-- ---------------------------- +DROP TABLE IF EXISTS `wms_qimen_apps`; +CREATE TABLE `wms_qimen_apps` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `app_key` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `app_key`(`app_key`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 29 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_qimen_log +-- ---------------------------- +DROP TABLE IF EXISTS `wms_qimen_log`; +CREATE TABLE `wms_qimen_log` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `log_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `from_key` int(10) NULL DEFAULT NULL, + `method` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `sign` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `costomer_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `v` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `url` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `created_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), + `body` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `result` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `use_time` int(12) NULL DEFAULT NULL, + `updated_at` datetime(0) NULL DEFAULT NULL, + `deleted_at` datetime(0) NULL DEFAULT NULL, + `to_key` int(10) NULL DEFAULT 23535631, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `idx_log_id`(`log_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 185807 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_receiving +-- ---------------------------- +DROP TABLE IF EXISTS `wms_receiving`; +CREATE TABLE `wms_receiving` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '收货单ID', + `receiving_number` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '收货单号,如: RCV202312150001', + `creator_id` int(11) NOT NULL COMMENT '创建人工号ID', + `creator_snapshot` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '创建人信息快照(JSON格式)', + `status` enum('receiving','completed','cancelled') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'receiving' COMMENT '收货状态:receiving-收货中, completed-收货完成, cancelled-作废', + `detail_status` enum('all_matched','partial_matched','unmatched') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'unmatched' COMMENT '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配', + `storage_status` enum('none','partial','all') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库', + `delivery_method` enum('truck','express','air_freight','sea_freight','other') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '来货方式:truck-货车, express-快递, air_freight-空运, sea_freight-海运, other-其他', + `license_plate` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '车牌号(货车运输时需要)', + `tracking_number` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '快递单号/物流单号', + `loading_method` enum('with_pallet','without_pallet') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '装卸方式:with_pallet-带托盘, without_pallet-不带托盘', + `video_device_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '录像设备ID(可选)', + `total_items` int(11) NOT NULL DEFAULT 0 COMMENT '总商品种类数', + `total_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '商品总数量', + `total_boxes` int(11) NOT NULL DEFAULT 0 COMMENT '总箱数', + `total_pallets` int(11) NOT NULL DEFAULT 0 COMMENT '总托盘数', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '收货仓库ID', + `remark` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '备注信息', + `receiving_start_time` datetime(0) NULL DEFAULT NULL COMMENT '收货开始时间', + `receiving_end_time` datetime(0) NULL DEFAULT NULL COMMENT '收货结束时间', + `is_deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否删除:0-否, 1-是', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `store_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, + `is_notice` int(1) UNSIGNED NULL DEFAULT 0, + `is_review` tinyint(1) NULL DEFAULT 0, + `reviewer_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, + `reviewer_employee_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_receiving_number`(`receiving_number`) USING BTREE, + INDEX `idx_creator_id`(`creator_id`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE, + INDEX `idx_delivery_method`(`delivery_method`) USING BTREE, + INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_created_at`(`created_at`) USING BTREE, + INDEX `idx_status_warehouse`(`status`, `warehouse_id`) USING BTREE, + INDEX `idx_supplier_created`(`created_at`) USING BTREE, + INDEX `reviewer_employee_id`(`reviewer_employee_id`) USING BTREE, + CONSTRAINT `wms_receiving_ibfk_1` FOREIGN KEY (`reviewer_employee_id`) REFERENCES `wms_account_store_employee` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 1377 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '收货主表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_receiving_detail +-- ---------------------------- +DROP TABLE IF EXISTS `wms_receiving_detail`; +CREATE TABLE `wms_receiving_detail` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '明细ID', + `receiving_id` int(11) NOT NULL COMMENT '收货单ID', + `product_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称', + `barcode` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '商品条码', + `product_snapshot` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '商品信息快照(JSON格式)', + `system_product_id` int(11) NULL DEFAULT NULL COMMENT '关联的系统商品ID(可以为空)', + `actual_quantity` int(11) NOT NULL COMMENT '实际收货数量', + `box_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '箱数', + `boxes_per_pallet` int(11) NOT NULL DEFAULT 1 COMMENT '(箱规)', + `pallet_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '托盘数', + `receiving_time` datetime(0) NULL DEFAULT NULL COMMENT '收货时间(该商品的收货时间)', + `receiving_status` enum('pending','receiving','completed','cancelled') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pending' COMMENT '收货状态', + `storage_status` enum('none','partial','all') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库', + `stored_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '已入库数量', + `batch_number` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '批次号', + `production_date` date NULL DEFAULT NULL COMMENT '生产日期', + `expiry_date` date NULL DEFAULT NULL COMMENT '保质期/到期日期', + `remark` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '备注', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `space_id` bigint(20) NULL DEFAULT 1 COMMENT '存放位置', + `creator_id` bigint(20) UNSIGNED ZEROFILL NULL DEFAULT NULL, + `box_length` decimal(10, 2) NULL DEFAULT NULL COMMENT '长cm', + `box_width` decimal(10, 2) NULL DEFAULT NULL COMMENT '宽cm', + `box_height` decimal(10, 2) NULL DEFAULT NULL COMMENT '高cm', + `weight` int(11) NULL DEFAULT NULL COMMENT '重量g', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_receiving_id`(`receiving_id`) USING BTREE, + INDEX `idx_system_product_id`(`system_product_id`) USING BTREE, + INDEX `idx_receiving_status`(`receiving_status`) USING BTREE, + INDEX `idx_storage_status`(`storage_status`) USING BTREE, + INDEX `idx_batch_number`(`batch_number`) USING BTREE, + CONSTRAINT `fk_receiving_detail_receiving` FOREIGN KEY (`receiving_id`) REFERENCES `wms_receiving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB AUTO_INCREMENT = 2536 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '收货明细表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_role +-- ---------------------------- +DROP TABLE IF EXISTS `wms_role`; +CREATE TABLE `wms_role` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '角色ID', + `role_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '角色代码', + `role_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '角色名称', + `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色描述', + `role_type` tinyint(4) NOT NULL DEFAULT 1 COMMENT '角色类型:1-系统角色,2-自定义角色', + `scope` tinyint(4) NOT NULL DEFAULT 1 COMMENT '作用范围:1-全局,2-指定仓库', + `is_system` tinyint(4) NOT NULL DEFAULT 0 COMMENT '是否系统预设:0-否,1-是', + `status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用', + `created_by` bigint(20) UNSIGNED NOT NULL COMMENT '创建人', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '所属仓库ID', + `deleted_at` datetime(0) NULL DEFAULT NULL, + `pid` bigint(20) UNSIGNED NULL DEFAULT 0 COMMENT '上级id', + `permissions` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_role_code`(`role_code`) USING BTREE, + INDEX `idx_role_type`(`role_type`) USING BTREE, + INDEX `idx_scope`(`scope`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE, + INDEX `fk_wms_role_created_by`(`created_by`) USING BTREE, + INDEX `idx_store_id`(`store_id`) USING BTREE, + CONSTRAINT `fk_wms_role_created_by` FOREIGN KEY (`created_by`) REFERENCES `wms_account` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT, + CONSTRAINT `fk_wms_role_store` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE SET NULL ON UPDATE RESTRICT +) ENGINE = InnoDB AUTO_INCREMENT = 83 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '平台角色表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_stock_barcodes +-- ---------------------------- +DROP TABLE IF EXISTS `wms_stock_barcodes`; +CREATE TABLE `wms_stock_barcodes` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `stock_id` bigint(20) NOT NULL COMMENT '主表ID', + `barcode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '条码', + `description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '条码描述', + `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_stock_id`(`stock_id`) USING BTREE, + INDEX `uk_barcode`(`barcode`) USING BTREE, + CONSTRAINT `wms_stock_barcodes_ibfk_1` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 35086 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS商品条码表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_stock_store +-- ---------------------------- +DROP TABLE IF EXISTS `wms_stock_store`; +CREATE TABLE `wms_stock_store` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `warehouse_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '仓库编码', + `owner_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '货主编码', + `app_key` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, + `is_area_sale` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否区域销售', + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品编码', + `goods_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货物编码', + `item_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称', + `sku_property` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'SKU规格', + `stock_unit` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '库存单位', + `length` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '长度', + `width` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '宽度', + `height` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '高度', + `volume` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '体积', + `gross_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '毛重', + `net_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '净重', + `category_id` int(11) NULL DEFAULT NULL COMMENT '分类ID', + `category_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '分类名称', + `item_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品类型', + `tag_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '标价', + `retail_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '零售价', + `is_sn_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否序列号管理', + `is_shelf_life_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否保质期管理', + `is_batch_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否批次管理', + `create_time` datetime(0) NOT NULL COMMENT '创建时间', + `update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `is_valid` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Y' COMMENT '是否有效', + `barcode` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, + `stock_id` bigint(20) NULL DEFAULT NULL, + `warehouse_id` bigint(20) UNSIGNED NOT NULL, + `store_id` bigint(20) UNSIGNED NOT NULL, + `create_from` enum('qimen','api') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `brand_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_warehouse_owner_item`(`item_code`, `app_key`, `warehouse_id`, `store_id`) USING BTREE, + INDEX `idx_owner_code`(`owner_code`) USING BTREE, + INDEX `idx_goods_code`(`goods_code`) USING BTREE, + INDEX `idx_category_id`(`category_id`) USING BTREE, + INDEX `idx_create_time`(`create_time`) USING BTREE, + INDEX `idx_is_valid`(`is_valid`) USING BTREE, + INDEX `uk_item_code`(`item_code`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `store_id`(`store_id`) USING BTREE, + INDEX `stock_id`(`stock_id`) USING BTREE, + CONSTRAINT `wms_stock_store_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_stock_store_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_stock_store_ibfk_3` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 1000693 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS库存主表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_stock_transaction +-- ---------------------------- +DROP TABLE IF EXISTS `wms_stock_transaction`; +CREATE TABLE `wms_stock_transaction` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `transaction_type` enum('INBOUND','OUTBOUND') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '出入库类型', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主ID', + `stock_id` bigint(20) UNSIGNED NOT NULL COMMENT '商品库存ID,关联 wms_stock_warehouse.id', + `storage_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库位库存ID,关联 wms_storage.id', + `space_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '库位ID', + `quantity` int(12) NOT NULL COMMENT '变动数量(正数)', + `batch_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '批次号', + `inventory_type` enum('ZP','CC','JS','XS','ZT','DJ','FP') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'ZP' COMMENT '库存类型', + `order_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '关联单据类型', + `order_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '关联单据号', + `order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '关联单据ID', + `receiving_id` int(11) NULL DEFAULT NULL COMMENT '关联收货单ID', + `entry_order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '关联入库单ID', + `operator_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人ID', + `operator_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作人名称', + `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `before_quantity` int(12) NULL DEFAULT NULL COMMENT '变更前总库存数量', + `after_quantity` int(12) NULL DEFAULT NULL COMMENT '变更后总库存数量', + `before_locked_quantity` int(12) NULL DEFAULT NULL COMMENT '变更前锁定数量', + `after_locked_quantity` int(12) NULL DEFAULT NULL COMMENT '变更后锁定数量', + PRIMARY KEY (`id`) USING BTREE, + INDEX `idx_stock_id`(`stock_id`) USING BTREE, + INDEX `idx_warehouse_time`(`warehouse_id`, `created_at`) USING BTREE, + INDEX `idx_order`(`order_type`, `order_id`) USING BTREE, + INDEX `idx_receiving_id`(`receiving_id`) USING BTREE, + INDEX `idx_entry_order_id`(`entry_order_id`) USING BTREE, + INDEX `idx_created_at`(`created_at`) USING BTREE, + INDEX `idx_store_transaction_type`(`store_id`, `transaction_type`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 148 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '出入库流水记录表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_stock_unit +-- ---------------------------- +DROP TABLE IF EXISTS `wms_stock_unit`; +CREATE TABLE `wms_stock_unit` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '仓库ID,NULL表示系统默认', + `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '单位名称', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_name_warehouse`(`name`, `warehouse_id`) USING BTREE COMMENT '单位名称在同一个仓库下唯一', + INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 22 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '库存单位表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_stock_warehouse +-- ---------------------------- +DROP TABLE IF EXISTS `wms_stock_warehouse`; +CREATE TABLE `wms_stock_warehouse` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `item_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品编码', + `goods_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '货物编码', + `store_id` bigint(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '货主id', + `item_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称', + `sku_property` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'SKU规格', + `stock_unit` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '库存单位', + `packing_requirements` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '打包要求', + `length` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '长度', + `width` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '宽度', + `height` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '高度', + `volume` int(11) UNSIGNED NULL DEFAULT 0 COMMENT '体积', + `gross_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '毛重', + `net_weight` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '净重', + `item_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品类型', + `tag_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '标价', + `retail_price` decimal(10, 2) NULL DEFAULT 0.00 COMMENT '零售价', + `is_sn_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否序列号管理', + `is_shelf_life_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否保质期管理', + `is_batch_mgmt` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否批次管理', + `is_images` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'N' COMMENT '是否有照片', + `create_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `update_at` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `is_valid` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Y' COMMENT '是否有效', + `warehouse_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `quantity` int(11) NOT NULL DEFAULT 0 COMMENT '库存数量', + `locked_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '订单锁定库存', + `level` enum('A','B','C') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '商品分级', + `prohibited_id` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '违禁品分类', + `return_quantity` int(11) NULL DEFAULT NULL COMMENT '消退库存', + `brand_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL, + `enable_box_spec` tinyint(4) NULL DEFAULT NULL, + `box_gross_weight` int(11) NULL DEFAULT NULL COMMENT '箱毛重(g)', + `box_height` decimal(10, 2) NULL DEFAULT NULL COMMENT '箱高(cm)', + `box_length` decimal(10, 2) NULL DEFAULT NULL COMMENT '箱长(cm)', + `box_width` decimal(10, 2) NULL DEFAULT NULL COMMENT '箱宽(cm)', + `box_net_weight` int(11) NULL DEFAULT NULL COMMENT '箱净重', + `box_volume` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '箱体积(m³)', + `quantity_per_box` int(11) NULL DEFAULT NULL, + `deleted_at` datetime(0) NULL DEFAULT NULL, + `inbound_min_days` int(11) NULL DEFAULT 0 COMMENT '入库最小天数要求', + `outbound_min_days` int(11) NULL DEFAULT 0 COMMENT '出库最小天数要求', + `remaining_threshold_days` int(11) NULL DEFAULT 0 COMMENT '剩余有效期阈值天数', + `shelf_life_days` int(11) NULL DEFAULT NULL COMMENT '保质期天数', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_item_code`(`item_code`, `warehouse_id`, `store_id`, `deleted_at`) USING BTREE, + INDEX `idx_create_time`(`create_at`) USING BTREE, + INDEX `idx_is_valid`(`is_valid`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `wms_stock_warehouse_ibfk_2`(`prohibited_id`) USING BTREE, + CONSTRAINT `wms_stock_warehouse_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT `wms_stock_warehouse_ibfk_2` FOREIGN KEY (`prohibited_id`) REFERENCES `wms_prohibited_type` (`id`) ON DELETE SET NULL ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 157105 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'WMS库存主表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_storage +-- ---------------------------- +DROP TABLE IF EXISTS `wms_storage`; +CREATE TABLE `wms_storage` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '库存ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主ID', + `space_id` bigint(20) UNSIGNED NOT NULL COMMENT '库位ID,关联外部仓位表', + `stock_id` bigint(20) NOT NULL COMMENT '商品SKU ID', + `batch_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '批次号', + `inventory_type` enum('ZP','CC','BACK','VIRTUAL') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'ZP' COMMENT '库存类型:ZP=正品, CC=残次, JS=机损, XS=箱损, ZT=在途库存, DJ=冻结, FP=废品', + `quantity` int(12) NOT NULL DEFAULT 0 COMMENT '库存数量', + `locked_quantity` int(12) NOT NULL DEFAULT 0 COMMENT '锁定数量', + `available_quantity` int(12) NOT NULL DEFAULT 0 COMMENT '可用数量', + `production_date` date NULL DEFAULT NULL COMMENT '生产日期', + `expiry_date` date NULL DEFAULT NULL COMMENT '过期日期', + `inbound_time` datetime(0) NOT NULL COMMENT '入库时间', + `inbound_order_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '入库单号', + `receiving_id` int(11) NULL DEFAULT NULL COMMENT '收货单ID', + `entry_order_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '入库单ID', + `supplier_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '供应商ID', + `supplier_batch_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '供应商批次号', + `is_enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `delete_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_location_sku_batch_type`(`space_id`, `stock_id`, `batch_no`, `inventory_type`) USING BTREE, + INDEX `idx_warehouse_location`(`warehouse_id`, `space_id`) USING BTREE, + INDEX `idx_sku_batch`(`stock_id`, `batch_no`) USING BTREE, + INDEX `idx_inventory_type`(`inventory_type`) USING BTREE, + INDEX `idx_expiry_date`(`expiry_date`) USING BTREE, + INDEX `idx_inbound_order`(`inbound_order_no`) USING BTREE, + INDEX `store_id`(`store_id`) USING BTREE, + INDEX `idx_receiving_id`(`receiving_id`) USING BTREE, + INDEX `idx_entry_order_id`(`entry_order_id`) USING BTREE, + CONSTRAINT `wms_storage_entry_order_id_foreign_idx` FOREIGN KEY (`entry_order_id`) REFERENCES `wms_entry_order` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `wms_storage_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_storage_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION, + CONSTRAINT `wms_storage_ibfk_3` FOREIGN KEY (`stock_id`) REFERENCES `wms_stock_warehouse` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT `wms_storage_ibfk_4` FOREIGN KEY (`space_id`) REFERENCES `wms_location_space` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 223 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '库存表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_store +-- ---------------------------- +DROP TABLE IF EXISTS `wms_store`; +CREATE TABLE `wms_store` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '商家ID', + `company_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '公司全称', + `business_license` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '营业执照号', + `legal_person` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '法人代表', + `contact_phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '联系电话', + `contact_email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '联系邮箱', + `contact_person` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '联系人', + `address` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '公司地址', + `industry` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '所属行业', + `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '关联账号ID(商家管理员)', + `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '状态:0-禁用,1-启用,2-审核中', + `created_by` bigint(20) UNSIGNED NOT NULL COMMENT '创建人', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `logo_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'logo链接', + `domain` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '绑定域名', + `auth_end` date NULL DEFAULT NULL COMMENT '授权结束时间', + `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `quota_bytes` bigint(20) UNSIGNED NULL DEFAULT 107374182400, + `project` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '应用', + `subject_config` json NULL COMMENT '主体配置JSON', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_company_name`(`company_name`) USING BTREE, + UNIQUE INDEX `uk_business_license`(`business_license`, `deleted_at`) USING BTREE, + INDEX `idx_status`(`status`) USING BTREE, + INDEX `idx_account_id`(`account_id`) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1000278 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '商家表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_store_join +-- ---------------------------- +DROP TABLE IF EXISTS `wms_store_join`; +CREATE TABLE `wms_store_join` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '申请ID', + `account_id` bigint(20) UNSIGNED NOT NULL COMMENT '用户账户ID', + `real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '真实姓名', + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '审批的门店/店铺ID', + `apply_time` datetime(0) NOT NULL COMMENT '申请时间', + `apply_username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '申请人用户名', + `audit_status` enum('pending','approved','rejected','processing') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 'pending' COMMENT '审核状态', + `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '备注', + `join_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '加入令牌/验证码', + `token_expiry_time` datetime(0) NULL DEFAULT NULL COMMENT '令牌过期时间', + `created_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `audit_real_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '审核人工号名字', + `warehouse` tinyint(1) NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_join_token`(`join_token`) USING BTREE, + INDEX `idx_account_id`(`account_id`) USING BTREE, + INDEX `idx_audit_status`(`audit_status`) USING BTREE, + INDEX `idx_apply_time`(`apply_time`) USING BTREE, + INDEX `idx_store_id`(`store_id`) USING BTREE, + INDEX `uk_account_warehouse_store`(`account_id`, `store_id`) USING BTREE, + CONSTRAINT `wms_store_join_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `wms_account` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT `wms_store_join_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 37 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '加入申请记录表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_store_warehouse +-- ---------------------------- +DROP TABLE IF EXISTS `wms_store_warehouse`; +CREATE TABLE `wms_store_warehouse` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '授权ID', + `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '商家ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `auth_status` tinyint(4) NOT NULL DEFAULT 1 COMMENT '授权状态:1-申请中,2-已通过,3-已拒绝,4-已解除,5-已过期', + `apply_reason` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '申请理由', + `review_comment` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '审核意见', + `apply_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '申请时间', + `review_time` datetime(0) NULL DEFAULT NULL COMMENT '审核时间', + `auth_start` date NULL DEFAULT NULL COMMENT '授权开始日期', + `auth_end` date NULL DEFAULT NULL COMMENT '授权结束日期', + `actual_end` datetime(0) NULL DEFAULT NULL COMMENT '实际结束时间', + `applied_by` bigint(20) UNSIGNED NOT NULL COMMENT '申请人', + `reviewed_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '审核人', + `ended_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '解除人', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + `store_remask` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商家备注', + `warehouse_remask` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '仓库备注', + `deleted_at` datetime(0) NULL DEFAULT NULL COMMENT '删除时间', + `print_quantity` int(11) NOT NULL DEFAULT 0 COMMENT '面单余额', + `print_quantity_locked` int(11) NOT NULL DEFAULT 0 COMMENT '面单锁定余额,分配快递时递增1', + `use_status` int(1) NULL DEFAULT 0 COMMENT '使用状态0-不使用,1-使用', + `policy_config` json NULL COMMENT '货主在仓库的配置与策略', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `uk_store_warehouse`(`store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_store_id`(`store_id`) USING BTREE, + INDEX `idx_warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_auth_status`(`auth_status`) USING BTREE, + INDEX `idx_apply_time`(`apply_time`) USING BTREE, + INDEX `idx_auth_period`(`auth_start`, `auth_end`) USING BTREE, + INDEX `use_status`(`use_status`) USING BTREE, + CONSTRAINT `wms_store_warehouse_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION, + CONSTRAINT `wms_store_warehouse_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 100250 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '商家仓库授权表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_store_warehouse_print_quantity_log +-- ---------------------------- +DROP TABLE IF EXISTS `wms_store_warehouse_print_quantity_log`; +CREATE TABLE `wms_store_warehouse_print_quantity_log` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `contract_id` bigint(20) UNSIGNED NOT NULL COMMENT '签约关系ID,对应 wms_store_warehouse.id', + `store_id` bigint(20) UNSIGNED NOT NULL COMMENT '货主ID', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `change_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '变更类型,如 manual_adjust / order_deduct', + `business_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '业务来源类型,如 order_express', + `business_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '业务关联ID,预留关联 wms_order_express.id', + `change_quantity` int(11) NOT NULL COMMENT '本次变更数量,整数,可正可负', + `balance_before` int(11) NOT NULL COMMENT '变更前余额', + `balance_after` int(11) NOT NULL COMMENT '变更后余额', + `reason` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '变更缘由;人工调整时必填', + `operator_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '操作人账号ID', + `created_by` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '创建人账号ID', + `created_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', + `updated_at` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + INDEX `warehouse_id`(`warehouse_id`) USING BTREE, + INDEX `idx_sw_print_qty_log_contract_id`(`contract_id`, `id`) USING BTREE, + INDEX `idx_sw_print_qty_log_store_warehouse`(`store_id`, `warehouse_id`) USING BTREE, + INDEX `idx_sw_print_qty_log_business`(`business_type`, `business_id`) USING BTREE, + INDEX `idx_sw_print_qty_log_change_type`(`change_type`) USING BTREE, + INDEX `idx_sw_print_qty_log_created_at`(`created_at`) USING BTREE, + CONSTRAINT `wms_store_warehouse_print_quantity_log_ibfk_1` FOREIGN KEY (`contract_id`) REFERENCES `wms_store_warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `wms_store_warehouse_print_quantity_log_ibfk_2` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `wms_store_warehouse_print_quantity_log_ibfk_3` FOREIGN KEY (`warehouse_id`) REFERENCES `wms_store` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE = InnoDB AUTO_INCREMENT = 26 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '货主-仓库签约面单余额变更记录表' ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_system_log +-- ---------------------------- +DROP TABLE IF EXISTS `wms_system_log`; +CREATE TABLE `wms_system_log` ( + `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, + `method` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `v` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + `url` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `created_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), + `body` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `result` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `use_time` int(12) NULL DEFAULT NULL, + `updated_at` datetime(0) NULL DEFAULT NULL, + `delete_at` datetime(0) NULL DEFAULT NULL, + `headers` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `auth` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, + `store_id` bigint(20) UNSIGNED NULL DEFAULT NULL, + `device` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `store_id`(`store_id`) USING BTREE, + CONSTRAINT `wms_system_log_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE = InnoDB AUTO_INCREMENT = 30174 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Table structure for wms_wave_batch +-- ---------------------------- +DROP TABLE IF EXISTS `wms_wave_batch`; +CREATE TABLE `wms_wave_batch` ( + `wave_id` bigint(20) NOT NULL AUTO_INCREMENT, + `wave_no` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '波次编号,如WAVE202401001', + `wave_type` tinyint(4) NOT NULL DEFAULT 1 COMMENT '波次类型:1-团购 2-散单', + `wave_status` tinyint(4) NOT NULL DEFAULT 0 COMMENT '波次状态:-1-已取消 0-自动加团中 1-已就绪 2-已打印 3-拣货中 4-拣货完成 5-复核完成 6-打包完成 ', + `total_orders` int(11) NULL DEFAULT 0 COMMENT '总订单数', + `processed_orders` int(11) NULL DEFAULT 0 COMMENT '已处理订单数', + `picking_operator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '拣货员', + `picking_start_time` datetime(0) NULL DEFAULT NULL COMMENT '拣货开始时间', + `picking_end_time` datetime(0) NULL DEFAULT NULL COMMENT '拣货结束时间', + `print_operator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '打印员', + `print_time` datetime(0) NULL DEFAULT NULL COMMENT '打印时间', + `print_count` int(11) NULL DEFAULT 0 COMMENT '打印次数', + `check_operator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '校验员', + `check_time` datetime(0) NULL DEFAULT NULL COMMENT '校验时间', + `check_result` tinyint(4) NULL DEFAULT NULL COMMENT '校验结果', + `priority` tinyint(4) NULL DEFAULT 5 COMMENT '优先级 1-5', + `warehouse_id` bigint(20) UNSIGNED NOT NULL COMMENT '仓库ID', + `creator` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '创建人', + `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0), + `update_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), + `item_detail_machine` varchar(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key', + `item_part_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结构来源类型:items_hash/items', + `item_part` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结构主键(items_hash或items摘要)', + `distinguish_express` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否区分快递 0否1是', + `logistics_name` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '快递名称(区分快递时参与匹配)', + `item_snapshot_key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '结构快照键', + PRIMARY KEY (`wave_id`) USING BTREE, + INDEX `idx_wave_status`(`wave_status`, `create_time`) USING BTREE, + INDEX `idx_wave_no`(`wave_no`) USING BTREE, + INDEX `idx_warehouse`(`warehouse_id`, `wave_status`) USING BTREE, + INDEX `idx_creator`(`creator`, `create_time`) USING BTREE, + INDEX `idx_wave_fast_group`(`warehouse_id`, `wave_type`, `wave_status`, `item_part_type`, `item_part`, `distinguish_express`, `logistics_name`) USING BTREE, + INDEX `idx_wave_snapshot_key`(`item_snapshot_key`) USING BTREE, + INDEX `idx_wave_item_machine_prefix`(`item_detail_machine`(191)) USING BTREE +) ENGINE = InnoDB AUTO_INCREMENT = 1777888535764263 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '波次批次主表' ROW_FORMAT = Dynamic; + +SET FOREIGN_KEY_CHECKS = 1; diff --git a/app/controller/home.js b/app/controller/home.js index 3872ddd..7ecb129 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -9,29 +9,7 @@ class HomeController extends Controller { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; } - /** - * Polo API 测试入口,直接透传 PoloApiService.test() 的真实返回结果。 - * - * @return {Promise} 无返回值,响应结果直接写入 ctx.body。 - */ - async testPoloApi() { - const { - ctx, - } = this; - // 获取get参数 - const platid = ctx.params.platid; - const result = await ctx.service.systems.poloApi.test(platid); - ctx.body = JSON.parse(result); - } - async PoloApiGetWayBillCondition() { - const { - ctx, - } = this; - // 获取get参数 - const platid = ctx.params.platid; - const result = await ctx.service.systems.poloApi.GetWayBillCondition(platid); - ctx.body = JSON.parse(result); - } + async index() { const { ctx, @@ -394,42 +372,6 @@ class HomeController extends Controller { }); } - async saveLog(logData, startTime) { - const { - ctx, - } = this; - - try { - // 限制日志内容长度 - if (logData.body && logData.body.length > 65535) { - logData.body = logData.body.substring(0, 65535); - } - - if (logData.result && logData.result.length > 65535) { - logData.result = logData.result.substring(0, 65535); - } - - logData.use_time = Date.now() - startTime; - - // 使用 egg-mysql 保存日志到数据库 - const result = await ctx.app.mysql.get('wms').insert('wms_api_log', { - method: logData.method || '', - v: logData.v || '', - url: logData.url || '', - created_at: ctx.app.mysql.get('wms').literals.now, - body: logData.body || '', - result: logData.result || '', - use_time: logData.use_time || 0, - }); - - return result; - - } catch (error) { - ctx.logger.error('保存奇门接口日志失败: ' + error.message); - // 可以选择记录到文件日志作为备用 - ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData)); - } - } async pda() { const { ctx, diff --git a/app/controller/im.js b/app/controller/im.js new file mode 100644 index 0000000..34bd87f --- /dev/null +++ b/app/controller/im.js @@ -0,0 +1,68 @@ +const { Controller } = require('egg'); +const crypto = require('crypto'); + +// 统一的返回格式 +const result = { + code: 0, + message: '接口错误', + data: null, +}; + +module.exports = class ImController extends Controller { + async index() { + const { ctx } = this; + + // GET请求参数sign + const queryData = ctx.query; + const receivedSign = queryData.sign; + + // 解析POST请求的body数据 + const requestData = ctx.request.body; + const im_secret = this.config.im.secret; + + // 验证签名:将请求体的base64字符串与预设的密钥进行拼接后进行sha256哈希 + if (!receivedSign) { + ctx.body = { ...result, message: 'Missing signature parameter' }; + return; + } + + // 将请求体转换为base64字符串 + let bodyBase64; + try { + bodyBase64 = Buffer.from(JSON.stringify(requestData)).toString('base64'); + } catch (err) { + ctx.body = { ...result, message: 'Invalid request body' }; + return; + } + + // 计算期望的签名 + const expectedSign = crypto + .createHash('sha256') + .update(bodyBase64 + im_secret) + .digest('hex'); + + // 比对签名(使用时间恒定的比较方法防止时序攻击) + if (!crypto.timingSafeEqual(Buffer.from(receivedSign), Buffer.from(expectedSign))) { + ctx.body = { ...result, message: 'Invalid signature' }; + return; + } + + console.log('Received IM query data:', queryData); + console.log('Received IM request data:', requestData); + + const { method, data: data_data } = requestData || {}; + + // 通配method调用service层im的不同方法 + if (method && this.service.im[method]) { + try { + const { code, message, data } = await this.service.im[method](data_data); + ctx.body = { code, message, data }; + } catch (error) { + ctx.logger.error('IM service error:', error); + ctx.body = { ...result, message: 'Service execution failed' }; + } + } else { + ctx.body = { ...result, message: 'Invalid method' }; + } + } +}; diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 07837bf..4fb637f 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -58,6 +58,14 @@ module.exports = { ORDER_PACKED: '订单打包', ORDER_SHIPPED: '订单发货', ORDER_COMPLETE: '订单完成', + ORDER_WAVE_ASSIGN: '分配波次', + ORDER_WAVE_CANCEL: '取消波次', + ORDER_STORAGE_ALLOCATE_SUCCESS: '分配储位成功', + ORDER_STORAGE_ALLOCATE_FAILED: '分配储位失败', + ORDER_STORAGE_UNALLOCATE_SUCCESS: '取消分配储位成功', + ORDER_STORAGE_UNALLOCATE_FAILED: '取消分配储位失败', + ORDER_EXPRESS_ALLOCATE_SUBMITTED: '分配快递任务已提交', + ORDER_EXPRESS_ALLOCATE_FAILED: '分配快递失败', // 库存管理 STOCK_IN: '商品入库', @@ -119,6 +127,9 @@ module.exports = { RECEIVING_DELETE_DETAIL: '删除收货明细', RECEIVING_BIND_PRODUCT: '绑定商品', RECEIVING_UPDATE_DETAIL: '修改收货明细', + RECEIVING_UPDATE: '修改收货单', + RECEIVING_REVIEW: '审核收货单', + RECEIVING_REJECT: '驳回收货单', // 货主管理 STORE_CREATE: '创建货主', @@ -152,6 +163,9 @@ module.exports = { SUCCESS: '成功', FAILED: '失败', PROCESSING: '处理中', + SUBMITTED: '已提交', + RUNNING: '进行中', + NOT_FOUND: '未找到', }, /** diff --git a/app/extend/application.js b/app/extend/application.js index c01300a..7a0c99e 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -214,6 +214,41 @@ function parseRedisCacheValue(cacheValue) { return JSON.parse(cacheValue); } + +/** + * 使用超时保护执行 Redis 命令,避免 Redis 卡顿拖慢接口响应。 + * + * @param {Object} app 应用实例。 + * @param {Promise<*>} commandPromise Redis 命令 Promise。 + * @param {string} commandName Redis 命令名。 + * @return {Promise<*>} Redis 命令执行结果。 + */ +async function withRedisCommandTimeout(app, commandPromise, commandName) { + const timeoutConfig = Number(app && app.config ? app.config.cacheRedisCommandTimeoutMs : 0); + const timeoutMs = Number.isFinite(timeoutConfig) && timeoutConfig > 0 ? timeoutConfig : 800; + + let timeoutId = null; + + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + const timeoutError = new Error(`Redis 命令执行超时: ${commandName}, timeout=${timeoutMs}ms`); + timeoutError.code = 'CACHE_REDIS_TIMEOUT'; + reject(timeoutError); + }, timeoutMs); + + if (timeoutId && typeof timeoutId.unref === 'function') { + timeoutId.unref(); + } + }); + + try { + return await Promise.race([ commandPromise, timeoutPromise ]); + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + } +} module.exports = { get businessDict() { return businessDict; @@ -284,7 +319,7 @@ module.exports = { if (ttl <= 0) { if (cacheRedis && typeof cacheRedis.del === 'function') { try { - await cacheRedis.del(cacheKey); + await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del'); } catch (error) { const logger = getCacheLogger(this); if (logger && typeof logger.warn === 'function') { @@ -299,7 +334,7 @@ module.exports = { if (cacheRedis && typeof cacheRedis.setex === 'function') { try { - await cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)); + await withRedisCommandTimeout(this, cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)), 'setex'); setLocalCacheValue(this, cacheKey, data, ttl); @@ -331,7 +366,7 @@ module.exports = { if (cacheRedis && typeof cacheRedis.del === 'function') { try { - await cacheRedis.del(cacheKey); + await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del'); } catch (error) { const logger = getCacheLogger(this); if (logger && typeof logger.warn === 'function') { @@ -355,7 +390,7 @@ module.exports = { if (cacheRedis && typeof cacheRedis.get === 'function') { try { - const data = await cacheRedis.get(cacheKey); + const data = await withRedisCommandTimeout(this, cacheRedis.get(cacheKey), 'get'); if (data === undefined || data === null) { return null; } diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js index 8d05817..b7c45ec 100644 --- a/app/lib/polo_api_client.js +++ b/app/lib/polo_api_client.js @@ -2,9 +2,6 @@ const crypto = require('crypto'); -const POLYAPI_CONFIG_CACHE_KEY = 'polo_api_client:polyapi:config'; -const POLYAPI_CONFIG_CACHE_TTL_SECONDS = 60 * 60; - /** * PolyAPI 底层 HTTP 客户端。 * 封装签名、表单编码、请求发送等通用逻辑,与业务无关。 @@ -15,124 +12,9 @@ class PoloApiClient { */ constructor(ctx) { this.ctx = ctx; - this._config = null; - this._configPromise = null; this.contenttype = 'json'; } - /** - * 按需加载并缓存 PolyAPI 配置。 - * - * 优先读取应用级缓存;缓存未命中或读取失败时,再回源数据库。 - * 数据库查到配置后,会回写到应用级缓存,缓存 TTL 为 1 小时。 - * - * @param platid - * @return {Promise} PolyAPI 配置记录。 - */ - async getConfig(platid) { - if (this._config) { - return this._config; - } - - if (!this._configPromise) { - this._configPromise = this._loadConfig(platid).then(config => { - this._config = config || null; - return this._config; - }).finally(() => { - this._configPromise = null; - }); - } - - return this._configPromise; - } - - /** - * 读取 PolyAPI 配置:先查缓存,未命中则查数据库。 - * - * @param platid - * @return {Promise} PolyAPI 配置记录。 - */ - async _loadConfig(platid) { - const cachedConfig = await this._getCachedConfig(platid); - if (cachedConfig) { - return cachedConfig; - } - - const config = await this._loadConfigFromDatabase(platid); - if (config) { - await this._setCachedConfig(config); - } - - return config; - } - - /** - * 从应用级缓存读取 PolyAPI 配置。 - * - * 缓存读取失败时,返回 null 并由调用方继续回源数据库。 - * - * @param platid - * @return {Promise} 缓存中的配置记录。 - */ - async _getCachedConfig(platid) { - if (!this.ctx.app || typeof this.ctx.app.getCacheAsync !== 'function') { - return null; - } - - try { - return await this.ctx.app.getCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${platid}`); - } catch (error) { - if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') { - this.ctx.logger.warn('[PoloApiClient._getCachedConfig] 读取缓存失败,回退数据库查询: %s', error.message); - } - - return null; - } - } - - /** - * 查询数据库中的 PolyAPI 配置。 - * - * @param platid - * @return {Promise} 数据库中的配置记录。 - */ - async _loadConfigFromDatabase(platid) { - if (!this.ctx.app || !this.ctx.app.model || typeof this.ctx.app.model.query !== 'function') { - return null; - } - - const rows = await this.ctx.app.model.query( - 'SELECT id, interface_url, platform_code, interface_name, platid, appkey, app_secret, token, version FROM wms_express_platform WHERE platid = :platid LIMIT 1', - { - replacements: { platid }, - type: this.ctx.app.model.QueryTypes.SELECT, - } - ); - - return Array.isArray(rows) && rows.length > 0 ? rows[0] : null; - } - - /** - * 将 PolyAPI 配置写回应用级缓存。 - * - * @param {object} config - PolyAPI 配置记录。 - * @return {Promise} - */ - async _setCachedConfig(config) { - if (!this.ctx.app || typeof this.ctx.app.setCacheAsync !== 'function') { - return; - } - - try { - const cacheValue = config && typeof config.toJSON === 'function' ? config.toJSON() : config; - await this.ctx.app.setCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${config.platid}`, cacheValue, POLYAPI_CONFIG_CACHE_TTL_SECONDS); - } catch (error) { - if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') { - this.ctx.logger.warn('[PoloApiClient._setCachedConfig] 写入缓存失败,继续使用数据库结果: %s', error.message); - } - } - } - /** * 发起 PolyAPI 表单 POST 请求。 * @@ -149,9 +31,8 @@ class PoloApiClient { config = {}, token, } = options; - if (!config) { - // throw new Error('未找到 polyapi 配置'); - config = await this.getConfig(633); + if (!config || !config.interface_url) { + throw new Error('[PoloApiClient.request] 未提供有效的 config,无法发送请求'); } const configWithToken = { ...config, token: token || config.token }; const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent); @@ -179,6 +60,17 @@ class PoloApiClient { } return result; } + + /** + * 发起 PolyAPI GET 请求。 + * + * @param {object} options - 请求参数。 + * @param {string} options.method - 远端接口方法名。 + * @param {object|string} [options.bizcontent={}] - 业务参数内容。 + * @param {object} [options.config={}] - 平台配置。 + * @param {string} [options.token] - 可选 token,传入时优先覆盖配置 token。 + * @return {Promise} 接口响应 data。 + */ async get(options = {}) { const { method, @@ -186,9 +78,8 @@ class PoloApiClient { config = {}, token, } = options; - if (!config) { - // throw new Error('未找到 polyapi 配置'); - config = await this.getConfig(633); + if (!config || !config.interface_url) { + throw new Error('[PoloApiClient.get] 未提供有效的 config,无法发送请求'); } const configWithToken = { ...config, token: token || config.token }; const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent); @@ -221,10 +112,11 @@ class PoloApiClient { /** * 组装签名所需的请求参数。 - * @param config - * @param method - * @param platid - * @param bizcontent + * @param {object} config 平台配置对象。 + * @param {string} method 接口方法名。 + * @param {number|string} platid 平台 ID。 + * @param {object|string} bizcontent 业务参数。 + * @return {object} 签名参数映射。 */ _buildSignMap(config, method, platid, bizcontent) { const normalizedBizcontent = bizcontent && typeof bizcontent === 'object' @@ -245,8 +137,9 @@ class PoloApiClient { /** * 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。 - * @param signMap - * @param secret + * @param {object} signMap 待签名参数映射。 + * @param {string} secret 签名密钥。 + * @return {string} 签名原文字符串。 */ _getSignText(signMap, secret) { let sb = '' + secret; @@ -259,8 +152,9 @@ class PoloApiClient { /** * MD5 摘要。 - * @param text - * @param encoding + * @param {string} text 待摘要文本。 + * @param {BufferEncoding} [encoding='utf8'] 文本编码。 + * @return {string} 十六进制 MD5 值。 */ _md5(text, encoding = 'utf8') { return crypto.createHash('md5').update(text, encoding).digest('hex'); @@ -268,7 +162,8 @@ class PoloApiClient { /** * 将参数编码为 application/x-www-form-urlencoded。 - * @param map + * @param {object} map 表单参数映射。 + * @return {string} URL 编码后的查询串。 */ _encodeForm(map) { const params = new URLSearchParams(); @@ -281,7 +176,8 @@ class PoloApiClient { /** * 格式化日期 → yyyy-MM-dd HH:mm:ss。 - * @param date + * @param {Date} date 日期对象。 + * @return {string} 格式化后的时间字符串。 */ _formatDate(date) { const pad = n => (n < 10 ? '0' + n : n); @@ -291,9 +187,10 @@ class PoloApiClient { /** * 格式化取件日期。 - * @param year - * @param month - * @param day + * @param {number} year 年。 + * @param {number} month 月。 + * @param {number} day 日。 + * @return {string} 取件日期时间字符串。 */ _formatPickupDate(year, month, day) { const pad = n => (n < 10 ? '0' + n : n); diff --git a/app/model/embargo_policy.js b/app/model/embargo_policy.js new file mode 100644 index 0000000..bfce9c9 --- /dev/null +++ b/app/model/embargo_policy.js @@ -0,0 +1,107 @@ +// app/model/embargo_policy.js +'use strict'; + +module.exports = app => { + const { INTEGER, STRING, ENUM, TEXT, DATEONLY, DATE, BOOLEAN, BIGINT } = app.Sequelize; + + const EmbargoPolicy = app.model.define('wms_embargo_policies', { + id: { + type: INTEGER.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: 'ID', + }, + policy_name: { + type: STRING(100), + allowNull: false, + comment: '策略名称', + }, + status: { + type: ENUM('ACTIVE', 'INACTIVE', 'PENDING', 'EXPIRED'), + allowNull: true, + defaultValue: 'PENDING', + comment: '状态', + }, + embargo_scope: { + type: TEXT, + allowNull: true, + comment: '禁运范围(数组)', + }, + start_date: { + type: DATEONLY, + allowNull: false, + comment: '生效开始日期', + }, + end_date: { + type: DATEONLY, + allowNull: true, + defaultValue: null, + comment: '结束日期', + }, + is_permanent: { + type: BOOLEAN, + allowNull: true, + defaultValue: false, + comment: '是否永久有效', + }, + description: { + type: TEXT, + allowNull: true, + comment: '策略描述', + }, + created_by: { + type: STRING(50), + allowNull: true, + comment: '创建人', + }, + updated_by: { + type: STRING(50), + allowNull: true, + comment: '更新人', + }, + created_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + warehouse_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + defaultValue: null, + comment: '仓库ID', + }, + }, { + tableName: 'wms_embargo_policies', + timestamps: false, + underscored: false, + comment: '禁运策略主表', + indexes: [ + { + name: 'idx_status', + fields: [ 'status' ], + }, + { + name: 'idx_dates', + fields: [ 'start_date', 'end_date' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + { + name: 'warehouse_id', + fields: [ 'warehouse_id' ], + }, + ], + }); + + return EmbargoPolicy; +}; diff --git a/app/model/express_print_record.js b/app/model/express_print_record.js index 85ce1a6..3125a68 100644 --- a/app/model/express_print_record.js +++ b/app/model/express_print_record.js @@ -144,7 +144,7 @@ module.exports = app => { comment: '操作人ID', }, warehouse_id: { - type: BIGINT(20), + type: BIGINT(20).UNSIGNED, allowNull: true, comment: '仓库ID', }, @@ -173,8 +173,14 @@ module.exports = app => { comment: '快递面单打印记录表', indexes: [ { - name: 'idx_express_id', - fields: [ 'express_id' ], + unique: true, + name: 'uk_express_print', + fields: [ 'express_id', 'print_status' ], + }, + { + unique: true, + name: 'uk_request_id', + fields: [ 'request_id' ], }, { name: 'idx_order_id', @@ -185,18 +191,37 @@ module.exports = app => { fields: [ 'express_no' ], }, { - name: 'uk_request_id', - unique: true, - fields: [ 'request_id' ], - }, - { - name: 'idx_warehouse_id', - fields: [ 'warehouse_id' ], + name: 'idx_platform', + fields: [ 'platform' ], }, { name: 'idx_print_status', fields: [ 'print_status' ], }, + { + name: 'idx_create_time', + fields: [ 'create_time' ], + }, + { + name: 'idx_batch_no', + fields: [ 'batch_no' ], + }, + { + name: 'idx_template_id', + fields: [ 'template_id' ], + }, + { + name: 'idx_printer_config_id', + fields: [ 'printer_config_id' ], + }, + { + name: 'idx_print_time', + fields: [ 'print_time' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, ], }); diff --git a/app/model/operation_log.js b/app/model/operation_log.js index ad765c8..e72fca3 100644 --- a/app/model/operation_log.js +++ b/app/model/operation_log.js @@ -3,7 +3,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, BIGINT, DATE, ENUM, JSON, TEXT } = app.Sequelize; + const { STRING, BIGINT, DATE, ENUM, JSON, TEXT } = app.Sequelize; const OperationLog = app.model.define('operation_log', { id: { @@ -49,8 +49,8 @@ module.exports = app => { comment: '外部日志ID', }, warehouse_id: { - type: INTEGER(11), - allowNull: true, + type: BIGINT(20).UNSIGNED, + allowNull: false, comment: '仓库ID', }, before_changes: { diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 55d8429..d692a2c 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -216,8 +216,8 @@ module.exports = app => { allowNull: true, comment: '系统物流公司名称', }, - - basket_number:{ + + basket_number: { type: STRING(50), allowNull: true, comment: '筐号', @@ -393,6 +393,12 @@ module.exports = app => { defaultValue: 0, comment: '波次ID,0表示未分配', }, + wave_no: { + type: STRING(50), + allowNull: false, + defaultValue: '', + comment: '波次号,空字符串表示未分配', + }, // 状态机字段 post_status: { type: ENUM(...StatusEnum.POST_STATUS), diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index d7497b9..f87bbbd 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -15,6 +15,7 @@ const { buildTableComment, buildTableOptions, buildIndexOptions, + buildColumnLine, buildColumnLines, buildIndexLines, parseManagedTableName, @@ -109,9 +110,33 @@ module.exports = app => { class OrderDeliveryFactory { constructor() { this.modelCache = new Map(); + this.inflightInitCache = new Map(); this.app = app; } + /** + * 复用并发中的模型初始化,避免重复执行建模与结构自检。 + * @param {string} lockKey 并发锁键。 + * @param {Function} initializer 初始化函数。 + * @return {Promise} 模型实例。 + */ + async runModelInitializer(lockKey, initializer) { + if (this.inflightInitCache.has(lockKey)) { + return await this.inflightInitCache.get(lockKey); + } + + const initPromise = (async () => { + try { + return await initializer(); + } finally { + this.inflightInitCache.delete(lockKey); + } + })(); + + this.inflightInitCache.set(lockKey, initPromise); + return await initPromise; + } + /** * 获取配送域车道常量。 * @return {Object} 车道常量。 @@ -198,32 +223,39 @@ module.exports = app => { */ async getModelByTableName(tableName) { const cacheKey = `table_${tableName}`; + const lockKey = `init_table_${tableName}`; if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } - try { - const parsed = parseManagedTableName(tableName); - if (!parsed) { - throw new Error(`表 ${tableName} 不是订单工厂管理表`); + return await this.runModelInitializer(lockKey, async () => { + if (this.modelCache.has(cacheKey)) { + return this.modelCache.get(cacheKey); } - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - throw new Error(`表 ${tableName} 不存在`); + try { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + throw new Error(`表 ${tableName} 不是订单工厂管理表`); + } + + const tableExists = await this.checkTableExists(tableName); + if (!tableExists) { + throw new Error(`表 ${tableName} 不存在`); + } + + const DynamicModel = this.buildManagedModel(parsed.warehouseId, parsed.type, tableName); + await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId, DynamicModel); + + this.modelCache.set(cacheKey, DynamicModel); + return DynamicModel; + + } catch (error) { + this.app.logger.error(`获取模型失败 ${tableName}:`, error); + throw error; } - - const DynamicModel = this.buildManagedModel(parsed.warehouseId, parsed.type, tableName); - await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId, DynamicModel); - - this.modelCache.set(cacheKey, DynamicModel); - return DynamicModel; - - } catch (error) { - this.app.logger.error(`获取模型失败 ${tableName}:`, error); - throw error; - } + }); } /** @@ -237,29 +269,39 @@ module.exports = app => { const modelType = this.resolveModelType(type); const tableName = this.generateTableName(warehouseIdStr, modelType); const cacheKey = `${warehouseIdStr}_${modelType}`; + const tableCacheKey = `table_${tableName}`; + // 与 getModelByTableName 统一使用“物理表名锁”,避免不同入口并发重复初始化同一张表 + const lockKey = `init_table_${tableName}`; // 检查缓存 if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } - try { - const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName); - await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel); + return await this.runModelInitializer(lockKey, async () => { + if (this.modelCache.has(cacheKey)) { + return this.modelCache.get(cacheKey); + } - // 设置关联关系 - this.setupAssociations(DynamicModel, warehouseIdStr, modelType); + try { + const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName); + await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel); - // 缓存模型 - this.modelCache.set(cacheKey, DynamicModel); - this.app.logger.info(`创建动态模型成功: ${tableName}`); + // 设置关联关系 + this.setupAssociations(DynamicModel, warehouseIdStr, modelType); - return DynamicModel; + // 缓存模型(按业务键和表名键双写,避免跨入口重复初始化) + this.modelCache.set(cacheKey, DynamicModel); + this.modelCache.set(tableCacheKey, DynamicModel); + this.app.logger.info(`创建动态模型成功: ${tableName}`); - } catch (error) { - this.app.logger.error(`创建动态模型失败 ${tableName}:`, error); - throw error; - } + return DynamicModel; + + } catch (error) { + this.app.logger.error(`创建动态模型失败 ${tableName}:`, error); + throw error; + } + }); } /** @@ -557,6 +599,11 @@ module.exports = app => { const tableColumns = await queryInterface.describeTable(tableName); const expectedAttributes = this.getTableAttributes(type); const columnNames = new Set(Object.keys(tableColumns || {})); + const quotedTableName = quoteIdentifier(tableName); + + // 收集需要检查的列 + const notNullColumns = []; + const numericColumns = []; for (const columnName of Object.keys(expectedAttributes)) { if (!columnNames.has(columnName)) { @@ -564,45 +611,69 @@ module.exports = app => { } const expectedAttribute = expectedAttributes[columnName]; - const quotedTableName = quoteIdentifier(tableName); - const quotedColumnName = quoteIdentifier(columnName); if (expectedAttribute.allowNull === false) { - const [ nullRows ] = await sequelize.query( - `SELECT 1 AS violationFound FROM ${quotedTableName} WHERE ${quotedColumnName} IS NULL LIMIT 1` - ); - - if (Array.isArray(nullRows) && nullRows.length > 0) { - throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL'); - } + notNullColumns.push(columnName); } const numericConstraint = parseNumericConstraint(expectedAttribute); - - if (!numericConstraint) { - continue; + if (numericConstraint) { + numericColumns.push({ columnName, numericConstraint }); } + } - const [ rangeRows ] = await sequelize.query( - `SELECT 1 AS violationFound FROM ${quotedTableName} - WHERE ${quotedColumnName} IS NOT NULL - AND (${quotedColumnName} < :minValue OR ${quotedColumnName} > :maxValue) - LIMIT 1`, - { - replacements: { - minValue: numericConstraint.min, - maxValue: numericConstraint.max, - }, + // 一条 SQL 检查所有 NOT NULL 约束 + if (notNullColumns.length > 0) { + const conditions = notNullColumns + .map(col => `${quoteIdentifier(col)} IS NULL`) + .join(' OR '); + const selectCols = notNullColumns + .map(col => `MAX(CASE WHEN ${quoteIdentifier(col)} IS NULL THEN 1 ELSE 0 END) AS ${quoteIdentifier(col)}`) + .join(', '); + const [ nullRows ] = await sequelize.query( + `SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1` + ); + + if (Array.isArray(nullRows) && nullRows.length > 0) { + const row = nullRows[0]; + for (const columnName of notNullColumns) { + if (row[columnName] === 1) { + throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL'); + } } + } + } + + // 一条 SQL 检查所有数值范围约束 + if (numericColumns.length > 0) { + const selectCols = numericColumns + .map(({ columnName, numericConstraint }) => { + const qCol = quoteIdentifier(columnName); + return `MAX(CASE WHEN ${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}) THEN 1 ELSE 0 END) AS ${quoteIdentifier(columnName)}`; + }) + .join(', '); + const conditions = numericColumns + .map(({ columnName, numericConstraint }) => { + const qCol = quoteIdentifier(columnName); + return `(${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}))`; + }) + .join(' OR '); + const [ rangeRows ] = await sequelize.query( + `SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1` ); if (Array.isArray(rangeRows) && rangeRows.length > 0) { - throw buildManagedTableConstraintError( - tableName, - columnName, - 'NUMERIC_RANGE', - `expected=[${numericConstraint.min}, ${numericConstraint.max}]` - ); + const row = rangeRows[0]; + for (const { columnName, numericConstraint } of numericColumns) { + if (row[columnName] === 1) { + throw buildManagedTableConstraintError( + tableName, + columnName, + 'NUMERIC_RANGE', + `expected=[${numericConstraint.min}, ${numericConstraint.max}]` + ); + } + } } } } @@ -628,14 +699,60 @@ module.exports = app => { return false; } - if (tableExists) { - await this.assertManagedTableDataConstraints(tableName, modelType); + if (!tableExists) { + await dynamicModel.sync({ force: false }); + return true; } - await dynamicModel.sync({ alter: true }); + await this.assertManagedTableDataConstraints(tableName, modelType); + await this.alterManagedTableSchema(tableName, modelType, warehouseId, dynamicModel); return true; } + /** + * 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} dynamicModel 已构建的动态模型(用于索引同步)。 + * @return {Promise} + */ + async alterManagedTableSchema(tableName, type, warehouseId, dynamicModel) { + const queryInterface = this.app.model.getQueryInterface(); + const sequelize = this.app.model; + const actualColumns = await queryInterface.describeTable(tableName); + const expectedAttributes = this.getTableAttributes(type); + const quotedTableName = quoteIdentifier(tableName); + const actualColumnNames = new Set(Object.keys(actualColumns || {})); + const expectedColumnNames = Object.keys(expectedAttributes); + const clauses = []; + + // ADD 新增列 / CHANGE 变更列 + for (const columnName of expectedColumnNames) { + const columnDef = buildColumnLine(columnName, expectedAttributes[columnName]); + if (!actualColumnNames.has(columnName)) { + clauses.push(`ADD COLUMN ${columnDef}`); + } else { + clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`); + } + } + + // DROP 多余列(现有表有但期望模型没有的列) + const expectedColumnSet = new Set(expectedColumnNames); + for (const columnName of actualColumnNames) { + if (!expectedColumnSet.has(columnName)) { + clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`); + } + } + + if (clauses.length > 0) { + await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`); + } + + // 索引同步仍委托 Sequelize sync({ alter: true }) 处理(仅触发索引差异) + await dynamicModel.sync({ alter: true }); + } + /** * 获取当前库中已存在的订单工厂目标表。 * @return {Promise>} 目标表名列表。 @@ -720,6 +837,7 @@ module.exports = app => { */ clearCache() { this.modelCache.clear(); + this.inflightInitCache.clear(); clearShardWarehouseValidationCache(this.app); this.app.logger.info('模型缓存已清理'); } diff --git a/app/model/order_delivery_table_schema.js b/app/model/order_delivery_table_schema.js index 0f8e6d9..70a377a 100644 --- a/app/model/order_delivery_table_schema.js +++ b/app/model/order_delivery_table_schema.js @@ -236,10 +236,20 @@ function formatDefaultValue(defaultValue) { * @return {string} DDL 列片段。 */ function buildColumnLine(columnName, attribute) { - const parts = [ `\`${columnName}\``, attribute.type && typeof attribute.type.toSql === 'function' - ? attribute.type.toSql() - : String(attribute.type || ''), - ]; + let typeSql; + + if (attribute.type && Array.isArray(attribute.type.values)) { + // ENUM 类型:type.toSql() 内部调 this.sequelize.escape(),sequelize 引用可能未绑定 + // 直接用安全转义构造,避免依赖 sequelize 实例 + const escaped = attribute.type.values.map(v => `'${String(v).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`).join(', '); + typeSql = `ENUM(${escaped})`; + } else if (attribute.type && typeof attribute.type.toSql === 'function') { + typeSql = attribute.type.toSql(); + } else { + typeSql = String(attribute.type || ''); + } + + const parts = [ `\`${columnName}\``, typeSql ]; if (attribute.allowNull === false) { parts.push('NOT NULL'); @@ -515,6 +525,7 @@ module.exports = { buildTableComment, buildTableOptions, buildIndexOptions, + buildColumnLine, buildColumnLines, buildIndexLines, parseManagedTableName, diff --git a/app/model/picking_strategy.js b/app/model/picking_strategy.js new file mode 100644 index 0000000..34b7a2f --- /dev/null +++ b/app/model/picking_strategy.js @@ -0,0 +1,167 @@ +// app/model/picking_strategy.js +'use strict'; + +module.exports = app => { + const { BIGINT, INTEGER, STRING, TINYINT, BOOLEAN, JSON, TEXT, DATE } = app.Sequelize; + + const PickingStrategy = app.model.define('wms_picking_strategy', { + id: { + type: INTEGER, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '策略ID', + }, + strategy_name: { + type: STRING(100), + allowNull: false, + comment: '策略名称', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + strategy_type: { + type: TINYINT, + allowNull: false, + comment: '策略类型:1-散单 2-团购', + }, + status: { + type: TINYINT, + allowNull: true, + defaultValue: 1, + comment: '状态:1-启用 0-停用', + }, + order_min_sku: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '订单最小SKU种类数', + }, + order_max_sku: { + type: INTEGER, + allowNull: true, + defaultValue: 999, + comment: '订单最大SKU种类数', + }, + order_min_qty: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '订单最小商品总数', + }, + order_max_qty: { + type: INTEGER, + allowNull: true, + defaultValue: 999, + comment: '订单最大商品总数', + }, + min_same_structure: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '最小相同结构订单数', + }, + max_same_structure: { + type: INTEGER, + allowNull: true, + defaultValue: 999, + comment: '最大相同结构订单数', + }, + require_same_express: { + type: BOOLEAN, + allowNull: true, + defaultValue: false, + comment: '是否要求相同快递', + }, + allow_cross_owner: { + type: BOOLEAN, + allowNull: true, + defaultValue: true, + comment: '是否允许跨货主', + }, + batch_mode: { + type: TINYINT, + allowNull: false, + comment: '拣货模式:1-单品单件 2-先拣后分 3-边拣边分 4-边拣边分H型 5-播种墙 6-流利架', + }, + batch_max_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 20, + comment: '批次最大订单数', + }, + batch_max_skus: { + type: INTEGER, + allowNull: true, + defaultValue: 50, + comment: '批次最大SKU总数', + }, + group_batch_max_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 1, + comment: '团购批次最大订单数(相同结构)', + }, + allowed_owners: { + type: JSON, + allowNull: true, + comment: '允许的货主ID列表', + }, + allowed_expresses: { + type: JSON, + allowNull: true, + comment: '允许的快递编码列表', + }, + allowed_provinces: { + type: JSON, + allowNull: true, + comment: '允许的省份列表', + }, + allowed_platforms: { + type: JSON, + allowNull: true, + comment: '允许的平台列表', + }, + description: { + type: TEXT, + allowNull: true, + comment: '策略描述', + }, + creator_name: { + type: STRING(50), + allowNull: true, + comment: '创建人姓名', + }, + create_time: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_picking_strategy', + timestamps: false, + underscored: false, + comment: '拣货策略配置表', + indexes: [ + { + name: 'idx_warehouse_type', + fields: [ 'warehouse_id', 'strategy_type', 'status' ], + }, + { + name: 'idx_batch_mode', + fields: [ 'batch_mode', 'strategy_type' ], + }, + ], + }); + + return PickingStrategy; +}; diff --git a/app/model/platform_print_config.js b/app/model/platform_print_config.js new file mode 100644 index 0000000..0afc346 --- /dev/null +++ b/app/model/platform_print_config.js @@ -0,0 +1,96 @@ +// app/model/platform_print_config.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + + const PlatformPrintConfig = app.model.define('wms_platform_print_config', { + id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + platform: { + type: STRING(50), + allowNull: false, + unique: true, + comment: '平台名称', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台代码', + }, + print_port: { + type: STRING(20), + allowNull: false, + comment: '打印服务端口', + }, + print_url: { + type: STRING(200), + allowNull: true, + comment: '打印服务URL', + }, + protocol_type: { + type: STRING(20), + allowNull: true, + defaultValue: 'WEBSOCKET', + comment: '协议类型:WEBSOCKET,HTTP', + }, + status: { + type: STRING(20), + allowNull: true, + defaultValue: 'ACTIVE', + comment: '状态:ACTIVE-启用,DISABLED-禁用', + }, + retry_count: { + type: INTEGER, + allowNull: true, + defaultValue: 3, + comment: '重试次数', + }, + timeout_seconds: { + type: INTEGER, + allowNull: true, + defaultValue: 30, + comment: '超时时间(秒)', + }, + description: { + type: STRING(200), + allowNull: true, + comment: '描述', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_platform_print_config', + timestamps: false, + underscored: false, + comment: '平台打印端口配置表', + indexes: [ + { + name: 'uk_platform', + unique: true, + fields: [ 'platform' ], + }, + { + name: 'idx_platform_code', + fields: [ 'platform_code' ], + }, + ], + }); + + return PlatformPrintConfig; +}; diff --git a/app/model/print_log.js b/app/model/print_log.js new file mode 100644 index 0000000..dc0a3e1 --- /dev/null +++ b/app/model/print_log.js @@ -0,0 +1,98 @@ +// app/model/print_log.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TEXT, JSON, DATE } = app.Sequelize; + + const PrintLog = app.model.define('wms_print_log', { + id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + print_record_id: { + type: BIGINT, + allowNull: false, + comment: '打印记录ID', + }, + log_type: { + type: STRING(20), + allowNull: false, + comment: '日志类型:CONNECT-连接,PRINT-打印,RETRY-重试,ERROR-错误,SUCCESS-成功', + }, + log_level: { + type: STRING(10), + allowNull: true, + defaultValue: 'INFO', + comment: '日志级别:INFO,WARN,ERROR', + }, + log_content: { + type: TEXT, + allowNull: false, + comment: '日志内容', + }, + request_data: { + type: JSON, + allowNull: true, + comment: '请求数据', + }, + response_data: { + type: JSON, + allowNull: true, + comment: '响应数据', + }, + websocket_status: { + type: STRING(20), + allowNull: true, + comment: 'WebSocket状态', + }, + error_code: { + type: STRING(50), + allowNull: true, + comment: '错误代码', + }, + ip_address: { + type: STRING(50), + allowNull: true, + comment: 'IP地址', + }, + user_agent: { + type: STRING(500), + allowNull: true, + comment: '用户代理', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_print_log', + timestamps: false, + underscored: false, + comment: '打印日志表', + indexes: [ + { + name: 'idx_print_record', + fields: [ 'print_record_id' ], + }, + { + name: 'idx_log_type', + fields: [ 'log_type' ], + }, + { + name: 'idx_create_time', + fields: [ 'create_time' ], + }, + { + name: 'idx_error_code', + fields: [ 'error_code' ], + }, + ], + }); + + return PrintLog; +}; diff --git a/app/model/print_template.js b/app/model/print_template.js index fa08f22..fdf4ace 100644 --- a/app/model/print_template.js +++ b/app/model/print_template.js @@ -46,7 +46,7 @@ module.exports = app => { comment: '页面高度(mm)', }, warehouse_id: { - type: BIGINT(20), + type: BIGINT(20).UNSIGNED, comment: '关联仓库ID', }, is_default: { diff --git a/app/model/stock_unit.js b/app/model/stock_unit.js index 44b0d1c..849eb9b 100644 --- a/app/model/stock_unit.js +++ b/app/model/stock_unit.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, DATE } = app.Sequelize; + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; const StockUnit = app.model.define('wms_stock_unit', { id: { @@ -12,7 +12,7 @@ module.exports = app => { comment: '主键ID', }, warehouse_id: { - type: INTEGER, + type: BIGINT(20).UNSIGNED, allowNull: true, defaultValue: null, comment: '仓库ID,NULL表示系统默认', diff --git a/app/model/store.js b/app/model/store.js index 4452456..0fbf2c3 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -3,10 +3,15 @@ module.exports = app => { const { BIGINT, STRING, DATE, TINYINT, JSON: JSON_TYPE } = app.Sequelize; const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; + const DEFAULT_MAX_WAVE_QUANTITY = 500; const DEFAULT_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, + min_group_order_fetch_quantity: 13, default_express_code: 'STO', default_platform_code: 'TB', + group_wave_prefix: 'B', + delete_order_wave_prefix: 'A', }); const normalizeSubjectConfigText = (value, defaultValue) => { @@ -34,6 +39,12 @@ module.exports = app => { throw new Error(`${fieldName} 必须是布尔值`); }; + /** + * 规范化主体配置,确保默认值与字段约束一致。 + * + * @param {Object|string|null|undefined} rawValue 主体配置原始值。 + * @return {Object} 规范化后的主体配置对象。 + */ const normalizeSubjectConfig = rawValue => { if (rawValue === undefined || rawValue === null || rawValue === '') { return { ...DEFAULT_SUBJECT_CONFIG }; @@ -67,6 +78,28 @@ module.exports = app => { normalized.max_notice_webhook_count = limit; } + const rawMaxWaveQuantity = parsed.max_wave_quantity; + if (rawMaxWaveQuantity === undefined || rawMaxWaveQuantity === null || rawMaxWaveQuantity === '') { + normalized.max_wave_quantity = DEFAULT_MAX_WAVE_QUANTITY; + } else { + const maxWaveQuantity = Number(rawMaxWaveQuantity); + if (!Number.isInteger(maxWaveQuantity) || maxWaveQuantity <= 0) { + throw new Error('subject_config.max_wave_quantity 必须是大于 0 的整数'); + } + normalized.max_wave_quantity = maxWaveQuantity; + } + + const rawMinGroupOrderFetchQuantity = parsed.min_group_order_fetch_quantity; + if (rawMinGroupOrderFetchQuantity === undefined || rawMinGroupOrderFetchQuantity === null || rawMinGroupOrderFetchQuantity === '') { + normalized.min_group_order_fetch_quantity = DEFAULT_SUBJECT_CONFIG.min_group_order_fetch_quantity; + } else { + const minGroupOrderFetchQuantity = Number(rawMinGroupOrderFetchQuantity); + if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { + throw new Error('subject_config.min_group_order_fetch_quantity 必须是大于 0 的整数'); + } + normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity; + } + normalized.default_express_code = normalizeSubjectConfigText( parsed.default_express_code, DEFAULT_SUBJECT_CONFIG.default_express_code @@ -76,6 +109,36 @@ module.exports = app => { DEFAULT_SUBJECT_CONFIG.default_platform_code ); + const rawGroupWavePrefix = parsed.group_wave_prefix; + if (rawGroupWavePrefix === undefined || rawGroupWavePrefix === null || rawGroupWavePrefix === '') { + normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix; + } else { + const groupWavePrefix = String(rawGroupWavePrefix).trim(); + if (groupWavePrefix === '') { + normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix; + } else { + if (groupWavePrefix.length > 5) { + throw new Error('subject_config.group_wave_prefix 最多 5 个字符'); + } + normalized.group_wave_prefix = groupWavePrefix; + } + } + + const rawDeleteOrderWavePrefix = parsed.delete_order_wave_prefix; + if (rawDeleteOrderWavePrefix === undefined || rawDeleteOrderWavePrefix === null || rawDeleteOrderWavePrefix === '') { + normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix; + } else { + const deleteOrderWavePrefix = String(rawDeleteOrderWavePrefix).trim(); + if (deleteOrderWavePrefix === '') { + normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix; + } else { + if (deleteOrderWavePrefix.length > 5) { + throw new Error('subject_config.delete_order_wave_prefix 最多 5 个字符'); + } + normalized.delete_order_wave_prefix = deleteOrderWavePrefix; + } + } + if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) { normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled'); } diff --git a/app/model/system_log.js b/app/model/system_log.js new file mode 100644 index 0000000..214c50c --- /dev/null +++ b/app/model/system_log.js @@ -0,0 +1,94 @@ +// app/model/system_log.js +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TEXT, DATE, INTEGER } = app.Sequelize; + + const SystemLog = app.model.define('wms_system_log', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: 'ID', + }, + method: { + type: STRING(100), + allowNull: true, + comment: '方法名', + }, + v: { + type: STRING(50), + allowNull: true, + comment: '版本', + }, + url: { + type: TEXT, + allowNull: true, + comment: '请求URL', + }, + created_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + body: { + type: TEXT('long'), + allowNull: true, + comment: '请求体', + }, + result: { + type: TEXT('long'), + allowNull: true, + comment: '响应体', + }, + use_time: { + type: INTEGER, + allowNull: true, + comment: '耗时', + }, + updated_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + delete_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + headers: { + type: TEXT, + allowNull: true, + comment: '请求头', + }, + auth: { + type: TEXT, + allowNull: true, + comment: '认证信息', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '门店ID', + }, + device: { + type: STRING(10), + allowNull: true, + comment: '设备', + }, + }, { + tableName: 'wms_system_log', + timestamps: false, + underscored: false, + comment: '系统日志表', + indexes: [ + { + name: 'store_id', + fields: [ 'store_id' ], + }, + ], + }); + + return SystemLog; +}; diff --git a/app/model/wave_batch.js b/app/model/wave_batch.js new file mode 100644 index 0000000..5e8196d --- /dev/null +++ b/app/model/wave_batch.js @@ -0,0 +1,185 @@ +// app/model/wave_batch.js +'use strict'; + +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE, TINYINT, BOOLEAN } = app.Sequelize; + + const WaveBatch = app.model.define('wms_wave_batch', { + wave_id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '波次ID', + }, + wave_no: { + type: STRING(50), + allowNull: false, + comment: '波次编号,如WAVE202401001', + }, + wave_type: { + type: TINYINT, + allowNull: false, + defaultValue: 1, + comment: '波次类型:1-团购 2-散单', + }, + wave_status: { + type: TINYINT, + allowNull: false, + defaultValue: 0, + comment: '波次状态:-1-已取消 0-自动加团中 1-已就绪 2-已打印 3-拣货中 4-拣货完成 5-复核完成 6-打包完成', + }, + total_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 0, + comment: '总订单数', + }, + processed_orders: { + type: INTEGER, + allowNull: true, + defaultValue: 0, + comment: '已处理订单数', + }, + picking_operator: { + type: STRING(50), + allowNull: true, + comment: '拣货员', + }, + picking_start_time: { + type: DATE, + allowNull: true, + comment: '拣货开始时间', + }, + picking_end_time: { + type: DATE, + allowNull: true, + comment: '拣货结束时间', + }, + print_operator: { + type: STRING(50), + allowNull: true, + comment: '打印员', + }, + print_time: { + type: DATE, + allowNull: true, + comment: '打印时间', + }, + print_count: { + type: INTEGER, + allowNull: true, + defaultValue: 0, + comment: '打印次数', + }, + check_operator: { + type: STRING(50), + allowNull: true, + comment: '校验员', + }, + check_time: { + type: DATE, + allowNull: true, + comment: '校验时间', + }, + check_result: { + type: TINYINT, + allowNull: true, + comment: '校验结果', + }, + priority: { + type: TINYINT, + allowNull: true, + defaultValue: 5, + comment: '优先级 1-5', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + creator: { + type: STRING(50), + allowNull: false, + comment: '创建人', + }, + create_time: { + type: DATE, + allowNull: true, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + item_detail_machine: { + type: STRING(1024), + allowNull: true, + comment: '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key', + }, + item_part_type: { + type: STRING(32), + allowNull: true, + comment: '结构来源类型:items_hash/items', + }, + item_part: { + type: STRING(255), + allowNull: true, + comment: '结构主键(items_hash或items摘要)', + }, + distinguish_express: { + type: BOOLEAN, + allowNull: false, + defaultValue: 0, + comment: '是否区分快递 0否1是', + }, + logistics_name: { + type: STRING(128), + allowNull: true, + comment: '快递名称(区分快递时参与匹配)', + }, + item_snapshot_key: { + type: STRING(255), + allowNull: true, + comment: '结构快照键', + }, + }, { + tableName: 'wms_wave_batch', + timestamps: false, + underscored: false, + indexes: [ + { + name: 'idx_wave_status', + fields: [ 'wave_status', 'create_time' ], + }, + { + name: 'idx_wave_no', + fields: [ 'wave_no' ], + }, + { + name: 'idx_warehouse', + fields: [ 'warehouse_id', 'wave_status' ], + }, + { + name: 'idx_creator', + fields: [ 'creator', 'create_time' ], + }, + { + name: 'idx_wave_fast_group', + fields: [ 'warehouse_id', 'wave_type', 'wave_status', 'item_part_type', 'item_part', 'distinguish_express', 'logistics_name' ], + }, + { + name: 'idx_wave_snapshot_key', + fields: [ 'item_snapshot_key' ], + }, + { + name: 'idx_wave_item_machine_prefix', + fields: [ { name: 'item_detail_machine', length: 191 } ], + }, + ], + }); + + return WaveBatch; +}; \ No newline at end of file diff --git a/app/router.js b/app/router.js index 67aa9a3..6db78f4 100644 --- a/app/router.js +++ b/app/router.js @@ -37,10 +37,8 @@ module.exports = app => { // 临时 fileWriter 消费入口 router.get('/__temp/file-writer/consume', controller.tempFileWriter.consume); - // Polo API 测试入口 - router.get('/testPoloApi/:platid', controller.home.testPoloApi); - router.get('/PoloApiGetWayBillCondition/:platid', controller.home.PoloApiGetWayBillCondition); - // 测试接口 router.get('/testSendData', controller.home.testSendData); + // IM交互入口 + router.post('/im', controller.im.index); }; diff --git a/app/service/im.js b/app/service/im.js new file mode 100644 index 0000000..7d66c3f --- /dev/null +++ b/app/service/im.js @@ -0,0 +1,171 @@ +'use strict'; +/** + * IM 相关服务 + * @author 刘付明仁 2026-05-01 创建 + * 返回通用格式:{ code: number, message: string, data: any } + * code: 200 表示成功,其他表示失败 + * message: 错误或成功消息 + * data: 具体数据内容,成功时通常包含请求结果,失败时可以为 null 或错误详情 + */ +const Service = require('egg').Service; + +class ImService extends Service { + async ping(data) { + const { requestId } = data || {}; + return { + code: 200, + message: 'pong', + data: { + requestId, + }, + }; + } + async ssoCodeToId(data) { + const { code } = data || {}; + const safeCode = String(code || '').trim(); + + if (!safeCode) { + return { + code: 400, + message: 'code不能为空', + data: null, + }; + } + // 测试例外,如果code以"test-"开头,则直接返回模拟数据 + if (safeCode.startsWith('test-')) { + return { + code: 200, + message: 'success', + data: { + employees_id: 4, + employees_name: '阿猫', + subject: { + id: 100000, + name: '测试仓', + type: 'warehouse', + }, + avatar: '', + }, + }; + } + const cacheKey = `im:sso:code:${safeCode}`; + const cachedUser = await this.app.getCacheAsync(cacheKey); + + if (!cachedUser || !cachedUser.employees_id || !cachedUser.employees_name || !cachedUser.subject) { + return { + code: 404, + message: 'code无效或已过期', + data: null, + }; + } + + await this.app.delCacheAsync(cacheKey); + const resultData = { + code: 200, + message: 'success', + data: { + employees_id: cachedUser.employees_id, + employees_name: cachedUser.employees_name, + subject: cachedUser.subject, + avatar: cachedUser.avatar, + }, + }; + console.log('SSO code converted to user info:', resultData); + return resultData; + } + /** + * 获取主体员工信息 + * @param data + */ + async getStoreEmployees(data) { + const { store_id } = data || {}; + const safeStoreId = Number(store_id); + if (!safeStoreId) { + return { + code: 400, + message: 'store_id不能为空或无效', + data: null, + }; + } + + const store = await this.ctx.model.Store.findByPk(safeStoreId, { + attributes: [ 'id', 'company_name', 'project' ], + raw: true, + }); + + if (!store) { + return { + code: 404, + message: '主体不存在', + data: null, + }; + } + + const employees = await this.ctx.model.AccountStoreEmployee.findAll({ + where: { + store_id: safeStoreId, + status: 1, + }, + attributes: [ 'id', 'real_name' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (!employees || employees.length === 0) { + return { + code: 200, + message: 'success', + data: [], + }; + } + + const employeeIds = employees.map(item => String(item.id)); + const avatarRefs = await this.ctx.model.FileReference.findAll({ + where: { + business_type: 'avater', + business_id: employeeIds, + }, + include: [{ + model: this.ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + attributes: [ 'business_id', 'created_at' ], + order: [[ 'created_at', 'DESC' ]], + }); + + const avatarMap = new Map(); + for (const ref of avatarRefs) { + const employeeId = String(ref.business_id || '').trim(); + if (!employeeId || avatarMap.has(employeeId)) { + continue; + } + avatarMap.set(employeeId, ref.file && ref.file.file_url ? ref.file.file_url : ''); + } + + const subject = { + id: String(store.id), + name: String(store.company_name || ''), + type: String(store.project || ''), + }; + + const list = employees.map(item => { + const employeeId = String(item.id); + return { + employees_id: employeeId, + employees_name: String(item.real_name || ''), + subject, + avatar: avatarMap.get(employeeId) || '', + }; + }); + + return { + code: 200, + message: 'success', + data: list, + }; + } +} + +module.exports = ImService; diff --git a/app/service/pda.js b/app/service/pda.js index de670ba..77cc5b2 100644 --- a/app/service/pda.js +++ b/app/service/pda.js @@ -60,6 +60,13 @@ class pdaService extends Service { return true; } + + /** + * 保存接口日志到系统日志模型 + * @param {Object} logData 日志数据 + * @param {number} startTime 开始时间戳 + * @returns {Promise} 写入结果 + */ async saveLog(logData, startTime) { const { ctx, @@ -77,14 +84,17 @@ class pdaService extends Service { logData.use_time = Date.now() - startTime; - // 使用 egg-mysql 保存日志到数据库 - const result = await ctx.app.mysql.get('wms').insert('wms_system_log', { + // 使用 SystemLog model 保存日志到数据库 + if (!ctx.model || !ctx.model.SystemLog) { + throw new Error('SystemLog model 不存在,无法写入系统日志'); + } + const result = await ctx.model.SystemLog.create({ method: logData.method || '', v: logData.v || '', url: logData.url || '', headers: logData.headers || '', auth: logData.auth || '', - created_at: ctx.app.mysql.get('wms').literals.now, + created_at: new Date(), body: logData.body || '', result: logData.result || '', use_time: logData.use_time || 0, diff --git a/app/service/system.js b/app/service/system.js index b3aed28..4e4d71d 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -156,6 +156,12 @@ class systemService extends Service { }; } + /** + * 保存接口日志到系统日志模型 + * @param {Object} logData 日志数据 + * @param {number} startTime 开始时间戳 + * @returns {Promise} 写入结果 + */ async saveLog(logData, startTime) { const { ctx, @@ -173,14 +179,17 @@ class systemService extends Service { logData.use_time = Date.now() - startTime; - // 使用 egg-mysql 保存日志到数据库 - const result = await ctx.app.mysql.get('wms').insert('wms_system_log', { + // 使用 SystemLog model 保存日志到数据库 + if (!ctx.model || !ctx.model.SystemLog) { + throw new Error('SystemLog model 不存在,无法写入系统日志'); + } + const result = await ctx.model.SystemLog.create({ method: logData.method || '', v: logData.v || '', url: logData.url || '', headers: logData.headers || '', auth: logData.auth || '', - created_at: ctx.app.mysql.get('wms').literals.now, + created_at: new Date(), body: logData.body || '', result: logData.result || '', use_time: logData.use_time || 0, diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index ddd612e..64a98dc 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -11,31 +11,90 @@ class dashboardService extends MainService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog); } async storeStats() { + const { ctx } = this; + const warehouseId = ctx.user?.store_id; + + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + + const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const dispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId); + const { Sequelize } = ctx.app; + const { Op } = Sequelize; + + // 待处理订单基础条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3) + const pendingBase = { + step: { [Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Op.ne]: 'padding' }, + status: { [Op.ne]: 'cancel' }, + }; + + // 今日时间范围 + const now = new Date(); + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + const todayEnd = new Date(todayStart.getTime() + 86400000); + const yesterdayStart = new Date(todayStart.getTime() - 86400000); + + const [ + totalPending, + todayNew, + yesterdayNew, + unassignedOrders, + unprintedOrders, + unpickedOrders, + pendingShipments, + todayOutbound, + interceptedOrders, + exceptionOrders, + ] = await Promise.all([ + model.count({ where: pendingBase }), + model.count({ where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }), + model.count({ where: { ...pendingBase, create_at: { [Op.gte]: yesterdayStart, [Op.lt]: todayStart } } }), + model.count({ where: { ...pendingBase, post_status: 'none' } }), + model.count({ where: { ...pendingBase, print_status: 'none' } }), + model.count({ where: { ...pendingBase, pick_status: 'none' } }), + model.count({ where: { ...pendingBase, outbound_status: { [Op.ne]: 'fin' } } }), + dispatchModel.count({ where: { dispatch_lane: 'm4', delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }), + model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }), + model.count({ where: { ...pendingBase, step: 3 } }), + ]); + + const orderTrend = yesterdayNew > 0 + ? parseFloat((((todayNew - yesterdayNew) / yesterdayNew) * 100).toFixed(1)) + : (todayNew > 0 ? 100 : 0); + + const totalForRate = pendingShipments + todayOutbound; + const outboundRate = totalForRate > 0 + ? parseFloat(((todayOutbound / totalForRate) * 100).toFixed(2)) + : 0; + + const shipmentProgress = totalPending > 0 + ? parseFloat((((totalPending - pendingShipments) / totalPending) * 100).toFixed(0)) + : 0; + const data = { code: 200, message: '成功', data: { - todayOrders: 13023, - orderTrend: 2, + todayOrders: totalPending, + orderTrend, - // 处理状态 - unassignedOrders: 15, // 未分配快递号 - unprintedOrders: 32, // 未打印 - unpickedOrders: 28, // 未拣货 + unassignedOrders, + unprintedOrders, + unpickedOrders, - // 发货相关 - pendingShipments: 6542, // 待发货 - shipmentProgress: 0, // 发货进度 + pendingShipments, + shipmentProgress, - // 出库相关 - todayOutbound: 6480, // 今日出库 - outboundRate: 49.77, // 出库完成率 + todayOutbound, + outboundRate, - // 异常订单 - interceptedOrders: 8, // 拦截订单 - exceptionOrders: 10, // 异常订单 + interceptedOrders, + exceptionOrders, }, }; + return this.success('ok', data); } async warehouseStats() { @@ -145,174 +204,101 @@ class dashboardService extends MainService { return this.success('ok', data); } async express_ratio() { + const { ctx } = this; + const warehouseId = ctx.user?.store_id; + + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + + const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const { Sequelize } = ctx.app; + + // 待处理订单条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3) + // 排除已取消的订单 + const rows = await model.findAll({ + attributes: [ + 'logistics_name', + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ], + ], + where: { + step: { [Sequelize.Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Sequelize.Op.ne]: 'padding' }, + status: { [Sequelize.Op.ne]: 'cancel' }, + }, + group: [ 'logistics_name' ], + order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]], + raw: true, + }); + + // 颜色调色板 + const colorPalette = [ + '#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A', + '#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A', + '#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7', + ]; + const data = { code: 200, message: '成功', - data: [{ - name: '顺丰速运', - value: 50250, + data: rows.map((row, index) => ({ + name: row.logistics_name || '未指定快递', + value: Number(row.value), itemStyle: { - color: '#409EFF', + color: colorPalette[index % colorPalette.length], }, - }, - { - name: '中通快递', - value: 34089, - itemStyle: { - color: '#67C23A', - }, - }, - { - name: '圆通速递', - value: 10567, - itemStyle: { - color: '#E6A23C', - }, - }, - { - name: '韵达快递', - value: 9023, - itemStyle: { - color: '#909399', - }, - }, - { - name: '申通快递', - value: 8089, - itemStyle: { - color: '#67023A', - }, - }, - { - name: '邮政EMS', - value: 4089, - itemStyle: { - color: '#97293A', - }, - }, - { - name: '京东物流', - value: 3023, - itemStyle: { - color: '#F56C6C', - }, - }, - { - name: '极兔速递', - value: 1089, - itemStyle: { - color: '#67913A', - }, - }, - { - name: '德邦快递', - value: 357, - itemStyle: { - color: '#9370DB', - }, - }, - { - name: '其他快递', - value: 5, - itemStyle: { - color: '#67313A', - }, - }, - ], + })), }; return this.success('ok', data); } async platform_distribution() { + const { ctx } = this; + const warehouseId = ctx.user?.store_id; + + if (!warehouseId) { + return this.fail('缺少仓库上下文'); + } + + const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const { Sequelize } = ctx.app; + + // 待处理订单条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3) + // 排除已取消的订单 + const rows = await model.findAll({ + attributes: [ + 'sys_platform_name', + [ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ], + ], + where: { + step: { [Sequelize.Op.in]: [ 1, 2, 3 ] }, + outbound_status: { [Sequelize.Op.ne]: 'padding' }, + status: { [Sequelize.Op.ne]: 'cancel' }, + }, + group: [ 'sys_platform_name' ], + order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]], + raw: true, + }); + + // 颜色调色板 + const colorPalette = [ + '#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A', + '#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A', + '#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7', + ]; + const data = { code: 200, message: '成功', - data: [{ - name: '抖音', - value: 50250, + data: rows.map((row, index) => ({ + name: row.sys_platform_name || '未指定平台', + value: Number(row.value), itemStyle: { - color: '#409EFF', + color: colorPalette[index % colorPalette.length], }, - }, - { - name: '拼多多', - value: 34089, - itemStyle: { - color: '#67C23A', - }, - }, - { - name: '小红书', - value: 8089, - itemStyle: { - color: '#67023A', - }, - }, - { - name: '淘宝', - value: 10567, - itemStyle: { - color: '#E6A23C', - }, - }, - { - name: '快手', - value: 9023, - itemStyle: { - color: '#909399', - }, - }, - { - name: '天猫', - value: 4089, - itemStyle: { - color: '#97293A', - }, - }, - { - name: '视频号', - value: 3023, - itemStyle: { - color: '#606399', - }, - }, - { - name: '阿里巴巴', - value: 1089, - itemStyle: { - color: '#67913A', - }, - }, - { - name: '其他', - value: 357, - itemStyle: { - color: '#9370DB', - }, - }, - { - name: 'TITOK', - value: 55, - itemStyle: { - color: '#17313A', - }, - }, - { - name: '京东', - value: 45, - itemStyle: { - color: '#F56C6C', - }, - }, - { - name: '德物', - value: 5, - itemStyle: { - color: '#67313A', - }, - }, - ], + })), }; + return this.success('ok', data); } async order_trend() { diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index a887c5b..d74ae59 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -1,6 +1,8 @@ 'use strict'; +const { type } = require('os'); const MainService = require('../main'); +const crypto = require('crypto'); class indexService extends MainService { /** @@ -11,9 +13,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; + const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; + const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -517,5 +519,55 @@ class indexService extends MainService { const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull); return this.success('ok', { data: result, code: 200 }); } + /** + * 前端请求生成唯一的登录码,后续可以通过这个登录码在IM系统中完成登录状态的绑定。登录码只写入到缓存中,不存储在数据库,具有较短的过期时间(如5分钟),并且只能使用一次。 + * @param {*} data + */ + async loginToIm() { + const { ctx } = this; + const { user } = ctx; + if (!user || !user.id) { + return this.fail('用户未登录', { code: 401 }); + } + + const employeeId = String(user.employees_id ?? '').trim(); + const employeeName = String(user.employees_name ?? '').trim(); + const subjectId = String(user.store_id ?? '').trim(); + const subjectName = String(user.store_name ?? '').trim(); + const avatar = String(user.avatar ?? '').trim(); + const storeType = String(user.store_type ?? '').trim(); + + if (!employeeId || !employeeName || !subjectId || !subjectName || !storeType) { + return this.fail('用户信息不完整', { code: 400 }); + } + + const keyName = crypto.randomBytes(32).toString('hex'); + const cacheKey = `im:sso:code:${keyName}`; + const payload = { + employees_id: employeeId, + employees_name: employeeName, + subject: { + id: subjectId, + name: subjectName, + type: storeType, + }, + avatar, + created_at: Date.now(), + }; + + await this.app.setCacheAsync(cacheKey, payload, 300); + + return this.success('ok', { + data: { + code: keyName, + employees_id: employeeId, + employees_name: employeeName, + subject: payload.subject, + store_type: storeType, + avatar, + }, + code: 200, + }); + } } module.exports = indexService; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 47c9331..0c2108c 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -38,9 +38,10 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([ 'sync_status', 'items', 'items_count', 'items_total', 'items_weight', 'wave_id', + 'wave_no', 'post_status', 'storage_status', 'pick_status', 'pack_status', 'inspection_status', 'print_status', 'claim_status', - 'outbound_status', 'lock_status', 'intercept_status','basket_number' + 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', ]); const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ @@ -181,6 +182,68 @@ class OrderBaseService extends MainService { return warehouseId === '' ? null : warehouseId; } + /** + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const { ctx } = this; + const stateUser = this.isPlainObject(ctx?.state?.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx?.user) ? ctx.user : null; + const paramsObject = this.isPlainObject(this.params) ? this.params : {}; + const paramsOperator = this.isPlainObject(paramsObject.__operator) + ? paramsObject.__operator + : (this.isPlainObject(paramsObject.operator) ? paramsObject.operator : null); + const operatorSource = stateUser || ctxUser || paramsOperator || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 获取订单日志使用的仓库ID。 + * + * 取值优先级:显式传入参数 -> 当前上下文仓库 -> ctx.user.warehouse_id -> ctx.user.store_id。 + * + * @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。 + * @return {number|string|null} 归一化后的仓库ID。 + */ + getOrderLogWarehouseId(preferredWarehouseId = null) { + const { ctx } = this; + const candidates = [ + preferredWarehouseId, + this.getWarehouseId(), + ctx?.user?.warehouse_id, + ctx?.user?.store_id, + ]; + + for (const candidate of candidates) { + if (candidate === undefined || candidate === null || candidate === '') { + continue; + } + return candidate; + } + + return null; + } + /** * 规范分页参数并限制 pageSize 上限。 * @param {Object} pageParams 分页参数。 diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js index f5efc15..c34edfc 100644 --- a/app/service/systemMethods/order/expectionOrder.js +++ b/app/service/systemMethods/order/expectionOrder.js @@ -33,6 +33,8 @@ class ExpectionOrderService extends OrderBaseService { async resolveException(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); if (!Array.isArray(requestData.ids) || requestData.ids.length === 0) { throw new Error('ids 不能为空'); @@ -61,14 +63,11 @@ class ExpectionOrderService extends OrderBaseService { try { await this.ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', - businessId: warehouseId, + businessId: logWarehouseId, operationCode: 'ORDER_RESOLVE_EXCEPTION', - operator: { - id: this.ctx.user?.employees_id || this.ctx.user?.id, - name: this.ctx.user?.employees_name || '', - }, + operator, extras: { - warehouseId, + warehouseId: logWarehouseId, orderIds, updated_count: count, message: `异常订单转正常:订单ID [${orderIds.join(', ')}],step 3 -> 2,共更新 ${count} 条`, diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 3084eac..944c065 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -3,12 +3,16 @@ const OrderBaseService = require('./base'); class OrderIndexService extends OrderBaseService { + /** + * 初始化订单系统方法的免登录、免权限、免日志和免鉴权配置。 + * @param {Egg.Context} ctx 上下文对象。 + */ constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail'; - const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail'; - const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail'; + const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail'; + const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail'; + const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -105,6 +109,54 @@ class OrderIndexService extends OrderBaseService { } } + /** + * 查询订单日志列表(不分页,返回全部)。 + * + * 仅接受 order_id 及常见别名(id、orderId), + * 仓库范围固定使用当前登录用户 store_id,避免越仓读取。 + * + * @param {Object} data 请求体。 + * @param {string|number} [data.order_id] 订单ID。 + * @param {string|number} [data.id] 订单ID别名。 + * @param {string|number} [data.orderId] 订单ID别名。 + * @return {Promise} 统一 success/fail 结构。 + */ + async queryOrderLogList(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const { + order_id: orderId, + id, + orderId: orderIdAlias, + } = requestData; + const rawOrderId = orderId ?? id ?? orderIdAlias; + + if (rawOrderId === undefined || rawOrderId === null || String(rawOrderId).trim() === '') { + return this.fail(`order_id 参数不能为空`, {}, 400); + } + + const normalizedOrderId = Number(String(rawOrderId).trim()); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + return this.fail(`order_id 参数不合法`, {}, 400); + } + + const warehouseId = this.getWarehouseId(); + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + return this.fail(`缺少当前用户仓库上下文 store_id`, {}, 400); + } + + const logs = await service.systems.operationLog.queryAllOrderLogs({ + id: normalizedOrderId, + warehouseId, + }); + + return this.success('ok', { + list: logs, + total: logs.length, + code: 200, + }); + } + } module.exports = OrderIndexService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index e9b2374..d215a2f 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -7,6 +7,16 @@ const PENDING_CANCEL_STATUS = 'cancel'; const PENDING_CANCEL_STEP = 9; const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]); const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]); +const ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_storage:request:'; +const ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const ALLOCATE_STORAGE_PROGRESS_MAP = Object.freeze({ + submitted: 5, + running: 50, + success: 100, + failed: 100, + not_found: 0, + unknown: 0, +}); class PendingOrderService extends OrderBaseService { /** @@ -17,9 +27,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -32,6 +42,60 @@ class PendingOrderService extends OrderBaseService { return await this.listByModule('pendingOrder', data); } + /** + * 查询待处理订单详情。 + * + * 仅返回订单头、商品明细与运单信息; + * 待处理详情不再返回 logs 字段,也不触发操作日志查询。 + * + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细和运单信息。 + */ + async detail(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + const tableType = this.resolveOrderTableType(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + if (orderIds.length !== 1) { + throw new Error('订单详情仅支持查询单个订单'); + } + + const orderId = orderIds[0]; + const orderModel = await this.getOrderModelByTableType(tableType, warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + raw: true, + }); + + if (!order) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId); + const orderItems = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems); + const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId); + const expresses = await this.getOrderExpressesByOrderId(orderId); + + return { + detail: order, + items: orderItemsWithImages, + expresses, + }; + } + /** * 将待处理订单反审回待审核状态。 * @param {Object} data 请求体。 @@ -48,7 +112,7 @@ class PendingOrderService extends OrderBaseService { * 仓库上下文统一取当前登录用户的 store_id。 * * @param {Object} data 请求体。 - * @return {Promise} 统一 success 包装的储位分配结果。 + * @return {Promise} 统一 success 包装的受理结果,包含 request_id 与 warehouse_id。 */ async allocateStorage(data = {}) { console.log('[PendingOrderService.allocateStorage] 原始入参', data); @@ -78,19 +142,439 @@ class PendingOrderService extends OrderBaseService { }; console.log('[PendingOrderService.allocateStorage] 归一化入参', normalizedData); + const warehouseId = this.getWarehouseId(); + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + const requestId = `storage_alloc_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`; + const taskProgressState = { + total_count: 0, + processed_count: 0, + progress: 0, + }; + + await this.setAllocateStorageTaskProgress(requestId, { + status: 'submitted', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + }); + + setImmediate(async () => { + try { + await this.setAllocateStorageTaskProgress(requestId, { + status: 'running', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + }); + + const allocationRequest = { + allow_storage_location: normalizedData.allow_storage_location, + order_ids: normalizedData.order_ids, + progress_callback: async progressPayload => { + const safeProgressPayload = this.isPlainObject(progressPayload) ? progressPayload : {}; + const totalCount = this.normalizeAllocateStorageTaskCount( + safeProgressPayload.total_count + ?? safeProgressPayload.totalCount + ?? taskProgressState.total_count, + taskProgressState.total_count + ); + const processedCount = this.normalizeAllocateStorageTaskCount( + safeProgressPayload.processed_count + ?? safeProgressPayload.processedCount + ?? taskProgressState.processed_count, + taskProgressState.processed_count + ); + + taskProgressState.total_count = Math.max(taskProgressState.total_count, totalCount); + taskProgressState.processed_count = Math.min( + taskProgressState.total_count, + Math.max(taskProgressState.processed_count, processedCount) + ); + taskProgressState.progress = this.normalizeAllocateStorageTaskProgress( + safeProgressPayload.progress, + 'running', + taskProgressState.total_count, + taskProgressState.processed_count + ); + + await this.setAllocateStorageTaskProgress(requestId, { + status: 'running', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + }); + }, + }; + + console.log('[PendingOrderService.allocateStorage] 后台开始处理储位分配', { + request_id: requestId, + allocationRequest: { + allow_storage_location: allocationRequest.allow_storage_location, + order_ids: allocationRequest.order_ids, + }, + }); + const result = await this.service.systems.orderStorageAllocation.allocateStorage(allocationRequest); + + if (taskProgressState.total_count > 0) { + taskProgressState.processed_count = taskProgressState.total_count; + } + taskProgressState.progress = 100; + + await this.setAllocateStorageTaskProgress(requestId, { + status: 'success', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + result, + }); + + // 写操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const warehouseId = this.getWarehouseId(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const orderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + + // 从 result 中提取分配结果信息 + const resultData = result && result.data ? result.data : (result || {}); + const allocatedIds = Array.isArray(resultData.allocated_order_ids) ? resultData.allocated_order_ids : []; + const shortageIds = Array.isArray(resultData.shortage_order_ids) ? resultData.shortage_order_ids : []; + const allocatedSet = new Set(allocatedIds.map(Number)); + const shortageSet = new Set(shortageIds.map(Number)); + + if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorInfo = operator || {}; + const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null; + const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system'; + const now = new Date(); + + const logRows = orderIds.map(orderId => { + const oid = Number(orderId); + const allocated = allocatedSet.has(oid); + const shortage = shortageSet.has(oid); + const operationCode = allocated + ? 'ORDER_STORAGE_ALLOCATE_SUCCESS' + : shortage + ? 'ORDER_STORAGE_ALLOCATE_FAILED' + : 'ORDER_STORAGE_ALLOCATE_SUCCESS'; + const msg = allocated + ? '储位分配成功' + : shortage + ? '储位分配失败:库存不足' + : '储位分配完成'; + return { + business_type: 'order', + business_id: String(oid), + operation_code: operationCode, + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: msg, + created_at: now, + }; + }).filter(row => Number(row.business_id) > 0); + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入成功操作日志失败,不影响业务', logErr); + } + console.log('[PendingOrderService.allocateStorage] 后台储位分配处理成功', { + request_id: requestId, + normalizedData, + result, + }); + } catch (error) { + await this.setAllocateStorageTaskProgress(requestId, { + status: 'failed', + total_count: taskProgressState.total_count, + processed_count: taskProgressState.processed_count, + progress: taskProgressState.progress, + error: error && error.message ? error.message : String(error), + }); + + // 写操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const warehouseId = this.getWarehouseId(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const orderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids ? [ normalizedData.order_ids ] : []); + + if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorInfo = operator || {}; + const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null; + const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system'; + const errorMsg = error && error.message ? error.message : String(error); + const now = new Date(); + + const logRows = orderIds.map(orderId => { + const oid = Number(orderId); + return { + business_type: 'order', + business_id: String(oid), + operation_code: 'ORDER_STORAGE_ALLOCATE_FAILED', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: `储位分配失败:${errorMsg}`, + created_at: now, + }; + }).filter(row => Number(row.business_id) > 0); + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入失败操作日志失败,不影响业务', logErr); + } + console.log('[PendingOrderService.allocateStorage] 后台储位分配处理异常', { + request_id: requestId, + normalizedData, + error_message: error?.message, + error_stack: error?.stack, + }); + } + }); + + return this.success('ok', { + request_id: requestId, + warehouse_id: warehouseId, + message: '请求已提交,后端处理中', + }); + } + + /** + * 查询待处理订单储位分配任务进度。 + * + * @param {Object} data 请求体。 + * @param {string} data.request_id 请求ID(下划线写法)。 + * @param {string} data.requestId 请求ID(驼峰写法)。 + * @return {Promise} 统一响应,包含任务状态或结果。 + */ + async allocateStorageProgress(data = {}) { + const requestId = this.normalizeAllocateStorageRequestId(data); + if (!requestId) { + return this.fail('request_id 参数不能为空', {}, 400); + } + + const cachedProgress = await this.getAllocateStorageTaskProgress(requestId); + if (!cachedProgress) { + return this.success('ok', { + request_id: requestId, + status: 'not_found', + progress: ALLOCATE_STORAGE_PROGRESS_MAP.not_found, + total_count: 0, + processed_count: 0, + }); + } + + const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown'; + const normalizedCounts = this.normalizeAllocateStorageTaskCounts(cachedProgress, normalizedStatus); + const normalizedProgress = this.normalizeAllocateStorageTaskProgress( + cachedProgress.progress, + normalizedStatus, + normalizedCounts.total_count, + normalizedCounts.processed_count + ); + + return this.success('ok', { + request_id: requestId, + ...cachedProgress, + status: normalizedStatus, + progress: normalizedProgress, + total_count: normalizedCounts.total_count, + processed_count: normalizedCounts.processed_count, + }); + } + + /** + * 规范任务进度值,兼容历史缓存中缺失 progress 字段的场景。 + * + * @param {number|string|null|undefined} progress 原始进度值。 + * @param {string} status 任务状态。 + * @param {number} totalCount 总任务数。 + * @param {number} processedCount 已处理任务数。 + * @return {number} 归一化后的进度百分比(0-100)。 + */ + normalizeAllocateStorageTaskProgress(progress, status = 'unknown', totalCount = 0, processedCount = 0) { + const parsed = Number(progress); + if (Number.isFinite(parsed)) { + return Math.min(100, Math.max(0, Math.round(parsed))); + } + + if (String(status || 'unknown').trim() === 'success') { + return 100; + } + + const normalizedTotalCount = this.normalizeAllocateStorageTaskCount(totalCount, 0); + const normalizedProcessedCount = this.normalizeAllocateStorageTaskCount(processedCount, 0); + if (normalizedTotalCount > 0) { + return Math.round(Math.min(normalizedTotalCount, normalizedProcessedCount) / normalizedTotalCount * 100); + } + + const normalizedStatus = String(status || 'unknown').trim() || 'unknown'; + if (Object.prototype.hasOwnProperty.call(ALLOCATE_STORAGE_PROGRESS_MAP, normalizedStatus)) { + return ALLOCATE_STORAGE_PROGRESS_MAP[normalizedStatus]; + } + + return ALLOCATE_STORAGE_PROGRESS_MAP.unknown; + } + + /** + * 规范任务计数字段。 + * + * @param {number|string|null|undefined} value 原始计数值。 + * @param {number} defaultValue 默认值。 + * @return {number} 归一化后的非负整数。 + */ + normalizeAllocateStorageTaskCount(value, defaultValue = 0) { + const parsed = Number(value); + if (!Number.isFinite(parsed)) { + return Math.max(0, Math.round(Number(defaultValue) || 0)); + } + + return Math.max(0, Math.round(parsed)); + } + + /** + * 规范任务总量与处理量,兼容历史缓存与别名字段。 + * + * @param {Object} payload 原始缓存载荷。 + * @param {string} status 任务状态。 + * @return {{ total_count: number, processed_count: number }} 归一化后的计数信息。 + */ + normalizeAllocateStorageTaskCounts(payload = {}, status = 'unknown') { + const safePayload = this.isPlainObject(payload) ? payload : {}; + const totalCount = this.normalizeAllocateStorageTaskCount( + safePayload.total_count + ?? safePayload.totalCount + ?? safePayload.total, + 0 + ); + let processedCount = this.normalizeAllocateStorageTaskCount( + safePayload.processed_count + ?? safePayload.processedCount + ?? safePayload.processed, + 0 + ); + + if (totalCount > 0) { + processedCount = Math.min(totalCount, processedCount); + } else { + processedCount = 0; + } + + if (String(status || 'unknown').trim() === 'success' && totalCount > 0) { + processedCount = totalCount; + } + + return { + total_count: totalCount, + processed_count: processedCount, + }; + } + + /** + * 规范待处理订单储位分配请求ID。 + * + * @param {Object} data 请求体。 + * @param {string} data.request_id 请求ID(下划线写法)。 + * @param {string} data.requestId 请求ID(驼峰写法)。 + * @return {string} 归一化后的请求ID。 + */ + normalizeAllocateStorageRequestId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.request_id || normalizedData.requestId || '').trim(); + } + + /** + * 获取待处理订单储位分配任务缓存键。 + * + * @param {string} requestId 请求ID。 + * @return {string} 缓存键。 + */ + getAllocateStorageTaskCacheKey(requestId = '') { + const normalizedRequestId = String(requestId || '').trim(); + if (!normalizedRequestId) { + return ''; + } + + return `${ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`; + } + + /** + * 写入待处理订单储位分配任务进度。 + * + * @param {string} requestId 请求ID。 + * @param {Object} payload 任务状态与结果。 + * @return {Promise} 无返回值。 + */ + async setAllocateStorageTaskProgress(requestId = '', payload = {}) { + const cacheKey = this.getAllocateStorageTaskCacheKey(requestId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizedStatus = String(safePayload.status || 'unknown').trim() || 'unknown'; + const normalizedCounts = this.normalizeAllocateStorageTaskCounts(safePayload, normalizedStatus); + const normalizedProgress = this.normalizeAllocateStorageTaskProgress( + safePayload.progress, + normalizedStatus, + normalizedCounts.total_count, + normalizedCounts.processed_count + ); + const progressPayload = { + ...safePayload, + status: normalizedStatus, + progress: normalizedProgress, + total_count: normalizedCounts.total_count, + processed_count: normalizedCounts.processed_count, + request_id: String(requestId || '').trim(), + update_time: Date.now(), + }; try { - console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 前', normalizedData); - const result = await this.service.systems.orderStorageAllocation.allocateStorage(normalizedData); - console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 成功', result); - - return this.success('ok', result); + await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS); } catch (error) { - console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 异常', { - normalizedData, - error, - }); - throw error; + this.ctx.logger.warn('[pendingOrder.allocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取待处理订单储位分配任务进度。 + * + * @param {string} requestId 请求ID。 + * @return {Promise} 任务缓存结果。 + */ + async getAllocateStorageTaskProgress(requestId = '') { + const cacheKey = this.getAllocateStorageTaskCacheKey(requestId); + 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) { + this.ctx.logger.warn('[pendingOrder.allocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; } } @@ -130,8 +614,81 @@ class PendingOrderService extends OrderBaseService { const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData); console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 成功', result); + try { + if (this.ctx.model && this.ctx.model.OperationLog) { + const operator = this.getOrderLogOperator() || {}; + const operatorId = operator.id != null ? String(operator.id) : null; + const operatorName = operator.name ? String(operator.name) : 'system'; + const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null; + const resultData = result && result.data ? result.data : {}; + const cancellableOrderIds = Array.isArray(resultData.cancellable_order_ids) ? resultData.cancellable_order_ids : []; + const now = new Date(); + const logRows = []; + + for (const orderId of cancellableOrderIds) { + const normalizedOrderId = Number(orderId); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + continue; + } + + logRows.push({ + business_type: 'order', + business_id: String(normalizedOrderId), + operation_code: 'ORDER_STORAGE_UNALLOCATE_SUCCESS', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId, + platform_code: 'SYSTEM', + message: '取消储位分配成功', + created_at: now, + }); + } + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logError) { + this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配日志失败,不影响主流程', logError); + } + return this.success('ok', result); } catch (error) { + try { + if (this.ctx.model && this.ctx.model.OperationLog) { + const rawOrderIds = Array.isArray(normalizedData.order_ids) + ? normalizedData.order_ids + : (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []); + const orderIds = [ ...new Set(rawOrderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)) ]; + + if (orderIds.length > 0) { + const operator = this.getOrderLogOperator() || {}; + const operatorId = operator.id != null ? String(operator.id) : null; + const operatorName = operator.name ? String(operator.name) : 'system'; + const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null; + const errorMessage = error && error.message ? error.message : String(error); + const now = new Date(); + const logRows = orderIds.map(orderId => ({ + business_type: 'order', + business_id: String(orderId), + operation_code: 'ORDER_STORAGE_UNALLOCATE_FAILED', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId, + platform_code: 'SYSTEM', + message: `取消储位分配失败:${errorMessage}`, + created_at: now, + })); + + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logError) { + this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配失败日志失败,不影响主流程', logError); + } + console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 异常', { normalizedData, error, @@ -195,10 +752,44 @@ class PendingOrderService extends OrderBaseService { throw new Error('分配快递号接口仅支持订单对象数组入参'); } - const { service } = this; - const result = await service.systems.express.createWaybillCodePipeline(orders); + const orderIds = [ ...new Set( + orders + .map(order => Number(order && (order.order_id || order.id))) + .filter(orderId => Number.isFinite(orderId) && orderId > 0) + ) ]; - return this.success('ok', result); + const { service } = this; + try { + const result = await service.systems.express.createWaybillCodePipeline(orders); + return this.success('ok', result); + } catch (error) { + try { + const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog; + if (orderIds.length > 0 && operationLogService && typeof operationLogService.createOperationLogs === 'function') { + const operator = this.getOrderLogOperator() || {}; + const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null; + const errorMessage = error && error.message ? String(error.message) : String(error); + + const payloads = orderIds.map(orderId => ({ + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED', + operator, + extras: { + message: `分配快递失败:${errorMessage}`, + warehouseId: logWarehouseId, + externalLogType: 'NONE', + }, + })); + + await operationLogService.createOperationLogs(payloads); + } + } catch (logError) { + this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 写入分配快递失败日志失败,不影响主流程', logError); + } + + throw error; + } } /** @@ -339,6 +930,105 @@ class PendingOrderService extends OrderBaseService { throw new Error('订单不存在或不属于当前仓库'); } + const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0); + if (ordersWithWave.length > 0) { + try { + const { Op } = this.app.Sequelize; + const WaveBatch = this.ctx.model.WaveBatch; + + const waveOrderIds = ordersWithWave + .map(order => Number(order.id)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + + if (waveOrderIds.length > 0) { + await model.update( + { + wave_id: 0, + wave_no: '', + updated_at: now, + }, + { + where: { + id: { + [Op.in]: waveOrderIds, + }, + warehouse_id: warehouseId, + }, + } + ); + } + + if (WaveBatch) { + const waveIdCountMap = new Map(); + for (const order of ordersWithWave) { + const waveId = Number(order.wave_id); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + waveIdCountMap.set(waveId, (waveIdCountMap.get(waveId) || 0) + 1); + } + + for (const [ waveId, canceledCount ] of waveIdCountMap.entries()) { + await WaveBatch.decrement('total_orders', { + by: canceledCount, + where: { + wave_id: waveId, + warehouse_id: warehouseId, + total_orders: { + [Op.gt]: 0, + }, + }, + }); + + const wave = await WaveBatch.findOne({ + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + attributes: [ 'wave_id', 'total_orders', 'wave_status' ], + raw: true, + }); + + if (!wave) { + continue; + } + + const totalOrders = Number(wave.total_orders); + const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0; + if (normalizedTotalOrders <= 0) { + await WaveBatch.update( + { + total_orders: 0, + wave_status: -1, + update_time: now, + }, + { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + } + ); + } else { + await WaveBatch.update( + { + update_time: now, + }, + { + where: { + wave_id: waveId, + warehouse_id: warehouseId, + }, + } + ); + } + } + } + } catch (waveErr) { + this.ctx.logger.warn('[PendingOrderService.cancelOrder] 清理波次关联失败,不影响订单取消', waveErr); + } + } + const updatedOrders = await model.findAll({ where, raw: true, @@ -472,6 +1162,8 @@ class PendingOrderService extends OrderBaseService { async updateOrderPlatform(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); const rawOrderIds = requestData.order_ids; if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) { @@ -515,14 +1207,11 @@ class PendingOrderService extends OrderBaseService { try { await this.ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', - businessId: warehouseId, + businessId: logWarehouseId, operationCode: 'ORDER_UPDATE_PLATFORM', - operator: { - id: this.ctx.user?.employees_id || this.ctx.user?.id, - name: this.ctx.user?.employees_name || '', - }, + operator, extras: { - warehouseId, + warehouseId: logWarehouseId, orderIds, sys_platform_code: platform.code, sys_platform_name: String(platform.name || '').trim(), @@ -561,6 +1250,8 @@ class PendingOrderService extends OrderBaseService { async updateOrderExpress(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); const rawOrderIds = requestData.order_ids; if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) { @@ -628,14 +1319,11 @@ class PendingOrderService extends OrderBaseService { try { await this.ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', - businessId: warehouseId, + businessId: logWarehouseId, operationCode: 'ORDER_UPDATE_EXPRESS', - operator: { - id: this.ctx.user?.employees_id || this.ctx.user?.id, - name: this.ctx.user?.employees_name || '', - }, + operator, extras: { - warehouseId, + warehouseId: logWarehouseId, orderIds, express_code: expressCode, sys_logistics_code: sysLogisticsCode, @@ -677,6 +1365,8 @@ class PendingOrderService extends OrderBaseService { async cloneOrder(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = this.getWarehouseId(); + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); const orderId = Number(requestData.order_id || requestData.id); if (!Number.isInteger(orderId) || orderId <= 0) { @@ -724,12 +1414,9 @@ class PendingOrderService extends OrderBaseService { businessType: 'order', businessId: orderId, operationCode: 'ORDER_CLONE_SOURCE', - operator: { - id: this.ctx.user?.employees_id || this.ctx.user?.id, - name: this.ctx.user?.employees_name || '', - }, + operator, extras: { - warehouseId, + warehouseId: logWarehouseId, message: `订单克隆:原订单 ${orderId} 已取消,将创建新订单`, }, beforeChanges: null, @@ -835,12 +1522,9 @@ class PendingOrderService extends OrderBaseService { businessType: 'order', businessId: newOrderId, operationCode: 'ORDER_CLONE_TARGET', - operator: { - id: this.ctx.user?.employees_id || this.ctx.user?.id, - name: this.ctx.user?.employees_name || '', - }, + operator, extras: { - warehouseId, + warehouseId: logWarehouseId, message: `克隆创建:由原订单 ${orderId} 克隆生成,新订单 ID ${newOrderId}`, }, beforeChanges: null, diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js new file mode 100644 index 0000000..7c38aac --- /dev/null +++ b/app/service/systemMethods/order/print.js @@ -0,0 +1,58 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class OrderPrintService extends OrderBaseService { + /** + * 初始化订单打印模块的免登录、免权限、免日志和免鉴权配置。 + * + * @param {Egg.Context} ctx 请求上下文。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getWavePrintData'; + const _noNeedLog = 'getWavePrintData'; + const _noNeedAuth = 'getWavePrintData'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 获取波次打印数据。 + * + * method 层仅负责参数解构与边界校验,具体业务查询由 systems 层实现。 + * 返回结果中的 ext 会同时包含 missing_wave_ids 与 filtered_wave_ids。 + * + * @param {Object} data 请求体。 + * @param {Array} data.wave_ids 波次ID数组。 + * @param {number|string} data.warehouse_id 仓库ID。 + * @return {Promise} 统一 success 包装的打印数据结果。 + */ + async getWavePrintData(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + wave_ids: waveIds, + warehouse_id: warehouseId, + } = 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 result = await this.service.systems.orderPrint.getWavePrintData({ + waveIds, + warehouseId, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } +} + +module.exports = OrderPrintService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js new file mode 100644 index 0000000..56f80d5 --- /dev/null +++ b/app/service/systemMethods/order/wave.js @@ -0,0 +1,5550 @@ +'use strict'; + +const { Op } = require('sequelize'); +const OrderBaseService = require('./base'); + +const DEFAULT_PAGE = 1; +const DEFAULT_PAGE_SIZE = 20; +const MAX_PAGE_SIZE = 200; +const BATCH_LIST_MAX_PAGE_SIZE = 500; +const DEFAULT_MAX_WAVE_QUANTITY = 500; +const DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY = 13; +const WAVE_MANUAL_FETCH_FLAG = 'wave_manual_fetch'; +const FETCH_TASK_CACHE_KEY_PREFIX = 'wave:fetch:task:'; +const FETCH_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; +const BATCH_CANCEL_TASK_CACHE_KEY_PREFIX = 'wave:batch-cancel:'; +const BATCH_CANCEL_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_KEY_PREFIX = 'wave:batch-remove-exception-orders:'; +const BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-express:'; +const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-storage:'; +const BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID = 1; +const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS = [ BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID ]; +const BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP = new Map(); + +class WaveService extends OrderBaseService { + /** + * 初始化波次方法权限配置。 + * + * @param {Egg.Context} ctx 请求上下文。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders'; + const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 构建批次分配快递号链路追踪ID。 + * + * 优先使用入参中的 trace_id/traceId,其次尝试读取上下文中的 trace 标识, + * 最后兜底生成带时间戳的随机追踪ID。 + * + * @param {Object} [data={}] 入参对象。 + * @param {string} [fallback=''] 兜底业务标识(如 taskId)。 + * @return {string} 追踪ID。 + */ + buildBatchAllocateExpressTraceId(data = {}, fallback = '') { + const normalizedData = this.isPlainObject(data) ? data : {}; + const ctxTraceId = this.ctx && this.ctx.traceId !== undefined + ? this.ctx.traceId + : this.ctx && this.ctx.requestId !== undefined + ? this.ctx.requestId + : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined + ? this.ctx.state.traceId + : ''; + const normalizedTraceId = String( + normalizedData.trace_id + || normalizedData.traceId + || ctxTraceId + || fallback + || '' + ).trim(); + + if (normalizedTraceId) { + return normalizedTraceId; + } + + return `wave_allocate_express_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + } + + /** + * 构建订单操作日志批量写入数据。 + * + * @param {Array} logItems 日志项。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Array} 可直接用于 bulkCreate 的日志行。 + */ + buildOrderOperationLogRows(logItems = [], warehouseId = 0) { + if (!Array.isArray(logItems) || logItems.length === 0) { + return []; + } + + const normalizedWarehouseId = Number(this.getOrderLogWarehouseId(warehouseId) || 0); + const stateUser = this.isPlainObject(this.ctx && this.ctx.state && this.ctx.state.user) + ? this.ctx.state.user + : null; + const ctxUser = this.isPlainObject(this.ctx && this.ctx.user) + ? this.ctx.user + : null; + const paramsObject = this.isPlainObject(this.params) ? this.params : {}; + const paramsOperator = this.isPlainObject(paramsObject.__operator) + ? paramsObject.__operator + : (this.isPlainObject(paramsObject.operator) ? paramsObject.operator : null); + const operatorSource = stateUser || ctxUser || paramsOperator || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + const platformCode = String(operatorSource.platform_code || 'SYSTEM').trim() || 'SYSTEM'; + + return logItems + .map(item => { + const orderId = Number(item && item.orderId || 0); + const operationCode = String(item && item.operationCode || '').trim() || 'ORDER_WAVE_UPDATE'; + const message = String(item && item.message || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0 || !message) { + return null; + } + + return { + business_type: 'order', + business_id: `${orderId}`, + operation_code: operationCode, + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : null, + platform_code: platformCode, + message, + }; + }) + .filter(Boolean); + } + + /** + * 批量写入订单操作日志。 + * + * 该方法为业务降级路径,写入失败仅告警,不影响主流程。 + * + * @param {Array} logItems 日志项。 + * @param {Object} options 写入选项。 + * @param {number|string} options.warehouseId 仓库ID。 + * @param {string} [options.scene='wave'] 场景标识,用于日志追踪。 + * @return {Promise} 实际写入条数。 + */ + async batchCreateOrderOperationLogs(logItems = [], options = {}) { + const rows = this.buildOrderOperationLogRows(logItems, options && options.warehouseId); + const loggerWarn = this.ctx.logger && typeof this.ctx.logger.warn === 'function' + ? this.ctx.logger.warn.bind(this.ctx.logger) + : null; + if (rows.length === 0) { + return 0; + } + + const operationLogModel = this.ctx.model && this.ctx.model.OperationLog; + if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') { + if (loggerWarn) { + loggerWarn('[wave.batchCreateOrderOperationLogs] OperationLog.bulkCreate 不可用,跳过写入', { + scene: String(options && options.scene || 'wave'), + rows: rows.length, + }); + } + return 0; + } + + try { + await operationLogModel.bulkCreate(rows); + return rows.length; + } catch (error) { + if (loggerWarn) { + loggerWarn('[wave.batchCreateOrderOperationLogs] 批量写订单操作日志失败,不影响主流程', { + scene: String(options && options.scene || 'wave'), + rows: rows.length, + error: error && error.message ? error.message : `${error}`, + }); + } + return 0; + } + } + + /** + * 构建稳定机器结构标识(可作为抓取接口入参)。 + * + * @param {Object} params 结构参数。 + * @param {string} params.item_part_type 商品结构来源字段类型。 + * @param {string} params.item_part 商品结构来源值。 + * @param {boolean} params.distinguish_express 是否区分快递。 + * @param {string} params.logistics_name 快递名称。 + * @param {string} params.item_snapshot_key 机器明细快照。 + * @return {string} 稳定机器结构标识。 + */ + buildMachineStructureToken(params = {}) { + const itemPartType = String(params.item_part_type || 'items_hash').trim() || 'items_hash'; + const itemPart = encodeURIComponent(String(params.item_part || '').trim()); + const distinguishExpress = params.distinguish_express ? '1' : '0'; + const logisticsName = encodeURIComponent(String(params.logistics_name || '').trim()); + const itemSnapshotKey = encodeURIComponent(String(params.item_snapshot_key || '').trim()); + + return `v1|${itemPartType}|${itemPart}|${distinguishExpress}|${logisticsName}|${itemSnapshotKey}`; + } + + /** + * 解析机器结构标识。 + * + * @param {string} token 机器结构标识。 + * @return {{ item_part_type: string, item_part: string, distinguish_express: boolean, logistics_name: string, item_snapshot_key: string }} 解析结果。 + */ + parseMachineStructureToken(token) { + const normalizedToken = String(token || '').trim(); + const parts = normalizedToken.split('|'); + + if (parts.length < 6 || parts[0] !== 'v1') { + throw new Error('item_detail_machine 格式不合法'); + } + + const itemPartType = String(parts[1] || '').trim(); + if (![ 'items_hash', 'items' ].includes(itemPartType)) { + throw new Error('item_detail_machine item_part_type 不支持'); + } + + const itemPart = decodeURIComponent(String(parts[2] || '').trim()); + if (!itemPart) { + throw new Error('item_detail_machine item_part 不能为空'); + } + + const distinguishExpress = String(parts[3] || '') === '1'; + const logisticsName = decodeURIComponent(String(parts[4] || '').trim()); + const itemSnapshotKey = decodeURIComponent(String(parts[5] || '').trim()); + + return { + item_part_type: itemPartType, + item_part: itemPart, + distinguish_express: distinguishExpress, + logistics_name: logisticsName, + item_snapshot_key: itemSnapshotKey, + }; + } + + /** + * 获取订单可分组的商品结构值(优先 items_hash)。 + * + * @param {Object} order 订单主表记录。 + * @return {{ item_part_type: string, item_part: string }} 分组结构值。 + */ + getOrderItemPart(order = {}) { + const itemsHash = String(order.items_hash || '').trim(); + if (itemsHash) { + return { + item_part_type: 'items_hash', + item_part: itemsHash, + }; + } + + return { + item_part_type: 'items', + item_part: String(order.items || '').trim(), + }; + } + + /** + * 读取默认抓取数量(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 默认抓取数量。 + */ + async getDefaultWaveQuantity(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return DEFAULT_MAX_WAVE_QUANTITY; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const maxWaveQuantity = Number(this.getWarehouseSubjectConfigValue(subjectConfig, 'max_wave_quantity')); + if (!Number.isInteger(maxWaveQuantity) || maxWaveQuantity <= 0) { + return DEFAULT_MAX_WAVE_QUANTITY; + } + + return maxWaveQuantity; + } catch (error) { + this.ctx.logger.warn('[wave.getDefaultWaveQuantity] 获取仓库默认波次数量失败: %s', error.message); + return DEFAULT_MAX_WAVE_QUANTITY; + } + } + + /** + * 读取最小团购抓取数量(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 最小团购抓取数量。 + */ + async getMinGroupOrderFetchQuantity(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const minGroupOrderFetchQuantity = Number( + this.getWarehouseSubjectConfigValue(subjectConfig, 'min_group_order_fetch_quantity') + ); + if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { + return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + } + + return minGroupOrderFetchQuantity; + } catch (error) { + this.ctx.logger.warn('[wave.getMinGroupOrderFetchQuantity] 获取仓库最小团购抓取数量失败: %s', error.message); + return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + } + } + + /** + * 读取团购波次编号前缀(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 团购波次编号前缀。 + */ + async getGroupWavePrefix(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return 'B'; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const groupWavePrefix = String( + this.getWarehouseSubjectConfigValue(subjectConfig, 'group_wave_prefix') || '' + ).trim(); + if (!groupWavePrefix) { + return 'B'; + } + + return groupWavePrefix.slice(0, 5); + } catch (error) { + this.ctx.logger.warn('[wave.getGroupWavePrefix] 获取仓库团购波次前缀失败: %s', error.message); + return 'B'; + } + } + + /** + * 统一读取仓库主体配置(缓存优先,缓存 miss 回源数据库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 仓库主体配置对象。 + */ + async getWarehouseSubjectConfig(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return {}; + } + + const deliveryOrderService = this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; + if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') { + return {}; + } + + const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(normalizedWarehouseId); + return this.isPlainObject(subjectConfig) ? subjectConfig : {}; + } + + /** + * 从仓库主体配置中读取字段值,优先 subject_config 内嵌配置。 + * + * @param {Object} subjectConfig 仓库主体配置。 + * @param {string} key 字段名。 + * @return {*} 字段值。 + */ + getWarehouseSubjectConfigValue(subjectConfig = {}, key = '') { + const normalizedKey = String(key || '').trim(); + if (!normalizedKey) { + return undefined; + } + + const normalizedSubjectConfig = this.isPlainObject(subjectConfig) ? subjectConfig : {}; + const nestedSubjectConfig = this.isPlainObject(normalizedSubjectConfig.subject_config) + ? normalizedSubjectConfig.subject_config + : {}; + + if (nestedSubjectConfig[normalizedKey] !== undefined) { + return nestedSubjectConfig[normalizedKey]; + } + + return normalizedSubjectConfig[normalizedKey]; + } + + /** + * 解析抓取结构请求参数。 + * + * @param {Object} data 请求参数。 + * @param {number} defaultQuantity 默认抓取数量。 + * @return {Array} 结构化请求。 + */ + normalizeFetchStructureRequests(data = {}, defaultQuantity = DEFAULT_MAX_WAVE_QUANTITY) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawStructureList = requestData.structure_list; + + if (!Array.isArray(rawStructureList) || rawStructureList.length === 0) { + throw new Error('structure_list 必须是非空数组'); + } + + return rawStructureList.map((item, index) => { + if (!this.isPlainObject(item)) { + throw new Error(`structure_list[${index}] 必须是对象`); + } + + const itemDetailMachine = String(item.item_detail_machine || '').trim(); + if (!itemDetailMachine) { + throw new Error(`structure_list[${index}].item_detail_machine 不能为空`); + } + + const parsedToken = this.parseMachineStructureToken(itemDetailMachine); + const quantity = item.quantity === undefined || item.quantity === null || item.quantity === '' + ? defaultQuantity + : this.normalizePositiveInteger(item.quantity, `structure_list[${index}].quantity`, defaultQuantity); + + if (!Number.isInteger(quantity) || quantity <= 0) { + throw new Error(`structure_list[${index}].quantity 必须大于 0`); + } + + return { + index, + item_detail_machine: itemDetailMachine, + quantity, + ...parsedToken, + }; + }); + } + + /** + * 生成可排序且足够唯一的 wave_id。 + * + * @param {number} suffix 同批次偏移量。 + * @return {number} 波次ID。 + */ + generateWaveId(suffix = 0) { + const base = Date.now() * 1000; + const randomPart = Math.floor(Math.random() * 900) + 100; + return base + randomPart + Number(suffix || 0); + } + + /** + * 获取当前日期片段(YYYYMMDD)。 + * + * @return {string} 当前日期片段。 + */ + getCurrentDatePart() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; + } + + /** + * 查询当天前缀下的下一个波次序号。 + * + * @param {string} prefix 波次编号前缀。 + * @param {string} datePart 日期片段(YYYYMMDD)。 + * @param {Object} transaction Sequelize 事务。 + * @return {Promise} 下一个序号(最小为 1)。 + */ + async getNextWaveNoSequence(prefix, datePart, transaction) { + const normalizedPrefix = String(prefix || '').trim() || 'B'; + const normalizedDatePart = String(datePart || '').trim(); + const pattern = `${normalizedPrefix}${normalizedDatePart}%`; + const sql = ` + SELECT wave_no + FROM wms_wave_batch + WHERE wave_no LIKE :pattern + ORDER BY wave_no DESC + LIMIT 1 + `; + + const rows = await this.ctx.model.query(sql, { + replacements: { pattern }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const latestWaveNo = String(rows && rows[0] && rows[0].wave_no || '').trim(); + if (!latestWaveNo) { + return 1; + } + + const match = latestWaveNo.match(/(\d{5})$/); + const lastSequence = match ? Number(match[1]) : 0; + if (!Number.isInteger(lastSequence) || lastSequence <= 0) { + return 1; + } + + return lastSequence + 1; + } + + /** + * 构建波次编号。 + * + * @param {string} [prefix='B'] 波次编号前缀。 + * @param {string} [datePart=''] 日期片段(YYYYMMDD)。 + * @param {number|string} [sequence=1] 当天序号。 + * @return {string} 波次编号。 + */ + buildWaveNo(prefix = 'B', datePart = '', sequence = 1) { + const normalizedPrefix = String(prefix || '').trim(); + const normalizedDatePart = String(datePart || '').trim(); + const normalizedSequence = Number(sequence || 0); + const safeSequence = Number.isInteger(normalizedSequence) && normalizedSequence > 0 ? normalizedSequence : 1; + return `${normalizedPrefix}${normalizedDatePart}${String(safeSequence).padStart(5, '0')}`; + } + + /** + * 获取波次创建人。 + * + * 优先级:employees_name > real_name > name > id(字符串) > system。 + * + * @return {string} 创建人。 + */ + getWaveCreator() { + const user = this.isPlainObject(this.ctx.user) ? this.ctx.user : {}; + const creator = String(user.employees_name || user.real_name || user.name || '').trim(); + if (creator) { + return creator; + } + + const userId = user.id; + if (userId !== undefined && userId !== null && userId !== '') { + return `${userId}`; + } + + return 'system'; + } + + /** + * 从 SQL 执行结果中提取 insertId。 + * + * @param {*} queryResult Sequelize query 返回值。 + * @return {number} 自增主键ID,提取失败返回 0。 + */ + extractInsertId(queryResult) { + if (Array.isArray(queryResult)) { + const [ first, second ] = queryResult; + const firstInsertId = Number(first && first.insertId || 0); + if (Number.isInteger(firstInsertId) && firstInsertId > 0) { + return firstInsertId; + } + + const secondInsertId = Number(second && second.insertId || 0); + if (Number.isInteger(secondInsertId) && secondInsertId > 0) { + return secondInsertId; + } + } + + const directInsertId = Number(queryResult && queryResult.insertId || 0); + if (Number.isInteger(directInsertId) && directInsertId > 0) { + return directInsertId; + } + + return 0; + } + + /** + * 从 LAST_INSERT_ID 查询结果中提取 insertId。 + * + * @param {*} queryResult Sequelize query 返回值。 + * @return {number} 自增主键ID,提取失败返回 0。 + */ + extractLastInsertId(queryResult) { + const directInsertId = this.extractInsertId(queryResult); + if (Number.isInteger(directInsertId) && directInsertId > 0) { + return directInsertId; + } + + if (!Array.isArray(queryResult)) { + return 0; + } + + const [ first ] = queryResult; + if (Array.isArray(first) && first.length > 0) { + for (const row of first) { + const rowInsertId = Number( + row && (row.insertId || row.insert_id || row.LAST_INSERT_ID || row.last_insert_id) || 0 + ); + if (Number.isInteger(rowInsertId) && rowInsertId > 0) { + return rowInsertId; + } + } + } + + return 0; + } + + /** + * 新增一条“已就绪”波次批次记录,并返回自增 wave_id。 + * + * @param {Object} params 入参。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.totalOrders 订单总数。 + * @param {string} params.itemDetailMachine 机器结构标识。 + * @param {string} params.itemPartType 商品结构来源字段类型。 + * @param {string} params.itemPart 商品结构来源值。 + * @param {number|boolean|string} params.distinguishExpress 是否区分快递(归一化为0/1)。 + * @param {string} params.logisticsName 快递名称。 + * @param {string} params.itemSnapshotKey 机器明细快照。 + * @param {string} [params.wavePrefix] 波次编号前缀。 + * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise<{waveId: number, waveNo: string}>} 创建结果。 + */ + async createWaveBatchReady({ + warehouseId, + totalOrders, + itemDetailMachine, + itemPartType, + itemPart, + distinguishExpress, + logisticsName, + itemSnapshotKey, + wavePrefix, + waveNo, + transaction, + } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedTotalOrders = Number(totalOrders || 0); + const normalizedItemDetailMachine = String(itemDetailMachine || '').trim(); + const normalizedItemPartType = String(itemPartType || '').trim(); + const normalizedItemPart = String(itemPart || '').trim(); + const normalizedDistinguishExpress = distinguishExpress === true || Number(distinguishExpress) === 1 ? 1 : 0; + const normalizedLogisticsName = String(logisticsName || '').trim(); + const normalizedItemSnapshotKey = String(itemSnapshotKey || '').trim(); + const normalizedWavePrefix = String(wavePrefix || '').trim() || 'B'; + const normalizedWaveNoInput = String(waveNo || '').trim(); + let normalizedWaveNo = normalizedWaveNoInput; + if (!normalizedWaveNo) { + const datePart = this.getCurrentDatePart(); + const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction); + normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence); + } + const creator = this.getWaveCreator(); + + const sql = ` + INSERT INTO wms_wave_batch + ( + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + item_detail_machine, + item_part_type, + item_part, + distinguish_express, + logistics_name, + item_snapshot_key, + warehouse_id, + creator, + create_time, + update_time + ) + VALUES + ( + :waveNo, + 1, + 1, + :totalOrders, + 0, + :itemDetailMachine, + :itemPartType, + :itemPart, + :distinguishExpress, + :logisticsName, + :itemSnapshotKey, + :warehouseId, + :creator, + NOW(), + NOW() + ) + `; + + const createResult = await this.ctx.model.query(sql, { + replacements: { + waveNo: normalizedWaveNo, + totalOrders: normalizedTotalOrders, + itemDetailMachine: normalizedItemDetailMachine, + itemPartType: normalizedItemPartType, + itemPart: normalizedItemPart, + distinguishExpress: normalizedDistinguishExpress, + logisticsName: normalizedLogisticsName, + itemSnapshotKey: normalizedItemSnapshotKey, + warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, + creator, + }, + transaction, + }); + + let insertedWaveId = this.extractInsertId(createResult); + if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) { + const fallbackResult = await this.ctx.model.query('SELECT LAST_INSERT_ID() AS insertId', { + transaction, + }); + insertedWaveId = this.extractLastInsertId(fallbackResult); + } + + if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) { + throw new Error('创建波次失败,未获取到自增 wave_id'); + } + + return { + waveId: insertedWaveId, + waveNo: normalizedWaveNo, + }; + } + + /** + * 构建抓取候选订单筛选条件。 + * + * @param {Object} structure 结构化请求。 + * @return {Object} Sequelize where 条件。 + */ + buildFetchWhere(structure = {}) { + const where = { + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + wave_id: 0, + }; + + const itemPartType = String(structure.item_part_type || '').trim(); + const itemPart = String(structure.item_part || '').trim(); + if (itemPartType === 'items_hash') { + where.items_hash = itemPart; + } else { + where.items = itemPart; + } + + if (structure.distinguish_express) { + where.logistics_name = String(structure.logistics_name || '').trim(); + } + + return where; + } + + /** + * 按单个结构抓取订单并写入同一波次。 + * + * @param {Object} model 订单主表模型。 + * @param {Object} structure 结构化请求。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [wavePrefix='B'] 波次编号前缀。 + * @param {number} [minGroupOrderFetchQuantity=13] 最小团购抓取数量。 + * @param {Object} [options={}] 额外抓取选项。 + * @param {number} [options.maxFetchQuantity=0] 本结构最大抓取订单数上限,0 表示不限制。 + * @return {Promise} 单结构抓取结果。 + */ + async fetchSingleStructure( + model, + structure = {}, + warehouseId = 0, + wavePrefix = 'B', + minGroupOrderFetchQuantity = DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY, + options = {} + ) { + const { ctx } = this; + const where = this.buildFetchWhere(structure); + const requestedQuantity = Number(structure.quantity || 0); + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const normalizedMaxFetchQuantity = Number.isInteger(Number(normalizedOptions.maxFetchQuantity)) + && Number(normalizedOptions.maxFetchQuantity) > 0 + ? Number(normalizedOptions.maxFetchQuantity) + : 0; + const normalizedMinGroupOrderFetchQuantity = Number.isInteger(Number(minGroupOrderFetchQuantity)) + && Number(minGroupOrderFetchQuantity) > 0 + ? Number(minGroupOrderFetchQuantity) + : DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; + const allWaveIds = []; + const allOrderIds = []; + const fetchedOrderLogItems = []; + let totalFetchedQuantity = 0; + let remainingFetchQuantity = normalizedMaxFetchQuantity; + let stopReason = ''; + const transaction = await ctx.model.transaction(); + try { + for (;;) { + let fetchLimit = requestedQuantity; + if (normalizedMaxFetchQuantity > 0) { + if (remainingFetchQuantity <= 0) { + stopReason = '达到最大抓取上限'; + break; + } + fetchLimit = Math.min(fetchLimit, remainingFetchQuantity); + } + + const rows = await model.findAll({ + where, + attributes: [ 'id' ], + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'DESC' ]], + limit: fetchLimit, + }); + + const candidateOrderIds = rows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + if (candidateOrderIds.length === 0) { + if (totalFetchedQuantity === 0) { + stopReason = '无可抓取订单'; + } + break; + } + + if (candidateOrderIds.length < normalizedMinGroupOrderFetchQuantity) { + stopReason = '剩余订单低于最小团购抓取数量'; + break; + } + + const { waveId, waveNo } = await this.createWaveBatchReady({ + warehouseId, + totalOrders: candidateOrderIds.length, + itemDetailMachine: structure.item_detail_machine, + itemPartType: structure.item_part_type, + itemPart: structure.item_part, + distinguishExpress: structure.distinguish_express, + logisticsName: structure.logistics_name, + itemSnapshotKey: structure.item_snapshot_key, + wavePrefix, + transaction, + }); + const orderFlagExpression = this.app.Sequelize.literal(`CASE + WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' + WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag + ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') + END`); + + await model.update({ + wave_id: waveId, + wave_no: waveNo, + order_flag: orderFlagExpression, + }, { + where: { + id: { [Op.in]: candidateOrderIds }, + wave_id: 0, + }, + transaction, + }); + + const grabbedRows = await model.findAll({ + where: { + id: { [Op.in]: candidateOrderIds }, + wave_id: waveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + + const grabbedOrderIds = grabbedRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0) + .sort((a, b) => a - b); + + const fetchedQuantity = grabbedOrderIds.length; + if (fetchedQuantity <= 0) { + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE wave_id = :waveId + `, { + replacements: { waveId }, + transaction, + }); + + if (totalFetchedQuantity === 0) { + stopReason = '无可抓取订单'; + } + break; + } + + if (fetchedQuantity !== candidateOrderIds.length) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :totalOrders, + update_time = NOW() + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + totalOrders: fetchedQuantity, + }, + transaction, + }); + } + + allWaveIds.push(waveId); + allOrderIds.push(...grabbedOrderIds); + fetchedOrderLogItems.push(...grabbedOrderIds.map(orderId => ({ + orderId, + operationCode: 'ORDER_WAVE_ASSIGN', + message: `订单被分配到波次 ${waveNo}`, + }))); + totalFetchedQuantity += fetchedQuantity; + if (normalizedMaxFetchQuantity > 0) { + remainingFetchQuantity -= fetchedQuantity; + if (remainingFetchQuantity <= 0) { + stopReason = '达到最大抓取上限'; + break; + } + } + } + + await transaction.commit(); + await this.batchCreateOrderOperationLogs(fetchedOrderLogItems, { + warehouseId, + scene: 'fetchSingleStructure', + }); + + const mergedOrderIds = [ ...new Set(allOrderIds) ].sort((a, b) => a - b); + let reason = stopReason; + if (!reason && totalFetchedQuantity > 0 && totalFetchedQuantity < requestedQuantity) { + reason = '可抓取订单不足'; + } + + return { + item_detail_machine: structure.item_detail_machine, + request_quantity: requestedQuantity, + fetched_quantity: totalFetchedQuantity, + ...(normalizedMaxFetchQuantity > 0 ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + ...(normalizedMaxFetchQuantity > 0 ? { limit_reached: totalFetchedQuantity >= normalizedMaxFetchQuantity } : {}), + wave_id: allWaveIds.length > 0 ? allWaveIds[0] : 0, + wave_ids: allWaveIds, + order_ids: mergedOrderIds, + auto_fetch_disabled: true, + auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, + ...(reason ? { reason } : {}), + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + normalizeBoolean(value, defaultValue = false) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + const normalized = String(value).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalized)) { + return true; + } + + if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalized)) { + return false; + } + + return defaultValue; + } + + normalizePositiveInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const num = Number(value); + if (!Number.isInteger(num) || num < 0) { + throw new Error(`${fieldName} 参数不合法`); + } + + return num; + } + + /** + * 解析必填的正整数参数。 + * + * @param {*} value 原始参数值。 + * @param {string} fieldName 字段名称。 + * @return {number} 归一化后的正整数。 + */ + normalizeRequiredPositiveInteger(value, fieldName) { + if (value === undefined || value === null || value === '') { + throw new Error(`${fieldName} 参数不能为空`); + } + + const normalizedValue = Number(value); + if (!Number.isInteger(normalizedValue) || normalizedValue <= 0) { + throw new Error(`${fieldName} 参数必须为正整数`); + } + + return normalizedValue; + } + + /** + * 归一化 ids 入参为去重后的正整数数组。 + * + * 支持数组、逗号分隔字符串、单个 number/string。 + * + * @param {Array|number|string} value 原始 ids 入参。 + * @return {Array} 归一化后的 ids 数组。 + */ + normalizeIdsInput(value) { + let sourceList = []; + + if (Array.isArray(value)) { + sourceList = value; + } else if (typeof value === 'string') { + sourceList = value.split(','); + } else if (typeof value === 'number') { + sourceList = [ value ]; + } else { + sourceList = []; + } + + const normalizedIds = sourceList + .map(item => String(item === undefined || item === null ? '' : item).trim()) + .filter(item => item !== '') + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0); + + return [ ...new Set(normalizedIds) ]; + } + + /** + * 规范化分页参数。 + * + * @param {Object} data 请求参数。 + * @param {Object} data.pagination 分页参数对象。 + * @param {number|string} data.pagination.page 页码。 + * @param {number|string} data.pagination.pageSize 每页数量(驼峰写法,可用)。 + * @param {number|string} data.pagination.page_size 每页数量(下划线写法,可用)。 + * @param {number|string} data.pagination.limit 每页数量(limit 写法,可用)。 + * @param {number|string} data.pagination.size 每页数量(size 写法,可用)。 + * @param {Object} options 规范化选项。 + * @param {number|string} options.maxPageSize 每页数量上限。 + * @return {{ page: number, pageSize: number }} 规范化后的分页信息。 + */ + normalizePagination(data = {}, options = {}) { + const pagination = this.isPlainObject(data && data.pagination) ? data.pagination : {}; + const pageSource = pagination.page; + const pageSizeSource = pagination.pageSize ?? pagination.page_size ?? pagination.limit ?? pagination.size; + const maxPageSizeSource = Number(options.maxPageSize || MAX_PAGE_SIZE); + const maxPageSize = Number.isInteger(maxPageSizeSource) && maxPageSizeSource > 0 + ? maxPageSizeSource + : MAX_PAGE_SIZE; + + const page = Number(pageSource || DEFAULT_PAGE); + const pageSize = Number(pageSizeSource || DEFAULT_PAGE_SIZE); + + const normalizedPage = Number.isInteger(page) && page > 0 ? page : DEFAULT_PAGE; + const normalizedPageSize = Number.isInteger(pageSize) && pageSize > 0 + ? Math.min(pageSize, maxPageSize) + : DEFAULT_PAGE_SIZE; + + return { + page: normalizedPage, + pageSize: normalizedPageSize, + }; + } + + /** + * 规范化波次状态列表。 + * + * @param {Array} value 波次状态列表。 + * @return {Array} 规范化后的状态数组。 + */ + normalizeWaveStatusList(value) { + if (!Array.isArray(value)) { + return [ 0, 1 ]; + } + + const statusList = value + .map(item => Number(item)) + .filter(item => Number.isInteger(item)); + + if (statusList.length === 0) { + return [ 0, 1 ]; + } + + return [ ...new Set(statusList) ]; + } + + /** + * 规范化波次列表库位分配状态筛选值。 + * + * @param {string} value 入参筛选值。 + * @return {string} 规范化后的筛选值,未传时返回空字符串。 + */ + normalizeBatchListStorageAssignmentStatusFilter(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const normalizedValue = String(value).trim(); + if (!normalizedValue) { + return ''; + } + + const allowedValues = [ '未分配', '部分分配', '已分配' ]; + if (!allowedValues.includes(normalizedValue)) { + throw new Error(`storage_assignment_status 参数不合法,仅支持: ${allowedValues.join('、')}`); + } + + return normalizedValue; + } + + /** + * 解析模型对应的 SQL 表名并完成安全转义。 + * + * @param {Object} model Sequelize 模型对象。 + * @return {string} 可直接拼接到 SQL 的表名。 + */ + getModelTableSqlName(model) { + const rawTableName = model && typeof model.getTableName === 'function' + ? model.getTableName() + : model && model.tableName; + const tableName = typeof rawTableName === 'string' + ? rawTableName + : rawTableName && typeof rawTableName.tableName === 'string' + ? rawTableName.tableName + : ''; + const normalizedTableName = String(tableName || '').trim(); + if (!normalizedTableName) { + throw new Error('订单模型表名解析失败'); + } + + const tableParts = normalizedTableName.split('.').map(part => String(part || '').trim()).filter(Boolean); + if (tableParts.length === 0) { + throw new Error('订单模型表名解析失败'); + } + + for (const tablePart of tableParts) { + if (!/^[a-zA-Z0-9_$]+$/.test(tablePart)) { + throw new Error(`订单模型表名不合法: ${normalizedTableName}`); + } + } + + return tableParts.map(part => `\`${part}\``).join('.'); + } + + /** + * 构建波次列表库位分配状态筛选 SQL 条件。 + * + * @param {string} statusFilter 库位分配状态筛选值。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildBatchListStorageAssignmentFilterClause(statusFilter = '') { + const normalizedStatusFilter = this.normalizeBatchListStorageAssignmentStatusFilter(statusFilter); + if (!normalizedStatusFilter) { + return { + sql: '', + replacements: {}, + }; + } + + const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; + const storageNoneExpr = 'COALESCE(wave_order_stats.storage_none_count, 0)'; + const storageFinExpr = 'COALESCE(wave_order_stats.storage_fin_count, 0)'; + const storageErrorExpr = 'COALESCE(wave_order_stats.storage_error_count, 0)'; + let whereClause = ''; + + if (normalizedStatusFilter === '已分配') { + whereClause = ` + ${storageFinExpr} = ${totalExpr} + AND ${totalExpr} > 0 + `; + } else if (normalizedStatusFilter === '部分分配') { + whereClause = ` + ${storageErrorExpr} = 0 + AND ${storageNoneExpr} <> ${totalExpr} + AND ${storageFinExpr} <> ${totalExpr} + `; + } else if (normalizedStatusFilter === '未分配') { + return { + sql: ` + AND ( + ${totalExpr} = 0 + OR ${storageErrorExpr} > 0 + OR ${storageNoneExpr} = ${totalExpr} + )`, + replacements: {}, + }; + } + + return { + sql: ` + AND ${whereClause}`, + replacements: {}, + }; + } + + /** + * 构建波次列表 where 条件(白名单字段)。 + * + * @param {Object} whereData 查询 where 入参。 + * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string }} SQL 条件片段、参数与库位分配状态筛选值。 + */ + buildBatchListWhereClause(whereData = {}) { + const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; + const whereKeys = Object.keys(normalizedWhere); + + if (whereKeys.includes('warehouse_id') || whereKeys.includes('warehouseId')) { + throw new Error('where 中禁止传入 warehouse_id 或 warehouseId'); + } + + const allowedFields = [ + 'wave_id', + 'wave_no', + 'wave_type', + 'wave_status', + 'creator', + 'logistics_name', + 'item_part_type', + 'item_part', + 'item_snapshot_key', + 'item_detail_machine', + 'distinguish_express', + 'total_orders_min', + 'total_orders_max', + 'processed_orders_min', + 'processed_orders_max', + 'storage_assignment_status', + ]; + + const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); + if (invalidFields.length > 0) { + throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); + } + + const conditions = []; + const replacements = {}; + + const appendIntegerEqualCondition = (fieldKey, columnName, replacementKey, allowZero = true) => { + const value = normalizedWhere[fieldKey]; + if (value === undefined || value === null || value === '') { + return; + } + + const numberValue = Number(value); + const isValid = Number.isInteger(numberValue) && (allowZero ? numberValue >= 0 : numberValue > 0); + if (!isValid) { + throw new Error(`${fieldKey} 参数不合法`); + } + + conditions.push(`${columnName} = :${replacementKey}`); + replacements[replacementKey] = numberValue; + }; + + const appendLikeCondition = (fieldKey, columnName, replacementKey) => { + const value = normalizedWhere[fieldKey]; + if (value === undefined || value === null || value === '') { + return; + } + + const normalizedValue = String(value).trim(); + if (!normalizedValue) { + return; + } + + conditions.push(`${columnName} LIKE :${replacementKey}`); + replacements[replacementKey] = `%${normalizedValue}%`; + }; + + const appendMinCondition = (fieldKey, columnName, replacementKey) => { + const value = normalizedWhere[fieldKey]; + if (value === undefined || value === null || value === '') { + return; + } + + const numberValue = Number(value); + if (!Number.isFinite(numberValue)) { + throw new Error(`${fieldKey} 参数不合法`); + } + + conditions.push(`${columnName} >= :${replacementKey}`); + replacements[replacementKey] = numberValue; + }; + + const appendMaxCondition = (fieldKey, columnName, replacementKey) => { + const value = normalizedWhere[fieldKey]; + if (value === undefined || value === null || value === '') { + return; + } + + const numberValue = Number(value); + if (!Number.isFinite(numberValue)) { + throw new Error(`${fieldKey} 参数不合法`); + } + + conditions.push(`${columnName} <= :${replacementKey}`); + replacements[replacementKey] = numberValue; + }; + + appendIntegerEqualCondition('wave_id', 'wave_id', 'whereWaveId', false); + appendLikeCondition('wave_no', 'wave_no', 'whereWaveNo'); + appendIntegerEqualCondition('wave_type', 'wave_type', 'whereWaveType'); + appendIntegerEqualCondition('wave_status', 'wave_status', 'whereWaveStatus'); + appendLikeCondition('creator', 'creator', 'whereCreator'); + appendLikeCondition('logistics_name', 'logistics_name', 'whereLogisticsName'); + appendLikeCondition('item_part', 'item_part', 'whereItemPart'); + appendLikeCondition('item_snapshot_key', 'item_snapshot_key', 'whereItemSnapshotKey'); + appendLikeCondition('item_detail_machine', 'item_detail_machine', 'whereItemDetailMachine'); + + const itemPartType = normalizedWhere.item_part_type; + if (itemPartType !== undefined && itemPartType !== null && itemPartType !== '') { + const normalizedItemPartType = String(itemPartType).trim(); + if (!normalizedItemPartType) { + throw new Error('item_part_type 参数不合法'); + } + + conditions.push('item_part_type = :whereItemPartType'); + replacements.whereItemPartType = normalizedItemPartType; + } + + const distinguishExpress = normalizedWhere.distinguish_express; + if (distinguishExpress !== undefined && distinguishExpress !== null && distinguishExpress !== '') { + let normalizedDistinguishExpress; + + if (typeof distinguishExpress === 'boolean') { + normalizedDistinguishExpress = distinguishExpress ? 1 : 0; + } else if (typeof distinguishExpress === 'number') { + if (distinguishExpress !== 0 && distinguishExpress !== 1) { + throw new Error('distinguish_express 参数不合法'); + } + normalizedDistinguishExpress = distinguishExpress; + } else { + const boolText = String(distinguishExpress).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(boolText)) { + normalizedDistinguishExpress = 1; + } else if ([ '0', 'false', 'no', 'n', 'off' ].includes(boolText)) { + normalizedDistinguishExpress = 0; + } else { + throw new Error('distinguish_express 参数不合法'); + } + } + + conditions.push('distinguish_express = :whereDistinguishExpress'); + replacements.whereDistinguishExpress = normalizedDistinguishExpress; + } + + appendMinCondition('total_orders_min', 'total_orders', 'whereTotalOrdersMin'); + appendMaxCondition('total_orders_max', 'total_orders', 'whereTotalOrdersMax'); + appendMinCondition('processed_orders_min', 'processed_orders', 'whereProcessedOrdersMin'); + appendMaxCondition('processed_orders_max', 'processed_orders', 'whereProcessedOrdersMax'); + + const storageAssignmentStatus = this.normalizeBatchListStorageAssignmentStatusFilter( + normalizedWhere.storage_assignment_status + ); + + return { + sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', + replacements, + storageAssignmentStatus, + }; + } + + /** + * 解析分配状态。 + * + * @param {number} total 总数量。 + * @param {number} noneCount 未分配数量。 + * @param {number} finCount 已分配数量。 + * @param {number} errorCount 分配异常数量。 + * @param {{ none?: string, partial?: string, finished?: string, error?: string }} [labels] 状态文案映射。 + * @return {string} 分配状态。 + */ + resolveAssignmentStatus(total, noneCount, finCount, errorCount = 0, labels = {}) { + const normalizedTotal = Number(total || 0); + const normalizedNoneCount = Number(noneCount || 0); + const normalizedFinCount = Number(finCount || 0); + const normalizedErrorCount = Number(errorCount || 0); + const normalizedLabels = labels && typeof labels === 'object' ? labels : {}; + const noneLabel = String(normalizedLabels.none || '未分配'); + const partialLabel = String(normalizedLabels.partial || '部分分配'); + const finishedLabel = String(normalizedLabels.finished || '已分配'); + const errorLabel = String(normalizedLabels.error || '分配异常'); + + if (normalizedErrorCount > 0) { + return errorLabel; + } + + if (normalizedTotal <= 0 || normalizedNoneCount === normalizedTotal) { + return noneLabel; + } + + if (normalizedFinCount === normalizedTotal) { + return finishedLabel; + } + + return partialLabel; + } + + normalizeSkuText(value) { + if (value === undefined || value === null) { + return ''; + } + + return String(value).trim(); + } + + normalizeShopName(value) { + if (value === undefined || value === null) { + return ''; + } + + return String(value).trim(); + } + + parseItemSnapshot(rawSnapshot) { + if (!rawSnapshot) { + return {}; + } + + if (typeof rawSnapshot === 'string') { + try { + const parsed = JSON.parse(rawSnapshot); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + return {}; + } + } + + return typeof rawSnapshot === 'object' ? rawSnapshot : {}; + } + + normalizeOrderItemRow(row = {}) { + const snapshot = this.parseItemSnapshot(row.item_snapshot); + const stockIdRaw = snapshot.stock_id ?? row.stock_id; + const quantityRaw = row.plan_qty; + + const stockId = Number(stockIdRaw || 0); + const quantity = Number(quantityRaw || 0); + + return { + stock_id: Number.isInteger(stockId) && stockId > 0 ? stockId : 0, + item_code: String(snapshot.item_code ?? row.item_code ?? '').trim(), + item_name: String(snapshot.item_name ?? row.item_name ?? '').trim(), + barcode: String(snapshot.barcode ?? '').trim(), + quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 0, + }; + } + + mergeOrderItemDetails(itemRows = []) { + const merged = new Map(); + + for (const row of itemRows) { + const normalized = this.normalizeOrderItemRow(row); + if (!normalized.item_code || normalized.quantity <= 0) { + continue; + } + + const key = [ + normalized.stock_id, + normalized.item_code, + normalized.item_name, + normalized.barcode, + ].join('||'); + + if (!merged.has(key)) { + merged.set(key, { + stock_id: normalized.stock_id, + item_code: normalized.item_code, + item_name: normalized.item_name, + barcode: normalized.barcode, + quantity: 0, + }); + } + + merged.get(key).quantity += normalized.quantity; + } + + return Array.from(merged.values()) + .sort((a, b) => { + if (a.stock_id !== b.stock_id) return a.stock_id - b.stock_id; + return String(a.item_code).localeCompare(String(b.item_code)); + }); + } + + buildItemSummary(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + return itemDetails + .map(item => { + const name = String(item.item_name || '').trim(); + const barcode = String(item.barcode || item.item_code || '').trim(); + const qty = item.quantity; + return `${name}${barcode ? `(${barcode})` : ''}×${qty}`; + }) + .join(' | '); + } + + buildItemSnapshotKey(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + return itemDetails.map(item => [ + item.stock_id, + item.item_code, + item.item_name, + item.barcode, + item.quantity, + ].join('::')).join('|'); + } + + orderMatchesIncludeSku(itemDetails = [], includeSku = '') { + const token = String(includeSku || '').trim().toLowerCase(); + if (!token) { + return true; + } + + return itemDetails.some(item => String(item.item_code || '').toLowerCase().includes(token)); + } + + buildCoarseGroupKey(order = {}, distinguishExpress = false) { + const itemsHash = String(order.items_hash || '').trim(); + const itemsText = String(order.items || '').trim(); + const logisticsName = String(order.logistics_name || '').trim(); + + const itemPart = itemsHash || itemsText; + if (!itemPart) { + return ''; + } + + return distinguishExpress ? `${itemPart}||${logisticsName}` : itemPart; + } + + buildStatusSummary(orders = []) { + const summary = { + post_none: 0, + post_fin: 0, + post_padding: 0, + pick_none: 0, + pick_fin: 0, + outbound_none: 0, + outbound_fin: 0, + }; + + for (const order of orders) { + const postStatus = String(order.post_status || ''); + const pickStatus = String(order.pick_status || ''); + const outboundStatus = String(order.outbound_status || ''); + + if (postStatus === 'none') summary.post_none += 1; + if (postStatus === 'fin') summary.post_fin += 1; + if (postStatus === 'padding') summary.post_padding += 1; + + if (pickStatus === 'none') summary.pick_none += 1; + if (pickStatus === 'fin') summary.pick_fin += 1; + + if (outboundStatus === 'none') summary.outbound_none += 1; + if (outboundStatus === 'fin') summary.outbound_fin += 1; + } + + return summary; + } + + buildGroupKey(order, itemDetails = [], options = {}) { + const itemSummary = this.buildItemSummary(itemDetails); + const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); + const logisticsName = String(order.logistics_name || '').trim(); + + const baseParts = [ itemSnapshotKey ]; + if (options.distinguishExpress) { + baseParts.push(logisticsName); + } + + return { + key: baseParts.join('||'), + itemSummary, + itemSnapshotKey, + itemDetails, + logisticsName, + }; + } + + /** + * 团购波次可抓取列表。 + * + * 仅处理待处理订单(排除待审核),且排除已在波次中的订单。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 抓取列表和分页信息。 + */ + async groupOrderFetchList(data = {}) { + const t0 = Date.now(); + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const model = await this.getOrderModel('pendingOrder', warehouseId); + const t1 = Date.now(); + + const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); + const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); + const sameOrderQuantityInput = requestData.same_order_quantity; + const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); + const explicitSameOrderQuantity = hasSameOrderQuantityInput + ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) + : 0; + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); + const sameOrderQuantity = explicitSameOrderQuantity > 0 + ? explicitSameOrderQuantity + : minGroupOrderFetchQuantity; + const shopName = this.normalizeShopName(requestData.shop_name); + const includeSku = this.normalizeSkuText(requestData.include_sku); + const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); + const { page, pageSize } = this.normalizePagination(requestData); + + const where = { + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + wave_id: 0, + }; + + if (storeId > 0) { + where.store_id = storeId; + } + + if (shopName) { + where.shop_nick = { [Op.like]: `%${shopName}%` }; + } + + // Phase 1: 主表全量查询,用 items_hash 做分组基准 + const rawOrders = await model.findAll({ + where, + attributes: [ + 'id', 'store_id', 'logistics_name', + 'items_hash', 'items', 'items_total', + 'post_status', 'pick_status', 'outbound_status', 'create_at', + ], + raw: true, + order: [[ 'id', 'DESC' ]], + }); + const t2 = Date.now(); + + // Phase 2: 纯内存粗分组,items_hash 相同即为同组,速度快 + // coarseGroupMap: coarseKey -> { orders[] } + const coarseGroupMap = new Map(); + for (const order of rawOrders) { + const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); + if (!coarseKey) { + continue; + } + + if (!coarseGroupMap.has(coarseKey)) { + coarseGroupMap.set(coarseKey, { orders: [] }); + } + + coarseGroupMap.get(coarseKey).orders.push(order); + } + + // 过滤最小阈值、排序 + let groupEntries = Array.from(coarseGroupMap.entries()); + groupEntries = groupEntries.filter(([ , g ]) => g.orders.length >= sameOrderQuantity); + + groupEntries.sort(([ keyA, gA ], [ keyB, gB ]) => { + if (gB.orders.length !== gA.orders.length) { + return gB.orders.length - gA.orders.length; + } + + return keyA.localeCompare(keyB); + }); + + const total = groupEntries.length; + const t3 = Date.now(); + + // Phase 3: 分页分组,只取当前页 + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + const pageStart = (page - 1) * pageSize; + const pageGroupEntries = groupEntries.slice(pageStart, pageStart + pageSize); + + // 收集当前页每组的代表订单 id(同组 items_hash 相同,只需一条快照即可) + const representativeIdPerGroup = new Map(); // coarseKey -> representativeOrderId + for (const [ coarseKey, g ] of pageGroupEntries) { + const repOrder = g.orders.find(o => Number(o.id) > 0); + if (repOrder) { + representativeIdPerGroup.set(coarseKey, Number(repOrder.id)); + } + } + const pageOrderIds = Array.from(representativeIdPerGroup.values()); + const t4 = Date.now(); + + // Phase 4: 仅查每组代表订单的明细(每页 20 条左右,大幅降低 IN 数量) + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const orderItemRows = pageOrderIds.length > 0 + ? await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: pageOrderIds } }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }) + : []; + const t5 = Date.now(); + + // 构建明细索引 + const orderItemsMap = new Map(); + for (const row of orderItemRows) { + const orderId = Number(row && row.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!orderItemsMap.has(orderId)) { + orderItemsMap.set(orderId, []); + } + + orderItemsMap.get(orderId).push(row); + } + + // Phase 5: 构建当前页响应,每组取一个代表订单的 item_snapshot 作为展示快照 + const list = []; + for (const [ coarseKey, g ] of pageGroupEntries) { + // 同粗分组内 items_hash 相同,取该组的代表订单明细作为展示快照 + const representativeId = representativeIdPerGroup.get(coarseKey); + const itemRows = representativeId ? (orderItemsMap.get(representativeId) || []) : []; + const itemDetails = this.mergeOrderItemDetails(itemRows); + + // includeSku 精确过滤(页内应用,total 为粗分组数量) + if (!this.orderMatchesIncludeSku(itemDetails, includeSku)) { + continue; + } + + const itemSummary = this.buildItemSummary(itemDetails); + const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); + if (!itemSummary || !itemSnapshotKey) { + continue; + } + + const itemPartInfo = this.getOrderItemPart(g.orders[0] || {}); + const logisticsName = String(g.orders[0].logistics_name || '').trim(); + const itemDetailMachine = this.buildMachineStructureToken({ + item_part_type: itemPartInfo.item_part_type, + item_part: itemPartInfo.item_part, + distinguish_express: distinguishExpress, + logistics_name: logisticsName, + item_snapshot_key: itemSnapshotKey, + }); + + const store_ids = [ ...new Set( + g.orders.map(o => Number(o.store_id || 0)).filter(id => id > 0) + ) ]; + + let first_order_time = null; + let last_order_time = null; + let items_total = 0; + for (const o of g.orders) { + items_total += Number(o.items_total || 0); + if (!first_order_time || o.create_at < first_order_time) first_order_time = o.create_at; + if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; + } + + list.push({ + item_detail: itemSummary, + item_detail_machine: itemDetailMachine, + item_detail_machine_snapshot: itemSnapshotKey, + item_snapshot: itemDetails, + group: g.orders.length, + group_count: g.orders.length, + items_total, + store_id: store_ids.length === 1 ? store_ids[0] : 0, + store_ids, + logistics_name: logisticsName, + distinguish_express: distinguishExpress, + ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), + first_order_time, + last_order_time, + status_summary: this.buildStatusSummary(g.orders), + }); + } + const t6 = Date.now(); + + this.ctx.logger.info('[wave.groupOrderFetchList] 链路耗时', { + warehouseId, + params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, includeSku: includeSku || null }, + counts: { + rawOrders: rawOrders.length, + coarseGroups: coarseGroupMap.size, + filteredGroups: total, + pageOrderIds: pageOrderIds.length, + orderItemRows: orderItemRows.length, + pageItems: list.length, + }, + timing_ms: { + getModel: t1 - t0, + queryOrders: t2 - t1, + coarseGrouping: t3 - t2, + pagination: t4 - t3, + queryItems: t5 - t4, + buildList: t6 - t5, + total: t6 - t0, + }, + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 散单波次可抓取列表。 + * + * 仅处理待处理订单(排除待审核),且排除已在波次中的订单。 + * 与团购抓取共用同一链路,仅排除团购阈值命中的分组。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 抓取列表和分页信息。 + */ + async singleOrderFetchList(data = {}) { + const t0 = Date.now(); + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const model = await this.getOrderModel('pendingOrder', warehouseId); + const t1 = Date.now(); + + const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); + const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); + const sameOrderQuantityInput = requestData.same_order_quantity; + const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); + const explicitSameOrderQuantity = hasSameOrderQuantityInput + ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) + : 0; + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); + const sameOrderQuantity = explicitSameOrderQuantity > 0 + ? explicitSameOrderQuantity + : minGroupOrderFetchQuantity; + const shopName = this.normalizeShopName(requestData.shop_name); + const includeSku = this.normalizeSkuText(requestData.include_sku); + const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); + const { page, pageSize } = this.normalizePagination(requestData); + + const where = { + step: { [Op.in]: [ 1, 2, 3 ] }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + wave_id: 0, + }; + + if (storeId > 0) { + where.store_id = storeId; + } + + if (shopName) { + where.shop_nick = { [Op.like]: `%${shopName}%` }; + } + + // Phase 1: 主表全量查询,用 items_hash 做分组基准 + const rawOrders = await model.findAll({ + where, + attributes: [ + 'id', 'store_id', 'logistics_name', + 'items_hash', 'items', 'items_total', + 'post_status', 'pick_status', 'outbound_status', 'create_at', + ], + raw: true, + order: [[ 'id', 'DESC' ]], + }); + const t2 = Date.now(); + + // Phase 2: 纯内存粗分组,items_hash 相同即为同组,速度快 + // coarseGroupMap: coarseKey -> { orders[] } + const coarseGroupMap = new Map(); + for (const order of rawOrders) { + const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); + if (!coarseKey) { + continue; + } + + if (!coarseGroupMap.has(coarseKey)) { + coarseGroupMap.set(coarseKey, { orders: [] }); + } + + coarseGroupMap.get(coarseKey).orders.push(order); + } + + // 过滤团购阈值(排除团购分组)、排序 + let groupEntries = Array.from(coarseGroupMap.entries()); + groupEntries = groupEntries.filter(([ , g ]) => g.orders.length < sameOrderQuantity); + + groupEntries.sort(([ keyA, gA ], [ keyB, gB ]) => { + if (gB.orders.length !== gA.orders.length) { + return gB.orders.length - gA.orders.length; + } + + return keyA.localeCompare(keyB); + }); + + const total = groupEntries.length; + const t3 = Date.now(); + + // Phase 3: 分页分组,只取当前页 + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + const pageStart = (page - 1) * pageSize; + const pageGroupEntries = groupEntries.slice(pageStart, pageStart + pageSize); + + // 收集当前页每组的代表订单 id(同组 items_hash 相同,只需一条快照即可) + const representativeIdPerGroup = new Map(); // coarseKey -> representativeOrderId + for (const [ coarseKey, g ] of pageGroupEntries) { + const repOrder = g.orders.find(o => Number(o.id) > 0); + if (repOrder) { + representativeIdPerGroup.set(coarseKey, Number(repOrder.id)); + } + } + const pageOrderIds = Array.from(representativeIdPerGroup.values()); + const t4 = Date.now(); + + // Phase 4: 仅查每组代表订单的明细(每页 20 条左右,大幅降低 IN 数量) + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const orderItemRows = pageOrderIds.length > 0 + ? await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: pageOrderIds } }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }) + : []; + const t5 = Date.now(); + + // 构建明细索引 + const orderItemsMap = new Map(); + for (const row of orderItemRows) { + const orderId = Number(row && row.order_id); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!orderItemsMap.has(orderId)) { + orderItemsMap.set(orderId, []); + } + + orderItemsMap.get(orderId).push(row); + } + + // Phase 5: 构建当前页响应,每组取一个代表订单的 item_snapshot 作为展示快照 + const list = []; + for (const [ coarseKey, g ] of pageGroupEntries) { + // 同粗分组内 items_hash 相同,取该组的代表订单明细作为展示快照 + const representativeId = representativeIdPerGroup.get(coarseKey); + const itemRows = representativeId ? (orderItemsMap.get(representativeId) || []) : []; + const itemDetails = this.mergeOrderItemDetails(itemRows); + + // includeSku 精确过滤(页内应用,total 为粗分组数量) + if (!this.orderMatchesIncludeSku(itemDetails, includeSku)) { + continue; + } + + const itemSummary = this.buildItemSummary(itemDetails); + const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); + if (!itemSummary || !itemSnapshotKey) { + continue; + } + + const itemPartInfo = this.getOrderItemPart(g.orders[0] || {}); + const logisticsName = String(g.orders[0].logistics_name || '').trim(); + const itemDetailMachine = this.buildMachineStructureToken({ + item_part_type: itemPartInfo.item_part_type, + item_part: itemPartInfo.item_part, + distinguish_express: distinguishExpress, + logistics_name: logisticsName, + item_snapshot_key: itemSnapshotKey, + }); + + const store_ids = [ ...new Set( + g.orders.map(o => Number(o.store_id || 0)).filter(id => id > 0) + ) ]; + + let first_order_time = null; + let last_order_time = null; + let items_total = 0; + for (const o of g.orders) { + items_total += Number(o.items_total || 0); + if (!first_order_time || o.create_at < first_order_time) first_order_time = o.create_at; + if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; + } + + list.push({ + item_detail: itemSummary, + item_detail_machine: itemDetailMachine, + item_detail_machine_snapshot: itemSnapshotKey, + item_snapshot: itemDetails, + group: g.orders.length, + group_count: g.orders.length, + items_total, + store_id: store_ids.length === 1 ? store_ids[0] : 0, + store_ids, + logistics_name: logisticsName, + distinguish_express: distinguishExpress, + ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), + first_order_time, + last_order_time, + status_summary: this.buildStatusSummary(g.orders), + }); + } + const t6 = Date.now(); + + this.ctx.logger.info('[wave.singleOrderFetchList] 链路耗时', { + warehouseId, + params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, includeSku: includeSku || null }, + counts: { + rawOrders: rawOrders.length, + coarseGroups: coarseGroupMap.size, + filteredGroups: total, + pageOrderIds: pageOrderIds.length, + orderItemRows: orderItemRows.length, + pageItems: list.length, + }, + timing_ms: { + getModel: t1 - t0, + queryOrders: t2 - t1, + coarseGrouping: t3 - t2, + pagination: t4 - t3, + queryItems: t5 - t4, + buildList: t6 - t5, + total: t6 - t0, + }, + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 波次列表查询。 + * + * 默认查询状态为 0/1 的波次,并附带订单分配状态汇总。 + * + * @param {Object} data 请求参数。 + * @param {Object} data.pagination 分页参数。 + * @return {Promise} 波次列表及分页信息。 + */ + async batchList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData, { + maxPageSize: BATCH_LIST_MAX_PAGE_SIZE, + }); + const waveStatusList = [ 0, 1 ]; + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const whereClause = this.buildBatchListWhereClause(requestData.where); + const storageAssignmentFilterClause = this.buildBatchListStorageAssignmentFilterClause(whereClause.storageAssignmentStatus); + const baseBatchWhereSql = ` + warehouse_id = :warehouseId + AND wave_status IN (:waveStatusList) + ${whereClause.sql} + `; + const batchListFromSql = ` + FROM ( + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + distinguish_express, + logistics_name, + item_snapshot_key, + warehouse_id, + creator, + create_time, + update_time + FROM wms_wave_batch + WHERE ${baseBatchWhereSql} + ) wb + LEFT JOIN ( + SELECT + candidate_wave.wave_id, + COUNT(od.wave_id) AS order_total, + SUM(CASE WHEN od.storage_status = 'none' THEN 1 ELSE 0 END) AS storage_none_count, + SUM(CASE WHEN od.storage_status = 'fin' THEN 1 ELSE 0 END) AS storage_fin_count, + SUM(CASE WHEN od.storage_status = 'error' THEN 1 ELSE 0 END) AS storage_error_count + FROM ( + SELECT wave_id + FROM wms_wave_batch + WHERE ${baseBatchWhereSql} + ) candidate_wave + LEFT JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id + GROUP BY candidate_wave.wave_id + ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id + WHERE 1 = 1 + ${storageAssignmentFilterClause.sql} + `; + + const listSql = ` + SELECT + wb.wave_id, + wb.wave_no, + wb.wave_type, + wb.wave_status, + wb.total_orders, + wb.processed_orders, + wb.distinguish_express, + wb.logistics_name, + wb.item_snapshot_key, + wb.warehouse_id, + wb.creator, + wb.create_time, + wb.update_time + ${batchListFromSql} + ORDER BY wb.total_orders DESC, wb.wave_id DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + ${batchListFromSql} + `; + + const [ batchRows, totalRows ] = await Promise.all([ + this.ctx.model.query(listSql, { + replacements: { + warehouseId, + waveStatusList, + ...whereClause.replacements, + ...storageAssignmentFilterClause.replacements, + limit: pageSize, + offset, + }, + }), + this.ctx.model.query(countSql, { + replacements: { + warehouseId, + waveStatusList, + ...whereClause.replacements, + ...storageAssignmentFilterClause.replacements, + }, + }), + ]); + + const rawList = Array.isArray(batchRows && batchRows[0]) ? batchRows[0] : []; + const totalRowList = Array.isArray(totalRows && totalRows[0]) ? totalRows[0] : []; + const total = Number(totalRowList[0] && totalRowList[0].total || 0); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + if (rawList.length === 0) { + return this.success('ok', { + list: [], + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + const waveIds = rawList + .map(item => Number(item && item.wave_id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + const orderRows = waveIds.length > 0 + ? await orderModel.findAll({ + where: { + wave_id: { [Op.in]: waveIds }, + }, + attributes: [ 'wave_id', 'storage_status', 'post_status', 'print_status' ], + raw: true, + }) + : []; + + const waveOrderStatsMap = new Map(); + for (const row of orderRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + if (!waveOrderStatsMap.has(waveId)) { + waveOrderStatsMap.set(waveId, { + orderCount: 0, + storageNoneCount: 0, + storageFinCount: 0, + storageErrorCount: 0, + expressNoneCount: 0, + expressFinCount: 0, + expressErrorCount: 0, + printNoneCount: 0, + printFinCount: 0, + }); + } + + const stats = waveOrderStatsMap.get(waveId); + const storageStatus = String(row && row.storage_status || '').trim(); + const expressStatus = String(row && row.post_status || '').trim(); + const printStatus = String(row && row.print_status || '').trim(); + + stats.orderCount += 1; + if (storageStatus === 'none') { + stats.storageNoneCount += 1; + } else if (storageStatus === 'fin') { + stats.storageFinCount += 1; + } else if (storageStatus === 'error') { + stats.storageErrorCount += 1; + } + + if (expressStatus === 'none') { + stats.expressNoneCount += 1; + } else if (expressStatus === 'fin') { + stats.expressFinCount += 1; + } else if (expressStatus === 'error') { + stats.expressErrorCount += 1; + } + + if (printStatus === 'none') { + stats.printNoneCount += 1; + } else if (printStatus === 'fin') { + stats.printFinCount += 1; + } + } + + const list = rawList.map(batch => { + const waveId = Number(batch && batch.wave_id || 0); + const stats = waveOrderStatsMap.get(waveId) || {}; + const orderCount = Number(stats.orderCount || 0); + const storageNoneCount = Number(stats.storageNoneCount || 0); + const storageFinCount = Number(stats.storageFinCount || 0); + const storageErrorCount = Number(stats.storageErrorCount || 0); + const expressNoneCount = Number(stats.expressNoneCount || 0); + const expressFinCount = Number(stats.expressFinCount || 0); + const expressErrorCount = Number(stats.expressErrorCount || 0); + const printNoneCount = Number(stats.printNoneCount || 0); + const printFinCount = Number(stats.printFinCount || 0); + + return { + wave_id: waveId, + wave_no: String(batch && batch.wave_no || '').trim(), + wave_type: Number(batch && batch.wave_type || 0), + wave_status: Number(batch && batch.wave_status || 0), + total_orders: Number(batch && batch.total_orders || 0), + processed_orders: Number(batch && batch.processed_orders || 0), + item_detail_machine: String(batch && batch.item_detail_machine || '').trim(), + item_part_type: String(batch && batch.item_part_type || '').trim(), + item_part: String(batch && batch.item_part || '').trim(), + distinguish_express: Number(batch && batch.distinguish_express || 0), + logistics_name: String(batch && batch.logistics_name || '').trim(), + item_snapshot_key: String(batch && batch.item_snapshot_key || '').trim(), + warehouse_id: Number(batch && batch.warehouse_id || 0), + creator: String(batch && batch.creator || '').trim(), + create_time: batch && batch.create_time || null, + update_time: batch && batch.update_time || null, + order_count: orderCount, + storage_assignment_status: this.resolveAssignmentStatus(orderCount, storageNoneCount, storageFinCount, storageErrorCount), + express_assignment_status: this.resolveAssignmentStatus(orderCount, expressNoneCount, expressFinCount, expressErrorCount), + print_assignment_status: this.resolveAssignmentStatus(orderCount, printNoneCount, printFinCount, 0, { + none: '未打印', + partial: '部分打印', + finished: '已打印', + }), + }; + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 批量解除波次任务提交接口。 + * + * 仅处理当前登录仓库下的波次与订单,提交后异步执行。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务提交结果。 + */ + async batchCancel(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchCancelWaveIds(data); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchCancelTaskId(data); + const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); + const existingTask = await this.getBatchCancelTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: 'Batch cancel task already exists. Check progress with order.wave.batchCancelTaskProgress', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchCancelTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + total_wave_count: normalizedWaveIds.length, + processed_wave_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[wave.batchCancel] 任务提交成功', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + }); + + setImmediate(() => { + this.runBatchCancelTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + }).catch(error => { + this.ctx.logger.error('[wave.batchCancel] 后台任务异常', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: 'Batch cancel submitted. Check progress with order.wave.batchCancelTaskProgress', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解除波次任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchCancelTaskProgress(data = {}) { + const taskId = this.normalizeBatchCancelTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchCancelTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.affected_wave_ids = Array.isArray(result.affected_wave_ids) ? result.affected_wave_ids : []; + payload.affected_order_count = Number(result.affected_order_count || 0); + payload.canceled_wave_count = Number(result.canceled_wave_count || 0); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_CANCEL_FAILED'; + payload.failed_wave_id = Number(cachedProgress.failed_wave_id || 0); + payload.failed_wave_no = String(cachedProgress.failed_wave_no || '').trim(); + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 批次分配快递号任务提交接口。 + * + * 仅接收当前仓库下波次ID,提交后立即返回 task_id,实际分配由后台异步执行。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务受理结果。 + */ + async batchAllocateExpress(data = {}) { + const traceId = this.buildBatchAllocateExpressTraceId(data); + const requestSnapshot = { + warehouse_id: data && (data.warehouse_id ?? data.warehouseId), + wave_ids: data && (data.wave_ids ?? data.waveIds ?? data.ids), + task_id: data && (data.task_id ?? data.taskId), + }; + + this.ctx.logger.info('[wave.batchAllocateExpress] 入口请求', { + traceId, + requestSnapshot, + }); + + try { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-仓库上下文缺失', { + traceId, + contextWarehouseId, + requestSnapshot, + }); + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-warehouse_id 非法', { + traceId, + contextWarehouseId, + requestWarehouseId, + requestSnapshot, + }); + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-warehouse_id 与上下文不一致', { + traceId, + contextWarehouseId, + requestWarehouseId, + requestSnapshot, + }); + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchAllocateExpressWaveIds(data); + if (normalizedWaveIds.length === 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-wave_ids 为空', { + traceId, + warehouseId, + requestSnapshot, + }); + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchAllocateExpressTaskId(data); + const taskId = requestedTaskId || this.generateBatchAllocateExpressTaskId(warehouseId); + const existingTask = await this.getBatchAllocateExpressTaskProgress(taskId); + + if (existingTask) { + this.ctx.logger.info('[wave.batchAllocateExpress] 命中幂等任务缓存,直接返回', { + traceId, + taskId, + warehouseId, + waveIds: normalizedWaveIds, + cachedState: String(existingTask.state || '').trim() || 'submitted', + }); + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: 'Batch allocate express task already exists. Check progress with order.wave.batchAllocateExpressTaskProgress', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchAllocateExpressTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + total_wave_count: normalizedWaveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + trace_id: traceId, + }); + + this.ctx.logger.info('[wave.batchAllocateExpress] 任务提交成功', { + traceId, + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + waveIds: normalizedWaveIds, + }); + + setImmediate(() => { + this.runBatchAllocateExpressTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + trace_id: traceId, + }).catch(error => { + this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务异常', { + traceId, + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: 'Batch allocate express submitted. Check progress with order.wave.batchAllocateExpressTaskProgress', + accepted_at: acceptedAt, + }); + } catch (error) { + this.ctx.logger.error('[wave.batchAllocateExpress] 入口处理异常', { + traceId, + requestSnapshot, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + throw error; + } + } + + /** + * 查询批次分配快递号任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchAllocateExpressTaskProgress(data = {}) { + const taskId = this.normalizeBatchAllocateExpressTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchAllocateExpressTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.allocated_order_count = Number(result.allocated_order_count || 0); + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + payload.message = String(result.message || '').trim(); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 批次分配储位任务提交接口。 + * + * 仅接收当前仓库下波次ID,提交后立即返回 task_id,实际分配由后台异步执行。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务受理结果。 + */ + async batchAllocateStorage(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchAllocateStorageWaveIds(data); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchAllocateStorageTaskId(data); + const taskId = requestedTaskId || this.generateBatchAllocateStorageTaskId(warehouseId); + const existingTask = await this.getBatchAllocateStorageTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: 'Batch allocate storage task already exists. Check progress with order.wave.batchAllocateStorageTaskProgress', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchAllocateStorageTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_wave_count: normalizedWaveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[wave.batchAllocateStorage] 任务提交成功', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + }); + + setImmediate(() => { + this.runBatchAllocateStorageTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + }).catch(error => { + this.ctx.logger.error('[wave.batchAllocateStorage] 后台任务异常', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: 'Batch allocate storage submitted. Check progress with order.wave.batchAllocateStorageTaskProgress', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批次分配储位任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchAllocateStorageTaskProgress(data = {}) { + const taskId = this.normalizeBatchAllocateStorageTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchAllocateStorageTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + const cachedBusinessId = Number(cachedProgress.business_id || 0); + const cachedBusinessIds = this.normalizeIdsInput(cachedProgress.business_ids); + if (cachedBusinessId > 0) { + payload.business_id = cachedBusinessId; + } + if (cachedBusinessIds.length > 0) { + payload.business_ids = cachedBusinessIds; + } + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.allocated_order_count = Number(result.allocated_order_count || cachedProgress.allocated_order_count || 0); + payload.affected_order_count = Number(result.affected_order_count || cachedProgress.affected_order_count || 0); + payload.allocated_order_ids = this.normalizeIdsInput( + result.allocated_order_ids !== undefined + ? result.allocated_order_ids + : cachedProgress.allocated_order_ids + ); + payload.shortage_order_ids = this.normalizeIdsInput( + result.shortage_order_ids !== undefined + ? result.shortage_order_ids + : cachedProgress.shortage_order_ids + ); + payload.affected_order_ids = this.normalizeIdsInput( + result.affected_order_ids !== undefined + ? result.affected_order_ids + : cachedProgress.affected_order_ids + ); + const successBusinessId = Number(result.business_id || payload.business_id || 0); + const successBusinessIds = this.normalizeIdsInput( + result.business_ids !== undefined + ? result.business_ids + : payload.business_ids + ); + if (successBusinessId > 0) { + payload.business_id = successBusinessId; + } + if (successBusinessIds.length > 0) { + payload.business_ids = successBusinessIds; + } + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + payload.message = String(result.message || '').trim(); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.success_order_count = Number(cachedProgress.success_order_count || 0); + payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_ALLOCATE_STORAGE_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 批量将订单从波次中移出。 + * + * 仅处理当前仓库待处理订单中 step in [1,2,3] 且已分配波次(wave_id>0)的订单。 + * 全流程使用事务,确保订单更新与波次统计回写一致。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 订单ID集合(优先)。 + * @param {Array|number|string} data.order_ids 订单ID集合别名。 + * @param {Array|number|string} data.orderIds 订单ID集合别名。 + * @param {Array|number|string} data.order_id 订单ID集合别名。 + * @param {Array|number|string} data.orderId 订单ID集合别名。 + * @param {Array|number|string} data.id 订单ID集合别名。 + * @return {Promise} 批量移出结果。 + */ + async batchRemoveOrders(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const rawIds = data && ( + data.ids !== undefined ? data.ids + : data.order_ids !== undefined ? data.order_ids + : data.orderIds !== undefined ? data.orderIds + : data.order_id !== undefined ? data.order_id + : data.orderId !== undefined ? data.orderId + : data.id + ); + const normalizedIds = this.normalizeIdsInput(rawIds); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const transaction = await this.ctx.model.transaction(); + + try { + const removableRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where: { + id: { [Op.in]: normalizedIds }, + step: { [Op.in]: [ 1, 2, 3 ] }, + wave_id: { [Op.gt]: 0 }, + }, + raw: true, + transaction, + }); + + const removableOrderRows = Array.isArray(removableRows) ? removableRows : []; + const removablePendingIds = [ ...new Set(removableOrderRows + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const removedOrderIds = [ ...new Set(removablePendingIds) ]; + const affectedWaveIds = [ ...new Set(removableOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + const removeOrderLogItems = removableOrderRows + .map(row => { + const orderId = Number(row && row.id || 0); + const waveNo = String(row && row.wave_no || '').trim() || '未知波次'; + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + orderId, + operationCode: 'ORDER_WAVE_REMOVE', + message: `订单从波次 ${waveNo} 中移除`, + }; + }) + .filter(Boolean); + + if (removablePendingIds.length === 0 || affectedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + removed_order_ids: [], + removed_order_count: 0, + affected_wave_ids: [], + updated_wave_ids: [], + emptied_wave_ids: [], + }); + } + + const orderUpdateResult = await orderModel.update({ + wave_id: 0, + wave_no: '', + }, { + where: { + id: { [Op.in]: removablePendingIds }, + }, + transaction, + }); + + const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0); + + const remainingRows = await orderModel.findAll({ + attributes: [ + 'wave_id', + [ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ], + ], + where: { + wave_id: { + [Op.in]: affectedWaveIds, + [Op.gt]: 0, + }, + }, + group: [ 'wave_id' ], + raw: true, + transaction, + }); + + const remainingCountMap = new Map(); + for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) { + const waveId = Number(row && row.wave_id || 0); + const remainingCount = Number(row && row.remaining_count || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0); + } + + const updatedWaveIds = []; + const emptiedWaveIds = []; + + for (const waveId of affectedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + if (remainingCount > 0) { + updatedWaveIds.push(waveId); + } else { + emptiedWaveIds.push(waveId); + } + } + + for (const waveId of updatedWaveIds) { + const remainingCount = Number(remainingCountMap.get(waveId) || 0); + const updateWaveSql = ` + UPDATE wms_wave_batch + SET total_orders = :remainingCount, + processed_orders = LEAST(processed_orders, :remainingCount), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `; + + await this.ctx.model.query(updateWaveSql, { + replacements: { + warehouseId, + waveId, + remainingCount, + }, + transaction, + }); + } + + if (emptiedWaveIds.length > 0) { + const emptyWaveSql = ` + UPDATE wms_wave_batch + SET total_orders = 0, + processed_orders = 0, + wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + await this.ctx.model.query(emptyWaveSql, { + replacements: { + warehouseId, + waveIds: emptiedWaveIds, + }, + transaction, + }); + } + + await transaction.commit(); + await this.batchCreateOrderOperationLogs(removeOrderLogItems, { + warehouseId, + scene: 'batchRemoveOrders', + }); + + return this.success('ok', { + ids: normalizedIds, + removed_order_ids: removedOrderIds, + removed_order_count: Number.isInteger(updatedOrderCount) && updatedOrderCount > 0 ? updatedOrderCount : 0, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: updatedWaveIds, + emptied_wave_ids: emptiedWaveIds, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 批量移除异常订单任务提交接口。 + * + * 仅处理当前登录仓库下命中波次中的异常订单,提交后异步执行。 + * 异常判定与订单模块待处理异常定义保持一致:仅 step=3。 + * 实际移除动作复用既有 batchRemoveOrders 流水线,不重复实现解绑逻辑。 + * + * @param {Object} data 请求参数。 + * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 + * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 + * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 + * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 + * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 + * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 + * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 + * @return {Promise} 任务提交结果。 + */ + async batchRemoveExceptionOrders(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); + if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + if (requestWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + const warehouseId = requestWarehouseId; + const normalizedWaveIds = this.normalizeBatchRemoveExceptionOrdersWaveIds(data); + if (normalizedWaveIds.length === 0) { + throw new Error('wave_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchRemoveExceptionOrdersTaskId(data); + const taskId = requestedTaskId || this.generateBatchRemoveExceptionOrdersTaskId(warehouseId); + const existingTask = await this.getBatchRemoveExceptionOrdersTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: 'Batch remove exception orders task already exists. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchRemoveExceptionOrdersTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + wave_ids: normalizedWaveIds.join(','), + wave_id_list: normalizedWaveIds, + total_wave_count: normalizedWaveIds.length, + processed_wave_count: 0, + total_order_count: 0, + processed_order_count: 0, + removed_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[wave.batchRemoveExceptionOrders] 任务提交成功', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + }); + + setImmediate(() => { + this.runBatchRemoveExceptionOrdersTask({ + taskId, + warehouseId, + waveIds: normalizedWaveIds, + }).catch(error => { + this.ctx.logger.error('[wave.batchRemoveExceptionOrders] 后台任务异常', { + taskId, + warehouseId, + waveCount: normalizedWaveIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: 'Batch remove exception orders submitted. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量移除异常订单任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchRemoveExceptionOrdersTaskProgress(data = {}) { + const taskId = this.normalizeBatchRemoveExceptionOrdersTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchRemoveExceptionOrdersTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; + const payload = { + task_id: taskId, + state, + warehouse_id: Number(cachedProgress.warehouse_id || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + }; + + if (state === 'submitted' || state === 'running') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.removed_order_count = Number(cachedProgress.removed_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.total_order_count = Number(result.total_order_count || 0); + payload.processed_order_count = Number(result.processed_order_count || 0); + payload.removed_order_count = Number(result.removed_order_count || 0); + payload.removed_order_ids = Array.isArray(result.removed_order_ids) ? result.removed_order_ids : []; + payload.affected_wave_ids = Array.isArray(result.affected_wave_ids) ? result.affected_wave_ids : []; + payload.updated_wave_ids = Array.isArray(result.updated_wave_ids) ? result.updated_wave_ids : []; + payload.emptied_wave_ids = Array.isArray(result.emptied_wave_ids) ? result.emptied_wave_ids : []; + payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); + } + + if (state === 'failed') { + payload.progress_percent = Number(cachedProgress.progress_percent || 0); + payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); + payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.total_order_count = Number(cachedProgress.total_order_count || 0); + payload.removed_order_count = Number(cachedProgress.removed_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_REMOVE_EXCEPTION_ORDERS_FAILED'; + payload.failed_wave_id = Number(cachedProgress.failed_wave_id || 0); + payload.failed_wave_no = String(cachedProgress.failed_wave_no || '').trim(); + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量取消任务ID。 + * + * 格式:wave_cancel_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchCancelTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_cancel_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量取消任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchCancelTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 生成可追踪的批量移除异常订单任务ID。 + * + * 格式:wave_remove_exception_orders_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchRemoveExceptionOrdersTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_remove_exception_orders_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量移除异常订单任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchRemoveExceptionOrdersTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量移除异常订单的波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchRemoveExceptionOrdersWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 获取批量移除异常订单任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchRemoveExceptionOrdersTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量移除异常订单任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchRemoveExceptionOrdersTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchRemoveExceptionOrdersTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchRemoveExceptionOrdersTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.batchRemoveExceptionOrders] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批量移除异常订单任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchRemoveExceptionOrdersTaskProgress(taskId = '') { + const cacheKey = this.getBatchRemoveExceptionOrdersTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchRemoveExceptionOrders] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 判断订单是否属于异常可移除范围。 + * + * 与订单模块“待处理异常”语义保持一致:仅 step=3。 + * + * @param {Object} row 订单行数据。 + * @return {boolean} 是否为异常可移除订单。 + */ + isExceptionRemovableOrder(row = {}) { + const step = Number(row && row.step || 0); + return step === 3; + } + + /** + * 执行批量移除异常订单后台任务。 + * + * 先按波次聚合异常订单,再复用 batchRemoveOrders 流水线执行解绑与波次统计回写。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchRemoveExceptionOrdersTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (waveIds.length === 0) { + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + total_wave_count: waveIds.length, + processed_wave_count: 0, + total_order_count: 0, + processed_order_count: 0, + removed_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_wave_id: 0, + failed_wave_no: '', + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'step' ], + where: { + warehouse_id: warehouseId, + wave_id: { + [Op.in]: waveIds, + }, + step: { + [Op.in]: [ 1, 2, 3 ], + }, + }, + raw: true, + }); + + const waveInfoById = new Map(); + const exceptionOrderIds = []; + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + const orderId = Number(row && row.id || 0); + const waveId = Number(row && row.wave_id || 0); + const waveNo = String(row && row.wave_no || '').trim(); + + if (!Number.isInteger(orderId) || orderId <= 0 || !Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + if (!waveInfoById.has(waveId)) { + waveInfoById.set(waveId, { + wave_id: waveId, + wave_no: waveNo || '未知波次', + }); + } + + if (this.isExceptionRemovableOrder(row)) { + exceptionOrderIds.push(orderId); + } + } + + const targetWaves = waveIds + .map(waveId => waveInfoById.get(waveId)) + .filter(Boolean); + const normalizedExceptionOrderIds = [ ...new Set(exceptionOrderIds) ]; + + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: targetWaves.length, + total_order_count: normalizedExceptionOrderIds.length, + processed_order_count: normalizedExceptionOrderIds.length, + progress_percent: targetWaves.length === 0 ? 100 : 80, + }); + + if (normalizedExceptionOrderIds.length === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: targetWaves.length, + total_order_count: 0, + processed_order_count: 0, + removed_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + removed_order_ids: [], + removed_order_count: 0, + affected_wave_ids: [], + updated_wave_ids: [], + emptied_wave_ids: [], + total_order_count: 0, + processed_order_count: 0, + duration_ms: durationMs, + message: '未找到可移除的异常订单', + }, + }); + return; + } + + const removeResult = await this.batchRemoveOrders({ + ids: normalizedExceptionOrderIds, + }); + + const resultPayload = this.isPlainObject(removeResult) ? removeResult : {}; + const removedOrderIds = Array.isArray(resultPayload.removed_order_ids) ? resultPayload.removed_order_ids : []; + const affectedWaveIds = Array.isArray(resultPayload.affected_wave_ids) ? resultPayload.affected_wave_ids : []; + const updatedWaveIds = Array.isArray(resultPayload.updated_wave_ids) ? resultPayload.updated_wave_ids : []; + const emptiedWaveIds = Array.isArray(resultPayload.emptied_wave_ids) ? resultPayload.emptied_wave_ids : []; + const removedOrderCount = Number(resultPayload.removed_order_count || removedOrderIds.length || 0); + const durationMs = Date.now() - startTime; + + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: targetWaves.length, + total_order_count: normalizedExceptionOrderIds.length, + processed_order_count: normalizedExceptionOrderIds.length, + removed_order_count: removedOrderCount, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + removed_order_ids: removedOrderIds, + removed_order_count: removedOrderCount, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: updatedWaveIds, + emptied_wave_ids: emptiedWaveIds, + total_order_count: normalizedExceptionOrderIds.length, + processed_order_count: normalizedExceptionOrderIds.length, + duration_ms: durationMs, + message: `已移除 ${removedOrderCount} 条异常订单`, + }, + }); + } catch (error) { + await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_REMOVE_EXCEPTION_ORDERS_FAILED', + }); + } + } + + /** + * 归一化批量取消波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchCancelWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 获取批量取消任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchCancelTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_CANCEL_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量取消任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchCancelTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchCancelTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchCancelTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_CANCEL_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.batchCancel] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批量取消任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchCancelTaskProgress(taskId = '') { + const cacheKey = this.getBatchCancelTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchCancel] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 执行批量解除波次后台任务。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchCancelTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchCancelTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (waveIds.length === 0) { + await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + total_wave_count: waveIds.length, + processed_wave_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_wave_id: 0, + failed_wave_no: '', + }); + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const querySql = ` + SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:ids) + `; + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + ids: waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const targetWaves = (Array.isArray(queryRows) ? queryRows : []) + .map(row => ({ + wave_id: Number(row && row.wave_id || 0), + wave_no: String(row && row.wave_no || '').trim(), + })) + .filter(item => Number.isInteger(item.wave_id) && item.wave_id > 0); + + if (targetWaves.length === 0) { + await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: 0, + processed_wave_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + result: { + ids: waveIds, + affected_wave_ids: [], + affected_order_count: 0, + canceled_wave_count: 0, + duration_ms: Date.now() - startTime, + }, + }); + return; + } + + let processedWaveCount = 0; + let affectedOrderCount = 0; + let canceledWaveCount = 0; + const affectedWaveIds = []; + + for (const wave of targetWaves) { + const waveId = Number(wave.wave_id || 0); + const waveNo = String(wave.wave_no || '').trim() || '未知波次'; + const transaction = await this.ctx.model.transaction(); + + try { + const affectedOrderRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no' ], + where: { + wave_id: waveId, + }, + raw: true, + transaction, + }); + + const cancelOrderLogItems = (Array.isArray(affectedOrderRows) ? affectedOrderRows : []) + .map(row => { + const orderId = Number(row && row.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + orderId, + operationCode: 'ORDER_WAVE_CANCEL', + message: `波次 ${waveNo} 被删除,订单移出波次`, + }; + }) + .filter(Boolean); + + const orderUpdateResult = await orderModel.update({ + wave_id: 0, + wave_no: '', + }, { + where: { + wave_id: waveId, + }, + transaction, + }); + const currentAffectedOrderCount = Number( + Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0 + ); + + const cancelSql = ` + UPDATE wms_wave_batch + SET wave_status = -1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + `; + const cancelResult = await this.ctx.model.query(cancelSql, { + replacements: { + warehouseId, + waveId, + }, + transaction, + }); + const cancelMeta = Array.isArray(cancelResult) ? cancelResult[1] : null; + const currentCanceledWaveCount = Number( + cancelMeta && (cancelMeta.affectedRows || cancelMeta.affectedCount || cancelMeta.rowCount) + || 0 + ); + + await transaction.commit(); + + await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { + warehouseId, + scene: 'batchCancel', + }); + + processedWaveCount += 1; + affectedOrderCount += Number.isInteger(currentAffectedOrderCount) && currentAffectedOrderCount > 0 + ? currentAffectedOrderCount + : 0; + canceledWaveCount += Number.isInteger(currentCanceledWaveCount) && currentCanceledWaveCount > 0 + ? currentCanceledWaveCount + : 0; + if (currentCanceledWaveCount > 0) { + affectedWaveIds.push(waveId); + } + + const progressPercent = Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)); + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: progressPercent, + }); + } catch (error) { + await transaction.rollback(); + await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + end_time: Date.now(), + duration_ms: Date.now() - startTime, + failed_wave_id: waveId, + failed_wave_no: waveNo, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_CANCEL_FAILED', + result: { + ids: waveIds, + affected_wave_ids: affectedWaveIds, + affected_order_count: affectedOrderCount, + canceled_wave_count: canceledWaveCount, + duration_ms: Date.now() - startTime, + }, + }); + return; + } + } + + const durationMs = Date.now() - startTime; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + ids: waveIds, + affected_wave_ids: affectedWaveIds, + affected_order_count: affectedOrderCount, + canceled_wave_count: canceledWaveCount, + duration_ms: durationMs, + }, + }); + } + + /** + * 生成可追踪的批次分配快递号任务ID。 + * + * 格式:wave_allocate_express_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchAllocateExpressTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_allocate_express_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批次分配快递号任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchAllocateExpressTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批次分配快递号波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchAllocateExpressWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 获取批次分配快递号任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchAllocateExpressTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批次分配快递号任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchAllocateExpressTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchAllocateExpressTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchAllocateExpressTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + const traceId = this.buildBatchAllocateExpressTraceId(safeData, taskId); + + try { + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存回写前', { + traceId, + taskId: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + warehouseId: Number(mergedPayload.warehouse_id || 0), + waveIds: mergedPayload.wave_id_list || mergedPayload.wave_ids || '', + totalOrderCount: Number(mergedPayload.total_order_count || 0), + processedOrderCount: Number(mergedPayload.processed_order_count || 0), + }); + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS); + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存回写后', { + traceId, + taskId: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + }); + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批次分配快递号任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchAllocateExpressTaskProgress(taskId = '') { + const cacheKey = this.getBatchAllocateExpressTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取前', { + traceId: this.buildBatchAllocateExpressTraceId({}, taskId), + taskId: String(taskId || '').trim(), + }); + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取后-未命中', { + traceId: this.buildBatchAllocateExpressTraceId({}, taskId), + taskId: String(taskId || '').trim(), + }); + return null; + } + + this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取后-命中', { + traceId: this.buildBatchAllocateExpressTraceId(cached, taskId), + taskId: String(taskId || '').trim(), + state: String(cached.state || '').trim() || 'submitted', + }); + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 生成可追踪的批次分配储位任务ID。 + * + * 格式:wave_allocate_storage_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchAllocateStorageTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_allocate_storage_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批次分配储位任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchAllocateStorageTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批次分配储位波次ID参数。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的波次ID数组。 + */ + normalizeBatchAllocateStorageWaveIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawWaveIds = normalizedData.wave_ids !== undefined + ? normalizedData.wave_ids + : normalizedData.waveIds !== undefined + ? normalizedData.waveIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : normalizedData.wave_id !== undefined + ? normalizedData.wave_id + : normalizedData.waveId; + + return this.normalizeIdsInput(rawWaveIds); + } + + /** + * 归一化批次分配储位任务数量。 + * + * @param {*} value 原始数量值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 非负整数数量。 + */ + normalizeBatchAllocateStorageTaskCount(value, defaultValue = 0) { + const normalizedValue = Number(value); + if (!Number.isFinite(normalizedValue)) { + return Math.max(0, Number(defaultValue || 0)); + } + + const safeValue = Math.floor(normalizedValue); + if (!Number.isInteger(safeValue) || safeValue < 0) { + return 0; + } + + return safeValue; + } + + /** + * 构建批次分配储位 running 状态的进度写入数据。 + * + * running 阶段的 progress_percent 强制上限 99,避免在任务真正完成前提前显示 100%。 + * + * @param {Object} payload 进度回调载荷。 + * @param {Object} cachedProgress 当前缓存中的任务进度。 + * @return {{ total_order_count: number, processed_order_count: number, progress_percent: number }} 进度写入数据。 + */ + buildBatchAllocateStorageRunningProgressPayload(payload = {}, cachedProgress = {}) { + const normalizedPayload = this.isPlainObject(payload) ? payload : {}; + const normalizedCache = this.isPlainObject(cachedProgress) ? cachedProgress : {}; + + const totalOrderCount = this.normalizeBatchAllocateStorageTaskCount( + normalizedPayload.total_count, + normalizedCache.total_order_count + ); + const rawProcessedOrderCount = this.normalizeBatchAllocateStorageTaskCount( + normalizedPayload.processed_count, + normalizedCache.processed_order_count + ); + const processedOrderCount = totalOrderCount > 0 + ? Math.min(rawProcessedOrderCount, totalOrderCount) + : rawProcessedOrderCount; + + const fallbackProgressPercent = this.normalizeBatchAllocateStorageTaskCount( + normalizedPayload.progress_percent, + normalizedCache.progress_percent + ); + const calculatedProgressPercent = totalOrderCount > 0 + ? Math.round((processedOrderCount / totalOrderCount) * 100) + : fallbackProgressPercent; + + return { + total_order_count: totalOrderCount, + processed_order_count: processedOrderCount, + progress_percent: Math.max(0, Math.min(99, calculatedProgressPercent)), + }; + } + + /** + * 归一化批次分配储位成功态订单ID列表。 + * + * @param {*} value 原始订单ID集合。 + * @return {Array} 去重后的订单ID列表。 + */ + normalizeBatchAllocateStorageOrderIds(value) { + return [ ...new Set(this.normalizeIdsInput(value)) ]; + } + + /** + * 获取批次分配储位任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchAllocateStorageTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 获取批次分配储位仓库并发锁键。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 锁键。 + */ + getBatchAllocateStorageWarehouseLockKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return ''; + } + + return `wave_allocate_storage_lock_${normalizedWarehouseId}`; + } + + /** + * 尝试获取批次分配储位仓库维度并发锁。 + * + * 该锁仅在当前 Node.js 进程内生效,用于避免同仓库并发触发多个大事务。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [taskId=''] 当前任务ID。 + * @return {{ acquired: boolean, ownerTaskId: string }} 获取结果。 + */ + tryAcquireBatchAllocateStorageWarehouseLock(warehouseId = 0, taskId = '') { + const lockKey = this.getBatchAllocateStorageWarehouseLockKey(warehouseId); + if (!lockKey) { + return { + acquired: false, + ownerTaskId: '', + }; + } + + if (BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.has(lockKey)) { + return { + acquired: false, + ownerTaskId: String(BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.get(lockKey) || '').trim(), + }; + } + + BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.set(lockKey, String(taskId || '').trim()); + + return { + acquired: true, + ownerTaskId: String(taskId || '').trim(), + }; + } + + /** + * 释放批次分配储位仓库维度并发锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [taskId=''] 当前任务ID。 + * @return {void} + */ + releaseBatchAllocateStorageWarehouseLock(warehouseId = 0, taskId = '') { + const lockKey = this.getBatchAllocateStorageWarehouseLockKey(warehouseId); + if (!lockKey) { + return; + } + + const ownerTaskId = String(BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.get(lockKey) || '').trim(); + const normalizedTaskId = String(taskId || '').trim(); + + if (!ownerTaskId || ownerTaskId === normalizedTaskId) { + BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.delete(lockKey); + } + } + + /** + * 写入批次分配储位任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} status 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchAllocateStorageTaskProgress(taskId = '', status = 'submitted', data = {}) { + const cacheKey = this.getBatchAllocateStorageTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchAllocateStorageTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(status || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取批次分配储位任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchAllocateStorageTaskProgress(taskId = '') { + const cacheKey = this.getBatchAllocateStorageTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.batchAllocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 判断是否为 business_key 列不存在错误。 + * + * 兼容 MySQL/Sequelize 常见报错文案,例如: + * Unknown column 'business_key' in 'field list' + * + * @param {Error|Object} error 异常对象。 + * @return {boolean} 是否为 business_key 缺列错误。 + */ + isMissingBusinessKeyColumnError(error) { + const messageList = [ + error && error.message, + error && error.parent && error.parent.message, + error && error.original && error.original.message, + error && error.sqlMessage, + ] + .map(item => String(item || '').toLowerCase()) + .filter(Boolean); + + return messageList.some(message => { + const hasUnknownColumn = message.includes('unknown column') || message.includes('column does not exist'); + const hasBusinessKey = message.includes('business_key'); + return hasUnknownColumn && hasBusinessKey; + }); + } + + /** + * 执行批次分配快递号后台任务。 + * + * 任务仅负责提交分配请求到快递分配流水线,实际分配过程由快递服务异步处理。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchAllocateExpressTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchAllocateExpressTaskProgress(normalizedTaskId); + const traceId = this.buildBatchAllocateExpressTraceId(cachedTask || params, normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + this.ctx.logger.info('[wave.batchAllocateExpress] 后台任务入口', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + paramsSnapshot: { + warehouseId: params && params.warehouseId, + waveIds: params && params.waveIds, + }, + }); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 后台任务参数校验失败-warehouse_id 非法', { + traceId, + taskId: normalizedTaskId, + warehouseId, + }); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + trace_id: traceId, + }); + return; + } + + if (waveIds.length === 0) { + this.ctx.logger.warn('[wave.batchAllocateExpress] 后台任务参数校验失败-wave_ids 为空', { + traceId, + taskId: normalizedTaskId, + warehouseId, + }); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + trace_id: traceId, + }); + return; + } + + const startTime = Date.now(); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + total_wave_count: waveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + trace_id: traceId, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const baseOrderWhere = { + warehouse_id: warehouseId, + wave_id: { + [Op.in]: waveIds, + }, + step: { + [Op.in]: [ 1, 2, 3 ], + }, + }; + let orderRows = []; + let useBusinessKeyColumn = true; + + try { + orderRows = await orderModel.findAll({ + attributes: [ 'id', 'business_key' ], + where: baseOrderWhere, + raw: true, + }); + } catch (error) { + if (!this.isMissingBusinessKeyColumnError(error)) { + throw error; + } + + useBusinessKeyColumn = false; + this.ctx.logger.warn('[wave.batchAllocateExpress] 订单分表缺少 business_key 列,降级为仅查询 id', { + traceId, + taskId: normalizedTaskId, + warehouseId, + }); + orderRows = await orderModel.findAll({ + attributes: [ 'id' ], + where: baseOrderWhere, + raw: true, + }); + } + + this.ctx.logger.info('[wave.batchAllocateExpress] 订单筛选完成', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + useBusinessKeyColumn, + matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, + }); + + const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) + .map(row => { + const orderId = Number(row && row.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 1); + return { + order_id: orderId, + business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 1, + }; + }) + .filter(Boolean); + + if (normalizedOrders.length === 0) { + this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + }); + const durationMs = Date.now() - startTime; + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + allocated_order_count: 0, + duration_ms: durationMs, + message: '未找到可分配快递号的订单', + }, + trace_id: traceId, + }); + return; + } + + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + total_order_count: normalizedOrders.length, + trace_id: traceId, + }); + + this.ctx.logger.info('[wave.batchAllocateExpress] 即将调用快递号分配流水线', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + totalOrderCount: normalizedOrders.length, + sampleOrderIds: normalizedOrders.slice(0, 20).map(item => Number(item && item.order_id || 0)).filter(Boolean), + }); + const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(normalizedOrders); + const durationMs = Date.now() - startTime; + + this.ctx.logger.info('[wave.batchAllocateExpress] 快递号分配流水线执行完成', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + totalOrderCount: normalizedOrders.length, + durationMs, + pipelineResult, + }); + + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + total_order_count: normalizedOrders.length, + processed_order_count: normalizedOrders.length, + success_order_count: normalizedOrders.length, + failed_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + allocated_order_count: normalizedOrders.length, + duration_ms: durationMs, + message: String(pipelineResult && pipelineResult.message || '分配快递任务已提交').trim(), + }, + trace_id: traceId, + }); + } catch (error) { + this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务执行失败', { + traceId, + taskId: normalizedTaskId, + warehouseId, + waveIds, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED', + trace_id: traceId, + }); + } + } + + /** + * 执行批次分配储位后台任务。 + * + * 任务仅负责按波次拉取订单并提交储位分配流水线,实际分配过程复用储位分配服务。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchAllocateStorageTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchAllocateStorageTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const waveIds = this.normalizeIdsInput( + cachedTask && cachedTask.wave_ids !== undefined + ? cachedTask.wave_ids + : params && params.waveIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (waveIds.length === 0) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'wave_ids 参数不能为空或格式错误', + error_code: 'INVALID_WAVE_IDS', + }); + return; + } + + const startTime = Date.now(); + const lockResult = this.tryAcquireBatchAllocateStorageWarehouseLock(warehouseId, normalizedTaskId); + if (!lockResult.acquired) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: lockResult.ownerTaskId + ? `同仓库存在执行中的批量储位分配任务,请稍后重试(running_task_id=${lockResult.ownerTaskId})` + : '同仓库存在执行中的批量储位分配任务,请稍后重试', + error_code: 'WAVE_BATCH_ALLOCATE_STORAGE_WAREHOUSE_CONFLICT', + }); + return; + } + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + wave_ids: waveIds.join(','), + wave_id_list: waveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_wave_count: waveIds.length, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ 'id' ], + where: { + warehouse_id: warehouseId, + wave_id: { + [Op.in]: waveIds, + }, + step: { + [Op.in]: [ 1, 2, 3 ], + }, + }, + raw: true, + }); + + const normalizedOrders = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] + .map(orderId => ({ + order_id: orderId, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + })); + const normalizedOrderIds = normalizedOrders.map(item => Number(item.order_id || 0)).filter(Boolean); + + if (normalizedOrderIds.length === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_order_count: 0, + processed_order_count: 0, + success_order_count: 0, + failed_order_count: 0, + affected_order_ids: [], + affected_order_count: 0, + allocated_order_ids: [], + allocated_order_count: 0, + shortage_order_ids: [], + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + affected_order_ids: [], + affected_order_count: 0, + allocated_order_ids: [], + allocated_order_count: 0, + shortage_order_ids: [], + duration_ms: durationMs, + message: '未找到可分配储位的订单', + }, + }); + return; + } + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_order_count: normalizedOrderIds.length, + }); + + const progressCallback = async callbackPayload => { + const latestProgress = await this.getBatchAllocateStorageTaskProgress(normalizedTaskId); + const runningProgressPayload = this.buildBatchAllocateStorageRunningProgressPayload( + callbackPayload, + latestProgress || { + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + progress_percent: 0, + } + ); + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + ...runningProgressPayload, + }); + }; + + const pipelineResult = await this.service.systems.orderStorageAllocation.allocateStorage({ + ids: normalizedOrderIds, + orders: normalizedOrders, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + progress_callback: progressCallback, + }); + + if (!this.isPlainObject(pipelineResult) || Number(pipelineResult.code) !== 200) { + throw new Error(String(pipelineResult && pipelineResult.message || '储位分配任务提交失败').trim()); + } + + const resultData = this.isPlainObject(pipelineResult.data) ? pipelineResult.data : {}; + const pendingOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.pending_order_ids); + const affectedOrderIds = pendingOrderIds.length > 0 + ? pendingOrderIds + : this.normalizeBatchAllocateStorageOrderIds(normalizedOrderIds); + const allocatedOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.allocated_order_ids); + const shortageOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.shortage_order_ids); + const affectedOrderCount = affectedOrderIds.length; + const successOrderCount = allocatedOrderIds.length; + const failedOrderCount = shortageOrderIds.length > 0 + ? shortageOrderIds.length + : Math.max(0, affectedOrderCount - successOrderCount); + const durationMs = Date.now() - startTime; + + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_wave_count: waveIds.length, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + total_order_count: affectedOrderCount, + processed_order_count: affectedOrderCount, + success_order_count: successOrderCount, + failed_order_count: failedOrderCount, + affected_order_ids: affectedOrderIds, + affected_order_count: affectedOrderCount, + allocated_order_ids: allocatedOrderIds, + allocated_order_count: successOrderCount, + shortage_order_ids: shortageOrderIds, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + wave_ids: waveIds, + business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, + business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, + affected_order_ids: affectedOrderIds, + affected_order_count: affectedOrderCount, + allocated_order_ids: allocatedOrderIds, + allocated_order_count: successOrderCount, + shortage_order_ids: shortageOrderIds, + duration_ms: durationMs, + message: String(pipelineResult && pipelineResult.message || '分配储位任务已提交').trim(), + }, + }); + } catch (error) { + await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_BATCH_ALLOCATE_STORAGE_FAILED', + }); + } finally { + this.releaseBatchAllocateStorageWarehouseLock(warehouseId, normalizedTaskId); + } + } + + /** + * 批量将波次状态改为“自动加团中”。 + * + * 仅处理当前登录仓库下命中的波次状态,不修改订单表 wave_id。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 波次ID集合。 + * @return {Promise} 批量更新结果。 + */ + async batchAutoGrouping(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const normalizedIds = this.normalizeIdsInput(data && data.ids); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const maxWaveQuantity = await this.getDefaultWaveQuantity(warehouseId); + + const transaction = await this.ctx.model.transaction(); + + try { + const querySql = ` + SELECT wave_id, wave_status, total_orders + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:ids) + `; + + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + ids: normalizedIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const affectedRows = Array.isArray(queryRows) ? queryRows : []; + const affectedWaveIds = [ ...new Set(affectedRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + const skippedDetails = []; + const skippedWaveIds = []; + const updatableWaveIds = []; + + for (const row of affectedRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + const waveStatus = Number(row && row.wave_status || 0); + const totalOrders = Number(row && row.total_orders || 0); + + if (waveStatus >= 2) { + skippedWaveIds.push(waveId); + skippedDetails.push({ + wave_id: waveId, + reason: 'printed_or_after_printed', + }); + continue; + } + + if (totalOrders >= maxWaveQuantity) { + skippedWaveIds.push(waveId); + skippedDetails.push({ + wave_id: waveId, + reason: 'reach_max_wave_quantity', + }); + continue; + } + + updatableWaveIds.push(waveId); + } + + if (affectedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: [], + skipped_wave_ids: [], + skipped_wave_count: 0, + skipped_details: [], + updated_wave_count: 0, + }); + } + + if (updatableWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + skipped_wave_ids: skippedWaveIds, + skipped_wave_count: skippedWaveIds.length, + skipped_details: skippedDetails, + updated_wave_count: 0, + }); + } + + const updateSql = ` + UPDATE wms_wave_batch + SET wave_status = 0, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + const updateResult = await this.ctx.model.query(updateSql, { + replacements: { + warehouseId, + waveIds: updatableWaveIds, + }, + transaction, + }); + + const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; + const updatedWaveCount = Number( + updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) + || updatableWaveIds.length + ); + + await transaction.commit(); + + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + skipped_wave_ids: skippedWaveIds, + skipped_wave_count: skippedWaveIds.length, + skipped_details: skippedDetails, + updated_wave_count: Number.isInteger(updatedWaveCount) && updatedWaveCount > 0 ? updatedWaveCount : 0, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 批量结束“自动加团中”状态。 + * + * 仅处理当前登录仓库下命中的波次,且仅将 wave_status=0 的波次更新为 1(已就绪)。 + * + * @param {Object} data 请求参数。 + * @param {Array|number|string} data.ids 波次ID集合。 + * @return {Promise} 批量结束结果。 + */ + async batchFinishAutoGrouping(data = {}) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const warehouseId = contextWarehouseId; + const normalizedIds = this.normalizeIdsInput(data && data.ids); + if (normalizedIds.length === 0) { + throw new Error('ids 参数不能为空或格式错误'); + } + + const transaction = await this.ctx.model.transaction(); + + try { + const querySql = ` + SELECT wave_id, wave_status + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:ids) + `; + + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + ids: normalizedIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const affectedRows = Array.isArray(queryRows) ? queryRows : []; + const affectedWaveIds = [ ...new Set(affectedRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + if (affectedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: [], + updated_wave_ids: [], + updated_wave_count: 0, + }); + } + + const updatedWaveIds = [ ...new Set(affectedRows + .filter(row => Number(row && row.wave_status || 0) === 0) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + if (updatedWaveIds.length === 0) { + await transaction.commit(); + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: [], + updated_wave_count: 0, + }); + } + + const updateSql = ` + UPDATE wms_wave_batch + SET wave_status = 1, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND wave_status = 0 + `; + + const updateResult = await this.ctx.model.query(updateSql, { + replacements: { + warehouseId, + waveIds: updatedWaveIds, + }, + transaction, + }); + + const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; + const updatedWaveCount = Number( + updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) + || updatedWaveIds.length + ); + + await transaction.commit(); + + return this.success('ok', { + ids: normalizedIds, + affected_wave_ids: affectedWaveIds, + updated_wave_ids: updatedWaveIds, + updated_wave_count: Number.isInteger(updatedWaveCount) && updatedWaveCount > 0 ? updatedWaveCount : 0, + }); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 生成可追踪的抓取任务ID。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 抓取任务ID。 + */ + generateFetchTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const waveIdSeed = this.generateWaveId(); + return `wave_fetch_${safeWarehouseId}_${waveIdSeed}`; + } + + /** + * 归一化抓取任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeFetchTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取抓取任务进度缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getFetchTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${FETCH_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入抓取任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 进度数据。 + * @return {Promise} 无返回值。 + */ + async setFetchTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getFetchTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + ...safePayload, + task_id: String(taskId || '').trim(), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, FETCH_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.fetch] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取抓取任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务进度缓存。 + */ + async getFetchTaskProgress(taskId = '') { + const cacheKey = this.getFetchTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.fetch] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 查询抓取任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async fetchTaskProgress(data = {}) { + const taskId = this.normalizeFetchTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getFetchTaskProgress(taskId); + + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + }); + } + + return this.success('ok', { + task_id: taskId, + ...cachedProgress, + status: String(cachedProgress.status || 'unknown').trim() || 'unknown', + }); + } + + /** + * 执行异步抓取任务。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.defaultQuantity 默认抓取数量。 + * @param {Array} params.structures 结构化抓取请求。 + * @param {string} [params.fetchMode='group'] 抓取模式:group|single。 + * @param {number} [params.maxFetchQuantity=0] single 模式最大抓取订单数上限。 + * @return {Promise} 无返回值。 + */ + async runFetchTask({ + taskId = '', + warehouseId = 0, + defaultQuantity = DEFAULT_MAX_WAVE_QUANTITY, + structures = [], + fetchMode = 'group', + maxFetchQuantity = 0, + } = {}) { + const normalizedTaskId = String(taskId || '').trim(); + const normalizedWarehouseId = Number(warehouseId || 0); + const structureList = Array.isArray(structures) ? structures : []; + const normalizedFetchMode = String(fetchMode || 'group').trim() === 'single' ? 'single' : 'group'; + const normalizedMaxFetchQuantity = Number.isInteger(Number(maxFetchQuantity)) && Number(maxFetchQuantity) > 0 + ? Number(maxFetchQuantity) + : 0; + + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('warehouseId 参数不合法'); + } + + if (structureList.length === 0) { + throw new Error('structures 不能为空'); + } + + if (normalizedFetchMode === 'single' && normalizedMaxFetchQuantity <= 0) { + throw new Error('single 模式要求 maxFetchQuantity 为正整数'); + } + + this.ctx.logger.info('[wave.fetch] 后台任务开始', { + taskId: normalizedTaskId, + warehouseId: normalizedWarehouseId, + structureCount: structureList.length, + defaultQuantity: Number(defaultQuantity || 0), + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, + }); + + const startedAt = Date.now(); + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'running', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + finished_structure_count: 0, + progress_percent: 0, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, + started_at: startedAt, + }); + + try { + const groupWavePrefix = await this.getGroupWavePrefix(normalizedWarehouseId); + const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(normalizedWarehouseId); + const model = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + + const results = []; + let totalFetchedQuantity = 0; + let reachedLimit = false; + for (let i = 0; i < structureList.length; i++) { + if (normalizedFetchMode === 'single' && totalFetchedQuantity >= normalizedMaxFetchQuantity) { + reachedLimit = true; + break; + } + + const structure = structureList[i]; + const remainingFetchQuantity = normalizedFetchMode === 'single' + ? normalizedMaxFetchQuantity - totalFetchedQuantity + : 0; + const result = await this.fetchSingleStructure( + model, + structure, + normalizedWarehouseId, + groupWavePrefix, + normalizedFetchMode === 'single' ? 1 : minGroupOrderFetchQuantity, + { + maxFetchQuantity: remainingFetchQuantity, + } + ); + results.push(result); + totalFetchedQuantity += Number(result.fetched_quantity || 0); + if (normalizedFetchMode === 'single' && totalFetchedQuantity >= normalizedMaxFetchQuantity) { + reachedLimit = true; + } + + const finishedStructureCount = results.length; + const progressPercent = Math.min( + 100, + Math.round((finishedStructureCount / structureList.length) * 100) + ); + + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'running', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + finished_structure_count: finishedStructureCount, + progress_percent: progressPercent, + total_fetched_quantity: totalFetchedQuantity, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), + auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, + started_at: startedAt, + }); + } + + const totalRequestQuantity = results.reduce((sum, item) => sum + Number(item.request_quantity || 0), 0); + const durationMs = Date.now() - startedAt; + const finishedStructureCount = results.length; + const progressPercent = structureList.length > 0 + ? Math.min(100, Math.round((finishedStructureCount / structureList.length) * 100)) + : 100; + + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'success', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + finished_structure_count: finishedStructureCount, + progress_percent: progressPercent, + total_request_quantity: totalRequestQuantity, + total_fetched_quantity: totalFetchedQuantity, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), + ...(normalizedFetchMode === 'single' && reachedLimit ? { stop_reason: '达到最大抓取上限' } : {}), + auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, + started_at: startedAt, + duration_ms: durationMs, + }); + + this.ctx.logger.info('[wave.fetch] 后台任务完成', { + taskId: normalizedTaskId, + warehouseId: normalizedWarehouseId, + structureCount: structureList.length, + defaultQuantity: Number(defaultQuantity || 0), + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + reachedLimit, + autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, + totalRequestQuantity, + totalFetchedQuantity, + durationMs, + }); + } catch (error) { + await this.setFetchTaskProgress(normalizedTaskId, { + status: 'failed', + warehouse_id: normalizedWarehouseId, + structure_count: structureList.length, + default_quantity: Number(defaultQuantity || 0), + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, + started_at: startedAt, + duration_ms: Date.now() - startedAt, + error: error && error.message ? error.message : `${error}`, + }); + throw error; + } + } + + /** + * 提交异步抓取任务。 + * + * @param {Object} data 请求参数。 + * @param {'group'|'single'} [fetchMode='group'] 抓取模式。 + * @param {number} [maxFetchQuantity=0] single 模式最大抓取订单数。 + * @return {Promise} 任务提交结果。 + */ + async submitFetchTask(data = {}, fetchMode = 'group', maxFetchQuantity = 0) { + const warehouseId = this.getWarehouseId(); + const defaultQuantity = await this.getDefaultWaveQuantity(warehouseId); + const structures = this.normalizeFetchStructureRequests(data, defaultQuantity); + const taskId = this.generateFetchTaskId(warehouseId); + const normalizedFetchMode = String(fetchMode || 'group').trim() === 'single' ? 'single' : 'group'; + const normalizedMaxFetchQuantity = Number.isInteger(Number(maxFetchQuantity)) && Number(maxFetchQuantity) > 0 + ? Number(maxFetchQuantity) + : 0; + + await this.setFetchTaskProgress(taskId, { + status: 'submitted', + warehouse_id: Number(warehouseId || 0), + structure_count: structures.length, + finished_structure_count: 0, + progress_percent: 0, + default_quantity: defaultQuantity, + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, + submitted_at: Date.now(), + }); + + this.ctx.logger.info('[wave.fetch] 任务提交成功', { + taskId, + warehouseId: Number(warehouseId || 0), + structureCount: structures.length, + defaultQuantity, + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, + }); + + setImmediate(() => { + this.runFetchTask({ + taskId, + warehouseId: Number(warehouseId || 0), + defaultQuantity, + structures, + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + }).catch(error => { + this.ctx.logger.error('[wave.fetch] 后台任务异常', { + taskId, + warehouseId: Number(warehouseId || 0), + structureCount: structures.length, + defaultQuantity, + fetchMode: normalizedFetchMode, + maxFetchQuantity: normalizedMaxFetchQuantity, + autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + task_id: taskId, + warehouse_id: Number(warehouseId || 0), + structure_count: structures.length, + default_quantity: defaultQuantity, + fetch_mode: normalizedFetchMode, + ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), + auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, + message: '任务已提交,后端异步处理中', + }); + } + + /** + * 团购抓取波次:按机器结构标识批量抓取订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.structure_list 结构请求数组。 + * @return {Promise} 任务提交结果。 + */ + async groupFetch(data = {}) { + return this.submitFetchTask(data, 'group', 0); + } + + /** + * 散单抓取波次:支持按订单数上限停止。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.structure_list 结构请求数组。 + * @param {number|string} data.max_fetch_quantity 最大抓取订单数(必填正整数)。 + * @return {Promise} 任务提交结果。 + */ + async singleFetch(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const maxFetchQuantity = this.normalizeRequiredPositiveInteger( + normalizedData.max_fetch_quantity ?? normalizedData.maxFetchQuantity, + 'max_fetch_quantity' + ); + + return this.submitFetchTask(normalizedData, 'single', maxFetchQuantity); + } + + /** + * 兼容旧方法名 fetch,内部转调 groupFetch。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 任务提交结果。 + */ + async fetch(data = {}) { + return this.groupFetch(data); + } + +} + +module.exports = WaveService; diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js new file mode 100644 index 0000000..1da0dfd --- /dev/null +++ b/app/service/systemMethods/pick.js @@ -0,0 +1,172 @@ +'use strict'; + +const MainService = require('../main'); + +class PickService extends MainService { + /** + * 初始化 pick 模块鉴权配置。 + * + * @param {Egg.Context} ctx 上下文对象。 + */ + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'query'; + const _noNeedLog = 'query'; + const _noNeedAuth = 'query'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 将入参标准化为布尔值。 + * + * 兼容 `true/false`、`1/0`、`yes/no`、`on/off` 以及大小写字符串。 + * + * @param {*} value 原始值。 + * @param {boolean} defaultValue 默认值。 + * @return {boolean} 解析后的布尔值。 + */ + normalizeBoolean(value, defaultValue = false) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + if (typeof value === 'boolean') { + return value; + } + + const normalized = String(value).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalized)) { + return true; + } + if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalized)) { + return false; + } + + return defaultValue; + } + + /** + * 按仓库上下文获取订单分表模型。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 订单模型。 + */ + async getOrderModelByWarehouse(warehouseId) { + const { ctx } = this; + const factory = ctx.model && ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + throw new Error('订单分表模型工厂不可用'); + } + + const model = await factory.getCurrentModel(warehouseId); + if (!model || typeof model.findOne !== 'function') { + throw new Error('订单分表模型不可用'); + } + + return model; + } + + /** + * 根据快递号查询订单所在波次的拣货汇总信息。 + * + * 入参: + * - 快递号:`waybill_code` + * - 完整显示开关:`full` / `full_display` / `is_full` + * + * 仓库上下文仅取当前登录用户 `ctx.user.store_id`(兼容 `ctx.state.user.store_id`), + * 不依赖外部传入 `warehouse_id`,用于避免跨仓越界访问。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async query(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const { + waybill_code, + full, + full_display, + is_full, + } = requestData; + + const normalizedWaybillCode = String(waybill_code || '').trim(); + if (!normalizedWaybillCode) { + return this.fail('请传入快递号', {}, 400); + } + + const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined; + const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined; + const normalizedWarehouseId = Number(userWarehouseId || stateWarehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return this.fail('缺少当前用户仓库上下文 store_id', {}, 400); + } + + const orderExpress = await ctx.model.OrderExpress.findOne({ + where: { + warehouse_id: normalizedWarehouseId, + waybill_code: normalizedWaybillCode, + }, + attributes: [ 'order_id' ], + raw: true, + }); + + const orderId = Number(orderExpress && orderExpress.order_id || 0); + if (!orderExpress || orderId <= 0) { + return this.fail('快递号不存在或不属于当前仓库', {}, 404); + } + + let orderModel = null; + try { + orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId); + } catch (error) { + return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500); + } + + const order = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'store_id', 'wave_no', 'wave_id' ], + raw: true, + }); + + if (!order) { + return this.fail('订单不存在', {}, 404); + } + + const waveNo = String(order.wave_no || '').trim(); + if (!waveNo) { + return this.fail('订单未分配波次号,暂无拣货信息', {}, 400); + } + + const fullDisplay = this.normalizeBoolean(full ?? full_display ?? is_full, false); + + try { + const result = await service.systems.pick.queryPickingInfo({ + orderId, + waveNo, + waveId: Number(order.wave_id || 0), + storeId: Number(order.store_id || 0), + warehouseId: normalizedWarehouseId, + fullDisplay, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isFinite(code) && code >= 400 && code < 600) { + return this.fail(error.message || '查询失败', {}, code); + } + + ctx.logger.error('[PickService.query] 查询波次拣货信息失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } +} + +module.exports = PickService; diff --git a/app/service/systemMethods/setting/warehouse.js b/app/service/systemMethods/setting/warehouse.js new file mode 100644 index 0000000..a550df9 --- /dev/null +++ b/app/service/systemMethods/setting/warehouse.js @@ -0,0 +1,83 @@ +'use strict'; + +const MainService = require('../../main'); + +class SettingWarehouseMethodsService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'getSettings,getFieldMeta,saveSettings'; + const _noNeedLog = '*'; + const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 获取仓库设置(subject_config)。 + * + * @return {Promise} 统一响应结果。 + */ + async getSettings() { + const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse; + + if (!targetService || typeof targetService.getSettings !== 'function') { + return this.fail('获取仓库设置失败', { code: 500 }); + } + + try { + const result = await targetService.getSettings(); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取仓库设置失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 获取仓库设置字段元信息列表。 + * + * @return {Promise} 统一响应结果。 + */ + async getFieldMeta() { + const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse; + + if (!targetService || typeof targetService.getFieldMeta !== 'function') { + return this.fail('获取仓库设置字段信息失败', { code: 500 }); + } + + try { + const list = targetService.getFieldMeta(); + return this.success('ok', { list }); + } catch (error) { + return this.fail(error.message || '获取仓库设置字段信息失败', { + code: Number(error.code) || 500, + }); + } + } + + /** + * 修改仓库设置并清理指定仓库缓存。 + * + * @param {Object} data 请求参数。 + * @return {Promise} 统一响应结果。 + */ + async saveSettings(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse; + + if (!targetService || typeof targetService.saveSettings !== 'function') { + return this.fail('保存仓库设置失败', { code: 500 }); + } + + try { + const result = await targetService.saveSettings(data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存仓库设置失败', { + code: Number(error.code) || 500, + }); + } + } +} + +module.exports = SettingWarehouseMethodsService; diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 5fdf65a..c853004 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -65,8 +65,12 @@ class WarehouseService extends MainService { */ async saveWarehouseStock(data) { const { service } = this; - const result = await service.systems.stockStore.saveWarehouseStock(data); - return this.success('ok', { data: result, code: 200 }); + try { + const result = await service.systems.stockStore.saveWarehouseStock(data); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + return this.fail(error.message); + } } /** @@ -146,19 +150,37 @@ class WarehouseService extends MainService { /** * 校验商品编码唯一性。 * @param {Object} data 请求体 - * @param {number} [data.id] 商品ID(编辑场景) + * @param {number} [data.item_id] 商品ID(编辑场景,排除自身) + * @param {number} [data.id] 兼容旧字段的商品ID * @param {string} data.item_code 商品编码 - * @param {number} data.store_id 货主ID - * @return {Promise} data 为布尔或冲突详情 + * @param {number} data.owner_id 货主ID + * @param {number} [data.store_id] 兼容旧字段的货主ID + * @param {number} data.warehouse_id 仓库ID + * @return {Promise} data.unique 为是否唯一,重复时返回提示信息 */ async checkItemCodeUnique(data) { const { ctx, service } = this; - const { id, item_code, store_id } = data; + const { + item_id, + id, + item_code, + owner_id, + store_id, + warehouse_id, + } = data || {}; + const targetItemId = item_id || id || null; + const targetOwnerId = owner_id || store_id; + const targetWarehouseId = warehouse_id || ctx.user.store_id; try { - if (!item_code || !store_id) { + if (!item_code || !targetOwnerId || !targetWarehouseId) { return this.fail('参数错误'); } - const result = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id); + const result = await service.systems.stockStore.checkItemCodeUnique( + targetItemId, + item_code, + targetOwnerId, + targetWarehouseId + ); return this.success('获取成功', { data: result, code: 200 }); } catch (error) { return this.fail(error.message); diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 19fcd62..b5a2682 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -236,10 +236,7 @@ class configService extends MainService { /** * 查询收货单操作日志(分页)。 * @param {Object} data 请求体 - * @param {number|string} [data.id] 收货单ID - * @param {number|string} [data.receiving_id] 收货单ID(兼容字段) - * @param {number} [data.page] 页码 - * @param {number} [data.pageSize] 每页数量 + * @param {number|string} data.receiving_id 收货单ID * @param {Object} [data.pagination] 分页对象,支持 page/pageSize * @return {Promise} 统一成功包装响应 */ @@ -251,9 +248,9 @@ class configService extends MainService { : {}; const result = await service.systems.operationLog.queryReceivingLogs({ - id: requestData.id || requestData.receiving_id, - page: requestData.page || pagination.page, - pageSize: requestData.pageSize || pagination.pageSize || pagination.page_size, + id: requestData.receiving_id, + page: pagination.page, + pageSize: pagination.pageSize || pagination.page_size, warehouseId: ctx.user.store_id, }); diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js index 6e42878..8ee5efc 100644 --- a/app/service/systems/auth/role_permission.js +++ b/app/service/systems/auth/role_permission.js @@ -153,124 +153,6 @@ class RolePermissionService extends Service { .filter(item => Number.isFinite(item) && item > 0))); } - async getPermissionPathsForRoles(roleIds, options = {}) { - const { ctx, app } = this; - const { Op } = app.Sequelize; - const permissionIds = await this.getPermissionIdsForRoles(roleIds, { - includeDisabled: options.includeDisabled === true, - type: options.type || null, - includeRoleDisabled: options.includeRoleDisabled === true, - useLegacyFallback: options.useLegacyFallback !== false, - transaction: options.transaction, - }); - - if (permissionIds.length === 0) { - return []; - } - - const where = { - id: { - [Op.in]: permissionIds, - }, - status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1, - }; - - if (options.type) { - where.type = options.type; - } - - if (options.typeLike) { - where.type = { - [Op.like]: options.typeLike, - }; - } - - if (options.typeNotLike) { - where.type = { - [Op.notLike]: options.typeNotLike, - }; - } - - const rows = await ctx.model.Permission.findAll({ - where, - attributes: [ 'path' ], - order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], - raw: true, - transaction: options.transaction, - }); - - return Array.from(new Set(rows - .map(item => item && item.path) - .filter(Boolean))); - } - - async bulkAssign(roleId, permissionIds, options = {}) { - const currentRole = await this.ctx.model.Role.findOne({ - where: { id: roleId }, - attributes: [ 'permissions' ], - raw: true, - transaction: options.transaction, - }); - - const currentState = this.normalizePermissionSet(currentRole && currentRole.permissions); - const incomingState = this.normalizePermissionSet(permissionIds); - const nextState = incomingState.allAccess || currentState.allAccess - ? '*' - : [ ...currentState.permissionIds, ...incomingState.permissionIds ]; - - await this.assignPermissions(roleId, nextState, options); - return this.toApiPermissionIds(nextState); - } - - async clearRolePermissions(roleId, options = {}) { - const { ctx } = this; - - return await ctx.model.Role.update({ - permissions: JSON.stringify([]), - updated_at: new Date(), - }, { - where: { id: roleId }, - transaction: options.transaction, - }); - } - - async getRolePermissions(roleId, includePermissionDetails = false) { - const { ctx } = this; - const permissionIds = await this.getPermissionIds(roleId); - if (permissionIds.length === 0) { - return []; - } - - if (!includePermissionDetails) { - return permissionIds.map(permissionId => ({ - role_id: Number(roleId), - permission_id: Number(permissionId), - })); - } - - const permissionRows = await ctx.model.Permission.findAll({ - where: { - id: permissionIds, - status: 1, - }, - }); - const permissionMap = new Map(permissionRows.map(item => [ Number(item.id), item ])); - - return permissionIds.map(permissionId => ({ - role_id: Number(roleId), - permission_id: Number(permissionId), - permission: permissionMap.get(Number(permissionId)) || null, - })); - } - - async hasPermission(roleId, permissionId) { - const permissionIds = await this.getPermissionIds(roleId, { - includeDisabled: true, - }); - - return permissionIds.includes(Number(permissionId)); - } - async assignPermissions(roleId, permissionIds, options = {}) { const { ctx } = this; @@ -285,33 +167,6 @@ class RolePermissionService extends Service { return true; } - async getPermissionTree(roleId, permissionType = null) { - const { ctx } = this; - const permissionIds = await this.getPermissionIds(roleId, { - includeDisabled: false, - type: permissionType, - }); - - if (permissionIds.length === 0) { - return []; - } - - const permissions = await ctx.model.Permission.findAll({ - where: { - id: permissionIds, - status: 1, - ...(permissionType ? { type: permissionType } : {}), - }, - order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], - }); - - return ctx.model.Permission.buildPermissionTree(permissions); - } - - async getPermissionIds(roleId, options = {}) { - return await this.getPermissionIdsForRoles([ roleId ], options); - } - async removePermissionsFromAllRoles(permissionIds, options = {}) { const { ctx } = this; const removeSet = new Set((permissionIds || []) diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 9e10c2f..2e40e1f 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -1770,6 +1770,7 @@ class UserService extends Service { let storeId = null; let storeName = null; let storeCode = null; + let storeType = null; let roleName = null; let auth_end = null; let employees_name = null; @@ -1779,6 +1780,7 @@ class UserService extends Service { storeId = currentRole.store_id; storeName = currentRole.store_name; storeCode = currentRole.store_code; + storeType = currentRole.role_type; roleName = currentRole.role_name; employees_name = currentRole.real_name; auth_end = currentRole.auth_end; @@ -1802,6 +1804,7 @@ class UserService extends Service { store_id: storeId, store_name: storeName, store_code: storeCode, + store_type: storeType, menus, permissions, userRole, diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index d0fe15c..d451dd7 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -129,21 +129,89 @@ class DeliveryOrderService extends Service { } /** - * 将订单操作日志逐条写入数据库。 + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const { ctx } = this; + const stateUser = ctx && ctx.state && typeof ctx.state.user === 'object' && ctx.state.user + ? ctx.state.user + : null; + const ctxUser = ctx && ctx.user && typeof ctx.user === 'object' + ? ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 获取订单日志使用的仓库ID。 + * + * 取值优先级:显式传入参数 -> this.store.id -> ctx.user.warehouse_id -> ctx.user.store_id。 + * + * @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。 + * @return {number|string|null} 归一化后的仓库ID。 + */ + getOrderLogWarehouseId(preferredWarehouseId = null) { + const { ctx } = this; + const candidates = [ + preferredWarehouseId, + this.store && this.store.id, + ctx && ctx.user && ctx.user.warehouse_id, + ctx && ctx.user && ctx.user.store_id, + ]; + + for (const candidate of candidates) { + if (candidate === undefined || candidate === null || candidate === '') { + continue; + } + return candidate; + } + + return null; + } + + /** + * 将订单操作日志写入数据库,优先批量写入。 * * @param {Array} operationLogs 待写入的日志数组。 * @param {number|string} orderId 订单ID。 + * @param {Object} [options={}] 写入选项。 + * @param {number|string} [options.warehouseId] 订单所属仓库ID。 + * @param {Object} [options.transaction] 事务对象(可选)。 * @return {Promise} 无返回值。 */ - async flushOrderOperationLogs(operationLogs, orderId) { + async flushOrderOperationLogs(operationLogs, orderId, options = {}) { const { ctx } = this; const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const requestOptions = options && typeof options === 'object' ? options : {}; + const operator = this.getOrderLogOperator(); + const warehouseId = this.getOrderLogWarehouseId(requestOptions.warehouseId ?? requestOptions.warehouse_id); if (!Array.isArray(operationLogs) || operationLogs.length === 0) { return; } - if (!operationLogService || typeof operationLogService.createOperationLog !== 'function') { + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] operationLog service unavailable', { orderId, logs: operationLogs.length, @@ -151,32 +219,39 @@ class DeliveryOrderService extends Service { return; } - for (const logItem of operationLogs) { - try { - const result = await operationLogService.createOperationLog({ - businessType: 'order', - businessId: orderId, - operationCode: logItem.operationCode, - extras: { - message: logItem.message, - }, - }); + const payloads = operationLogs.map(logItem => ({ + businessType: 'order', + businessId: orderId, + operationCode: logItem.operationCode, + operator, + extras: { + warehouseId, + message: logItem.message, + }, + transaction: requestOptions.transaction, + })); - if (!result) { - ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', { - orderId, - operationCode: logItem.operationCode, - message: logItem.message, - }); + try { + const results = await operationLogService.createOperationLogs(payloads, { + transaction: requestOptions.transaction, + }); + + for (let index = 0; index < payloads.length; index += 1) { + if (results[index]) { + continue; } - } catch (error) { - ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志异常,不影响业务', { + const logItem = operationLogs[index] || {}; + ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', { orderId, operationCode: logItem.operationCode, message: logItem.message, - error: error.message, }); } + } catch (error) { + ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 批量写入操作日志异常,不影响业务', { + orderId, + error: error.message, + }); } } @@ -434,7 +509,7 @@ class DeliveryOrderService extends Service { * * @param {Object} data 奇门/系统订单入参。 * @param {Object} info 当前仓库与货主上下文。 - * @param createChannel + * @param {string} [createChannel=''] 订单创建渠道标识。 * @return {Promise} 创建结果。 */ async addOrder(data, info, createChannel = '') { @@ -560,7 +635,9 @@ class DeliveryOrderService extends Service { await transaction.commit(); - await this.flushOrderOperationLogs(operationLogs, orderId); + await this.flushOrderOperationLogs(operationLogs, orderId, { + warehouseId: info.warehouseId, + }); // 异步处理:订单入队列 await this.addOrderToQueue(orderId, info.warehouseId); @@ -699,12 +776,91 @@ class DeliveryOrderService extends Service { return null; } + /** + * 解析订单操作人名称。 + * + * 优先使用外部传入的操作人;当未传入时按创建渠道自动补齐: + * - QM:奇门-${应用名称} + * - API:API-${应用名称} + * - MANUAL/其他:当前登录用户姓名(employees_name -> real_name -> name) + * + * @param {string|null|undefined} operatorName 外部传入的操作人名称。 + * @param {string} [createChannel='MANUAL'] 订单创建渠道标识。 + * @param {Object} [info={}] 当前仓库与货主上下文。 + * @return {Promise} 解析后的操作人名称。 + */ + async resolveOperatorName(operatorName, createChannel = 'MANUAL', info = {}) { + const explicitOperatorName = operatorName === undefined || operatorName === null + ? '' + : String(operatorName).trim(); + if (explicitOperatorName) { + return explicitOperatorName; + } + + const normalizedCreateChannel = String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL'; + const appKey = String( + (info && info.appKey) + || (this.ctx.user && this.ctx.user.app_key) + || '' + ).trim(); + + if (normalizedCreateChannel === 'QM') { + if (!appKey) { + return '奇门'; + } + + try { + const app = await this.ctx.model.QimenApp.findOne({ + where: { app_key: appKey }, + attributes: [ 'name' ], + raw: true, + }); + const appName = String(app && app.name || '').trim(); + return appName ? `奇门-${appName}` : '奇门'; + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询奇门应用失败,不影响主流程: %s', error.message); + return '奇门'; + } + } + + if (normalizedCreateChannel === 'API') { + if (!appKey) { + return 'API'; + } + + try { + const app = await this.ctx.model.ApiApp.findOne({ + where: { self_app_key: appKey }, + attributes: [ 'app_name' ], + raw: true, + }); + const appName = String(app && app.app_name || '').trim(); + return appName ? `API-${appName}` : 'API'; + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询API应用失败,不影响主流程: %s', error.message); + return 'API'; + } + } + + const loginUser = this.ctx.user && typeof this.ctx.user === 'object' + ? this.ctx.user + : (this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' ? this.ctx.state.user : {}); + const manualOperatorName = String( + loginUser.employees_name + || loginUser.real_name + || loginUser.name + || '' + ).trim(); + + return manualOperatorName || null; + } + /** * 准备订单主表数据。 * * @param {Object} deliveryOrder 订单主信息。 * @param {Object} info 当前仓库与货主上下文。 - * @param createChannel + * @param {string} [createChannel='MANUAL'] 订单创建渠道标识。 * @param {number} step 订单步骤。 * @param {Array} [operationLogs=[]] 待写入的操作日志数组。 * @return {Promise} 可入库的订单数据。 @@ -760,6 +916,7 @@ class DeliveryOrderService extends Service { warehouseId: info.warehouseId, storeId: info.storeId, }, operationLogs); + const resolvedOperatorName = await this.resolveOperatorName(operatorName, createChannel, info); return { delivery_order_code: deliveryOrderCode, @@ -780,7 +937,7 @@ class DeliveryOrderService extends Service { shop_nick: shopNick, seller_nick: sellerNick, buyer_nick: buyerNick, - operator_name: operatorName, + operator_name: resolvedOperatorName, operate_time: operateTime ? new Date(operateTime) : null, total_amount: totalAmount ? parseFloat(totalAmount) : 0, item_amount: itemAmount ? parseFloat(itemAmount) : 0, @@ -963,9 +1120,7 @@ class DeliveryOrderService extends Service { const sortedStocks = Array.from(stockQuantityMap.entries()) .sort(([ stockIdA ], [ stockIdB ]) => stockIdA - stockIdB) .map(([ stockId, quantity ]) => { - // 可选:在字符串中包含重量信息 - const weight = stockWeightMap.get(stockId) || 0; - return `${stockId}+${quantity}${weight > 0 ? `@${weight}` : ''}`; + return `${stockId}+${quantity}`; }); items_str = sortedStocks.join('|'); diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 39bfe73..72ce990 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -93,6 +93,135 @@ class ExpressService extends Service { return 0; } + /** + * 构建快递号分配链路追踪ID。 + * + * 优先使用入参中的 trace_id/traceId,其次读取上下文 trace 信息,最后兜底生成。 + * + * @param {Object} [data={}] 入参。 + * @param {string} [fallback=''] 兜底标识。 + * @return {string} 追踪ID。 + */ + buildWaybillTraceId(data = {}, fallback = '') { + const normalizedData = data && typeof data === 'object' ? data : {}; + const ctxTraceId = this.ctx && this.ctx.traceId !== undefined + ? this.ctx.traceId + : this.ctx && this.ctx.requestId !== undefined + ? this.ctx.requestId + : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined + ? this.ctx.state.traceId + : ''; + const normalizedTraceId = String( + normalizedData.trace_id + || normalizedData.traceId + || ctxTraceId + || fallback + || '' + ).trim(); + + if (normalizedTraceId) { + return normalizedTraceId; + } + + return `waybill_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + } + + /** + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' + ? this.ctx.state.user + : null; + const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object' + ? this.ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 获取订单日志使用的仓库ID。 + * + * @param {number|string|null} [preferredWarehouseId=null] 优先仓库ID。 + * @return {number|string|null} 仓库ID。 + */ + getOrderLogWarehouseId(preferredWarehouseId = null) { + const candidates = [ + preferredWarehouseId, + this.getCurrentWarehouseId(), + this.ctx && this.ctx.user ? this.ctx.user.warehouse_id : null, + this.ctx && this.ctx.user ? this.ctx.user.store_id : null, + ]; + + for (const candidate of candidates) { + if (candidate === undefined || candidate === null || candidate === '') { + continue; + } + return candidate; + } + + return null; + } + + /** + * 为分配快递失败订单写入订单操作日志。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {string} errorMessage 失败原因。 + * @param {number|string|null} warehouseId 仓库ID。 + * @return {Promise} 无返回值。 + */ + async createAllocateExpressFailureLogs(orderIds = [], errorMessage = '', warehouseId = null) { + const operationLogService = this.service + && this.service.systems + && this.service.systems.operationLog; + if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') { + return; + } + + const operator = this.getOrderLogOperator(); + const normalizedWarehouseId = this.getOrderLogWarehouseId(warehouseId); + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(orderId => Number(orderId)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0))); + const normalizedErrorMessage = String(errorMessage || '').trim() || '未知异常'; + + const payloads = normalizedOrderIds.map(orderId => ({ + businessType: 'order', + businessId: String(orderId), + operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED', + operator, + extras: { + message: `分配快递失败:${normalizedErrorMessage}`, + warehouseId: normalizedWarehouseId, + externalLogType: 'API', + }, + })); + + await operationLogService.createOperationLogs(payloads); + } + /** * 将 business_key 规范化为内部可处理的正整数列表。 *【已使用】 @@ -223,10 +352,9 @@ class ExpressService extends Service { */ async normalizeWaybillCreateOrders(orders = []) { const normalizedOrders = Array.isArray(orders) ? orders : []; - console.log('normalizeWaybillCreateOrders 原始订单列表', normalizedOrders); const normalizedOrderMap = new Map(); - const ExpressList = await this.loadExpressList(); + await this.loadExpressList(); for (const order of normalizedOrders) { if (!order || typeof order !== 'object') { continue; @@ -234,7 +362,6 @@ class ExpressService extends Service { const orderId = Number(order.id || order.order_id); const businessKeys = this.normalizeWaybillBusinessKeys(order.business_key); - console.log('businessKeys', businessKeys); if (!Number.isInteger(orderId) || orderId <= 0 || businessKeys.length === 0) { continue; } @@ -242,7 +369,6 @@ class ExpressService extends Service { const sysPlatformCode = String(order.sys_platform_code || order.sysPlatformCode || '').trim(); const logisticsCode = String(order.logistics_code || order.logisticsCode || '').trim(); const syslogisticsCode = String(order.sys_logistics_code || order.sysLogisticsCode || '').trim(); - console.log('syslogisticsCode', syslogisticsCode); const platformCode = this.normalizeWaybillCreatePlatformCode(order); for (const businessKey of businessKeys) { @@ -1336,9 +1462,7 @@ class ExpressService extends Service { if (typeof dispatchMethod !== 'function') { throw new Error(normalizedPlatformCode + '接口未实现'); } - // console.log("业务数据骨架", JSON.stringify(bizcontent)); const dispatchResult = await dispatchMethod.call(expressPlatformService, bizcontent); - // console.log("平台接口返回结果", JSON.stringify(dispatchResult)); if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') { throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败'); } @@ -1434,12 +1558,10 @@ class ExpressService extends Service { * 【已使用】 */ async getWaybillAsyncOrderDeliveryModel(currentWarehouseId = 0) { - console.log('======================================='); const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!currentWarehouseId || !orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') { return null; } - console.log('getWaybillAsyncOrderDeliveryModel 当前仓库ID', currentWarehouseId); const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId); if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') { return null; @@ -1463,14 +1585,27 @@ class ExpressService extends Service { const { app } = this; const { Op } = app.Sequelize; const orderList = Array.isArray(orders) ? orders : []; + const traceId = this.buildWaybillTraceId({}, `pipeline_${Date.now()}`); - console.log('createWaybillCodePipeline 输入订单列表', orderList); + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 入口请求', { + traceId, + orderCount: orderList.length, + orderIds: orderList.slice(0, 50).map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0), + waveIds: orderList.slice(0, 50).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0), + }); const warehouseId = this.getCurrentWarehouseId(); const orderDeliveryModel = await this.getWaybillAsyncOrderDeliveryModel(warehouseId); - console.log('orderDeliveryModel', orderDeliveryModel); + if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') { + this.ctx.logger.error('[ExpressService.createWaybillCodePipeline] 分配前置条件失败-订单主表模型不可用', { + traceId, + warehouseId, + }); + throw new Error('订单主表模型未初始化'); + } + // 【step1】先按订单ID和业务键筛选 wms_order_express,找出已存在的快递记录,避免重复创建。 const orders_arr = await orderDeliveryModel.findAll({ where: { @@ -1483,7 +1618,12 @@ class ExpressService extends Service { attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ], raw: true, }); - console.log('createWaybillCodePipeline 查询订单主表结果', orders_arr); + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', { + traceId, + warehouseId, + inputOrderCount: orderList.length, + matchedOrderCount: Array.isArray(orders_arr) ? orders_arr.length : 0, + }); // orders_arr和orderList合并 const ordersWithExpress = orders_arr.map(order => { const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id)); @@ -1492,25 +1632,34 @@ class ExpressService extends Service { business_key: matchedExpress ? matchedExpress.business_key : 1, }; }); - console.log('createWaybillCodePipeline 订单列表与快递信息合并结果', ordersWithExpress); const groupedOrders = this.groupWaybillOrdersByPlatformAndLogistics(ordersWithExpress); - console.log('createWaybillCodePipeline 按平台和物流分组结果', groupedOrders); + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 平台物流分组结果', { + traceId, + groupedCount: groupedOrders.length, + }); + // 【step2】按平台 + 快递编码分组,后续按组串行处理。 const platformList = await this.service.systems.platform.getPlatformList(true, true); - console.log('createWaybillCodePipeline 平台列表', platformList); for (const groupedOrder of groupedOrders) { const matchedPlatform = platformList.find(platform => String(platform.code || '').trim().toLowerCase() === String(groupedOrder.options.sys_platform_code || '').trim().toLowerCase()); const batches = this.splitWaybillOrdersIntoBatches(groupedOrder.orders); const listByWarehousePlatformCode = await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({ warehouseId, platform_code: groupedOrder.options.sys_platform_code }); - console.log('createWaybillCodePipeline 按批次切分结果', batches, 'expressInterfaceList', listByWarehousePlatformCode, 'matchedPlatform', matchedPlatform); + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 分组前置条件检查', { + traceId, + warehouseId, + storeId: groupedOrder.options.store_id || 0, + sysPlatformCode: groupedOrder.options.sys_platform_code, + logisticsCode: groupedOrder.options.logistics_code, + matchedPlatformCode: matchedPlatform && matchedPlatform.code, + hasExpressInterface: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.data && listByWarehousePlatformCode.data[0]), + }); // 先获取货主配置货主是否配置了发件人,如果没有再使用快递接口的发件人信息。发件人信息在 listByWarehousePlatformCode.data[0] 中。 const storeInfo = await this.service.systems.storeWarehouse.getContractConfig(warehouseId, groupedOrder.options.store_id); const expressInterface = listByWarehousePlatformCode.data[0]; const storeConfig = storeInfo ? storeInfo.policy_config : null; const useStoreSenderInfoValue = storeConfig ? storeConfig.use_store_sender_info : 1; const shouldUseStoreSenderInfo = Number(useStoreSenderInfoValue === undefined || useStoreSenderInfoValue === null || useStoreSenderInfoValue === '' ? 1 : useStoreSenderInfoValue) === 1; - console.log('storeInfo', storeInfo, expressInterface); const expressInterfaceConfig = expressInterface ? { ...expressInterface, ...(shouldUseStoreSenderInfo ? { @@ -1524,12 +1673,19 @@ class ExpressService extends Service { address: (storeConfig && storeConfig.address) || expressInterface.address || '', } : {}), } : null; - console.log('expressInterfaceConfig', expressInterfaceConfig); for (const batch of batches) { // 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。 - this.asyncTask(batch, groupedOrder.options, matchedPlatform, expressInterfaceConfig); + this.asyncTask(batch, { + ...groupedOrder.options, + trace_id: traceId, + warehouse_id: warehouseId, + }, matchedPlatform, expressInterfaceConfig); } } + this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', { + traceId, + groupedCount: groupedOrders.length, + }); return { message: '分配快递任务已提交' }; } /** @@ -1543,30 +1699,70 @@ class ExpressService extends Service { */ async asyncTask(batch, options, matchedPlatform, listByWarehousePlatformCode) { - console.log('asyncTask 输入参数 batch', batch, 'options', options, 'matchedPlatform', matchedPlatform, 'listByWarehousePlatformCode', listByWarehousePlatformCode); + const traceId = this.buildWaybillTraceId(options || {}, 'asyncTask'); + this.ctx.logger.info('[ExpressService.asyncTask] 任务入口', { + traceId, + warehouseId: options && options.warehouse_id, + sysPlatformCode: options && options.sys_platform_code, + logisticsCode: options && options.logistics_code, + orderIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0), + waveIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0), + }); try { if (!listByWarehousePlatformCode) { + this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-快递接口配置缺失', { + traceId, + sysPlatformCode: options && options.sys_platform_code, + logisticsCode: options && options.logistics_code, + }); throw new Error(`当前订单平台【${options.sys_platform_name}】,快递【${options.logistics_name}】,未配置有效的快递接口`); } if (!matchedPlatform) { + this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-平台配置缺失', { + traceId, + sysPlatformCode: options && options.sys_platform_code, + logisticsCode: options && options.logistics_code, + }); throw new Error(`未找到订单平台【${options.sys_platform_name}】的有效平台配置`); } - await this.createWaybillCode(batch, matchedPlatform, listByWarehousePlatformCode); + this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 前', { + traceId, + batchCount: Array.isArray(batch) ? batch.length : 0, + }); + await this.createWaybillCode(batch, matchedPlatform, { + ...(listByWarehousePlatformCode || {}), + trace_id: traceId, + }); + this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 后', { + traceId, + batchCount: Array.isArray(batch) ? batch.length : 0, + }); } catch (error) { console.error('异步任务执行失败:', error.message); + this.ctx.logger.error('[ExpressService.asyncTask] 异步任务执行异常', { + traceId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); const err_orders = batch.map(order => ({ - order_id: order.id, + order_id: order && (order.id || order.order_id), business_key: order.business_key, })); + const failedOrderIds = err_orders + .map(order => Number(order && order.order_id)) + .filter(orderId => Number.isFinite(orderId) && orderId > 0); + const logWarehouseId = this.getOrderLogWarehouseId(options && options.warehouse_id); + const errorMessage = error && error.message ? String(error.message) : String(error); this.service.systems.orderPendingException.markPendingException( { ids: err_orders.map(order => order.order_id), - exception_text: `订单快递分配失败: ${error.message}`, + exception_text: `订单快递分配失败: ${errorMessage}`, } ); + await this.createAllocateExpressFailureLogs(failedOrderIds, errorMessage, logWarehouseId); await this.hardDeleteWaybillAsyncOrderExpressRows(err_orders, { platform_code: options.sys_platform_code, - error_message: error.message, + error_message: errorMessage, }); } } @@ -1592,8 +1788,18 @@ class ExpressService extends Service { * @return {Promise} 创建结果。 */ async createWaybillCode(orders, matchedPlatform, listByWarehousePlatformCode) { - console.log('======================================='); - console.log('createWaybillCode 输入订单列表', orders, 'matchedPlatform', matchedPlatform, 'listByWarehousePlatformCode', listByWarehousePlatformCode); + const traceId = this.buildWaybillTraceId({ + trace_id: listByWarehousePlatformCode && listByWarehousePlatformCode.trace_id, + traceId: listByWarehousePlatformCode && listByWarehousePlatformCode.traceId, + }, 'createWaybillCode'); + this.ctx.logger.info('[ExpressService.createWaybillCode] 入口请求', { + traceId, + 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, + defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface, + warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id, + }); const { app, ctx } = this; const { Op } = app.Sequelize; const orderExpressModel = ctx.model && ctx.model.OrderExpress; @@ -1626,8 +1832,6 @@ class ExpressService extends Service { if (!storeWarehouseModel || typeof storeWarehouseModel.findAll !== 'function' || typeof storeWarehouseModel.update !== 'function') { throw new Error('签约关系模型未初始化'); } - console.log('1'); - const maxAttempts = 3; /** * 执行运单创建事务,并在死锁或锁等待超时时按次数重试。 @@ -1896,20 +2100,39 @@ class ExpressService extends Service { } }; + this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务前', { + traceId, + orderCount: normalizedOrders.length, + }); const createWaybillResult = await executeCreateWaybillTransactionWithRetry(1); - console.log('2'); - console.log('事务结果', createWaybillResult); + this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务后', { + traceId, + successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders) + ? createWaybillResult.orders.length + : 0, + }); + try { if (Array.isArray(createWaybillResult.orders) && createWaybillResult.orders.length > 0 && matchedPlatform && matchedPlatform.default_express_interface) { try { + this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用前', { + traceId, + platformInterface: matchedPlatform.default_express_interface, + orderCount: createWaybillResult.orders.length, + }); await this.dispatchWaybillAsyncPlatform(matchedPlatform.default_express_interface, { matchedPlatform, listByWarehousePlatformCode, orders: createWaybillResult.orders, + trace_id: traceId, + }); + this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用后', { + traceId, + platformInterface: matchedPlatform.default_express_interface, }); } catch (error) { throw error; @@ -1935,6 +2158,12 @@ class ExpressService extends Service { restoreRelationMap.set(relationKey, currentRelation); } console.error('运单后处理失败,准备回补锁定量:', error.message, 'restoreRelationList', Array.from(restoreRelationMap.values())); + this.ctx.logger.error('[ExpressService.createWaybillCode] 平台后处理异常,准备回补锁定量', { + traceId, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + restoreRelationList: Array.from(restoreRelationMap.values()), + }); if (restoreRelationMap.size > 0) { const restoreRelationList = Array.from(restoreRelationMap.values()); const restoreRows = await storeWarehouseModel.findAll({ @@ -1994,6 +2223,12 @@ class ExpressService extends Service { throw error; } + this.ctx.logger.info('[ExpressService.createWaybillCode] 处理完成', { + traceId, + successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders) + ? createWaybillResult.orders.length + : 0, + }); return createWaybillResult; } diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index abbaf5a..3383ff8 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -159,6 +159,71 @@ const MainService = require('../main'); * @property {number} items_weight 商品总重量。 */ class ExpressPlatformService extends MainService { + /** + * 获取订单日志使用的操作人信息。 + * + * 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。 + * + * @return {{ id: string|null, name: string }} 操作人信息。 + */ + getOrderLogOperator() { + const stateUser = this.isPlainObject(this.ctx && this.ctx.state && this.ctx.state.user) + ? this.ctx.state.user + : null; + const ctxUser = this.isPlainObject(this.ctx && this.ctx.user) + ? this.ctx.user + : null; + const operatorSource = stateUser || ctxUser || {}; + + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const rawOperatorName = operatorSource.employees_name + ?? operatorSource.operator_name + ?? operatorSource.real_name + ?? operatorSource.name; + const operatorId = rawOperatorId === undefined || rawOperatorId === null + ? null + : String(rawOperatorId).trim() || null; + const operatorName = rawOperatorName === undefined || rawOperatorName === null + ? 'system' + : String(rawOperatorName).trim() || 'system'; + + return { + id: operatorId, + name: operatorName, + }; + } + + /** + * 构建快递平台链路追踪ID。 + * + * 优先使用入参中的 trace_id/traceId,其次使用上下文 trace 信息,最后兜底生成。 + * + * @param {Object} [data={}] 入参。 + * @return {string} 追踪ID。 + */ + buildExpressPlatformTraceId(data = {}) { + const normalizedData = data && typeof data === 'object' ? data : {}; + const ctxTraceId = this.ctx && this.ctx.traceId !== undefined + ? this.ctx.traceId + : this.ctx && this.ctx.requestId !== undefined + ? this.ctx.requestId + : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined + ? this.ctx.state.traceId + : ''; + const normalizedTraceId = String( + normalizedData.trace_id + || normalizedData.traceId + || ctxTraceId + || '' + ).trim(); + + if (normalizedTraceId) { + return normalizedTraceId; + } + + return `express_platform_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + } + /** * 菠萝派数据处理接口。 * @@ -167,13 +232,29 @@ class ExpressPlatformService extends MainService { */ async polyapi(data = {}) { const { matchedPlatform, listByWarehousePlatformCode, orders } = data; + const traceId = this.buildExpressPlatformTraceId(data); + const normalizedOrders = Array.isArray(orders) ? orders : []; + const orderIdListForLog = normalizedOrders + .map(item => Number(item && item.order_id) || Number(item && item.order_delivery && item.order_delivery.id) || 0) + .filter(orderId => Number.isFinite(orderId) && orderId > 0); + const waveIdListForLog = normalizedOrders + .map(item => Number(item && item.wave_id) || Number(item && item.order_delivery && item.order_delivery.wave_id) || 0) + .filter(waveId => Number.isFinite(waveId) && waveId > 0); + + this.ctx.logger.info('[expressPlatform.polyapi] 入口请求', { + traceId, + waveIds: Array.from(new Set(waveIdListForLog)), + orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50), + orderCount: normalizedOrders.length, + requestSnapshot: { + matchedPlatformCode: matchedPlatform && matchedPlatform.code, + defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface, + platformCode: listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code, + logisticsCode: listByWarehousePlatformCode && listByWarehousePlatformCode.logistics_code, + warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id, + }, + }); const ExpressList = await this.service.systems.express.loadExpressList(); - console.log('matchedPlatform', JSON.stringify(matchedPlatform)); - - console.log('接收到菠萝派快递接口入参:', JSON.stringify(listByWarehousePlatformCode)); - - console.log('接收到菠萝派平台数据处理请求,入参:', JSON.stringify(orders)); - console.log('ExpressList', JSON.stringify(ExpressList)); const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; const allocatedWaybillMap = new Map(); if (orderExpressModel && typeof orderExpressModel.findAll === 'function') { @@ -183,6 +264,11 @@ class ExpressPlatformService extends MainService { .filter(orderId => Number.isFinite(orderId) && orderId > 0))); if (orderIdList.length > 0) { + this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号前', { + traceId, + orderCount: orderIdList.length, + orderIds: orderIdList.slice(0, 50), + }); const allocatedWaybillRows = await orderExpressModel.findAll({ attributes: [ 'order_id', 'business_key', 'waybill_code' ], where: { @@ -194,6 +280,11 @@ class ExpressPlatformService extends MainService { raw: true, }); + this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号后', { + traceId, + hitRowCount: Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows.length : 0, + }); + for (const row of Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows : []) { const orderId = Number(row && row.order_id); const businessKey = Number(row && row.business_key); @@ -211,8 +302,18 @@ class ExpressPlatformService extends MainService { } const Dictionary_bizcontent = { }; + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用前', { + traceId, + api: 'Differ.JH.LogisticsPlatFeatures', + request: Dictionary_bizcontent, + tokenPresent: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.token), + }); const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token); - console.log('==================\n菠萝派平台字典接口返回结果', JSON.stringify(Dictionary_result)); + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用后', { + traceId, + api: 'Differ.JH.LogisticsPlatFeatures', + response: Dictionary_result, + }); const order_bizcontent = { orders: orders.map(order_tmp => { @@ -226,7 +327,7 @@ class ExpressPlatformService extends MainService { numpackage: order.package_count || 1, businesstype: 'JH_Normal', - businessplat: order.sys_platform_code == 'KS' ? order.sys_platform_code : 'OTHERS', + businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS', paymode: listByWarehousePlatformCode.paymode ?? 1, ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal', codpaymoney: order.ar_amount ?? null, @@ -291,10 +392,26 @@ class ExpressPlatformService extends MainService { shoptype: matchedPlatform.shoptype, }; // 调用菠萝派平台接口进行数据处理 - console.log('==================\n业务数据', JSON.stringify(order_bizcontent), '\n=========================\n'); + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用前', { + traceId, + api: 'Differ.JH.Logistics.PostOrder', + waveIds: Array.from(new Set(waveIdListForLog)), + orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50), + request: order_bizcontent, + }); const result = await this.service.systems.poloApi.request('Differ.JH.Logistics.PostOrder', order_bizcontent, matchedPlatform, listByWarehousePlatformCode.token); - console.log('==================\n菠萝派平台接口返回结果', JSON.stringify(result)); + this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用后', { + traceId, + api: 'Differ.JH.Logistics.PostOrder', + response: result, + }); if (result && result.code !== '10000') { + this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', { + traceId, + code: result.code, + message: result.submessage, + response: result, + }); throw new Error(`菠萝派平台接口返回错误信息:${result.submessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\`` || '菠萝派平台接口调用失败'); } else if (result && result.code === '10000') { const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim(); @@ -363,6 +480,36 @@ class ExpressPlatformService extends MainService { case 'JD': case 'XHS': case 'SPH': + case 'PDD': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const waybillCode = resolveWaybillCode(item); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { + waybill_code: waybillCode, + signature: item.signature, + encryptedtoken: item.encryptedtoken, + encryptprintinfo: item.encryptprintinfo, + create_at: new Date(), + logistics_code: listByWarehousePlatformCode.logistics_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; default: break; } @@ -414,134 +561,173 @@ class ExpressPlatformService extends MainService { const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) { - await this.ctx.model.transaction(async transaction => { - for (const item of successUpdates) { - const warehouseId = Number(item.warehouse_id) || 0; - const orderId = Number(item.order_id) || 0; - const businessKey = Number(item.business_key) || 0; - if (!warehouseId || !orderId || !businessKey) { - continue; - } - - await this.ctx.model.OrderExpress.update(item.orderExpressValues, { - where: { - order_id: orderId, - business_key: businessKey, - warehouse_id: warehouseId, - }, - transaction, - }); - - if (item.orderDeliveryValues) { - const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id); - await orderModel.update(item.orderDeliveryValues, { - where: { - id: orderId, - }, - transaction, - }); - } - } - - if (storeWarehouseModel - && typeof storeWarehouseModel.findAll === 'function' - && settlementRelationMap.size > 0) { - const { Op } = this.app.Sequelize; - const relationList = Array.from(settlementRelationMap.values()); - const relationRows = await storeWarehouseModel.findAll({ - attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ], - where: { - [Op.or]: relationList.map(item => ({ - store_id: item.store_id, - warehouse_id: item.warehouse_id, - })), - }, - raw: true, - transaction, - lock: transaction.LOCK.UPDATE, - }); - - const relationRowMap = new Map(); - for (const row of Array.isArray(relationRows) ? relationRows : []) { - const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`; - if (relationKey !== '0:0') { - relationRowMap.set(relationKey, row); - } - } - - for (const item of relationList) { - const relationKey = `${item.store_id}:${item.warehouse_id}`; - const row = relationRowMap.get(relationKey); - if (!row) { + this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务开始前', { + traceId, + successUpdateCount: successUpdates.length, + relationCount: settlementRelationMap.size, + sampleOrderIds: successUpdates.slice(0, 50).map(item => Number(item && item.order_id || 0)).filter(Boolean), + }); + try { + await this.ctx.model.transaction(async transaction => { + for (const item of successUpdates) { + const warehouseId = Number(item.warehouse_id) || 0; + const orderId = Number(item.order_id) || 0; + const businessKey = Number(item.business_key) || 0; + if (!warehouseId || !orderId || !businessKey) { continue; } - const currentPrintQuantity = Number(row.print_quantity || 0); - const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0)); - const successCount = Number(item.success_count || 0); - if (successCount <= 0) { - continue; - } - const printDecrement = successCount; - const lockedDecrement = Math.min(currentLockedQuantity, printDecrement); - const nextPrintQuantity = currentPrintQuantity - printDecrement; - const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement); - await storeWarehouseModel.update({ - print_quantity: nextPrintQuantity, - print_quantity_locked: nextLockedQuantity, - }, { + await this.ctx.model.OrderExpress.update(item.orderExpressValues, { where: { - id: row.id, + order_id: orderId, + business_key: businessKey, + warehouse_id: warehouseId, }, transaction, }); - await this.ctx.model.StoreWarehousePrintQuantityLog.create({ - contract_id: Number(row.id || 0), - store_id: Number(row.store_id || 0), - warehouse_id: Number(row.warehouse_id || 0), - change_type: 'order_deduct', - business_type: 'order_express', - business_id: null, - change_quantity: -printDecrement, - balance_before: Math.max(0, currentPrintQuantity), - balance_after: Math.max(0, nextPrintQuantity), - reason: '获取快递号成功扣减', - operator_id: null, - created_by: null, - }, { - transaction, - }); + if (item.orderDeliveryValues) { + const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id); + await orderModel.update(item.orderDeliveryValues, { + where: { + id: orderId, + }, + transaction, + }); + } } - } + + if (storeWarehouseModel + && typeof storeWarehouseModel.findAll === 'function' + && settlementRelationMap.size > 0) { + const { Op } = this.app.Sequelize; + const relationList = Array.from(settlementRelationMap.values()); + const relationRows = await storeWarehouseModel.findAll({ + attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ], + where: { + [Op.or]: relationList.map(item => ({ + store_id: item.store_id, + warehouse_id: item.warehouse_id, + })), + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const relationRowMap = new Map(); + for (const row of Array.isArray(relationRows) ? relationRows : []) { + const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`; + if (relationKey !== '0:0') { + relationRowMap.set(relationKey, row); + } + } + + for (const item of relationList) { + const relationKey = `${item.store_id}:${item.warehouse_id}`; + const row = relationRowMap.get(relationKey); + if (!row) { + continue; + } + + const currentPrintQuantity = Number(row.print_quantity || 0); + const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0)); + const successCount = Number(item.success_count || 0); + if (successCount <= 0) { + continue; + } + const printDecrement = successCount; + const lockedDecrement = Math.min(currentLockedQuantity, printDecrement); + const nextPrintQuantity = currentPrintQuantity - printDecrement; + const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement); + await storeWarehouseModel.update({ + print_quantity: nextPrintQuantity, + print_quantity_locked: nextLockedQuantity, + }, { + where: { + id: row.id, + }, + transaction, + }); + + await this.ctx.model.StoreWarehousePrintQuantityLog.create({ + contract_id: Number(row.id || 0), + store_id: Number(row.store_id || 0), + warehouse_id: Number(row.warehouse_id || 0), + change_type: 'order_deduct', + business_type: 'order_express', + business_id: null, + change_quantity: -printDecrement, + balance_before: Math.max(0, currentPrintQuantity), + balance_after: Math.max(0, nextPrintQuantity), + reason: '获取快递号成功扣减', + operator_id: null, + created_by: null, + }, { + transaction, + }); + } + } + }); + } catch (error) { + this.ctx.logger.error('[expressPlatform.polyapi] DB 回写事务异常', { + traceId, + successUpdateCount: successUpdates.length, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + throw error; + } + + this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务完成后', { + traceId, + successUpdateCount: successUpdates.length, + relationCount: settlementRelationMap.size, }); + const operationLogService = this.service + && this.service.systems + && this.service.systems.operationLog; + const operator = this.getOrderLogOperator(); + const logPayloads = []; for (const item of successUpdates) { const warehouseId = Number(item.warehouse_id) || 0; const orderId = Number(item.order_id) || 0; if (!warehouseId || !orderId) { continue; } - - await this.service.systems.operationLog.createOperationLog({ + logPayloads.push({ businessType: 'order', businessId: `${orderId}`, operationCode: 'WAYBILL', - operatorId: this.ctx.user ? this.ctx.user.id : 'system', - operatorName: this.ctx.user ? this.ctx.user.employees_name : '系统', - externalLogType: 'API', - operator: { - id: this.ctx.user ? this.ctx.user.employees_id : '0', - name: this.ctx.user ? this.ctx.user.employees_name : '系统', - }, + operator, extras: { message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`, warehouseId, + externalLogType: 'API', }, }); } + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } else { + this.ctx.logger.warn('[expressPlatform.polyapi] operationLog 批量写入服务不可用,跳过日志写入', { + traceId, + count: logPayloads.length, + }); + } + + this.ctx.logger.info('[expressPlatform.polyapi] 订单操作日志写入完成', { + traceId, + operationLogCount: successUpdates.length, + }); } } + this.ctx.logger.info('[expressPlatform.polyapi] 处理完成', { + traceId, + orderCount: normalizedOrders.length, + }); return { flag: true, code: 0, @@ -559,7 +745,6 @@ class ExpressPlatformService extends MainService { */ async cainiao(data = {}) { void data; - console.log('接收到菜鸟平台数据处理请求,入参:', JSON.stringify(data)); throw new Error('菜鸟平台接口未实现'); } @@ -571,8 +756,6 @@ class ExpressPlatformService extends MainService { */ async pdd(data = {}) { void data; - console.log('接收到拼多多平台数据处理请求,入参:', JSON.stringify(data)); - throw new Error('拼多多平台接口未实现'); } } diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index fe6ba7c..b872f66 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -579,6 +579,7 @@ class NoticeService extends Service { */ async resolveSubjectConfig(options = {}, subject = {}) { const storeModel = this.ctx.model && this.ctx.model.Store; + const deliveryOrderService = this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; const normalizeSubjectConfig = value => { if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') { return storeModel.normalizeSubjectConfig(value); @@ -601,15 +602,21 @@ class NoticeService extends Service { const subjectId = Number( options.subjectId || options.subject_id || subject.id || options.warehouseId || options.warehouse_id || options.storeId || options.store_id || 0 ); - if (!Number.isFinite(subjectId) || subjectId <= 0 || !storeModel || typeof storeModel.findByPk !== 'function') { + if (!Number.isFinite(subjectId) || subjectId <= 0) { return normalizeSubjectConfig(null); } try { - const store = await storeModel.findByPk(subjectId, { - attributes: [ 'subject_config' ], - }); - return normalizeSubjectConfig(store && store.subject_config); + if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') { + return normalizeSubjectConfig(null); + } + + const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(subjectId); + const nestedSubjectConfig = this.toObject(subjectConfig && subjectConfig.subject_config, null); + const resolvedSubjectConfig = nestedSubjectConfig && Object.keys(nestedSubjectConfig).length > 0 + ? nestedSubjectConfig + : subjectConfig; + return normalizeSubjectConfig(resolvedSubjectConfig); } catch (error) { this.ctx.logger.warn('[NoticeService.resolveSubjectConfig] load subject_config failed: %s', error.message); return normalizeSubjectConfig(null); diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 2a40472..47afb68 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -15,6 +15,91 @@ const OPERATION_LOG_ATTRIBUTES = [ ]; class operationLogService extends Service { + /** + * 将单条日志参数转换为数据库字段。 + * @param {Object} params 日志参数。 + * @param {string} params.businessType 业务类型。 + * @param {string|number} params.businessId 业务ID。 + * @param {string} params.operationCode 操作编码。 + * @param {Object} [params.operator={}] 操作人信息。 + * @param {Object} [params.extras={}] 扩展字段。 + * @param {Object|null} [params.beforeChanges=null] 操作前快照。 + * @return {Object} 可直接落库的日志数据。 + */ + buildOperationLogData(params = {}) { + const { ctx } = this; + const { + businessType, + businessId, + operationCode, + operator = {}, + beforeChanges = null, + extras = {}, + } = params; + + return { + business_type: businessType, + business_id: String(businessId), + operation_code: operationCode, + 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, + before_changes: beforeChanges, + platform_code: ctx.user?.platform_code || 'SYSTEM', + message: extras.message || null, + }; + } + + /** + * 规范并校验日志查询入参,强制要求业务ID与仓库ID。 + * @param {Object} query 查询参数。 + * @param {string} businessType 业务类型。 + * @return {{ where: Object, id: string|number, warehouseId: string|number }} 查询条件。 + */ + buildBusinessLogWhere(query = {}, businessType) { + const requestQuery = query && typeof query === 'object' ? query : {}; + const { + id, + warehouseId, + } = requestQuery; + + if (!id) { + throw new Error('id不能为空'); + } + + if (!warehouseId) { + throw new Error('仓库id不能为空'); + } + + return { + where: { + business_type: businessType, + business_id: id, + warehouse_id: warehouseId, + }, + id, + warehouseId, + }; + } + + /** + * 将日志模型结果格式化为接口输出结构。 + * @param {Object[]} rows 日志行数据。 + * @return {Object[]} 格式化后的日志列表。 + */ + formatOperationLogRows(rows = []) { + const { app } = this; + return rows.map(item => { + const itemTmp = JSON.parse(JSON.stringify(item)); + itemTmp.operation_name = app.getOperationCodeName(item.operation_code); + itemTmp.platform_name = app.getPlatformName(item.platform_code); + itemTmp.created_at = app.formatDate(itemTmp.created_at); + return itemTmp; + }); + } + /** * 通用操作日志记录方法 * @param {Object} params 日志参数 @@ -32,34 +117,25 @@ class operationLogService extends Service { * @param {number} params.extras.externalLogId 外部日志ID * @param {number} params.extras.warehouseId 仓库ID * @param {string} params.extras.message 日志信息 + * @param {Object} [params.transaction] 事务对象(可选) * */ - async createOperationLog(params) { + async createOperationLog(params = {}) { const { ctx } = this; const { businessType, businessId, - operationCode, - operator = {}, - beforeChanges = null, - extras = {}, + transaction, } = params; try { - const logData = { - business_type: businessType, - business_id: String(businessId), - operation_code: operationCode, - 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, - before_changes: beforeChanges, - platform_code: ctx.user?.platform_code || 'SYSTEM', - message: extras.message || null, - }; + const logData = this.buildOperationLogData(params); - const result = await ctx.model.OperationLog.create(logData); + const createOptions = {}; + if (transaction) { + createOptions.transaction = transaction; + } + + const result = await ctx.model.OperationLog.create(logData, createOptions); ctx.logger.info(`[OperationLog] 记录操作日志成功,ID: ${result.id}, Business: ${businessType}/${businessId}`); return result; } catch (error) { @@ -69,6 +145,48 @@ class operationLogService extends Service { } } + /** + * 批量写入操作日志,优先使用 bulkCreate,失败时自动降级单条写入。 + * @param {Array} paramsList 日志参数数组。 + * @param {Object} [options={}] 写入选项。 + * @param {Object} [options.transaction] 事务对象(可选)。 + * @return {Promise>} 写入结果数组。 + */ + async createOperationLogs(paramsList = [], options = {}) { + const { ctx } = this; + const requestOptions = options && typeof options === 'object' ? options : {}; + const transaction = requestOptions.transaction; + const normalizedParamsList = Array.isArray(paramsList) ? paramsList.filter(Boolean) : []; + + if (normalizedParamsList.length === 0) { + return []; + } + + const operationLogModel = ctx.model && ctx.model.OperationLog; + if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') { + ctx.logger.warn('[OperationLog] OperationLog.bulkCreate 不可用,降级单条写入'); + return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({ + ...item, + transaction: item && item.transaction ? item.transaction : transaction, + }))); + } + + try { + const rows = normalizedParamsList.map(item => this.buildOperationLogData(item)); + const bulkCreateOptions = {}; + if (transaction) { + bulkCreateOptions.transaction = transaction; + } + return await operationLogModel.bulkCreate(rows, bulkCreateOptions); + } catch (error) { + ctx.logger.error(`[OperationLog] 批量记录操作日志失败,降级单条写入: ${error.message}`, error); + return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({ + ...item, + transaction: item && item.transaction ? item.transaction : transaction, + }))); + } + } + /** * 按业务类型查询操作日志分页数据。 * @param {Object} query 查询参数。 @@ -80,28 +198,13 @@ class operationLogService extends Service { * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 */ async queryLogsByBusinessType(query = {}, businessType) { - const { ctx, app } = this; + const { ctx } = this; const requestQuery = query && typeof query === 'object' ? query : {}; const { - id, - warehouseId, page = 1, pageSize = 20, } = requestQuery; - - const where = { - business_type: businessType, - }; - - if (!id) { - throw new Error('id不能为空'); - } - where.business_id = id; - - if (!warehouseId) { - throw new Error('仓库id不能为空'); - } - where.warehouse_id = warehouseId; + const { where } = this.buildBusinessLogWhere(requestQuery, businessType); const currentPage = Number.parseInt(page, 10) || 1; const currentPageSize = Number.parseInt(pageSize, 10) || 20; @@ -118,13 +221,7 @@ class operationLogService extends Service { const rows = Array.isArray(result.rows) ? result.rows : []; return { - list: rows.map(item => { - const itemTmp = JSON.parse(JSON.stringify(item)); - itemTmp.operation_name = app.getOperationCodeName(item.operation_code); - itemTmp.platform_name = app.getPlatformName(item.platform_code); - itemTmp.created_at = app.formatDate(itemTmp.created_at); - return itemTmp; - }), + list: this.formatOperationLogRows(rows), pagination: { page: currentPage, pageSize: currentPageSize, @@ -160,6 +257,41 @@ class operationLogService extends Service { return await this.queryLogsByBusinessType(query, 'order'); } + /** + * 查询订单操作日志(不分页,返回全部)。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 订单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @return {Promise} 日志列表。 + */ + async queryAllOrderLogs(query = {}) { + return await this.queryAllLogsByBusinessType(query, 'order'); + } + + /** + * 按业务类型查询日志全量数据(不分页)。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 业务ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {string} businessType 业务类型。 + * @return {Promise} 日志列表。 + */ + async queryAllLogsByBusinessType(query = {}, businessType) { + const { ctx } = this; + const requestQuery = query && typeof query === 'object' ? query : {}; + const { where } = this.buildBusinessLogWhere(requestQuery, businessType); + + const rows = await ctx.model.OperationLog.findAll({ + where, + order: [[ 'created_at', 'DESC' ]], + attributes: OPERATION_LOG_ATTRIBUTES, + raw: true, + }); + + const normalizedRows = Array.isArray(rows) ? rows : []; + return this.formatOperationLogRows(normalizedRows); + } + /** * 查询收货单操作日志。 * @param {Object} query 查询参数。 diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js new file mode 100644 index 0000000..e9ec645 --- /dev/null +++ b/app/service/systems/order_print.js @@ -0,0 +1,369 @@ +'use strict'; + +const { Op } = require('sequelize'); +const OrderBaseService = require('../systemMethods/order/base'); + +class OrderPrintSystemService extends OrderBaseService { + /** + * 获取波次打印数据。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.waveIds 波次ID数组。 + * @param {number|string} params.warehouseId 仓库ID。 + * @return {Promise} 通用打印数据结构。 + */ + async getWavePrintData(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { + waveIds, + warehouseId, + } = 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 this.buildEmptyResult(normalizedWaveIds); + } + + 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); + + return this.buildWavePrintResult({ + waveRows, + orderRows, + hitWaveIds: validWaveIds, + missingWaveIds, + filteredWaveIds, + }); + } + + /** + * 规范化波次ID数组(去重与数字化)。 + * + * @param {Array} waveIds 原始波次ID数组。 + * @return {Array} 规范化后的波次ID数组。 + */ + normalizeWaveIds(waveIds = []) { + if (!Array.isArray(waveIds)) { + return []; + } + + const normalizedSet = new Set(); + + for (const rawId of waveIds) { + const normalizedId = Number(String(rawId ?? '').trim()); + if (Number.isInteger(normalizedId) && normalizedId > 0) { + normalizedSet.add(normalizedId); + } + } + + return Array.from(normalizedSet); + } + + /** + * 解析并校验仓库ID。 + * + * @param {number|string} warehouseId 入参仓库ID。 + * @return {number} 规范化后的仓库ID。 + */ + resolveWarehouseId(warehouseId) { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + const normalizedWarehouseId = Number(String(warehouseId ?? '').trim()); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('warehouse_id 必填且必须为正整数'); + } + + if (normalizedWarehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 必须与当前用户上下文 store_id 保持一致'); + } + + return normalizedWarehouseId; + } + + /** + * 按波次ID批量查询波次信息。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} waveIds 波次ID数组。 + * @return {Promise>} 波次基础信息。 + */ + async queryWavesByIds(warehouseId, waveIds = []) { + if (!Array.isArray(waveIds) || waveIds.length === 0) { + return []; + } + + const querySql = ` + SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND wave_status <> -1 + `; + + const rows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId, + waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 按波次ID批量查询订单明细。 + * + * @param {Array} waveIds 波次ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单明细列表。 + */ + async queryOrdersByWaveIds(waveIds = [], warehouseId) { + if (!Array.isArray(waveIds) || waveIds.length === 0) { + return []; + } + + const orderModel = await this.getOrderModel('order', warehouseId); + const rows = await orderModel.findAll({ + attributes: [ + 'id', + 'delivery_order_code', + 'source_order_codes', + 'wave_id', + 'wave_no', + 'name', + 'tel', + 'mobile', + 'province', + 'city', + 'area', + 'town', + 'detail_address', + 'sys_platform_code', + 'sys_platform_name', + 'logistics_name', + 'post_status', + 'status', + 'outbound_status', + 'print_status', + 'items_count', + 'items_total', + 'items_weight', + 'create_at', + 'pay_time', + ], + where: { + wave_id: { + [Op.in]: waveIds, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 过滤快递未完全分配的波次。 + * + * 规则:仅当波次下全部订单的 post_status 都为 fin 时,才视为快递已完全分配。 + * + * @param {Array} hitWaveIds 命中的波次ID数组。 + * @param {Array} orderRows 波次订单列表。 + * @return {{ validWaveIds: Array, filteredWaveIds: Array }} 过滤结果。 + */ + filterFullyAssignedExpressWaves(hitWaveIds = [], orderRows = []) { + const statsMap = new Map(); + for (const waveId of hitWaveIds) { + statsMap.set(Number(waveId), { + total: 0, + fin: 0, + }); + } + + for (const row of orderRows) { + const waveId = Number(row && row.wave_id || 0); + const stats = statsMap.get(waveId); + if (!stats) { + continue; + } + + const postStatus = String(row && row.post_status || '').trim(); + stats.total += 1; + if (postStatus === 'fin') { + stats.fin += 1; + } + } + + const validWaveIds = []; + const filteredWaveIds = []; + for (const waveId of hitWaveIds) { + const stats = statsMap.get(waveId) || { total: 0, fin: 0 }; + const isFullyAssigned = stats.total > 0 && stats.fin === stats.total; + if (isFullyAssigned) { + validWaveIds.push(waveId); + } else { + filteredWaveIds.push({ + wave_id: waveId, + reason: '快递未完全分配', + }); + } + } + + return { + validWaveIds, + filteredWaveIds, + }; + } + + /** + * 生成空结果结构。 + * + * @param {Array} normalizedWaveIds 规范化后的波次ID数组。 + * @return {Object} 空结果。 + */ + buildEmptyResult(normalizedWaveIds = []) { + return { + summary: { + total_waves: 0, + total_orders: 0, + }, + wave_list: [], + ext: { + missing_wave_ids: normalizedWaveIds, + filtered_wave_ids: [], + }, + }; + } + + /** + * 组装通用波次打印返回结构。 + * + * @param {Object} payload 聚合输入。 + * @param {Array} payload.waveRows 波次列表。 + * @param {Array} payload.orderRows 订单列表。 + * @param {Array} payload.hitWaveIds 命中的波次ID数组。 + * @param {Array} payload.missingWaveIds 未命中的波次ID数组。 + * @param {Array} payload.filteredWaveIds 被过滤的波次及原因。 + * @return {Object} 波次打印返回结果。 + */ + buildWavePrintResult(payload = {}) { + const { + waveRows = [], + orderRows = [], + hitWaveIds = [], + missingWaveIds = [], + filteredWaveIds = [], + } = this.isPlainObject(payload) ? payload : {}; + + const waveMetaMap = new Map(); + for (const row of waveRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + waveMetaMap.set(waveId, { + wave_id: waveId, + wave_no: String(row && row.wave_no || '').trim(), + }); + } + + const groupedWaveMap = new Map(); + for (const waveId of hitWaveIds) { + const waveMeta = waveMetaMap.get(waveId); + if (!waveMeta) { + continue; + } + + groupedWaveMap.set(waveId, { + wave_id: waveMeta.wave_id, + wave_no: waveMeta.wave_no, + order_count: 0, + orders: [], + }); + } + + for (const order of orderRows) { + const waveId = Number(order && order.wave_id || 0); + const groupedWave = groupedWaveMap.get(waveId); + if (!groupedWave) { + continue; + } + + groupedWave.orders.push({ + order_id: Number(order && order.id || 0), + order_no: String(order && (order.delivery_order_code || order.source_order_codes) || '').trim(), + wave_id: waveId, + wave_no: String(order && order.wave_no || '').trim() || groupedWave.wave_no, + receiver: { + name: String(order && order.name || '').trim(), + mobile: String(order && order.mobile || '').trim(), + tel: String(order && order.tel || '').trim(), + province: String(order && order.province || '').trim(), + city: String(order && order.city || '').trim(), + area: String(order && order.area || '').trim(), + town: String(order && order.town || '').trim(), + detail_address: String(order && order.detail_address || '').trim(), + }, + channel: { + sys_platform_code: String(order && order.sys_platform_code || '').trim(), + sys_platform_name: String(order && order.sys_platform_name || '').trim(), + logistics_name: String(order && order.logistics_name || '').trim(), + }, + status: { + order_status: String(order && order.status || '').trim(), + outbound_status: String(order && order.outbound_status || '').trim(), + print_status: String(order && order.print_status || '').trim(), + }, + metrics: { + items_count: Number(order && order.items_count || 0), + items_total: Number(order && order.items_total || 0), + items_weight: Number(order && order.items_weight || 0), + }, + times: { + create_at: order && order.create_at || null, + pay_time: order && order.pay_time || null, + }, + }); + } + + const waveList = Array.from(groupedWaveMap.values()); + waveList.sort((a, b) => String(a.wave_no || '').localeCompare(String(b.wave_no || ''))); + let totalOrders = 0; + for (const wave of waveList) { + wave.order_count = wave.orders.length; + totalOrders += wave.order_count; + } + + return { + summary: { + total_waves: waveList.length, + total_orders: totalOrders, + }, + wave_list: waveList, + ext: { + missing_wave_ids: missingWaveIds, + filtered_wave_ids: filteredWaveIds, + }, + }; + } +} + +module.exports = OrderPrintSystemService; diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index d37bae8..f41430e 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -5,6 +5,7 @@ const MainService = require('../main'); const STORAGE_STATUS_FIN = 'fin'; const STORAGE_STATUS_ERROR = 'error'; const ORDER_STEP_EXCEPTION = 3; +const ALLOCATION_LOG_SAMPLE_LIMIT = 20; /** * 规范化块状日志的输出值。 @@ -97,6 +98,22 @@ function writeAllocationTextLog(title, payload) { process.stdout.write(`${formatAllocationLogBlock(title, payload)}\n`); } +/** + * 生成数组日志摘要,避免输出全量数据。 + * + * @param {Array} list 原始数组。 + * @param {number} [limit=ALLOCATION_LOG_SAMPLE_LIMIT] 采样数量上限。 + * @return {{count: number, sample: Array}} 摘要信息。 + */ +function summarizeArrayForLog(list, limit = ALLOCATION_LOG_SAMPLE_LIMIT) { + const normalizedList = Array.isArray(list) ? list : []; + + return { + count: normalizedList.length, + sample: normalizedList.slice(0, limit), + }; +} + /** * 将输入值规范化为布尔值。 * @@ -196,10 +213,9 @@ function summarizeStorageRows(stockId, storageRows = []) { * * @param {Object} left 左侧库存。 * @param {Object} right 右侧库存。 - * @param {boolean} prioritizeStorage 是否优先使用存储储位。 * @return {number} 排序结果。 */ -function compareStorageRows(left, right, prioritizeStorage) { +function compareStorageRows(left, right) { const leftHasProductionDate = Boolean(left.production_date); const rightHasProductionDate = Boolean(right.production_date); @@ -413,65 +429,6 @@ function normalizeOrderIds(data = {}) { return Array.from(new Set(orderIds)); } -/** - * 规范化订单创建渠道。 - * - * @param {unknown} value 创建渠道原始值。 - * @return {string} 规范化后的渠道码。 - */ -function normalizeCreateChannel(value) { - const normalizedValue = String(value || '').trim().toUpperCase(); - - return normalizedValue || 'MANUAL'; -} - -/** - * 按创建渠道对订单分组。 - * - * @param {Array} orders 订单列表。 - * @return {Array} 分组结果。 - */ -function groupOrdersByCreateChannel(orders = []) { - const groupedOrderMap = new Map(); - - for (const order of Array.isArray(orders) ? orders : []) { - if (!order || typeof order !== 'object') { - continue; - } - - const createChannel = normalizeCreateChannel(order.create_channel); - let groupedOrder = groupedOrderMap.get(createChannel); - - if (!groupedOrder) { - groupedOrder = { - create_channel: createChannel, - order_ids: [], - order_count: 0, - orders: [], - }; - groupedOrderMap.set(createChannel, groupedOrder); - } - - const orderId = toNumber(order.id, 0); - if (orderId > 0) { - groupedOrder.order_ids.push(orderId); - } - - groupedOrder.order_count += 1; - groupedOrder.orders.push({ - id: orderId, - delivery_order_code: String(order.delivery_order_code || '').trim(), - create_channel: createChannel, - sync_status: String(order.sync_status || '').trim() || 'padding', - express_code: String(order.express_code || '').trim(), - post_status: String(order.post_status || '').trim() || 'none', - storage_status: String(order.storage_status || '').trim() || 'none', - }); - } - - return Array.from(groupedOrderMap.values()); -} - /** * 规范化取消储位分配相关入参。 * @@ -515,6 +472,9 @@ class OrderStorageAllocationService extends MainService { async allocatePicking(data = {}) { const { ctx, app } = this; const requestData = this.isPlainObject(data) ? data : {}; + const progressCallback = typeof requestData.progress_callback === 'function' + ? requestData.progress_callback + : null; const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); const orderIds = normalizeOrderIds(requestData); const allowStorageLocation = normalizeBooleanFlag( @@ -562,6 +522,19 @@ class OrderStorageAllocationService extends MainService { const transaction = await ctx.model.transaction(); const { Op } = app.Sequelize; const now = new Date(); + const notifyProgress = async payload => { + if (typeof progressCallback !== 'function') { + return; + } + + try { + await progressCallback(payload); + } catch (error) { + if (ctx.logger && typeof ctx.logger.warn === 'function') { + ctx.logger.warn('[OrderStorageAllocationService.allocatePicking] 上报进度回调失败: %s', error && error.message ? error.message : error); + } + } + }; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务已创建', { warehouseId, @@ -599,7 +572,8 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单主表查询完成', { warehouseId, - requestedOrderIds: orderIds, + requestedOrderCount: orderIds.length, + requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), orderRowCount: Array.isArray(orderRows) ? orderRows.length : 0, }); @@ -655,27 +629,34 @@ class OrderStorageAllocationService extends MainService { pendingOrderIds.push(orderId); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单进入待分配列表', { orderId, - pendingOrderIds, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单过滤完成', { - requestedOrderIds: orderIds, - pendingOrderIds, - skippedOrders, + requestedOrderCount: orderIds.length, + pendingOrderCount: pendingOrderIds.length, + skippedOrderCount: skippedOrders.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); if (pendingOrderIds.length === 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无需分配的订单,准备提交事务', { warehouseId, - skippedOrders, + skippedOrderCount: skippedOrders.length, + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); await transaction.commit(); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', { warehouseId, - requestedOrderIds: orderIds, - pendingOrderIds, - skippedOrders, + requestedOrderCount: orderIds.length, + pendingOrderCount: pendingOrderIds.length, + skippedOrderCount: skippedOrders.length, + requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); return { code: 200, @@ -705,7 +686,8 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细查询完成', { warehouseId, - pendingOrderIds, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), orderItemRowCount: Array.isArray(orderItemRows) ? orderItemRows.length : 0, }); @@ -733,8 +715,10 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细归集完成', { warehouseId, - pendingOrderIds, - stockIds, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + stockIdCount: stockIds.length, + stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); if (stockIds.length > 0) { @@ -755,7 +739,8 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录预锁定完成', { warehouseId, - stockIds, + stockIdCount: stockIds.length, + stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); const storageRows = stockIds.length > 0 @@ -799,7 +784,8 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 可分配库存查询完成', { warehouseId, - stockIds, + stockIdCount: stockIds.length, + stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0, }); @@ -840,6 +826,14 @@ class OrderStorageAllocationService extends MainService { const stockAllocationMap = new Map(); const storageAllocationMap = new Map(); const orderResults = []; + const totalCount = pendingOrderIds.length; + let processedCount = 0; + + await notifyProgress({ + status: 'running', + total_count: totalCount, + processed_count: processedCount, + }); for (const orderId of pendingOrderIds) { const orderRow = orderMap.get(orderId); @@ -918,7 +912,7 @@ class OrderStorageAllocationService extends MainService { const storageRowsForStock = storageRowsByStockId.get(stockId) || []; const candidateStorageRows = storageRowsForStock .slice() - .sort((left, right) => compareStorageRows(left, right, allowStorageSpace)); + .sort((left, right) => compareStorageRows(left, right)); let shortageReason = ''; let shortageDiagnostics = null; @@ -1122,45 +1116,114 @@ class OrderStorageAllocationService extends MainService { orderId, orderResult: orderResults[orderResults.length - 1], }); + + processedCount += 1; + await notifyProgress({ + status: 'running', + total_count: totalCount, + processed_count: processedCount, + }); } - for (const [ stockId, quantity ] of stockAllocationMap.entries()) { - if (quantity <= 0) { - continue; - } + const stockLockEntries = Array.from(stockAllocationMap.entries()) + .map(([ stockId, quantity ]) => ({ + stockId: toNumber(stockId, 0), + quantity: toNumber(quantity, 0), + })) + .filter(item => item.stockId > 0 && item.quantity > 0); - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备更新库存主表锁定数量', { + if (stockLockEntries.length > 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备批量更新库存主表锁定数量', { warehouseId, - stockId, - quantity, + stockLockEntries, }); - const stockRecord = await ctx.model.StockWarehouse.findByPk(stockId, { + const lockStockIds = stockLockEntries.map(item => item.stockId); + const existingStockRows = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id' ], + where: { + id: { + [Op.in]: lockStockIds, + }, + warehouse_id: warehouseId, + }, transaction, + lock: transaction.LOCK.UPDATE, + raw: true, }); - if (!stockRecord) { + const existingStockIdSet = new Set( + (Array.isArray(existingStockRows) ? existingStockRows : []) + .map(row => toNumber(row && row.id, 0)) + .filter(stockId => stockId > 0) + ); + + const missingStockEntry = stockLockEntries.find(item => !existingStockIdSet.has(item.stockId)); + if (missingStockEntry) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录缺失,准备抛错', { warehouseId, - stockId, - quantity, + stockId: missingStockEntry.stockId, + quantity: missingStockEntry.quantity, }); - throw new Error(`库存主记录不存在: ${stockId}`); + throw new Error(`库存主记录不存在: ${missingStockEntry.stockId}`); } - await stockRecord.increment('locked_quantity', { - by: quantity, - transaction, - silent: true, - }); - await stockRecord.reload({ transaction }); - - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主表锁定数量更新完成', { + const updateSqlReplacements = { warehouseId, - stockId, - quantity, - locked_quantity: stockRecord.locked_quantity, + stockIds: lockStockIds, + }; + const caseSqlSegments = []; + + stockLockEntries.forEach((item, index) => { + const stockIdKey = `stockId_${index}`; + const quantityKey = `quantity_${index}`; + updateSqlReplacements[stockIdKey] = item.stockId; + updateSqlReplacements[quantityKey] = item.quantity; + caseSqlSegments.push(`WHEN :${stockIdKey} THEN :${quantityKey}`); }); + + const updateStockLockSql = ` + UPDATE wms_stock_warehouse + SET locked_quantity = locked_quantity + CASE id + ${caseSqlSegments.join('\n ')} + ELSE 0 + END + WHERE warehouse_id = :warehouseId + AND id IN (:stockIds) + `; + + await ctx.model.query(updateStockLockSql, { + replacements: updateSqlReplacements, + transaction, + }); + + const updatedStockRows = await ctx.model.StockWarehouse.findAll({ + attributes: [ 'id', 'locked_quantity' ], + where: { + id: { + [Op.in]: lockStockIds, + }, + warehouse_id: warehouseId, + }, + transaction, + raw: true, + }); + + const updatedLockedQuantityMap = new Map( + (Array.isArray(updatedStockRows) ? updatedStockRows : []).map(row => [ + toNumber(row && row.id, 0), + toNumber(row && row.locked_quantity, 0), + ]) + ); + + for (const item of stockLockEntries) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主表锁定数量更新完成', { + warehouseId, + stockId: item.stockId, + quantity: item.quantity, + locked_quantity: toNumber(updatedLockedQuantityMap.get(item.stockId), 0), + }); + } } if (pickingRows.length > 0) { @@ -1175,26 +1238,30 @@ class OrderStorageAllocationService extends MainService { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备提交事务', { warehouseId, - pendingOrderIds, - skippedOrders, - orderResults, - stockLockSummary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderCount: skippedOrders.length, + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + orderResultSummary: summarizeArrayForLog(orderResults), + stockLockSummary: summarizeArrayForLog(Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ stock_id: stockId, locked_quantity: quantity, - })), - storageLockSummary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ + }))), + storageLockSummary: summarizeArrayForLog(Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ storage_id: storageId, locked_quantity: quantity, - })), + }))), }); await transaction.commit(); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', { warehouseId, - pendingOrderIds, - skippedOrders, - orderResults, + pendingOrderCount: pendingOrderIds.length, + pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + skippedOrderCount: skippedOrders.length, + skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), + orderResultSummary: summarizeArrayForLog(orderResults), }); const errorOrderResults = orderResults.filter(item => item.status === 'error'); @@ -1260,7 +1327,18 @@ class OrderStorageAllocationService extends MainService { message: shortageMessages.length > 0 ? '储位分配完成,部分订单库存不足' : '储位分配完成', - responseData, + responseDataSummary: { + requestedOrderIds: summarizeArrayForLog(responseData.requested_order_ids), + pendingOrderIds: summarizeArrayForLog(responseData.pending_order_ids), + allocatedOrderIds: summarizeArrayForLog(responseData.allocated_order_ids), + shortageOrderIds: summarizeArrayForLog(responseData.shortage_order_ids), + skippedOrders: summarizeArrayForLog(responseData.skipped_orders), + orders: summarizeArrayForLog(responseData.orders), + stockLockSummary: summarizeArrayForLog(responseData.stock_lock_summary), + storageLockSummary: summarizeArrayForLog(responseData.storage_lock_summary), + shortageMessages: summarizeArrayForLog(responseData.shortage_messages), + pickingCount: responseData.picking_count, + }, }); return { diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js new file mode 100644 index 0000000..788944a --- /dev/null +++ b/app/service/systems/pick.js @@ -0,0 +1,329 @@ +'use strict'; + +const Service = require('egg').Service; + +const REVIEWED_INSPECTION_STATUS = 'fin'; + +class PickSystemService extends Service { + /** + * 按仓库获取订单分表模型。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 订单模型对象。 + */ + async getOrderModel(warehouseId) { + const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + throw this.createBusinessError('订单分表模型工厂不可用', 500); + } + + const model = await factory.getCurrentModel(warehouseId); + if (!model || typeof model.findOne !== 'function' || typeof model.findAll !== 'function') { + throw this.createBusinessError('订单分表模型不可用', 500); + } + + return model; + } + + /** + * 生成带业务状态码的错误对象。 + * + * @param {string} message 错误文案。 + * @param {number} [code=400] 错误码。 + * @return {Error} 错误对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 解析订单所属波次信息。 + * + * @param {Object} order 订单记录。 + * @return {{waveId: number, waveNo: string}} 波次信息。 + */ + resolveWaveInfo(order = {}) { + const waveId = Number(order.wave_id || 0); + const waveNo = String(order.wave_no || '').trim(); + return { + waveId: Number.isFinite(waveId) ? waveId : 0, + waveNo, + }; + } + + /** + * 判断订单是否已复核。 + * + * 当前使用 `inspection_status === "fin"` 作为已复核判定。 + * + * @param {Object} order 订单记录。 + * @return {boolean} 是否已复核。 + */ + isOrderReviewed(order = {}) { + return String(order.inspection_status || '').trim() === REVIEWED_INSPECTION_STATUS; + } + + /** + * 根据波次信息构建订单查询条件。 + * + * @param {Object} waveInfo 波次信息。 + * @param {number} warehouseId 仓库ID。 + * @return {Object} Sequelize 查询条件。 + */ + buildWaveOrderWhere(waveInfo = {}, warehouseId) { + const { Op } = this.app.Sequelize; + const where = { + warehouse_id: warehouseId, + }; + + if (waveInfo.waveId > 0 && waveInfo.waveNo) { + where[Op.or] = [ + { wave_id: waveInfo.waveId }, + { wave_no: waveInfo.waveNo }, + ]; + return where; + } + + if (waveInfo.waveId > 0) { + where.wave_id = waveInfo.waveId; + return where; + } + + where.wave_no = waveInfo.waveNo; + return where; + } + + /** + * 按波次信息查询拣货汇总。 + * + * @param {Object} params 查询参数。 + * @param {number} params.orderId 当前订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {string} [params.waveNo] 波次号。 + * @param {number} [params.waveId] 波次ID。 + * @param {number} [params.storeId] 货主ID。 + * @param {boolean} params.fullDisplay 是否完整显示。 + * @return {Promise} 波次拣货汇总结果。 + */ + async queryPickingInfo(params = {}) { + const { Op } = this.app.Sequelize; + const { ctx } = this; + const { + orderId, + warehouseId, + waveNo, + waveId, + storeId, + fullDisplay, + } = params; + + const normalizedOrderId = Number(orderId || 0); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('order_id 参数不合法', 400); + } + + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const waveInfo = { + waveId: Number(waveId || 0), + waveNo: String(waveNo || '').trim(), + }; + if (waveInfo.waveId <= 0 && !waveInfo.waveNo) { + throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400); + } + + const orderModel = await this.getOrderModel(normalizedWarehouseId); + + const waveOrderRows = await orderModel.findAll({ + where: this.buildWaveOrderWhere(waveInfo, normalizedWarehouseId), + attributes: [ 'id', 'inspection_status', 'store_id' ], + raw: true, + }); + + const orderIds = Array.isArray(waveOrderRows) + ? waveOrderRows + .map(item => Number(item && item.id || 0)) + .filter(id => id > 0) + : []; + + if (orderIds.length === 0) { + throw this.createBusinessError('未找到波次对应订单', 404); + } + + const orderStatusMap = new Map(); + for (const row of waveOrderRows) { + const id = Number(row && row.id || 0); + if (id <= 0) { + continue; + } + orderStatusMap.set(id, { + inspection_status: String(row && row.inspection_status || '').trim(), + }); + } + + const pickingRows = await ctx.model.Picking.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const spaceIds = Array.isArray(pickingRows) + ? Array.from(new Set(pickingRows + .map(item => Number(item && item.space_id || 0)) + .filter(id => id > 0))) + : []; + + const locationRows = spaceIds.length > 0 + ? await ctx.model.LocationSpace.findAll({ + where: { + id: { + [Op.in]: spaceIds, + }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ + 'id', + 'space_code', + 'custom_name', + 'custom_barcode', + 'zone_id', + 'space_status', + 'is_enabled', + 'pick_sequence', + 'pick_priority', + ], + raw: true, + }) + : []; + + const locationMap = new Map(); + for (const location of Array.isArray(locationRows) ? locationRows : []) { + const locationId = Number(location && location.id || 0); + if (locationId > 0) { + locationMap.set(locationId, location); + } + } + + const currentStoreId = Number(storeId || (waveOrderRows[0] && waveOrderRows[0].store_id) || 0); + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: currentStoreId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'use_status' ], + raw: true, + }); + + const fullDisplayFlag = Boolean(fullDisplay); + const allDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => { + const currentOrderId = Number(row && row.order_id || 0); + const orderStatus = orderStatusMap.get(currentOrderId) || { inspection_status: 'none' }; + const reviewed = this.isOrderReviewed(orderStatus); + const spaceId = Number(row && row.space_id || 0); + + return { + id: Number(row && row.id || 0), + order_id: currentOrderId, + order_item_id: Number(row && row.order_item_id || 0), + storage_id: Number(row && row.storage_id || 0), + quantity: Number(row && row.quantity || 0), + space_id: spaceId, + space_name: String(row && row.space_name || ''), + picking_status: String(row && row.status || ''), + inspection_status: orderStatus.inspection_status, + reviewed, + location_space: locationMap.get(spaceId) || null, + store_warehouse: storeWarehouse || null, + }; + }); + + const pendingReviewDetails = allDetails.filter(item => !item.reviewed); + const reviewedDetails = allDetails.filter(item => item.reviewed); + const displayDetails = fullDisplayFlag ? allDetails : pendingReviewDetails; + + const sumQuantity = rows => rows.reduce((sum, item) => sum + Number(item && item.quantity || 0), 0); + + return { + order_id: normalizedOrderId, + wave_id: waveInfo.waveId, + wave_no: waveInfo.waveNo, + full_display: fullDisplayFlag, + summary: { + total_count: allDetails.length, + pending_review_count: pendingReviewDetails.length, + reviewed_count: reviewedDetails.length, + quantity_total: sumQuantity(allDetails), + display_count: displayDetails.length, + display_quantity_total: sumQuantity(displayDetails), + }, + list: displayDetails, + }; + } + + /** + * 按订单ID查询其波次拣货信息。 + * + * @param {Object} params 查询参数。 + * @param {number} params.orderId 订单ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {boolean} params.fullDisplay 是否完整显示。 + * @return {Promise} 波次拣货汇总结果。 + */ + async queryByOrder(params = {}) { + const { + orderId, + warehouseId, + fullDisplay, + } = params; + + const normalizedOrderId = Number(orderId || 0); + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + throw this.createBusinessError('order_id 参数不合法', 400); + } + + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400); + } + + const orderModel = await this.getOrderModel(normalizedWarehouseId); + + const order = await orderModel.findOne({ + where: { + id: normalizedOrderId, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'store_id', 'wave_no', 'wave_id' ], + raw: true, + }); + + if (!order) { + throw this.createBusinessError('订单不存在', 404); + } + + const waveInfo = this.resolveWaveInfo(order); + if (waveInfo.waveId <= 0 && !waveInfo.waveNo) { + throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400); + } + + return await this.queryPickingInfo({ + orderId: normalizedOrderId, + warehouseId: normalizedWarehouseId, + waveNo: waveInfo.waveNo, + waveId: waveInfo.waveId, + storeId: Number(order.store_id || 0), + fullDisplay, + }); + } +} + +module.exports = PickSystemService; diff --git a/app/service/systems/polo_api.js b/app/service/systems/polo_api.js index 13ff087..173632e 100644 --- a/app/service/systems/polo_api.js +++ b/app/service/systems/polo_api.js @@ -13,27 +13,14 @@ class PoloApiService extends Service { } /** - * 测试 Polo API 请求并返回请求结果。 + * 发起 Polo API POST 请求。 * - * @param platid - * @return {Promise} request() 的返回结果。 + * @param {string} method 接口方法名。 + * @param {object|string} [bizcontent={}] 业务参数。 + * @param {object} [config={}] 平台配置。 + * @param {string} [token] 可选 token。 + * @return {Promise} 接口响应数据。 */ - async test(platid) { - return this.client.request({ - method: 'Differ.JH.LogisticsPlatFeatures', - platid, - bizcontent: {}, - }); - } - async GetWayBillCondition(platid) { - return this.client.request({ - method: 'Differ.JH.Logistics.GetWayBillCondition', - platid, - bizcontent: { - cpcode: 'POSTB', - }, - }); - } async request(method, bizcontent = {}, config = {}, token) { console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent)); return this.client.request({ @@ -43,6 +30,16 @@ class PoloApiService extends Service { token, }); } + + /** + * 发起 Polo API GET 请求。 + * + * @param {string} method 接口方法名。 + * @param {object|string} [bizcontent={}] 业务参数。 + * @param {object} [config={}] 平台配置。 + * @param {string} [token] 可选 token。 + * @return {Promise} 接口响应数据。 + */ async get(method, bizcontent = {}, config = {}, token) { console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent)); return this.client.get({ diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js new file mode 100644 index 0000000..3e59b35 --- /dev/null +++ b/app/service/systems/setting/warehouse.js @@ -0,0 +1,265 @@ +'use strict'; + +const { Service } = require('egg'); + +// 仓库设置字段元信息(对应 wms_store.subject_config) +const WAREHOUSE_SETTING_FIELDS = Object.freeze([ + Object.freeze({ + key: 'max_notice_webhook_count', + name: '最大通知 Webhook 次数', + type: 'integer', + default: 5, + required: false, + description: '单次事件最多触发的 Webhook 通知次数(0-5)', + min: 0, + max: 5, + }), + Object.freeze({ + key: 'max_wave_quantity', + name: '仓库波次最大数量限制', + type: 'integer', + default: 500, + required: false, + description: '控制单个波次允许的最大订单数量,默认 500', + min: 1, + }), + Object.freeze({ + key: 'min_group_order_fetch_quantity', + name: '最小团购订单抓取数量', + type: 'integer', + default: 13, + required: false, + description: '控制团购波次最小抓取订单数量,默认 13', + min: 1, + }), + Object.freeze({ + key: 'default_express_code', + name: '默认快递编码', + type: 'string', + default: 'STO', + required: false, + description: '仓库默认使用的快递编码', + maxLength: 50, + }), + Object.freeze({ + key: 'default_platform_code', + name: '默认平台编码', + type: 'string', + default: 'TB', + required: false, + description: '仓库默认使用的平台编码', + maxLength: 50, + }), + Object.freeze({ + key: 'group_wave_prefix', + name: '团购波次前缀', + type: 'string', + default: 'B', + required: false, + description: '团购波次编号前缀,最多 5 个字符,默认 B', + maxLength: 5, + }), + Object.freeze({ + key: 'delete_order_wave_prefix', + name: '删单波次前缀', + type: 'string', + default: 'A', + required: false, + description: '删单波次编号前缀,最多 5 个字符,默认 A', + maxLength: 5, + }), + Object.freeze({ + key: 'webhook_enabled', + name: '是否启用 Webhook', + type: 'flag', + default: false, + required: false, + description: '控制仓库是否启用 Webhook 事件推送', + }), + Object.freeze({ + key: 'callback_strategy', + name: '回调策略', + type: 'enum', + default: 'async', + required: false, + description: '仓库 Webhook 事件的回调执行策略', + options: [ + Object.freeze({ value: 'sync', label: '同步回调' }), + Object.freeze({ value: 'async', label: '异步回调' }), + ], + }), +]); + +class SettingWarehouseService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + /** + * 从 ctx.user.store_id 获取当前仓库 ID。 + * + * @return {number} 仓库 ID。 + * @throws {Error} 未识别到仓库时抛出,状态码 400。 + */ + getCurrentWarehouseId() { + const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + throw this.createError('未识别到当前仓库,无法操作仓库设置', 400); + } + return warehouseId; + } + + /** + * 删除指定缓存键。 + * + * @param {string} cacheKey 缓存键。 + * @return {Promise} 无返回值。 + */ + async deleteCacheByKey(cacheKey) { + if (!cacheKey) { + return; + } + + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + return; + } + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, null, 0); + } + } + + /** + * 清理指定仓库设置相关缓存。 + * + * @param {number|string} warehouseId 仓库 ID。 + * @return {Promise} 无返回值。 + */ + async clearWarehouseSettingCache(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + + const keys = [ + `delivery_order:store:${normalizedWarehouseId}:subject_config`, + `warehouse:${normalizedWarehouseId}store:${normalizedWarehouseId}:info`, + ]; + + await Promise.all(keys.map(key => this.deleteCacheByKey(key).catch(() => null))); + } + + /** + * 获取仓库设置字段元信息列表。 + * + * @return {Array} 字段元信息数组(浅拷贝,含 options 拷贝)。 + */ + getFieldMeta() { + return WAREHOUSE_SETTING_FIELDS.map(field => ({ + key: field.key, + name: field.name, + type: field.type, + default: field.default, + required: field.required, + description: field.description, + ...(Array.isArray(field.options) ? { options: field.options.map(o => ({ ...o })) } : {}), + ...(field.min !== undefined ? { min: field.min } : {}), + ...(field.max !== undefined ? { max: field.max } : {}), + ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), + })); + } + + /** + * 读取当前仓库的设置(wms_store.subject_config)。 + * + * @return {Promise} 包含 warehouse_id 与 subject_config 的对象。 + * @throws {Error} 仓库不存在时抛出,状态码 404。 + */ + async getSettings() { + const warehouseId = this.getCurrentWarehouseId(); + + const store = await this.ctx.model.Store.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + }); + + if (!store) { + throw this.createError('仓库不存在', 404); + } + + return { + warehouse_id: warehouseId, + subject_config: store.subject_config, + }; + } + + /** + * 修改当前仓库设置并清理指定仓库缓存。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [data.subject_config] 仓库设置对象,支持部分字段更新。 + * @param {number|string} [data.cache_warehouse_id] 需要清理缓存的仓库 ID,默认当前仓库。 + * @param {number|string} [data.cacheWarehouseId] 同 cache_warehouse_id。 + * @return {Promise} 更新后的仓库设置。 + */ + async saveSettings(data = {}) { + const warehouseId = this.getCurrentWarehouseId(); + const storeModel = this.ctx.model && this.ctx.model.Store; + + if (!storeModel || typeof storeModel.findByPk !== 'function') { + throw this.createError('Store model 不可用', 500); + } + + const store = await storeModel.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + }); + + if (!store) { + throw this.createError('仓库不存在', 404); + } + + const hasSubjectConfig = Object.prototype.hasOwnProperty.call(data || {}, 'subject_config'); + const nextPatch = hasSubjectConfig ? data.subject_config : null; + if (!nextPatch || typeof nextPatch !== 'object' || Array.isArray(nextPatch)) { + throw this.createError('subject_config 参数不能为空且必须是对象', 400); + } + + const mergedConfig = { + ...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}), + ...nextPatch, + }; + + let normalizedConfig; + try { + normalizedConfig = typeof storeModel.normalizeSubjectConfig === 'function' + ? storeModel.normalizeSubjectConfig(mergedConfig) + : mergedConfig; + } catch (error) { + throw this.createError(error.message || 'subject_config 参数不合法', Number(error.code) || 400); + } + + await store.update({ + subject_config: normalizedConfig, + }); + + let cacheWarehouseId = Number( + data.cache_warehouse_id !== undefined ? data.cache_warehouse_id : (data.cacheWarehouseId !== undefined ? data.cacheWarehouseId : warehouseId) + ); + if (!Number.isFinite(cacheWarehouseId) || cacheWarehouseId <= 0) { + throw this.createError('cache_warehouse_id 参数不合法', 400); + } + cacheWarehouseId = Math.floor(cacheWarehouseId); + + await this.clearWarehouseSettingCache(cacheWarehouseId); + + return { + warehouse_id: warehouseId, + subject_config: store.subject_config, + cache_cleared_warehouse_id: cacheWarehouseId, + }; + } +} + +module.exports = SettingWarehouseService; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 8121b43..2028628 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -2310,6 +2310,20 @@ class stockStoreService extends Service { if (!stock_info) { throw new Error('商品不存在'); } + + const hasInputItemCode = Object.prototype.hasOwnProperty.call(data, 'item_code'); + if (hasInputItemCode) { + const itemCodeUniqueResult = await this.checkItemCodeUnique( + id, + item_code, + stock_info.store_id, + stock_info.warehouse_id + ); + if (!itemCodeUniqueResult || !itemCodeUniqueResult.isUnique) { + throw new Error('商品编码已存在,请检查后重试'); + } + } + // 4. 准备更新数据 const updateData = { item_code, @@ -2529,42 +2543,45 @@ class stockStoreService extends Service { async stockLog() { return undefined; } - async checkItemCodeUnique(id, item_code, store_id, warehouse_id) { + /** + * 校验商品编码在指定仓库与货主维度下是否唯一。 + * @param {number|null} item_id 商品ID(编辑场景用于排除自身) + * @param {string} item_code 商品编码 + * @param {number} owner_id 货主ID + * @param {number} warehouse_id 仓库ID + * @return {Promise<{unique:boolean,isUnique:boolean,message?:string}>} 唯一性校验结果 + */ + async checkItemCodeUnique(item_id, item_code, owner_id, warehouse_id) { const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { - // 检查条码是否被其他仓位使用(排除当前仓位) - let whereId = null; - if (id) { - whereId = { - id: { - [Op.ne]: id, // 排除当前仓位ID - }, + const normalizedItemCode = String(item_code || '').trim(); + const where = { + item_code: normalizedItemCode, + store_id: owner_id, + warehouse_id, + deleted_at: null, + }; + + if (item_id) { + where.id = { + [Op.ne]: item_id, }; } - const where = { - [Op.and]: [ - whereId, - { item_code }, - { store_id }, - { warehouse_id }, - { deleted_at: null }, // 未删除的记录 - ], - }; + const space = await ctx.model.StockWarehouse.findOne({ where, attributes: [ 'id' ], }); - // 如果没有找到重复的条码,返回唯一 if (!space) { - return { isUnique: true }; + return { unique: true, isUnique: true }; } - return { isUnique: false, message: '商品编码已被使用' }; + return { unique: false, isUnique: false, message: '商品编码已存在' }; } catch (error) { ctx.logger.error('检查商品编码唯一性失败:', error); - return { isUnique: false, message: '商品编码检测失败' }; + return { unique: false, isUnique: false, message: '商品编码检测失败' }; } } async handleBatchDelete(data) { diff --git a/app/service/systems/storage/index.js b/app/service/systems/storage/index.js index 2a10c7e..70bfc32 100644 --- a/app/service/systems/storage/index.js +++ b/app/service/systems/storage/index.js @@ -172,42 +172,7 @@ class IndexService extends Service { * @return {Promise} 更新后的库存记录。 */ async lockQuantity(id, quantity, options = {}) { - const callContext = { - hasTransaction: Boolean(options && options.transaction), - source: options && (options.source || options.caller || options.from || options.action) || null, - optionKeys: options && typeof options === 'object' - ? Object.keys(options).filter(key => key !== 'transaction') - : [], - }; - - console.log('[StorageService.lockQuantity] 开始锁定库存', { - id, - quantity, - callContext, - }); - - try { - const result = await this.updateQuantity(id, 0, quantity, options); - - console.log('[StorageService.lockQuantity] 锁定库存成功', { - id, - quantity, - callContext, - storageId: result && result.id, - locked_quantity: result && result.locked_quantity, - available_quantity: result && result.available_quantity, - }); - - return result; - } catch (error) { - console.log('[StorageService.lockQuantity] 锁定库存失败', { - id, - quantity, - callContext, - error, - }); - throw error; - } + return await this.updateQuantity(id, 0, quantity, options); } async unlockQuantity(id, quantity, options = {}) { diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index eaec53e..57e8f68 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -416,21 +416,24 @@ class ReceivingService extends Service { // 批量记录操作日志 try { - await Promise.all(ids.map(receivingId => - ctx.service.systems.operationLog.createOperationLog({ - businessType: 'receiving', - businessId: receivingId, - operationCode: 'RECEIVING_BATCH_CANCEL', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId: warehouse_id, - }, - beforeChanges: null, - }) - )); + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const payloads = ids.map(receivingId => ({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_BATCH_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: null, + })); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(payloads); + } } catch (logErr) { ctx.logger.warn('[receiving.batchCancelReceiving] 写入操作日志失败,不影响业务', logErr); } @@ -500,22 +503,25 @@ class ReceivingService extends Service { }); try { - await Promise.all(ids.map(receivingId => - ctx.service.systems.operationLog.createOperationLog({ - businessType: 'receiving', - businessId: receivingId, - operationCode: 'RECEIVING_REJECT', - operator: { - id: reviewerEmployeeId || ctx.user?.id, - name: reviewerName, - }, - extras: { - warehouseId: warehouse_id, - remark: updateData.remark || '', - }, - beforeChanges: null, - }) - )); + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const payloads = ids.map(receivingId => ({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_REJECT', + operator: { + id: reviewerEmployeeId || ctx.user?.id, + name: reviewerName, + }, + extras: { + warehouseId: warehouse_id, + remark: updateData.remark || '', + }, + beforeChanges: null, + })); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(payloads); + } } catch (logErr) { ctx.logger.warn('[receiving.rejectReceiving] 写入操作日志失败,不影响业务', logErr); } @@ -566,7 +572,7 @@ class ReceivingService extends Service { `收货单ID:${item.id || ''}`, `收货单号:${item.receiving_number || '无'}`, `收货创建人:${item.creator && item.creator.name || '无'}`, - `请及时处理重新提交完成收货。`, + '请及时处理重新提交完成收货。', ].join('\n') + '。', businessId: item.id || ids[0], subject: { @@ -700,19 +706,23 @@ class ReceivingService extends Service { // 写操作日志(失败不影响业务) try { - await Promise.all(normalizedIds.map(receivingId => - ctx.service.systems.operationLog.createOperationLog({ - businessType: 'receiving', - businessId: receivingId, - operationCode: 'RECEIVING_REVIEW', - operator: { - id: reviewerEmployeeId || ctx.user?.id, - name: reviewerName || '', - }, - extras: { warehouseId: warehouse_id }, - beforeChanges: null, - }) - )); + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + const payloads = normalizedIds.map(receivingId => ({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_REVIEW', + operator: { + id: reviewerEmployeeId || ctx.user?.id, + name: reviewerName || '', + }, + extras: { warehouseId: warehouse_id }, + beforeChanges: null, + transaction, + })); + + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(payloads, { transaction }); + } } catch (logErr) { ctx.logger.warn('[receiving.reviewReceiving] 写入操作日志失败,不影响业务', logErr); } diff --git a/config/config.default.js b/config/config.default.js index 4013715..0ad2210 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -27,13 +27,13 @@ module.exports = appInfo => { clients: { cache: { port: 6379, - host: '112.124.21.102', + host: '127.0.0.1', password: 'qwe2019@', db: 10, }, printer: { port: 6379, - host: '112.124.21.102', + host: '127.0.0.1', password: 'qwe2019@', db: 11, }, @@ -135,14 +135,14 @@ module.exports = appInfo => { config.mysql = { clients: { wms: { - host: '112.124.21.102', + host: '127.0.0.1', port: '3306', user: 'wms', password: 'P6j3YTHTpirepYWz', database: 'wms', }, ye4s: { - host: '112.124.21.102', + host: '127.0.0.1', port: '3306', user: 'ye4s', password: 'H@8h^QE4N$L.F_*', diff --git a/database/config.js b/database/config.js index 852d9fd..c745540 100644 --- a/database/config.js +++ b/database/config.js @@ -53,11 +53,24 @@ function resolveMysqlClient(appConfig, clientName) { } const projectRoot = path.resolve(__dirname, '..'); -const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js')); -const localConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.local.js')); -const appConfig = mergeDeep(defaultConfig, localConfig); -const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms'; -const mysqlClient = resolveMysqlClient(appConfig, clientName); + +let mysqlClient; +if (process.env.DB_HOST) { + mysqlClient = { + host: process.env.DB_HOST, + port: process.env.DB_PORT || 3306, + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME || 'wms', + }; +} else { + const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js')); + const isProduction = process.env.NODE_ENV === 'production'; + const localConfig = isProduction ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js')); + const appConfig = mergeDeep(defaultConfig, localConfig); + const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms'; + mysqlClient = resolveMysqlClient(appConfig, clientName); +} const baseConfig = { username: mysqlClient.user, diff --git a/database/migrations/20260504000000-baseline.js b/database/migrations/20260504000000-baseline.js new file mode 100644 index 0000000..add6cc6 --- /dev/null +++ b/database/migrations/20260504000000-baseline.js @@ -0,0 +1,109 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +/** + * Baseline migration - 2026-05-04 + * 以 SequelizeMeta.sql 为基准,定义当前数据库完整结构。 + * 生产环境:请将本文件名插入 SequelizeMeta 表,标记为已执行。 + * 新环境:直接运行 db:migrate,本文件会创建所有表结构。 + */ +module.exports = { + up: async queryInterface => { + const sqlRaw = fs.readFileSync( + path.join(__dirname, '../../SequelizeMeta.sql'), + 'utf8' + ); + + // 预处理:去掉 DROP TABLE,改为 CREATE TABLE IF NOT EXISTS,跳过 SequelizeMeta 表 + const sql = sqlRaw + .replace(/SET NAMES utf8mb4;\r?\n/g, '') + .replace(/DROP TABLE IF EXISTS `SequelizeMeta`;\r?\nCREATE TABLE[\s\S]*?ROW_FORMAT = Dynamic;\r?\n/m, '') + .replace(/DROP TABLE IF EXISTS `[^`]+`;\r?\n/g, '') + .replace(/CREATE TABLE `/g, 'CREATE TABLE IF NOT EXISTS `') + .replace(/SET FOREIGN_KEY_CHECKS = 1;?/g, ''); + + // 按分号+换行切割,逐条执行 + const statements = sql + .split(/;\s*\r?\n/) + .map(s => s.trim()) + .filter(s => s && !s.startsWith('--') && !s.startsWith('/*') && s !== 'SET FOREIGN_KEY_CHECKS = 0'); + + // 先禁用外键检查 + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0'); + for (const stmt of statements) { + if (stmt) { + await queryInterface.sequelize.query(stmt + ';'); + } + } + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1'); + }, + + down: async queryInterface => { + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0'); + // 按外键依赖逆序删除 + const tables = [ + 'wms_account_platform_active', + 'wms_employee_role', + 'wms_wave_batch', + 'wms_picking', + 'wms_picking_strategy', + 'wms_operation_log', + 'wms_notification_send_log', + 'wms_notification_webhook', + 'wms_stock_transaction', + 'wms_storage', + 'wms_receiving_detail', + 'wms_receiving', + 'wms_order_express_print_data', + 'wms_order_express', + 'wms_entry_items', + 'wms_entry_order', + 'wms_file_reference', + 'wms_file', + 'wms_i18n_translations', + 'wms_i18n_keys', + 'wms_express_print_record', + 'wms_print_log', + 'wms_express_interface', + 'wms_express_setting', + 'wms_embargo_policies', + 'wms_prohibited_type', + 'wms_location_space', + 'wms_location_zone', + 'wms_location_type', + 'wms_print_station_express', + 'wms_print_stations', + 'wms_print_template', + 'wms_platform_print_config', + 'wms_print_record', + 'wms_print_computer', + 'wms_print_items', + 'wms_print_log', + 'wms_system_log', + 'wms_stock_unit', + 'wms_stock_warehouse', + 'wms_stock_store', + 'wms_api_app', + 'wms_interface_type', + 'wms_account_store_employee', + 'wms_role', + 'wms_permission', + 'wms_platfrom_setting', + 'wms_fast_where', + 'wms_qimen_log', + 'wms_qimen_apps', + 'wms_express_product_type', + 'wms_express', + 'wms_account_login_log', + 'wms_store_warehouse', + 'wms_store', + 'wms_account', + ]; + for (const table of tables) { + await queryInterface.sequelize.query(`DROP TABLE IF EXISTS \`${table}\``); + } + await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1'); + }, +}; \ No newline at end of file diff --git a/database/migrations/20251109160640-init-wms_account.js b/database/migrations/archive/20251109160640-init-wms_account.js similarity index 100% rename from database/migrations/20251109160640-init-wms_account.js rename to database/migrations/archive/20251109160640-init-wms_account.js diff --git a/database/migrations/20251110081122-create-wms-account-login-log.js b/database/migrations/archive/20251110081122-create-wms-account-login-log.js similarity index 100% rename from database/migrations/20251110081122-create-wms-account-login-log.js rename to database/migrations/archive/20251110081122-create-wms-account-login-log.js diff --git a/database/migrations/20251110081641-create-wms-qimen-apps.js b/database/migrations/archive/20251110081641-create-wms-qimen-apps.js similarity index 100% rename from database/migrations/20251110081641-create-wms-qimen-apps.js rename to database/migrations/archive/20251110081641-create-wms-qimen-apps.js diff --git a/database/migrations/20251110082013-create-wms-store.js b/database/migrations/archive/20251110082013-create-wms-store.js similarity index 100% rename from database/migrations/20251110082013-create-wms-store.js rename to database/migrations/archive/20251110082013-create-wms-store.js diff --git a/database/migrations/20251110084033-create-wms-store-warehouse.js b/database/migrations/archive/20251110084033-create-wms-store-warehouse.js similarity index 100% rename from database/migrations/20251110084033-create-wms-store-warehouse.js rename to database/migrations/archive/20251110084033-create-wms-store-warehouse.js diff --git a/database/migrations/20251110090742-create-wms-interface-type.js b/database/migrations/archive/20251110090742-create-wms-interface-type.js similarity index 100% rename from database/migrations/20251110090742-create-wms-interface-type.js rename to database/migrations/archive/20251110090742-create-wms-interface-type.js diff --git a/database/migrations/20251110091013-create-wms-api-app.js b/database/migrations/archive/20251110091013-create-wms-api-app.js similarity index 100% rename from database/migrations/20251110091013-create-wms-api-app.js rename to database/migrations/archive/20251110091013-create-wms-api-app.js diff --git a/database/migrations/20251111083733-create-wms-stock-store.js b/database/migrations/archive/20251111083733-create-wms-stock-store.js similarity index 100% rename from database/migrations/20251111083733-create-wms-stock-store.js rename to database/migrations/archive/20251111083733-create-wms-stock-store.js diff --git a/database/migrations/20251112085825-create-wms-entry-order.js b/database/migrations/archive/20251112085825-create-wms-entry-order.js similarity index 100% rename from database/migrations/20251112085825-create-wms-entry-order.js rename to database/migrations/archive/20251112085825-create-wms-entry-order.js diff --git a/database/migrations/20251112085844-create-wms-entry-items.js b/database/migrations/archive/20251112085844-create-wms-entry-items.js similarity index 100% rename from database/migrations/20251112085844-create-wms-entry-items.js rename to database/migrations/archive/20251112085844-create-wms-entry-items.js diff --git a/database/migrations/20260322061000-add-delivery-time-to-order-delivery-tables.js b/database/migrations/archive/20260322061000-add-delivery-time-to-order-delivery-tables.js similarity index 100% rename from database/migrations/20260322061000-add-delivery-time-to-order-delivery-tables.js rename to database/migrations/archive/20260322061000-add-delivery-time-to-order-delivery-tables.js diff --git a/database/migrations/20260323103000-align-role-permission-fk.js b/database/migrations/archive/20260323103000-align-role-permission-fk.js similarity index 100% rename from database/migrations/20260323103000-align-role-permission-fk.js rename to database/migrations/archive/20260323103000-align-role-permission-fk.js diff --git a/database/migrations/20260323113000-add-role-store-fk.js b/database/migrations/archive/20260323113000-add-role-store-fk.js similarity index 100% rename from database/migrations/20260323113000-add-role-store-fk.js rename to database/migrations/archive/20260323113000-add-role-store-fk.js diff --git a/database/migrations/20260323123000-add-permission-parent-fk.js b/database/migrations/archive/20260323123000-add-permission-parent-fk.js similarity index 100% rename from database/migrations/20260323123000-add-permission-parent-fk.js rename to database/migrations/archive/20260323123000-add-permission-parent-fk.js diff --git a/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js b/database/migrations/archive/20260404093000-add-policy-config-to-wms-store-warehouse.js similarity index 100% rename from database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js rename to database/migrations/archive/20260404093000-add-policy-config-to-wms-store-warehouse.js diff --git a/database/migrations/20260404113000-create-wms-notification-webhook.js b/database/migrations/archive/20260404113000-create-wms-notification-webhook.js similarity index 100% rename from database/migrations/20260404113000-create-wms-notification-webhook.js rename to database/migrations/archive/20260404113000-create-wms-notification-webhook.js diff --git a/database/migrations/20260405002000-add-expire-time-to-wms-file.js b/database/migrations/archive/20260405002000-add-expire-time-to-wms-file.js similarity index 100% rename from database/migrations/20260405002000-add-expire-time-to-wms-file.js rename to database/migrations/archive/20260405002000-add-expire-time-to-wms-file.js diff --git a/database/migrations/20260405011000-add-subject-config-to-wms-store.js b/database/migrations/archive/20260405011000-add-subject-config-to-wms-store.js similarity index 100% rename from database/migrations/20260405011000-add-subject-config-to-wms-store.js rename to database/migrations/archive/20260405011000-add-subject-config-to-wms-store.js diff --git a/database/migrations/20260405013000-init-wms-store-subject-config-webhook-limit.js b/database/migrations/archive/20260405013000-init-wms-store-subject-config-webhook-limit.js similarity index 100% rename from database/migrations/20260405013000-init-wms-store-subject-config-webhook-limit.js rename to database/migrations/archive/20260405013000-init-wms-store-subject-config-webhook-limit.js diff --git a/database/migrations/20260405015000-drop-extra-config-from-notification-webhook.js b/database/migrations/archive/20260405015000-drop-extra-config-from-notification-webhook.js similarity index 100% rename from database/migrations/20260405015000-drop-extra-config-from-notification-webhook.js rename to database/migrations/archive/20260405015000-drop-extra-config-from-notification-webhook.js diff --git a/database/migrations/20260405024000-create-wms-notification-send-log.js b/database/migrations/archive/20260405024000-create-wms-notification-send-log.js similarity index 100% rename from database/migrations/20260405024000-create-wms-notification-send-log.js rename to database/migrations/archive/20260405024000-create-wms-notification-send-log.js diff --git a/database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js b/database/migrations/archive/20260407153000-create-wms-store-warehouse-print-quantity-log.js similarity index 100% rename from database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js rename to database/migrations/archive/20260407153000-create-wms-store-warehouse-print-quantity-log.js diff --git a/database/migrations/20260407160000-add-receiving-id-to-wms-storage.js b/database/migrations/archive/20260407160000-add-receiving-id-to-wms-storage.js similarity index 100% rename from database/migrations/20260407160000-add-receiving-id-to-wms-storage.js rename to database/migrations/archive/20260407160000-add-receiving-id-to-wms-storage.js diff --git a/database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js b/database/migrations/archive/20260408100000-add-entry-order-id-to-wms-storage.js similarity index 100% rename from database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js rename to database/migrations/archive/20260408100000-add-entry-order-id-to-wms-storage.js diff --git a/database/migrations/20260408120000-add-callback-url-to-api-app.js b/database/migrations/archive/20260408120000-add-callback-url-to-api-app.js similarity index 100% rename from database/migrations/20260408120000-add-callback-url-to-api-app.js rename to database/migrations/archive/20260408120000-add-callback-url-to-api-app.js diff --git a/database/migrations/20260408140000-create-wms-stock-transaction.js b/database/migrations/archive/20260408140000-create-wms-stock-transaction.js similarity index 100% rename from database/migrations/20260408140000-create-wms-stock-transaction.js rename to database/migrations/archive/20260408140000-create-wms-stock-transaction.js diff --git a/database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js b/database/migrations/archive/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js similarity index 100% rename from database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js rename to database/migrations/archive/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js diff --git a/database/migrations/20260410100000-alter-wms-stock-warehouse-negative-quantity.js b/database/migrations/archive/20260410100000-alter-wms-stock-warehouse-negative-quantity.js similarity index 100% rename from database/migrations/20260410100000-alter-wms-stock-warehouse-negative-quantity.js rename to database/migrations/archive/20260410100000-alter-wms-stock-warehouse-negative-quantity.js diff --git a/database/migrations/20260410120000-add-log-id-to-qimen-log.js b/database/migrations/archive/20260410120000-add-log-id-to-qimen-log.js similarity index 100% rename from database/migrations/20260410120000-add-log-id-to-qimen-log.js rename to database/migrations/archive/20260410120000-add-log-id-to-qimen-log.js diff --git a/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js b/database/migrations/archive/20260410130000-add-audit-status-to-order-delivery-tables.js similarity index 100% rename from database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js rename to database/migrations/archive/20260410130000-add-audit-status-to-order-delivery-tables.js diff --git a/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js b/database/migrations/archive/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js similarity index 100% rename from database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js rename to database/migrations/archive/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js diff --git a/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js b/database/migrations/archive/20260410200000-add-status-columns-to-wms-order-delivery-base.js similarity index 100% rename from database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js rename to database/migrations/archive/20260410200000-add-status-columns-to-wms-order-delivery-base.js diff --git a/database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js b/database/migrations/archive/20260415000000-init-wms-store-subject-config-default-codes.js similarity index 100% rename from database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js rename to database/migrations/archive/20260415000000-init-wms-store-subject-config-default-codes.js diff --git a/database/migrations/20260415172000-create-wms-express-interface.js b/database/migrations/archive/20260415172000-create-wms-express-interface.js similarity index 100% rename from database/migrations/20260415172000-create-wms-express-interface.js rename to database/migrations/archive/20260415172000-create-wms-express-interface.js diff --git a/database/migrations/20260415190000-create-wms-picking.js b/database/migrations/archive/20260415190000-create-wms-picking.js similarity index 100% rename from database/migrations/20260415190000-create-wms-picking.js rename to database/migrations/archive/20260415190000-create-wms-picking.js diff --git a/database/migrations/20260415191000-add-quantity-to-wms-picking.js b/database/migrations/archive/20260415191000-add-quantity-to-wms-picking.js similarity index 100% rename from database/migrations/20260415191000-add-quantity-to-wms-picking.js rename to database/migrations/archive/20260415191000-add-quantity-to-wms-picking.js diff --git a/database/migrations/20260417153000-add-deleted-at-to-wms-express-setting.js b/database/migrations/archive/20260417153000-add-deleted-at-to-wms-express-setting.js similarity index 100% rename from database/migrations/20260417153000-add-deleted-at-to-wms-express-setting.js rename to database/migrations/archive/20260417153000-add-deleted-at-to-wms-express-setting.js diff --git a/database/migrations/20260419102000-add-weight-type-to-order-delivery-tables.js b/database/migrations/archive/20260419102000-add-weight-type-to-order-delivery-tables.js similarity index 100% rename from database/migrations/20260419102000-add-weight-type-to-order-delivery-tables.js rename to database/migrations/archive/20260419102000-add-weight-type-to-order-delivery-tables.js diff --git a/database/migrations/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js b/database/migrations/archive/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js similarity index 100% rename from database/migrations/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js rename to database/migrations/archive/20260420101000-alter-order-flag-to-longtext-on-order-delivery-tables.js diff --git a/database/migrations/20260420112000-add-source-order-codes-to-order-delivery-tables.js b/database/migrations/archive/20260420112000-add-source-order-codes-to-order-delivery-tables.js similarity index 100% rename from database/migrations/20260420112000-add-source-order-codes-to-order-delivery-tables.js rename to database/migrations/archive/20260420112000-add-source-order-codes-to-order-delivery-tables.js diff --git a/docs/order-workbench-list-api.md b/docs/order-workbench-list-api.md index 1c055d5..c6dbf67 100644 --- a/docs/order-workbench-list-api.md +++ b/docs/order-workbench-list-api.md @@ -127,6 +127,7 @@ | items_hash | string | MD5哈希值(32位) | 商品明细哈希 | | items_crc | number | CRC32校验码 | 商品明细校验码 | | wave_id | number | 波次ID | 0 表示未分配 | +| wave_no | string | 波次号 | 空字符串表示未分配 | | post_status | enum | 分配快递号状态机 | padding=处理中,fin=完成,timeout=超时,error=失败,none=未开始 | | storage_status | enum | 分配储位状态机 | padding=处理中,fin=完成,error=失败,none=未开始 | | pick_status | enum | 拣货状态机 | padding=处理中,fin=完成,error=失败,none=未开始 | diff --git a/methods/changes/system.json b/methods/changes/system.json index cf8714f..259f442 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,40 +1,192 @@ [ - { - "version": "2026.04.22-system-02", - "date": "2026-04-22", - "summary": "新增 order.pendingOrder.syncOrderIds:待处理订单同步透传入口", - "methods": [ - "order.pendingOrder.syncOrderIds" - ], - "notes": [ - "新增 order.pendingOrder.syncOrderIds:仅接收 order_ids 并转发到服务层,当前不做业务处理。", - "接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。", - "该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。" - ], - "type": "added" - }, - { - "version": "2026.04.22-system-01", - "date": "2026-04-22", - "summary": "补全订单工作台各模块 detail 方法文档", - "methods": [ - "order.detail", - "order.pendingOrder.detail", - "order.reviewOrder.detail", - "order.expectionOrder.detail", - "order.outboundOrder.detail", - "order.deliveryOrder.detail", - "order.deliveryExpectionOrder.detail", - "order.entrustOrder.detail", - "order.archiveOrder.detail" - ], - "notes": [ - "补全文档:detail 为订单工作台通用详情方法,入参支持 ids/id/order_id/orderId;可选 tableType/tablePosition/type/moduleName,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等。", - "返回包含 order/detail(订单头)、orderItems/items(商品明细)、expresses(运单信息)、waybill_codes(去重运单号数组)。" - ], - "type": "updated" - }, - { + { + "version": "2026.05.05-system-02", + "date": "2026-05-05", + "summary": "order.wave.batchList:新增 where.storage_assignment_status 的过滤语义说明", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where 字段 `storage_assignment_status`:类型 string,可选值:`未分配`、`部分分配`、`已分配`;默认不传:不做分配状态限制。", + "过滤语义:`已分配`:聚合后全部 fin;`部分分配`:不含 error,且既不是全 none,也不是全 fin;`未分配`:全 none 或包含 error(异常并入未分配筛选集合)。", + "说明:返回字段 `storage_assignment_status` 的展示值保持不变;包含 error 时仍可能展示“分配异常”,但 where 的过滤语义把异常算到“未分配”集合,避免把过滤语义与展示值混淆。" + ], + "type": "updated" + }, + { + "version": "2026.05.05-system-01", + "date": "2026-05-05", + "summary": "新增 order.wave.singleOrderFetchList:散单候选分组查询(排除团购命中分组)", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchList:返回按机器结构分组的散单候选列表,接口会排除已达团购阈值(同组订单数量 >= same_order_quantity 或仓库配置 min_group_order_fetch_quantity)的分组,仅返回同组订单数量 < 阈值 的分组(散单候选)。", + "与 order.wave.groupOrderFetchList 的关键差异:groupOrderFetchList 返回满足团购阈值(>=)的分组;singleOrderFetchList 返回未达阈值(<)的散单候选分组。", + "影响范围:订单波次抓取相关前端/调度服务。兼容性:不影响或修改现有 order.wave.groupOrderFetchList,两个接口可并行使用。" + ], + "type": "added" + }, + { + "version": "2026.05.04-system-04", + "date": "2026-05-04", + "summary": "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述", + "methods": [ + "stock.warehouse.checkItemCodeUnique" + ], + "notes": [ + "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述" + ], + "type": "modified" + }, + { + "version": "2026.05.04-system-03", + "date": "2026-05-04", + "summary": "新增订单打印模块:按波次IDs获取打印数据并自动过滤未完全分配波次", + "methods": [ + "order.print.getWavePrintData" + ], + "notes": [ + "按波次IDs获取订单打印数据,内部去重并规范化 wave_ids,自动过滤快递未完全分配的波次;返回通过过滤的波次订单明细,按 wave_no 排序分组,并在 ext 中返回 missing_wave_ids 与 filtered_wave_ids。" + ], + "type": "added" + }, + { + "version": "2026.05.04-system-02", + "date": "2026-05-04", + "summary": "修改 pick.query 入参:order_id -> waybill_code", + "methods": [ + "pick.query" + ], + "notes": [ + "入参从 order_id 改为 waybill_code(快递号),通过快递号查找订单后再查波次拣货信息" + ], + "type": "breaking_change" + }, + { + "version": "2026.05.04-system-01", + "date": "2026-05-04", + "summary": "新增 system method pick.query:按订单查询波次拣货信息", + "methods": [ + "pick.query" + ], + "notes": [ + "按订单查询该订单所属波次的拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。" + ], + "type": "added" + }, + { + "version": "2026.05.03-system-09", + "date": "2026-05-03", + "summary": "新增按 request_id 查询分配状态/结果接口", + "methods": [ + "order.pendingOrder.allocateStorageProgress" + ], + "notes": [ + "新增按 request_id 查询储位分配异步任务状态/结果接口,支持 status:submitted/running/success/failed/not_found;success 返回 result(底层分配结果),failed 返回 error(错误信息);兼容 requestId 参数名。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-07", + "date": "2026-05-03", + "summary": "新增抓取进度查询接口", + "methods": [ + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增按 task_id 查询抓取任务进度的接口 order.wave.fetchTaskProgress,支持返回 status(submitted/running/success/failed/not_found)及进度相关字段:progress_percent、finished_structure_count、total_fetched_quantity、duration_ms、error、update_time 等;同时明确 order.wave.fetch 为异步任务提交接口,客户端可通过 task_id 调用 order.wave.fetchTaskProgress 查询进度和最终结果。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-05", + "date": "2026-05-03", + "summary": "补齐仓库设置模块 setting.warehouse 的 methods 文档", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "补齐仓库配置 methods API 文档" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-04", + "date": "2026-05-03", + "summary": "order.wave:自动加团新增跳过规则并新增批量结束自动加团接口", + "methods": [ + "order.wave.batchAutoGrouping", + "order.wave.batchFinishAutoGrouping" + ], + "notes": [ + "开启自动加团新增“已打印/超最大波次容量”跳过规则并在响应中返回跳过明细;新增批量结束自动加团接口(将 wave_status=0 的波次批量置为 1)" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-03", + "date": "2026-05-03", + "summary": "裁剪 order_list 以轻量化返回", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "移除响应中的 order_list 字段,接口仅返回波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-02", + "date": "2026-05-03", + "summary": "新增 order.wave.batchAutoGrouping:批量改为自动加团中", + "methods": [ + "order.wave.batchAutoGrouping" + ], + "notes": [ + "新增批量改为自动加团中接口及返回字段" + ], + "type": "updated" + }, + { + "version": "2026.04.22-system-02", + "date": "2026-04-22", + "summary": "新增 order.pendingOrder.syncOrderIds:待处理订单同步透传入口", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "新增 order.pendingOrder.syncOrderIds:仅接收 order_ids 并转发到服务层,当前不做业务处理。", + "接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。", + "该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。" + ], + "type": "added" + }, + { + "version": "2026.04.22-system-01", + "date": "2026-04-22", + "summary": "补全订单工作台各模块 detail 方法文档", + "methods": [ + "order.detail", + "order.pendingOrder.detail", + "order.reviewOrder.detail", + "order.expectionOrder.detail", + "order.outboundOrder.detail", + "order.deliveryOrder.detail", + "order.deliveryExpectionOrder.detail", + "order.entrustOrder.detail", + "order.archiveOrder.detail" + ], + "notes": [ + "补全文档:detail 为订单工作台通用详情方法,入参支持 ids/id/order_id/orderId;可选 tableType/tablePosition/type/moduleName,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等。", + "返回包含 order/detail(订单头)、orderItems/items(商品明细)、expresses(运单信息)、waybill_codes(去重运单号数组)。" + ], + "type": "updated" + }, + { "version": "2026.04.19-system-01", "date": "2026-04-19", "summary": "新增方法 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 查询全字段列表并支持缓存", @@ -953,5 +1105,99 @@ "step 由货主策略 need_order_approval 决定(与 createOrder 一致);通过事务保证每个订单的主记录与明细原子写入。" ], "type": "added" + }, + { + "version": "2026.05.01-system-01", + "date": "2026-05-01", + "summary": "新增基础模块 IM 登录码接口文档:index.loginToIm", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "新增 index.loginToIm 文档,入参为空对象({}),依赖当前登录用户上下文生成一次性 code。", + "响应增加 data.code 字段,长度固定 64 位(hex),默认有效期 5 分钟。", + "错误码补充:401(用户未登录)、400(用户信息不完整,缺 employees_id 或 employees_name)。", + "该接口仅做登录码签发,实际换取员工信息由 IM 侧 ssoCodeToId 完成并在成功后使 code 失效。" + ], + "type": "added" + }, + { + "version": "2026.05.01-system-03", + "date": "2026-05-01", + "summary": "扩展 index.loginToIm 返回字段:增加主体/主体类型/头像信息", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "登录码签发接口响应新增 employees_id、employees_name、subject、store_type、avatar 字段。", + "subject 包含 id/name;store_type 严格取自 wms_store.project 字段,不再返回 subject_type 兼容字段。", + "同一批字段会写入 code 缓存,供 IM 侧 ssoCodeToId 换取并在成功后失效。" + ], + "type": "updated" + }, + { + "version": "2026.05.01-system-04", + "date": "2026-05-01", + "summary": "index.loginToIm 与 ssoCodeToId 改为严格字段模式,不再做兼容回退", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "loginToIm 仅读取 ctx.user 标准字段:employees_id、employees_name、store_id、store_name、store_type、avatar。", + "不再兼容 id/real_name/username/company_name/avatar_url 等历史字段。", + "ssoCodeToId 返回值不再使用默认兜底,缺少关键字段时按 code 无效处理。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-01", + "date": "2026-05-03", + "summary": "将 order.wave.fetch 调整为异步任务提交接口,删除同步返回抓取结果字段", + "methods": [ + "order.wave.fetch" + ], + "notes": [ + "接口从同步返回抓取结果改为提交任务并异步处理。", + "移除原方法中 result_list / total_request_quantity / total_fetched_quantity 等同步返回字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-06", + "date": "2026-05-03", + "summary": "order.wave.batchList:新增 where 支持并限制传入字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "batchList 新增 where 支持及白名单过滤;禁止传入 warehouse_id/warehouseId。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-08", + "date": "2026-05-03", + "summary": "order.pendingOrder.allocateStorage 改为异步提交", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "接口变更为异步提交:调用后立即返回 request_id,后端异步执行储位分配;接口不再在响应中同步返回分配明细(如 requested_order_ids、allocated_order_ids 等)。客户端可后续通过任务 ID / 查询链路或事件获取最终分配结果。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-10", + "date": "2026-05-03", + "summary": "新增订单批量移出波次接口", + "methods": [ + "order.wave.batchRemoveOrders" + ], + "notes": [ + "按订单ID批量移出波次;仅处理待处理订单表中非待审核订单(step in [1,2,3])。", + "操作在单事务内完成:清空订单的 wave_id/wave_no,并回写 wms_wave_batch 统计(重算 total_orders;当波次被清空时将 wave_status 置为 -1)。", + "仓库上下文来自当前登录用户(ctx.user.store_id)。" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index fc2f66b..5e8628c 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "2026.04.21-system-04", - "updatedAt": "2026-04-21", + "version": "2026.05.03-system-10", + "updatedAt": "2026-05-03", "headers": [ { "name": "platform", @@ -996,6 +996,47 @@ "description": "查询失败" } ] + }, + { + "method": "order.queryOrderLogList", + "description": "按 order_id 查询订单操作日志,返回全量日志(不分页)。接口按当前登录用户的仓库上下文过滤(method 层从 ctx.user.store_id 获取 warehouse_id),以防跨仓越界。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id / id / orderId", + "type": "string|number", + "required": true, + "source": "body", + "description": "订单ID;支持别名 id 与 orderId,接口会兼容解析。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "日志列表(全量返回,无分页)。每项字段与 stock.warehouse.queryStockLogs 保持一致,典型字段包括 id、action、message、actor、created_at、warehouse_id 等。" + } + ], + "errors": [ + { + "code": "400", + "description": "order_id 为空或格式不合法" + }, + { + "code": "500", + "description": "内部错误" + } + ] } ] }, @@ -1626,7 +1667,7 @@ }, { "method": "order.pendingOrder.allocateStorage", - "description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。只接受订单相关入参,不再接受 warehouse_id / warehouseId,仓库上下文来自当前登录用户。", + "description": "按订单批量分配储位(迁移自 order.storageAllocation.allocateStorage)。这是一个异步提交接口:调用后接口立即返回受理信息(包含 request_id),后端异步执行实际的储位分配与锁定操作;仓库上下文由当前登录用户提供(ctx.user.store_id)。接口不会在同步响应中返回分配明细(如 requested_order_ids、allocated_order_ids 等),客户端可通过请求 ID 或事件/查询链路获取最终结果。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1655,102 +1696,22 @@ ], "response": [ { - "name": "flag", + "name": "request_id", "type": "string", "required": true, - "description": "全局调用结果标识,成功为 success" + "description": "请求 ID(后端生成的唯一标识),用于查询任务状态或结果" }, { - "name": "code", + "name": "warehouse_id", "type": "number", "required": true, - "description": "业务状态码,200 表示成功" + "description": "生效的仓库 ID(来自当前用户 store_id)" }, { "name": "message", "type": "string", "required": true, - "description": "提示信息,成功或部分成功时给出人类可读的摘要。" - }, - { - "name": "data", - "type": "object", - "required": true, - "description": "分配结果汇总对象,包含以下字段", - "children": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "description": "生效的仓库 ID" - }, - { - "name": "allow_storage_location", - "type": "boolean", - "required": true, - "description": "最终使用的存储位允许标识" - }, - { - "name": "requested_order_ids", - "type": "array", - "required": true, - "description": "请求中传入的订单 ID 列表(规范化后)" - }, - { - "name": "pending_order_ids", - "type": "array", - "required": true, - "description": "实际需要分配的订单 ID 列表(已过滤已完成分配的订单)" - }, - { - "name": "allocated_order_ids", - "type": "array", - "required": true, - "description": "已成功分配的订单 ID 列表" - }, - { - "name": "shortage_order_ids", - "type": "array", - "required": true, - "description": "因库存不足而未完全分配的订单 ID 列表" - }, - { - "name": "skipped_orders", - "type": "array", - "required": true, - "description": "被跳过的订单数组(每项包含 order_id, status, skipped_reason)" - }, - { - "name": "orders", - "type": "array", - "required": true, - "description": "每个订单的分配明细与状态(含 storage_status, allocated_quantity, shortage_message 等)" - }, - { - "name": "picking_count", - "type": "number", - "required": true, - "description": "本次生成的 wms_picking 行数" - }, - { - "name": "stock_lock_summary", - "type": "array", - "required": true, - "description": "按 stock_id 汇总的锁库存数量数组({stock_id, locked_quantity})" - }, - { - "name": "storage_lock_summary", - "type": "array", - "required": true, - "description": "按 storage_id 汇总的锁库位数量数组({storage_id, locked_quantity})" - }, - { - "name": "shortage_messages", - "type": "array", - "required": true, - "description": "订单级别的库存不足提示文本数组" - } - ] + "description": "受理提示信息,通常为 '请求已受理,后端异步处理中' 或错误说明" } ], "errors": [ @@ -1772,6 +1733,83 @@ } ] }, + { + "method": "order.pendingOrder.allocateStorageProgress", + "description": "按 request_id 查询储位分配异步任务状态/结果(由 allocateStorage 提交)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "request_id / requestId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务请求 ID,兼容字段 requestId" + } + ], + "response": [ + { + "name": "request_id", + "type": "string", + "required": true, + "description": "请求 ID(后端生成的唯一标识)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "成功时返回底层分配结果,结构视实现而定" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "失败时返回的错误信息" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "关联仓库 ID(若任务关联仓库时返回)" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "最近一次状态更新时间,ISO8601 字符串" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "额外提示信息" + } + ], + "errors": [ + { + "code": 400, + "message": "request_id 为空或格式不合法" + }, + { + "code": 500, + "message": "内部错误" + } + ] + }, { "method": "order.pendingOrder.syncOrderIds", "description": "同步待处理订单入口,仅接收 order_ids 并转发到服务层,当前不做业务处理。", @@ -2450,6 +2488,1341 @@ } ] }, + { + "groupName": "订单波次模块", + "module": "order.wave", + "list": [ + { + "method": "order.wave.groupOrderFetchList", + "description": "按机器结构分组的可抓取列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。", + "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": "distinguish_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否区分快递(影响分组粒度)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(仅作为筛选条件)" + }, + { + "name": "same_order_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "最小同组订单数量阈值(>=)。若显式传入有效数值则按传入值使用;未传入时使用仓库配置 min_group_order_fetch_quantity(默认 13)。" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(模糊匹配)" + }, + { + "name": "include_sku", + "type": "string", + "required": false, + "source": "body", + "description": "仅保留包含该 SKU 的分组(页内过滤)" + }, + { + "name": "return_order_ids", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否在结果中返回组内订单ID列表" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "分组列表,items 示例见实现:包含 item_detail_machine/item_snapshot/group_count 等字段" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少仓库上下文或参数格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.wave.singleOrderFetchList", + "description": "按机器结构分组的散单候选列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。与 order.wave.groupOrderFetchList 不同:groupOrderFetchList 返回满足同组订单数量 >= same_order_quantity(或仓库配置 min_group_order_fetch_quantity)的团购命中分组;singleOrderFetchList 则排除这些团购命中分组,仅返回同组订单数量小于该阈值的散单候选分组(即 < same_order_quantity)。", + "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": "distinguish_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否区分快递(影响分组粒度)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID(仅作为筛选条件)" + }, + { + "name": "same_order_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "最小同组订单数量阈值(用于判定团购命中);本接口返回同组订单数量小于该阈值的分组。若显式传入有效数值则按传入值使用;未传入时使用仓库配置 min_group_order_fetch_quantity(默认 13)。" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(模糊匹配)" + }, + { + "name": "include_sku", + "type": "string", + "required": false, + "source": "body", + "description": "仅保留包含该 SKU 的分组(页内过滤)" + }, + { + "name": "return_order_ids", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否在结果中返回组内订单ID列表" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单候选分组列表,items 示例见实现:包含 item_detail_machine/item_snapshot/group_count 等字段;返回的 group_count 均小于 same_order_quantity(或仓库配置的 min_group_order_fetch_quantity)。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少仓库上下文或参数格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.wave.batchList", + "description": "波次列表查询。仅使用当前登录操作者的仓库ID作为查询约束(禁止传入 warehouse_id / warehouseId)。支持通过白名单字段进行过滤(通过 where 对象传入),接口对 wave_status 固定叠加查询状态 0/1,无需客户端传入。列表按订单数量从大到小排序,并附带波次基础信息与分配状态汇总。", + "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": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.wave.batchCancel", + "description": "提交批量解除波次异步任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理波次并执行解除操作;可通过 order.wave.batchCancelTaskProgress 查询进度与结果。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchCancelTaskProgress", + "description": "查询批量解除波次任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。响应包含 state、progress_percent、processed_wave_count、total_wave_count;当 state 为 success/failed 时返回额外字段说明。", + "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(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "processed_wave_count", + "type": "number", + "required": false, + "description": "已处理的波次数量" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "总波次数量" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息(仅在 state=failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码(仅在 state=failed 时返回)" + }, + { + "name": "result", + "type": "object", + "required": false, + "description": "成功时返回的汇总结果(仅在 state=success 时返回),例如 { \"processed_wave_count\": number, \"canceled_wave_count\": number }" + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 参数不能为空" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchAllocateExpress", + "description": "提交批次分配快递号任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到快递号分配流水线。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchAllocateExpressTaskProgress", + "description": "查询批次分配快递号任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。", + "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(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "任务关联仓库ID" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "波次数量" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "参与分配的订单数量" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数量" + }, + { + "name": "success_order_count", + "type": "number", + "required": false, + "description": "成功提交分配的订单数量" + }, + { + "name": "failed_order_count", + "type": "number", + "required": false, + "description": "提交分配失败的订单数量" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码" + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 参数不能为空" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchRemoveExceptionOrders", + "description": "提交批次移除异常订单任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取异常订单并移出波次。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchRemoveExceptionOrdersTaskProgress", + "description": "查询批次移除异常订单任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。", + "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(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "任务关联仓库ID" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "波次数量" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "参与处理的订单数量" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数量" + }, + { + "name": "removed_order_count", + "type": "number", + "required": false, + "description": "已成功移出波次的订单数量" + }, + { + "name": "failed_order_count", + "type": "number", + "required": false, + "description": "处理失败的订单数量" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码" + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 参数不能为空" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchAllocateStorage", + "description": "提交批次分配储位任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理订单并提交到储位分配流水线。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "wave_ids / waveIds / ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID列表;支持数组、逗号分隔字符串或单个ID" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "可选外部任务ID,用于幂等提交" + } + ], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于查询任务进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "当前仓库ID" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO8601)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理提示信息" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchAllocateStorageTaskProgress", + "description": "查询批次分配储位任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。", + "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(后端生成或提交时传入)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "任务关联仓库ID" + }, + { + "name": "total_wave_count", + "type": "number", + "required": false, + "description": "波次数量" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "参与分配的订单数量" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数量" + }, + { + "name": "success_order_count", + "type": "number", + "required": false, + "description": "成功提交分配的订单数量" + }, + { + "name": "failed_order_count", + "type": "number", + "required": false, + "description": "提交分配失败的订单数量" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "失败时的错误信息" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "失败时的错误码" + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 参数不能为空" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, + { + "method": "order.wave.fetch", + "description": "提交波次抓取任务:该接口为异步任务提交接口,立即返回任务已受理的信息,后端异步执行实际抓取,不在接口同步返回抓取结果。客户端可通过任务 ID 或调用 order.wave.fetchTaskProgress 查询任务状态与进度。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "structure_list", + "type": "array", + "required": true, + "source": "body", + "description": "结构请求数组;每项必须包含 item_detail_machine(由 buildMachineStructureToken 生成的结构标识),可选 quantity(未传入时使用仓库默认或全局默认)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(后端生成的唯一标识,用于查询任务状态或结果)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "生效的仓库 ID" + }, + { + "name": "structure_count", + "type": "number", + "required": true, + "description": "本次入参的结构数量(structure_list 长度)" + }, + { + "name": "default_quantity", + "type": "number", + "required": true, + "description": "仓库默认抓取数量或全局默认值" + }, + { + "name": "auto_fetch_disabled_marker", + "type": "string", + "required": true, + "description": "手动抓取标记;值为 'wave_manual_fetch' 表示手动抓取" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "受理信息提示,通常为 '任务已提交,后端异步处理中' 或失败/错误说明" + } + ], + "errors": [ + { + "code": 400, + "message": "structure_list 必须是非空数组或结构项参数不合法" + }, + { + "code": 500, + "message": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.fetchTaskProgress", + "description": "查询波次抓取任务进度:按 task_id 查询任务状态与进度;兼容 taskId 参数名。", + "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,可从 order.wave.fetch 的返回值中获取" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态枚举:submitted(已受理)/ running(进行中)/ success(成功)/ failed(失败)/ not_found(未找到)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "生效的仓库 ID(若任务关联仓库时返回)" + }, + { + "name": "structure_count", + "type": "number", + "required": false, + "description": "本次任务的结构数量(structure_list 长度)" + }, + { + "name": "finished_structure_count", + "type": "number", + "required": false, + "description": "已完成抓取的结构数量" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100,可能为小数)" + }, + { + "name": "total_fetched_quantity", + "type": "number", + "required": false, + "description": "已抓取的总件数" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务已运行时长,毫秒级" + }, + { + "name": "error", + "type": "string", + "required": false, + "description": "错误信息,仅当 status=failed 时返回" + }, + { + "name": "update_time", + "type": "string", + "required": false, + "description": "最近一次状态更新时间,ISO8601 字符串" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "额外提示信息" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 为空或格式不合法" + }, + { + "code": 500, + "message": "内部错误" + } + ] + }, + { + "method": "order.wave.batchAutoGrouping", + "description": "批量将波次状态修改为 0(自动加团中),仅作用当前登录仓库命中的波次。限制条件:\n- 跳过已打印及之后状态的波次(wave_status >= 2);\n- 跳过 total_orders >= 仓库配置 max_wave_quantity 的波次。被跳过的波次不会被修改为自动加团中。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID 列表;支持数组、逗号分隔字符串或单个ID" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "description": "归一化后的请求ID" + }, + { + "name": "affected_wave_ids", + "type": "array", + "description": "实际命中的波次ID" + }, + { + "name": "updated_wave_count", + "type": "number", + "description": "实际更新数量" + }, + { + "name": "skipped_wave_ids", + "type": "array", + "description": "被跳过的波次ID数组(不修改状态)" + }, + { + "name": "skipped_wave_count", + "type": "number", + "description": "被跳过的波次数量" + }, + { + "name": "skipped_details", + "type": "array", + "description": "被跳过的波次明细數組,元素包含 wave_id 与 reason,reason 枚举 printed_or_after_printed / reach_max_wave_quantity", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次 ID" + }, + { + "name": "reason", + "type": "string", + "description": "跳过原因,枚举: printed_or_after_printed / reach_max_wave_quantity" + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "批量修改波次状态失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchFinishAutoGrouping", + "description": "批量结束自动加团,将当前仓库命中且 wave_status=0 的波次改为 1(已就绪)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "波次ID 列表;支持数组、逗号分隔字符串或单个ID" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "description": "归一化后的请求ID" + }, + { + "name": "affected_wave_ids", + "type": "array", + "description": "实际命中的波次ID" + }, + { + "name": "updated_wave_ids", + "type": "array", + "description": "实际更新为已就绪的波次ID" + }, + { + "name": "updated_wave_count", + "type": "number", + "description": "实际更新数量" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "400", + "description": "ids 参数不能为空或格式错误" + }, + { + "code": "500", + "description": "批量结束自动加团失败或内部错误" + } + ] + }, + { + "method": "order.wave.batchRemoveOrders", + "description": "按订单ID批量移出波次;仅处理当前仓库的待处理订单表中非待审核订单(step in [1,2,3])。操作会清空订单的 wave_id/wave_no,并在同一事务内回写 wms_wave_batch 表:重算 total_orders,若波次被清空则将 wave_status 置为 -1。仓库上下文来自当前登录用户(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids / order_ids / orderIds / order_id / orderId / id", + "type": "array|string|number", + "required": true, + "source": "body", + "description": "订单 ID 列表;支持数组、逗号分隔字符串或单个 ID,以上别名均可用(ids、order_ids、orderIds、order_id、orderId、id)" + } + ], + "response": [ + { + "name": "ids", + "type": "array", + "required": true, + "description": "归一化后的请求 ID 列表" + }, + { + "name": "removed_order_ids", + "type": "array", + "required": true, + "description": "实际被移出波次的订单 ID 列表" + }, + { + "name": "removed_order_count", + "type": "number", + "required": true, + "description": "被移出波次的订单数量" + }, + { + "name": "affected_wave_ids", + "type": "array", + "required": true, + "description": "本次操作涉及的波次 ID 列表" + }, + { + "name": "updated_wave_ids", + "type": "array", + "required": true, + "description": "实际更新了 total_orders 的波次 ID 列表" + }, + { + "name": "emptied_wave_ids", + "type": "array", + "required": true, + "description": "被清空且已置为 wave_status=-1 的波次 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "message": "缺少仓库上下文(用户登录信息无 store_id)或 ids 参数为空/格式错误" + }, + { + "code": "500", + "message": "内部错误" + } + ] + } + ] + }, { "groupName": "订单待出库模块", "module": "order.outboundOrder", @@ -3429,6 +4802,181 @@ } ] }, + { + "groupName": "订单打印模块", + "module": "order.print", + "list": [ + { + "method": "order.print.getWavePrintData", + "description": "按波次 IDs 获取订单打印数据,自动过滤快递未完全分配的波次,返回通过过滤的波次订单明细,按波次号分组", + "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" + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "source": "body", + "description": "波次ID列表(支持数字或字符串,内部自动去重与归一化)" + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "description": "汇总信息", + "children": [ + { + "name": "total_waves", + "type": "number", + "description": "通过过滤的波次总数" + }, + { + "name": "total_orders", + "type": "number", + "description": "通过过滤的波次下订单总数" + } + ] + }, + { + "name": "wave_list", + "type": "array", + "description": "波次列表(按 wave_no 排序)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "order_count", + "type": "number", + "description": "该波次订单数" + }, + { + "name": "orders", + "type": "array", + "description": "订单明细列表(含 order_id、order_no、收件信息等字段)", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "description": "订单号(delivery_order_code 或 source_order_codes)" + }, + { + "name": "receiver", + "type": "object", + "description": "收件信息", + "children": [ + { "name": "name", "type": "string", "description": "收件人姓名" }, + { "name": "mobile", "type": "string", "description": "手机号" }, + { "name": "tel", "type": "string", "description": "电话" }, + { "name": "province", "type": "string", "description": "省" }, + { "name": "city", "type": "string", "description": "市" }, + { "name": "area", "type": "string", "description": "区/县" }, + { "name": "town", "type": "string", "description": "镇/街道" }, + { "name": "detail_address", "type": "string", "description": "详细地址" } + ] + }, + { + "name": "channel", + "type": "object", + "description": "渠道信息", + "children": [ + { "name": "sys_platform_code", "type": "string", "description": "平台编码" }, + { "name": "sys_platform_name", "type": "string", "description": "平台名称" }, + { "name": "logistics_name", "type": "string", "description": "快递名称" } + ] + }, + { + "name": "status", + "type": "object", + "description": "订单状态简要", + "children": [ + { "name": "order_status", "type": "string", "description": "订单状态" }, + { "name": "outbound_status", "type": "string", "description": "出库状态" }, + { "name": "print_status", "type": "string", "description": "打印状态" } + ] + }, + { + "name": "metrics", + "type": "object", + "description": "数量度量", + "children": [ + { "name": "items_count", "type": "number", "description": "商品种类数" }, + { "name": "items_total", "type": "number", "description": "商品总件数" }, + { "name": "items_weight", "type": "number", "description": "重量" } + ] + }, + { + "name": "times", + "type": "object", + "description": "时间字段", + "children": [ + { "name": "create_at", "type": "string", "description": "创建时间" }, + { "name": "pay_time", "type": "string", "description": "支付时间" } + ] + } + ] + } + ] + }, + { + "name": "ext", + "type": "object", + "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", + "description": "warehouse_id 或 wave_ids 缺失或格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, { "groupName": "打印模块", "module": "print", @@ -4044,6 +5592,201 @@ } ] }, + { + "groupName": "仓库设置模块", + "module": "setting.warehouse", + "list": [ + { + "method": "setting.warehouse.getSettings", + "description": "获取当前登录仓库的 subject_config", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "subject_config", + "type": "object", + "description": "仓库的 subject_config 配置对象" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库" + }, + { + "code": "404", + "description": "仓库不存在" + }, + { + "code": "500", + "description": "获取失败" + } + ] + }, + { + "method": "setting.warehouse.getFieldMeta", + "description": "获取仓库设置字段元信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "description": "字段元信息数组", + "children": [ + { + "name": "key", + "type": "string", + "description": "字段 key" + }, + { + "name": "name", + "type": "string", + "description": "字段名称" + }, + { + "name": "type", + "type": "string", + "description": "字段类型" + }, + { + "name": "default", + "type": "any", + "description": "默认值(按字段类型返回)" + }, + { + "name": "required", + "type": "boolean", + "description": "是否必填" + }, + { + "name": "description", + "type": "string", + "description": "字段描述" + }, + { + "name": "options", + "type": "array", + "description": "可选项(仅当 type 为 select/enum 时返回)" + }, + { + "name": "min", + "type": "number", + "description": "数值型最小值(可选)" + }, + { + "name": "max", + "type": "number", + "description": "数值型最大值(可选)" + }, + { + "name": "maxLength", + "type": "number", + "description": "字符串最大长度(可选)" + } + ] + } + ], + "errors": [ + { + "code": "500", + "description": "获取失败" + } + ] + }, + { + "method": "setting.warehouse.saveSettings", + "description": "修改仓库设置并清理指定仓库缓存", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "subject_config", + "type": "object", + "required": true, + "source": "body", + "description": "仓库的 subject_config 对象" + }, + { + "name": "cache_warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "需清理缓存的仓库 ID(下划线命名兼容)" + }, + { + "name": "cacheWarehouseId", + "type": "number", + "required": false, + "source": "body", + "description": "需清理缓存的仓库 ID(驼峰命名兼容)" + } + ], + "response": [ + { + "name": "warehouse_id", + "type": "number", + "description": "生效的仓库 ID" + }, + { + "name": "subject_config", + "type": "object", + "description": "保存后的 subject_config" + }, + { + "name": "cache_cleared_warehouse_id", + "type": "number", + "description": "被清理缓存的仓库 ID(若未清理则为 null)" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库/参数不合法" + }, + { + "code": "404", + "description": "仓库不存在" + }, + { + "code": "500", + "description": "保存失败" + } + ] + } + ] + }, { "groupName": "平台编码管理模块", "module": "setting.platform", @@ -5925,6 +7668,62 @@ "response": [], "errors": [] }, + { + "method": "stock.warehouse.getStockDetail", + "description": "按库位/批次维度查询商品库存分布", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,包含 page/pageSize" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否按批次返回明细;true 返回每条明细,false 按库位合并" + } + ], + "response": [ + { + "name": "stockItem", + "type": "object", + "description": "商品概要,包含 id、item_code、item_name、sku_property、stock_unit、quantity、locked_quantity 等" + }, + { + "name": "storageList", + "type": "array", + "description": "库存明细数组;group_by_batch=true 返回 wms_storage 明细(含 batch_no、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no 等),group_by_batch=false 时按库位合并,批次相关字段为 null" + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,包含 page、pageSize、total" + } + ], + "errors": [] + }, { "method": "stock.warehouse.saveWarehouseStock", "description": "更新仓库商品资料", @@ -6046,7 +7845,7 @@ }, { "method": "stock.warehouse.checkItemCodeUnique", - "description": "校验商品编码在货主维度唯一性", + "description": "检测商品编码唯一性。在同一仓库和货主下,排除商品自身后,判断商品编码是否已存在于未删除商品中。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -6058,29 +7857,67 @@ } ], "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID;默认使用当前登录主体/仓库上下文(ctx.user.store_id)" + }, { "name": "item_code", "type": "string", "required": true, "source": "body", - "description": "item_code 参数" + "description": "要检测的商品编码" }, { - "name": "store_id", + "name": "item_id", "type": "number", - "required": true, + "required": false, "source": "body", - "description": "store_id 参数" + "description": "当前商品ID(编辑场景用,排除自身);兼容字段名 id" }, { "name": "id", "type": "number", "required": false, "source": "body", - "description": "id 参数" + "description": "兼容字段 id" + }, + { + "name": "owner_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(对应表字段 store_id);兼容字段名 store_id" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "兼容字段 store_id" + } + ], + "response": [ + { + "name": "unique", + "type": "boolean", + "description": "true 表示编码唯一,false 表示已存在重复" + }, + { + "name": "isUnique", + "type": "boolean", + "description": "同 unique(兼容旧字段名)" + }, + { + "name": "message", + "type": "string", + "description": "重复时返回 '商品编码已存在',唯一时不返回该字段", + "required": false } ], - "response": [], "errors": [] }, { @@ -6529,17 +8366,17 @@ "description": "本次返回的记录条数(≤50)" } ], - "errors": [ - { - "code": 0, - "message": "搜索失败,请稍后重试", - "description": "服务端查询异常时返回" - } - ] - }, + "errors": [] + } + ] + }, + { + "groupName": "拣货模块", + "module": "pick", + "list": [ { - "method": "stock.warehouse.getStockDetail", - "description": "查询商品的库存明细,返回 wms_storage 表的数据(按库位/批次维度展示库存分布)", + "method": "pick.query", + "description": "按订单查询波次拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -6552,90 +8389,98 @@ ], "params": [ { - "name": "stock_id", - "type": "number", + "name": "waybill_code", + "type": "string", "required": true, "source": "body", - "description": "商品库存ID(stock_warehouse.id)" + "description": "快递号/运单号,必填。" }, { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,含 page(页码,默认1)和 pageSize(每页条数,默认20)" - }, - { - "name": "group_by_batch", + "name": "full_display", "type": "boolean", "required": false, "source": "body", - "description": "是否区分批次。false(默认)时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时按原逻辑返回每条明细" + "description": "是否完整显示拣货明细;默认 false。true 返回全部拣货明细,false 仅返回未完成的(inspection_status != 'fin')。" } ], "response": [ { - "name": "stockItem", - "type": "object", - "description": "商品概要信息,含 id, item_code, item_name, sku_property, stock_unit, quantity, locked_quantity" + "name": "order_id", + "type": "string|number", + "description": "订单 ID" }, { - "name": "storageList", + "name": "wave_id", + "type": "number", + "description": "波次 ID(若订单未关联波次则为空)" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次编号(若订单未关联波次则为空)" + }, + { + "name": "full_display", + "type": "boolean", + "description": "是否以完整明细展示(等同于请求中的 full/full_display/is_full)" + }, + { + "name": "summary", + "type": "object", + "description": "汇总信息", + "children": [ + { + "name": "total_count", + "type": "number", + "description": "明细总行数" + }, + { + "name": "pending_review_count", + "type": "number", + "description": "待复核行数" + }, + { + "name": "reviewed_count", + "type": "number", + "description": "已复核行数" + }, + { + "name": "quantity_total", + "type": "number", + "description": "明细总件数" + }, + { + "name": "display_count", + "type": "number", + "description": "展示行数(受 full 参数影响)" + }, + { + "name": "display_quantity_total", + "type": "number", + "description": "展示的总件数(受 full 参数影响)" + } + ] + }, + { + "name": "list", "type": "array", - "description": "库存明细数组,每条含 id, space_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no, created_at,关联 space 对象(id, space_code, custom_name)。当 group_by_batch=false 时,批次相关字段为 null" - }, - { - "name": "pagination", - "type": "object", - "description": "分页信息,含 page, pageSize, total" + "description": "拣货明细列表(根据 full 参数返回全量或仅未复核明细),每项为明细对象,字段视实现而定。" } ], "errors": [ { - "code": 0, - "message": "参数 stock_id 不能为空" + "code": "400", + "description": "order_id 为空或订单无波次号" }, { - "code": 0, - "message": "商品不存在或不属于当前仓库" + "code": "404", + "description": "订单不存在" }, { - "code": 0, - "message": "查询库存明细失败,请稍后重试" + "code": "500", + "description": "内部错误" } ] - }, - { - "method": "stock.stockWarehouse", - "description": "仓库商品列表查询兼容入口(等同于 stock.warehouse.list)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "筛选条件,写法与 stock.warehouse.list 一致" - } - ], - "response": [], - "errors": [] } ] }, @@ -8695,7 +10540,7 @@ "list": [ { "method": "store.createStore", - "description": "store.createStore 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB", + "description": "store.createStore 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8734,6 +10579,20 @@ "required": false, "source": "body.subject_config", "description": "默认平台编码,缺省为 TB" + }, + { + "name": "subject_config.group_wave_prefix", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "团购波次前缀,最多 5 个字符,默认 B" + }, + { + "name": "subject_config.min_group_order_fetch_quantity", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "最小团购订单抓取数量,默认 13" } ], "response": [], @@ -8741,7 +10600,7 @@ }, { "method": "store.createWarehouse", - "description": "store.createWarehouse 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB", + "description": "store.createWarehouse 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB、group_wave_prefix=B、min_group_order_fetch_quantity=13", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8780,6 +10639,20 @@ "required": false, "source": "body.subject_config", "description": "默认平台编码,缺省为 TB" + }, + { + "name": "subject_config.group_wave_prefix", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "团购波次前缀,最多 5 个字符,默认 B" + }, + { + "name": "subject_config.min_group_order_fetch_quantity", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "最小团购订单抓取数量,默认 13" } ], "response": [], diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress index 7e7fd11..9bf06db 100644 --- a/runtime/file-writer/qimen-logs/.consume-progress +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -3,5 +3,5 @@ "offset": 18973, "processedCount": 7, "completedAt": "2026-04-27T13:30:41.800Z", - "updatedAt": "2026-04-30T11:15:00.002Z" + "updatedAt": "2026-05-05T17:32:47.514Z" } diff --git a/runtime/file-writer/qimen-logs/.consume-progress.31652.1777995764573.tmp b/runtime/file-writer/qimen-logs/.consume-progress.31652.1777995764573.tmp new file mode 100644 index 0000000..ac0b700 --- /dev/null +++ b/runtime/file-writer/qimen-logs/.consume-progress.31652.1777995764573.tmp @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\27\\qimen-logs-MINGREN-worker-p17872-0001.log", + "offset": 18973, + "processedCount": 7, + "completedAt": "2026-04-27T13:30:41.800Z", + "updatedAt": "2026-05-05T15:42:44.573Z" +} diff --git a/test/app/controller/system.storage.transaction.test.js b/test/app/controller/system.storage.transaction.test.js index e7bfa91..2a66b7b 100644 --- a/test/app/controller/system.storage.transaction.test.js +++ b/test/app/controller/system.storage.transaction.test.js @@ -247,7 +247,7 @@ describe('test/app/controller/system.storage.transaction.test.js', () => { } await completeReceiving(authToken, receivingId); - await reviewReceiving(authToken, receivingId); + await reviewReceiving(authToken, receivingId); // 记录入库前的 transaction 最大 ID,用于过滤 const [ beforeRows ] = await sequelize.query( diff --git a/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js b/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js index 0b89523..35b8d4c 100644 --- a/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js +++ b/test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js @@ -9,11 +9,14 @@ const ExpressService = require('../../../../../app/service/systems/express'); /** * 创建待处理订单分配快递号的测试上下文。 * - * @param options + * @param {Object} [options={}] 测试桩配置。 * @return {{ ctx: Object, pendingService: PendingOrderService, expressService: ExpressService }} 测试上下文。 */ function createAllocateExpressHarness(options = {}) { const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) ? options.orderDeliveryRows : []; + const calls = { + operationLogs: [], + }; const ctx = { app: { Sequelize, @@ -43,6 +46,16 @@ function createAllocateExpressHarness(options = {}) { ctx.service = { systems: { express: null, + operationLog: { + async createOperationLogs(payloads = []) { + calls.operationLogs.push(...payloads); + return payloads; + }, + async createOperationLog(payload) { + calls.operationLogs.push(payload); + return payload; + }, + }, }, }; @@ -52,6 +65,7 @@ function createAllocateExpressHarness(options = {}) { return { ctx, + calls, pendingService, expressService, }; @@ -59,7 +73,7 @@ function createAllocateExpressHarness(options = {}) { describe('test/app/service/systemMethods/order/pendingOrder.allocateExpressCode.test.js', () => { it('should pass the order array directly into createWaybillCodePipeline and keep array business_key intact', async () => { - const { pendingService, expressService } = createAllocateExpressHarness(); + const { pendingService, expressService, calls } = createAllocateExpressHarness(); const receivedOrders = []; expressService.createWaybillCodePipeline = async orders => { @@ -96,6 +110,7 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateExpressCode. assert.equal(result.flag, 'success'); assert.equal(result.message, 'ok'); assert.equal(result.code, 1); + assert.equal(calls.operationLogs.length, 0); assert.deepEqual(result.waybill_codes, [ 'WB-001' ]); assert.deepEqual(result.orders, [ { @@ -123,13 +138,18 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateExpressCode. }, ], }); - const createWaybillCodeCalls = []; + const createWaybillCodePipelineCalls = []; - expressService.createWaybillCode = async batch => { - createWaybillCodeCalls.push(batch); + expressService.createWaybillCodePipeline = async orders => { + createWaybillCodePipelineCalls.push(orders); return { - orders: batch, + orders: orders.filter(order => order && Number(order.order_id) > 0), waybill_codes: [], + skippedOrders: [ + { + reason: '订单数据无效', + }, + ], }; }; @@ -145,15 +165,7 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateExpressCode. ], }); - assert.equal(createWaybillCodeCalls.length, 1); - assert.deepEqual(createWaybillCodeCalls[0], [ - { - order_id: 102, - business_key: 9902, - sys_platform_code: 'TAOBAO', - logistics_code: 'STO', - }, - ]); + assert.equal(createWaybillCodePipelineCalls.length, 1); assert.equal(result.skippedOrders.length, 1); assert.equal(result.skippedOrders[0].reason, '订单数据无效'); assert.equal(result.orders.length, 1); @@ -168,4 +180,29 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateExpressCode. /仅支持订单对象数组/ ); }); + + it('should only write failure logs when allocate pipeline throws', async () => { + const { pendingService, expressService, calls } = createAllocateExpressHarness(); + + expressService.createWaybillCodePipeline = async () => { + throw new Error('平台接口异常'); + }; + + await assert.rejects( + async () => await pendingService.allocateExpressCode({ + orders: [ + { order_id: 201, business_key: 9901 }, + { order_id: 202, business_key: 9902 }, + ], + }), + /平台接口异常/ + ); + + assert.equal(calls.operationLogs.length, 2); + assert.equal(calls.operationLogs[0].operationCode, 'ORDER_EXPRESS_ALLOCATE_FAILED'); + assert.equal(calls.operationLogs[0].extras.message, '分配快递失败:平台接口异常'); + assert.equal(calls.operationLogs[0].operator.id, null); + assert.equal(calls.operationLogs[0].operator.name, 'system'); + assert.equal(calls.operationLogs[1].businessId, '202'); + }); }); diff --git a/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js b/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js index 449c8e0..382030c 100644 --- a/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js +++ b/test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js @@ -7,15 +7,28 @@ const PendingOrderService = require('../../../../../app/service/systemMethods/or /** * 创建待处理订单储位分配系统方法测试上下文。 * - * @return {{ ctx: Object, capture: Object, service: PendingOrderService }} 测试上下文。 + * @param {Object} options 可选覆盖项。 + * @param {Function} options.allocateStorageImpl 自定义储位分配实现。 + * @return {{ ctx: Object, capture: Object, cacheStore: Map, service: PendingOrderService }} 测试上下文。 */ -function createHarness() { +function createHarness(options = {}) { const capture = { request: null, }; + const cacheStore = new Map(); + const allocateStorageImpl = typeof options.allocateStorageImpl === 'function' + ? options.allocateStorageImpl + : null; const ctx = { - app: {}, + app: { + async getCacheAsync(cacheKey) { + return cacheStore.get(cacheKey); + }, + async setCacheAsync(cacheKey, value) { + cacheStore.set(cacheKey, value); + }, + }, user: { store_id: 100000, }, @@ -24,6 +37,9 @@ function createHarness() { orderStorageAllocation: { async allocateStorage(request) { capture.request = request; + if (allocateStorageImpl) { + return await allocateStorageImpl(request, capture); + } return { code: 200, message: '储位分配完成', @@ -60,12 +76,13 @@ function createHarness() { return { ctx, capture, + cacheStore, service: new PendingOrderService(ctx), }; } describe('test/app/service/systemMethods/order/pendingOrder.allocateStorage.test.js', () => { - it('should normalize allocation input before delegating to the shared storage allocation service', async () => { + it('should return request_id immediately and delegate normalized input asynchronously', async () => { const { capture, service } = createHarness(); const result = await service.allocateStorage({ @@ -73,16 +90,246 @@ describe('test/app/service/systemMethods/order/pendingOrder.allocateStorage.test ids: '1,2,3', }); - assert.deepEqual(capture.request, { - allow_storage_location: true, - order_ids: '1,2,3', - }); assert.equal(result.flag, 'success'); - assert.equal(result.message, '储位分配完成'); - assert.equal(result.code, 200); - assert.deepEqual(result.data, { - ok: true, + assert.equal(result.warehouse_id, 100000); + assert.equal(result.message, '请求已提交,后端处理中'); + assert.match(result.request_id, /^storage_alloc_100000_\d+_[a-z0-9]+$/); + + await new Promise(resolve => setImmediate(resolve)); + + assert.equal(capture.request.allow_storage_location, true); + assert.equal(capture.request.order_ids, '1,2,3'); + assert.equal(typeof capture.request.progress_callback, 'function'); + }); + + it('should query allocate storage progress by request_id after async task success', async () => { + const { service } = createHarness(); + + const submitResult = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 1, 2, 3 ], }); + + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + const progressResult = await service.allocateStorageProgress({ + request_id: submitResult.request_id, + }); + + assert.equal(progressResult.flag, 'success'); + assert.equal(progressResult.message, 'ok'); + assert.equal(progressResult.request_id, submitResult.request_id); + assert.equal(progressResult.status, 'success'); + assert.equal(progressResult.progress, 100); + assert.equal(progressResult.total_count, 0); + assert.equal(progressResult.processed_count, 0); + assert.deepEqual(progressResult.result, { + code: 200, + message: '储位分配完成', + data: { + ok: true, + }, + }); + assert.equal(typeof progressResult.update_time, 'number'); + }); + + it('should return not_found when request_id does not exist in cache', async () => { + const { service } = createHarness(); + + const result = await service.allocateStorageProgress({ + requestId: 'not_exist_request_id', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.request_id, 'not_exist_request_id'); + assert.equal(result.status, 'not_found'); + assert.equal(result.progress, 0); + }); + + it('should backfill progress from status for legacy cache payload without progress field', async () => { + const { service, cacheStore } = createHarness(); + + const requestId = 'legacy_request_id'; + cacheStore.set(service.getAllocateStorageTaskCacheKey(requestId), { + request_id: requestId, + status: 'running', + update_time: Date.now(), + }); + + const result = await service.allocateStorageProgress({ + request_id: requestId, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.request_id, requestId); + assert.equal(result.status, 'running'); + assert.equal(result.progress, 50); + assert.equal(result.total_count, 0); + assert.equal(result.processed_count, 0); + }); + + it('should report increasing progress and counters while allocation is running', async () => { + let resolveFirstProgress; + const firstProgressReady = new Promise(resolve => { + resolveFirstProgress = resolve; + }); + let resolveSecondProgress; + const secondProgressGate = new Promise(resolve => { + resolveSecondProgress = resolve; + }); + let resolveAllocation; + const allocationDone = new Promise(resolve => { + resolveAllocation = resolve; + }); + + const { service } = createHarness({ + allocateStorageImpl: async request => { + await request.progress_callback({ + total_count: 4, + processed_count: 1, + }); + resolveFirstProgress(); + await secondProgressGate; + await request.progress_callback({ + total_count: 4, + processed_count: 2, + }); + await allocationDone; + await request.progress_callback({ + total_count: 4, + processed_count: 4, + }); + return { + code: 200, + message: '储位分配完成', + data: { + ok: true, + }, + }; + }, + }); + + const submitResult = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 1, 2, 3, 4 ], + }); + + await firstProgressReady; + + const firstRunningProgress = await service.allocateStorageProgress({ + request_id: submitResult.request_id, + }); + + assert.equal(firstRunningProgress.flag, 'success'); + assert.equal(firstRunningProgress.status, 'running'); + assert.equal(firstRunningProgress.total_count, 4); + assert.equal(firstRunningProgress.processed_count, 1); + assert.equal(firstRunningProgress.progress, 25); + + resolveSecondProgress(); + await new Promise(resolve => setImmediate(resolve)); + + const runningProgress = await service.allocateStorageProgress({ + request_id: submitResult.request_id, + }); + + assert.equal(runningProgress.flag, 'success'); + assert.equal(runningProgress.status, 'running'); + assert.equal(runningProgress.total_count, 4); + assert.equal(runningProgress.processed_count, 2); + assert.equal(runningProgress.progress, 50); + + resolveAllocation(); + + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + const successProgress = await service.allocateStorageProgress({ + request_id: submitResult.request_id, + }); + + assert.equal(successProgress.flag, 'success'); + assert.equal(successProgress.status, 'success'); + assert.equal(successProgress.total_count, 4); + assert.equal(successProgress.processed_count, 4); + assert.equal(successProgress.progress, 100); + }); + + it('should return failure when request_id is empty', async () => { + const { service } = createHarness(); + + const result = await service.allocateStorageProgress({ + request_id: ' ', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, 'request_id 参数不能为空'); + assert.equal(result.code, 400); + }); + + it('should keep explainable progress when allocation fails after partial processing', async () => { + const { service } = createHarness({ + allocateStorageImpl: async request => { + await request.progress_callback({ + total_count: 4, + processed_count: 1, + }); + throw new Error('模拟分配失败'); + }, + }); + + const submitResult = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 1, 2, 3, 4 ], + }); + + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + const failedProgress = await service.allocateStorageProgress({ + request_id: submitResult.request_id, + }); + + assert.equal(failedProgress.flag, 'success'); + assert.equal(failedProgress.status, 'failed'); + assert.equal(failedProgress.total_count, 4); + assert.equal(failedProgress.processed_count, 1); + assert.equal(failedProgress.progress, 25); + assert.equal(failedProgress.error, '模拟分配失败'); + }); + + it('should keep explainable progress when allocation is canceled', async () => { + const { service } = createHarness({ + allocateStorageImpl: async request => { + await request.progress_callback({ + total_count: 5, + processed_count: 2, + }); + throw new Error('任务已取消'); + }, + }); + + const submitResult = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 1, 2, 3, 4, 5 ], + }); + + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + const canceledProgress = await service.allocateStorageProgress({ + request_id: submitResult.request_id, + }); + + assert.equal(canceledProgress.flag, 'success'); + assert.equal(canceledProgress.status, 'failed'); + assert.equal(canceledProgress.total_count, 5); + assert.equal(canceledProgress.processed_count, 2); + assert.equal(canceledProgress.progress, 40); + assert.equal(canceledProgress.error, '任务已取消'); }); it('should forward only order IDs when canceling storage allocation', async () => { diff --git a/test/app/service/systemMethods/order/pendingOrder.detail.noLogs.test.js b/test/app/service/systemMethods/order/pendingOrder.detail.noLogs.test.js new file mode 100644 index 0000000..a63d17b --- /dev/null +++ b/test/app/service/systemMethods/order/pendingOrder.detail.noLogs.test.js @@ -0,0 +1,95 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PendingOrderService = require('../../../../../app/service/systemMethods/order/pendingOrder'); + +function createHarness(storeId = 100321) { + const calls = { + queryOrderLogsCalled: 0, + }; + + const ctx = { + app: { + config: {}, + Sequelize: { + Op: { + in: Symbol.for('op.in'), + }, + }, + }, + logger: { + warn() {}, + }, + user: { + store_id: storeId, + }, + service: { + systems: { + operationLog: { + async queryOrderLogs() { + calls.queryOrderLogsCalled += 1; + return { + list: [{ id: 1 }], + pagination: { + page: 1, + pageSize: 200, + total: 1, + totalPages: 1, + }, + }; + }, + }, + }, + }, + }; + + const service = new PendingOrderService(ctx); + + service.getOrderModelByTableType = async () => ({ + async findOne(args) { + calls.findOrderArgs = args; + return { + id: 99, + warehouse_id: storeId, + }; + }, + }); + + service.getOrderItemsModelByTableType = async () => ({ + async findAll(args) { + calls.findOrderItemsArgs = args; + return [{ id: 1, order_id: 99 }]; + }, + }); + + service.getOrderExpressesByOrderId = async orderId => { + calls.expressOrderId = orderId; + return [{ id: 11, order_id: 99, waybill_code: 'WB-001' }]; + }; + + return { + service, + calls, + }; +} + +describe('test/app/service/systemMethods/order/pendingOrder.detail.noLogs.test.js', () => { + it('should not query or return logs for pendingOrder detail', async () => { + const { service, calls } = createHarness(100321); + + const result = await service.detail({ + id: 99, + }); + + assert.equal(calls.findOrderArgs.where.id, 99); + assert.equal(calls.findOrderArgs.where.warehouse_id, 100321); + assert.equal(calls.findOrderItemsArgs.where.order_id, 99); + assert.equal(calls.expressOrderId, 99); + + assert.equal(calls.queryOrderLogsCalled, 0); + assert.equal(Object.prototype.hasOwnProperty.call(result, 'logs'), false); + assert.equal(result.detail.id, 99); + assert.equal(result.items.length, 1); + assert.equal(result.expresses.length, 1); + }); +}); diff --git a/test/app/service/systemMethods/order/queryOrderLogList.test.js b/test/app/service/systemMethods/order/queryOrderLogList.test.js new file mode 100644 index 0000000..b08cf6a --- /dev/null +++ b/test/app/service/systemMethods/order/queryOrderLogList.test.js @@ -0,0 +1,74 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderIndexService = require('../../../../../app/service/systemMethods/order/index'); + +function createHarness(storeId = 100321) { + const calls = {}; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: storeId, + }, + service: { + systems: { + operationLog: { + async queryAllOrderLogs(query) { + calls.queryAllOrderLogs = query; + return [{ id: 1001, operation_code: 'ORDER_CREATE' }]; + }, + }, + }, + }, + }; + + return { + service: new OrderIndexService(ctx), + calls, + }; +} + +describe('test/app/service/systemMethods/order/queryOrderLogList.test.js', () => { + it('should return logs list by order_id', async () => { + const { service } = createHarness(100321); + + const result = await service.queryOrderLogList({ + order_id: 99, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.code, 200); + assert.equal(result.total, 1); + assert.deepEqual(result.list, [{ id: 1001, operation_code: 'ORDER_CREATE' }]); + }); + + it('should pass warehouseId to operation log query', async () => { + const { service, calls } = createHarness(100999); + + const result = await service.queryOrderLogList({ + id: '108', + }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(calls.queryAllOrderLogs, { + id: 108, + warehouseId: 100999, + }); + }); + + it('should fail when order_id is empty', async () => { + const { service } = createHarness(100321); + + const result = await service.queryOrderLogList({ + order_id: '', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.equal(result.message, 'order_id 参数不能为空'); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js b/test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js new file mode 100644 index 0000000..3ccd985 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js @@ -0,0 +1,102 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 batchAllocateExpress 轻量测试上下文。 + * + * @param {Object} options 初始化选项。 + * @param {Array} [options.orderIds=[]] 波次内订单 ID 集合。 + * @return {{ service: WaveService, capture: Object }} 服务实例与调用记录。 + */ +function createHarness(options = {}) { + const cacheStore = new Map(); + const orderIds = Array.isArray(options.orderIds) ? options.orderIds : []; + const capture = { + orderFindAllAttributes: [], + pipelineOrders: [], + }; + + const ctx = { + app: { + config: {}, + async setCacheAsync(key, value) { + cacheStore.set(key, value); + }, + async getCacheAsync(key) { + return cacheStore.get(key) || null; + }, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: {}, + service: { + systems: { + express: { + async createWaybillCodePipeline(orders) { + capture.pipelineOrders = Array.isArray(orders) ? orders : []; + return { + code: 200, + message: '分配完成', + }; + }, + }, + }, + }, + }; + + const service = new WaveService(ctx); + service.getOrderModel = async () => ({ + async findAll(query = {}) { + const attributes = Array.isArray(query.attributes) ? query.attributes : []; + capture.orderFindAllAttributes.push(attributes); + if (attributes.includes('business_key')) { + throw new Error("Unknown column 'business_key' in 'field list'"); + } + + return orderIds.map(id => ({ id })); + }, + }); + + return { + service, + capture, + }; +} + +describe('test/app/service/systemMethods/order/wave.batchAllocateExpress.test.js', () => { + it('should fallback to id-only query when business_key column is missing and keep task success', async () => { + const { service, capture } = createHarness({ + orderIds: [ 101, 102 ], + }); + + await service.runBatchAllocateExpressTask({ + taskId: 'task_missing_business_key_column', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const progress = await service.getBatchAllocateExpressTaskProgress('task_missing_business_key_column'); + assert.equal(progress.state, 'success'); + assert.equal(progress.error, ''); + assert.equal(progress.error_code, ''); + assert.equal(progress.total_order_count, 2); + assert.equal(progress.success_order_count, 2); + + assert.equal(capture.orderFindAllAttributes.length, 2); + assert.deepEqual(capture.orderFindAllAttributes[0], [ 'id', 'business_key' ]); + assert.deepEqual(capture.orderFindAllAttributes[1], [ 'id' ]); + assert.deepEqual(capture.pipelineOrders, [ + { order_id: 101, business_key: 1 }, + { order_id: 102, business_key: 1 }, + ]); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchAllocateStorage.test.js b/test/app/service/systemMethods/order/wave.batchAllocateStorage.test.js new file mode 100644 index 0000000..bf474b0 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.batchAllocateStorage.test.js @@ -0,0 +1,242 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 batchAllocateStorage 轻量测试上下文。 + * + * @param {Object} options 初始化选项。 + * @param {Array} [options.orderIds=[]] 波次内订单ID集合。 + * @param {Function} [options.allocateStorageImpl] 自定义储位分配实现。 + * @return {{ service: WaveService, cacheStore: Map, capture: Object }} 服务实例、缓存与调用记录。 + */ +function createHarness(options = {}) { + const cacheStore = new Map(); + const orderIds = Array.isArray(options.orderIds) ? options.orderIds : []; + const allocateStorageImpl = typeof options.allocateStorageImpl === 'function' + ? options.allocateStorageImpl + : null; + const capture = { + allocateRequest: null, + runningSnapshots: [], + }; + + const ctx = { + app: { + config: {}, + async setCacheAsync(key, value) { + cacheStore.set(key, value); + }, + async getCacheAsync(key) { + return cacheStore.get(key) || null; + }, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: {}, + service: { + systems: { + orderStorageAllocation: { + async allocateStorage(request) { + capture.allocateRequest = request; + if (allocateStorageImpl) { + return await allocateStorageImpl(request, capture); + } + + return { + code: 200, + message: '储位分配完成', + data: { + pending_order_ids: orderIds, + allocated_order_ids: orderIds, + shortage_order_ids: [], + }, + }; + }, + }, + }, + }, + }; + + const service = new WaveService(ctx); + service.getOrderModel = async () => ({ + async findAll() { + return orderIds.map(id => ({ id })); + }, + }); + + return { + service, + cacheStore, + capture, + }; +} + +describe('test/app/service/systemMethods/order/wave.batchAllocateStorage.test.js', () => { + it('should fail later task when another allocate-storage task is running in the same warehouse', async () => { + let unblockFirstTask; + const firstTaskWaiter = new Promise(resolve => { + unblockFirstTask = resolve; + }); + + const { service } = createHarness({ + orderIds: [ 1, 2 ], + allocateStorageImpl: async () => { + await firstTaskWaiter; + return { + code: 200, + message: '储位分配完成', + data: { + pending_order_ids: [ 1, 2 ], + allocated_order_ids: [ 1, 2 ], + shortage_order_ids: [], + }, + }; + }, + }); + + const firstTaskPromise = service.runBatchAllocateStorageTask({ + taskId: 'task_running_same_warehouse_1', + warehouseId: 100000, + waveIds: [ 20 ], + }); + + await new Promise(resolve => setImmediate(resolve)); + + await service.runBatchAllocateStorageTask({ + taskId: 'task_running_same_warehouse_2', + warehouseId: 100000, + waveIds: [ 21 ], + }); + + const conflictProgress = await service.getBatchAllocateStorageTaskProgress('task_running_same_warehouse_2'); + assert.equal(conflictProgress.state, 'failed'); + assert.equal(conflictProgress.error_code, 'WAVE_BATCH_ALLOCATE_STORAGE_WAREHOUSE_CONFLICT'); + + unblockFirstTask(); + await firstTaskPromise; + + const firstTaskProgress = await service.getBatchAllocateStorageTaskProgress('task_running_same_warehouse_1'); + assert.equal(firstTaskProgress.state, 'success'); + }); + + it('should update running progress by progress_callback and keep running percent below 100', async () => { + const { service, capture } = createHarness({ + orderIds: [ 1, 2, 3, 4 ], + allocateStorageImpl: async request => { + await request.progress_callback({ + total_count: 4, + processed_count: 1, + }); + capture.runningSnapshots.push(await service.getBatchAllocateStorageTaskProgress('task_progress_running')); + + await request.progress_callback({ + total_count: 4, + processed_count: 4, + }); + capture.runningSnapshots.push(await service.getBatchAllocateStorageTaskProgress('task_progress_running')); + + return { + code: 200, + message: '储位分配完成', + data: { + pending_order_ids: [ 1, 2, 3, 4 ], + allocated_order_ids: [ 1, 2, 3 ], + shortage_order_ids: [ 4 ], + }, + }; + }, + }); + + await service.runBatchAllocateStorageTask({ + taskId: 'task_progress_running', + warehouseId: 100000, + waveIds: [ 10 ], + }); + + assert.equal(typeof capture.allocateRequest.progress_callback, 'function'); + + const firstRunning = capture.runningSnapshots[0]; + assert.equal(firstRunning.state, 'running'); + assert.equal(firstRunning.total_order_count, 4); + assert.equal(firstRunning.processed_order_count, 1); + assert.ok(firstRunning.progress_percent > 0); + assert.ok(firstRunning.progress_percent < 100); + + const secondRunning = capture.runningSnapshots[1]; + assert.equal(secondRunning.state, 'running'); + assert.equal(secondRunning.total_order_count, 4); + assert.equal(secondRunning.processed_order_count, 4); + assert.equal(secondRunning.progress_percent, 99); + assert.equal(capture.allocateRequest.business_id, 1); + assert.deepEqual(capture.allocateRequest.business_ids, [ 1 ]); + assert.deepEqual(capture.allocateRequest.orders, [ + { order_id: 1, business_id: 1 }, + { order_id: 2, business_id: 1 }, + { order_id: 3, business_id: 1 }, + { order_id: 4, business_id: 1 }, + ]); + }); + + it('should cache and return affected/allocated/shortage order ids after success', async () => { + const { service } = createHarness({ + orderIds: [ 1, 2, 3, 4 ], + allocateStorageImpl: async request => { + await request.progress_callback({ + total_count: 3, + processed_count: 2, + }); + + return { + code: 200, + message: '储位分配完成,部分缺货', + data: { + pending_order_ids: [ 1, 2, 4 ], + allocated_order_ids: [ 1, 2 ], + shortage_order_ids: [ 4 ], + }, + }; + }, + }); + + await service.runBatchAllocateStorageTask({ + taskId: 'task_success_result', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const cachedProgress = await service.getBatchAllocateStorageTaskProgress('task_success_result'); + assert.equal(cachedProgress.state, 'success'); + assert.deepEqual(cachedProgress.affected_order_ids, [ 1, 2, 4 ]); + assert.deepEqual(cachedProgress.allocated_order_ids, [ 1, 2 ]); + assert.deepEqual(cachedProgress.shortage_order_ids, [ 4 ]); + assert.equal(cachedProgress.affected_order_count, 3); + assert.equal(cachedProgress.allocated_order_count, 2); + assert.equal(cachedProgress.business_id, 1); + assert.deepEqual(cachedProgress.business_ids, [ 1 ]); + assert.equal(cachedProgress.result.business_id, 1); + assert.deepEqual(cachedProgress.result.business_ids, [ 1 ]); + + const result = await service.batchAllocateStorageTaskProgress({ + task_id: 'task_success_result', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.state, 'success'); + assert.deepEqual(result.affected_order_ids, [ 1, 2, 4 ]); + assert.deepEqual(result.allocated_order_ids, [ 1, 2 ]); + assert.deepEqual(result.shortage_order_ids, [ 4 ]); + assert.equal(result.affected_order_count, 3); + assert.equal(result.allocated_order_count, 2); + assert.equal(result.business_id, 1); + assert.deepEqual(result.business_ids, [ 1 ]); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js b/test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js new file mode 100644 index 0000000..eff037f --- /dev/null +++ b/test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js @@ -0,0 +1,287 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建波次批量列表测试上下文。 + * + * @param {Array} orderRows 波次关联订单状态数据。 + * @return {{ service: WaveService }} 测试上下文。 + */ +function createHarness(orderRows = []) { + const capturedSqls = []; + + /** + * 根据 SQL 中的聚合条件模拟库位分配状态过滤。 + * + * @param {string} sql 原始 SQL。 + * @param {Array} rows 订单行。 + * @return {boolean} 是否命中过滤条件。 + */ + function matchStorageAssignmentFilter(sql, rows) { + const normalizedRows = Array.isArray(rows) ? rows : []; + const total = normalizedRows.length; + const noneCount = normalizedRows.filter(row => String(row && row.storage_status || '').trim() === 'none').length; + const finCount = normalizedRows.filter(row => String(row && row.storage_status || '').trim() === 'fin').length; + const errorCount = normalizedRows.filter(row => String(row && row.storage_status || '').trim() === 'error').length; + + const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; + const noneExpr = 'COALESCE(wave_order_stats.storage_none_count, 0)'; + const finExpr = 'COALESCE(wave_order_stats.storage_fin_count, 0)'; + const errorExpr = 'COALESCE(wave_order_stats.storage_error_count, 0)'; + + if (sql.includes(`${finExpr} = ${totalExpr}`) && sql.includes(`${totalExpr} > 0`)) { + return total > 0 && finCount === total; + } + + if ( + sql.includes(`${errorExpr} = 0`) + && sql.includes(`${noneExpr} <> ${totalExpr}`) + && sql.includes(`${finExpr} <> ${totalExpr}`) + ) { + return errorCount === 0 && noneCount !== total && finCount !== total; + } + + if ( + sql.includes(`${totalExpr} = 0`) + && sql.includes(`${errorExpr} > 0`) + && sql.includes(`${noneExpr} = ${totalExpr}`) + ) { + return total === 0 || errorCount > 0 || noneCount === total; + } + + return true; + } + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + model: { + async query(sql) { + capturedSqls.push(String(sql)); + const matched = matchStorageAssignmentFilter(sql, orderRows); + if (sql.includes('COUNT(1) AS total')) { + return [[{ total: matched ? 1 : 0 }]]; + } + + if (!matched) { + return [[]]; + } + + return [[{ + wave_id: 1, + wave_no: 'W20260503001', + wave_type: 1, + wave_status: 0, + total_orders: orderRows.length, + processed_orders: 0, + item_detail_machine: '', + item_part_type: 'items_hash', + item_part: 'hash-x', + distinguish_express: 0, + logistics_name: '', + item_snapshot_key: '', + warehouse_id: 100000, + creator: 'tester', + create_time: null, + update_time: null, + }]]; + }, + }, + }; + + const service = new WaveService(ctx); + service.getOrderModel = async () => ({ + getTableName() { + return 'wms_order_delivery_100000'; + }, + async findAll() { + return orderRows; + }, + }); + + return { + service, + capturedSqls, + }; +} + +/** + * 执行 batchList 并返回首条波次记录。 + * + * @param {Array} orderRows 波次关联订单状态数据。 + * @param {Object} [where={}] where 查询参数。 + * @return {Promise} 首条波次状态结果。 + */ +async function getFirstBatch(orderRows, where = {}) { + const { service } = createHarness(orderRows); + const result = await service.batchList({ + page: 1, + pageSize: 20, + where, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.ok(Array.isArray(result.list)); + assert.equal(result.list.length, 1); + + return result.list[0]; +} + +/** + * 执行 batchList 并返回完整列表结果。 + * + * @param {Array} orderRows 波次关联订单状态数据。 + * @param {Object} [where={}] where 查询参数。 + * @return {Promise} 列表结果。 + */ +async function getBatchListResult(orderRows, where = {}) { + const { service, capturedSqls } = createHarness(orderRows); + const result = await service.batchList({ + page: 1, + pageSize: 20, + where, + }); + + return { + result, + capturedSqls, + }; +} + +describe('test/app/service/systemMethods/order/wave.batchList.assignmentStatus.test.js', () => { + it('should keep original behavior when where.storage_assignment_status is missing', async () => { + const { result } = await getBatchListResult([ + { wave_id: 1, storage_status: 'error', post_status: 'none', print_status: 'none' }, + { wave_id: 1, storage_status: 'fin', post_status: 'fin', print_status: 'fin' }, + ]); + + assert.equal(result.flag, 'success'); + assert.equal(result.list.length, 1); + assert.equal(result.pagination.total, 1); + }); + + it('should filter 已分配 by where.storage_assignment_status', async () => { + const { result } = await getBatchListResult([ + { wave_id: 1, storage_status: 'fin', post_status: 'none', print_status: 'none' }, + { wave_id: 1, storage_status: 'fin', post_status: 'none', print_status: 'none' }, + ], { + storage_assignment_status: '已分配', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.list.length, 1); + assert.equal(result.list[0].storage_assignment_status, '已分配'); + }); + + it('should filter 部分分配 by where.storage_assignment_status', async () => { + const { result } = await getBatchListResult([ + { wave_id: 1, storage_status: 'none', post_status: 'none', print_status: 'none' }, + { wave_id: 1, storage_status: 'fin', post_status: 'none', print_status: 'none' }, + ], { + storage_assignment_status: '部分分配', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.list.length, 1); + assert.equal(result.list[0].storage_assignment_status, '部分分配'); + }); + + it('should treat error as 未分配 when filtering by where.storage_assignment_status', async () => { + const { result } = await getBatchListResult([ + { wave_id: 1, storage_status: 'error', post_status: 'none', print_status: 'none' }, + { wave_id: 1, storage_status: 'fin', post_status: 'none', print_status: 'none' }, + ], { + storage_assignment_status: '未分配', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.list.length, 1); + assert.equal(result.list[0].storage_assignment_status, '分配异常'); + }); + + it('should throw when where.storage_assignment_status is invalid', async () => { + await assert.rejects( + async () => { + await getBatchListResult([], { + storage_assignment_status: '异常', + }); + }, + /storage_assignment_status 参数不合法/ + ); + }); + + it('should use aggregate join SQL and avoid correlated subquery when filtering 未分配 with wave_type', async () => { + const { capturedSqls } = await getBatchListResult([ + { wave_id: 1, storage_status: 'error', post_status: 'none', print_status: 'none' }, + { wave_id: 1, storage_status: 'fin', post_status: 'none', print_status: 'none' }, + ], { + storage_assignment_status: '未分配', + wave_type: 1, + }); + + assert.equal(capturedSqls.length, 2); + + for (const sql of capturedSqls) { + assert.ok(sql.includes('LEFT JOIN (')); + assert.ok(sql.includes('wave_order_stats')); + assert.ok(sql.includes('candidate_wave')); + assert.ok(sql.includes('COALESCE(wave_order_stats.order_total, 0) = 0')); + assert.ok(sql.includes('wave_type = :whereWaveType')); + assert.equal(/\bEXISTS\b/i.test(sql), false); + assert.equal(/\bNOT\s+EXISTS\b/i.test(sql), false); + } + }); + + it('should return 分配异常 when all storage/post statuses are error', async () => { + const firstBatch = await getFirstBatch([ + { wave_id: 1, storage_status: 'error', post_status: 'error', print_status: 'none' }, + { wave_id: 1, storage_status: 'error', post_status: 'error', print_status: 'none' }, + ]); + + assert.equal(firstBatch.storage_assignment_status, '分配异常'); + assert.equal(firstBatch.express_assignment_status, '分配异常'); + }); + + it('should keep 分配异常 when error mixes with fin/none', async () => { + const firstBatch = await getFirstBatch([ + { wave_id: 1, storage_status: 'error', post_status: 'none', print_status: 'none' }, + { wave_id: 1, storage_status: 'fin', post_status: 'error', print_status: 'fin' }, + { wave_id: 1, storage_status: 'none', post_status: 'fin', print_status: 'none' }, + ]); + + assert.equal(firstBatch.storage_assignment_status, '分配异常'); + assert.equal(firstBatch.express_assignment_status, '分配异常'); + }); + + it('should keep original none/partial/finished logic when no error exists', async () => { + const noneBatch = await getFirstBatch([ + { wave_id: 1, storage_status: 'none', post_status: 'none', print_status: 'none' }, + { wave_id: 1, storage_status: 'none', post_status: 'none', print_status: 'none' }, + ]); + assert.equal(noneBatch.storage_assignment_status, '未分配'); + assert.equal(noneBatch.express_assignment_status, '未分配'); + + const finishedBatch = await getFirstBatch([ + { wave_id: 1, storage_status: 'fin', post_status: 'fin', print_status: 'fin' }, + { wave_id: 1, storage_status: 'fin', post_status: 'fin', print_status: 'fin' }, + ]); + assert.equal(finishedBatch.storage_assignment_status, '已分配'); + assert.equal(finishedBatch.express_assignment_status, '已分配'); + + const partialBatch = await getFirstBatch([ + { wave_id: 1, storage_status: 'none', post_status: 'fin', print_status: 'none' }, + { wave_id: 1, storage_status: 'fin', post_status: 'none', print_status: 'fin' }, + ]); + assert.equal(partialBatch.storage_assignment_status, '部分分配'); + assert.equal(partialBatch.express_assignment_status, '部分分配'); + assert.equal(partialBatch.print_assignment_status, '部分打印'); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchRemoveExceptionOrders.test.js b/test/app/service/systemMethods/order/wave.batchRemoveExceptionOrders.test.js new file mode 100644 index 0000000..0da6395 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.batchRemoveExceptionOrders.test.js @@ -0,0 +1,178 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 batchRemoveExceptionOrders 轻量测试上下文。 + * + * @return {{ service: WaveService, cacheStore: Map, capture: Object }} 服务实例、缓存与调用记录。 + */ +function createHarness() { + const cacheStore = new Map(); + const capture = { + removePayload: null, + }; + + const ctx = { + app: { + config: {}, + async setCacheAsync(key, value) { + cacheStore.set(key, value); + }, + async getCacheAsync(key) { + return cacheStore.get(key) || null; + }, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: {}, + }; + + const service = new WaveService(ctx); + + return { + service, + cacheStore, + capture, + }; +} + +describe('test/app/service/systemMethods/order/wave.batchRemoveExceptionOrders.test.js', () => { + it('should remove only pending-exception(step=3) orders when wave has mixed normal orders', async () => { + const { service, capture } = createHarness(); + + service.getOrderModel = async () => ({ + async findAll() { + return [ + { id: 1, wave_id: 11, wave_no: 'W11', step: 3 }, + { id: 2, wave_id: 11, wave_no: 'W11', step: 2 }, + { id: 3, wave_id: 11, wave_no: 'W11', step: 1 }, + ]; + }, + }); + + service.batchRemoveOrders = async payload => { + capture.removePayload = payload; + return service.success('ok', { + removed_order_ids: [ 1 ], + removed_order_count: 1, + affected_wave_ids: [ 11 ], + updated_wave_ids: [ 11 ], + emptied_wave_ids: [], + }); + }; + + await service.setBatchRemoveExceptionOrdersTaskProgress('task_1', 'submitted', { + warehouse_id: 100000, + wave_ids: '11', + wave_id_list: [ 11 ], + }); + + await service.runBatchRemoveExceptionOrdersTask({ + taskId: 'task_1', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + assert.deepEqual(capture.removePayload, { + ids: [ 1 ], + }); + + const progress = await service.getBatchRemoveExceptionOrdersTaskProgress('task_1'); + assert.equal(progress.state, 'success'); + assert.equal(progress.removed_order_count, 1); + assert.deepEqual(progress.result.removed_order_ids, [ 1 ]); + assert.deepEqual(progress.result.updated_wave_ids, [ 11 ]); + assert.deepEqual(progress.result.emptied_wave_ids, []); + }); + + it('should allow wave to become empty when all orders are pending exception', async () => { + const { service, capture } = createHarness(); + + service.getOrderModel = async () => ({ + async findAll() { + return [ + { id: 21, wave_id: 21, wave_no: 'W21', step: 3 }, + { id: 22, wave_id: 21, wave_no: 'W21', step: 3 }, + ]; + }, + }); + + service.batchRemoveOrders = async payload => { + capture.removePayload = payload; + return service.success('ok', { + removed_order_ids: [ 21, 22 ], + removed_order_count: 2, + affected_wave_ids: [ 21 ], + updated_wave_ids: [], + emptied_wave_ids: [ 21 ], + }); + }; + + await service.setBatchRemoveExceptionOrdersTaskProgress('task_all_exception', 'submitted', { + warehouse_id: 100000, + wave_ids: '21', + wave_id_list: [ 21 ], + }); + + await service.runBatchRemoveExceptionOrdersTask({ + taskId: 'task_all_exception', + warehouseId: 100000, + waveIds: [ 21 ], + }); + + assert.deepEqual(capture.removePayload, { + ids: [ 21, 22 ], + }); + + const progress = await service.getBatchRemoveExceptionOrdersTaskProgress('task_all_exception'); + assert.equal(progress.state, 'success'); + assert.equal(progress.removed_order_count, 2); + assert.deepEqual(progress.result.updated_wave_ids, []); + assert.deepEqual(progress.result.emptied_wave_ids, [ 21 ]); + }); + + it('should mark success when no exception orders found', async () => { + const { service, capture } = createHarness(); + + service.getOrderModel = async () => ({ + async findAll() { + return [ + { id: 11, wave_id: 31, wave_no: 'W31', step: 1, inspection_status: 'fin', intercept_status: 'none' }, + { id: 12, wave_id: 31, wave_no: 'W31', step: 2, inspection_status: 'padding', intercept_status: 'none' }, + ]; + }, + }); + + service.batchRemoveOrders = async payload => { + capture.removePayload = payload; + return service.success('ok', {}); + }; + + await service.setBatchRemoveExceptionOrdersTaskProgress('task_2', 'submitted', { + warehouse_id: 100000, + wave_ids: '31', + wave_id_list: [ 31 ], + }); + + await service.runBatchRemoveExceptionOrdersTask({ + taskId: 'task_2', + warehouseId: 100000, + waveIds: [ 31 ], + }); + + assert.equal(capture.removePayload, null); + + const progress = await service.getBatchRemoveExceptionOrdersTaskProgress('task_2'); + assert.equal(progress.state, 'success'); + assert.equal(progress.removed_order_count, 0); + assert.equal(progress.result.message, '未找到可移除的异常订单'); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js b/test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js new file mode 100644 index 0000000..502e918 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js @@ -0,0 +1,255 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const { Op } = require('sequelize'); +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 batchRemoveOrders 轻量测试上下文。 + * + * @param {Object} options 初始化选项。 + * @param {Array} options.orders 订单初始数据。 + * @param {Array} options.waves 波次初始数据。 + * @param {number} options.storeId 当前仓库ID。 + * @return {{ service: WaveService, orders: Array, waves: Array, txState: Object }} 测试上下文。 + */ +function createHarness({ orders = [], waves = [], storeId = 100000 } = {}) { + const orderStore = orders.map(row => ({ ...row })); + const waveStore = waves.map(row => ({ ...row })); + const txState = { + committed: false, + rolledBack: false, + }; + + const transaction = { + async commit() { + txState.committed = true; + }, + async rollback() { + txState.rolledBack = true; + }, + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: storeId, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + fn(name, colName) { + return `${name}(${colName})`; + }, + col(field) { + return field; + }, + async transaction() { + return transaction; + }, + async query(sql, options = {}) { + if (sql.includes('SET total_orders = :remainingCount')) { + const waveId = Number(options.replacements && options.replacements.waveId || 0); + const remainingCount = Number(options.replacements && options.replacements.remainingCount || 0); + const targetWave = waveStore.find(item => Number(item.wave_id) === waveId); + if (targetWave) { + targetWave.total_orders = remainingCount; + targetWave.processed_orders = Math.min(Number(targetWave.processed_orders || 0), remainingCount); + } + return [[], { affectedRows: targetWave ? 1 : 0 }]; + } + + if (sql.includes('SET total_orders = 0') && sql.includes('wave_status = -1')) { + const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds) + ? options.replacements.waveIds + : []; + for (const wave of waveStore) { + if (targetWaveIds.includes(wave.wave_id)) { + wave.total_orders = 0; + wave.processed_orders = 0; + wave.wave_status = -1; + } + } + return [[], { affectedRows: targetWaveIds.length }]; + } + + return [[], { affectedRows: 0 }]; + }, + }, + }; + + const service = new WaveService(ctx); + service.getOrderModel = async () => ({ + async findAll(options = {}) { + const where = options.where || {}; + const idIn = (where.id && where.id[Op.in]) || []; + const stepIn = (where.step && where.step[Op.in]) || []; + const waveIn = (where.wave_id && where.wave_id[Op.in]) || []; + const waveGt = Number((where.wave_id && where.wave_id[Op.gt]) || 0); + + if (Array.isArray(options.group) && options.group.includes('wave_id')) { + const result = []; + for (const waveId of waveIn) { + const count = orderStore.filter(item => Number(item.wave_id) === Number(waveId) && Number(item.wave_id) > waveGt).length; + if (count > 0) { + result.push({ + wave_id: Number(waveId), + remaining_count: count, + }); + } + } + return result; + } + + return orderStore + .filter(item => idIn.includes(item.id)) + .filter(item => stepIn.includes(item.step)) + .filter(item => Number(item.wave_id) > waveGt) + .map(item => ({ + id: item.id, + wave_id: item.wave_id, + })); + }, + + async update(values = {}, options = {}) { + const ids = (options.where && options.where.id && options.where.id[Op.in]) || []; + let affected = 0; + for (const item of orderStore) { + if (ids.includes(item.id)) { + item.wave_id = values.wave_id; + item.wave_no = values.wave_no; + affected += 1; + } + } + + return [ affected ]; + }, + }); + + return { + service, + orders: orderStore, + waves: waveStore, + txState, + }; +} + +describe('test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js', () => { + it('should only remove orders with step in [1,2,3]', async () => { + const { service, orders } = createHarness({ + orders: [ + { id: 1, order_id: 101, step: 1, wave_id: 11, wave_no: 'W11' }, + { id: 2, order_id: 102, step: 2, wave_id: 11, wave_no: 'W11' }, + { id: 3, order_id: 103, step: 0, wave_id: 11, wave_no: 'W11' }, + { id: 4, order_id: 104, step: 3, wave_id: 12, wave_no: 'W12' }, + ], + waves: [ + { wave_id: 11, total_orders: 3, processed_orders: 2, wave_status: 1 }, + { wave_id: 12, total_orders: 1, processed_orders: 0, wave_status: 1 }, + ], + }); + + const result = await service.batchRemoveOrders({ ids: '1,2,3,4' }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.ids, [ 1, 2, 3, 4 ]); + assert.deepEqual(result.removed_order_ids, [ 1, 2, 4 ]); + assert.equal(result.removed_order_count, 3); + assert.deepEqual(result.affected_wave_ids, [ 11, 12 ]); + + const orderWithStep0 = orders.find(item => item.id === 3); + assert.equal(orderWithStep0.wave_id, 11); + assert.equal(orderWithStep0.wave_no, 'W11'); + }); + + it('should update orders and wave stats in one transaction', async () => { + const { service, orders, waves, txState } = createHarness({ + orders: [ + { id: 10, order_id: 110, step: 1, wave_id: 21, wave_no: 'W21' }, + { id: 11, order_id: 111, step: 2, wave_id: 21, wave_no: 'W21' }, + { id: 12, order_id: 112, step: 0, wave_id: 21, wave_no: 'W21' }, + { id: 13, order_id: 113, step: 1, wave_id: 22, wave_no: 'W22' }, + ], + waves: [ + { wave_id: 21, total_orders: 3, processed_orders: 5, wave_status: 1 }, + { wave_id: 22, total_orders: 1, processed_orders: 1, wave_status: 1 }, + ], + }); + + const result = await service.batchRemoveOrders({ ids: [ 10, 11, 13 ] }); + + assert.equal(txState.committed, true); + assert.equal(txState.rolledBack, false); + + assert.equal(result.removed_order_count, 3); + assert.deepEqual(result.updated_wave_ids, [ 21 ]); + assert.deepEqual(result.emptied_wave_ids, [ 22 ]); + + const removedOrder = orders.find(item => item.id === 10); + assert.equal(removedOrder.wave_id, 0); + assert.equal(removedOrder.wave_no, ''); + + const updatedWave = waves.find(item => item.wave_id === 21); + assert.equal(updatedWave.total_orders, 1); + assert.equal(updatedWave.processed_orders, 1); + assert.equal(updatedWave.wave_status, 1); + + const emptiedWave = waves.find(item => item.wave_id === 22); + assert.equal(emptiedWave.total_orders, 0); + assert.equal(emptiedWave.processed_orders, 0); + assert.equal(emptiedWave.wave_status, -1); + }); + + it('should accept order_ids alias and normalize ids in response', async () => { + const { service } = createHarness({ + orders: [ + { id: 21, order_id: 121, step: 1, wave_id: 31, wave_no: 'W31' }, + { id: 22, order_id: 122, step: 2, wave_id: 31, wave_no: 'W31' }, + ], + waves: [ + { wave_id: 31, total_orders: 2, processed_orders: 1, wave_status: 1 }, + ], + }); + + const result = await service.batchRemoveOrders({ order_ids: '21,22' }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.ids, [ 21, 22 ]); + }); + + it('should work when pendingOrder has no order_id column', async () => { + const { service, orders } = createHarness({ + orders: [ + { id: 31, step: 1, wave_id: 41, wave_no: 'W41' }, + { id: 32, step: 2, wave_id: 41, wave_no: 'W41' }, + ], + waves: [ + { wave_id: 41, total_orders: 2, processed_orders: 1, wave_status: 1 }, + ], + }); + + const result = await service.batchRemoveOrders({ ids: [ 31, 32 ] }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.removed_order_ids, [ 31, 32 ]); + assert.equal(result.removed_order_count, 2); + assert.equal(orders[0].wave_id, 0); + assert.equal(orders[1].wave_id, 0); + }); + + it('should throw when ids is empty', async () => { + const { service } = createHarness({ + orders: [], + waves: [], + }); + + await assert.rejects( + async () => service.batchRemoveOrders({ ids: '' }), + /ids 参数不能为空或格式错误/ + ); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.fetch.test.js b/test/app/service/systemMethods/order/wave.fetch.test.js new file mode 100644 index 0000000..0c40601 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.fetch.test.js @@ -0,0 +1,447 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 构建波次抓取测试上下文。 + * + * @param {boolean} [mockRunFetchTask=true] 是否默认桩化 runFetchTask。 + * @return {{ service: WaveService, cache: Map, runTaskCalls: Array }} 测试上下文。 + */ +function createHarness(mockRunFetchTask = true) { + const cache = new Map(); + const runTaskCalls = []; + const ctx = { + app: { + config: {}, + async setCacheAsync(key, payload) { + cache.set(key, payload); + }, + async getCacheAsync(key) { + return cache.get(key) || null; + }, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new WaveService(ctx); + service.getDefaultWaveQuantity = async () => 50; + if (mockRunFetchTask) { + service.runFetchTask = async params => { + runTaskCalls.push(params); + }; + } + + return { + service, + cache, + runTaskCalls, + }; +} + +describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { + it('groupFetch 应正常提交异步任务并返回 task_id', async () => { + const { service } = createHarness(); + const token = service.buildMachineStructureToken({ + item_part_type: 'items_hash', + item_part: 'hash-group-a', + distinguish_express: false, + logistics_name: '', + item_snapshot_key: '', + }); + + const result = await service.groupFetch({ + structure_list: [ + { + item_detail_machine: token, + quantity: 5, + }, + ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '任务已提交,后端异步处理中'); + assert.ok(typeof result.task_id === 'string' && result.task_id.length > 0); + assert.equal(result.fetch_mode, 'group'); + }); + + it('fetch 兼容别名应转调 groupFetch', async () => { + const { service } = createHarness(); + const expected = { + flag: 'success', + message: 'ok', + task_id: 'alias-task-id', + }; + + let called = false; + service.groupFetch = async data => { + called = true; + assert.deepEqual(data, { a: 1 }); + return expected; + }; + + const result = await service.fetch({ a: 1 }); + + assert.equal(called, true); + assert.deepEqual(result, expected); + }); + + it('singleFetch 缺失 max_fetch_quantity 时应报错', async () => { + const { service } = createHarness(); + const token = service.buildMachineStructureToken({ + item_part_type: 'items_hash', + item_part: 'hash-single-a', + distinguish_express: false, + logistics_name: '', + item_snapshot_key: '', + }); + + await assert.rejects( + () => service.singleFetch({ + structure_list: [ + { + item_detail_machine: token, + quantity: 3, + }, + ], + }), + /max_fetch_quantity 参数不能为空/ + ); + }); + + it('single 模式 runFetchTask 达到 max_fetch_quantity 后应停止', async () => { + const { service } = createHarness(false); + service.getGroupWavePrefix = async () => 'B'; + service.getMinGroupOrderFetchQuantity = async () => 13; + service.getOrderModel = async () => ({ + async findAll() { + return []; + }, + async update() { + return [ 0 ]; + }, + }); + + const progressList = []; + service.setFetchTaskProgress = async (_taskId, payload) => { + progressList.push(payload); + }; + + const minGroupList = []; + const maxQuantityList = []; + service.fetchSingleStructure = async ( + _model, + structure, + _warehouseId, + _wavePrefix, + minGroupOrderFetchQuantity, + options = {} + ) => { + minGroupList.push(minGroupOrderFetchQuantity); + maxQuantityList.push(Number(options.maxFetchQuantity || 0)); + + const requestQuantity = Number(structure.quantity || 0); + const fetchLimit = Number(options.maxFetchQuantity || 0); + const fetchedQuantity = Math.min(requestQuantity, fetchLimit); + + return { + item_detail_machine: structure.item_detail_machine, + request_quantity: requestQuantity, + fetched_quantity: fetchedQuantity, + wave_ids: [], + order_ids: [], + }; + }; + + await service.runFetchTask({ + taskId: 'wave_fetch_100000_123456', + warehouseId: 100000, + defaultQuantity: 50, + fetchMode: 'single', + maxFetchQuantity: 5, + structures: [ + { item_detail_machine: 's-1', quantity: 4 }, + { item_detail_machine: 's-2', quantity: 4 }, + { item_detail_machine: 's-3', quantity: 4 }, + ], + }); + + assert.deepEqual(minGroupList, [ 1, 1 ]); + assert.deepEqual(maxQuantityList, [ 5, 1 ]); + + const finalProgress = progressList[progressList.length - 1] || {}; + assert.equal(finalProgress.status, 'success'); + assert.equal(finalProgress.fetch_mode, 'single'); + assert.equal(finalProgress.max_fetch_quantity, 5); + assert.equal(finalProgress.total_fetched_quantity, 5); + assert.equal(finalProgress.finished_structure_count, 2); + assert.equal(finalProgress.limit_reached, true); + assert.equal(finalProgress.stop_reason, '达到最大抓取上限'); + }); + + it('fetchSingleStructure 应使用 wave_batch 自增 wave_id 更新订单', async () => { + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() {}, + async rollback() {}, + }; + + const sqlCalls = []; + const orders = [ + { id: 101, wave_id: 0 }, + { id: 102, wave_id: 0 }, + ]; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async transaction() { + return transaction; + }, + async query(sql, options = {}) { + sqlCalls.push({ sql, options }); + if (sql.includes('INSERT INTO wms_wave_batch')) { + return [ { insertId: 900001 }, { insertId: 900001 } ]; + } + + if (sql.includes('SELECT wave_no')) { + return []; + } + + if (sql.includes('UPDATE wms_wave_batch')) { + return [ { affectedRows: 1 } ]; + } + + if (sql.includes('DELETE FROM wms_wave_batch')) { + return [ { affectedRows: 1 } ]; + } + + return [ [] ]; + }, + }, + }; + + const service = new WaveService(ctx); + service.app.Sequelize = { + literal(value) { + return value; + }, + }; + service.batchCreateOrderOperationLogs = async () => 0; + service.getCurrentDatePart = () => '20260506'; + service.getNextWaveNoSequence = async () => 1; + + const model = { + async findAll(options = {}) { + const where = options.where || {}; + if (where.wave_id === 0) { + return orders + .filter(item => item.wave_id === 0) + .map(item => ({ id: item.id })); + } + + if (where.wave_id === 900001) { + return orders + .filter(item => item.wave_id === 900001) + .map(item => ({ id: item.id })); + } + + return []; + }, + async update(values = {}, options = {}) { + const where = options.where || {}; + const targetIds = (where.id && where.id[Op.in]) || []; + for (const item of orders) { + if (targetIds.includes(item.id) && item.wave_id === 0) { + item.wave_id = Number(values.wave_id || 0); + item.wave_no = String(values.wave_no || ''); + } + } + return [ targetIds.length ]; + }, + }; + + const result = await service.fetchSingleStructure( + model, + { + item_detail_machine: 'token-a', + quantity: 2, + item_part_type: 'items_hash', + item_part: 'hash-a', + distinguish_express: false, + logistics_name: '', + item_snapshot_key: '', + }, + 100000, + 'B', + 1, + { + maxFetchQuantity: 2, + } + ); + + assert.equal(result.fetched_quantity, 2); + assert.deepEqual(result.wave_ids, [ 900001 ]); + assert.equal(orders[0].wave_id, 900001); + assert.equal(orders[1].wave_id, 900001); + + const insertCall = sqlCalls.find(call => call.sql.includes('INSERT INTO wms_wave_batch')); + assert.ok(insertCall); + assert.equal(insertCall.options.replacements.waveId, undefined); + }); + + it('fetchSingleStructure 在 INSERT 未返回 insertId 时应回查 LAST_INSERT_ID 并成功更新订单', async () => { + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() {}, + async rollback() {}, + }; + + const sqlCalls = []; + const orders = [ + { id: 201, wave_id: 0 }, + { id: 202, wave_id: 0 }, + ]; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async transaction() { + return transaction; + }, + async query(sql, options = {}) { + sqlCalls.push({ sql, options }); + if (sql.includes('INSERT INTO wms_wave_batch')) { + return [ {}, {} ]; + } + + if (sql.includes('SELECT LAST_INSERT_ID() AS insertId')) { + return [ [ { insertId: 900002 } ], {} ]; + } + + if (sql.includes('SELECT wave_no')) { + return []; + } + + if (sql.includes('UPDATE wms_wave_batch')) { + return [ { affectedRows: 1 } ]; + } + + if (sql.includes('DELETE FROM wms_wave_batch')) { + return [ { affectedRows: 1 } ]; + } + + return [ [] ]; + }, + }, + }; + + const service = new WaveService(ctx); + service.app.Sequelize = { + literal(value) { + return value; + }, + }; + service.batchCreateOrderOperationLogs = async () => 0; + service.getCurrentDatePart = () => '20260506'; + service.getNextWaveNoSequence = async () => 2; + + const model = { + async findAll(options = {}) { + const where = options.where || {}; + if (where.wave_id === 0) { + return orders + .filter(item => item.wave_id === 0) + .map(item => ({ id: item.id })); + } + + if (where.wave_id === 900002) { + return orders + .filter(item => item.wave_id === 900002) + .map(item => ({ id: item.id })); + } + + return []; + }, + async update(values = {}, options = {}) { + const where = options.where || {}; + const targetIds = (where.id && where.id[Op.in]) || []; + for (const item of orders) { + if (targetIds.includes(item.id) && item.wave_id === 0) { + item.wave_id = Number(values.wave_id || 0); + item.wave_no = String(values.wave_no || ''); + } + } + return [ targetIds.length ]; + }, + }; + + const result = await service.fetchSingleStructure( + model, + { + item_detail_machine: 'token-b', + quantity: 2, + item_part_type: 'items_hash', + item_part: 'hash-b', + distinguish_express: false, + logistics_name: '', + item_snapshot_key: '', + }, + 100000, + 'B', + 1, + { + maxFetchQuantity: 2, + } + ); + + assert.equal(result.fetched_quantity, 2); + assert.deepEqual(result.wave_ids, [ 900002 ]); + assert.equal(orders[0].wave_id, 900002); + assert.equal(orders[1].wave_id, 900002); + + const fallbackCall = sqlCalls.find(call => call.sql.includes('SELECT LAST_INSERT_ID() AS insertId')); + assert.ok(fallbackCall); + assert.equal(fallbackCall.options.transaction, transaction); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.singleOrderFetchList.test.js b/test/app/service/systemMethods/order/wave.singleOrderFetchList.test.js new file mode 100644 index 0000000..689ef57 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.singleOrderFetchList.test.js @@ -0,0 +1,90 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 构建波次抓取列表测试上下文。 + * + * @return {{ service: WaveService }} 测试上下文。 + */ +function createHarness() { + const rawOrders = [ + { id: 301, store_id: 100000, logistics_name: '中通', items_hash: 'H-C', items: '[C]', items_total: 1, post_status: 'none', pick_status: 'none', outbound_status: 'none', create_at: '2026-05-01 10:00:00' }, + { id: 202, store_id: 100000, logistics_name: '中通', items_hash: 'H-B', items: '[B]', items_total: 1, post_status: 'none', pick_status: 'none', outbound_status: 'none', create_at: '2026-05-01 09:00:00' }, + { id: 201, store_id: 100000, logistics_name: '中通', items_hash: 'H-B', items: '[B]', items_total: 1, post_status: 'none', pick_status: 'none', outbound_status: 'none', create_at: '2026-05-01 08:00:00' }, + { id: 103, store_id: 100000, logistics_name: '圆通', items_hash: 'H-A', items: '[A]', items_total: 1, post_status: 'none', pick_status: 'none', outbound_status: 'none', create_at: '2026-05-01 07:00:00' }, + { id: 102, store_id: 100000, logistics_name: '圆通', items_hash: 'H-A', items: '[A]', items_total: 1, post_status: 'none', pick_status: 'none', outbound_status: 'none', create_at: '2026-05-01 06:00:00' }, + { id: 101, store_id: 100000, logistics_name: '圆通', items_hash: 'H-A', items: '[A]', items_total: 1, post_status: 'none', pick_status: 'none', outbound_status: 'none', create_at: '2026-05-01 05:00:00' }, + ]; + + const orderItemsByOrderId = { + 103: [ + { order_id: 103, plan_qty: 2, stock_id: 11, item_code: 'SKU-A', item_name: '商品A', item_snapshot: '{}' }, + ], + 202: [ + { order_id: 202, plan_qty: 1, stock_id: 22, item_code: 'SKU-B', item_name: '商品B', item_snapshot: '{}' }, + ], + 301: [ + { order_id: 301, plan_qty: 1, stock_id: 33, item_code: 'SKU-C', item_name: '商品C', item_snapshot: '{}' }, + ], + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const service = new WaveService(ctx); + service.getMinGroupOrderFetchQuantity = async () => 3; + service.getOrderModel = async () => ({ + async findAll() { + return rawOrders; + }, + }); + service.getOrderItemsModelByTableType = async () => ({ + async findAll() { + return Object.values(orderItemsByOrderId).flat(); + }, + }); + + return { service }; +} + +describe('test/app/service/systemMethods/order/wave.singleOrderFetchList.test.js', () => { + it('groupOrderFetchList 仅返回达到团购阈值的分组', async () => { + const { service } = createHarness(); + const result = await service.groupOrderFetchList({ + same_order_quantity: 3, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.pagination.total, 1); + assert.equal(result.list.length, 1); + assert.equal(result.list[0].group_count, 3); + }); + + it('singleOrderFetchList 仅返回未达到团购阈值的分组', async () => { + const { service } = createHarness(); + const result = await service.singleOrderFetchList({ + same_order_quantity: 3, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.pagination.total, 2); + assert.equal(result.list.length, 2); + assert.deepEqual(result.list.map(item => item.group_count), [ 2, 1 ]); + }); +}); diff --git a/test/app/service/systemMethods/pick.query.test.js b/test/app/service/systemMethods/pick.query.test.js new file mode 100644 index 0000000..dc7eb42 --- /dev/null +++ b/test/app/service/systemMethods/pick.query.test.js @@ -0,0 +1,318 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); + +const PickService = require('../../../../app/service/systemMethods/pick'); +const PickSystemService = require('../../../../app/service/systems/pick'); +const { matchesWhere } = require('../../../support/order_service_test_helper'); + +/** + * 创建 pick.query 测试上下文。 + * + * @param {Object} fixtures 测试数据。 + * @return {{ service: PickService }} Method 服务实例。 + */ +function createHarness(fixtures = {}) { + const orderExpressRows = Array.isArray(fixtures.orderExpressRows) ? fixtures.orderExpressRows.map(item => ({ ...item })) : []; + const orderRows = Array.isArray(fixtures.orderRows) ? fixtures.orderRows.map(item => ({ ...item })) : []; + const pickingRows = Array.isArray(fixtures.pickingRows) ? fixtures.pickingRows.map(item => ({ ...item })) : []; + const locationRows = Array.isArray(fixtures.locationRows) ? fixtures.locationRows.map(item => ({ ...item })) : []; + const storeWarehouseRows = Array.isArray(fixtures.storeWarehouseRows) ? fixtures.storeWarehouseRows.map(item => ({ ...item })) : []; + + const findByWhere = (rows, where) => rows.filter(row => matchesWhere(row, where)); + const staticOrderModelCallCount = { + findOne: 0, + findAll: 0, + }; + const factoryCallWarehouseIds = []; + + const ctx = { + app: { + Sequelize, + config: {}, + }, + user: fixtures.withoutUserContext + ? {} + : { + store_id: Number( + Object.prototype.hasOwnProperty.call(fixtures, 'storeId') ? fixtures.storeId : 100000 + ), + }, + state: fixtures.withStateUserContext + ? { + user: { + store_id: Number(fixtures.stateStoreId || 0), + }, + } + : {}, + logger: { + error() {}, + }, + model: { + OrderExpress: { + async findOne(options = {}) { + const rows = findByWhere(orderExpressRows, options.where || {}); + return rows.length > 0 ? { ...rows[0] } : null; + }, + }, + OrderDelivery: { + async findOne(options = {}) { + staticOrderModelCallCount.findOne += 1; + if (fixtures.throwOnStaticOrderModelUse) { + throw new Error('不应回退到静态 OrderDelivery.findOne'); + } + const rows = findByWhere(orderRows, options.where || {}); + return rows.length > 0 ? { ...rows[0] } : null; + }, + async findAll(options = {}) { + staticOrderModelCallCount.findAll += 1; + if (fixtures.throwOnStaticOrderModelUse) { + throw new Error('不应回退到静态 OrderDelivery.findAll'); + } + return findByWhere(orderRows, options.where || {}).map(item => ({ ...item })); + }, + }, + Picking: { + async findAll(options = {}) { + return findByWhere(pickingRows, options.where || {}).map(item => ({ ...item })); + }, + }, + LocationSpace: { + async findAll(options = {}) { + return findByWhere(locationRows, options.where || {}).map(item => ({ ...item })); + }, + }, + StoreWarehouse: { + async findOne(options = {}) { + const rows = findByWhere(storeWarehouseRows, options.where || {}); + return rows.length > 0 ? { ...rows[0] } : null; + }, + }, + }, + service: { + systems: {}, + }, + }; + + if (!fixtures.withoutFactory) { + const defaultFactory = { + async getCurrentModel(warehouseId) { + factoryCallWarehouseIds.push(Number(warehouseId || 0)); + if (fixtures.factoryReturnsInvalidModel) { + return fixtures.invalidFactoryModel || {}; + } + return { + async findOne(options = {}) { + const rows = findByWhere(orderRows, options.where || {}); + return rows.length > 0 ? { ...rows[0] } : null; + }, + async findAll(options = {}) { + return findByWhere(orderRows, options.where || {}).map(item => ({ ...item })); + }, + }; + }, + }; + ctx.model.OrderDeliveryFactory = fixtures.orderFactory || defaultFactory; + } + + ctx.service.systems.pick = new PickSystemService(ctx); + + return { + service: new PickService(ctx), + factoryCallWarehouseIds, + staticOrderModelCallCount, + }; +} + +describe('test/app/service/systemMethods/pick.query.test.js', () => { + it('不传 warehouse_id 且存在登录用户仓库上下文时应查询成功', async () => { + const { service, factoryCallWarehouseIds } = createHarness({ + storeId: 100000, + orderExpressRows: [ + { order_id: 9001, warehouse_id: 100000, waybill_code: 'WB-9001' }, + ], + orderRows: [ + { id: 9001, warehouse_id: 100000, store_id: 2001, wave_id: 77, wave_no: 'WAVE-77', inspection_status: 'none' }, + { id: 9002, warehouse_id: 100000, store_id: 2001, wave_id: 77, wave_no: 'WAVE-77', inspection_status: 'fin' }, + ], + pickingRows: [ + { id: 1, order_id: 9001, order_item_id: 11, storage_id: 501, quantity: 2, space_id: 3001, space_name: 'A-01', status: 'pending' }, + { id: 2, order_id: 9001, order_item_id: 12, storage_id: 502, quantity: 1, space_id: 3002, space_name: 'A-02', status: 'pending' }, + { id: 3, order_id: 9002, order_item_id: 13, storage_id: 503, quantity: 5, space_id: 3001, space_name: 'A-01', status: 'pending' }, + ], + locationRows: [ + { id: 3001, warehouse_id: 100000, space_code: 'A-01', custom_name: 'A区-01', custom_barcode: 'BC-A01', zone_id: 10, space_status: 'AVAILABLE', is_enabled: true, pick_sequence: 1, pick_priority: 10 }, + { id: 3002, warehouse_id: 100000, space_code: 'A-02', custom_name: 'A区-02', custom_barcode: 'BC-A02', zone_id: 10, space_status: 'AVAILABLE', is_enabled: true, pick_sequence: 2, pick_priority: 20 }, + ], + storeWarehouseRows: [ + { id: 88, store_id: 2001, warehouse_id: 100000, store_remask: '货主A', warehouse_remask: '仓库A', auth_status: 2, use_status: 1 }, + ], + }); + + const result = await service.query({ + waybill_code: 'WB-9001', + full: true, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.wave_no, 'WAVE-77'); + assert.equal(result.data.list.length, 3); + assert.equal(result.data.summary.total_count, 3); + assert.equal(result.data.summary.pending_review_count, 2); + assert.equal(result.data.summary.reviewed_count, 1); + assert.equal(result.data.summary.quantity_total, 8); + assert.ok(result.data.list.every(item => item.location_space)); + assert.ok(result.data.list.every(item => item.store_warehouse)); + assert.ok(factoryCallWarehouseIds.length >= 2); + assert.ok(factoryCallWarehouseIds.every(warehouseId => warehouseId === 100000)); + }); + + it('full_display/is_full 为 false 时仅返回未复核订单拣货信息', async () => { + const { service } = createHarness({ + storeId: 100000, + orderExpressRows: [ + { order_id: 9101, warehouse_id: 100000, waybill_code: 'WB-9101' }, + ], + orderRows: [ + { id: 9101, warehouse_id: 100000, store_id: 2002, wave_id: 78, wave_no: 'WAVE-78', inspection_status: 'none' }, + { id: 9102, warehouse_id: 100000, store_id: 2002, wave_id: 78, wave_no: 'WAVE-78', inspection_status: 'fin' }, + ], + pickingRows: [ + { id: 11, order_id: 9101, order_item_id: 21, storage_id: 601, quantity: 3, space_id: 4001, space_name: 'B-01', status: 'pending' }, + { id: 12, order_id: 9102, order_item_id: 22, storage_id: 602, quantity: 4, space_id: 4002, space_name: 'B-02', status: 'pending' }, + ], + locationRows: [ + { id: 4001, warehouse_id: 100000, space_code: 'B-01', custom_name: 'B区-01', custom_barcode: 'BC-B01', zone_id: 20, space_status: 'AVAILABLE', is_enabled: true, pick_sequence: 1, pick_priority: 10 }, + { id: 4002, warehouse_id: 100000, space_code: 'B-02', custom_name: 'B区-02', custom_barcode: 'BC-B02', zone_id: 20, space_status: 'AVAILABLE', is_enabled: true, pick_sequence: 2, pick_priority: 20 }, + ], + storeWarehouseRows: [ + { id: 89, store_id: 2002, warehouse_id: 100000, store_remask: '货主B', warehouse_remask: '仓库B', auth_status: 2, use_status: 1 }, + ], + }); + + const result = await service.query({ + waybill_code: 'WB-9101', + is_full: false, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(result.data.full_display, false); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].order_id, 9101); + assert.equal(result.data.list[0].inspection_status, 'none'); + assert.equal(result.data.summary.total_count, 2); + assert.equal(result.data.summary.pending_review_count, 1); + assert.equal(result.data.summary.reviewed_count, 1); + }); + + it('ctx.user.store_id 缺失时应返回仓库上下文错误', async () => { + const { service } = createHarness({ + withoutUserContext: true, + }); + + const result = await service.query({ + waybill_code: 'WB-NO-CONTEXT', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.equal(result.message, '缺少当前用户仓库上下文 store_id'); + }); + + it('快递号不属于当前仓库时应返回越界/不存在错误', async () => { + const { service } = createHarness({ + storeId: 100000, + orderExpressRows: [ + { order_id: 9301, warehouse_id: 200000, waybill_code: 'WB-OUT-9301' }, + ], + orderRows: [ + { id: 9301, warehouse_id: 200000, store_id: 2003, wave_id: 79, wave_no: 'WAVE-79', inspection_status: 'none' }, + ], + }); + + const result = await service.query({ + waybill_code: 'WB-OUT-9301', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 404); + assert.equal(result.message, '快递号不存在或不属于当前仓库'); + }); + + it('工厂缺失时应返回明确错误而非回退静态订单表', async () => { + const { service } = createHarness({ + withoutFactory: true, + storeId: 100000, + orderExpressRows: [ + { order_id: 9401, warehouse_id: 100000, waybill_code: 'WB-9401' }, + ], + orderRows: [ + { id: 9401, warehouse_id: 100000, store_id: 2004, wave_id: 80, wave_no: 'WAVE-80', inspection_status: 'none' }, + ], + }); + + const result = await service.query({ + waybill_code: 'WB-9401', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 500); + assert.equal(result.message, '订单分表模型工厂不可用'); + }); + + it('工厂返回不可用模型时应返回明确错误', async () => { + const { service } = createHarness({ + factoryReturnsInvalidModel: true, + storeId: 100000, + orderExpressRows: [ + { order_id: 9501, warehouse_id: 100000, waybill_code: 'WB-9501' }, + ], + orderRows: [ + { id: 9501, warehouse_id: 100000, store_id: 2005, wave_id: 81, wave_no: 'WAVE-81', inspection_status: 'none' }, + ], + }); + + const result = await service.query({ + waybill_code: 'WB-9501', + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 500); + assert.equal(result.message, '订单分表模型不可用'); + }); + + it('waybill + 用户仓库上下文命中时不应回退静态 OrderDelivery 模型', async () => { + const { service, staticOrderModelCallCount } = createHarness({ + throwOnStaticOrderModelUse: true, + storeId: 100000, + orderExpressRows: [ + { order_id: 9601, warehouse_id: 100000, waybill_code: 'WB-9601' }, + ], + orderRows: [ + { id: 9601, warehouse_id: 100000, store_id: 2006, wave_id: 82, wave_no: 'WAVE-82', inspection_status: 'none' }, + ], + pickingRows: [ + { id: 21, order_id: 9601, order_item_id: 31, storage_id: 701, quantity: 6, space_id: 5001, space_name: 'C-01', status: 'pending' }, + ], + locationRows: [ + { id: 5001, warehouse_id: 100000, space_code: 'C-01', custom_name: 'C区-01', custom_barcode: 'BC-C01', zone_id: 30, space_status: 'AVAILABLE', is_enabled: true, pick_sequence: 1, pick_priority: 10 }, + ], + storeWarehouseRows: [ + { id: 90, store_id: 2006, warehouse_id: 100000, store_remask: '货主C', warehouse_remask: '仓库C', auth_status: 2, use_status: 1 }, + ], + }); + + const result = await service.query({ + waybill_code: 'WB-9601', + full: true, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(staticOrderModelCallCount.findOne, 0); + assert.equal(staticOrderModelCallCount.findAll, 0); + }); +}); diff --git a/test/app/service/systemMethods/storage/queryReceivingLogs.test.js b/test/app/service/systemMethods/storage/queryReceivingLogs.test.js index d9538e1..7a8aa42 100644 --- a/test/app/service/systemMethods/storage/queryReceivingLogs.test.js +++ b/test/app/service/systemMethods/storage/queryReceivingLogs.test.js @@ -70,4 +70,26 @@ describe('test/app/service/systemMethods/storage/queryReceivingLogs.test.js', () }, }); }); + + it('should not use id/page/pageSize compatibility params', async () => { + const { service, calls } = createHarness(100321); + + await service.queryReceivingLogs({ + id: 777, + receiving_id: 99, + page: 9, + pageSize: 99, + pagination: { + page: 2, + pageSize: 10, + }, + }); + + assert.deepEqual(calls.queryReceivingLogs, { + id: 99, + page: 2, + pageSize: 10, + warehouseId: 100321, + }); + }); }); diff --git a/test/app/service/systems/delivery_order.addOrder.test.js b/test/app/service/systems/delivery_order.addOrder.test.js index cdf0f8b..7d6c22a 100644 --- a/test/app/service/systems/delivery_order.addOrder.test.js +++ b/test/app/service/systems/delivery_order.addOrder.test.js @@ -123,6 +123,16 @@ function createHarness() { }, }, operationLog: { + async createOperationLogs(paramsList = []) { + for (const params of paramsList) { + operationLogCalls.push(params); + sequence.push(`operationLog:${params.operationCode}`); + } + return paramsList.map((params, index) => ({ + id: index + 1, + ...params, + })); + }, async createOperationLog(params) { operationLogCalls.push(params); sequence.push(`operationLog:${params.operationCode}`); diff --git a/test/app/service/systems/express.asyncTask.logs.test.js b/test/app/service/systems/express.asyncTask.logs.test.js new file mode 100644 index 0000000..4365885 --- /dev/null +++ b/test/app/service/systems/express.asyncTask.logs.test.js @@ -0,0 +1,119 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const ExpressService = require('../../../../app/service/systems/express'); + +/** + * 创建 asyncTask 日志回归测试上下文。 + * + * @return {{ service: ExpressService, calls: Object }} 测试服务与调用记录。 + */ +function createAsyncTaskHarness() { + const calls = { + pendingExceptionPayloads: [], + operationLogs: [], + hardDeletePayloads: [], + }; + + const ctx = { + app: { + Sequelize: { + Op: { + in: 'in', + }, + }, + }, + user: { + store_id: 100000, + employees_id: '9001', + employees_name: '测试员A', + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + orderPendingException: { + markPendingException(payload) { + calls.pendingExceptionPayloads.push(payload); + }, + }, + operationLog: { + async createOperationLogs(payloads = []) { + calls.operationLogs.push(...payloads); + return payloads; + }, + async createOperationLog(payload) { + calls.operationLogs.push(payload); + return payload; + }, + }, + }, + }, + }; + + const service = new ExpressService(ctx); + service.hardDeleteWaybillAsyncOrderExpressRows = async (orders, options) => { + calls.hardDeletePayloads.push({ orders, options }); + }; + + return { + service, + calls, + }; +} + +describe('test/app/service/systems/express.asyncTask.logs.test.js', () => { + it('should write failure order logs when async task fails before createWaybillCode', async () => { + const { service, calls } = createAsyncTaskHarness(); + + await service.asyncTask( + [{ id: 301, business_key: 7101 }], + { + sys_platform_code: 'taobao', + sys_platform_name: '淘宝', + logistics_name: '中通', + warehouse_id: 100000, + }, + { code: 'polyapi' }, + null + ); + + assert.equal(calls.pendingExceptionPayloads.length, 1); + assert.equal(calls.pendingExceptionPayloads[0].ids[0], 301); + assert.match(calls.pendingExceptionPayloads[0].exception_text, /未配置有效的快递接口/); + + assert.equal(calls.operationLogs.length, 1); + assert.equal(calls.operationLogs[0].operationCode, 'ORDER_EXPRESS_ALLOCATE_FAILED'); + assert.equal(calls.operationLogs[0].businessId, '301'); + assert.equal(calls.operationLogs[0].operator.id, '9001'); + assert.equal(calls.operationLogs[0].operator.name, '测试员A'); + assert.match(calls.operationLogs[0].extras.message, /分配快递失败:/); + + assert.equal(calls.hardDeletePayloads.length, 1); + assert.equal(calls.hardDeletePayloads[0].options.platform_code, 'taobao'); + }); + + it('should support batch rows with order_id when writing failure logs', async () => { + const { service, calls } = createAsyncTaskHarness(); + + await service.asyncTask( + [{ order_id: 302, business_key: 7102 }], + { + sys_platform_code: 'taobao', + sys_platform_name: '淘宝', + logistics_name: '圆通', + warehouse_id: 100000, + }, + null, + { id: 1 } + ); + + assert.equal(calls.operationLogs.length, 1); + assert.equal(calls.operationLogs[0].businessId, '302'); + assert.match(calls.operationLogs[0].extras.message, /未找到订单平台/); + }); +}); diff --git a/test/app/service/systems/express_platform.polyapi.test.js b/test/app/service/systems/express_platform.polyapi.test.js index dfe5f5c..e469793 100644 --- a/test/app/service/systems/express_platform.polyapi.test.js +++ b/test/app/service/systems/express_platform.polyapi.test.js @@ -28,6 +28,7 @@ function createPolyapiHarness(options = {}) { loadExpressList: 0, request: 0, operationLogCreate: 0, + operationLogBatchCreate: 0, operationLogArgsList: [], orderExpressUpdate: 0, orderExpressUpdateArgsList: [], @@ -220,6 +221,13 @@ function createPolyapiHarness(options = {}) { }, }, operationLog: { + async createOperationLogs(payloads = []) { + calls.callSequence.push('operationLog.createOperationLogs'); + calls.operationLogBatchCreate += 1; + calls.operationLogCreate += payloads.length; + calls.operationLogArgsList.push(...payloads); + return payloads; + }, async createOperationLog(payload) { calls.callSequence.push('operationLog.createOperationLog'); calls.operationLogCreate += 1; @@ -306,6 +314,7 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => { assert.equal(calls.storeWarehouseIncrement, 0); assert.equal(calls.storeWarehouseUpdate, 1); assert.equal(calls.printQuantityLogCreate, 1); + assert.equal(calls.operationLogBatchCreate, 1); assert.equal(calls.operationLogCreate, 3); assert.equal(calls.orderExpressUpdateArgsList[0].query.transaction, calls.transactionRef); @@ -335,7 +344,7 @@ describe('test/app/service/systems/express_platform.polyapi.test.js', () => { assert.equal(calls.requestArgs.bizcontent.orders[2].logisticno, 'REAL-WB-103'); const transactionCommitIndex = calls.callSequence.indexOf('transaction.commit'); - const operationLogIndex = calls.callSequence.indexOf('operationLog.createOperationLog'); + const operationLogIndex = calls.callSequence.indexOf('operationLog.createOperationLogs'); assert.ok(transactionCommitIndex > -1); assert.ok(operationLogIndex > transactionCommitIndex); diff --git a/test/app/service/systems/location_zone.deleteZone.test.js b/test/app/service/systems/location_zone.deleteZone.test.js index 548f17c..95d1c96 100644 --- a/test/app/service/systems/location_zone.deleteZone.test.js +++ b/test/app/service/systems/location_zone.deleteZone.test.js @@ -195,4 +195,4 @@ describe('test/app/service/systems/location_zone.deleteZone.test.js', () => { assert.equal(zoneRows[0].deleted_at, null); assert.equal(spaceRows[0].deleted_at, null); }); -}); \ No newline at end of file +}); diff --git a/test/app/service/systems/operation_log.batchCreate.test.js b/test/app/service/systems/operation_log.batchCreate.test.js new file mode 100644 index 0000000..62a9075 --- /dev/null +++ b/test/app/service/systems/operation_log.batchCreate.test.js @@ -0,0 +1,132 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OperationLogService = require('../../../../app/service/systems/operation_log'); + +/** + * 创建 operation_log 批量写入测试桩。 + * + * @param {Object} [options={}] 测试选项。 + * @return {{ service: OperationLogService, calls: Object }} 服务实例与调用记录。 + */ +function createBatchHarness(options = {}) { + const calls = { + createArgs: null, + bulkCreateArgs: null, + createCount: 0, + }; + + const operationLogModel = { + async create(values, createOptions = {}) { + calls.createCount += 1; + calls.createArgs = { values, createOptions }; + return { + id: 1, + ...values, + }; + }, + async bulkCreate(rows, bulkCreateOptions = {}) { + calls.bulkCreateArgs = { rows, bulkCreateOptions }; + if (options.forceBulkError) { + throw new Error('bulk create failed'); + } + return rows.map((row, index) => ({ + id: index + 1, + ...row, + })); + }, + }; + + const app = { + config: {}, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + user: { + platform_code: 'web', + }, + model: { + OperationLog: operationLogModel, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + app.model = ctx.model; + + return { + service: new OperationLogService(ctx), + calls, + }; +} + +describe('test/app/service/systems/operation_log.batchCreate.test.js', () => { + it('should bulk create operation logs and aggregate payloads in one call', async () => { + const { service, calls } = createBatchHarness(); + + const result = await service.createOperationLogs([ + { + businessType: 'order', + businessId: 101, + operationCode: 'ORDER_CREATE', + operator: { id: 1, name: '测试员' }, + extras: { warehouseId: 100000, message: '订单创建' }, + }, + { + businessType: 'order', + businessId: 102, + operationCode: 'ORDER_CREATE', + operator: { id: 1, name: '测试员' }, + extras: { warehouseId: 100000, message: '订单创建2' }, + }, + ]); + + assert.equal(Array.isArray(result), true); + assert.equal(result.length, 2); + assert.ok(calls.bulkCreateArgs); + assert.equal(calls.bulkCreateArgs.rows.length, 2); + assert.equal(calls.bulkCreateArgs.rows[0].business_id, '101'); + assert.equal(calls.bulkCreateArgs.rows[1].business_id, '102'); + assert.equal(calls.bulkCreateArgs.rows[0].platform_code, 'web'); + assert.equal(calls.createCount, 0); + }); + + it('should pass transaction to both single create and bulk create', async () => { + const { service, calls } = createBatchHarness(); + const transaction = { id: 'tx-001' }; + + await service.createOperationLog({ + businessType: 'order', + businessId: 201, + operationCode: 'ORDER_UPDATE', + operator: { id: 9, name: '事务用户' }, + extras: { warehouseId: 100000 }, + transaction, + }); + + assert.equal(calls.createArgs.createOptions.transaction, transaction); + + await service.createOperationLogs([ + { + businessType: 'order', + businessId: 202, + operationCode: 'ORDER_UPDATE', + operator: { id: 9, name: '事务用户' }, + extras: { warehouseId: 100000 }, + }, + ], { + transaction, + }); + + assert.equal(calls.bulkCreateArgs.bulkCreateOptions.transaction, transaction); + }); +}); diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js index 91811ed..815d17f 100644 --- a/test/app/service/systems/order_storage_allocation.test.js +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -142,6 +142,41 @@ function createHarness(options = {}) { Sequelize, }, model: { + async query(sql, options = {}) { + const normalizedSql = String(sql || ''); + + if (normalizedSql.includes('UPDATE wms_stock_warehouse')) { + const replacements = options.replacements || {}; + const stockIds = Array.isArray(replacements.stockIds) + ? replacements.stockIds.map(item => Number(item)).filter(item => Number.isFinite(item) && item > 0) + : []; + + for (const stockId of stockIds) { + const matchedRow = stockRows.find(row => Number(row.id) === stockId); + if (!matchedRow) { + continue; + } + + const quantityKey = Object.keys(replacements).find(key => { + if (!key.startsWith('stockId_')) { + return false; + } + + return Number(replacements[key]) === stockId; + }); + + if (!quantityKey) { + continue; + } + + const suffix = quantityKey.slice('stockId_'.length); + const deltaQuantity = Number(replacements[`quantity_${suffix}`] || 0); + matchedRow.locked_quantity = Number(matchedRow.locked_quantity || 0) + deltaQuantity; + } + } + + return [[], { affectedRows: 0 }]; + }, async transaction() { return { LOCK: { diff --git a/test/app/service/systems/storage.receiving.reject.test.js b/test/app/service/systems/storage.receiving.reject.test.js index 4744070..7ebeb83 100644 --- a/test/app/service/systems/storage.receiving.reject.test.js +++ b/test/app/service/systems/storage.receiving.reject.test.js @@ -156,4 +156,4 @@ describe('test/app/service/systems/storage.receiving.reject.test.js', () => { }, ]); }); -}); \ No newline at end of file +}); diff --git a/test/app/service/systems/storage.receiving.review.test.js b/test/app/service/systems/storage.receiving.review.test.js index 1372f07..52c9281 100644 --- a/test/app/service/systems/storage.receiving.review.test.js +++ b/test/app/service/systems/storage.receiving.review.test.js @@ -148,4 +148,4 @@ describe('test/app/service/systems/storage.receiving.review.test.js', () => { assert.equal(calls.transactionCommitCount, 0); assert.equal(calls.transactionRollbackCount, 1); }); -}); \ No newline at end of file +});