feat(backend): 仪表盘报表接口、配置裁剪、单号 5 位与账号名称/头像

- 仪表盘报表:新增 app/service/dashboard.js + app/controller/dashboard.js +
  app/lib/billStatus.js,注册 GET /api/dashboard/report(jwtAuth + principalCheck),
  一次聚合返回概览指标、发货单/入库单/出库单状态分布与待办、近 N 天单据量与
  出入库数量趋势、库存 Top 商品、最近出入库流水;warehouse_id 只过滤单据与流水
  (product_stocks 无仓库维度);契约 dashboard* 同步到 swagger
- 接口配置裁剪:仓库接口配置只保留 api_version 与 item_name_with_spec;
  历史 warehouse_apis.extra 冗余键、owner_code 配置、递交/回传设置一并清理
  (迁移 20260915002400~02800)
- 入库/出库/发货单报文与字段对齐 WMS 标准:去掉 ownerCode、operatorCode 等多余字段,
  入库明细补 itemId;发货单明细去掉无意义的 owner_code(迁移 20260915002600)
- 单号 5 位起:四张单据表 AUTO_INCREMENT 提到 10000(迁移 20260915002900)
- 账号名称/头像按主体维护:principal_users 增 name/avatar 并回填(迁移 20260915003000/03100),
  新增 app/lib/accountProfile.js(关联表名称/头像 → users 兜底);审核人写入 operator/operator_name;
  register 不再写 nickname、updateProfile 仅接受邮箱/手机号
- 出库单推送/锁库存链路的配套调整(outboundOrderPush、订单与发货单控制器)

Co-Authored-By: GitHub Copilot <noreply@github.com>
This commit is contained in:
liufumingren 2026-09-14 16:09:35 +08:00
parent 09a5d31220
commit 489563a4b2
25 changed files with 1353 additions and 445 deletions

View File

@ -87,7 +87,6 @@ module.exports = {
password: { type: 'string', required: true, description: '登录密码(明文,不少于 6 位),服务端生成盐并加盐哈希存储' },
email: { type: 'string', required: true, description: '邮箱,全局唯一,需通过邮箱验证码认证' },
code: { type: 'string', required: true, description: '邮箱收到的 6 位验证码,10 分钟内有效' },
nickname: { type: 'string', description: '昵称,不传则默认与账号相同' },
phone: { type: 'string', description: '手机号' },
},
loginData: {
@ -151,8 +150,6 @@ module.exports = {
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: '手机号' },
},
@ -220,6 +217,8 @@ module.exports = {
id: { type: 'integer', description: '主键' },
principal_id: { type: 'integer', description: '主体ID' },
user_id: { type: 'integer', description: '用户ID' },
name: { type: 'string', description: '该账号在此主体下的显示名称(推送单据操作人取此值)' },
avatar: { type: 'string', description: '该账号在此主体下的头像 URL' },
role: { type: 'string', description: '该主体下的角色标识' },
is_default: { type: 'integer', description: '是否默认主体:1是 0否' },
status: { type: 'integer', description: '状态:1启用 0禁用' },
@ -231,13 +230,16 @@ module.exports = {
bindPrincipalUserRequest: {
principal_id: { type: 'integer', required: true, description: '主体ID' },
user_id: { type: 'integer', required: true, description: '用户ID' },
name: { type: 'string', description: '该账号在此主体下的显示名称' },
avatar: { type: 'string', description: '该账号在此主体下的头像 URL' },
role: { type: 'string', description: '角色标识,如 admin' },
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: '用户名称(昵称)' },
name: { type: 'string', required: true, description: '该账号在此主体下的名称(推送单据操作人取此值)' },
avatar: { type: 'string', description: '该账号在此主体下的头像 URL(选填)' },
principal_id: { type: 'integer', required: true, description: '目标主体ID,需当前账号已绑定该主体' },
},
invitePrincipalUserData: {
@ -937,18 +939,18 @@ module.exports = {
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 }' },
operator: { type: 'string', description: '操作人名称(审核时系统写入=审核人昵称/用户名,接口不可传)' },
operator_code: { type: 'string', description: '操作员编码(审核时系统写入=审核人用户ID;WMS 入库单报文不支持该字段,仅本地留存)' },
operate_time: { type: 'string', description: '操作时间(推送为 operateTime)' },
purchase_order_code: { type: 'string', description: '采购单号/关联单据号(推送为 relatedOrders.relatedOrder.orderCode)' },
expect_start_time: { type: 'string', description: '预计到货时间(推送为 expectedArriveTime)' },
expect_end_time: { type: 'string', description: '最迟预期到货时间(推送为 expectEndTime)' },
logistics_code: { type: 'string', description: '物流公司编码(SF/YTO/ZTO 等,推送为 logisticsCode)' },
logistics_name: { type: 'string', description: '物流公司名称(推送为 logisticsName,由物流公司下拉自动带出)' },
express_code: { type: 'string', description: '运单号(推送为 expressCode)' },
sender_info: { type: 'string', description: '发件人信息 JSON(仅本地留存:WMS 入库单报文不识别 senderInfo,不下发)' },
receiver_info: { type: 'string', description: '收件人信息 JSON(仅本地留存:WMS 入库单报文不识别 receiverInfo,不下发)' },
extend_props: { type: 'string', description: '扩展属性 JSON:{ key: value }(仅本地留存:不下发)' },
total_amount: { type: 'number', description: '单据总金额' },
remark: { type: 'string', description: '备注' },
void_at: { type: 'string', description: '作废时间(状态 5=已作废)' },
@ -965,18 +967,16 @@ module.exports = {
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: '预期到货开始时间' },
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 }' },
sender_info: { type: 'string', description: '发件人信息 JSON(仅本地留存:不下发 WMS)' },
receiver_info: { type: 'string', description: '收件人信息 JSON(仅本地留存:不下发 WMS)' },
extend_props: { type: 'string', description: '扩展属性 JSON:{ key: value }(仅本地留存:不下发 WMS)' },
total_amount: { type: 'number', description: '单据总金额' },
remark: { type: 'string', description: '备注' },
items: { type: 'array', itemType: 'createStockItemRequest', description: '明细,可随单一次性写入' },
@ -986,18 +986,16 @@ module.exports = {
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: '最迟预期到货时间' },
operate_time: { type: 'string', description: '操作时间(推送为 operateTime)' },
purchase_order_code: { type: 'string', description: '采购单号/关联单据号(推送为 relatedOrders.relatedOrder.orderCode)' },
expect_start_time: { type: 'string', description: '预计到货时间(推送为 expectedArriveTime)' },
expect_end_time: { type: 'string', description: '最迟预期到货时间(推送为 expectEndTime)' },
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 }' },
sender_info: { type: 'string', description: '发件人信息 JSON(仅本地留存:不下发 WMS)' },
receiver_info: { type: 'string', description: '收件人信息 JSON(仅本地留存:不下发 WMS)' },
extend_props: { type: 'string', description: '扩展属性 JSON:{ key: value }(仅本地留存:不下发 WMS)' },
total_amount: { type: 'number', description: '单据总金额' },
remark: { type: 'string', description: '备注' },
},
@ -1014,7 +1012,7 @@ module.exports = {
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: '操作人' },
operator: { type: 'string', description: '操作人(审核时系统写入=审核人昵称/用户名,接口不可传)' },
waybill_codes: { type: 'array', itemType: 'string', description: '运单号集合(WMS 出库确认回传,多包裹时为多个;列名对齐 wms_order_stockout;系统托管)' },
total_amount: { type: 'number', description: '单据总金额' },
remark: { type: 'string', description: '备注' },
@ -1046,7 +1044,6 @@ module.exports = {
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: '备注' },
express_code: { type: 'string', description: '快递公司编码(推送为 deliveryOrder.logisticsCode,如 SF/STO)' },
@ -1070,7 +1067,6 @@ module.exports = {
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: '备注' },
express_code: { type: 'string', description: '快递公司编码(推送为 deliveryOrder.logisticsCode,如 SF/STO)' },
@ -1129,7 +1125,7 @@ module.exports = {
express_code: { type: 'string', description: '运单号(面单号,系统托管:取号/回写链路写入,手工不填;多包裹时为首个运单号)' },
express_codes: { type: 'array', itemType: 'string', description: '运单号集合(WMS 发货确认回传,多包裹时为多个;系统托管)' },
logistics_area_code: { type: 'string', description: '快递区域编码(大头笔,系统托管)' },
operator_name: { type: 'string', description: 'ERP 审核人(奇门 operatorName)' },
operator_name: { type: 'string', description: 'ERP 审核人(奇门 operatorName):审核时系统写入 = 审核人在本主体下的账号名称(principal_users.name),接口不可传' },
oaid_order_source_code: { type: 'string', description: 'OAID 订单来源编码(手工单不填写)' },
source_order_codes: { type: 'string', description: '来源订单号集合(手工单不填写)' },
extend_props: { type: 'string', description: '请求级扩展属性 JSON(手工单固定写入 labels: 手工单)' },
@ -1238,7 +1234,6 @@ module.exports = {
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,手工建单直传)' },
@ -1259,7 +1254,6 @@ module.exports = {
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,手工建单直传)' },
@ -1275,7 +1269,6 @@ module.exports = {
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)' },
@ -1579,4 +1572,106 @@ module.exports = {
},
stockRecordPage: buildPage('stockRecord', '出入库记录(库存流水)列表'),
stockRecordListResponse: buildListResponse('stockRecordPage'),
// ---------- 仪表盘报表 dashboard ----------
/** 报表时间区间 */
dashboardRange: {
days: { type: 'integer', description: '趋势区间天数(7/14/30/90)' },
start_date: { type: 'string', description: '区间起始日 YYYY-MM-DD' },
end_date: { type: 'string', description: '区间结束日 YYYY-MM-DD(含当天)' },
},
/** 概览指标卡 */
dashboardOverview: {
product_count: { type: 'integer', description: '商品数(未删除)' },
shop_count: { type: 'integer', description: '店铺数' },
warehouse_count: { type: 'integer', description: '仓库数' },
stock_product_kind: { type: 'integer', description: '有库存记录的商品种类数' },
stock_quantity: { type: 'number', description: '库存总数量(正品+残次品)' },
stock_available: { type: 'number', description: '可用数量合计' },
stock_locked: { type: 'number', description: '锁定数量合计' },
stock_zc: { type: 'number', description: '正品库存数量(ZC)' },
stock_cc: { type: 'number', description: '残次品库存数量(CC)' },
bill_total: { type: 'integer', description: '单据总数(发货单+入库单+出库单,按仓库过滤后)' },
delivery_count_30d: { type: 'integer', description: '近 30 天发货单数' },
delivery_amount_30d: { type: 'number', description: '近 30 天发货单金额合计' },
},
/** 单据状态计数 */
dashboardStatusCount: {
status: { type: 'integer', description: '状态码:1待处理 2已审核 3已推送 4已完成 5已作废 9已取消' },
label: { type: 'string', description: '状态中文名' },
count: { type: 'integer', description: '该状态单据数' },
},
/** 单类单据统计 */
dashboardBill: {
key: { type: 'string', description: '单据类型:delivery 发货单 / inbound 入库单 / outbound 出库单' },
label: { type: 'string', description: '单据类型中文名' },
path: { type: 'string', description: '对应列表页前端路由,可用于点击跳转' },
total: { type: 'integer', description: '单据总数' },
by_status: { type: 'array', itemType: 'dashboardStatusCount', description: '各状态数量(含 0 的状态)' },
range_count: { type: 'integer', description: '区间内新增单据数' },
amount: { type: 'number', description: '区间内单据金额合计' },
wait_handle: { type: 'integer', description: '待处理(状态1)数量' },
wait_push: { type: 'integer', description: '已审核待推送(状态2)数量' },
wait_finish: { type: 'integer', description: '已推送待完成(状态3)数量' },
finished: { type: 'integer', description: '已完成(状态4)数量' },
voided: { type: 'integer', description: '已作废(状态5)数量' },
canceled: { type: 'integer', description: '已取消(状态9)数量' },
push_fail: { type: 'integer', description: '最近一次推送失败的数量(wms_push_result.success=false)' },
},
/** 待办项 */
dashboardTodo: {
key: { type: 'string', description: '待办标识' },
label: { type: 'string', description: '待办名称' },
count: { type: 'integer', description: '待处理数量' },
path: { type: 'string', description: '跳转的前端路由' },
query: { type: 'string', description: '跳转时附带的筛选条件(JSON),如 {"status":1};为空表示列表页无对应筛选' },
},
/** 趋势序列 */
dashboardSeries: {
key: { type: 'string', description: '序列标识:delivery/inbound/outbound 为单据量,inbound_qty/outbound_qty 为出入库数量' },
label: { type: 'string', description: '序列名称' },
unit: { type: 'string', description: '单位:单 / 件' },
values: { type: 'array', itemType: 'integer', description: '与 dates 一一对应的每日数值' },
},
/** 趋势数据 */
dashboardTrend: {
days: { type: 'integer', description: '区间天数' },
dates: { type: 'array', itemType: 'string', description: '日期数组 YYYY-MM-DD(升序)' },
series: { type: 'array', itemType: 'dashboardSeries', description: '趋势序列(按天补 0)' },
max_bill: { type: 'integer', description: '单据量序列的最大值(用于图表刻度,最小 1)' },
max_qty: { type: 'integer', description: '出入库数量序列的最大值(用于图表刻度,最小 1)' },
},
/** 库存 Top 商品 */
dashboardTopProduct: {
product_id: { type: 'integer', description: '系统商品ID' },
item_code: { type: 'string', description: '商品编码' },
item_name: { type: 'string', description: '商品名称' },
sku_property: { type: 'string', description: 'SKU 规格' },
stock_unit: { type: 'string', description: '库存单位' },
item_type: { type: 'string', description: '库存类型:ZC 正品 / CC 残次品' },
quantity: { type: 'number', description: '总数量' },
lock_quantity: { type: 'number', description: '锁定数量' },
available: { type: 'number', description: '可用数量' },
},
/** 区间内出入库数量合计 */
dashboardMovement: {
inbound_qty: { type: 'number', description: '区间内入库数量合计(来自库存流水 direction=1)' },
outbound_qty: { type: 'number', description: '区间内出库数量合计(来自库存流水 direction=2)' },
},
/** 仪表盘报表数据 */
dashboardReport: {
range: { type: 'dashboardRange', description: '报表区间' },
overview: { type: 'dashboardOverview', description: '概览指标' },
bills: { type: 'array', itemType: 'dashboardBill', description: '三类单据的统计(发货单/入库单/出库单)' },
todo: { type: 'array', itemType: 'dashboardTodo', description: '待办清单(仅返回数量大于 0 的项)' },
trend: { type: 'dashboardTrend', description: '近 N 天趋势' },
movement: { type: 'dashboardMovement', description: '区间内出入库数量合计' },
top_products: { type: 'array', itemType: 'dashboardTopProduct', description: '库存 Top 商品(按可用数量倒序)' },
recent_records: { type: 'array', itemType: 'stockRecord', description: '最近出入库流水' },
},
dashboardReportResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
message: { type: 'string', description: '提示信息' },
data: { type: 'dashboardReport', description: '仪表盘报表数据' },
},
};

