diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 4f4e166..0c82863 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -42,6 +42,35 @@ const buildListResponse = pageContract => ({ data: { type: pageContract, description: '分页数据:page / pageSize / total / list' }, }); +/** 店铺基础字段契约(列表与详情共用) */ +const shopItem = { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + code: { type: 'string', description: '店铺编码(平台店铺ID / 自定义编码 / OMS 前缀自动生成)' }, + name: { type: 'string', description: '店铺名称' }, + platform: { type: 'string', description: '所属平台:taobao/pdd/douyin/jd/other' }, + contact_name: { type: 'string', description: '联系人' }, + contact_phone: { type: 'string', description: '联系电话' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + extra: { type: 'string', description: '扩展配置 JSON' }, + remark: { type: 'string', description: '备注' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, +}; + +/** 仓库基础字段契约(列表与详情共用,不含接口配置列表) */ +const warehouseBaseItem = { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + code: { type: 'string', description: '仓库编码(系统自动生成,WH 前缀)' }, + name: { type: 'string', description: '仓库名称' }, + type: { type: 'string', description: '仓库类型:wms/erp/other' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, +}; + module.exports = { baseResponse, @@ -106,11 +135,35 @@ module.exports = { resetPasswordRequest: { password: { type: 'string', required: true, description: '新密码(明文),服务端重新生成盐值并加盐哈希' }, }, + sendLoginCodeRequest: { + email: { type: 'string', required: true, description: '已注册的邮箱,用于接收 6 位登录验证码' }, + }, + emailLoginRequest: { + email: { type: 'string', required: true, description: '已注册的邮箱' }, + code: { type: 'string', required: true, description: '邮箱收到的 6 位验证码' }, + }, + sendResetCodeRequest: { + email: { type: 'string', required: true, description: '已注册的邮箱,用于接收 4 位重置验证码' }, + }, + resetPasswordByCodeRequest: { + email: { type: 'string', required: true, description: '已注册的邮箱' }, + code: { type: 'string', required: true, description: '邮箱收到的 4 位验证码' }, + password: { type: 'string', required: true, description: '新密码(明文,不少于 6 位)' }, + }, + updateProfileRequest: { + nickname: { type: 'string', description: '昵称' }, + avatar: { type: 'string', description: '头像URL' }, + email: { type: 'string', description: '邮箱,需格式正确且全局唯一(排除自身)' }, + phone: { type: 'string', description: '手机号' }, + }, + changePasswordRequest: { + old_password: { type: 'string', required: true, description: '原密码(明文),用于身份校验' }, + password: { type: 'string', required: true, description: '新密码(明文),不少于 6 位且不能与原密码相同' }, + }, // ---------- 主体 principals ---------- principalItem: { id: { type: 'integer', description: '主键' }, - code: { type: 'string', description: '主体编码,唯一' }, name: { type: 'string', description: '主体名称' }, type: { type: 'integer', description: '主体类型:1自营 2加盟 3外部' }, contact_name: { type: 'string', description: '联系人' }, @@ -122,8 +175,30 @@ module.exports = { }, principalPage: buildPage('principalItem', '主体列表'), principalListResponse: buildListResponse('principalPage'), + /** 头部主体切换/下拉选择项(带 role 与默认标识) */ + principalOptionItem: { + id: { type: 'integer', description: '主体ID' }, + name: { type: 'string', description: '主体名称' }, + type: { type: 'integer', description: '主体类型:1自营 2加盟 3外部' }, + status: { type: 'integer', description: '主体状态:1启用 0禁用' }, + contact_name: { type: 'string', description: '联系人' }, + contact_phone: { type: 'string', description: '联系电话' }, + role: { type: 'string', description: '当前账号在该主体下的角色,如 owner/member' }, + is_default: { type: 'integer', description: '是否默认主体:1是 0否' }, + relation_status: { type: 'integer', description: '关联状态:1启用 0禁用' }, + }, + principalOptionsResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { + type: 'principalOptionList', + description: '可选主体数据', + }, + }, + principalOptionList: { + list: { type: 'array', itemType: 'principalOptionItem', description: '当前账号可选主体列表' }, + }, createPrincipalRequest: { - code: { type: 'string', required: true, description: '主体编码,唯一' }, name: { type: 'string', required: true, description: '主体名称' }, type: { type: 'integer', description: '主体类型:1自营 2加盟 3外部,默认1' }, contact_name: { type: 'string', description: '联系人' }, @@ -160,22 +235,64 @@ module.exports = { is_default: { type: 'integer', description: '是否默认主体:1是 0否,默认0' }, status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, }, + invitePrincipalUserRequest: { + email: { type: 'string', required: true, description: '被邀请人邮箱,全局唯一,创建后作为登录账号' }, + name: { type: 'string', required: true, description: '用户名称(昵称)' }, + principal_id: { type: 'integer', required: true, description: '目标主体ID,需当前账号已绑定该主体' }, + }, + invitePrincipalUserData: { + user_id: { type: 'integer', description: '新建用户ID' }, + relation_id: { type: 'integer', description: '主体用户关联记录ID' }, + email: { type: 'string', description: '邮箱(即登录账号)' }, + username: { type: 'string', description: '登录账号(此处为邮箱)' }, + nickname: { type: 'string', description: '用户名称' }, + password: { type: 'string', description: '随机生成的初始密码(明文,仅返回一次,需妥善交付)' }, + }, + invitePrincipalUserResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'invitePrincipalUserData', description: '开通结果,含明文初始密码' }, + }, // ---------- 商品 products ---------- productItem: { id: { type: 'integer', description: '主键' }, principal_id: { type: 'integer', description: '所属主体ID' }, - code: { type: 'string', description: '商品编码' }, - name: { type: 'string', description: '商品名称' }, - type: { type: 'integer', description: '商品类型' }, - category: { type: 'string', description: '分类' }, - spec: { type: 'string', description: '规格' }, - unit: { type: 'string', description: '单位' }, - price: { type: 'number', description: '销售价' }, + item_code: { type: 'string', description: '商品编码' }, + goods_code: { type: 'string', description: '货物编码' }, + item_name: { type: 'string', description: '商品名称' }, + sku_property: { type: 'string', description: 'SKU规格' }, + stock_unit: { type: 'string', description: '库存单位' }, + zc_available: { type: 'number', description: '正品可用数量(product_stocks, item_type=ZC)' }, + zc_locked: { type: 'number', description: '正品锁定数量(item_type=ZC)' }, + cc_available: { type: 'number', description: '次品可用数量(item_type=CC)' }, + cc_locked: { type: 'number', description: '次品锁定数量(item_type=CC)' }, + length: { type: 'number', description: '长度(cm)' }, + width: { type: 'number', description: '宽度(cm)' }, + height: { type: 'number', description: '高度(cm)' }, + volume: { type: 'number', description: '体积(cm³)' }, + gross_weight: { type: 'integer', description: '毛重(g)' }, + net_weight: { type: 'integer', description: '净重(g)' }, + category_id: { type: 'integer', description: '分类ID' }, + category_name: { type: 'string', description: '分类名称' }, + item_type: { type: 'integer', description: '商品类型' }, + tag_price: { type: 'number', description: '标价' }, + retail_price: { type: 'number', description: '零售价' }, cost_price: { type: 'number', description: '成本价' }, - image: { type: 'string', description: '图片URL' }, + is_area_sale: { type: 'string', description: '是否区域销售:Y/N' }, + is_sn_mgmt: { type: 'string', description: '是否序列号管理:Y/N' }, + is_shelf_life_mgmt: { type: 'string', description: '是否保质期管理:Y/N' }, + is_batch_mgmt: { type: 'string', description: '是否批次管理:Y/N' }, + barcode: { type: 'string', description: '条码' }, + brand_name: { type: 'string', description: '品牌名称' }, + image: { type: 'string', description: '图片URL(主图,取 images 首张)' }, + images: { type: 'array', itemType: 'string', description: '图片组(URL 数组,首张为主图)' }, status: { type: 'integer', description: '状态:1上架 0下架' }, remark: { type: 'string', description: '备注' }, + create_from: { type: 'string', description: '数据来源:self / qimen / api' }, + stock_id: { type: 'integer', description: '库存ID' }, + warehouse_id: { type: 'integer', description: '仓库ID' }, + store_id: { type: 'integer', description: '门店ID' }, created_at: { type: 'string', description: '创建时间' }, updated_at: { type: 'string', description: '更新时间' }, }, @@ -183,41 +300,94 @@ module.exports = { productListResponse: buildListResponse('productPage'), createProductRequest: { principal_id: { type: 'integer', required: true, description: '所属主体ID' }, - code: { type: 'string', required: true, description: '商品编码,主体内唯一' }, - name: { type: 'string', required: true, description: '商品名称' }, - type: { type: 'integer', description: '商品类型,默认1' }, - category: { type: 'string', description: '分类' }, - spec: { type: 'string', description: '规格' }, - unit: { type: 'string', description: '单位' }, - price: { type: 'number', required: true, description: '销售价' }, + item_code: { type: 'string', required: true, description: '商品编码,主体内唯一' }, + item_name: { type: 'string', required: true, description: '商品名称' }, + goods_code: { type: 'string', description: '货物编码' }, + sku_property: { type: 'string', description: 'SKU规格' }, + stock_unit: { type: 'string', description: '库存单位' }, + item_type: { type: 'integer', description: '商品类型,默认1' }, + category_id: { type: 'integer', description: '分类ID' }, + category_name: { type: 'string', description: '分类名称' }, + brand_name: { type: 'string', description: '品牌名称' }, + barcode: { type: 'string', description: '条码' }, + length: { type: 'number', description: '长度(cm)' }, + width: { type: 'number', description: '宽度(cm)' }, + height: { type: 'number', description: '高度(cm)' }, + volume: { type: 'number', description: '体积(cm³)' }, + gross_weight: { type: 'integer', description: '毛重(g)' }, + net_weight: { type: 'integer', description: '净重(g)' }, + is_area_sale: { type: 'string', description: '是否区域销售:Y/N,默认N' }, + is_sn_mgmt: { type: 'string', description: '是否序列号管理:Y/N,默认N' }, + is_shelf_life_mgmt: { type: 'string', description: '是否保质期管理:Y/N,默认N' }, + is_batch_mgmt: { type: 'string', description: '是否批次管理:Y/N,默认N' }, + tag_price: { type: 'number', description: '标价' }, + retail_price: { type: 'number', required: true, description: '零售价' }, cost_price: { type: 'number', description: '成本价' }, - image: { type: 'string', description: '图片URL' }, + image: { type: 'string', description: '图片URL(主图,取 images 首张)' }, + images: { type: 'array', itemType: 'string', description: '图片组(URL 数组),首张作为主图写入 image' }, status: { type: 'integer', description: '状态:1上架 0下架,默认1' }, remark: { type: 'string', description: '备注' }, }, updateProductRequest: { principal_id: { type: 'integer', description: '所属主体ID' }, - code: { type: 'string', description: '商品编码' }, - name: { type: 'string', description: '商品名称' }, - type: { type: 'integer', description: '商品类型' }, - category: { type: 'string', description: '分类' }, - spec: { type: 'string', description: '规格' }, - unit: { type: 'string', description: '单位' }, - price: { type: 'number', description: '销售价' }, + item_code: { type: 'string', description: '商品编码' }, + item_name: { type: 'string', description: '商品名称' }, + goods_code: { type: 'string', description: '货物编码' }, + sku_property: { type: 'string', description: 'SKU规格' }, + stock_unit: { type: 'string', description: '库存单位' }, + item_type: { type: 'integer', description: '商品类型' }, + category_id: { type: 'integer', description: '分类ID' }, + category_name: { type: 'string', description: '分类名称' }, + brand_name: { type: 'string', description: '品牌名称' }, + barcode: { type: 'string', description: '条码' }, + length: { type: 'number', description: '长度(cm)' }, + width: { type: 'number', description: '宽度(cm)' }, + height: { type: 'number', description: '高度(cm)' }, + volume: { type: 'number', description: '体积(cm³)' }, + gross_weight: { type: 'integer', description: '毛重(g)' }, + net_weight: { type: 'integer', description: '净重(g)' }, + is_area_sale: { type: 'string', description: '是否区域销售:Y/N' }, + is_sn_mgmt: { type: 'string', description: '是否序列号管理:Y/N' }, + is_shelf_life_mgmt: { type: 'string', description: '是否保质期管理:Y/N' }, + is_batch_mgmt: { type: 'string', description: '是否批次管理:Y/N' }, + tag_price: { type: 'number', description: '标价' }, + retail_price: { type: 'number', description: '零售价' }, cost_price: { type: 'number', description: '成本价' }, - image: { type: 'string', description: '图片URL' }, + image: { type: 'string', description: '图片URL(主图)' }, + images: { type: 'array', itemType: 'string', description: '图片组(URL 数组),首张作为主图写入 image' }, status: { type: 'integer', description: '状态:1上架 0下架' }, remark: { type: 'string', description: '备注' }, }, + /** 商品快速搜索列表项(仅启用商品,返回精简字段) */ + productSearchItem: { + id: { type: 'integer', description: '主键' }, + item_code: { type: 'string', description: '商品编码' }, + goods_code: { type: 'string', description: '货物编码' }, + barcode: { type: 'string', description: '条码' }, + item_name: { type: 'string', description: '商品名称' }, + sku_property: { type: 'string', description: 'SKU规格' }, + stock_unit: { type: 'string', description: '库存单位' }, + status: { type: 'integer', description: '状态:1上架 0下架' }, + }, + /** 商品快速搜索响应:data 为命中商品数组(非分页,最多 50 条) */ + productSearchResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'array', itemType: 'productSearchItem', description: '命中的启用商品列表' }, + }, // ---------- 组合商品 combo_products ---------- + comboProductSubItem: { + product_id: { type: 'integer', description: '系统商品ID' }, + quantity: { type: 'integer', description: '该商品在组合中的数量' }, + }, comboProductItem: { id: { type: 'integer', description: '主键' }, principal_id: { type: 'integer', description: '所属主体ID' }, code: { type: 'string', description: '组合商品编码' }, name: { type: 'string', description: '组合商品名称' }, price: { type: 'number', description: '组合售价' }, - items: { type: 'string', description: '组合明细 JSON:[{ product_id: 1, quantity: 2 }]' }, + items: { type: 'array', itemType: 'comboProductSubItem', description: '组合明细(系统商品ID + 数量)' }, status: { type: 'integer', description: '状态:1上架 0下架' }, remark: { type: 'string', description: '备注' }, created_at: { type: 'string', description: '创建时间' }, @@ -230,7 +400,7 @@ module.exports = { code: { type: 'string', required: true, description: '组合商品编码,主体内唯一' }, name: { type: 'string', required: true, description: '组合商品名称' }, price: { type: 'number', required: true, description: '组合售价' }, - items: { type: 'string', description: '组合明细 JSON 数组:[{ product_id: 1, quantity: 2 }]' }, + items: { type: 'array', itemType: 'comboProductSubItem', description: '组合明细:[{ product_id: 1, quantity: 2 }]' }, status: { type: 'integer', description: '状态:1上架 0下架,默认1' }, remark: { type: 'string', description: '备注' }, }, @@ -239,7 +409,7 @@ module.exports = { code: { type: 'string', description: '组合商品编码' }, name: { type: 'string', description: '组合商品名称' }, price: { type: 'number', description: '组合售价' }, - items: { type: 'string', description: '组合明细 JSON 数组' }, + items: { type: 'array', itemType: 'comboProductSubItem', description: '组合明细:[{ product_id: 1, quantity: 2 }],传入则覆盖原明细' }, status: { type: 'integer', description: '状态:1上架 0下架' }, remark: { type: 'string', description: '备注' }, }, @@ -318,6 +488,218 @@ module.exports = { status: { type: 'integer', description: '状态:1启用 0禁用' }, }, + // ---------- 仓库 warehouses ---------- + /** 仓库接口配置(一个仓库可有多条) */ + warehouseApiItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + warehouse_id: { type: 'integer', description: '所属仓库ID' }, + name: { type: 'string', description: '接口配置名称' }, + type: { type: 'string', description: '接口类型,当前系统仅支持 qimen(类奇门JSON接口),由服务端固定写入' }, + base_url: { type: 'string', description: '接口基础地址' }, + app_key: { type: 'string', description: '应用Key' }, + app_secret: { type: 'string', description: '应用密钥(建议加密存储)' }, + callback_url: { type: 'string', description: '对外通用回调接口地址(POST /openapi),外部系统据此回调 OMS,系统参数 method/app_key/timestamp/sign 由调用方拼接' }, + extra: { type: 'string', description: '接口配置项值 JSON 对象({ 字段名: 值 }),由 /api/warehouse-apis/{id}/fields 单独维护,未配置的字段按硬编码默认值读取' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + warehouseApiPage: buildPage('warehouseApiItem', '仓库接口配置列表'), + warehouseApiListResponse: buildListResponse('warehouseApiPage'), + + /** 接口连通性测试结果 */ + warehouseApiTestData: { + ok: { type: 'boolean', description: 'WMS 心跳是否成功(code 命中成功码)' }, + code: { type: 'integer', description: 'WMS 返回的业务码' }, + message: { type: 'string', description: 'WMS 返回提示' }, + error: { type: 'string', description: '连接异常信息(网络/DNS/超时等)' }, + wms: { type: 'object', description: 'WMS 原始返回(index.ping 响应)' }, + }, + warehouseApiTestResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'warehouseApiTestData', description: '连通性测试结果' }, + }, + + /** 对外 API 请求记录(OMS → 外部 WMS) */ + apiOutboundLogItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + warehouse_id: { type: 'integer', description: '关联仓库ID' }, + warehouse_api_id: { type: 'integer', description: '使用的接口配置ID' }, + api_type: { type: 'string', description: '接口类型,如 qimen' }, + method: { type: 'string', description: 'WMS 方法名,如 index.ping / singleitem.synchronize' }, + url: { type: 'string', description: '完整请求地址(sign 已脱敏)' }, + request_headers: { type: 'string', description: '请求头 JSON' }, + request_body: { type: 'string', description: '请求报文 JSON' }, + response_status: { type: 'integer', description: 'HTTP 状态码' }, + response_body: { type: 'string', description: '响应报文' }, + is_success: { type: 'integer', description: '传输层是否成功:1是 0否' }, + business_code: { type: 'string', description: 'WMS 业务码' }, + business_message: { type: 'string', description: 'WMS 业务提示' }, + error: { type: 'string', description: '异常信息' }, + duration: { type: 'integer', description: '耗时(毫秒)' }, + created_at: { type: 'string', description: '创建时间' }, + }, + apiOutboundLogPage: buildPage('apiOutboundLogItem', '对外API请求记录列表'), + apiOutboundLogListResponse: buildListResponse('apiOutboundLogPage'), + createWarehouseApiRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + warehouse_id: { type: 'integer', required: true, description: '所属仓库ID' }, + name: { type: 'string', required: true, description: '接口配置名称' }, + type: { type: 'string', description: '接口类型,可不传;当前系统仅支持 qimen(类奇门JSON接口),服务端固定写入' }, + base_url: { type: 'string', description: '接口基础地址' }, + app_key: { type: 'string', description: '应用Key' }, + app_secret: { type: 'string', description: '应用密钥' }, + status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, + remark: { type: 'string', description: '备注' }, + }, + updateWarehouseApiRequest: { + name: { type: 'string', description: '接口配置名称' }, + base_url: { type: 'string', description: '接口基础地址' }, + app_key: { type: 'string', description: '应用Key' }, + app_secret: { type: 'string', description: '应用密钥' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + }, + + /** 配置项下拉选项 */ + warehouseApiFieldOption: { + label: { type: 'string', description: '选项文案' }, + value: { type: 'string', description: '选项值' }, + }, + /** 仓库接口配置项分组(硬编码,前端按组渲染小标题) */ + warehouseApiFieldGroup: { + key: { type: 'string', description: '分组标识,字段通过 group 归属' }, + label: { type: 'string', description: '分组标题' }, + description: { type: 'string', description: '分组说明(可含配置帮助文档链接)' }, + }, + /** 仓库接口配置项定义(硬编码清单,前端按 group 分组、按 type 渲染表单控件) */ + warehouseApiFieldItem: { + key: { type: 'string', description: '字段名,落库到 warehouse_apis.extra 的 key' }, + group: { type: 'string', description: '所属分组标识(warehouseApiFieldGroup.key)' }, + label: { type: 'string', description: '字段标签(表单展示)' }, + type: { type: 'string', description: '字段类型:text/textarea/number/switch/select/password/json' }, + required: { type: 'boolean', description: '是否必填' }, + defaultValue: { type: 'string', description: '未填写时的默认值(文本 / 数字 / 布尔)' }, + options: { type: 'array', itemType: 'warehouseApiFieldOption', description: 'type=select 时的可选项' }, + min: { type: 'number', description: 'type=number 时的最小值' }, + max: { type: 'number', description: 'type=number 时的最大值' }, + placeholder: { type: 'string', description: '输入框提示文案' }, + description: { type: 'string', description: '字段说明' }, + }, + /** 字段定义(分组 + 类型枚举 + 字段清单) */ + warehouseApiFieldSchema: { + types: { type: 'array', itemType: 'string', description: '字段类型枚举' }, + groups: { type: 'array', itemType: 'warehouseApiFieldGroup', description: '字段分组列表(前端按此渲染小标题)' }, + fields: { type: 'array', itemType: 'warehouseApiFieldItem', description: '配置项定义列表' }, + }, + warehouseApiFieldSchemaResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'warehouseApiFieldSchema', description: '配置项分组、定义与类型枚举' }, + }, + /** 字段值:{ 字段名: 值 } JSON 对象 */ + warehouseApiFieldValues: { + api_id: { type: 'integer', description: '接口配置ID' }, + values: { type: 'string', description: '字段值 JSON 对象 { 字段名: 值 },按类型归一化;未配置的字段返回硬编码默认值' }, + }, + warehouseApiFieldValuesResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'warehouseApiFieldValues', description: '接口配置项值' }, + }, + updateWarehouseApiFieldValuesRequest: { + values: { type: 'string', required: true, description: '字段值对象 { 字段key: 值 },整体覆盖保存;按字段类型校验,字段名需在硬编码清单内' }, + }, + + /** 仓库(仅基础信息,接口配置通过 apis 带出) */ + warehouseItem: { + ...warehouseBaseItem, + apis: { type: 'array', itemType: 'warehouseApiItem', description: '仓库接口配置列表' }, + }, + warehousePage: buildPage('warehouseItem', '仓库列表'), + warehouseListResponse: buildListResponse('warehousePage'), + warehouseStats: { + api_count: { type: 'integer', description: '接口配置数' }, + api_enabled_count: { type: 'integer', description: '启用中的接口配置数' }, + inbound_order_count: { type: 'integer', description: '关联入库单数' }, + outbound_order_count: { type: 'integer', description: '关联出库单数' }, + }, + warehouseDetailItem: { + ...warehouseBaseItem, + stats: { type: 'warehouseStats', description: '关联统计:接口配置数 / 入库出库单数' }, + }, + warehouseDetailResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'warehouseDetailItem', description: '仓库详情(含关联统计 stats)' }, + }, + + /** 仓库下的商品行:商品基础字段 + 该仓库的推送状态(来自 warehouse_products 关联表) */ + warehouseProductItem: { + id: { type: 'integer', description: '商品ID' }, + item_code: { type: 'string', description: '商品编码' }, + goods_code: { type: 'string', description: '货物编码' }, + item_name: { type: 'string', description: '商品名称' }, + sku_property: { type: 'string', description: 'SKU规格' }, + barcode: { type: 'string', description: '条码' }, + image: { type: 'string', description: '主图' }, + status: { type: 'integer', description: '商品状态:1启用 0禁用' }, + pushed: { type: 'boolean', description: '是否已推送到该仓库,未建立关联时为 false' }, + pushed_at: { type: 'string', description: '最近一次推送时间,未推送为 null' }, + }, + warehouseProductPage: buildPage('warehouseProductItem', '仓库商品列表'), + warehouseProductListResponse: buildListResponse('warehouseProductPage'), + + /** 单条商品推送结果 */ + warehouseProductPushResult: { + product_id: { type: 'integer', description: '商品ID' }, + item_code: { type: 'string', description: '商品编码(成功时返回)' }, + success: { type: 'boolean', description: '是否推送成功' }, + message: { type: 'string', description: '结果说明' }, + }, + /** 商品推送请求体 */ + warehouseProductPushRequest: { + product_ids: { type: 'array', itemType: 'integer', required: true, description: '待推送的商品ID列表' }, + }, + /** 库存同步(覆盖本地数量)单项 */ + warehouseInventorySyncItem: { + product_id: { type: 'integer', required: true, description: '商品ID' }, + wms_quantity: { type: 'number', required: true, description: '外部 WMS 库存数量(目标值)' }, + }, + /** 库存同步(覆盖本地数量)请求体 */ + warehouseInventorySyncRequest: { + items: { type: 'array', itemType: 'warehouseInventorySyncItem', required: true, description: '待同步商品列表(商品ID + 外部 WMS 库存数量)' }, + }, + /** 商品推送响应数据(逐条汇总) */ + warehouseProductPushData: { + total: { type: 'integer', description: '请求推送数' }, + success: { type: 'integer', description: '成功数' }, + failed: { type: 'integer', description: '失败数' }, + results: { type: 'array', itemType: 'warehouseProductPushResult', description: '逐条推送结果' }, + }, + warehouseProductPushResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'warehouseProductPushData', description: '推送汇总结果' }, + }, + createWarehouseRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + name: { type: 'string', required: true, description: '仓库名称' }, + type: { type: 'string', description: '仓库类型:wms/erp/other' }, + status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, + remark: { type: 'string', description: '备注' }, + }, + updateWarehouseRequest: { + name: { type: 'string', description: '仓库名称' }, + type: { type: 'string', description: '仓库类型' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + remark: { type: 'string', description: '备注' }, + }, + // ---------- 订单 orders ---------- orderItem: { id: { type: 'integer', description: '主键' }, @@ -344,19 +726,20 @@ module.exports = { createOrderRequest: { order_no: { type: 'string', required: true, description: '业务订单号,唯一' }, principal_id: { type: 'integer', required: true, description: '所属主体ID' }, + shop_id: { type: 'integer', description: '所属店铺ID,可为空' }, + items: { type: 'array', itemType: 'createOrderItemRequest', description: '订单明细,可随订单一次性写入' }, order_type: { type: 'integer', description: '订单类型,默认1' }, - status: { type: 'integer', description: '主状态,默认1(待处理)' }, - wms_status: { type: 'string', description: '外部WMS状态' }, - wms_order_no: { type: 'string', description: '外部WMS单号' }, + wms_status: { type: 'string', description: '外部WMS状态(只读,由 WMS 回调写入)' }, + wms_order_no: { type: 'string', description: '外部WMS单号(只读,由 WMS 回调写入)' }, total_amount: { type: 'number', description: '订单金额' }, pay_amount: { type: 'number', description: '实付金额' }, receiver: { type: 'string', description: '收货人信息 JSON:{ name, phone, address }' }, remark: { type: 'string', description: '备注' }, }, updateOrderRequest: { + shop_id: { type: 'integer', description: '所属店铺ID' }, order_no: { type: 'string', description: '业务订单号' }, order_type: { type: 'integer', description: '订单类型' }, - status: { type: 'integer', description: '主状态:1待处理 2处理中 3已完成 4已取消' }, total_amount: { type: 'number', description: '订单金额' }, pay_amount: { type: 'number', description: '实付金额' }, receiver: { type: 'string', description: '收货人信息 JSON' }, @@ -376,4 +759,676 @@ module.exports = { status: { type: 'integer', description: '同时更新主状态(可选)' }, message: { type: 'string', description: '状态说明/异常原因' }, }, + /** 整单解析明细的结果 */ + parseOrderItemsData: { + total: { type: 'integer', description: '明细总数' }, + resolved: { type: 'integer', description: '本次解析成功数' }, + failed: { type: 'integer', description: '解析失败数' }, + }, + parseOrderItemsResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'parseOrderItemsData', description: '解析结果' }, + }, + + // ---------- 订单明细 order_items ---------- + orderItemLine: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + order_id: { type: 'integer', description: '所属订单ID' }, + shop_id: { type: 'integer', description: '所属店铺ID' }, + product_id: { type: 'integer', description: '系统商品ID,为空表示未解析出商品' }, + combo_product_id: { type: 'integer', description: '组合商品ID' }, + shop_product_id: { type: 'integer', description: '命中的店铺商品ID' }, + item_type: { type: 'integer', description: '明细类型:0未识别 1普通商品 2组合商品' }, + parse_status: { type: 'integer', description: '解析状态:0未解析 1已解析 2解析失败' }, + parse_msg: { type: 'string', description: '解析失败原因' }, + outer_item_id: { type: 'string', description: '平台商品ID' }, + outer_sku_id: { type: 'string', description: '平台规格ID' }, + sku_code: { type: 'string', description: '商家编码' }, + name: { type: 'string', description: '商品名称(快照)' }, + spec: { type: 'string', description: '规格(快照)' }, + image: { type: 'string', description: '图片(快照)' }, + quantity: { type: 'number', description: '数量' }, + price: { type: 'number', description: '单价' }, + total_amount: { type: 'number', description: '明细金额' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + orderItemLinePage: buildPage('orderItemLine', '订单明细列表'), + orderItemLineListResponse: buildListResponse('orderItemLinePage'), + createOrderItemRequest: { + order_id: { type: 'integer', required: true, description: '所属订单ID' }, + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + shop_id: { type: 'integer', description: '店铺ID,不传则继承订单的店铺' }, + product_id: { type: 'integer', description: '系统商品ID,传入即视为已解析' }, + combo_product_id: { type: 'integer', description: '组合商品ID,传入即视为已解析' }, + shop_product_id: { type: 'integer', description: '命中的店铺商品ID' }, + outer_item_id: { type: 'string', description: '平台商品ID' }, + outer_sku_id: { type: 'string', description: '平台规格ID' }, + sku_code: { type: 'string', description: '商家编码,用于解析匹配' }, + name: { type: 'string', description: '商品名称(快照)' }, + spec: { type: 'string', description: '规格(快照)' }, + image: { type: 'string', description: '图片(快照)' }, + quantity: { type: 'number', description: '数量' }, + price: { type: 'number', description: '单价' }, + total_amount: { type: 'number', description: '明细金额' }, + raw: { type: 'string', description: '平台返回的明细原始数据 JSON' }, + }, + updateOrderItemRequest: { + shop_id: { type: 'integer', description: '店铺ID' }, + product_id: { type: 'integer', description: '系统商品ID' }, + combo_product_id: { type: 'integer', description: '组合商品ID' }, + shop_product_id: { type: 'integer', description: '店铺商品ID' }, + sku_code: { type: 'string', description: '商家编码' }, + outer_item_id: { type: 'string', description: '平台商品ID' }, + outer_sku_id: { type: 'string', description: '平台规格ID' }, + name: { type: 'string', description: '商品名称(快照)' }, + spec: { type: 'string', description: '规格(快照)' }, + image: { type: 'string', description: '图片(快照)' }, + quantity: { type: 'number', description: '数量' }, + price: { type: 'number', description: '单价' }, + total_amount: { type: 'number', description: '明细金额' }, + }, + + // ---------- 店铺 shops ---------- + shopItem, + shopPage: buildPage('shopItem', '店铺列表'), + shopListResponse: buildListResponse('shopPage'), + shopStats: { + shop_product_count: { type: 'integer', description: '店铺商品数' }, + shop_product_bound_count: { type: 'integer', description: '已绑定系统/组合商品的店铺商品数' }, + order_count: { type: 'integer', description: '关联订单数' }, + order_amount: { type: 'number', description: '关联订单金额合计' }, + latest_order_at: { type: 'string', description: '最近一笔订单创建时间,无订单为空' }, + }, + shopDetailItem: { + ...shopItem, + stats: { type: 'shopStats', description: '关联统计:店铺商品数 / 订单数 / 订单金额等' }, + }, + shopDetailResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'shopDetailItem', description: '店铺详情(含关联统计 stats)' }, + }, + createShopRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + code: { type: 'string', description: '店铺编码,留空则自动生成 OMS 前缀编码;传入时同一主体下唯一' }, + name: { type: 'string', required: true, description: '店铺名称' }, + platform: { type: 'string', description: '平台标识:taobao/pdd/douyin/jd/other' }, + contact_name: { type: 'string', description: '联系人' }, + contact_phone: { type: 'string', description: '联系电话' }, + status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, + extra: { type: 'string', description: '扩展配置 JSON' }, + remark: { type: 'string', description: '备注' }, + }, + updateShopRequest: { + code: { type: 'string', description: '店铺编码' }, + name: { type: 'string', description: '店铺名称' }, + platform: { type: 'string', description: '平台标识' }, + contact_name: { type: 'string', description: '联系人' }, + contact_phone: { type: 'string', description: '联系电话' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + extra: { type: 'string', description: '扩展配置 JSON' }, + remark: { type: 'string', description: '备注' }, + }, + + // ---------- 店铺商品 shop_products ---------- + shopProductItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + shop_id: { type: 'integer', description: '所属店铺ID' }, + outer_item_id: { type: 'string', description: '平台商品ID' }, + outer_sku_id: { type: 'string', description: '平台规格ID' }, + title: { type: 'string', description: '商品标题' }, + outer_code: { type: 'string', description: '商家编码,用于与系统商品匹配' }, + spec: { type: 'string', description: '规格' }, + image: { type: 'string', description: '图片' }, + price: { type: 'number', description: '店铺售价' }, + stock: { type: 'integer', description: '采集到的库存' }, + status: { type: 'integer', description: '店铺商品状态:1在售 0下架' }, + bind_type: { type: 'integer', description: '绑定类型:0未绑定 1系统商品 2组合商品' }, + product_id: { type: 'integer', description: '绑定的系统商品ID' }, + combo_product_id: { type: 'integer', description: '绑定的组合商品ID' }, + synced_at: { type: 'string', description: '最近一次采集时间' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + shopProductPage: buildPage('shopProductItem', '店铺商品列表'), + shopProductListResponse: buildListResponse('shopProductPage'), + createShopProductRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + shop_id: { type: 'integer', required: true, description: '所属店铺ID' }, + outer_item_id: { type: 'string', required: true, description: '平台商品ID' }, + outer_sku_id: { type: 'string', description: '平台规格ID,无规格时为空' }, + title: { type: 'string', description: '商品标题' }, + outer_code: { type: 'string', description: '商家编码' }, + spec: { type: 'string', description: '规格' }, + image: { type: 'string', description: '图片' }, + price: { type: 'number', description: '店铺售价' }, + stock: { type: 'integer', description: '库存' }, + status: { type: 'integer', description: '状态:1在售 0下架,默认1' }, + raw: { type: 'string', description: '采集原始数据 JSON' }, + }, + updateShopProductRequest: { + title: { type: 'string', description: '商品标题' }, + outer_code: { type: 'string', description: '商家编码' }, + spec: { type: 'string', description: '规格' }, + image: { type: 'string', description: '图片' }, + price: { type: 'number', description: '店铺售价' }, + stock: { type: 'integer', description: '库存' }, + status: { type: 'integer', description: '状态:1在售 0下架' }, + raw: { type: 'string', description: '采集原始数据 JSON' }, + }, + /** 店铺商品绑定到系统商品或组合商品 */ + bindShopProductRequest: { + bind_type: { type: 'integer', required: true, description: '绑定类型:0解绑 1系统商品 2组合商品' }, + product_id: { type: 'integer', description: '系统商品ID,bind_type=1 时必填' }, + combo_product_id: { type: 'integer', description: '组合商品ID,bind_type=2 时必填' }, + }, + + // ---------- 入库单 inbound_orders ---------- + inboundOrderItem: { + id: { type: 'integer', description: '主键' }, + bill_no: { type: 'string', description: '入库单号,唯一' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + shop_id: { type: 'integer', description: '来源店铺/仓库ID' }, + inbound_type: { type: 'string', description: '入库单类型(WMS 编码):B2BRK B2B入库 / SCRK 生产入库 / LYRK 领用入库 / CCRK 残次品入库 / CGRK 采购入库 / DBRK 调拨入库 / QTRK 其他入库' }, + status: { type: 'integer', description: '状态:1待入库 2已审核 3已推送 4完成 5已作废 9已取消' }, + supplier: { type: 'string', description: '供应商名称' }, + supplier_code: { type: 'string', description: '供应商编码' }, + operator: { type: 'string', description: '操作人名称' }, + operator_code: { type: 'string', description: '操作员编码' }, + operate_time: { type: 'string', description: '操作时间' }, + purchase_order_code: { type: 'string', description: '采购单号(entryOrderType=CGRK 时使用)' }, + expect_start_time: { type: 'string', description: '预期到货开始时间' }, + expect_end_time: { type: 'string', description: '最迟预期到货时间' }, + logistics_code: { type: 'string', description: '物流公司编码(SF/YTO/ZTO 等)' }, + logistics_name: { type: 'string', description: '物流公司名称' }, + express_code: { type: 'string', description: '运单号' }, + sender_info: { type: 'string', description: '发件人信息 JSON' }, + receiver_info: { type: 'string', description: '收件人信息 JSON' }, + extend_props: { type: 'string', description: '扩展属性 JSON:{ key: value }' }, + total_amount: { type: 'number', description: '单据总金额' }, + remark: { type: 'string', description: '备注' }, + void_at: { type: 'string', description: '作废时间(状态 5=已作废)' }, + void_by: { type: 'integer', description: '作废人ID(关联 users)' }, + void_reason: { type: 'string', description: '作废原因' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + inboundOrderPage: buildPage('inboundOrderItem', '入库单列表'), + inboundOrderListResponse: buildListResponse('inboundOrderPage'), + createInboundOrderRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + shop_id: { type: 'integer', description: '来源店铺/仓库ID' }, + inbound_type: { type: 'string', description: '入库单类型(WMS 编码):B2BRK / SCRK / LYRK / CCRK / CGRK / DBRK / QTRK,默认 CGRK(采购入库)' }, + supplier: { type: 'string', description: '供应商名称' }, + supplier_code: { type: 'string', description: '供应商编码' }, + operator: { type: 'string', description: '操作人名称' }, + operator_code: { type: 'string', description: '操作员编码' }, + operate_time: { type: 'string', description: '操作时间' }, + purchase_order_code: { type: 'string', description: '采购单号' }, + expect_start_time: { type: 'string', description: '预期到货开始时间' }, + expect_end_time: { type: 'string', description: '最迟预期到货时间' }, + logistics_code: { type: 'string', description: '物流公司编码' }, + logistics_name: { type: 'string', description: '物流公司名称' }, + express_code: { type: 'string', description: '运单号' }, + sender_info: { type: 'string', description: '发件人信息 JSON' }, + receiver_info: { type: 'string', description: '收件人信息 JSON' }, + extend_props: { type: 'string', description: '扩展属性 JSON:{ key: value }' }, + total_amount: { type: 'number', description: '单据总金额' }, + remark: { type: 'string', description: '备注' }, + items: { type: 'array', itemType: 'createStockItemRequest', description: '明细,可随单一次性写入' }, + }, + updateInboundOrderRequest: { + shop_id: { type: 'integer', description: '来源店铺/仓库ID' }, + inbound_type: { type: 'string', description: '入库单类型(WMS 编码):B2BRK / SCRK / LYRK / CCRK / CGRK / DBRK / QTRK' }, + supplier: { type: 'string', description: '供应商名称' }, + supplier_code: { type: 'string', description: '供应商编码' }, + operator: { type: 'string', description: '操作人名称' }, + operator_code: { type: 'string', description: '操作员编码' }, + operate_time: { type: 'string', description: '操作时间' }, + purchase_order_code: { type: 'string', description: '采购单号' }, + expect_start_time: { type: 'string', description: '预期到货开始时间' }, + expect_end_time: { type: 'string', description: '最迟预期到货时间' }, + logistics_code: { type: 'string', description: '物流公司编码' }, + logistics_name: { type: 'string', description: '物流公司名称' }, + express_code: { type: 'string', description: '运单号' }, + sender_info: { type: 'string', description: '发件人信息 JSON' }, + receiver_info: { type: 'string', description: '收件人信息 JSON' }, + extend_props: { type: 'string', description: '扩展属性 JSON:{ key: value }' }, + total_amount: { type: 'number', description: '单据总金额' }, + remark: { type: 'string', description: '备注' }, + }, + voidInboundOrderRequest: { + void_reason: { type: 'string', description: '作废原因(选填)' }, + }, + + // ---------- 出库单 outbound_orders ---------- + outboundOrderItem: { + id: { type: 'integer', description: '主键' }, + bill_no: { type: 'string', description: '出库单号,唯一' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + shop_id: { type: 'integer', description: '目标店铺/仓库ID' }, + outbound_type: { type: 'string', description: '出库单类型(WMS 编码):PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单' }, + status: { type: 'integer', description: '状态:1待出库 2已审核 3已推送 4完成 5已作废 9已取消' }, + customer: { type: 'string', description: '客户/收货方' }, + operator: { type: 'string', description: '操作人' }, + total_amount: { type: 'number', description: '单据总金额' }, + remark: { type: 'string', description: '备注' }, + void_at: { type: 'string', description: '作废时间(状态 5=已作废)' }, + void_by: { type: 'integer', description: '作废人ID(关联 users)' }, + void_reason: { type: 'string', description: '作废原因' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + outboundOrderPage: buildPage('outboundOrderItem', '出库单列表'), + outboundOrderListResponse: buildListResponse('outboundOrderPage'), + createOutboundOrderRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + shop_id: { type: 'integer', description: '目标店铺/仓库ID' }, + outbound_type: { type: 'string', description: '出库单类型(WMS 编码):PTCK / DBCK / B2BCK / QTCK / CGTH,默认 PTCK(普通出库单)' }, + customer: { type: 'string', description: '客户/收货方' }, + operator: { type: 'string', description: '操作人' }, + total_amount: { type: 'number', description: '单据总金额' }, + remark: { type: 'string', description: '备注' }, + items: { type: 'array', itemType: 'createStockItemRequest', description: '明细,可随单一次性写入' }, + }, + updateOutboundOrderRequest: { + shop_id: { type: 'integer', description: '目标店铺/仓库ID' }, + outbound_type: { type: 'string', description: '出库单类型(WMS 编码):PTCK / DBCK / B2BCK / QTCK / CGTH' }, + customer: { type: 'string', description: '客户/收货方' }, + operator: { type: 'string', description: '操作人' }, + total_amount: { type: 'number', description: '单据总金额' }, + remark: { type: 'string', description: '备注' }, + }, + voidOutboundOrderRequest: { + void_reason: { type: 'string', description: '作废原因(选填)' }, + }, + + // ---------- 发货单(订单)order_deliveries ---------- + orderDeliveryItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID(货主,对应 WMS store_id)' }, + warehouse_id: { type: 'integer', description: '仓库ID(关联 warehouses)' }, + shop_id: { type: 'integer', description: '店铺ID(关联 shops)' }, + warehouse_code: { type: 'string', description: '仓库编码(报文 warehouseCode 快照)' }, + delivery_order_code: { type: 'string', description: '发货单号,系统生成(FH_{自增id});历史搬迁数据保留原订单号' }, + order_type: { type: 'string', description: '订单类型(ORDER 组):JYCK 一般交易出库单 / HHCK 换货出库 / BFCK 补发出库' }, + order_flag: { type: 'string', description: '订单标记(手工单不填写)' }, + pre_delivery_order_code: { type: 'string', description: '预发货单号(手工单不填写)' }, + pre_delivery_order_id: { type: 'string', description: '预发货单ID(手工单不填写)' }, + is_urgency: { type: 'string', description: '是否紧急:Y / N(默认 N)' }, + invoice_flag: { type: 'string', description: '是否需要发票:Y / N(默认 N)' }, + source_platform_code: { type: 'string', description: '来源平台编码(手工单不填写)' }, + source_platform_name: { type: 'string', description: '来源平台名称(手工单不填写)' }, + shop_nick: { type: 'string', description: '店铺名称(取所选店铺,系统派生)' }, + seller_nick: { type: 'string', description: '卖家名称(手工单不填写)' }, + buyer_nick: { type: 'string', description: '买家名称(手工单不填写)' }, + buyer_message: { type: 'string', description: '买家留言(手工单不填写)' }, + seller_message: { type: 'string', description: '卖家留言(表单「留言」写入此字段)' }, + place_order_time: { type: 'string', description: '下单时间(手工单取创建时间,系统自动写入)' }, + pay_time: { type: 'string', description: '支付时间(手工单不填写)' }, + pay_no: { type: 'string', description: '支付单号(手工单不填写)' }, + operate_time: { type: 'string', description: 'ERP 审核时间(手工单不填写)' }, + total_amount: { type: 'number', description: '订单总金额' }, + item_amount: { type: 'number', description: '商品总金额(Σ 明细 计划数量 × 实际单价,由明细增删改后自动重算)' }, + discount_amount: { type: 'number', description: '订单折扣金额' }, + freight: { type: 'number', description: '快递费用' }, + ar_amount: { type: 'number', description: '应收金额' }, + got_amount: { type: 'number', description: '已收金额' }, + logistics_code: { type: 'string', description: '物流公司编码(快递公司字典 express_companies.code,如 SF/YTO)' }, + logistics_name: { type: 'string', description: '物流公司名称(随编码自动带出)' }, + express_code: { type: 'string', description: '运单号(面单号,系统托管:取号/回写链路写入,手工不填)' }, + logistics_area_code: { type: 'string', description: '快递区域编码(大头笔,系统托管)' }, + operator_name: { type: 'string', description: 'ERP 审核人(奇门 operatorName)' }, + oaid_order_source_code: { type: 'string', description: 'OAID 订单来源编码(手工单不填写)' }, + source_order_codes: { type: 'string', description: '来源订单号集合(手工单不填写)' }, + extend_props: { type: 'string', description: '请求级扩展属性 JSON(手工单固定写入 labels: 手工单)' }, + need_oms_waybill: { type: 'integer', description: '是否回 OMS 取号:1是 0否(手工创建恒为 0,该字段留给其他来源订单,暂不处理)' }, + name: { type: 'string', description: '收件人姓名(receiverInfo.name)' }, + tel: { type: 'string', description: '收件人电话(receiverInfo.tel)' }, + mobile: { type: 'string', description: '收件人移动电话(receiverInfo.mobile)' }, + email: { type: 'string', description: '收件人邮箱(receiverInfo.email)' }, + country_code: { type: 'string', description: '国家编码(receiverInfo.countryCode)' }, + province: { type: 'string', description: '省份(receiverInfo.province)' }, + city: { type: 'string', description: '城市(receiverInfo.city)' }, + area: { type: 'string', description: '区县(receiverInfo.area)' }, + town: { type: 'string', description: '街道/镇(receiverInfo.town)' }, + detail_address: { type: 'string', description: '详细地址(receiverInfo.detailAddress)' }, + zip_code: { type: 'string', description: '邮编(receiverInfo.zipCode)' }, + oaid: { type: 'string', description: 'OAID(receiverInfo.oaid,手工单不填写)' }, + status: { type: 'integer', description: '状态:1待处理 2已审核 3已推送 4已完成 5已作废 9已取消' }, + item_total: { type: 'number', description: '商品总数(明细计划数量合计,系统托管)' }, + item_kind: { type: 'integer', description: '商品种类数(不重复商品数,系统托管)' }, + audit_by: { type: 'integer', description: '审核人ID(关联 users,待处理→已审核时写入)' }, + audit_time: { type: 'string', description: '审核时间' }, + void_at: { type: 'string', description: '作废时间(状态 5=已作废)' }, + void_by: { type: 'integer', description: '作废人ID(关联 users)' }, + void_reason: { type: 'string', description: '作废原因' }, + created_by: { type: 'integer', description: '创建人ID(关联 users)' }, + pushed_at: { type: 'string', description: 'WMS 推送时间' }, + wms_push_result: { type: 'string', description: 'WMS 推送结果 JSON(外部单号/返回码/消息/原始报文)' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + orderDeliveryPage: buildPage('orderDeliveryItem', '发货单列表'), + orderDeliveryListResponse: buildListResponse('orderDeliveryPage'), + createOrderDeliveryRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入(服务端强制使用,请求体不可篡改)' }, + warehouse_id: { type: 'integer', required: true, description: '仓库ID(关联 warehouses,需属于当前主体;推送 WMS 依赖该仓库的 warehouseCode 与接口配置)' }, + shop_id: { type: 'integer', description: '店铺ID(关联 shops,需属于当前主体)' }, + warehouse_code: { type: 'string', description: '仓库编码,缺省按 warehouse_id 取 warehouses.code' }, + order_type: { type: 'string', description: '订单类型(ORDER 组枚举):JYCK 一般交易出库单 / HHCK 换货出库 / BFCK 补发出库,默认 JYCK' }, + is_urgency: { type: 'string', description: '是否紧急:Y / N,默认 N' }, + invoice_flag: { type: 'string', description: '是否需要发票:Y / N,默认 N' }, + seller_message: { type: 'string', description: '留言(写入奇门 sellerMessage/卖家留言)' }, + total_amount: { type: 'number', description: '订单总金额' }, + discount_amount: { type: 'number', description: '订单折扣金额' }, + freight: { type: 'number', description: '快递费用' }, + ar_amount: { type: 'number', description: '应收金额' }, + got_amount: { type: 'number', description: '已收金额' }, + logistics_code: { type: 'string', description: '物流公司编码(快递公司字典 express_companies.code)' }, + logistics_name: { type: 'string', description: '物流公司名称(随编码自动带出)' }, + operator_name: { type: 'string', description: 'ERP 审核人' }, + name: { type: 'string', required: true, description: '收件人姓名(receiverInfo.name,必填)' }, + tel: { type: 'string', description: '收件人电话(receiverInfo.tel),与 mobile 至少填一个' }, + mobile: { type: 'string', description: '收件人移动电话(receiverInfo.mobile),与 tel 至少填一个' }, + email: { type: 'string', description: '收件人邮箱(receiverInfo.email)' }, + country_code: { type: 'string', description: '国家编码(receiverInfo.countryCode)' }, + province: { type: 'string', required: true, description: '省份(receiverInfo.province,必填)' }, + city: { type: 'string', required: true, description: '城市(receiverInfo.city,必填)' }, + area: { type: 'string', required: true, description: '区县(receiverInfo.area,必填)' }, + town: { type: 'string', required: true, description: '街道/镇(receiverInfo.town,必填)' }, + detail_address: { type: 'string', description: '详细地址(receiverInfo.detailAddress)' }, + zip_code: { type: 'string', description: '邮编(receiverInfo.zipCode)' }, + items: { type: 'array', itemType: 'orderDeliveryLine', description: '子表商品明细(奇门 orderLines),随单在同一事务内创建;每行 plan_qty 与 actual_price 必填' }, + }, + updateOrderDeliveryRequest: { + warehouse_id: { type: 'integer', description: '仓库ID' }, + shop_id: { type: 'integer', description: '店铺ID' }, + warehouse_code: { type: 'string', description: '仓库编码(缺省按 warehouse_id 自动补)' }, + order_type: { type: 'string', description: '订单类型(ORDER 组枚举):JYCK / HHCK / BFCK' }, + is_urgency: { type: 'string', description: '是否紧急:Y / N' }, + invoice_flag: { type: 'string', description: '是否需要发票:Y / N' }, + seller_message: { type: 'string', description: '留言(写入奇门 sellerMessage/卖家留言)' }, + total_amount: { type: 'number', description: '订单总金额' }, + discount_amount: { type: 'number', description: '订单折扣金额' }, + freight: { type: 'number', description: '快递费用' }, + ar_amount: { type: 'number', description: '应收金额' }, + got_amount: { type: 'number', description: '已收金额' }, + logistics_code: { type: 'string', description: '物流公司编码(快递公司字典 express_companies.code)' }, + logistics_name: { type: 'string', description: '物流公司名称(随编码自动带出)' }, + operator_name: { type: 'string', description: 'ERP 审核人' }, + name: { type: 'string', description: '收件人姓名' }, + tel: { type: 'string', description: '收件人电话' }, + mobile: { type: 'string', description: '收件人移动电话' }, + email: { type: 'string', description: '收件人邮箱' }, + country_code: { type: 'string', description: '国家编码' }, + province: { type: 'string', description: '省份' }, + city: { type: 'string', description: '城市' }, + area: { type: 'string', description: '区县' }, + town: { type: 'string', description: '街道/镇' }, + detail_address: { type: 'string', description: '详细地址' }, + zip_code: { type: 'string', description: '邮编' }, + }, + + // ---------- 发货单明细(子表商品明细)order_delivery_items ---------- + orderDeliveryLine: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + order_delivery_id: { type: 'integer', description: '所属发货单ID(order_deliveries.id)' }, + order_line_no: { type: 'string', description: '行号(orderLineNo),缺省按行序号' }, + item_id: { type: 'integer', description: 'WMS 内部商品ID(itemId,取自 warehouse_products.wms_item_id)' }, + item_code: { type: 'string', description: '商品编码(itemCode)' }, + item_name: { type: 'string', description: '商品名称(itemName)' }, + plan_qty: { type: 'number', description: '计划数量(planQty),必须大于 0' }, + actual_price: { type: 'number', description: '实际单价(actualPrice);手工创建/维护明细时必填,不小于 0' }, + retail_price: { type: 'number', description: '零售价(retailPrice)' }, + ext_code: { type: 'string', description: '外部编码(extCode)' }, + inventory_type: { type: 'string', description: '库存类型:ZP 正品 / CC 残次(推送 WMS 时映射 ZC/CC)' }, + owner_code: { type: 'string', description: '货主编码(ownerCode)' }, + source_order_code: { type: 'string', description: '来源订单编码(sourceOrderCode)' }, + sub_source_order_code: { type: 'string', description: '子来源订单编码(subSourceOrderCode)' }, + stock_id: { type: 'integer', description: 'WMS 仓库库存ID(stockId,手工建单直传)' }, + extend_props: { type: 'string', description: '扩展属性(extendProps)JSON' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + orderDeliveryLinePage: buildPage('orderDeliveryLine', '发货单明细列表'), + orderDeliveryItemListResponse: buildListResponse('orderDeliveryLinePage'), + createOrderDeliveryItemRequest: { + order_delivery_id: { type: 'integer', required: true, description: '所属发货单ID(必填)' }, + order_line_no: { type: 'string', description: '行号(orderLineNo),缺省按行序号' }, + item_id: { type: 'integer', description: 'WMS 内部商品ID(itemId);与 item_code 至少填一个' }, + item_code: { type: 'string', description: '商品编码(itemCode);与 item_id 至少填一个' }, + item_name: { type: 'string', description: '商品名称(itemName)' }, + plan_qty: { type: 'number', required: true, description: '计划数量(planQty),必须大于 0' }, + actual_price: { type: 'number', required: true, description: '实际单价(actualPrice),必填,不小于 0' }, + retail_price: { type: 'number', description: '零售价(retailPrice)' }, + ext_code: { type: 'string', description: '外部编码(extCode)' }, + inventory_type: { type: 'string', description: '库存类型:ZP 正品 / CC 残次,默认 ZP' }, + owner_code: { type: 'string', description: '货主编码(ownerCode)' }, + source_order_code: { type: 'string', description: '来源订单编码(sourceOrderCode)' }, + sub_source_order_code: { type: 'string', description: '子来源订单编码(subSourceOrderCode)' }, + stock_id: { type: 'integer', description: 'WMS 仓库库存ID(stockId,手工建单直传)' }, + extend_props: { type: 'string', description: '扩展属性(extendProps)JSON' }, + }, + updateOrderDeliveryItemRequest: { + order_line_no: { type: 'string', description: '行号(orderLineNo)' }, + item_id: { type: 'integer', description: 'WMS 内部商品ID(itemId)' }, + item_code: { type: 'string', description: '商品编码(itemCode)' }, + item_name: { type: 'string', description: '商品名称(itemName)' }, + plan_qty: { type: 'number', description: '计划数量(planQty),必须大于 0' }, + actual_price: { type: 'number', description: '实际单价(actualPrice)' }, + retail_price: { type: 'number', description: '零售价(retailPrice)' }, + ext_code: { type: 'string', description: '外部编码(extCode)' }, + inventory_type: { type: 'string', description: '库存类型:ZP 正品 / CC 残次' }, + owner_code: { type: 'string', description: '货主编码(ownerCode)' }, + source_order_code: { type: 'string', description: '来源订单编码(sourceOrderCode)' }, + sub_source_order_code: { type: 'string', description: '子来源订单编码(subSourceOrderCode)' }, + stock_id: { type: 'integer', description: 'WMS 仓库库存ID(stockId)' }, + extend_props: { type: 'string', description: '扩展属性(extendProps)JSON' }, + }, + voidOrderDeliveryRequest: { + void_reason: { type: 'string', description: '作废原因(选填)' }, + }, + parseReceiverRequest: { + text: { type: 'string', required: true, description: '待识别的收件人文本(姓名/电话/地址等,最多 2000 字)' }, + }, + changeDeliveryWarehouseRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入(服务端强制使用)' }, + warehouse_id: { type: 'integer', required: true, description: '目标发货仓库ID(需属于当前主体,会同步刷新 warehouse_code 快照)' }, + ids: { type: 'array', itemType: 'integer', description: '按选中切换:发货单ID数组(scope_by=ids 时必传且不能为空)' }, + scope_by: { type: 'string', description: '切换范围类型:ids=按勾选(忽略筛选条件)/ filter=按筛选条件(忽略 ids);不传时按「有 ids 走 ids,否则走条件」兜底' }, + dry_run: { type: 'boolean', description: 'true=仅预览影响范围(不写库并返回样例单据),默认 false 执行切换' }, + delivery_order_code: { type: 'string', description: '条件:发货单号,模糊匹配' }, + status: { type: 'integer', description: '条件:状态 1待处理 2已审核 3已推送 4已完成 5已作废 9已取消' }, + order_type: { type: 'string', description: '条件:订单类型 JYCK / HHCK / BFCK' }, + shop_id: { type: 'integer', description: '条件:店铺ID' }, + from_warehouse_id: { type: 'integer', description: '条件:原发货仓库ID' }, + }, + orderDeliveryBatchRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入(服务端强制使用)' }, + scope_by: { type: 'string', description: '操作范围类型:ids=按勾选(ids 必传)/ filter=按筛选条件(忽略 ids);不传时按「有 ids 走 ids,否则走条件」兜底' }, + ids: { type: 'array', itemType: 'integer', description: '按勾选操作:发货单ID数组(scope_by=ids 时必传且不能为空)' }, + dry_run: { type: 'boolean', description: 'true=仅预览影响范围(不写库并返回样例单据),默认 false 执行' }, + delivery_order_code: { type: 'string', description: '条件:发货单号,模糊匹配' }, + status: { type: 'integer', description: '条件:状态 1待处理 2已审核 3已推送 4已完成 5已作废 9已取消' }, + order_type: { type: 'string', description: '条件:订单类型 JYCK / HHCK / BFCK' }, + shop_id: { type: 'integer', description: '条件:店铺ID' }, + from_warehouse_id: { type: 'integer', description: '条件:原发货仓库ID' }, + }, + orderDeliveryBatchResult: { + matched: { type: 'integer', description: '命中范围条数' }, + affected: { type: 'integer', description: '实际处理条数(审核生效条数 / 本次推送尝试条数)' }, + auditable: { type: 'integer', description: '批量审核:可审核条数(待处理 1)' }, + pushable: { type: 'integer', description: '批量推送:可推送条数(已审核 2)' }, + skipped: { type: 'integer', description: '范围内不符合条件的条数(按状态跳过)' }, + pending_rest: { type: 'integer', description: '批量推送:超出单次上限、留给定时任务继续推送的条数' }, + pushed: { type: 'integer', description: '批量推送:本批成功条数' }, + failed: { type: 'integer', description: '批量推送:本批失败条数(对方明确失败或超过重试上限,已退回待审核)' }, + retry: { type: 'integer', description: '批量推送:本批待重试条数(无响应/超时,保留已审核由定时任务重试)' }, + skipped_push: { type: 'integer', description: '批量推送:跳过条数(仓库未配置接口或在重试间隔内)' }, + details: { type: 'array', itemType: 'orderDeliveryBatchDetail', description: '批量推送:逐条结果' }, + samples: { type: 'array', itemType: 'orderDeliveryWarehouseChangeSample', description: '样例单据(最多 10 条,仅 dry_run=true 返回)' }, + scope: { type: 'object', description: '操作范围 { by: "ids" | "filter", ids: [] }' }, + }, + orderDeliveryBatchDetail: { + id: { type: 'integer', description: '发货单ID' }, + ok: { type: 'boolean', description: '是否推送成功' }, + skipped: { type: 'boolean', description: '是否跳过(仓库未配置接口 / 重试间隔内 / 状态不符)' }, + retry: { type: 'boolean', description: '是否待重试(无响应或超时,保留已审核)' }, + message: { type: 'string', description: '结果说明' }, + }, + orderDeliveryWarehouseChangeSample: { + id: { type: 'integer', description: '发货单ID' }, + delivery_order_code: { type: 'string', description: '发货单号' }, + status: { type: 'integer', description: '状态' }, + warehouse_name: { type: 'string', description: '当前仓库名称(或仓库编码)' }, + }, + orderDeliveryWarehouseChangeResult: { + target_warehouse: { type: 'object', description: '目标仓库 { id, code, name }' }, + matched: { type: 'integer', description: '命中范围条数(已排除本就属于目标仓库的单据)' }, + switchable: { type: 'integer', description: '可切换条数:待处理(1) / 已审核(2)' }, + blocked: { type: 'integer', description: '不可切换条数:已推送(3) / 已完成(4) / 已作废(5) / 已取消(9)' }, + blocked_reason: { type: 'object', description: '不可切换的状态分布,如 { "3": 2, "4": 1 }' }, + same_warehouse: { type: 'integer', description: '范围内已属于目标仓库的条数(无需切换)' }, + scope: { type: 'object', description: '切换范围 { by: "ids" | "filter", ids: [] }' }, + samples: { type: 'array', itemType: 'orderDeliveryWarehouseChangeSample', description: '样例单据(最多 5 条,仅 dry_run=true 返回)' }, + updated: { type: 'integer', description: '本次实际更新条数(仅 dry_run=false 返回)' }, + }, + + // ---------- 快递公司字典 express_companies ---------- + expressCompanyItem: { + id: { type: 'integer', description: '主键' }, + code: { type: 'string', description: '快递公司编码(行业/WMS 标准编码,如 SF/YTO/ZTO)' }, + name: { type: 'string', description: '快递公司名称(如 顺丰速运)' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + sort: { type: 'integer', description: '排序(下拉展示顺序,越小越靠前)' }, + remark: { type: 'string', description: '备注' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + expressCompanyPage: buildPage('expressCompanyItem', '快递公司列表'), + expressCompanyListResponse: buildListResponse('expressCompanyPage'), + createExpressCompanyRequest: { + code: { type: 'string', required: true, description: '快递公司编码(必填,统一转大写,全局唯一,如 SF)' }, + name: { type: 'string', required: true, description: '快递公司名称(必填,如 顺丰速运)' }, + status: { type: 'integer', description: '状态:1启用 0禁用,默认 1' }, + sort: { type: 'integer', description: '排序,默认 0' }, + remark: { type: 'string', description: '备注' }, + }, + updateExpressCompanyRequest: { + code: { type: 'string', description: '快递公司编码(统一转大写,全局唯一)' }, + name: { type: 'string', description: '快递公司名称' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + sort: { type: 'integer', description: '排序' }, + remark: { type: 'string', description: '备注' }, + }, + + // ---------- 出入库明细 stock_items ---------- + stockItemItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + bill_type: { type: 'integer', description: '单据类型:1入库 2出库' }, + bill_id: { type: 'integer', description: '关联单据头ID' }, + shop_id: { type: 'integer', description: '店铺/仓库ID' }, + product_id: { type: 'integer', description: '系统商品ID' }, + combo_product_id: { type: 'integer', description: '组合商品ID' }, + shop_product_id: { type: 'integer', description: '店铺商品ID' }, + name: { type: 'string', description: '商品名称(快照)' }, + code: { type: 'string', description: '商品编码(快照)' }, + inventory_type: { type: 'string', description: '库存类型:ZP=正品 CC=残次,默认 ZP' }, + spec: { type: 'string', description: '规格(快照)' }, + unit: { type: 'string', description: '单位' }, + quantity: { type: 'number', description: '数量' }, + plan_in_qty: { type: 'number', description: '应入数量(入库明细,默认取明细数量)' }, + actual_in_qty: { type: 'number', description: '已入数量(入库明细,WMS 收货确认回推)' }, + plan_out_qty: { type: 'number', description: '应出数量(出库明细,默认取明细数量)' }, + actual_out_qty: { type: 'number', description: '已出数量(出库明细,WMS 发货回推)' }, + price: { type: 'number', description: '单价' }, + total_amount: { type: 'number', description: '明细金额' }, + remark: { type: 'string', description: '备注' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + stockItemPage: buildPage('stockItemItem', '明细列表'), + stockItemListResponse: buildListResponse('stockItemPage'), + createStockItemRequest: { + bill_id: { type: 'integer', required: true, description: '所属单据ID' }, + bill_type: { type: 'integer', required: true, description: '单据类型:1入库 2出库' }, + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + shop_id: { type: 'integer', description: '店铺/仓库ID' }, + product_id: { type: 'integer', description: '系统商品ID' }, + combo_product_id: { type: 'integer', description: '组合商品ID' }, + shop_product_id: { type: 'integer', description: '店铺商品ID' }, + name: { type: 'string', description: '商品名称(快照)' }, + code: { type: 'string', description: '商品编码(快照)' }, + inventory_type: { type: 'string', description: '库存类型:ZP=正品 CC=残次,默认 ZP' }, + spec: { type: 'string', description: '规格(快照)' }, + unit: { type: 'string', description: '单位' }, + quantity: { type: 'number', required: true, description: '数量' }, + price: { type: 'number', description: '单价' }, + total_amount: { type: 'number', description: '明细金额' }, + remark: { type: 'string', description: '备注' }, + }, + updateStockItemRequest: { + shop_id: { type: 'integer', description: '店铺/仓库ID' }, + product_id: { type: 'integer', description: '系统商品ID' }, + combo_product_id: { type: 'integer', description: '组合商品ID' }, + shop_product_id: { type: 'integer', description: '店铺商品ID' }, + name: { type: 'string', description: '商品名称(快照)' }, + code: { type: 'string', description: '商品编码(快照)' }, + inventory_type: { type: 'string', description: '库存类型:ZP=正品 CC=残次,默认 ZP' }, + spec: { type: 'string', description: '规格(快照)' }, + unit: { type: 'string', description: '单位' }, + quantity: { type: 'number', description: '数量' }, + price: { type: 'number', description: '单价' }, + total_amount: { type: 'number', description: '明细金额' }, + remark: { type: 'string', description: '备注' }, + }, + + // ---------- 文件资源 files ---------- + fileItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + hash: { type: 'string', description: '文件内容 SHA256(去重依据)' }, + name: { type: 'string', description: '原始文件名' }, + ext: { type: 'string', description: '扩展名(含点,如 .png)' }, + mime: { type: 'string', description: 'MIME 类型' }, + size: { type: 'integer', description: '文件大小(字节)' }, + path: { type: 'string', description: '相对存储路径:主体ID/年/月/日/hash.ext' }, + url: { type: 'string', description: '访问地址,可直接用于 img src' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + /** 上传结果:deduped=true 表示命中已有文件,未重复上传 */ + fileUploadData: { + id: { type: 'integer', description: '主键' }, + hash: { type: 'string', description: '文件内容 SHA256' }, + name: { type: 'string', description: '原始文件名' }, + ext: { type: 'string', description: '扩展名' }, + size: { type: 'integer', description: '文件大小(字节)' }, + path: { type: 'string', description: '相对存储路径' }, + url: { type: 'string', description: '访问地址' }, + deduped: { type: 'boolean', description: 'true=命中已有文件(未重复上传)' }, + }, + fileUploadResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'fileUploadData', description: '上传结果' }, + }, + filePage: buildPage('fileItem', '文件列表'), + fileListResponse: buildListResponse('filePage'), + checkFilesRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + hashes: { type: 'array', itemType: 'string', description: '待查验的文件 SHA256 列表,最多 100 个' }, + }, + fileCheckResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'array', itemType: 'fileItem', description: '命中的文件列表,可直接复用其 url' }, + }, }; diff --git a/backend/app/controller/auth.js b/backend/app/controller/auth.js index c627b97..8cf2d5b 100644 --- a/backend/app/controller/auth.js +++ b/backend/app/controller/auth.js @@ -92,6 +92,8 @@ class AuthController extends Controller { const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn }); await user.update({ last_login_at: new Date() }); + // 登录时间变更,失效用户缓存,下次请求重新加载 + await ctx.service.cache.invalidateUser(user.id); ctx.body = { code: 0, @@ -190,9 +192,8 @@ class AuthController extends Controller { */ async profile() { const { ctx } = this; - const user = await ctx.model.User.findByPk(ctx.userId, { - attributes: { exclude: [ 'password', 'salt' ] }, - }); + // JWT 中间件已从缓存加载用户,这里不再查库 + const user = ctx.user || await ctx.service.cache.getUser(ctx.userId); if (!user) { ctx.status = 404; @@ -200,7 +201,306 @@ class AuthController extends Controller { return; } - ctx.body = { code: 0, message: 'success', data: user }; + // 返回用户所属主体列表,供前端判断是否已创建主体(多租户隔离);走缓存的可选主体列表 + const options = await ctx.service.cache.getUserPrincipalOptions(ctx.userId); + const principals = options.map(item => ({ id: item.id, name: item.name })); + + ctx.body = { code: 0, message: 'success', data: { ...user, principals } }; + } + + /** + * @summary 发送邮箱登录验证码 + * @description 公开接口,无需登录:邮箱必须已注册,发送 6 位数字验证码(10 分钟有效); + * 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429 + * @router post /api/auth/email-login/code + * @request body sendLoginCodeRequest *body + * @response 200 baseResponse success + */ + async sendLoginCode() { + const { ctx, app } = this; + const { email } = ctx.request.body; + + if (!email || !EMAIL_REGEX.test(email)) { + ctx.status = 400; + ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; + return; + } + + const user = await ctx.model.User.findOne({ where: { email } }); + if (!user) { + ctx.status = 400; + ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' }; + return; + } + + const result = await sendCode(app, email, { + userId: user.id, + ip: ctx.ip, + scene: 'login', + length: 6, + subject: 'OMS 邮箱登录验证码', + }); + if (!result.ok) { + ctx.status = 429; + ctx.body = { code: 429, message: result.message }; + return; + } + + ctx.body = { + code: 0, + message: 'success', + data: { email, expires_in: CODE_TTL }, + }; + } + + /** + * @summary 邮箱验证码登录 + * @description 公开接口,无需登录:校验 6 位验证码(通过后立即失效), + * 校验通过后直接签发 JWT;账号被禁用时返回 403 + * @router post /api/auth/email-login + * @request body emailLoginRequest *body + * @response 200 loginResponse success + */ + async loginByEmailCode() { + const { ctx, app } = this; + const { email, code } = ctx.request.body; + + if (!email || !EMAIL_REGEX.test(email)) { + ctx.status = 400; + ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; + return; + } + if (!code) { + ctx.status = 400; + ctx.body = { code: 400, message: 'email 与 code 为必填项' }; + return; + } + + const user = await ctx.model.User.findOne({ where: { email } }); + if (!user) { + ctx.status = 400; + ctx.body = { code: 400, message: '该邮箱未注册,请先注册账号' }; + return; + } + + if (Number(user.status) !== 1) { + ctx.status = 403; + ctx.body = { code: 403, message: '账号已禁用' }; + return; + } + + const verified = await verifyCode(app, email, code, 'login'); + if (!verified) { + ctx.status = 400; + ctx.body = { code: 400, message: '验证码错误或已过期' }; + return; + } + + const expiresIn = app.config.jwt.expiresIn || '2h'; + const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn }); + + await user.update({ last_login_at: new Date() }); + + ctx.body = { + code: 0, + message: 'success', + data: { + token, + user_id: user.id, + expires_in: this.parseExpiresIn(expiresIn), + }, + }; + } + + /** + * @summary 发送密码重置验证码 + * @description 公开接口,无需登录:邮箱必须已注册,发送 4 位数字验证码(10 分钟有效); + * 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429 + * @router post /api/auth/reset-password/code + * @request body sendResetCodeRequest *body + * @response 200 baseResponse success + */ + async sendResetCode() { + const { ctx, app } = this; + const { email } = ctx.request.body; + + if (!email || !EMAIL_REGEX.test(email)) { + ctx.status = 400; + ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; + return; + } + + // 找回密码:邮箱必须已注册 + const user = await ctx.model.User.findOne({ where: { email } }); + if (!user) { + ctx.status = 400; + ctx.body = { code: 400, message: '该邮箱未注册' }; + return; + } + + const result = await sendCode(app, email, { + userId: user.id, + ip: ctx.ip, + scene: 'reset-password', + length: 4, + subject: 'OMS 密码重置验证码', + }); + if (!result.ok) { + ctx.status = 429; + ctx.body = { code: 429, message: result.message }; + return; + } + + ctx.body = { + code: 0, + message: 'success', + data: { email, expires_in: CODE_TTL }, + }; + } + + /** + * @summary 通过邮箱验证码重置密码 + * @description 公开接口,无需登录:校验 4 位验证码(通过后立即失效), + * 然后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位 + * @router post /api/auth/reset-password + * @request body resetPasswordByCodeRequest *body + * @response 200 baseResponse success + */ + async resetPasswordByCode() { + const { ctx, app } = this; + const { email, code, password } = ctx.request.body; + + if (!email || !EMAIL_REGEX.test(email)) { + ctx.status = 400; + ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; + return; + } + if (!code || !password) { + ctx.status = 400; + ctx.body = { code: 400, message: '验证码与新密码均为必填项' }; + return; + } + if (String(password).length < 6) { + ctx.status = 400; + ctx.body = { code: 400, message: '新密码长度不能少于 6 位' }; + return; + } + + const user = await ctx.model.User.findOne({ where: { email } }); + if (!user) { + ctx.status = 400; + ctx.body = { code: 400, message: '该邮箱未注册' }; + return; + } + + const verified = await verifyCode(app, email, code, 'reset-password'); + if (!verified) { + ctx.status = 400; + ctx.body = { code: 400, message: '验证码错误或已过期' }; + return; + } + + const salt = generateSalt(); + await user.update({ salt, password: hashPassword(password, salt) }); + await ctx.service.cache.invalidateUser(user.id); + ctx.body = { code: 0, message: 'success', data: { id: user.id } }; + } + + /** + * @summary 修改当前登录用户资料 + * @description 自助服务:仅可修改昵称、邮箱、手机号与头像,不涉及密码、账号与状态; + * 邮箱需校验格式与全局唯一性(排除自身) + * @router put /api/auth/profile + * @apikey + * @request body updateProfileRequest *body + * @response 200 baseResponse success + */ + async updateProfile() { + const { ctx } = this; + const user = await ctx.model.User.findByPk(ctx.userId); + + if (!user) { + ctx.status = 404; + ctx.body = { code: 404, message: '用户不存在' }; + return; + } + + const { nickname, email, phone, avatar } = ctx.request.body; + + if (email && !EMAIL_REGEX.test(email)) { + ctx.status = 400; + ctx.body = { code: 400, message: '邮箱格式不正确' }; + return; + } + if (email) { + const exist = await ctx.model.User.findOne({ where: { email } }); + if (exist && Number(exist.id) !== Number(user.id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '该邮箱已被使用' }; + return; + } + } + + const patch = {}; + if (nickname !== undefined) patch.nickname = nickname; + if (email !== undefined) patch.email = email; + if (phone !== undefined) patch.phone = phone; + if (avatar !== undefined) patch.avatar = avatar; + + await user.update(patch); + await ctx.service.cache.invalidateUser(user.id); + + const updated = await ctx.model.User.findByPk(user.id, { + attributes: { exclude: [ 'password', 'salt' ] }, + }); + ctx.body = { code: 0, message: 'success', data: updated }; + } + + /** + * @summary 修改当前登录用户密码 + * @description 自助服务:需校验原密码,通过后重新生成盐值并更新加盐哈希密码;新密码不少于 6 位且不能与原密码相同 + * @router put /api/auth/password + * @apikey + * @request body changePasswordRequest *body + * @response 200 baseResponse success + */ + async changePassword() { + const { ctx } = this; + const { old_password: oldPassword, password } = ctx.request.body; + + if (!oldPassword || !password) { + ctx.status = 400; + ctx.body = { code: 400, message: '原密码与新密码均为必填项' }; + return; + } + if (String(password).length < 6) { + ctx.status = 400; + ctx.body = { code: 400, message: '新密码长度不少于 6 位' }; + return; + } + + const user = await ctx.model.User.findByPk(ctx.userId); + if (!user) { + ctx.status = 404; + ctx.body = { code: 404, message: '用户不存在' }; + return; + } + + if (hashPassword(oldPassword, user.salt) !== user.password) { + ctx.status = 400; + ctx.body = { code: 400, message: '原密码不正确' }; + return; + } + if (oldPassword === password) { + ctx.status = 400; + ctx.body = { code: 400, message: '新密码不能与原密码相同' }; + return; + } + + const salt = generateSalt(); + await user.update({ salt, password: hashPassword(password, salt) }); + await ctx.service.cache.invalidateUser(user.id); + ctx.body = { code: 0, message: 'success', data: { id: user.id } }; } /** diff --git a/backend/app/controller/expressCompany.js b/backend/app/controller/expressCompany.js new file mode 100644 index 0000000..9b4bfbd --- /dev/null +++ b/backend/app/controller/expressCompany.js @@ -0,0 +1,170 @@ +'use strict'; + +const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); + +/** + * @controller ExpressCompanyController 快递公司字典管理 + * 通用字典(不区分主体),供发货单等单据选择物流公司;code 为行业/WMS 标准编码 + */ +class ExpressCompanyController extends Controller { + /** + * @summary 快递公司列表 + * @description 分页查询快递公司字典,支持按编码、名称与状态过滤 + * @router get /api/express-companies + * @apikey + * @request query integer page 页码,默认 1 + * @request query integer pageSize 每页条数,默认 20 + * @request query string code 快递编码,支持模糊匹配 + * @request query string name 快递公司名称,支持模糊匹配 + * @request query integer status 状态:1启用 0禁用 + * @response 200 expressCompanyListResponse success + */ + async index() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const { page, pageSize, offset, limit } = parsePagination(ctx.query); + const { code, name, status } = ctx.query; + + const where = {}; + if (code) where.code = { [Op.like]: `%${String(code).trim().toUpperCase()}%` }; + if (name) where.name = { [Op.like]: `%${name}%` }; + if (status !== undefined && status !== '') where.status = Number(status); + + const { count, rows } = await ctx.model.ExpressCompany.findAndCountAll({ + where, + offset, + limit, + order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], + }); + + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + } + + /** + * @summary 快递公司下拉(仅启用) + * @description 供发货单等表单选择物流公司,按 sort 升序返回 + * @router get /api/express-companies/select + * @apikey + * @response 200 baseResponse success + */ + async select() { + const { ctx } = this; + const rows = await ctx.model.ExpressCompany.findAll({ + where: { status: 1 }, + attributes: [ 'id', 'code', 'name' ], + order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], + }); + ctx.body = { code: 0, message: 'success', data: rows }; + } + + /** + * @summary 快递公司详情 + * @router get /api/express-companies/{id} + * @apikey + * @request path integer *id 快递公司主键ID + * @response 200 baseResponse success + */ + async show() { + const { ctx } = this; + const item = await ctx.model.ExpressCompany.findByPk(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '快递公司不存在' }; + return; + } + ctx.body = { code: 0, message: 'success', data: item }; + } + + /** + * @summary 新增快递公司 + * @description 编码全局唯一(统一转大写),名称与编码为必填项 + * @router post /api/express-companies + * @apikey + * @request body createExpressCompanyRequest *body + * @response 200 baseResponse success + */ + async create() { + const { ctx } = this; + const body = ctx.request.body || {}; + const code = String(body.code || '').trim().toUpperCase(); + const name = String(body.name || '').trim(); + + if (!code || !name) { + ctx.status = 400; + ctx.body = { code: 400, message: 'code(快递编码)与 name(快递公司名称)为必填项' }; + return; + } + + const exist = await ctx.model.ExpressCompany.findOne({ where: { code } }); + if (exist) { + ctx.status = 400; + ctx.body = { code: 400, message: `快递编码 ${code} 已存在` }; + return; + } + + const item = await ctx.model.ExpressCompany.create({ ...body, code, name }); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 更新快递公司 + * @description 未传入的字段保持原值;编码唯一(统一转大写) + * @router put /api/express-companies/{id} + * @apikey + * @request path integer *id 快递公司主键ID + * @request body updateExpressCompanyRequest *body + * @response 200 baseResponse success + */ + async update() { + const { ctx } = this; + const item = await ctx.model.ExpressCompany.findByPk(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '快递公司不存在' }; + return; + } + + const body = { ...(ctx.request.body || {}) }; + if (body.code !== undefined) { + const code = String(body.code).trim().toUpperCase(); + if (!code) { + ctx.status = 400; + ctx.body = { code: 400, message: 'code(快递编码)不能为空' }; + return; + } + const exist = await ctx.model.ExpressCompany.findOne({ where: { code } }); + if (exist && Number(exist.id) !== Number(item.id)) { + ctx.status = 400; + ctx.body = { code: 400, message: `快递编码 ${code} 已存在` }; + return; + } + body.code = code; + } + + await item.update(body); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 删除快递公司 + * @description 物理删除字典项;如已停用建议改用 status=0 而非删除 + * @router delete /api/express-companies/{id} + * @apikey + * @request path integer *id 快递公司主键ID + * @response 200 baseResponse success + */ + async destroy() { + const { ctx } = this; + const item = await ctx.model.ExpressCompany.findByPk(ctx.params.id); + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '快递公司不存在' }; + return; + } + await item.destroy(); + ctx.body = { code: 0, message: 'success' }; + } +} + +module.exports = ExpressCompanyController; diff --git a/backend/app/controller/file.js b/backend/app/controller/file.js new file mode 100644 index 0000000..7fe5bf3 --- /dev/null +++ b/backend/app/controller/file.js @@ -0,0 +1,231 @@ +'use strict'; + +const { Controller } = require('egg'); +const crypto = require('crypto'); +const fs = require('fs'); +const fsp = require('fs/promises'); +const path = require('path'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); + +/** 允许上传的图片扩展名(与 config.multipart.whitelist 保持一致) */ +const ALLOWED_EXT = [ '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg' ]; + +/** 扩展名 -> Content-Type,供 raw 接口回写响应头 */ +const MIME = { + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.png': 'image/png', + '.gif': 'image/gif', + '.bmp': 'image/bmp', + '.webp': 'image/webp', + '.svg': 'image/svg+xml', +}; + +/** raw 访问路径必须形如「主体ID/年/月/日/hash.ext」,非法路径(含 .. 穿越)一律拒绝 */ +const RAW_PATH_RE = /^\d+\/\d{4}\/\d{2}\/\d{2}\/[a-f0-9]{64}\.[a-z0-9]+$/; + +const pad2 = num => String(num).padStart(2, '0'); + +/** 流式计算文件 SHA256,避免大图整块读入内存 */ +function sha256File(filepath) { + return new Promise((resolve, reject) => { + const hash = crypto.createHash('sha256'); + fs.createReadStream(filepath) + .on('data', chunk => hash.update(chunk)) + .on('end', () => resolve(hash.digest('hex'))) + .on('error', reject); + }); +} + +/** 临时目录与上传目录可能不在同一磁盘(EXDEV),先尝试 rename,失败再复制 */ +async function moveFile(from, to) { + try { + await fsp.rename(from, to); + } catch (err) { + if (err.code !== 'EXDEV') throw err; + await fsp.copyFile(from, to); + await fsp.unlink(from); + } +} + +/** + * @controller FileController 文件资源管理 + */ +class FileController extends Controller { + /** + * @summary 文件列表 + * @description 分页查询当前主体已上传的文件资源 + * @router get /api/files + * @apikey + * @request query integer page 页码,默认 1 + * @request query integer pageSize 每页条数,默认 20 + * @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) + * @request query string keyword 关键词,模糊匹配原始文件名 + * @response 200 fileListResponse success + */ + async index() { + const { ctx, app } = this; + const Op = app.Sequelize.Op; + const { page, pageSize, offset, limit } = parsePagination(ctx.query); + const keyword = (ctx.query.keyword || '').trim(); + + const where = { principal_id: ctx.state.principalId }; + if (keyword) where.name = { [Op.like]: `%${keyword}%` }; + + const { count, rows } = await ctx.model.File.findAndCountAll({ + where, + offset, + limit, + order: [[ 'id', 'DESC' ]], + }); + + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + } + + /** + * @summary 文件去重预检 + * @description 上传前按内容 SHA256 批量查验,命中的文件直接复用已有 URL,无需重复上传 + * @router post /api/files/check + * @apikey + * @request body checkFilesRequest *body + * @response 200 fileCheckResponse success + */ + async check() { + const { ctx } = this; + const hashes = ctx.request.body.hashes; + + if (!Array.isArray(hashes) || !hashes.length) { + ctx.body = { code: 0, message: 'success', data: [] }; + return; + } + + const rows = await ctx.model.File.findAll({ + where: { + principal_id: ctx.state.principalId, + hash: hashes.slice(0, 100).map(String), + }, + }); + ctx.body = { code: 0, message: 'success', data: rows }; + } + + /** + * @summary 上传文件 + * @description 单文件上传(表单字段 file,仅图片)。按内容 SHA256 在当前主体内去重: + * 命中已有记录直接返回其 URL,不重复落盘;未命中则按「主体ID/年/月/日」分目录存储,文件名为内容 hash + * @router post /api/files/upload + * @apikey + * @request formData file *file 图片文件 + * @request formData integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) + * @response 200 fileUploadResponse success + */ + async upload() { + const { ctx, app } = this; + const principalId = ctx.state.principalId; + const files = ctx.request.files || []; + + if (!files.length) { + ctx.status = 400; + ctx.body = { code: 400, message: '未接收到上传文件(表单字段名 file)' }; + return; + } + + const file = files.find(item => item.field === 'file') || files[0]; + const originalName = file.filename || path.basename(file.filepath); + const ext = path.extname(originalName).toLowerCase(); + + if (!ALLOWED_EXT.includes(ext)) { + await ctx.cleanupRequestFiles(); + ctx.status = 400; + ctx.body = { code: 400, message: `仅支持上传图片:${ALLOWED_EXT.join('、')}` }; + return; + } + + // 1) 内容 hash:既是去重依据,也是落盘文件名 + const hash = await sha256File(file.filepath); + const stat = await fsp.stat(file.filepath); + + // 2) 主体内已存在同一份文件:直接复用,丢弃临时文件 + const exist = await ctx.model.File.findOne({ + where: { principal_id: principalId, hash }, + }); + if (exist) { + await ctx.cleanupRequestFiles(); + ctx.body = { code: 0, message: 'success', data: { ...exist.toJSON(), deduped: true } }; + return; + } + + // 3) 未命中:按上传时间(年/月/日)分目录,并挂在主体目录下实现资源隔离 + const now = new Date(); + const relDir = path.posix.join( + String(principalId), + String(now.getFullYear()), + pad2(now.getMonth() + 1), + pad2(now.getDate()) + ); + const relPath = path.posix.join(relDir, `${hash}${ext}`); + + await fsp.mkdir(path.join(app.config.upload.dir, relDir), { recursive: true }); + await moveFile(file.filepath, path.join(app.config.upload.dir, relPath)); + await ctx.cleanupRequestFiles(); + + const payload = { + principal_id: principalId, + hash, + name: originalName, + ext, + mime: file.mime || file.mimeType || '', + size: stat.size, + path: relPath, + url: `${app.config.upload.urlPrefix}/${relPath}`, + }; + + try { + const saved = await ctx.model.File.create(payload); + ctx.body = { code: 0, message: 'success', data: { ...saved.toJSON(), deduped: false } }; + } catch (err) { + // 并发上传同一文件时唯一索引冲突,回读已有记录返回 + if (err.name === 'SequelizeUniqueConstraintError') { + const record = await ctx.model.File.findOne({ + where: { principal_id: principalId, hash }, + }); + ctx.body = { code: 0, message: 'success', data: { ...record.toJSON(), deduped: true } }; + return; + } + throw err; + } + } + + /** + * @summary 读取文件 + * @description 按存储相对路径读取文件内容。路径形如「主体ID/年/月/日/hash.ext」, + * 由上传接口返回,URL 不可枚举;公开读取便于 img 标签直接引用 + * @router get /api/files/raw/{path} + * @request path string *path 存储相对路径,形如 1/2026/09/11/{hash}.png + * @response 200 baseResponse 文件二进制流,Content-Type 由扩展名决定 + */ + async raw() { + const { ctx, app } = this; + const relPath = String(ctx.params[0] || ''); + + if (!RAW_PATH_RE.test(relPath)) { + ctx.status = 400; + ctx.body = { code: 400, message: '文件路径不合法' }; + return; + } + + const rootDir = path.resolve(app.config.upload.dir); + const absFile = path.resolve(rootDir, relPath); + if (!absFile.startsWith(rootDir + path.sep) || !fs.existsSync(absFile)) { + ctx.status = 404; + ctx.body = { code: 404, message: '文件不存在' }; + return; + } + + ctx.type = MIME[path.extname(absFile).toLowerCase()] || 'application/octet-stream'; + // 文件名即内容 hash,内容永不变化,可长期强缓存 + ctx.set('Cache-Control', 'public, max-age=31536000, immutable'); + ctx.body = fs.createReadStream(absFile); + } +} + +module.exports = FileController; diff --git a/backend/app/controller/menu.js b/backend/app/controller/menu.js index 943ff1e..fcd9349 100644 --- a/backend/app/controller/menu.js +++ b/backend/app/controller/menu.js @@ -1,6 +1,7 @@ 'use strict'; const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); /** * @controller MenuController 菜单管理 @@ -20,8 +21,7 @@ class MenuController extends Controller { */ async index() { const { ctx } = this; - const page = Number(ctx.query.page || 1); - const pageSize = Number(ctx.query.pageSize || 20); + const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { parent_id: parentId, type, status } = ctx.query; const where = {}; @@ -31,12 +31,12 @@ class MenuController extends Controller { const { count, rows } = await ctx.model.Menu.findAndCountAll({ where, - offset: (page - 1) * pageSize, - limit: pageSize, + offset, + limit, order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]], }); - ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } }; + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** diff --git a/backend/app/controller/principal.js b/backend/app/controller/principal.js index bd21f03..09fa77c 100644 --- a/backend/app/controller/principal.js +++ b/backend/app/controller/principal.js @@ -1,6 +1,7 @@ 'use strict'; const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); /** * @controller PrincipalController 主体管理 @@ -13,7 +14,7 @@ class PrincipalController extends Controller { * @apikey * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 - * @request query string keyword 关键词,匹配主体编码或名称 + * @request query string keyword 关键词,匹配主体名称 * @request query integer type 主体类型:1自营 2加盟 3外部,不传则不过滤 * @request query integer status 状态:1启用 0禁用,不传则不过滤 * @response 200 principalListResponse success @@ -21,33 +22,48 @@ class PrincipalController extends Controller { async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; - const page = Number(ctx.query.page || 1); - const pageSize = Number(ctx.query.pageSize || 20); + const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { keyword, type, status } = ctx.query; const where = {}; if (keyword) { - where[Op.or] = [ - { code: { [Op.like]: `%${keyword}%` } }, - { name: { [Op.like]: `%${keyword}%` } }, - ]; + where.name = { [Op.like]: `%${keyword}%` }; } if (type !== undefined && type !== '') where.type = Number(type); if (status !== undefined && status !== '') where.status = Number(status); + // 按当前登录账号所属主体隔离(多租户):仅返回通过该账号 principal_users 关联的主体 + // 主体ID列表由 JWT 中间件从缓存加载,列表本身不做缓存(分页/筛选要求实时) + const principalIds = ctx.state.principalIds || await ctx.service.cache.getUserPrincipalIds(ctx.userId); + where.id = { [Op.in]: principalIds }; + const { count, rows } = await ctx.model.Principal.findAndCountAll({ where, - offset: (page - 1) * pageSize, - limit: pageSize, + offset, + limit, order: [[ 'id', 'DESC' ]], }); - ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } }; + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + } + + /** + * @summary 我的可选主体(头部主体切换下拉) + * @description 返回当前登录账号已绑定的主体列表,用于页面头部切换/选择主体; + * 该接口走 Redis 缓存(主体新增、更新、删除或绑定关系变更时自动失效),管理端列表接口 /api/principals 不缓存 + * @router get /api/principals/options + * @apikey + * @response 200 principalOptionsResponse success + */ + async options() { + const { ctx } = this; + const list = await ctx.service.cache.getUserPrincipalOptions(ctx.userId); + ctx.body = { code: 0, message: 'success', data: { list } }; } /** * @summary 主体详情 - * @description 按主键查询主体 + * @description 按主键查询主体(走缓存,主体更新/删除时自动失效) * @router get /api/principals/{id} * @apikey * @request path integer *id 主体主键ID @@ -55,7 +71,7 @@ class PrincipalController extends Controller { */ async show() { const { ctx } = this; - const principal = await ctx.model.Principal.findByPk(ctx.params.id); + const principal = await ctx.service.cache.getPrincipal(ctx.params.id); if (!principal) { ctx.status = 404; @@ -68,7 +84,7 @@ class PrincipalController extends Controller { /** * @summary 新增主体 - * @description 主体编码 code 全局唯一 + * @description 主体名称 name 必填;创建者自动关联为该主体 owner(多租户隔离) * @router post /api/principals * @apikey * @request body createPrincipalRequest *body @@ -76,22 +92,30 @@ class PrincipalController extends Controller { */ async create() { const { ctx } = this; - const { code, name } = ctx.request.body; + const { name } = ctx.request.body; - if (!code || !name) { + if (!name) { ctx.status = 400; - ctx.body = { code: 400, message: 'code 与 name 为必填项' }; - return; - } - - const exist = await ctx.model.Principal.findOne({ where: { code } }); - if (exist) { - ctx.status = 400; - ctx.body = { code: 400, message: '主体编码已存在' }; + ctx.body = { code: 400, message: 'name 为必填项' }; return; } const principal = await ctx.model.Principal.create(ctx.request.body); + + // 将创建者关联为该主体的默认用户(owner),建立多租户归属关系 + if (ctx.userId) { + await ctx.model.PrincipalUser.create({ + principal_id: principal.id, + user_id: ctx.userId, + role: 'owner', + is_default: 1, + status: 1, + }); + } + + // 新增主体后,创建者立即可见:失效其主体ID列表与可选主体缓存 + await ctx.service.cache.invalidateUserPrincipals(ctx.userId); + ctx.body = { code: 0, message: 'success', data: { id: principal.id } }; } @@ -115,12 +139,16 @@ class PrincipalController extends Controller { } await principal.update(ctx.request.body); + + // 主体信息变更:失效主体详情缓存及所有依赖主体信息的缓存(可选主体列表等) + await ctx.service.cache.invalidatePrincipal(principal.id); + ctx.body = { code: 0, message: 'success', data: { id: principal.id } }; } /** * @summary 删除主体 - * @description 物理删除主体;存在关联商品/订单时需先清理关联数据 + * @description 物理删除主体;存在关联商品/订单时拒绝删除并提示先清理;删除前自动解除主体与用户的绑定关系 * @router delete /api/principals/{id} * @apikey * @request path integer *id 主体主键ID @@ -136,7 +164,23 @@ class PrincipalController extends Controller { return; } + // 业务数据受外键约束,先提示清理,避免直接删除报数据库错误 + const [ productCount, orderCount ] = await Promise.all([ + ctx.model.Product.count({ where: { principal_id: principal.id } }), + ctx.model.Order.count({ where: { principal_id: principal.id } }), + ]); + if (productCount || orderCount) { + ctx.status = 400; + ctx.body = { code: 400, message: `该主体下仍有 ${productCount} 个商品、${orderCount} 个订单,请先清理后再删除` }; + return; + } + + // 主体与用户的绑定关系含外键,需先解除,否则删除会因约束失败 + await ctx.model.PrincipalUser.destroy({ where: { principal_id: principal.id } }); await principal.destroy(); + + await ctx.service.cache.invalidatePrincipal(principal.id); + ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } } diff --git a/backend/app/controller/principalExternalApi.js b/backend/app/controller/principalExternalApi.js index 270558b..3b6d6f9 100644 --- a/backend/app/controller/principalExternalApi.js +++ b/backend/app/controller/principalExternalApi.js @@ -1,6 +1,7 @@ 'use strict'; const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); /** * @controller PrincipalExternalApiController 主体外部接口管理 @@ -20,8 +21,7 @@ class PrincipalExternalApiController extends Controller { */ async index() { const { ctx } = this; - const page = Number(ctx.query.page || 1); - const pageSize = Number(ctx.query.pageSize || 20); + const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { code, status } = ctx.query; const principalId = ctx.state.principalId; @@ -32,12 +32,12 @@ class PrincipalExternalApiController extends Controller { const { count, rows } = await ctx.model.PrincipalExternalApi.findAndCountAll({ where, - offset: (page - 1) * pageSize, - limit: pageSize, + offset, + limit, order: [[ 'id', 'DESC' ]], }); - ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } }; + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** diff --git a/backend/app/controller/principalUser.js b/backend/app/controller/principalUser.js index 38c96bb..93efbd8 100644 --- a/backend/app/controller/principalUser.js +++ b/backend/app/controller/principalUser.js @@ -1,6 +1,9 @@ 'use strict'; const { Controller } = require('egg'); +const crypto = require('crypto'); +const { generateSalt, hashPassword } = require('../lib/password'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); /** * @controller PrincipalUserController 主体用户关联管理 @@ -21,8 +24,7 @@ class PrincipalUserController extends Controller { */ async index() { const { ctx } = this; - const page = Number(ctx.query.page || 1); - const pageSize = Number(ctx.query.pageSize || 20); + const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { user_id: userId, role, status } = ctx.query; const principalId = ctx.state.principalId; @@ -34,12 +36,15 @@ class PrincipalUserController extends Controller { const { count, rows } = await ctx.model.PrincipalUser.findAndCountAll({ where, - offset: (page - 1) * pageSize, - limit: pageSize, + offset, + limit, order: [[ 'id', 'DESC' ]], + include: [ + { model: ctx.model.User, as: 'user', attributes: { exclude: [ 'password', 'salt' ] } }, + ], }); - ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } }; + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** @@ -96,9 +101,117 @@ class PrincipalUserController extends Controller { } const relation = await ctx.model.PrincipalUser.create(ctx.request.body); + // 绑定关系变化:失效该用户缓存的主体ID列表与可选主体列表 + await ctx.service.cache.invalidateUserPrincipals(userId); ctx.body = { code: 0, message: 'success', data: { id: relation.id } }; } + /** + * @summary 邀请开通主体账号 + * @description 传入邮箱、用户名称与主体ID,自动创建新用户(随机初始密码)并绑定到该主体(角色 member); + * 返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不可重复开通 + * @router post /api/principal-users/invite + * @apikey + * @request body invitePrincipalUserRequest *body + * @response 200 invitePrincipalUserResponse success + */ + async invite() { + const { ctx } = this; + const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + const { email, name, principal_id: principalId } = ctx.request.body; + + if (!email || !EMAIL_REGEX.test(email)) { + ctx.status = 400; + ctx.body = { code: 400, message: '请填写正确的邮箱地址' }; + return; + } + if (!name) { + ctx.status = 400; + ctx.body = { code: 400, message: '用户名称 name 为必填项' }; + return; + } + if (!principalId) { + ctx.status = 400; + ctx.body = { code: 400, message: '主体ID principal_id 为必填项' }; + return; + } + + // 主体必须存在,给出明确提示 + const principal = await ctx.model.Principal.findByPk(principalId); + if (!principal) { + ctx.status = 404; + ctx.body = { code: 404, message: '主体不存在' }; + return; + } + + // 邮箱全局唯一 + const emailExist = await ctx.model.User.findOne({ where: { email } }); + if (emailExist) { + ctx.status = 400; + ctx.body = { code: 400, message: '该邮箱已注册' }; + return; + } + + // 生成随机初始密码(明文仅此处返回一次) + const password = this.generateRandomPassword(12); + const salt = generateSalt(); + const hashed = hashPassword(password, salt); + + const transaction = await ctx.model.transaction(); + try { + const user = await ctx.model.User.create({ + username: email, + nickname: name, + email, + salt, + password: hashed, + status: 1, + }, { transaction }); + + const relation = await ctx.model.PrincipalUser.create({ + principal_id: principalId, + user_id: user.id, + role: 'member', + is_default: 0, + status: 1, + }, { transaction }); + + await transaction.commit(); + + await ctx.service.cache.invalidateUserPrincipals(user.id); + + ctx.body = { + code: 0, + message: 'success', + data: { + user_id: user.id, + relation_id: relation.id, + email: user.email, + username: user.username, + nickname: user.nickname, + password, + }, + }; + } catch (err) { + await transaction.rollback(); + ctx.status = 500; + ctx.body = { code: 500, message: '开通账号失败,请稍后重试' }; + } + } + + /** + * 生成随机密码:12 位,含大小写字母与数字(去除易混淆字符 0/O/1/l/I) + * @param {Number} len 长度,默认 12 + * @return {String} 随机密码 + */ + generateRandomPassword(len = 12) { + const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'; + const bytes = crypto.randomBytes(len); + let pwd = ''; + for (let i = 0; i < len; i++) pwd += chars[bytes[i] % chars.length]; + return pwd; + } + /** * @summary 更新关联信息 * @description 可修改角色、默认主体标识与状态 @@ -120,6 +233,7 @@ class PrincipalUserController extends Controller { delete ctx.request.body.principal_id; await relation.update(ctx.request.body); + await ctx.service.cache.invalidateUserPrincipals(relation.user_id); ctx.body = { code: 0, message: 'success', data: { id: relation.id } }; } @@ -141,7 +255,9 @@ class PrincipalUserController extends Controller { return; } + const relationUserId = relation.user_id; await relation.destroy(); + await ctx.service.cache.invalidateUserPrincipals(relationUserId); ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } } diff --git a/backend/app/controller/user.js b/backend/app/controller/user.js index fa8abab..950e6ae 100644 --- a/backend/app/controller/user.js +++ b/backend/app/controller/user.js @@ -2,6 +2,7 @@ const { Controller } = require('egg'); const { generateSalt, hashPassword } = require('../lib/password'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); /** * @controller UserController 用户管理 @@ -21,8 +22,7 @@ class UserController extends Controller { async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; - const page = Number(ctx.query.page || 1); - const pageSize = Number(ctx.query.pageSize || 20); + const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { keyword, status } = ctx.query; const where = {}; @@ -36,13 +36,13 @@ class UserController extends Controller { const { count, rows } = await ctx.model.User.findAndCountAll({ where, + offset, + limit, attributes: { exclude: [ 'password', 'salt' ] }, - offset: (page - 1) * pageSize, - limit: pageSize, order: [[ 'id', 'DESC' ]], }); - ctx.body = { code: 0, message: 'success', data: { list: rows, total: count, page, pageSize } }; + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** @@ -122,7 +122,10 @@ class UserController extends Controller { return; } + // 请求拦截器会注入 principal_id,而 users 表无该字段,更新前剔除避免脏字段写入 + delete ctx.request.body.principal_id; await user.update(ctx.request.body); + await ctx.service.cache.invalidateUser(user.id); ctx.body = { code: 0, message: 'success', data: { id: user.id } }; } @@ -154,6 +157,7 @@ class UserController extends Controller { const salt = generateSalt(); await user.update({ salt, password: hashPassword(password, salt) }); + await ctx.service.cache.invalidateUser(user.id); ctx.body = { code: 0, message: 'success', data: { id: user.id } }; } @@ -176,6 +180,7 @@ class UserController extends Controller { } await user.destroy(); + await ctx.service.cache.invalidateUser(user.id); ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } } diff --git a/backend/app/lib/emailCode.js b/backend/app/lib/emailCode.js index fac0624..b6920d7 100644 --- a/backend/app/lib/emailCode.js +++ b/backend/app/lib/emailCode.js @@ -6,16 +6,17 @@ const nodemailer = require('nodemailer'); const CODE_TTL = 10 * 60; /** 每日计数缓存时间:24 小时 */ const DAY_TTL = 24 * 60 * 60; -/** 邮件主题 */ +/** 默认邮件主题(注册场景) */ const SUBJECT = 'OMS 注册邮箱验证码'; /** - * 验证码在 Redis 中的 key + * 验证码在 Redis 中的 key(按场景隔离,避免注册与找回密码互串) * @param {String} email 邮箱 + * @param {String} scene 场景:register 注册 / reset-password 找回密码 * @return {String} redis key */ -function codeKey(email) { - return `oms:email:code:${email}`; +function codeKey(email, scene = 'register') { + return `oms:email:code:${scene}:${email}`; } /** @@ -39,11 +40,14 @@ function dailyKey(email) { } /** - * 生成 6 位数字验证码 + * 生成指定位数的数字验证码 + * @param {Number} len 位数,默认 6(找回密码场景为 4 位) * @return {String} 验证码 */ -function generateCode() { - return String(Math.floor(100000 + Math.random() * 900000)); +function generateCode(len = 6) { + const min = 10 ** (len - 1); + const max = 10 ** len - 1; + return String(Math.floor(min + Math.random() * (max - min + 1))); } /** @@ -101,18 +105,24 @@ async function markSent(app, email) { * 未配置 SMTP(config.mailer.host 为空)时仅记录日志,便于本地开发调试 * @param {Egg.Application} app egg application * @param {String} email 目标邮箱 - * @param {Object} options 附加信息:userId(注册场景为空)、ip、scene + * @param {Object} options 附加信息:userId、ip、scene、length(验证码位数,默认6)、subject * @return {Promise} { ok: 是否发送成功, message: 失败原因 } */ async function sendCode(app, email, options = {}) { - const { userId = null, ip = '', scene = 'register' } = options; + const { + userId = null, + ip = '', + scene = 'register', + length = 6, + subject = SUBJECT, + } = options; const limitMessage = await checkLimit(app, email); if (limitMessage) { await writeLog(app, { scene, to_email: email, - subject: SUBJECT, + subject, content: '', user_id: userId, ip, @@ -122,9 +132,9 @@ async function sendCode(app, email, options = {}) { return { ok: false, message: limitMessage }; } - const code = generateCode(); - const content = `您的注册验证码为:${code},${CODE_TTL / 60} 分钟内有效。`; - await app.redis.set(codeKey(email), code, 'EX', CODE_TTL); + const code = generateCode(length); + const content = `您的验证码为:${code},${CODE_TTL / 60} 分钟内有效。`; + await app.redis.set(codeKey(email, scene), code, 'EX', CODE_TTL); let errorMsg = ''; const mailer = app.config.mailer; @@ -143,7 +153,7 @@ async function sendCode(app, email, options = {}) { await transporter.sendMail({ from: mailer.from, to: email, - subject: SUBJECT, + subject, text: content, }); } catch (err) { @@ -155,7 +165,7 @@ async function sendCode(app, email, options = {}) { await writeLog(app, { scene, to_email: email, - subject: SUBJECT, + subject, content, user_id: userId, ip, @@ -174,13 +184,14 @@ async function sendCode(app, email, options = {}) { * @param {Egg.Application} app egg application * @param {String} email 邮箱 * @param {String} code 验证码 + * @param {String} scene 场景:register 注册 / reset-password 找回密码 * @return {Promise} 校验是否通过 */ -async function verifyCode(app, email, code) { - const cached = await app.redis.get(codeKey(email)); +async function verifyCode(app, email, code, scene = 'register') { + const cached = await app.redis.get(codeKey(email, scene)); if (!cached || cached !== String(code)) return false; - await app.redis.del(codeKey(email)); + await app.redis.del(codeKey(email, scene)); return true; } diff --git a/backend/app/lib/pagination.js b/backend/app/lib/pagination.js new file mode 100644 index 0000000..16d5b1b --- /dev/null +++ b/backend/app/lib/pagination.js @@ -0,0 +1,63 @@ +'use strict'; + +/** + * 列表分页统一封装 + * - 所有列表接口统一用 parsePagination 解析 page / pageSize,避免各控制器各写一套 + * - pageSize 做了上限保护(默认 200),防止前端传入超大值把整表拉到内存 + * - 列表响应体统一用 buildPageResult 组装,保证 { list, total, page, pageSize } 结构一致 + */ + +/** 默认每页条数 */ +const DEFAULT_PAGE_SIZE = 20; +/** 每页条数上限 */ +const MAX_PAGE_SIZE = 200; + +/** + * 转为整数,非法值返回兜底值 + * @param {*} value 原始值 + * @param {Number} fallback 兜底值 + * @return {Number} 整数 + */ +function toInt(value, fallback) { + const num = Number.parseInt(value, 10); + return Number.isFinite(num) ? num : fallback; +} + +/** + * 解析分页参数 + * @param {Object} query ctx.query + * @param {Object} [options] defaultPageSize 默认每页条数(默认 20)、maxPageSize 上限(默认 200) + * @return {{page: Number, pageSize: Number, offset: Number, limit: Number}} 分页参数 + */ +function parsePagination(query = {}, options = {}) { + const defaultPageSize = options.defaultPageSize || DEFAULT_PAGE_SIZE; + const maxPageSize = options.maxPageSize || MAX_PAGE_SIZE; + + const page = Math.max(1, toInt(query.page, 1)); + const pageSize = Math.min(maxPageSize, Math.max(1, toInt(query.pageSize, defaultPageSize))); + + return { page, pageSize, offset: (page - 1) * pageSize, limit: pageSize }; +} + +/** + * 组装统一的分页响应数据 + * @param {Array} rows 当前页数据 + * @param {Number} total 总条数 + * @param {Object} pageInfo 分页参数(parsePagination 的返回值或 { page, pageSize }) + * @return {{list: Array, total: Number, page: Number, pageSize: Number}} 响应数据 + */ +function buildPageResult(rows, total, pageInfo = {}) { + return { + list: rows, + total, + page: pageInfo.page, + pageSize: pageInfo.pageSize, + }; +} + +module.exports = { + DEFAULT_PAGE_SIZE, + MAX_PAGE_SIZE, + parsePagination, + buildPageResult, +}; diff --git a/backend/app/middleware/jwt_auth.js b/backend/app/middleware/jwt_auth.js index f36e29b..1313488 100644 --- a/backend/app/middleware/jwt_auth.js +++ b/backend/app/middleware/jwt_auth.js @@ -4,7 +4,8 @@ const TOKEN_PREFIX = 'Bearer '; /** * JWT 鉴权中间件 - * 校验请求头 Authorization: Bearer ,解析后仅取 user_id 挂载到 ctx.userId + * 校验请求头 Authorization: Bearer ,解析出 user_id 后加载用户信息(Redis 缓存优先,避免频繁查库), + * 并把用户信息与其可用主体ID列表挂载到 ctx,供控制器与后续中间件复用 * @return {Function} koa 中间件 */ module.exports = () => { @@ -19,15 +20,43 @@ module.exports = () => { return; } + // 仅校验 token 本身,不要把控制器(await next)抛出的业务异常也吞成 401 + let decoded; try { // token 载荷仅包含 user_id,不含任何敏感信息 - const decoded = app.jwt.verify(token, app.config.jwt.secret); - ctx.userId = decoded.user_id; - ctx.state.userId = decoded.user_id; - await next(); + decoded = app.jwt.verify(token, app.config.jwt.secret); } catch (err) { ctx.status = 401; ctx.body = { code: 401, message: '登录凭证无效或已过期' }; + return; } + + const userId = decoded.user_id; + + // 用户信息与可用主体ID均走缓存,命中时不再查库 + const [ user, principalIds ] = await Promise.all([ + ctx.service.cache.getUser(userId), + ctx.service.cache.getUserPrincipalIds(userId), + ]); + + if (!user) { + ctx.status = 401; + ctx.body = { code: 401, message: '用户不存在或已被删除' }; + return; + } + if (Number(user.status) !== 1) { + ctx.status = 403; + ctx.body = { code: 403, message: '账号已禁用' }; + return; + } + + ctx.userId = userId; + ctx.state.userId = userId; + ctx.user = user; + ctx.state.user = user; + ctx.userPrincipalIds = principalIds || []; + ctx.state.principalIds = principalIds || []; + + await next(); }; }; diff --git a/backend/app/middleware/principal_check.js b/backend/app/middleware/principal_check.js index 09e2114..7026a4b 100644 --- a/backend/app/middleware/principal_check.js +++ b/backend/app/middleware/principal_check.js @@ -56,11 +56,9 @@ module.exports = (options = {}) => { } principalId = Number(principalId); - // 校验账号与主体的绑定关系 - const bound = await ctx.model.PrincipalUser.findOne({ - where: { user_id: userId, principal_id: principalId }, - attributes: [ 'id' ], - }); + // 校验账号与主体的绑定关系:主体ID列表来自缓存(JWT 中间件已加载),避免每次请求查关联表 + const principalIds = ctx.state.principalIds || await ctx.service.cache.getUserPrincipalIds(userId); + const bound = new Set((principalIds || []).map(Number)).has(principalId); if (!bound) { ctx.status = 403; ctx.body = { code: 403, message: '无权操作该主体下的数据' }; diff --git a/backend/app/model/expressCompany.js b/backend/app/model/expressCompany.js new file mode 100644 index 0000000..6f09aef --- /dev/null +++ b/backend/app/model/expressCompany.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * 快递公司字典模型,对应 express_companies 表(通用字典,不区分主体) + * + * 供发货单等单据选择物流公司:code 使用行业/WMS 标准编码(SF/YTO/ZTO...), + * 选择后写入单据的 logistics_code / logistics_name。 + * @param {Egg.Application} app egg application + * @return {object} expressCompany model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize; + + const ExpressCompany = app.model.define('express_company', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + code: { type: STRING(50), allowNull: false, comment: '快递公司编码(行业/WMS 标准编码,如 SF/YTO/ZTO)' }, + name: { type: STRING(100), allowNull: false, comment: '快递公司名称(如 顺丰速运)' }, + status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + sort: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '排序(下拉展示顺序,越小越靠前)' }, + remark: { type: STRING(255), comment: '备注' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'express_companies', + comment: '快递公司字典', + }); + + return ExpressCompany; +}; diff --git a/backend/app/model/file.js b/backend/app/model/file.js new file mode 100644 index 0000000..79f5394 --- /dev/null +++ b/backend/app/model/file.js @@ -0,0 +1,35 @@ +'use strict'; + +/** + * 文件资源模型,对应 files 表 + * 同一主体下按内容 hash 去重(uk_files_principal_hash),磁盘路径按「主体ID/年/月/日」分层 + * @param {Egg.Application} app egg application + * @return {object} file model + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + + const File = app.model.define('file', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + hash: { type: STRING(64), allowNull: false, comment: '文件内容 SHA256,用于去重' }, + name: { type: STRING(255), allowNull: false, comment: '原始文件名' }, + ext: { type: STRING(20), allowNull: false, comment: '扩展名(小写,含点,如 .png)' }, + mime: { type: STRING(100), comment: 'MIME 类型' }, + size: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '文件大小(字节)' }, + path: { type: STRING(255), allowNull: false, comment: '相对存储路径:主体ID/年/月/日/hash.ext' }, + url: { type: STRING(500), allowNull: false, comment: '访问地址' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + deleted_at: { type: DATE, comment: '软删除时间' }, + }, { + paranoid: true, + deletedAt: 'deleted_at', + }); + + File.associate = () => { + app.model.File.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + }; + + return File; +}; diff --git a/backend/app/model/menu.js b/backend/app/model/menu.js index b31be82..88298fd 100644 --- a/backend/app/model/menu.js +++ b/backend/app/model/menu.js @@ -16,6 +16,7 @@ module.exports = app => { path: { type: STRING(200), comment: '前端路由/地址' }, icon: { type: STRING(100), comment: '图标' }, permission: { type: STRING(100), comment: '权限标识,如 order:create' }, + component: { type: STRING(200), comment: '前端组件路径,如 views/system/user/index.vue' }, sort: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '排序' }, status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, created_at: { type: DATE, comment: '创建时间' }, diff --git a/backend/app/model/principal.js b/backend/app/model/principal.js index 24c7a74..3df44b7 100644 --- a/backend/app/model/principal.js +++ b/backend/app/model/principal.js @@ -10,7 +10,6 @@ module.exports = app => { const Principal = app.model.define('principal', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, - code: { type: STRING(50), allowNull: false, comment: '主体编码' }, name: { type: STRING(100), allowNull: false, comment: '主体名称' }, type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '主体类型:1自营 2加盟 3外部' }, contact_name: { type: STRING(50), comment: '联系人' }, @@ -32,6 +31,9 @@ module.exports = app => { app.model.Principal.hasMany(app.model.ComboProduct, { foreignKey: 'principal_id', as: 'comboProducts' }); app.model.Principal.hasMany(app.model.Order, { foreignKey: 'principal_id', as: 'orders' }); app.model.Principal.hasMany(app.model.PrincipalExternalApi, { foreignKey: 'principal_id', as: 'externalApis' }); + app.model.Principal.hasMany(app.model.Shop, { foreignKey: 'principal_id', as: 'shops' }); + app.model.Principal.hasMany(app.model.Warehouse, { foreignKey: 'principal_id', as: 'warehouses' }); + app.model.Principal.hasMany(app.model.WarehouseApi, { foreignKey: 'principal_id', as: 'warehouseApis' }); }; return Principal; diff --git a/backend/app/router.js b/backend/app/router.js index 3e4003b..4227a3c 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -12,10 +12,19 @@ module.exports = app => { // 注册、登录、邮箱验证码接口无需鉴权 router.post('/api/auth/email-code', controller.auth.sendEmailCode); + // 邮箱验证码登录:发送登录验证码 + 校验验证码直接登录(公开接口,无需登录) + router.post('/api/auth/email-login/code', controller.auth.sendLoginCode); + router.post('/api/auth/email-login', controller.auth.loginByEmailCode); + // 忘记密码:发送 4 位重置验证码 + 校验验证码重置密码(公开接口,无需登录) + router.post('/api/auth/reset-password/code', controller.auth.sendResetCode); + router.post('/api/auth/reset-password', controller.auth.resetPasswordByCode); router.post('/api/auth/register', controller.auth.register); router.post('/api/auth/login', controller.auth.login); // 以下接口需要登录:请求头 Authorization: Bearer router.get('/api/auth/profile', jwtAuth, controller.auth.profile); + // 自助服务:修改当前登录用户自己的资料与密码,所有登录账号均可访问 + router.put('/api/auth/profile', jwtAuth, controller.auth.updateProfile); + router.put('/api/auth/password', jwtAuth, controller.auth.changePassword); // 菜单树需在 /api/menus/:id 之前注册,避免 tree 被当作 id 匹配 router.get('/api/menus/tree', jwtAuth, controller.menu.tree); @@ -26,13 +35,108 @@ module.exports = app => { // RESTful 资源路由:index / show / create / update / destroy(均需鉴权) router.resources('users', '/api/users', jwtAuth, controller.user); + // 头部主体切换下拉(带缓存),需在 /api/principals/:id 之前注册,避免 options 被当作 id 匹配 + router.get('/api/principals/options', jwtAuth, controller.principal.options); + // 管理端主体列表(不缓存,保证分页与筛选实时) router.resources('principals', '/api/principals', jwtAuth, controller.principal); // 主体用户关联:需校验主体绑定关系 router.resources('principalUsers', '/api/principal-users', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser); + // 邀请开通主体账号:创建新用户(随机密码)并绑定到指定主体 + router.post('/api/principal-users/invite', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser.invite); + // 商品快速搜索(聚合:商品编码/货品编码/条码/商品名称),需在 resources('products') 之前注册避免被 :id 误匹配 + router.get('/api/products/search', jwtAuth, principalCheck({ model: 'Product' }), controller.product.search); // 以下资源均归属某个主体,需做主体校验与数据隔离,防止跨主体操作 router.resources('products', '/api/products', jwtAuth, principalCheck({ model: 'Product' }), controller.product); router.resources('comboProducts', '/api/combo-products', jwtAuth, principalCheck({ model: 'ComboProduct' }), controller.comboProduct); router.resources('menus', '/api/menus', jwtAuth, controller.menu); router.resources('principalExternalApis', '/api/principal-external-apis', jwtAuth, principalCheck({ model: 'PrincipalExternalApi' }), controller.principalExternalApi); + // 仓库(仅基础信息)与仓库接口配置(一个仓库可有多条接口配置) + router.get('/api/warehouses/select', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse.select); + // 仓库下的商品(是否已推送到该仓库):需在 resources('warehouses') 之前注册,避免 /products 被当作 :id + router.get('/api/warehouses/:id/products', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.index); + // 仓库商品推送(商品资料推送到仓库 WMS):需在 resources('warehouses') 之前注册 + router.post('/api/warehouses/:id/products/push', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.push); + // 仓库商品 WMS 库存查询(按已推送商品的 WMS itemId 批量查询库存数量):需在 resources('warehouses') 之前注册 + router.post('/api/warehouses/:id/products/wms-inventory', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.wmsInventory); + // 库存同步:用外部 WMS 库存覆盖系统库存(差异以完成的出入库单平衡) + router.post('/api/warehouses/:id/inventory/sync', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.syncInventory); + router.resources('warehouses', '/api/warehouses', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse); + // 仓库接口配置项:定义(硬编码)与配置项值分开维护,需在 resources('warehouse-apis') 之前注册 + router.get('/api/warehouse-api-fields', jwtAuth, controller.warehouseApiField.index); + router.get('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApiField.show); + router.put('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApiField.update); + // 接口连通性测试(index.ping),需在 resources('warehouseApis') 之前注册 + router.post('/api/warehouse-apis/:id/test', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApi.test); + router.resources('warehouseApis', '/api/warehouse-apis', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApi); + // 对外 API 调用日志(OMS → 外部 WMS 的请求记录),按主体隔离(principal_id 由前端拦截器注入 query) + router.get('/api/outbound-logs', jwtAuth, principalCheck(), controller.apiOutboundLog.index); + // 订单整单解析需在 resources('orders') 之前注册,避免被 /api/orders/:id 误匹配 + router.post('/api/orders/:id/parse-items', jwtAuth, principalCheck({ model: 'Order' }), controller.order.parseItems); router.resources('orders', '/api/orders', jwtAuth, principalCheck({ model: 'Order' }), controller.order); + // 订单明细(订单副表):详情解析需在 resources('orderItems') 之前注册 + router.post('/api/order-items/:id/parse', jwtAuth, principalCheck({ model: 'OrderItem' }), controller.orderItem.parse); + router.resources('orderItems', '/api/order-items', jwtAuth, principalCheck({ model: 'OrderItem' }), controller.orderItem); + // 店铺与店铺商品(采集的商品可绑定到系统商品或组合商品) + router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop); + router.resources('shopProducts', '/api/shop-products', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct); + router.post('/api/shop-products/:id/bind', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.bind); + // 出入库单与明细(明细共用 stock_items 表,以 bill_type 区分:1入库 2出库) + // 单据状态由业务事务推动(审核/推送/完成/驳回/作废/取消/恢复),不提供直接修改状态的接口 + // 状态流转(按序校验):审核 / 推送 / 完成 / 取消 / 恢复 / 作废,需在 resources 之前注册避免被 :id 误匹配 + router.post('/api/inbound-orders/:id/audit', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.audit); + router.post('/api/inbound-orders/:id/push', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.push); + router.post('/api/inbound-orders/:id/complete', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.complete); + router.post('/api/inbound-orders/:id/cancel', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.cancel); + router.post('/api/inbound-orders/:id/restore', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.restore); + // 作废:已审核(2) 的单据只能作废(禁止删除),记录作废人/时间/原因 + router.post('/api/inbound-orders/:id/void', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.voidOrder); + // 驳回:已审核(2)/已推送(3) 且未完成,驳回后回到待处理(1);已推送的先走接口取消外部单据 + router.post('/api/inbound-orders/:id/reject', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder.reject); + router.post('/api/outbound-orders/:id/audit', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.audit); + router.post('/api/outbound-orders/:id/push', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.push); + router.post('/api/outbound-orders/:id/complete', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.complete); + router.post('/api/outbound-orders/:id/cancel', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.cancel); + router.post('/api/outbound-orders/:id/restore', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.restore); + router.post('/api/outbound-orders/:id/void', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.voidOrder); + // 驳回:已审核(2)/已推送(3) 且未完成,驳回后回到待处理(1);已推送的先走接口取消外部单据 + router.post('/api/outbound-orders/:id/reject', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder.reject); + router.resources('inboundOrders', '/api/inbound-orders', jwtAuth, principalCheck({ model: 'InboundOrder' }), controller.inboundOrder); + router.resources('outboundOrders', '/api/outbound-orders', jwtAuth, principalCheck({ model: 'OutboundOrder' }), controller.outboundOrder); + router.resources('stockItems', '/api/stock-items', jwtAuth, principalCheck({ model: 'StockItem' }), controller.stockItem); + // 快递公司字典(通用字典,不区分主体):下拉需在 resources 之前注册,避免 /select 被当作 :id + router.get('/api/express-companies/select', jwtAuth, controller.expressCompany.select); + router.resources('expressCompanies', '/api/express-companies', jwtAuth, controller.expressCompany); + + // 收件人信息智能识别(通用能力,仅需登录):需在 resources 之前注册,避免被 /:id 误匹配 + router.post('/api/order-deliveries/parse-receiver', jwtAuth, controller.orderDelivery.parseReceiver); + + // 批量切换发货仓库(按勾选 ids 或筛选条件;dry_run=true 仅预览影响范围) + router.post('/api/order-deliveries/change-warehouse', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.changeWarehouse); + // 发货单(订单):字段口径对齐 WMS 发货单(wms_order_delivery)与奇门 deliveryOrder,独立于出库单 + // 状态流转专用动作需在 resources 之前注册,避免被 /api/order-deliveries/:id 误匹配 + router.post('/api/order-deliveries/audit-batch', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.auditBatch); + router.post('/api/order-deliveries/push-batch', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.pushBatch); + router.post('/api/order-deliveries/:id/audit', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.audit); + router.post('/api/order-deliveries/:id/push', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.push); + router.post('/api/order-deliveries/:id/reject', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.reject); + router.post('/api/order-deliveries/:id/cancel', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.cancel); + router.post('/api/order-deliveries/:id/restore', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.restore); + router.post('/api/order-deliveries/:id/void', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery.voidOrder); + router.resources('orderDeliveries', '/api/order-deliveries', jwtAuth, principalCheck({ model: 'OrderDelivery' }), controller.orderDelivery); + // 发货单明细(子表商品明细,对应奇门 orderLines):明细锁定校验在控制器内按单据状态判断 + router.resources('orderDeliveryItems', '/api/order-delivery-items', jwtAuth, principalCheck({ model: 'OrderDeliveryItem' }), controller.orderDeliveryItem); + + // 文件资源:check/upload 需登录并按主体隔离;raw 为公开读取(URL 含内容 hash,不可枚举) + // raw 通配路由需在 resources('files') 之前注册,避免被 /api/files/:id 误匹配 + router.post('/api/files/check', jwtAuth, principalCheck(), controller.file.check); + router.post('/api/files/upload', jwtAuth, principalCheck(), controller.file.upload); + router.get('/api/files/raw/(.*)', controller.file.raw); + router.resources('files', '/api/files', jwtAuth, principalCheck({ model: 'File' }), controller.file); + + // WMS 出站通知回调(公开接口,无需登录):按 app_key 校验仓库接口配置 + MD5 签名校验 + router.post('/wms/notify', controller.wmsNotify.handle); + + // 对外通用回调接口(公开接口,无需登录):外部系统以 method/app_key/v/timestamp/sign 调用, + // 按 app_key 定位仓库接口配置与仓库后按 method 分发;协议与 WMS /openapi 对齐,已暴露 index.ping + router.post('/openapi', controller.openapi.index); }; diff --git a/backend/app/service/cache.js b/backend/app/service/cache.js new file mode 100644 index 0000000..95f0037 --- /dev/null +++ b/backend/app/service/cache.js @@ -0,0 +1,234 @@ +'use strict'; + +const { Service } = require('egg'); + +/** 业务缓存 key 统一前缀(与邮箱验证码 oms:email:* 区分) */ +const PREFIX = 'oms:cache'; + +/** 各类缓存的 key 构造器 */ +const KEYS = { + user: userId => `${PREFIX}:user:${userId}`, + userPrincipals: userId => `${PREFIX}:user-principals:${userId}`, + principalOptions: userId => `${PREFIX}:principal-options:${userId}`, + principal: principalId => `${PREFIX}:principal:${principalId}`, +}; + +/** + * 业务缓存服务 + * 缓存登录用户信息、用户可用主体列表、主体详情,避免高频请求反复查库。 + * Redis 异常时全部降级为直接查库(只告警不抛错),保证可用性。 + */ +class CacheService extends Service { + /** @return {Object} redis 客户端 */ + get redis() { + return this.app.redis; + } + + /** @return {Object} 缓存有效期配置(秒) */ + get ttls() { + return this.config.cache; + } + + /** + * 读取缓存(Redis 异常时返回 null,降级为查库) + * @param {String} key 缓存 key + * @return {Promise} 缓存值,不存在为 null + */ + async read(key) { + try { + const raw = await this.redis.get(key); + return raw ? JSON.parse(raw) : null; + } catch (err) { + this.logger.warn(`[cache] 读取失败,key=${key}:${err.message}`); + return null; + } + } + + /** + * 写入缓存(值为空时不写入,避免缓存穿透到空数据) + * @param {String} key 缓存 key + * @param {any} value 缓存值 + * @param {Number} ttl 有效秒数 + * @return {Promise} 无返回值 + */ + async write(key, value, ttl = 300) { + if (value === null || value === undefined) return; + try { + await this.redis.set(key, JSON.stringify(value), 'EX', ttl); + } catch (err) { + this.logger.warn(`[cache] 写入失败,key=${key}:${err.message}`); + } + } + + /** + * 删除若干 key + * @param {Array} keys 缓存 key 列表 + * @return {Promise} 无返回值 + */ + async forget(...keys) { + const valid = keys.filter(Boolean); + if (!valid.length) return; + try { + await this.redis.del(...valid); + } catch (err) { + this.logger.warn(`[cache] 删除失败,key=${valid.join(',')}:${err.message}`); + } + } + + /** + * 按前缀批量删除(SCAN + DEL,用于“某类缓存全部失效”) + * @param {String} prefix key 前缀 + * @return {Promise} 无返回值 + */ + async forgetByPrefix(prefix) { + try { + let cursor = '0'; + do { + const [ next, keys ] = await this.redis.scan(cursor, 'MATCH', `${prefix}*`, 'COUNT', 200); + cursor = next; + if (keys && keys.length) await this.redis.del(...keys); + } while (cursor !== '0'); + } catch (err) { + this.logger.warn(`[cache] 按前缀删除失败,prefix=${prefix}:${err.message}`); + } + } + + /** + * 缓存优先取值:命中直接返回,未命中执行 loader 查库并回写缓存 + * @param {String} key 缓存 key + * @param {Number} ttl 有效秒数 + * @param {Function} loader 未命中时的数据加载函数 + * @return {Promise} 数据 + */ + async remember(key, ttl, loader) { + const cached = await this.read(key); + if (cached !== null) return cached; + + const value = await loader(); + await this.write(key, value, ttl); + return value; + } + + // ---------- 用户信息 ---------- + + /** + * 登录用户信息(不含 password / salt) + * @param {Number} userId 用户ID + * @return {Promise} 用户信息,不存在为 null + */ + async getUser(userId) { + return await this.remember(KEYS.user(userId), this.ttls.user, async () => { + const user = await this.ctx.model.User.findByPk(userId, { + attributes: { exclude: [ 'password', 'salt' ] }, + }); + return user ? user.toJSON() : null; + }); + } + + // ---------- 用户与主体的关联 ---------- + + /** + * 用户已绑定的主体ID列表(用于多租户数据隔离) + * @param {Number} userId 用户ID + * @return {Promise>} 主体ID数组 + */ + async getUserPrincipalIds(userId) { + return await this.remember(KEYS.userPrincipals(userId), this.ttls.principal, async () => { + const rows = await this.ctx.model.PrincipalUser.findAll({ + where: { user_id: userId }, + attributes: [ 'principal_id' ], + }); + return rows.map(row => Number(row.principal_id)); + }); + } + + /** + * 用户可选主体列表(头部主体切换/下拉选择用,含该主体下的角色与默认标识) + * @param {Number} userId 用户ID + * @return {Promise>} 主体选项列表 + */ + async getUserPrincipalOptions(userId) { + return await this.remember(KEYS.principalOptions(userId), this.ttls.principalOptions, async () => { + const relations = await this.ctx.model.PrincipalUser.findAll({ + where: { user_id: userId }, + attributes: [ 'id', 'principal_id', 'role', 'is_default', 'status' ], + order: [[ 'is_default', 'DESC' ], [ 'id', 'ASC' ]], + }); + if (!relations.length) return []; + + const principals = await this.ctx.model.Principal.findAll({ + where: { id: relations.map(item => item.principal_id) }, + attributes: [ 'id', 'name', 'type', 'status', 'contact_name', 'contact_phone' ], + }); + const principalMap = new Map(principals.map(item => [ Number(item.id), item ])); + + return relations.map(item => { + const principal = principalMap.get(Number(item.principal_id)); + if (!principal) return null; + return { + id: Number(principal.id), + name: principal.name, + type: principal.type, + status: principal.status, + contact_name: principal.contact_name, + contact_phone: principal.contact_phone, + role: item.role, + is_default: item.is_default, + relation_status: item.status, + }; + }).filter(Boolean); + }); + } + + // ---------- 主体信息 ---------- + + /** + * 主体详情 + * @param {Number} principalId 主体ID + * @return {Promise} 主体信息,不存在为 null + */ + async getPrincipal(principalId) { + return await this.remember(KEYS.principal(principalId), this.ttls.principal, async () => { + const principal = await this.ctx.model.Principal.findByPk(principalId); + return principal ? principal.toJSON() : null; + }); + } + + // ---------- 失效 ---------- + + /** + * 用户资料/状态变更后失效:用户缓存 + 该用户的主体相关缓存 + * @param {Number} userId 用户ID + * @return {Promise} 无返回值 + */ + async invalidateUser(userId) { + await this.forget( + KEYS.user(userId), + KEYS.userPrincipals(userId), + KEYS.principalOptions(userId) + ); + } + + /** + * 用户与主体的绑定关系变更后失效:主体ID列表 + 可选主体列表 + * @param {Number} userId 用户ID + * @return {Promise} 无返回值 + */ + async invalidateUserPrincipals(userId) { + await this.forget(KEYS.userPrincipals(userId), KEYS.principalOptions(userId)); + } + + /** + * 主体新增/更新/删除后失效:主体详情 + 所有依赖主体信息的缓存 + * (主体名称与状态变化会影响任意用户的可选主体列表,故按前缀整体失效) + * @param {Number} principalId 主体ID + * @return {Promise} 无返回值 + */ + async invalidatePrincipal(principalId) { + await this.forget(KEYS.principal(principalId)); + await this.forgetByPrefix(`${PREFIX}:principal-options:`); + await this.forgetByPrefix(`${PREFIX}:user-principals:`); + } +} + +module.exports = CacheService; diff --git a/backend/config/config.default.js b/backend/config/config.default.js index 6255f77..f4fb388 100644 --- a/backend/config/config.default.js +++ b/backend/config/config.default.js @@ -3,6 +3,7 @@ // 加载项目根目录 .env(敏感配置不入库);文件不存在时自动忽略 require('dotenv').config(); +const path = require('path'); const db = require('../database/config').development; /** @@ -25,8 +26,30 @@ module.exports = appInfo => { config.requestLog = { keepDays: Number(process.env.REQUEST_LOG_KEEP_DAYS || 60), maxBodyLength: Number(process.env.REQUEST_LOG_MAX_BODY || 2000), - // 不记录的路径前缀(Swagger 静态资源等) - excludePaths: [ '/swagger' ], + // 不记录的路径前缀(Swagger 静态资源、图片读取等) + excludePaths: [ '/swagger', '/api/files/raw' ], + }; + + // 文件上传:使用 file 模式(先落临时文件再由控制器处理),仅允许图片 + config.multipart = { + mode: 'file', + fileSize: '20mb', + files: 10, + whitelist: [ '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg' ], + }; + + // 文件资源存储:按「主体ID/年/月/日」分层,由上传时间决定(见 app/controller/file.js) + config.upload = { + dir: process.env.UPLOAD_DIR || path.join(appInfo.baseDir, 'uploads'), + // 访问前缀,与 router.js 中 /api/files/raw 保持一致 + urlPrefix: '/api/files/raw', + }; + + // 对外通用回调接口(POST /openapi):展示给外部系统配置的回调服务地址前缀 + // 未配置时按请求访问地址(ctx.protocol + ctx.host)动态生成,便于本地联调; + // 部署在网关/Nginx 后请用 OMS_CALLBACK_BASE_URL 指定对外可访问的地址 + config.omsCallback = { + baseUrl: (process.env.OMS_CALLBACK_BASE_URL || '').replace(/\/+$/, ''), }; // close csrf for easy debugging, please enable it in production if needed @@ -65,6 +88,14 @@ module.exports = appInfo => { from: process.env.SMTP_FROM || 'noreply@oms.local', }; + // AI 智能识别(收件人信息解析):与 WMS 复用同一套配置 + // 配置项与 WMS 保持一致(config.deepseek = { apiKey, baseUrl }),密钥走 .env 的 DEEPSEEK_API_KEY + // 未配置 apiKey 时相关接口返回 400 并提示配置,不影响其它功能 + config.deepseek = { + apiKey: process.env.DEEPSEEK_API_KEY || '', + baseUrl: 'https://api.deepseek.com', + }; + // Redis 配置:缓存邮箱验证码等数据,敏感信息建议用环境变量覆盖 config.redis = { client: { @@ -75,6 +106,14 @@ module.exports = appInfo => { }, }; + // 业务缓存有效期(秒):用户信息、主体信息、可选主体列表 + // 主体/用户发生新增或更新时,相关缓存会被主动失效,这里的 TTL 仅作为兜底 + config.cache = { + user: Number(process.env.CACHE_TTL_USER || 600), + principal: Number(process.env.CACHE_TTL_PRINCIPAL || 600), + principalOptions: Number(process.env.CACHE_TTL_PRINCIPAL_OPTIONS || 600), + }; + // 邮箱验证码限流:同一邮箱发送间隔(秒)与每日发送上限 config.emailCode = { interval: Number(process.env.EMAIL_CODE_INTERVAL || 60), diff --git a/backend/database/migrations/20260909000600-add-component-to-menus.js b/backend/database/migrations/20260909000600-add-component-to-menus.js new file mode 100644 index 0000000..824cdd2 --- /dev/null +++ b/backend/database/migrations/20260909000600-add-component-to-menus.js @@ -0,0 +1,23 @@ +'use strict'; + +/** 6.1 菜单表补充 component 字段:用于前端动态路由映射到具体页面组件 */ +module.exports = { + async up(queryInterface, Sequelize) { + const exists = await queryInterface + .describeTable('menus') + .then((cols) => Boolean(cols.component)) + .catch(() => false); + + if (exists) return; + + await queryInterface.addColumn('menus', 'component', { + type: Sequelize.STRING(200), + allowNull: true, + comment: '前端组件路径,如 views/system/user/index.vue', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('menus', 'component'); + }, +}; diff --git a/backend/database/migrations/20260909000700-seed-menus.js b/backend/database/migrations/20260909000700-seed-menus.js new file mode 100644 index 0000000..8278e8a --- /dev/null +++ b/backend/database/migrations/20260909000700-seed-menus.js @@ -0,0 +1,87 @@ +'use strict'; + +/** + * 7. 种子菜单:依据后端已有功能模块设计菜单树,供前端通过 /api/menus/tree 拉取并动态生成侧边栏与路由。 + * 菜单 component 字段指向前端 views 下的页面(默认统一指向 views/Generic.vue 占位页)。 + * 仅在 menus 表为空时插入,避免重复。 + */ +const seedMenus = [ + { + name: '仪表盘', type: 2, path: '/dashboard', icon: 'HomeFilled', + component: 'views/Home.vue', sort: 100, + }, + { + name: '系统管理', type: 1, icon: 'Setting', sort: 90, + children: [ + { name: '用户管理', type: 2, path: '/system/user', icon: 'User', permission: 'user:list', component: 'views/Generic.vue', sort: 90 }, + { name: '主体管理', type: 2, path: '/system/principal', icon: 'OfficeBuilding', permission: 'principal:list', component: 'views/Principal/Index.vue', sort: 80 }, + { name: '主体用户', type: 2, path: '/system/principal-user', icon: 'Connection', permission: 'principalUser:list', component: 'views/Generic.vue', sort: 70 }, + { name: '菜单管理', type: 2, path: '/system/menu', icon: 'Menu', permission: 'menu:list', component: 'views/Generic.vue', sort: 60 }, + { name: '外部API', type: 2, path: '/system/external-api', icon: 'Link', permission: 'principalExternalApi:list', component: 'views/Generic.vue', sort: 50 }, + ], + }, + { + name: '商品管理', type: 1, icon: 'Goods', sort: 80, + children: [ + { name: '商品', type: 2, path: '/product', icon: 'Box', permission: 'product:list', component: 'views/Generic.vue', sort: 80 }, + { name: '组合商品', type: 2, path: '/combo-product', icon: 'Files', permission: 'comboProduct:list', component: 'views/Generic.vue', sort: 70 }, + ], + }, + { + name: '订单管理', type: 1, icon: 'List', sort: 70, + children: [ + { name: '订单', type: 2, path: '/order', icon: 'Tickets', permission: 'order:list', component: 'views/Generic.vue', sort: 70 }, + ], + }, +]; + +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + + const [rows] = await sequelize.query('SELECT COUNT(*) AS count FROM menus', { + type: sequelize.QueryTypes.SELECT, + }); + if (Number(rows.count) > 0) return; // 已存在菜单数据,跳过种子 + + async function insertMenu(m, parentId) { + await sequelize.query( + `INSERT INTO menus + (parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + { + replacements: [ + parentId, + m.name, + m.type, + m.path || null, + m.icon || null, + m.permission || null, + m.component || null, + m.sort || 0, + 1, + ], + } + ); + const [idRows] = await sequelize.query('SELECT LAST_INSERT_ID() AS id', { + type: sequelize.QueryTypes.SELECT, + }); + return Number(idRows.id); + } + + async function insertTree(list, parentId) { + for (const m of list) { + const id = await insertMenu(m, parentId); + if (m.children && m.children.length) { + await insertTree(m.children, id); + } + } + } + + await insertTree(seedMenus, 0); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query('DELETE FROM menus'); + }, +}; diff --git a/backend/database/migrations/20260909000701-update-principal-menu-component.js b/backend/database/migrations/20260909000701-update-principal-menu-component.js new file mode 100644 index 0000000..2f082c2 --- /dev/null +++ b/backend/database/migrations/20260909000701-update-principal-menu-component.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * 将已存在的“主体管理”菜单 component 由占位页 views/Generic.vue + * 修正为真实页面 views/Principal/Index.vue(前端已实现主体列表管理页)。 + * 幂等:仅当 component 仍为占位页时才更新。 + */ +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + await sequelize.query( + `UPDATE menus SET component = ? + WHERE name = ? AND path = ? AND type = 2 AND component = ?`, + { + replacements: [ + 'views/Principal/Index.vue', + '主体管理', + '/system/principal', + 'views/Generic.vue', + ], + } + ); + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + await sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`, + { + replacements: ['views/Generic.vue', '主体管理', '/system/principal'], + } + ); + }, +}; diff --git a/backend/database/migrations/20260909000800-remove-principal-code.js b/backend/database/migrations/20260909000800-remove-principal-code.js new file mode 100644 index 0000000..0f9e216 --- /dev/null +++ b/backend/database/migrations/20260909000800-remove-principal-code.js @@ -0,0 +1,18 @@ +'use strict'; + +/** 移除主体编码字段(code)及其唯一索引 */ +module.exports = { + async up(queryInterface) { + await queryInterface.removeIndex('principals', 'uk_principals_code'); + await queryInterface.removeColumn('principals', 'code'); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.addColumn('principals', 'code', { + type: Sequelize.STRING(50), + allowNull: false, + comment: '主体编码', + }); + await queryInterface.addIndex('principals', { fields: [ 'code' ], unique: true, name: 'uk_principals_code' }); + }, +}; diff --git a/backend/database/migrations/20260909000900-adjust-menus.js b/backend/database/migrations/20260909000900-adjust-menus.js new file mode 100644 index 0000000..d684804 --- /dev/null +++ b/backend/database/migrations/20260909000900-adjust-menus.js @@ -0,0 +1,51 @@ +'use strict'; + +/** + * 调整菜单顺序:订单管理置顶(sort 100),系统管理置底(sort 70); + * 并将“主体用户”菜单由占位页 views/Generic.vue 指向真实页面 views/PrincipalUser/Index.vue。 + */ +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + // 根菜单(parent_id=0,含目录与仪表盘这种根级菜单)重排:订单管理第一、系统管理最后 + await sequelize.query( + `UPDATE menus SET sort = CASE name + WHEN '订单管理' THEN 100 + WHEN '商品管理' THEN 90 + WHEN '仪表盘' THEN 80 + WHEN '系统管理' THEN 70 + ELSE sort END + WHERE parent_id = 0`, + ); + // 主体用户菜单指向真实页面(仅当仍指向占位页时更新,幂等) + await sequelize.query( + `UPDATE menus SET component = ? + WHERE name = ? AND path = ? AND type = 2 AND component = ?`, + { + replacements: [ + 'views/PrincipalUser/Index.vue', + '主体用户', + '/system/principal-user', + 'views/Generic.vue', + ], + }, + ); + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + await sequelize.query( + `UPDATE menus SET sort = CASE name + WHEN '订单管理' THEN 70 + WHEN '商品管理' THEN 80 + WHEN '仪表盘' THEN 100 + WHEN '系统管理' THEN 90 + ELSE sort END + WHERE parent_id = 0`, + ); + await sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['views/Generic.vue', '主体用户', '/system/principal-user'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001000-rename-principal-user-menu.js b/backend/database/migrations/20260909001000-rename-principal-user-menu.js new file mode 100644 index 0000000..7936946 --- /dev/null +++ b/backend/database/migrations/20260909001000-rename-principal-user-menu.js @@ -0,0 +1,22 @@ +'use strict'; + +/** + * 菜单改名:系统管理下的“主体用户”改为“账号”。 + * 仅修改展示名,path 与 component 保持不变;内部标识(principal_users 表、 + * PrincipalUser 模型与 /api/principal-users 接口)不受影响。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['账号', '主体用户', '/system/principal-user'] }, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['主体用户', '账号', '/system/principal-user'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001100-remove-menu-management.js b/backend/database/migrations/20260909001100-remove-menu-management.js new file mode 100644 index 0000000..9ddd995 --- /dev/null +++ b/backend/database/migrations/20260909001100-remove-menu-management.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 移除侧边栏「系统管理 → 菜单管理」菜单项。 + * 注意:仅删除菜单记录,后端 /api/menus 接口(尤其 /api/menus/tree)必须保留, + * 它是前端动态菜单与路由的数据来源。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `DELETE FROM menus WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['菜单管理', '/system/menu'] }, + ); + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + // 回滚时重新挂回「系统管理」目录下 + const [parent] = await sequelize.query( + `SELECT id FROM menus WHERE name = ? AND parent_id = 0 AND type = 1 LIMIT 1`, + { replacements: ['系统管理'], type: sequelize.QueryTypes.SELECT }, + ); + if (!parent) return; + + await sequelize.query( + `INSERT INTO menus + (parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at) + VALUES (?, ?, 2, ?, ?, ?, ?, ?, 1, NOW(), NOW())`, + { + replacements: [ + parent.id, + '菜单管理', + '/system/menu', + 'Menu', + 'menu:list', + 'views/Generic.vue', + 60, + ], + }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001200-rename-external-api-menu.js b/backend/database/migrations/20260909001200-rename-external-api-menu.js new file mode 100644 index 0000000..34a0ec9 --- /dev/null +++ b/backend/database/migrations/20260909001200-rename-external-api-menu.js @@ -0,0 +1,22 @@ +'use strict'; + +/** + * 菜单改名:系统管理下的「外部API」改为「外部仓库」。 + * 仅修改展示名,path、权限标识与组件保持不变; + * 后端模块 principal_external_apis 与 /api/principal-external-apis 接口不受影响。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['外部仓库', '外部API', '/system/external-api'] }, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET name = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['外部API', '外部仓库', '/system/external-api'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001300-move-external-api-to-root.js b/backend/database/migrations/20260909001300-move-external-api-to-root.js new file mode 100644 index 0000000..918e94e --- /dev/null +++ b/backend/database/migrations/20260909001300-move-external-api-to-root.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * 将「外部仓库」由「系统管理」的子菜单提升为独立根菜单(parent_id = 0)。 + * sort 设为 75:排在仪表盘(80)之后、系统管理(70)之前, + * 从而保持「订单管理第一、系统管理最后」的整体顺序。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET parent_id = 0, sort = 75 WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['外部仓库', '/system/external-api'] }, + ); + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + // 回滚:重新挂回「系统管理」目录下,恢复原排序 + const [parent] = await sequelize.query( + `SELECT id FROM menus WHERE name = ? AND parent_id = 0 AND type = 1 LIMIT 1`, + { replacements: ['系统管理'], type: sequelize.QueryTypes.SELECT }, + ); + if (!parent) return; + + await sequelize.query( + `UPDATE menus SET parent_id = ?, sort = 50 WHERE name = ? AND path = ? AND type = 2`, + { replacements: [parent.id, '外部仓库', '/system/external-api'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001400-fix-dashboard-first.js b/backend/database/migrations/20260909001400-fix-dashboard-first.js new file mode 100644 index 0000000..e9ef089 --- /dev/null +++ b/backend/database/migrations/20260909001400-fix-dashboard-first.js @@ -0,0 +1,33 @@ +'use strict'; + +/** + * 菜单顺序调整:仪表盘固定在第一位,系统管理保持最后一位。 + * 根菜单排序(sort DESC):仪表盘 100 > 订单管理 90 > 商品管理 80 > 外部仓库 75 > 系统管理 70。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET sort = CASE name + WHEN '仪表盘' THEN 100 + WHEN '订单管理' THEN 90 + WHEN '商品管理' THEN 80 + WHEN '外部仓库' THEN 75 + WHEN '系统管理' THEN 70 + ELSE sort END + WHERE parent_id = 0`, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET sort = CASE name + WHEN '仪表盘' THEN 80 + WHEN '订单管理' THEN 100 + WHEN '商品管理' THEN 90 + WHEN '外部仓库' THEN 75 + WHEN '系统管理' THEN 70 + ELSE sort END + WHERE parent_id = 0`, + ); + }, +}; diff --git a/backend/database/migrations/20260909001500-update-user-menu-component.js b/backend/database/migrations/20260909001500-update-user-menu-component.js new file mode 100644 index 0000000..b1be601 --- /dev/null +++ b/backend/database/migrations/20260909001500-update-user-menu-component.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * 将「用户管理」菜单由占位页 views/Generic.vue + * 指向真实页面 views/User/Index.vue(前端已实现用户管理页:列表/修改资料/修改密码)。 + * 幂等:仅当 component 仍为占位页时才更新。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`, + { + replacements: [ + 'views/User/Index.vue', + '用户管理', + '/system/user', + 'views/Generic.vue', + ], + }, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['views/Generic.vue', '用户管理', '/system/user'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001600-user-menu-to-profile.js b/backend/database/migrations/20260909001600-user-menu-to-profile.js new file mode 100644 index 0000000..cb538d6 --- /dev/null +++ b/backend/database/migrations/20260909001600-user-menu-to-profile.js @@ -0,0 +1,41 @@ +'use strict'; + +/** + * 「用户管理」改为「我的」:自助的个人中心页(修改自己的资料 / 修改自己的密码), + * 不再管理全部用户。 + * - name: 用户管理 -> 我的 + * - component: views/User/Profile.vue + * - permission: 置空,所有登录账号均可见(前端未做权限拦截,仅作标记) + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET name = ?, component = ?, permission = NULL + WHERE name = ? AND path = ? AND type = 2`, + { + replacements: [ + '我的', + 'views/User/Profile.vue', + '用户管理', + '/system/user', + ], + }, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET name = ?, component = ?, permission = ? + WHERE name = ? AND path = ? AND type = 2`, + { + replacements: [ + '用户管理', + 'views/User/Index.vue', + 'user:list', + '我的', + '/system/user', + ], + }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001700-update-external-api-menu-component.js b/backend/database/migrations/20260909001700-update-external-api-menu-component.js new file mode 100644 index 0000000..80fd197 --- /dev/null +++ b/backend/database/migrations/20260909001700-update-external-api-menu-component.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * 将「外部仓库」菜单由占位页 views/Generic.vue + * 指向真实页面 views/ExternalApi/Index.vue(前端已实现外部仓库配置管理页)。 + * 幂等:仅当 component 仍为占位页时才更新。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`, + { + replacements: [ + 'views/ExternalApi/Index.vue', + '外部仓库', + '/system/external-api', + 'views/Generic.vue', + ], + }, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['views/Generic.vue', '外部仓库', '/system/external-api'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001800-update-product-menu-components.js b/backend/database/migrations/20260909001800-update-product-menu-components.js new file mode 100644 index 0000000..fd7bf0c --- /dev/null +++ b/backend/database/migrations/20260909001800-update-product-menu-components.js @@ -0,0 +1,39 @@ +'use strict'; + +/** + * 将「商品管理」下的「商品」「组合商品」菜单由占位页 views/Generic.vue + * 分别指向真实页面 views/Product/Index.vue 与 views/ComboProduct/Index.vue。 + * 幂等:仅当 component 仍为占位页时才更新。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`, + { + replacements: ['views/Product/Index.vue', '商品', '/product', 'views/Generic.vue'], + }, + ); + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`, + { + replacements: [ + 'views/ComboProduct/Index.vue', + '组合商品', + '/combo-product', + 'views/Generic.vue', + ], + }, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['views/Generic.vue', '商品', '/product'] }, + ); + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['views/Generic.vue', '组合商品', '/combo-product'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909001900-update-order-menu-component.js b/backend/database/migrations/20260909001900-update-order-menu-component.js new file mode 100644 index 0000000..fb72a4b --- /dev/null +++ b/backend/database/migrations/20260909001900-update-order-menu-component.js @@ -0,0 +1,24 @@ +'use strict'; + +/** + * 将「订单管理 → 订单」菜单由占位页 views/Generic.vue + * 指向真实页面 views/Order/Index.vue(前端已实现订单列表/编辑/状态流转)。 + * 幂等:仅当 component 仍为占位页时才更新。 + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2 AND component = ?`, + { + replacements: ['views/Order/Index.vue', '订单', '/order', 'views/Generic.vue'], + }, + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + `UPDATE menus SET component = ? WHERE name = ? AND path = ? AND type = 2`, + { replacements: ['views/Generic.vue', '订单', '/order'] }, + ); + }, +}; diff --git a/backend/database/migrations/20260909002000-seed-shop-menus.js b/backend/database/migrations/20260909002000-seed-shop-menus.js new file mode 100644 index 0000000..5ae11d0 --- /dev/null +++ b/backend/database/migrations/20260909002000-seed-shop-menus.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 13. 新增「店铺管理」菜单(店铺页面)。「店铺商品」菜单见后续迁移,挂在「商品管理」下。 + * 按 name 判重,重复执行不会插入多条。 + */ +const menus = [ + { + name: '店铺管理', + type: 1, + icon: 'Shop', + sort: 85, + children: [ + { + name: '店铺', + type: 2, + path: '/shop', + icon: 'Shop', + permission: 'shop:list', + component: 'views/Shop/Index.vue', + sort: 80, + }, + ], + }, +]; + +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + + async function findMenu(name, parentId) { + const [ rows ] = await sequelize.query( + 'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1', + { replacements: [ name, parentId ], type: sequelize.QueryTypes.SELECT } + ); + return rows ? Number(rows.id) : null; + } + + async function insertMenu(m, parentId) { + await sequelize.query( + `INSERT INTO menus + (parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`, + { + replacements: [ + parentId, + m.name, + m.type, + m.path || null, + m.icon || null, + m.permission || null, + m.component || null, + m.sort || 0, + ], + } + ); + const [ idRows ] = await sequelize.query('SELECT LAST_INSERT_ID() AS id', { + type: sequelize.QueryTypes.SELECT, + }); + return Number(idRows.id); + } + + async function upsertTree(list, parentId) { + for (const m of list) { + let id = await findMenu(m.name, parentId); + if (!id) id = await insertMenu(m, parentId); + if (m.children && m.children.length) await upsertTree(m.children, id); + } + } + + await upsertTree(menus, 0); + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + const [ rows ] = await sequelize.query( + "SELECT id FROM menus WHERE name = '店铺管理' AND parent_id = 0 LIMIT 1", + { type: sequelize.QueryTypes.SELECT } + ); + if (!rows) return; + + await sequelize.query('DELETE FROM menus WHERE parent_id = ? OR id = ?', { + replacements: [ Number(rows.id), Number(rows.id) ], + }); + }, +}; diff --git a/backend/database/migrations/20260909002100-seed-shop-product-under-goods.js b/backend/database/migrations/20260909002100-seed-shop-product-under-goods.js new file mode 100644 index 0000000..01c91e5 --- /dev/null +++ b/backend/database/migrations/20260909002100-seed-shop-product-under-goods.js @@ -0,0 +1,52 @@ +'use strict'; + +/** + * 14. 将「店铺商品」菜单挂在「商品管理」下(与商品、组合商品并列)。 + * 兼容两种情况:全新库(尚未插入)或已有库(曾挂在店铺管理下,需移动到商品管理)。 + * 按 name 定位节点,幂等可重跑。 + */ +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + + const [ goods ] = await sequelize.query( + "SELECT id FROM menus WHERE name = '商品管理' AND parent_id = 0 LIMIT 1", + { type: sequelize.QueryTypes.SELECT } + ); + if (!goods) return; // 商品管理节点不存在则跳过(理论上不应发生) + const goodsId = Number(goods.id); + + const [ exist ] = await sequelize.query( + "SELECT id, parent_id FROM menus WHERE name = '店铺商品' LIMIT 1", + { type: sequelize.QueryTypes.SELECT } + ); + + if (exist) { + if (Number(exist.parent_id) === goodsId) return; // 已正确挂接,无需处理 + await sequelize.query( + 'UPDATE menus SET parent_id = ?, sort = ? WHERE id = ?', + { replacements: [ goodsId, 65, Number(exist.id) ] } + ); + } else { + await sequelize.query( + `INSERT INTO menus + (parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at) + VALUES (?, '店铺商品', 2, '/shop-product', 'GoodsFilled', 'shopProduct:list', 'views/ShopProduct/Index.vue', 65, 1, NOW(), NOW())`, + { replacements: [ goodsId ] } + ); + } + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + const [ goods ] = await sequelize.query( + "SELECT id FROM menus WHERE name = '商品管理' AND parent_id = 0 LIMIT 1", + { type: sequelize.QueryTypes.SELECT } + ); + if (!goods) return; + await sequelize.query( + "DELETE FROM menus WHERE name = '店铺商品' AND parent_id = ?", + { replacements: [ Number(goods.id) ] } + ); + }, +}; diff --git a/backend/database/migrations/20260909002400-seed-stock-menus.js b/backend/database/migrations/20260909002400-seed-stock-menus.js new file mode 100644 index 0000000..69a5928 --- /dev/null +++ b/backend/database/migrations/20260909002400-seed-stock-menus.js @@ -0,0 +1,95 @@ +'use strict'; + +/** + * 24. 新增「库存管理」菜单:入库单、出库单两个页面(component 指向前端 views)。 + * 按 name + parent_id 判重,重复执行不会插入多条。 + */ +const menus = [ + { + name: '库存管理', + type: 1, + icon: 'Box', + sort: 82, + children: [ + { + name: '入库单', + type: 2, + path: '/inbound-order', + icon: 'Bottom', + permission: 'inboundOrder:list', + component: 'views/InboundOrder/Index.vue', + sort: 75, + }, + { + name: '出库单', + type: 2, + path: '/outbound-order', + icon: 'Top', + permission: 'outboundOrder:list', + component: 'views/OutboundOrder/Index.vue', + sort: 70, + }, + ], + }, +]; + +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + + async function findMenu(name, parentId) { + const [ rows ] = await sequelize.query( + 'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1', + { replacements: [ name, parentId ], type: sequelize.QueryTypes.SELECT } + ); + return rows ? Number(rows.id) : null; + } + + async function insertMenu(m, parentId) { + await sequelize.query( + `INSERT INTO menus + (parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`, + { + replacements: [ + parentId, + m.name, + m.type, + m.path || null, + m.icon || null, + m.permission || null, + m.component || null, + m.sort || 0, + ], + } + ); + const [ idRows ] = await sequelize.query('SELECT LAST_INSERT_ID() AS id', { + type: sequelize.QueryTypes.SELECT, + }); + return Number(idRows.id); + } + + async function upsertTree(list, parentId) { + for (const m of list) { + let id = await findMenu(m.name, parentId); + if (!id) id = await insertMenu(m, parentId); + if (m.children && m.children.length) await upsertTree(m.children, id); + } + } + + await upsertTree(menus, 0); + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + const [ rows ] = await sequelize.query( + "SELECT id FROM menus WHERE name = '库存管理' AND parent_id = 0 LIMIT 1", + { type: sequelize.QueryTypes.SELECT } + ); + if (!rows) return; + + await sequelize.query('DELETE FROM menus WHERE parent_id = ? OR id = ?', { + replacements: [ Number(rows.id), Number(rows.id) ], + }); + }, +}; diff --git a/backend/database/migrations/20260911000100-create-files.js b/backend/database/migrations/20260911000100-create-files.js new file mode 100644 index 0000000..a6a01a6 --- /dev/null +++ b/backend/database/migrations/20260911000100-create-files.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 文件资源表 files: + * 1) 记录上传文件的大小、原始名称、内容 hash 与存储路径,便于按 hash 去重与审计 + * 2) 文件按主体区分:同一主体下 hash 唯一(uk_files_principal_hash),不同主体互不影响 + * 3) 磁盘目录按「主体ID/年/月/日」分层,由上传时间决定(见 app/controller/file.js) + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable( + 'files', + { + id: { type: Sequelize.BIGINT.UNSIGNED, autoIncrement: true, primaryKey: true, comment: '主键' }, + principal_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '所属主体ID', + references: { model: 'principals', key: 'id' }, + onDelete: 'CASCADE', + }, + hash: { type: Sequelize.STRING(64), allowNull: false, comment: '文件内容 SHA256,用于去重' }, + name: { type: Sequelize.STRING(255), allowNull: false, comment: '原始文件名' }, + ext: { type: Sequelize.STRING(20), allowNull: false, comment: '扩展名(小写,含点,如 .png)' }, + mime: { type: Sequelize.STRING(100), comment: 'MIME 类型' }, + size: { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '文件大小(字节)' }, + path: { type: Sequelize.STRING(255), allowNull: false, comment: '相对存储路径:主体ID/年/月/日/hash.ext' }, + url: { type: Sequelize.STRING(500), allowNull: false, comment: '访问地址' }, + deleted_at: { type: Sequelize.DATE, comment: '软删除时间' }, + created_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, + updated_at: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP') }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '文件资源' } + ); + + // 主体内按内容去重:同一份文件重复上传时直接复用已有记录与 URL + await queryInterface.addIndex('files', { + fields: [ 'principal_id', 'hash' ], + unique: true, + name: 'uk_files_principal_hash', + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('files'); + }, +};