oms/backend/app/controller/stockRecord.js
liufumingren 9774ee1414 feat(stock): 出入库单/记录增加货主并按货主隔离,创建人显示员工名称
- 迁移:inbound_orders / outbound_orders 增加 subsidiary_id 与索引,按仓库回填
- 单据货主由仓库决定:创建写入、改仓库同步,接口不接受直写 subsidiary_id
- 入库单/出库单列表返回 subsidiary_name 并新增货主筛选;详情/编辑/删除/审核/
  推送/完成/取消/恢复/作废/驳回与明细接口统一加货主越界 403
- 出入库记录按仓库归属货主:列表与导出收窄、返回 subsidiary_id/subsidiary_name、
  新增货主列与筛选
- 导出:入库单/出库单/出入库记录新增货主列并按所在公司权限收窄
- 新增 resolveAccountNameMap:列表/详情返回 creator_name/auditor_name/voider_name,
  创建人展示员工名称(principal_users.name),不再回退成邮箱账号
- 前端:三个列表新增货主列与筛选,创建人/作废人展示改为员工名称

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-05 15:13:22 +08:00

193 lines
8.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { BIZ_TYPES, BIZ_TYPE_LIST, DIRECTION_LABELS } = require('../utils/stockRecord');
const { resolveAccess, ownSubsidiaryIds } = require('../lib/billOwnerScope');
/**
* 把查询入参转成 Date:日期(YYYY-MM-DD)按当天 00:00:00 / 23:59:59 处理,含时间的按原值
* @param {String} value 入参时间字符串
* @param {Boolean} isEnd 是否为区间结束(true 时补到当天最后一刻)
* @return {Date|null} Date 或 null
*/
function toDate(value, isEnd) {
const raw = String(value == null ? '' : value).trim();
if (!raw) return null;
const normalized = raw.includes('T') ? raw : raw.replace(' ', 'T');
const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(raw);
const text = dateOnly ? `${raw}T${isEnd ? '23:59:59' : '00:00:00'}` : normalized;
const date = new Date(text);
return Number.isNaN(date.getTime()) ? null : date;
}
/**
* @controller StockRecordController 出入库记录(库存流水)
*
* 记录每一次库存变动:出库单推送锁定、出库解锁、出库确认扣减、出库驳回回补、入库确认增加,
* 以及发货单(订单)审核锁定、订单解锁、订单发货确认扣减,
* 写入入口统一在 app/utils/stockRecord.js(与库存变动同事务),本控制器只提供只读查询。
* 数据按主体隔离(principal_id 由 principalCheck 中间件校验后写入 ctx.state.principalId)。
*/
class StockRecordController extends Controller {
/**
* @summary 出入库记录列表
* @description 分页查询当前主体下的库存流水,支持按商品、仓库、业务动作、出入方向、单据类型、
* 单据号与时间区间过滤;keyword 同时匹配单据号/商品编码/商品名称。
* 前端可先用商品选择器按「商品编码/商品名称」关键词锁定 product_id,再按商品精确查询。
* @router get /api/stock-records
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query integer product_id 商品ID(商品选择器锁定后传入,精确匹配)
* @request query integer warehouse_id 仓库ID
* @request query integer subsidiary_id 货主(下属公司ID),按仓库所属公司筛选
* @request query string biz_type 业务动作:outbound_lock 出库推送锁定 / outbound_unlock 出库解锁 / outbound_deduct 出库确认扣减 / outbound_restore 出库驳回回补 / inbound_increase 入库确认增加 / order_lock 订单审核锁定 / order_unlock 订单解锁 / order_deduct 订单发货确认扣减
* @request query integer direction 业务方向:1入库方向 2出库方向
* @request query integer bill_type 单据类型:1入库单 2出库单 3发货单(订单)
* @request query string item_type 库存类型:ZC 正品 / CC 残次品
* @request query string bill_no 单据号,支持模糊匹配
* @request query string keyword 关键词,匹配单据号/商品编码/商品名称
* @request query string start_time 记录时间起(YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss)
* @request query string end_time 记录时间止(日期只写到天时按当天 23:59:59)
* @response 200 stockRecordListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const {
product_id: productId,
warehouse_id: warehouseId,
subsidiary_id: subsidiaryId,
biz_type: bizType,
direction,
bill_type: billType,
item_type: itemType,
bill_no: billNo,
keyword,
start_time: startTime,
end_time: endTime,
} = ctx.query;
const where = { principal_id: ctx.state.principalId };
if (productId) where.product_id = Number(productId);
if (warehouseId) where.warehouse_id = Number(warehouseId);
if (bizType) where.biz_type = String(bizType).trim();
if (direction !== undefined && direction !== '') where.direction = Number(direction);
if (billType !== undefined && billType !== '') where.bill_type = Number(billType);
if (itemType) where.item_type = String(itemType).trim().toUpperCase();
if (billNo) where.bill_no = { [Op.like]: `%${billNo}%` };
// 货主口径:流水按仓库所属公司归属;所在公司权限只能看自己所属公司仓库的流水
const access = await resolveAccess(ctx);
const ownIds = ownSubsidiaryIds(access);
const emptyPage = () => {
ctx.body = { code: 0, message: 'success', data: buildPageResult([], 0, { page, pageSize }) };
};
const warehouseIdsOf = async ids => {
if (!ids.length) return [];
const rows = await ctx.model.Warehouse.findAll({
where: { principal_id: ctx.state.principalId, subsidiary_id: { [Op.in]: ids } },
attributes: [ 'id' ],
raw: true,
});
return rows.map(row => Number(row.id));
};
if (ownIds) {
const ownedIds = await warehouseIdsOf(ownIds);
if (!ownedIds.length) {
emptyPage();
return;
}
if (warehouseId) {
// 只能查自己所属公司的仓库,传了别家仓库直接返回空
if (!ownedIds.includes(Number(warehouseId))) {
emptyPage();
return;
}
where.warehouse_id = Number(warehouseId);
} else {
where.warehouse_id = { [Op.in]: ownedIds };
}
} else if (subsidiaryId) {
const scopedIds = await warehouseIdsOf([ Number(subsidiaryId) ]);
if (!scopedIds.length) {
emptyPage();
return;
}
where.warehouse_id = { [Op.in]: scopedIds };
}
// 关键词:未锁定商品时用模糊匹配(单据号 / 商品编码 / 商品名称);已锁定商品时用 product_id 精确过滤
if (keyword) {
where[Op.or] = [
{ bill_no: { [Op.like]: `%${keyword}%` } },
{ item_code: { [Op.like]: `%${keyword}%` } },
{ item_name: { [Op.like]: `%${keyword}%` } },
];
}
const startDate = toDate(startTime, false);
const endDate = toDate(endTime, true);
if (startDate || endDate) {
where.created_at = {};
if (startDate) where.created_at[Op.gte] = startDate;
if (endDate) where.created_at[Op.lte] = endDate;
// 只有一个边界时补全另一个,避免 Sequelize 生成空条件
if (!startDate) where.created_at[Op.gte] = new Date(0);
if (!endDate) where.created_at[Op.lte] = new Date();
}
const { count, rows } = await ctx.model.StockRecord.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
});
// 附上中文标签与货主(流水按仓库归属货主),前端直接展示(避免前后端枚举文案漂移)
const warehouseIds = [ ...new Set(rows.map(row => Number(row.warehouse_id)).filter(id => Number.isInteger(id) && id > 0)) ];
const ownerByWarehouse = new Map();
if (warehouseIds.length) {
const warehouses = await ctx.model.Warehouse.findAll({
where: { id: { [Op.in]: warehouseIds }, principal_id: ctx.state.principalId },
attributes: [ 'id', 'subsidiary_id' ],
include: [{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }],
});
for (const wh of warehouses) {
ownerByWarehouse.set(Number(wh.id), {
subsidiary_id: wh.subsidiary_id == null ? null : Number(wh.subsidiary_id),
subsidiary_name: wh.subsidiary ? wh.subsidiary.name : '',
});
}
}
const list = rows.map(row => {
const item = row.get ? row.get({ plain: true }) : row;
const meta = BIZ_TYPES[item.biz_type] || {};
item.biz_type_label = meta.label || item.biz_type;
item.direction_label = DIRECTION_LABELS[item.direction] || '';
const owner = ownerByWarehouse.get(Number(item.warehouse_id));
item.subsidiary_id = owner ? owner.subsidiary_id : null;
item.subsidiary_name = owner ? owner.subsidiary_name : '';
return item;
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
}
/**
* @summary 出入库记录业务动作选项
* @description 返回业务动作枚举(值与中文名、方向、单据类型),供前端筛选下拉使用,避免前后端枚举漂移
* @router get /api/stock-records/biz-types
* @apikey
* @response 200 baseResponse success
*/
async bizTypes() {
const { ctx } = this;
ctx.body = { code: 0, message: 'success', data: BIZ_TYPE_LIST };
}
}
module.exports = StockRecordController;