View File

@ -116,7 +116,7 @@ class AuthController extends Controller {
*/
async register() {
const { ctx, app } = this;
const { username, password, email, code, nickname, phone } = ctx.request.body;
const { username, password, email, code, phone } = ctx.request.body;
if (!username || !password || !email || !code) {
ctx.status = 400;
@ -161,7 +161,8 @@ class AuthController extends Controller {
const salt = generateSalt();
const user = await ctx.model.User.create({
username,
nickname: nickname || username,
// 注册不再填写昵称:账号显示名称改到主体账号关联表(principal_users.name)维护
nickname: null,
email,
phone,
salt,
@ -202,8 +203,22 @@ class AuthController extends Controller {
}
// 返回用户所属主体列表,供前端判断是否已创建主体(多租户隔离);走缓存的可选主体列表
// 同时带出当前账号在每个主体下的名称/头像(principal_users.name / avatar),供右上角展示
const options = await ctx.service.cache.getUserPrincipalOptions(ctx.userId);
const principals = options.map(item => ({ id: item.id, name: item.name }));
const relations = await ctx.model.PrincipalUser.findAll({
where: { user_id: ctx.userId },
attributes: [ 'principal_id', 'name', 'avatar' ],
});
const relationMap = new Map(relations.map(r => [ Number(r.principal_id), r ]));
const principals = options.map(item => {
const relation = relationMap.get(Number(item.id));
return {
id: item.id,
name: item.name,
account_name: (relation && relation.name) || null,
account_avatar: (relation && relation.avatar) || null,
};
});
ctx.body = { code: 0, message: 'success', data: { ...user, principals } };
}
@ -408,8 +423,9 @@ class AuthController extends Controller {
/**
* @summary 修改当前登录用户资料
* @description 自助服务:仅可修改昵称、邮箱、手机号与头像,不涉及密码、账号与状态;
* 邮箱需校验格式与全局唯一性(排除自身)
* @description 自助服务:仅可修改邮箱与手机号,不涉及密码、账号与状态;
* 昵称/头像已改到「账号(主体账号关联)」处按主体维护(principal_users.name / avatar),
* 本接口不再接受 nickname / avatar
* @router put /api/auth/profile
* @apikey
* @request body updateProfileRequest *body
@ -425,7 +441,7 @@ class AuthController extends Controller {
return;
}
const { nickname, email, phone, avatar } = ctx.request.body;
const { email, phone } = ctx.request.body;
if (email && !EMAIL_REGEX.test(email)) {
ctx.status = 400;
@ -441,11 +457,10 @@ class AuthController extends Controller {
}
}
// 昵称/头像不再通过「我的」维护(改到账号处按主体设置),此处忽略传入值
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);

View File

@ -0,0 +1,42 @@
'use strict';
const { Controller } = require('egg');
/**
* @controller DashboardController 仪表盘报表
*
* 只读聚合接口:基于现有单据(发货单/入库单/出库单)、库存(product_stocks)
* 与库存流水(stock_records)生成概览指标、单据状态分布与待办、近 N 天趋势、
* 库存 Top 商品与最近流水。数据按主体隔离(principal_id 由 principalCheck 中间件校验)。
*/
class DashboardController extends Controller {
/**
* @summary 仪表盘报表数据
* @description 一次返回仪表盘所需的全部聚合数据,避免前端多次请求:
* overview 概览指标、bills 三类单据的状态分布与待办数、todo 待办清单(带跳转路径)、
* trend 近 N 天单据量与出入库数量趋势、top_products 库存 Top 商品、
* recent_records 最近出入库流水。
* 说明:product_stocks 只有 (principal_id, product_id, item_type) 维度,没有仓库字段,
* 因此 warehouse_id 只过滤单据与流水,不影响库存概览与 Top 商品。
* @router get /api/dashboard/report
* @apikey
* @request query integer principal_id 主体ID(前端拦截器自动注入)
* @request query integer days 趋势区间天数,支持 7/14/30/90,其他值按 7 处理
* @request query integer warehouse_id 仓库ID(可选,过滤单据与流水)
* @response 200 dashboardReportResponse success
*/
async report() {
const { ctx } = this;
const { days, warehouse_id: warehouseId } = ctx.query;
const data = await ctx.service.dashboard.report({
principalId: ctx.state.principalId,
days,
warehouseId: warehouseId ? Number(warehouseId) : null,
});
ctx.body = { code: 0, message: 'success', data };
}
}
module.exports = DashboardController;

View File

@ -5,6 +5,7 @@ const recalcStock = require('../utils/recalcStock');
const completeInbound = require('../utils/completeInbound');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { resolveAccountName } = require('../lib/accountProfile');
const QimenWmsClient = require('../lib/wms/qimenClient');
const { DEFAULT_INBOUND_ORDER_TYPE, INBOUND_ORDER_TYPE_LIST, normalizeInboundOrderType } = require('../lib/wms/orderTypes');
@ -59,6 +60,8 @@ function isUnsupportedCancelResponse(resp) {
const MANAGED_FIELDS = [
'bill_no', 'status', 'audit_by', 'audit_time', 'pushed_at', 'wms_push_result',
'void_at', 'void_by', 'void_reason', 'item_total', 'item_kind',
// 操作人与操作员编码由审核流程写入(操作人=审核人,编码=审核人用户ID),不接受接口传入
'operator', 'operator_code',
];
/**
@ -337,7 +340,18 @@ class InboundOrderController extends Controller {
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}
/** 审核:已创建(1) -> 已审核(2),并记录审核人与审核时间 */
/**
* 审核:已创建(1) -> 已审核(2),并记录审核人与审核时间
*
* **操作人 = 审核人**(无需表单传入,已入 MANAGED_FIELDS 接口不可写):
* - `operator` 取审核人在**本主体下的账号名称**(`principal_users.name`,未配置时回退 users.nickname/username),
* 推送时为 `entryOrder.operatorName`
* - `operator_code` 直接取用户ID 字符串(WMS 入库单报文不支持该字段,仅本地留存)
* @router post /api/inbound-orders/{id}/audit
* @apikey
* @request path integer *id 入库单主键ID
* @response 200 baseResponse success
*/
async audit() {
const { ctx } = this;
const id = Number(ctx.params.id);
@ -358,8 +372,16 @@ class InboundOrderController extends Controller {
ctx.body = { code: 400, message: '单据无明细,无法审核' };
return;
}
await order.update({ status: 2, audit_by: ctx.userId, audit_time: new Date() });
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
// 操作人取审核人在本主体下的账号名称(principal_users.name)
const operatorName = await resolveAccountName(ctx, ctx.userId, order.principal_id);
await order.update({
status: 2,
audit_by: ctx.userId,
audit_time: new Date(),
operator: operatorName,
operator_code: String(ctx.userId),
});
ctx.body = { code: 0, message: 'success', data: { id: order.id, operator: operatorName, operator_code: String(ctx.userId) } };
}
/**
* 推送:已审核(2) -> 已推送(3),并将入库单递交 WMS(entryorder.create)
@ -414,8 +436,25 @@ class InboundOrderController extends Controller {
const client = new QimenWmsClient(api, this.app);
const externalOrderCode = order.bill_no;
// 明细行 itemId(WMS 商品主键):取该仓库已推送商品的 wms_item_id,未建档的商品不带该字段(WMS 降级按 itemCode 匹配)
const Op = this.app.Sequelize.Op;
const productIds = items.map(i => (i.product_id != null ? Number(i.product_id) : null)).filter(Boolean);
const links = productIds.length
? await ctx.model.WarehouseProduct.findAll({
where: { principal_id: principalId, warehouse_id: order.warehouse_id, product_id: { [Op.in]: productIds } },
attributes: [ 'product_id', 'wms_item_id' ],
})
: [];
const wmsItemIdByProduct = {};
for (const l of links) {
if (l.wms_item_id != null) wmsItemIdByProduct[Number(l.product_id)] = Number(l.wms_item_id);
}
try {
const resp = await client.createEntryOrder(order, items, { warehouse: order.warehouse, creator: order.creator });
const resp = await client.createEntryOrder(order, items, {
warehouse: order.warehouse,
creator: order.creator,
wmsItemIdByProduct,
});
const success = client.isSuccess(resp);
const pushResult = {
success,

View File

@ -7,6 +7,7 @@ const recalcOrderDelivery = require('../utils/recalcOrderDelivery');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { lockDeliveryStock, releaseDeliveryStock } = require('../utils/deliveryStock');
const { isValidShopSyncStatus, SHOP_SYNC_STATUS_LIST } = require('../lib/shopSyncStatus');
const { resolveAccountName } = require('../lib/accountProfile');
const QimenWmsClient = require('../lib/wms/qimenClient');
const {
DELIVERY_ORDER_TYPE_LIST,
@ -78,6 +79,8 @@ const MANAGED_FIELDS = [
'pre_delivery_order_code', 'pre_delivery_order_id',
'order_flag', 'source_order_codes', 'oaid_order_source_code', 'oaid',
'extend_props',
// 操作人(奇门 operatorName)由审核流程写入 = 审核人在本主体下的账号名称,不接受接口传入
'operator_name',
];
/** 可编辑明细/单据头的状态:仅「待处理(1)」 */
@ -793,6 +796,8 @@ class OrderDeliveryController extends Controller {
// 审核即锁定库存(按明细 plan_qty 占用可用,可用不足则审核失败),并写 order_lock 流水;
// 库存锁定与状态流转同事务,避免『已审核但未锁定』的不一致
// 操作人 = 审核人:取审核人在本主体下的账号名称(principal_users.name),推送为 operatorName
const operatorName = await resolveAccountName(ctx, ctx.userId, order.principal_id);
const transaction = await ctx.model.transaction();
let lockResult;
try {
@ -802,6 +807,7 @@ class OrderDeliveryController extends Controller {
status: 2,
audit_by: ctx.userId,
audit_time: new Date(),
operator_name: operatorName,
pushed_at: null,
wms_push_result: null,
}, { transaction });

View File

@ -5,6 +5,7 @@ const recalcStock = require('../utils/recalcStock');
const { applyStockChange } = require('../utils/stockRecord');
const nextRejectedBillNo = require('../utils/rejectBillNo');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { resolveAccountName } = require('../lib/accountProfile');
const QimenWmsClient = require('../lib/wms/qimenClient');
const { DEFAULT_OUTBOUND_ORDER_TYPE, OUTBOUND_ORDER_TYPE_LIST, normalizeOutboundOrderType } = require('../lib/wms/orderTypes');
@ -21,6 +22,8 @@ const MANAGED_FIELDS = [
'bill_no', 'status', 'pushed_at', 'wms_push_result',
'void_at', 'void_by', 'void_reason', 'stock_deducted', 'stock_locked', 'item_total', 'item_kind',
'waybill_codes',
// 操作人由审核流程写入(=审核人),与入库单同口径,不接受接口传入
'operator',
];
/**
@ -283,7 +286,9 @@ class OutboundOrderController extends Controller {
* @description 状态流转:待出库(1) → 已审核(2);需先录入明细。
* **审核只入队不推送**:由定时任务(app/schedule/outboundOrderPush.js)异步递交 WMS stockout.create,
* 避免集中审核时把对方服务打满;也可用「推送」按钮立即推送(状态仍需为已审核)。
* 审核同时清空上一轮推送记录(重试次数归零)。推送失败的处理见 app/service/outboundOrderPush.js:
* 审核同时清空上一轮推送记录(重试计数归零)。**操作人 = 审核人**(无需表单传入,已入 MANAGED_FIELDS):
* `operator` 取审核人在本主体下的账号名称(`principal_users.name`,未配置时回退 users.nickname/username)。
* 推送失败的处理见 app/service/outboundOrderPush.js:
* 对方明确失败(含库存锁定失败)立即退回「待出库(1)」并释放锁定库存;无响应/超时最多尝试 3 次后同样退回。
* @router post /api/outbound-orders/{id}/audit
* @apikey
@ -309,12 +314,14 @@ class OutboundOrderController extends Controller {
ctx.body = { code: 400, message: '单据无明细,无法审核' };
return;
}
// 操作人取审核人在本主体下的账号名称(principal_users.name)
const operatorName = await resolveAccountName(ctx, ctx.userId, order.principal_id);
// 清空上一轮推送记录(重试次数从 0 开始),进入推送队列等待定时任务自动推送
await order.update({ status: 2, pushed_at: null, wms_push_result: null });
await order.update({ status: 2, operator: operatorName, pushed_at: null, wms_push_result: null });
ctx.body = {
code: 0,
message: '审核成功,已进入推送队列,稍后自动推送仓库',
data: { id: order.id, status: 2 },
data: { id: order.id, status: 2, operator: operatorName },
};
}
/**

View File

@ -108,7 +108,8 @@ class PrincipalUserController extends Controller {
/**
* @summary 邀请开通主体账号
* @description 传入邮箱、用户名称与主体ID,自动创建新用户(随机初始密码)并绑定到该主体(角色 member);
* @description 传入邮箱、用户名称(写入主体账号关联表 principal_users.name)与主体ID,
* 自动创建新用户(随机初始密码)并绑定到该主体(角色 member);
* 返回明文随机密码,需由调用方妥善交付给被邀请人;同一邮箱不可重复开通
* @router post /api/principal-users/invite
* @apikey
@ -118,7 +119,7 @@ class PrincipalUserController extends Controller {
async invite() {
const { ctx } = this;
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const { email, name, principal_id: principalId } = ctx.request.body;
const { email, name, avatar, principal_id: principalId } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
@ -161,7 +162,6 @@ class PrincipalUserController extends Controller {
try {
const user = await ctx.model.User.create({
username: email,
nickname: name,
email,
salt,
password: hashed,
@ -171,6 +171,9 @@ class PrincipalUserController extends Controller {
const relation = await ctx.model.PrincipalUser.create({
principal_id: principalId,
user_id: user.id,
// 账号显示名称/头像按主体维护(推送单据操作人取 name)
name: String(name).trim(),
avatar: avatar ? String(avatar).trim() : null,
role: 'member',
is_default: 0,
status: 1,
@ -188,7 +191,7 @@ class PrincipalUserController extends Controller {
relation_id: relation.id,
email: user.email,
username: user.username,
nickname: user.nickname,
nickname: relation.name,
password,
},
};
@ -214,7 +217,8 @@ class PrincipalUserController extends Controller {
/**
* @summary 更新关联信息
* @description 可修改角色、默认主体标识与状态
* @description 可修改该账号在此主体下的名称(name)、头像(avatar)、角色、默认主体标识与状态;
* 名称/头像即账号显示资料,推送单据的操作人取名称;不允许改归属(principal_id / user_id),非白名单字段一律忽略
* @router put /api/principal-users/{id}
* @apikey
* @request path integer *id 关联记录主键ID
@ -231,10 +235,34 @@ class PrincipalUserController extends Controller {
return;
}
delete ctx.request.body.principal_id;
await relation.update(ctx.request.body);
const body = ctx.request.body || {};
// 只接受名称/头像/角色/默认标识/状态,避免改归属或写入无关字段
const patch = {};
for (const key of [ 'name', 'avatar', 'role', 'is_default', 'status' ]) {
if (body[key] !== undefined) patch[key] = body[key];
}
if (patch.name !== undefined) {
const name = patch.name == null ? '' : String(patch.name).trim();
if (!name) {
ctx.status = 400;
ctx.body = { code: 400, message: '名称 name 不能为空' };
return;
}
patch.name = name;
}
if (patch.avatar !== undefined) {
patch.avatar = patch.avatar == null || String(patch.avatar).trim() === ''
? null
: String(patch.avatar).trim();
}
await relation.update(patch);
await ctx.service.cache.invalidateUserPrincipals(relation.user_id);
ctx.body = { code: 0, message: 'success', data: { id: relation.id } };
ctx.body = {
code: 0,
message: 'success',
data: { id: relation.id, name: relation.name, avatar: relation.avatar },
};
}
/**

View File

@ -0,0 +1,75 @@
'use strict';
/**
* 账号在「主体维度」下的资料(名称 / 头像)
*
* 口径(2026-09-14 按用户要求):同一账号在不同主体下可以有不同名称与头像,
* 数据落在主体账号关联表 `principal_users.name` / `principal_users.avatar`:
* - 推送单据的操作人取该关联表的名称(入库 entryOrder.operatorName、发货单 deliveryOrder.operatorName 等)
* - 页面右上角展示:有关联头像显示头像 → 无头像显示名称首字符 → 无名称显示账号(username)首字符
*
* 回退顺序(关联表未配置时保持旧行为,避免历史账号显示空白):
* name:principal_users.name → users.nickname → users.username
* avatar:principal_users.avatar → users.avatar
*/
/**
* 取账号在指定主体下的资料
* @param {Object} ctx egg context
* @param {Number|String} userId 用户ID
* @param {Number|String} principalId 主体ID(缺省时只取全局 users 字段)
* @return {Promise<{name: string, avatar: string}>} 名称与头像(可能为空串)
*/
async function resolveAccountProfile(ctx, userId, principalId) {
const id = Number(userId);
if (!id) return { name: '', avatar: '' };
let relation = null;
if (Number(principalId)) {
relation = await ctx.model.PrincipalUser.findOne({
where: { user_id: id, principal_id: Number(principalId) },
attributes: [ 'name', 'avatar' ],
});
}
let user = null;
if (!relation || !relation.name || !relation.avatar) {
user = await ctx.model.User.findByPk(id, { attributes: [ 'nickname', 'username', 'avatar' ] });
}
const name = (relation && relation.name)
|| (user && (user.nickname || user.username))
|| '';
const avatar = (relation && relation.avatar)
|| (user && user.avatar)
|| '';
return { name: String(name), avatar: String(avatar) };
}
/**
* 取账号在指定主体下的显示名称(推送单据操作人用)
* @param {Object} ctx egg context
* @param {Number|String} userId 用户ID
* @param {Number|String} principalId 主体ID
* @return {Promise<String>} 名称(兜底为空串)
*/
async function resolveAccountName(ctx, userId, principalId) {
const { name } = await resolveAccountProfile(ctx, userId, principalId);
return name;
}
/**
* 取展示用首字符:名称首字符(支持中文)→ 账号首字符
* @param {String} name 关联表名称
* @param {String} username 账号
* @return {String} 单个字符(都没有时返回空串)
*/
function firstCharOf(name, username) {
const source = String(name || '').trim() || String(username || '').trim();
if (!source) return '';
// 取首个「字」,避免把 emoji/代理对切一半
return Array.from(source)[0];
}
module.exports = { resolveAccountProfile, resolveAccountName, firstCharOf };

View File

@ -0,0 +1,43 @@
'use strict';
/**
* 单据状态常量(入库单 / 出库单 / 发货单通用口径)。
*
* 状态由业务事务推动,不提供直接改状态的接口:
* 1 待处理 → 2 已审核(audit)→ 3 已推送(push)→ 4 已完成(complete / WMS 回传确认)
* 另有 5 已作废(void,仅已审核可作废)、9 已取消(cancel,可 restore 恢复)
*
* 说明:状态文案的单一来源,供仪表盘报表等聚合场景复用,避免前后端枚举漂移。
*/
const BILL_STATUS = {
PENDING: 1,
AUDITED: 2,
PUSHED: 3,
DONE: 4,
VOID: 5,
CANCELED: 9,
};
const BILL_STATUS_LABELS = {
1: '待处理',
2: '已审核',
3: '已推送',
4: '已完成',
5: '已作废',
9: '已取消',
};
/** 列表展示顺序(与业务流转顺序一致,取消/作废排最后) */
const BILL_STATUS_ORDER = [ 1, 2, 3, 4, 5, 9 ];
const BILL_STATUS_LIST = BILL_STATUS_ORDER.map(value => ({
value,
label: BILL_STATUS_LABELS[value],
}));
module.exports = {
BILL_STATUS,
BILL_STATUS_LABELS,
BILL_STATUS_ORDER,
BILL_STATUS_LIST,
};

View File

@ -85,7 +85,6 @@ function buildItemRow(raw, opts = {}) {
ext_code: body.ext_code == null ? null : String(body.ext_code).trim(),
// 非 CC 一律落 ZP(正品),与出入库明细 inventory_type 口径一致
inventory_type: inventoryType === 'CC' ? 'CC' : 'ZP',
owner_code: body.owner_code == null ? null : String(body.owner_code).trim(),
source_order_code: body.source_order_code == null ? null : String(body.source_order_code).trim(),
sub_source_order_code: body.sub_source_order_code == null ? null : String(body.sub_source_order_code).trim(),
stock_id: body.stock_id == null || body.stock_id === '' ? null : Number(body.stock_id),

View File

@ -38,18 +38,11 @@ const FIELD_TYPE_LIST = Object.values(FIELD_TYPES);
* description:分组说明(可放配置帮助文档链接)
*/
const FIELD_GROUPS = [
{
key: 'basic',
label: '基础信息',
description: '账号配置帮助文档:https://s.jkyun.biz/IMqcSIg',
},
{
key: 'business',
label: '业务设置',
description: '业务设置奇门配置帮助文档',
},
{ key: 'submit', label: '递交设置' },
{ key: 'callback', label: '回传设置' },
];
/** 开关类型字段的默认值:默认不启用 */
@ -68,85 +61,17 @@ const SWITCH_OFF = false;
* description:字段说明(前端展示为提示文案)
*/
const WAREHOUSE_API_FIELDS = [
/* ---------- 基础信息 ---------- */
{
key: 'owner_alias',
group: 'basic',
label: '货主别名',
type: FIELD_TYPES.TEXT,
placeholder: '如 天豹云仓新WMS',
defaultValue: '天豹云仓新WMS',
description: '推送给外部系统的货主别名',
},
{
key: 'outsource_api_type',
group: 'basic',
label: '委外接口类型',
type: FIELD_TYPES.TEXT,
placeholder: '如 奇门-云谱WMS(appkey:23535631)',
description: '对接的委外仓接口类型',
},
{
key: 'customer_id',
group: 'basic',
label: '客户ID',
type: FIELD_TYPES.TEXT,
placeholder: '如 tbyc20260614',
defaultValue: 'tbyc20260614',
description: '外部系统分配的客户 ID',
},
{
key: 'owner_code',
group: 'basic',
label: '货主编码',
type: FIELD_TYPES.TEXT,
required: true,
placeholder: '如 tbyc20260614',
defaultValue: 'tbyc20260614',
description: '双方系统约定的货主(商家)编码',
},
// 说明(2026-09-14 按用户要求逐轮核实后精简 —— 配置项是 WMS 后台的一套设置,OMS 侧只用得上其中两项):
// - 「基础信息」分组已整体移除:customer_id 在 openapi 契约下恒为 null(奇门渠道才用于鉴权);
// owner_alias / outsource_api_type 无任何引用;owner_code 在 openapi 的三个推送接口均 required=false,
// 且 OMS 接收回传不看 ownerCode
// - 「递交设置」(submit)与「回传设置」(callback)两组已整体移除:35 项里只有 item_name_with_spec 在用
// - 「业务设置」里同样未被读取的项也已移除:purchase_return_code_type / transfer_in_code_type /
// transfer_out_code_type(出库/入库/退货类型编码已硬编码在 lib/wms/orderTypes.js 的枚举里)、
// sku_sync_key / barcode_sync_source(商品同步直接取 products.barcode/goods_code,不读配置)
// - 现仅保留两项真正被读取的:api_version(请求 v 参数)、item_name_with_spec(商品同步名称拼规格)
/* ---------- 业务设置 ---------- */
{
key: 'purchase_return_code_type',
group: 'business',
label: '采购退货代码类型',
type: FIELD_TYPES.SELECT,
defaultValue: 'CGTH',
options: [{ label: '采购退货(CGTH)', value: 'CGTH' }],
},
{
key: 'transfer_in_code_type',
group: 'business',
label: '调拨入库代码类型',
type: FIELD_TYPES.TEXT,
placeholder: '如 DBRK',
defaultValue: 'DBRK',
},
{
key: 'transfer_out_code_type',
group: 'business',
label: '调拨出库代码类型',
type: FIELD_TYPES.TEXT,
placeholder: '如 DBCK',
defaultValue: 'DBCK',
},
{
key: 'sku_sync_key',
group: 'business',
label: '货品同步SKU选择',
type: FIELD_TYPES.SELECT,
defaultValue: 'barcode',
options: [{ label: '[条码]作为双方系统识别商品SKU(不推荐,改条码有风险)', value: 'barcode' }],
},
{
key: 'barcode_sync_source',
group: 'business',
label: '货品同步条码选择',
type: FIELD_TYPES.SELECT,
defaultValue: 'product_barcode',
options: [{ label: '货品档案条码', value: 'product_barcode' }],
},
{
key: 'api_version',
group: 'business',
@ -158,258 +83,14 @@ const WAREHOUSE_API_FIELDS = [
{ label: 'V1.0', value: 'V1.0' },
],
},
/* ---------- 递交设置 ---------- */
// 货品同步名称带规格:商品推送(singleitem.synchronize)时是否把 sku_property 拼到 itemName
{
key: 'item_name_with_spec',
group: 'submit',
group: 'business',
label: '货品同步名称带规格',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'barcode_with_aux',
group: 'submit',
label: '货品同步条码带辅助条码',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'push_face_sheet',
group: 'submit',
label: '把物流面单数据传给WMS',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'order_info_not_push',
group: 'submit',
label: '递交订单时信息不传给仓库',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'shop_name_by_channel',
group: 'submit',
label: '销售单递交的店铺名称按渠道',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'price_shared_discount',
group: 'submit',
label: '递交使用分摊优惠后商品单价',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'platform_no_cut_length',
group: 'submit',
label: '截取电商平台订单号、支付单号长度',
type: FIELD_TYPES.NUMBER,
defaultValue: 0,
min: 0,
max: 50,
description: '截取长度,0 表示不截取;订单号与支付单号同时生效',
},
{
key: 'clear_logistics_no',
group: 'submit',
label: '已有物流单号的销售单,递交仓库发货时清空物流单号再进行递交',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'sync_order_custom_fields',
group: 'submit',
label: '订单级自定义字段同步递交给仓库',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'order_custom_fields_map',
group: 'submit',
label: '订单级自定义字段映射设置',
type: FIELD_TYPES.JSON,
description: '「设置」维护的映射,JSON 对象 { 订单字段: 仓库字段 }',
},
{
key: 'sync_item_custom_fields',
group: 'submit',
label: '货品级自定义字段同步递交给仓库',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'item_custom_fields_map',
group: 'submit',
label: '货品级自定义字段映射设置',
type: FIELD_TYPES.JSON,
description: '「设置」维护的映射,JSON 对象 { 货品字段: 仓库字段 }',
},
{
key: 'sender_company_use_shop',
group: 'submit',
label: '发件人公司使用店铺名称',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'consignment_doc_submit',
group: 'submit',
label: '寄售业务单据递交WMS,创建发货单或退货入库单',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'allow_invalid_item_order',
group: 'submit',
label: '允许无效货品订单递交仓库发货',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'order_flag_not_sync',
group: 'submit',
label: '订单标记无需同步递交给仓库',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'order_flag_setting',
group: 'submit',
label: '订单标记设置',
type: FIELD_TYPES.JSON,
description: '「设置」维护的订单标记规则,JSON 对象',
},
{
key: 'outsource_logistics_by_number',
group: 'submit',
label: '以取号返回的实际物流公司递交委外仓,回传不改订单的物流公司',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'wechat_dropship',
group: 'submit',
label: '使用微信代发模式',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'wechat_supplier_id',
group: 'submit',
label: '微店供应商ID',
type: FIELD_TYPES.TEXT,
placeholder: '使用微信代发模式时填写',
},
{
key: 'other_channel_flag_to_other',
group: 'submit',
label: '订单含指定标记时,递交委外仓的渠道为OTHER',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'other_channel_flag_setting',
group: 'submit',
label: '委外仓渠道为OTHER的设置',
type: FIELD_TYPES.JSON,
description: '「设置」维护需转为 OTHER 的订单标记,JSON 对象',
},
/* ---------- 回传设置 ---------- */
{
key: 'stock_change_type_mapping',
group: 'callback',
label: '库存异动回传单据类型映射',
type: FIELD_TYPES.JSON,
description: '「设置」维护的单据类型映射,JSON 对象',
},
{
key: 'stock_change_warehouse_strategy',
group: 'callback',
label: '库存异动仓库匹配策略',
type: FIELD_TYPES.JSON,
description: '「设置」维护的仓库匹配策略,JSON 对象',
},
{
key: 'salereturn_stock_in_type',
group: 'callback',
label: '销退入库类型库存异动',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'callback_by_actual_stock',
group: 'callback',
label: '按实际库存异动回传',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'aftersale_defect_callback',
group: 'callback',
label: '生成售后异常件回传',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'use_wms_warehouse_code',
group: 'callback',
label: '使用仓储方的仓库编码',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'forbid_stock_change_modify_erp',
group: 'callback',
label: '不允许仓库通过库存异动方式修改ERP库存',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'outbound_by_actual_qty',
group: 'callback',
label: '按实发数量生成出库单',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'allow_order_flow_write_logistics',
group: 'callback',
label: '允许订单流水通知写入物流单号',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'order_flow_abnormal_to_abnormal',
group: 'callback',
label: '订单流水通知回传“异常”时,销售单转入异常订单',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'order_flow_cancel_force_cancel',
group: 'callback',
label: '订单流水通知回传“取消”时,销售单强制取消发货单',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'outbound_time_use_current',
group: 'callback',
label: '仓库发货回传时,销售单“发货时间”使用当前时间',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
{
key: 'unique_code_allow_outsource',
group: 'callback',
label: '唯一码订单平台校验未通过时允许委外仓发货',
type: FIELD_TYPES.SWITCH,
defaultValue: SWITCH_OFF,
},
];
/** 字段 key 集合(用于校验入参) */

View File

@ -326,30 +326,60 @@ class QimenWmsClient {
}
/**
* 构建 entryorder.create 请求体(对齐 WMS 入库单规范)
* 字段来源:单据头 + 明细(含商品快照),货主编码取接口配置 owner_code,仓库编码取 warehouse.code
* 构建 entryorder.create 请求体(对齐 WMS `entryorder.create` 标准报文)
*
* 实际下发字段(见 `D:/wms/methods/openapi.json` 的 params:openapi 渠道除 entryOrderCode 外均为选填):
* entryOrder:entryOrderCode / entryOrderType / warehouseCode / orderCreateTime /
* expectedArriveTime / expectEndTime / totalOrderLines / supplierCode / supplierName /
* logisticsCode / logisticsName / expressCode / remark / operateTime / operatorName /
* relatedOrders.relatedOrder.orderCode(关联采购单号)
* orderLines.orderLine:orderLineNo / itemCode / itemId / itemName / planQty / inventoryType
* 已不再下发:entryOrder 的 ownerCode(openapi 不要求,不传 WMS 落空串;见 warehouseApiFields.js 说明)、
* purchaseOrderCode(改用 relatedOrders)、operatorCode、senderInfo、receiverInfo、extendProps;
* 行级 outBizCode / ownerCode / skuProperty / purchasePrice / retailPrice(WMS 不识别)。
* @param {Object} order OMS 入库单(model 实例或 plain,已 include warehouse/creator)
* @param {Array} items 入库明细(stock_items,已 include product)
* @param {Object} [opts] { warehouse, creator }
* @param {Object} [opts] { warehouse, creator, wmsItemIdByProduct }
* @return {Object} { entryOrder, orderLines: { orderLine: [...] } }
*/
_buildEntryOrder(order, items, opts = {}) {
const o = order.get ? order.get({ plain: true }) : order;
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
const creator = opts.creator && opts.creator.get ? opts.creator.get({ plain: true }) : (opts.creator || {});
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
const orderLineList = (items || []).map((it, idx) => {
const i = it.get ? it.get({ plain: true }) : it;
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
const productId = i.product_id != null ? Number(i.product_id) : null;
const wmsItemId = productId != null ? wmsItemIdByProduct[productId] : undefined;
return {
orderLineNo: String(idx + 1),
itemCode: i.code || product.item_code || '',
// 仓库商品主键:WMS 侧优先按 itemId 直查商品,未推送到该仓库的商品不带该字段(降级按 itemCode 匹配)
...(wmsItemId != null ? { itemId: wmsItemId } : {}),
itemName: i.name || product.item_name || '',
planQty: Number(i.quantity) || 0,
inventoryType: this._mapInventoryType(i.inventory_type),
};
});
const entryOrder = {
entryOrderCode: o.bill_no || '',
ownerCode: this.fields && this.fields.owner_code ? String(this.fields.owner_code) : '',
warehouseCode: warehouse.code || 'OTHER',
orderCreateTime: this._fmtDateTime(o.created_at),
// openapi 渠道的入库单类型字段是 entryOrderType(默认 SCRK),不是 orderType
entryOrderType: this._inboundOrderType(o.inbound_type),
totalOrderLines: orderLineList.length,
remark: o.remark || '',
};
if (o.purchase_order_code) entryOrder.purchaseOrderCode = o.purchase_order_code;
if (o.expect_start_time) entryOrder.expectStartTime = this._fmtDateTime(o.expect_start_time);
// 预计到货时间:标准字段名为 expectedArriveTime(落库 expect_start_time)
if (o.expect_start_time) entryOrder.expectedArriveTime = this._fmtDateTime(o.expect_start_time);
if (o.expect_end_time) entryOrder.expectEndTime = this._fmtDateTime(o.expect_end_time);
// 关联采购单号:标准报文用 relatedOrders.relatedOrder.orderCode 表达
if (o.purchase_order_code) {
entryOrder.relatedOrders = { relatedOrder: { orderCode: o.purchase_order_code } };
}
if (o.logistics_code) entryOrder.logisticsCode = o.logistics_code;
if (o.logistics_name) entryOrder.logisticsName = o.logistics_name;
if (o.express_code) entryOrder.expressCode = o.express_code;
@ -357,39 +387,8 @@ class QimenWmsClient {
if (o.supplier) entryOrder.supplierName = o.supplier;
const operatorName = o.operator || creator.nickname || creator.username || '';
if (operatorName) entryOrder.operatorName = operatorName;
if (o.operator_code) entryOrder.operatorCode = o.operator_code;
entryOrder.operateTime = this._fmtDateTime(o.operate_time || o.updated_at || new Date());
// 发件人 / 收件人信息(JSON 对象,已是 WMS senderInfo/receiverInfo 结构则直接透传)
if (o.sender_info && typeof o.sender_info === 'object' && !Array.isArray(o.sender_info)) {
entryOrder.senderInfo = o.sender_info;
}
if (o.receiver_info && typeof o.receiver_info === 'object' && !Array.isArray(o.receiver_info)) {
entryOrder.receiverInfo = o.receiver_info;
}
// 扩展属性:{ key: value } 对象
if (o.extend_props && typeof o.extend_props === 'object' && !Array.isArray(o.extend_props)) {
entryOrder.extendProps = o.extend_props;
}
const orderLineList = (items || []).map((it, idx) => {
const i = it.get ? it.get({ plain: true }) : it;
const product = i.product && i.product.get ? i.product.get({ plain: true }) : (i.product || {});
const itemCode = i.code || product.item_code || '';
return {
outBizCode: `${o.bill_no || 'RK'}-${idx + 1}`,
orderLineNo: String(idx + 1),
ownerCode: entryOrder.ownerCode,
itemCode,
itemName: i.name || product.item_name || '',
planQty: Number(i.quantity) || 0,
skuProperty: i.spec || product.sku_property || '',
purchasePrice: Number(i.price) || 0,
retailPrice: product.retail_price != null ? Number(product.retail_price) : 0,
inventoryType: this._mapInventoryType(i.inventory_type),
};
});
return {
entryOrder,
orderLines: { orderLine: orderLineList },
@ -400,7 +399,7 @@ class QimenWmsClient {
* 入库单推送:将 OMS 入库单映射为 WMS entryorder.create 并推送
* @param {Object} order OMS 入库单(已 include warehouse/creator)
* @param {Array} items 入库明细(已 include product)
* @param {Object} [opts] { warehouse, creator }
* @param {Object} [opts] { warehouse, creator, wmsItemIdByProduct }
* @return {Promise<{code,message,data}>}
*/
async createEntryOrder(order, items, opts = {}) {
@ -420,7 +419,7 @@ class QimenWmsClient {
/**
* 构建 stockout.create(非订单出库单)请求体(对齐 WMS 出库单规范)
* 字段来源:单据头 + 明细(含商品快照);货主编码取接口配置 owner_code,仓库编码取 warehouse.code;
* 字段来源:单据头 + 明细(含商品快照);仓库编码取 warehouse.code;
* 明细行 itemId 为 WMS 必填项,取 warehouse_products.wms_item_id(由调用方查好后传入)
* 快递公司与收件人:`deliveryOrder.logisticsCode` ← outbound_orders.express_code;
* `deliveryOrder.receiverInfo`(13 字段:name/company/zipCode/tel/mobile/email/countryCode/
@ -434,7 +433,6 @@ class QimenWmsClient {
const o = order.get ? order.get({ plain: true }) : order;
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
const ownerCode = this.fields && this.fields.owner_code ? String(this.fields.owner_code) : '';
const orderLineList = (items || []).map((it, idx) => {
const i = it.get ? it.get({ plain: true }) : it;
@ -442,7 +440,6 @@ class QimenWmsClient {
const wmsItemId = i.product_id != null ? wmsItemIdByProduct[Number(i.product_id)] : undefined;
const line = {
orderLineNo: String(idx + 1),
ownerCode,
itemCode: i.code || product.item_code || '',
itemName: i.name || product.item_name || '',
planQty: Number(i.quantity) || 0,
@ -558,7 +555,6 @@ class QimenWmsClient {
const warehouse = opts.warehouse && opts.warehouse.get ? opts.warehouse.get({ plain: true }) : (opts.warehouse || {});
const wmsItemIdByProduct = opts.wmsItemIdByProduct || {};
const wmsItemIdByItemCode = opts.wmsItemIdByItemCode || {};
const ownerCode = this.fields && this.fields.owner_code ? String(this.fields.owner_code) : '';
const deliveryOrder = {
deliveryOrderCode: o.delivery_order_code || '',
@ -649,7 +645,6 @@ class QimenWmsClient {
actualPrice: i.actual_price != null && i.actual_price !== '' ? Number(i.actual_price) : 0,
retailPrice: i.retail_price != null && i.retail_price !== '' ? Number(i.retail_price) : 0,
inventoryType: this._mapDeliveryLineInventoryType(i.inventory_type),
ownerCode: i.owner_code || ownerCode,
};
// itemId 与 itemCode 二选一:有 WMS 内部商品ID 时一并下发,命中率更高
if (itemId != null && !isNaN(itemId)) line.itemId = itemId;

View File

@ -32,7 +32,6 @@ module.exports = app => {
defaultValue: 'ZP',
comment: '库存类型:ZP=正品 CC=残次(对齐 WMS 行级 inventoryType,推送时映射 ZC/CC)',
},
owner_code: { type: STRING(50), comment: '货主编码(ownerCode)' },
source_order_code: { type: STRING(50), comment: '来源订单编码(sourceOrderCode)' },
sub_source_order_code: { type: STRING(50), comment: '子来源订单编码(subSourceOrderCode)' },
stock_id: { type: BIGINT.UNSIGNED, comment: 'WMS 仓库库存ID(stockId,手工建单直传)' },

View File

@ -12,6 +12,8 @@ module.exports = app => {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体ID' },
user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '用户ID' },
name: { type: STRING(50), allowNull: true, comment: '该账号在此主体下的显示名称(推送单据操作人取此值)' },
avatar: { type: STRING(255), allowNull: true, comment: '该账号在此主体下的头像 URL' },
role: { type: STRING(50), comment: '该主体下的角色标识' },
is_default: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否默认主体:1是 0否' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },

View File

@ -106,6 +106,8 @@ module.exports = app => {
// 出入库记录(库存流水):只读列表 + 业务动作选项(下拉),按主体隔离;记录由业务事务写入,不提供增删改接口
router.get('/api/stock-records/biz-types', jwtAuth, principalCheck(), controller.stockRecord.bizTypes);
router.get('/api/stock-records', jwtAuth, principalCheck(), controller.stockRecord.index);
// 仪表盘报表(只读聚合:概览/单据状态/趋势/库存 Top/最近流水),按主体隔离(principal_id 由前端拦截器注入 query)
router.get('/api/dashboard/report', jwtAuth, principalCheck(), controller.dashboard.report);
// 快递公司字典(通用字典,不区分主体):下拉需在 resources 之前注册,避免 /select 被当作 :id
router.get('/api/express-companies/select', jwtAuth, controller.expressCompany.select);
router.resources('expressCompanies', '/api/express-companies', jwtAuth, controller.expressCompany);

View File

@ -0,0 +1,501 @@
'use strict';
const { Service } = require('egg');
const { BILL_STATUS_LABELS, BILL_STATUS_ORDER } = require('../lib/billStatus');
const { BIZ_TYPES, DIRECTION_LABELS } = require('../utils/stockRecord');
/** 允许的趋势区间长度(天) */
const ALLOWED_DAYS = [ 7, 14, 30, 90 ];
const DEFAULT_DAYS = 7;
/** 库存 Top 商品条数 */
const TOP_PRODUCT_LIMIT = 8;
/** 最近流水条数 */
const RECENT_RECORD_LIMIT = 10;
const pad2 = n => String(n).padStart(2, '0');
/**
* Date → 'YYYY-MM-DD'(按服务器本地时区,与 Sequelize timezone=+08:00 的落库口径一致)
* @param {Date} date 日期对象
* @return {String} 日期串
*/
function toDayString(date) {
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
}
/**
* 按天+方向汇总 → Map<day, {in: Number, out: Number}>
* @param {Array} rows 聚合查询结果
* @return {Map} 汇总表
*/
function groupMovement(rows) {
const map = new Map();
for (const row of rows) {
const day = toDayString(new Date(row.day));
const current = map.get(day) || { in: 0, out: 0 };
const quantity = Number(row.quantity || 0);
if (Number(row.direction) === 1) current.in += quantity;
else current.out += quantity;
map.set(day, current);
}
return map;
}
/**
* 按天汇总单据数 → Map<day, Number>
* @param {Array} rows 聚合查询结果
* @return {Map} 汇总表
*/
function groupBillCount(rows) {
const map = new Map();
for (const row of rows) {
const day = toDayString(new Date(row.day));
map.set(day, (map.get(day) || 0) + Number(row.count || 0));
}
return map;
}
/**
* @service DashboardService 仪表盘报表
*
* 基于现有单据(发货单 / 入库单 / 出库单)、库存(product_stocks)与库存流水(stock_records)
* 做只读聚合:概览指标、单据状态分布与待办、近 N 天趋势、库存 Top 商品、最近流水。
* 全部按主体隔离(principal_id),可选按仓库过滤(库存无仓库维度,见 report 注释)。
*/
class DashboardService extends Service {
/**
* 仪表盘报表数据
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.days] 趋势区间天数(7/14/30/90,默认 7)
* @param {Number} [params.warehouseId] 仓库ID(过滤单据与流水;product_stocks 无仓库维度,库存概览不受此过滤)
* @return {Promise<Object>} 报表数据
*/
async report({ principalId, days, warehouseId }) {
const Op = this.app.Sequelize.Op;
const rangeDays = ALLOWED_DAYS.includes(Number(days)) ? Number(days) : DEFAULT_DAYS;
// 趋势区间:起始日 00:00:00(含) → 当前时间
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - (rangeDays - 1));
const endDate = new Date();
const baseWhere = { principal_id: principalId };
if (warehouseId) baseWhere.warehouse_id = warehouseId;
const rangeWhere = {
...baseWhere,
created_at: { [Op.gte]: startDate, [Op.lte]: endDate },
};
const bills = [
{ key: 'delivery', label: '发货单', model: 'OrderDelivery', path: '/order' },
{ key: 'inbound', label: '入库单', model: 'InboundOrder', path: '/inbound-order' },
{ key: 'outbound', label: '出库单', model: 'OutboundOrder', path: '/outbound-order' },
];
const [ overview, billStats, trend, stockMovement, topProducts, recentRecords ] = await Promise.all([
this._overview({ principalId, warehouseId }),
Promise.all(bills.map(item => this._billStats(item, { baseWhere, rangeWhere }))),
this._billTrend(bills, { baseWhere, startDate, endDate }),
this._stockMovement({ principalId, warehouseId, startDate, endDate }),
this._topProducts({ principalId }),
this._recentRecords({ principalId, warehouseId }),
]);
return {
range: {
days: rangeDays,
start_date: toDayString(startDate),
end_date: toDayString(endDate),
},
overview,
bills: billStats,
todo: this._buildTodo(billStats),
trend: this._mergeTrend({ days: rangeDays, startDate, billTrend: trend, stockMovement }),
movement: {
inbound_qty: stockMovement.reduce((sum, item) => sum + item.inbound_qty, 0),
outbound_qty: stockMovement.reduce((sum, item) => sum + item.outbound_qty, 0),
},
top_products: topProducts,
recent_records: recentRecords,
};
}
/**
* 概览指标:商品/店铺/仓库数量 + 库存汇总 + 区间内单据数与金额
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.warehouseId] 仓库ID
* @return {Promise<Object>} 概览数据
*/
async _overview({ principalId, warehouseId }) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
const { ProductStock, Product, Shop, Warehouse, OrderDelivery, InboundOrder, OutboundOrder } = ctx.model;
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - 29);
const endDate = new Date();
const billModels = [ OrderDelivery, InboundOrder, OutboundOrder ];
const billBase = { principal_id: principalId };
if (warehouseId) billBase.warehouse_id = warehouseId;
const billRange = { ...billBase, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } };
const [
productCount,
shopCount,
warehouseCount,
stockRows,
stockProductKind,
billTotal,
deliveryCount30,
deliveryAmount,
] = await Promise.all([
Product.count({ where: { principal_id: principalId } }),
Shop.count({ where: { principal_id: principalId } }),
Warehouse.count({ where: { principal_id: principalId } }),
// ⚠️ product_stocks 只有 (principal_id, product_id, item_type) 维度,没有 warehouse_id → 库存概览不按仓库过滤
ProductStock.findAll({
attributes: [
'item_type',
[ fn('SUM', col('quantity')), 'quantity' ],
[ fn('SUM', col('lock_quantity')), 'lock_quantity' ],
[ fn('SUM', col('available')), 'available' ],
],
where: { principal_id: principalId },
group: [ 'item_type' ],
raw: true,
}),
ProductStock.count({ where: { principal_id: principalId }, distinct: true, col: 'product_id' }),
Promise.all(billModels.map(model => model.count({ where: billBase }))).then(list => list.reduce((a, b) => a + b, 0)),
OrderDelivery.count({ where: billRange }),
OrderDelivery.sum('total_amount', { where: billRange }),
]);
const stock = { quantity: 0, available: 0, locked: 0, zc: 0, cc: 0 };
for (const row of stockRows) {
const quantity = Number(row.quantity || 0);
const available = Number(row.available || 0);
const locked = Number(row.lock_quantity || 0);
stock.quantity += quantity;
stock.available += available;
stock.locked += locked;
if (String(row.item_type).toUpperCase() === 'CC') stock.cc += quantity;
else stock.zc += quantity;
}
return {
product_count: productCount,
shop_count: shopCount,
warehouse_count: warehouseCount,
stock_product_kind: stockProductKind,
stock_quantity: this._round(stock.quantity),
stock_available: this._round(stock.available),
stock_locked: this._round(stock.locked),
stock_zc: this._round(stock.zc),
stock_cc: this._round(stock.cc),
bill_total: billTotal,
delivery_count_30d: deliveryCount30,
delivery_amount_30d: this._round(Number(deliveryAmount || 0), 2),
};
}
/**
* 单类单据的状态分布、区间新增、待办与推送失败数
* @param {Object} bill 单据定义(key/label/model/...)
* @param {Object} params 入参
* @param {Object} params.baseWhere 基础过滤(主体 + 可选仓库)
* @param {Object} params.rangeWhere 基础过滤 + 时间区间
* @return {Promise<Object>} 单据统计
*/
async _billStats(bill, { baseWhere, rangeWhere }) {
const { ctx } = this;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
const Model = ctx.model[bill.model];
const [ statusRows, rangeCount, pushFail, amount ] = await Promise.all([
Model.findAll({
attributes: [ 'status', [ fn('COUNT', col('id')), 'count' ]],
where: baseWhere,
group: [ 'status' ],
raw: true,
}),
Model.count({ where: rangeWhere }),
this._countPushFail(Model, baseWhere),
Model.sum('total_amount', { where: rangeWhere }),
]);
const countByStatus = new Map();
for (const row of statusRows) countByStatus.set(Number(row.status), Number(row.count || 0));
const byStatus = BILL_STATUS_ORDER.map(status => ({
status,
label: BILL_STATUS_LABELS[status],
count: countByStatus.get(status) || 0,
}));
const total = byStatus.reduce((sum, item) => sum + item.count, 0);
const pick = (...statuses) => statuses.reduce((sum, status) => sum + (countByStatus.get(status) || 0), 0);
return {
key: bill.key,
label: bill.label,
path: bill.path,
total,
by_status: byStatus,
range_count: rangeCount,
amount: this._round(Number(amount || 0), 2),
wait_handle: pick(1),
wait_push: pick(2),
wait_finish: pick(3),
finished: pick(4),
canceled: pick(9),
voided: pick(5),
push_fail: pushFail,
};
}
/**
* 推送失败单据数:wms_push_result.success = false(JSON 列取值,注意 JSON 里的 false 需显式比较)
* @param {Object} Model 单据模型
* @param {Object} baseWhere 基础过滤
* @return {Promise<Number>} 失败条数
*/
async _countPushFail(Model, baseWhere) {
const literal = this.app.Sequelize.literal;
return Model.count({
where: {
...baseWhere,
[this.app.Sequelize.Op.and]: [
literal("JSON_EXTRACT(`wms_push_result`, '$.success') = false"),
],
},
});
}
/**
* 近 N 天每类单据的创建量
* @param {Array} bills 单据定义列表
* @param {Object} params 入参
* @param {Object} params.baseWhere 基础过滤
* @param {Date} params.startDate 起始日
* @param {Date} params.endDate 结束时间
* @return {Promise<Array>} [{ key, label, values: Map<day, count> }]
*/
async _billTrend(bills, { baseWhere, startDate, endDate }) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
return Promise.all(bills.map(async bill => {
const rows = await ctx.model[bill.model].findAll({
attributes: [[ fn('DATE', col('created_at')), 'day' ], [ fn('COUNT', col('id')), 'count' ]],
where: { ...baseWhere, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } },
group: [ this.app.Sequelize.literal('DATE(`created_at`)') ],
raw: true,
});
return { key: bill.key, label: bill.label, counts: groupBillCount(rows) };
}));
}
/**
* 近 N 天每日出入库数量(来源 stock_records 流水,direction 1=入库方向 2=出库方向)
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.warehouseId] 仓库ID
* @param {Date} params.startDate 起始日
* @param {Date} params.endDate 结束时间
* @return {Promise<Array>} [{ day, inbound_qty, outbound_qty }]
*/
async _stockMovement({ principalId, warehouseId, startDate, endDate }) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
const where = { principal_id: principalId, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } };
if (warehouseId) where.warehouse_id = warehouseId;
const rows = await ctx.model.StockRecord.findAll({
attributes: [
[ fn('DATE', col('created_at')), 'day' ],
'direction',
[ fn('SUM', col('quantity')), 'quantity' ],
],
where,
group: [ this.app.Sequelize.literal('DATE(`created_at`)'), 'direction' ],
raw: true,
});
const map = groupMovement(rows);
return this._dayList(startDate, endDate).map(day => {
const item = map.get(day) || { in: 0, out: 0 };
return {
day,
inbound_qty: this._round(item.in),
outbound_qty: this._round(item.out),
};
});
}
/**
* 合并单据趋势与出入库趋势为前端可直接渲染的序列(按天对齐、补 0)
* @param {Object} params 入参
* @param {Number} params.days 区间天数
* @param {Date} params.startDate 起始日
* @param {Array} params.billTrend 单据趋势
* @param {Array} params.stockMovement 出入库趋势
* @return {Object} { days, dates, series, max_bill, max_qty }
*/
_mergeTrend({ days, startDate, billTrend, stockMovement }) {
const dates = this._dayList(startDate, new Date());
const movementMap = new Map(stockMovement.map(item => [ item.day, item ]));
const series = [
...billTrend.map(item => ({
key: item.key,
label: item.label,
unit: '单',
values: dates.map(day => item.counts.get(day) || 0),
})),
{
key: 'inbound_qty',
label: '入库数量',
unit: '件',
values: dates.map(day => (movementMap.get(day) || {}).inbound_qty || 0),
},
{
key: 'outbound_qty',
label: '出库数量',
unit: '件',
values: dates.map(day => (movementMap.get(day) || {}).outbound_qty || 0),
},
];
const billSeries = series.slice(0, billTrend.length);
const maxBill = Math.max(1, ...billSeries.flatMap(item => item.values));
const maxQty = Math.max(1, ...series.slice(billTrend.length).flatMap(item => item.values));
return { days, dates, series, max_bill: maxBill, max_qty: maxQty };
}
/**
* 库存 Top 商品(按可用数量倒序)
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @return {Promise<Array>} 商品库存列表
*/
async _topProducts({ principalId }) {
const { ctx } = this;
const rows = await ctx.model.ProductStock.findAll({
where: { principal_id: principalId },
include: [{
model: ctx.model.Product,
as: 'product',
attributes: [ 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
required: false,
}],
order: [[ 'available', 'DESC' ]],
limit: TOP_PRODUCT_LIMIT,
});
return rows.map(row => {
const item = row.get({ plain: true });
const product = item.product || {};
return {
product_id: item.product_id,
item_code: product.item_code || '-',
item_name: product.item_name || '(商品已删除)',
sku_property: product.sku_property || '',
stock_unit: product.stock_unit || '',
item_type: item.item_type,
quantity: this._round(Number(item.quantity || 0)),
lock_quantity: this._round(Number(item.lock_quantity || 0)),
available: this._round(Number(item.available || 0)),
};
});
}
/**
* 最近出入库记录(附业务动作/方向中文标签)
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.warehouseId] 仓库ID
* @return {Promise<Array>} 流水列表
*/
async _recentRecords({ principalId, warehouseId }) {
const { ctx } = this;
const where = { principal_id: principalId };
if (warehouseId) where.warehouse_id = warehouseId;
const rows = await ctx.model.StockRecord.findAll({
where,
order: [[ 'id', 'DESC' ]],
limit: RECENT_RECORD_LIMIT,
raw: true,
});
return rows.map(row => ({
...row,
biz_type_label: (BIZ_TYPES[row.biz_type] || {}).label || row.biz_type,
direction_label: DIRECTION_LABELS[row.direction] || '',
}));
}
/**
* 待办列表(计数大于 0 才返回,附前端跳转路径与筛选条件)
* @param {Array} billStats 单据统计
* @return {Array} 待办项
*/
_buildTodo(billStats) {
const todo = [];
const push = (key, label, count, path, query) => {
if (count > 0) todo.push({ key, label, count, path, query });
};
for (const bill of billStats) {
push(`${bill.key}_wait_handle`, `${bill.label}待处理`, bill.wait_handle, bill.path, { status: 1 });
push(`${bill.key}_wait_push`, `${bill.label}待推送`, bill.wait_push, bill.path, { status: 2 });
push(`${bill.key}_wait_finish`, `${bill.label}待完成`, bill.wait_finish, bill.path, { status: 3 });
push(`${bill.key}_push_fail`, `${bill.label}推送失败`, bill.push_fail, bill.path, null);
}
return todo;
}
/**
* 生成日期列表(含首尾)
* @param {Date} startDate 起始日(当天 00:00:00)
* @param {Date} endDate 结束日
* @return {Array<String>} ['YYYY-MM-DD', ...]
*/
_dayList(startDate, endDate) {
const days = [];
const cursor = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
const last = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
while (cursor <= last) {
days.push(toDayString(cursor));
cursor.setDate(cursor.getDate() + 1);
}
return days;
}
/**
* 数值取整(库存/数量按 3 位小数,金额按 2 位)
* @param {Number} value 数值
* @param {Number} [digits] 小数位,默认 3
* @return {Number} 处理后的数值
*/
_round(value, digits = 3) {
const factor = 10 ** digits;
return Math.round((Number(value) || 0) * factor) / factor;
}
}
module.exports = DashboardService;

View File

@ -329,11 +329,11 @@ class OutboundOrderPushService extends Service {
const items = await this.loadItems(order.id);
if (!items.length) {
// 审核要求有明细,正常不会走到这里;真出现则退回「待出库」,让用户补明细后重新审核
await order.update({
await ctx.model.OutboundOrder.update({
status: 1,
pushed_at: null,
wms_push_result: { ...base, success: false, failureKind: 'empty_items', retryable: false, message: '单据无明细,无法推送' },
});
}, { where: { id: order.id } });
ctx.logger.warn(`[outbound-push] ${order.bill_no} 无明细,已退回待出库`);
return { ok: false, retry: false, message: '单据无明细,无法推送', attempts };
}
@ -347,7 +347,8 @@ class OutboundOrderPushService extends Service {
} catch (err) {
const insufficient = err.code === 'INSUFFICIENT_STOCK';
const message = insufficient ? err.message : `库存锁定失败:${err.message}`;
await order.update({
// 用批量 update:CAS 已把 pushed_at 写入库而实例内存值仍为 null,实例 update 不会真正把 null 落库
await ctx.model.OutboundOrder.update({
status: 1,
pushed_at: null,
wms_push_result: {
@ -357,7 +358,7 @@ class OutboundOrderPushService extends Service {
retryable: false,
message,
},
});
}, { where: { id: order.id } });
ctx.logger.warn(`[outbound-push] ${order.bill_no} 推送前锁定库存失败,已退回待出库:${message}`);
return { ok: false, retry: false, message, attempts };
}
@ -381,7 +382,7 @@ class OutboundOrderPushService extends Service {
// 达到上限:冲正外部单据后退回「待出库」,并释放锁定库存
const cancelResult = await this.cancelRemote(client, order);
await this.releaseStock(order, items, '推送超时退回待出库,释放锁定库存');
await order.update({
await ctx.model.OutboundOrder.update({
status: 1,
pushed_at: null,
wms_push_result: {
@ -392,7 +393,7 @@ class OutboundOrderPushService extends Service {
error: err.message,
cancelResult,
},
});
}, { where: { id: order.id } });
ctx.logger.error(`[outbound-push] ${order.bill_no} 连续 ${attempts} 次推送异常,已退回待出库:${err.message}`);
return { ok: false, retry: false, message: `连续 ${attempts} 次无响应/超时,已退回待出库:${err.message}`, attempts };
}
@ -412,7 +413,7 @@ class OutboundOrderPushService extends Service {
const cancelResult = await this.cancelRemote(client, order);
const message = resp && (resp.message || resp.code);
await this.releaseStock(order, items, '推送失败退回待出库,释放锁定库存');
await order.update({
await ctx.model.OutboundOrder.update({
status: 1,
pushed_at: null,
wms_push_result: {
@ -425,7 +426,7 @@ class OutboundOrderPushService extends Service {
response: resp,
cancelResult,
},
});
}, { where: { id: order.id } });
ctx.logger.warn(`[outbound-push] ${order.bill_no} 推送失败(对方明确拒绝),已退回待出库:${message}`);
return { ok: false, retry: false, message: `WMS 返回失败:${message}`, response: resp, attempts };
}

View File

@ -0,0 +1,56 @@
'use strict';
/**
* 清理仓库接口配置项残留键:warehouse_apis.extra 中「已不在硬编码清单内」的键
*
* 背景:`app/lib/warehouseApiFields.js` 是配置项的唯一来源(分组 + 字段清单 + 类型),
* 字段值以 { 字段名: 值 } 落库在 `warehouse_apis.extra`。2026-09-14 按用户要求移除了
* 「基础信息」分组里从未被代码读取的三项(`owner_alias` 货主别名 / `outsource_api_type` 委外接口类型 /
* `customer_id` 客户ID),但历史落库的 extra 里仍残留这些键(读取时已被 `readFieldValues` 过滤,
* 保存时因整体覆盖也会消失)。本迁移做一次性修剪,使库内数据与清单一致。
*
* 口径:
* - 以当前清单的 key 集合为准,删除 extra 中**不在清单内**的所有键(幂等:无可删键时不做任何写库)
* - 只动 `extra` 字段,不改 `updated_at`
* - 不移除清单内字段的值(保留 `owner_code` 等在用配置)
*/
const { listFieldDefs } = require('../../app/lib/warehouseApiFields');
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
const validKeys = new Set(listFieldDefs().map(field => field.key));
const rows = await sequelize.query('SELECT id, extra FROM warehouse_apis', { type: sequelize.QueryTypes.SELECT });
let prunedKeys = 0;
let touchedRows = 0;
for (const row of rows) {
let extra = row.extra;
if (typeof extra === 'string') {
try { extra = JSON.parse(extra); } catch { extra = null; }
}
if (!extra || typeof extra !== 'object' || Array.isArray(extra)) continue;
const stale = Object.keys(extra).filter(key => !validKeys.has(key));
if (!stale.length) continue;
const next = { ...extra };
for (const key of stale) delete next[key];
await sequelize.query(
'UPDATE warehouse_apis SET extra = ? WHERE id = ?',
{ replacements: [ JSON.stringify(next), row.id ] }
);
prunedKeys += stale.length;
touchedRows += 1;
}
console.log(`[migration] warehouse_apis.extra 清理清单外配置项:${touchedRows} 行 / ${prunedKeys} 个键`);
},
/**
* 不可逆:被删的键已无任何代码引用(如确需恢复,在页面重新填写即可)
*/
async down() {},
};

View File

@ -0,0 +1,55 @@
'use strict';
/**
* 清理仓库接口配置项残留键(第二轮):warehouse_apis.extra 中「已不在硬编码清单内」的键
*
* 背景:2026-09-14 按用户要求核实后,把「基础信息」分组整体移除(`app/lib/warehouseApiFields.js`):
* - `customer_id` 客户ID:openapi 契约上下文里 customerId 恒为 null(奇门渠道才用它做鉴权),OMS 从未读取
* - `owner_alias` 货主别名 / `outsource_api_type` 委外接口类型:无任何代码引用
* - `owner_code` 货主编码:openapi 的 entryorder.create / stockout.create / deliveryorder.create
* 对 ownerCode 均为 required=false(不传则 WMS 落空串),且 OMS 接收回传不看 ownerCode
* 故不再需要这些配置项,报文中也不再下发 ownerCode(见 `app/lib/wms/qimenClient.js`)。
*
* 口径:以当前清单的 key 集合为准,删除 extra 中**不在清单内**的所有键;
* 无可删键时不写库(幂等),只动 `extra`,不改 `updated_at`。
*/
const { listFieldDefs } = require('../../app/lib/warehouseApiFields');
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
const validKeys = new Set(listFieldDefs().map(field => field.key));
const rows = await sequelize.query('SELECT id, extra FROM warehouse_apis', { type: sequelize.QueryTypes.SELECT });
let prunedKeys = 0;
let touchedRows = 0;
for (const row of rows) {
let extra = row.extra;
if (typeof extra === 'string') {
try { extra = JSON.parse(extra); } catch { extra = null; }
}
if (!extra || typeof extra !== 'object' || Array.isArray(extra)) continue;
const stale = Object.keys(extra).filter(key => !validKeys.has(key));
if (!stale.length) continue;
const next = { ...extra };
for (const key of stale) delete next[key];
await sequelize.query(
'UPDATE warehouse_apis SET extra = ? WHERE id = ?',
{ replacements: [ JSON.stringify(next), row.id ] }
);
prunedKeys += stale.length;
touchedRows += 1;
}
console.log(`[migration] warehouse_apis.extra 清理清单外配置项:${touchedRows} 行 / ${prunedKeys} 个键`);
},
/**
* 不可逆:被删的键已无任何代码引用(如确需恢复,在页面重新填写即可)
*/
async down() {},
};

View File

@ -0,0 +1,29 @@
'use strict';
/**
* 删除发货单明细的「货主编码」列:`order_delivery_items.owner_code`
*
* 背景(2026-09-14,按用户要求核实后清理):openapi 渠道的 deliveryorder.create 对行级 ownerCode
* 是 required=false(WMS 不传则落空串,且没有任何业务逻辑依赖它),OMS 侧也不回读该字段;
* 该列原本只是手工明细表单上的一个手填项(`ownerCode,选填`)。既然接口不要求、且是唯一还能
* 产生 ownerCode 的来源,故连同手填项一起移除,报文也不再下发(见 `app/lib/wms/qimenClient.js`)。
*
* 幂等:可重复执行(先 describeTable 判断列是否存在)。
*/
module.exports = {
async up(queryInterface) {
const columns = await queryInterface.describeTable('order_delivery_items');
if (!columns.owner_code) return;
await queryInterface.removeColumn('order_delivery_items', 'owner_code');
},
async down(queryInterface, Sequelize) {
const columns = await queryInterface.describeTable('order_delivery_items');
if (columns.owner_code) return;
await queryInterface.addColumn('order_delivery_items', 'owner_code', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '货主编码(ownerCode)',
});
},
};

View File

@ -0,0 +1,55 @@
'use strict';
/**
* 清理仓库接口配置项残留键(第三轮):warehouse_apis.extra 中「已不在硬编码清单内」的键
*
* 背景(2026-09-14 按用户要求核实后精简):
* - 「递交设置」(submit)22 项、「回传设置」(callback)13 项整体移除 —— 逐项核对源码后,
* 35 项里只有 `item_name_with_spec`(`qimenClient._buildItem` 拼 itemName 时读取)在用,
* 其余 34 项无任何引用;该字段已归入「业务设置」分组
* - 至此配置项清单只剩 7 项:purchase_return_code_type / transfer_in_code_type / transfer_out_code_type /
* sku_sync_key / barcode_sync_source / api_version / item_name_with_spec
*
* 口径:以当前清单的 key 集合为准,删除 extra 中**不在清单内**的所有键;
* 无可删键时不写库(幂等),只动 `extra`,不改 `updated_at`。
*/
const { listFieldDefs } = require('../../app/lib/warehouseApiFields');
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
const validKeys = new Set(listFieldDefs().map(field => field.key));
const rows = await sequelize.query('SELECT id, extra FROM warehouse_apis', { type: sequelize.QueryTypes.SELECT });
let prunedKeys = 0;
let touchedRows = 0;
for (const row of rows) {
let extra = row.extra;
if (typeof extra === 'string') {
try { extra = JSON.parse(extra); } catch { extra = null; }
}
if (!extra || typeof extra !== 'object' || Array.isArray(extra)) continue;
const stale = Object.keys(extra).filter(key => !validKeys.has(key));
if (!stale.length) continue;
const next = { ...extra };
for (const key of stale) delete next[key];
await sequelize.query(
'UPDATE warehouse_apis SET extra = ? WHERE id = ?',
{ replacements: [ JSON.stringify(next), row.id ] }
);
prunedKeys += stale.length;
touchedRows += 1;
}
console.log(`[migration] warehouse_apis.extra 清理清单外配置项:${touchedRows} 行 / ${prunedKeys} 个键`);
},
/**
* 不可逆:被删的键已无任何代码引用(如确需恢复,在页面重新填写即可)
*/
async down() {},
};

View File

@ -0,0 +1,57 @@
'use strict';
/**
* 清理仓库接口配置项残留键(第四轮):warehouse_apis.extra 中「已不在硬编码清单内」的键
*
* 背景(2026-09-14 按用户要求「可以直接清理」):业务设置里同样未被代码读取的 5 项也移除 ——
* - `purchase_return_code_type` / `transfer_in_code_type` / `transfer_out_code_type`:
* 出库/入库/退货类型编码已硬编码在 `app/lib/wms/orderTypes.js` 的枚举里,不读配置
* - `sku_sync_key` / `barcode_sync_source`:商品同步(singleitem.synchronize)直接取
* `products.barcode` / `goods_code`,不读配置
*
* 至此配置项只剩 2 项真正被 `qimenClient` 读取的:`api_version`(请求 v 参数)与
* `item_name_with_spec`(商品同步 itemName 是否拼规格)。
*
* 口径:以当前清单的 key 集合为准,删除 extra 中**不在清单内**的所有键;
* 无可删键时不写库(幂等),只动 `extra`,不改 `updated_at`。
*/
const { listFieldDefs } = require('../../app/lib/warehouseApiFields');
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
const validKeys = new Set(listFieldDefs().map(field => field.key));
const rows = await sequelize.query('SELECT id, extra FROM warehouse_apis', { type: sequelize.QueryTypes.SELECT });
let prunedKeys = 0;
let touchedRows = 0;
for (const row of rows) {
let extra = row.extra;
if (typeof extra === 'string') {
try { extra = JSON.parse(extra); } catch { extra = null; }
}
if (!extra || typeof extra !== 'object' || Array.isArray(extra)) continue;
const stale = Object.keys(extra).filter(key => !validKeys.has(key));
if (!stale.length) continue;
const next = { ...extra };
for (const key of stale) delete next[key];
await sequelize.query(
'UPDATE warehouse_apis SET extra = ? WHERE id = ?',
{ replacements: [ JSON.stringify(next), row.id ] }
);
prunedKeys += stale.length;
touchedRows += 1;
}
console.log(`[migration] warehouse_apis.extra 清理清单外配置项:${touchedRows} 行 / ${prunedKeys} 个键`);
},
/**
* 不可逆:被删的键已无任何代码引用(如确需恢复,在页面重新填写即可)
*/
async down() {},
};

View File

@ -0,0 +1,48 @@
'use strict';
/**
* 单号数字部分提到 5 位数:把单据表的自增起点推到 10000
*
* 背景(2026-09-14 按用户要求):出入库单/发货单号由系统按 `{前缀}_{自增id}` 生成
* (`RK_{id}` / `CK_{id}` / `FH_{id}`,见各控制器 create()),当前自增值还是个位数,
* 单号看起来太"短"。这里把相关表的 AUTO_INCREMENT 提升到 10000,
* 使后续新单号至少是 5 位数(如 RK_10000 / CK_10001 / FH_10002)。
*
* 口径:
* - **历史单号不改**(它们是 WMS 侧的外部单号:entryOrderCode / deliveryOrderCode / stockoutOrderCode,
* 改动会与外部系统失联),只影响之后新建的单据
* - id 与单号仍一一对应(单号就是 `{前缀}_{id}`),驳回换号 `nextRejectedBillNo` 仍按 id 识别基础号
* - 幂等:表当前自增值已 >= 10000 时不动;表不存在时跳过
*/
const TABLES = [ 'inbound_orders', 'outbound_orders', 'order_deliveries', 'orders' ];
const START = 10000;
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
for (const table of TABLES) {
const [ info ] = await sequelize.query(
`SELECT AUTO_INCREMENT AS autoIncrement FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`,
{ replacements: [ table ], type: sequelize.QueryTypes.SELECT }
);
if (!info) {
console.log(`[migration] 表 ${table} 不存在,跳过`);
continue;
}
const current = info.autoIncrement == null ? null : Number(info.autoIncrement);
if (current != null && current >= START) {
console.log(`[migration] 表 ${table} 自增值已是 ${current}(>= ${START}),跳过`);
continue;
}
await sequelize.query(`ALTER TABLE \`${table}\` AUTO_INCREMENT = ${START}`);
console.log(`[migration] 表 ${table} 自增起点 ${current} -> ${START}(新单号将 >= ${START})`);
}
},
/**
* 不可逆:自增起点只增不减(回退会让新单号重新变短,且可能与既有单据冲突),故不做处理
*/
async down() {},
};

View File

@ -0,0 +1,41 @@
'use strict';
/**
* 主体账号关联表增加「名称」与「头像」:`principal_users.name` / `principal_users.avatar`
*
* 背景(2026-09-14 按用户要求):账号的显示名称与头像改为**按主体维度**维护(同一账号在不同主体下
* 可以有不同名称/头像),不再放在全局 `users.nickname` / `users.avatar`:
* - 「我的」页不再提供昵称/头像设置;注册也不再填昵称
* - 账号(主体账号关联)处可设置名称与头像
* - 推送单据的操作人统一取该关联表的名称(见各单据 audit / 推送报文)
* - 页面右上角:有关联头像显示头像 → 无头像显示名称首字符 → 无名称显示账号(username)首字符
*
* 幂等:可重复执行(先 describeTable 判断列是否存在)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const columns = await queryInterface.describeTable('principal_users');
if (!columns.name) {
await queryInterface.addColumn('principal_users', 'name', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '该账号在此主体下的显示名称(推送单据操作人取此值)',
after: 'user_id',
});
}
if (!columns.avatar) {
await queryInterface.addColumn('principal_users', 'avatar', {
type: Sequelize.STRING(255),
allowNull: true,
comment: '该账号在此主体下的头像 URL',
after: 'name',
});
}
},
async down(queryInterface) {
const columns = await queryInterface.describeTable('principal_users');
if (columns.avatar) await queryInterface.removeColumn('principal_users', 'avatar');
if (columns.name) await queryInterface.removeColumn('principal_users', 'name');
},
};

View File

@ -0,0 +1,37 @@
'use strict';
/**
* 回填主体账号关联表的名称/头像:principal_users.name / avatar ← users.nickname / users.avatar
*
* 背景(2026-09-14):账号显示名称与头像改为按主体维度维护(principal_users.name / avatar),
* 新建/邀请会产生新值;为了让**历史账号**在关联表里也有名称与头像(右上角展示、推送单据操作人取名称),
* 这里把全局 users 的昵称/头像回填一份(仅回填关联表为空的记录,不覆盖已有值)。
*
* 幂等:只更新 name/avatar 为 NULL/空串 的行,可重复执行。
*/
module.exports = {
async up(queryInterface) {
const sequelize = queryInterface.sequelize;
const [ nameResult ] = await sequelize.query(
`UPDATE principal_users pu
JOIN users u ON u.id = pu.user_id
SET pu.name = u.nickname
WHERE (pu.name IS NULL OR pu.name = '') AND u.nickname IS NOT NULL AND u.nickname <> ''`
);
console.log(`[migration] principal_users.name 回填:${nameResult.affectedRows || 0} 行`);
const [ avatarResult ] = await sequelize.query(
`UPDATE principal_users pu
JOIN users u ON u.id = pu.user_id
SET pu.avatar = u.avatar
WHERE (pu.avatar IS NULL OR pu.avatar = '') AND u.avatar IS NOT NULL AND u.avatar <> ''`
);
console.log(`[migration] principal_users.avatar 回填:${avatarResult.affectedRows || 0} 行`);
},
/**
* 不可逆:回填是幂等的资料补齐,无需回退(如需清空可在账号页重新设置)
*/
async down() {},
};