feat(scrap): 新增对内接口,让 Track 能提交生产报废
料一经出库领用,那条库存行的可用量就扣掉了,走不了标准库存行报废。 本接口内部做两件事:① 走逆向物流「从出库单退回(不良品)」→ 在管不良品; ② 对这笔在管量提交报废申请。两者在**同一个事务**里,要么都成要么都不成。 - 鉴权用 X-API-Key(config.MOM_INTERNAL_API_KEY),与 TRACK_WEBHOOK_KEY 刻意分离:方向相反、权限不同,独立轮换不连坐。未配置一律 503(Fail-Closed), 不静默放行 —— 一个默认开着的写接口比没配好的更危险。 - 刻意收紧:is_defective 恒为 true、need_reissue 恒为 false,都不由请求体 控制。良品分支会往库存行加数量,一个泄漏的密钥就能凭空造库存。 - track_ref 必填:Redis 未部署,唯一索引是唯一的并发防线。 - 退回逻辑从 inbound/stock.py 抽到 services/return_service.py:内部接口没有 JWT,而视图里夹着 get_current_company_filter/_normalize_user_id,不抽没法复用。 API 层保留薄包装,restock 等既有调用方一行不用改。
This commit is contained in:
@ -24,11 +24,9 @@ from app.models.inbound.stocktake import (
|
||||
)
|
||||
from app.models.transaction import (
|
||||
TransBorrow,
|
||||
TransReturn,
|
||||
# 注:TransReturn / RETURN_TYPE_* / DEFECTIVE_STATUS_PENDING 曾在此使用,
|
||||
# 退回逻辑抽到 return_service 后本模块不再直接碰它们,故已移出导入。
|
||||
TransDefectiveGoods,
|
||||
RETURN_TYPE_GOOD,
|
||||
RETURN_TYPE_DEFECTIVE,
|
||||
DEFECTIVE_STATUS_PENDING,
|
||||
DEFECTIVE_STATUS_IN_PROGRESS,
|
||||
RESTOCKABLE_DEFECTIVE_STATUSES,
|
||||
SCRAPPABLE_DEFECTIVE_STATUSES,
|
||||
@ -37,6 +35,13 @@ from app.models.transaction import (
|
||||
)
|
||||
from app.models.outbound import TransOutbound
|
||||
from app.models.base import MaterialBase
|
||||
# 退回业务逻辑已抽到服务层(内部接口 Track → MOM 要复用同一段)。
|
||||
# 别名带 _service 后缀,避免与本模块的视图函数 return_from_outbound 撞名。
|
||||
from app.services.return_service import (
|
||||
lock_source_stock_row,
|
||||
assert_company_owns,
|
||||
return_from_outbound as return_from_outbound_service,
|
||||
)
|
||||
|
||||
# 库存状态语义的单一事实来源(与分配器共用同一套常量,避免两处定义漂移)
|
||||
from app.services.inventory_reservation import (
|
||||
@ -2606,46 +2611,21 @@ def _lock_source_stock_row(source_table, stock_id):
|
||||
"""
|
||||
解析并锁定退回目标的**原库存行**。业务不满足即抛 ValueError。
|
||||
|
||||
三条 Fail-Closed 规则:
|
||||
1. source_table 必须是三张库存表之一 —— 维修单等非库存来源没有可退回的行;
|
||||
2. 库存行必须仍然存在 —— 入库模块会物理删除库存行(见
|
||||
buy/semi/product_service 的 db.session.delete(stock)),实测 1077 条
|
||||
出库记录中已有 7 条指向不存在的行;
|
||||
3. 调用方拿到行后还需自行做公司隔离与状态校验(见 _assert_company_owns)。
|
||||
|
||||
★ 为什么必须加锁:本行随后会被加减数量,且与出库/报废/状态变更并发。
|
||||
不加锁会出现「读-改-写」丢失更新(lost update)。
|
||||
★ 实现已搬到 `app/services/return_service.py`(内部接口要复用,而服务层
|
||||
不得反向 import API 层)。这里保留薄包装:调用方(restock 等)一行不用改。
|
||||
"""
|
||||
model = get_stock_model(source_table)
|
||||
if model is None:
|
||||
raise ValueError(
|
||||
f'来源「{source_table or "(空)"}」不支持退回,'
|
||||
f'仅支持 stock_buy / stock_semi / stock_product'
|
||||
)
|
||||
|
||||
row = model.query.with_for_update().get(stock_id) if stock_id else None
|
||||
if not row:
|
||||
raise ValueError(
|
||||
f'原库存行已不存在({source_table}#{stock_id}),无法自动退回,'
|
||||
f'请改走入库流程手工登记这批实物'
|
||||
)
|
||||
return row
|
||||
return lock_source_stock_row(source_table, stock_id)
|
||||
|
||||
|
||||
def _assert_company_owns(row):
|
||||
"""
|
||||
行级多租户隔离:非跨域用户只能操作本公司库存。不满足即抛 PermissionError。
|
||||
|
||||
口径与扫码出库(OutboundService.get_stock_by_barcode)、状态变更接口完全一致
|
||||
—— 都走 MaterialBase.company_name,避免三处隔离逻辑分叉。
|
||||
★ 实现已搬到 `app/services/return_service.py`,那里收显式 company_limit
|
||||
(内部接口没有 JWT,不能在里面读 get_current_company_filter)。
|
||||
这里保留薄包装,把 JWT 依赖收在 API 层。
|
||||
"""
|
||||
company_limit = get_current_company_filter()
|
||||
if company_limit is None:
|
||||
return
|
||||
base = getattr(row, 'base', None)
|
||||
if (company_limit == '__NO_COMPANY__' or base is None
|
||||
or (base.company_name or '') != company_limit):
|
||||
raise PermissionError('无权操作其他公司的库存')
|
||||
return assert_company_owns(row, get_current_company_filter())
|
||||
|
||||
|
||||
@bp.route('/defective', methods=['GET'])
|
||||
@ -2786,226 +2766,42 @@ def return_from_outbound():
|
||||
operator_name = _normalize_user_id()
|
||||
|
||||
outbound_id = data.get('outbound_id')
|
||||
is_defective = data.get('is_defective')
|
||||
reason = (data.get('reason') or '').strip() or None
|
||||
# 补发(可选):退回后申请人往往仍需这件东西。勾选则自动生成一张免审批出库单。
|
||||
need_reissue = bool(data.get('need_reissue'))
|
||||
reissue_qty = data.get('reissue_qty')
|
||||
# 补发给谁:不传则回退为当前操作人(见下方补发块)
|
||||
reissue_applicant_id = data.get('reissue_applicant_id')
|
||||
|
||||
# ---- 1. 入参校验(脏值一律挡在入口)----
|
||||
# ---- 入参校验(脏值一律挡在入口)----
|
||||
# 只留这一条在视图层:其余校验的文案由 service 原样抛出,见其注释
|
||||
if not outbound_id:
|
||||
return jsonify({'code': 400, 'msg': 'outbound_id 为必填'}), 400
|
||||
if is_defective is None:
|
||||
return jsonify({
|
||||
'code': 400,
|
||||
'msg': 'is_defective 为必填(true=不良品退回,false=良品退回)',
|
||||
}), 400
|
||||
is_defective = bool(is_defective)
|
||||
|
||||
try:
|
||||
return_qty = float(data.get('return_qty') or 0)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'code': 400, 'msg': 'return_qty 无效'}), 400
|
||||
if return_qty <= 0:
|
||||
return jsonify({'code': 400, 'msg': '退回数量必须大于 0'}), 400
|
||||
|
||||
try:
|
||||
# ---- 2. 锁定原出库明细并校验退回额度 ----
|
||||
# ★ 行锁不可省:并发两笔退回若各自读到相同的 returned_quantity,会双双
|
||||
# 通过额度校验,合计退回量超过出库量 —— 凭空多出库存。
|
||||
outbound = TransOutbound.query.with_for_update().get(outbound_id)
|
||||
if not outbound:
|
||||
raise ValueError(f'出库记录不存在(ID: {outbound_id})')
|
||||
|
||||
shipped = float(outbound.quantity or 0)
|
||||
returned = float(outbound.returned_quantity or 0)
|
||||
returnable = shipped - returned
|
||||
if return_qty > returnable:
|
||||
raise ValueError(
|
||||
f'退回数量({return_qty})超出可退额度({returnable}):'
|
||||
f'原出库 {shipped},已退回 {returned}'
|
||||
)
|
||||
|
||||
# ---- 3. 锁定原库存行 + 多租户隔离 ----
|
||||
stock_row = _lock_source_stock_row(outbound.source_table, outbound.stock_id)
|
||||
_assert_company_owns(stock_row)
|
||||
|
||||
# 公司快照:退回看板的隔离判定不能依赖 join 链 —— 源库存行会被入库模块
|
||||
# 物理删除,届时链路断裂会让记录对普通用户静默消失。见 TransReturn 注释。
|
||||
_base = getattr(stock_row, 'base', None)
|
||||
snapshot_company = ((_base.company_name if _base else '') or '').strip() or None
|
||||
|
||||
goods = None
|
||||
if is_defective:
|
||||
# ================= 不良品分支 =================
|
||||
# ★ 原库存表**分毫不动**:坏件全程存放于独立在管台账,既不占用库存
|
||||
# 数量、也不改库存行 status,从根上杜绝「坏件混进可分配池」。
|
||||
base = getattr(stock_row, 'base', None)
|
||||
goods = TransDefectiveGoods(
|
||||
outbound_id=outbound.id,
|
||||
source_table=outbound.source_table,
|
||||
stock_id=outbound.stock_id,
|
||||
base_id=getattr(stock_row, 'base_id', None),
|
||||
sku=getattr(stock_row, 'sku', '') or '',
|
||||
material_name=(base.name if base else '') or '',
|
||||
spec_model=(base.spec_model if base else '') or '',
|
||||
quantity=return_qty,
|
||||
remaining_qty=return_qty,
|
||||
status=DEFECTIVE_STATUS_PENDING,
|
||||
company_name=(base.company_name if base else '') or '',
|
||||
reason=reason,
|
||||
operator=operator_name,
|
||||
)
|
||||
db.session.add(goods)
|
||||
outcome = '不良品已转入在管台账'
|
||||
else:
|
||||
# ================= 良品分支 =================
|
||||
# ★ 状态防呆:把良品加回一个已冻结/不良品的行,会让良品被该行的状态
|
||||
# 连带隔离(status 是行级属性)—— 静默造成良品不可用。宁可报错让
|
||||
# 人先决定该行的归属。
|
||||
current = (stock_row.status or '').strip()
|
||||
if current != STOCK_STATUS_IN_STOCK:
|
||||
raise ValueError(
|
||||
f'原库存行当前状态为「{current or "未设置"}」,'
|
||||
f'良品退回要求该行处于「{STOCK_STATUS_IN_STOCK}」状态'
|
||||
)
|
||||
stock_row.stock_quantity = float(stock_row.stock_quantity or 0) + return_qty
|
||||
stock_row.available_quantity = float(stock_row.available_quantity or 0) + return_qty
|
||||
outcome = '良品已加回原库存'
|
||||
|
||||
# ---- 4. 累加退回额度 + 写退回流水 ----
|
||||
outbound.returned_quantity = returned + return_qty
|
||||
|
||||
ledger = TransReturn(
|
||||
outbound_id=outbound.id,
|
||||
stock_id=outbound.stock_id,
|
||||
source_table=outbound.source_table,
|
||||
sku=outbound.sku,
|
||||
return_qty=return_qty,
|
||||
return_type=RETURN_TYPE_DEFECTIVE if is_defective else RETURN_TYPE_GOOD,
|
||||
reason=reason,
|
||||
operator=operator_name,
|
||||
company_name=snapshot_company,
|
||||
# ★ 业务逻辑全部在 app/services/return_service.py —— 内部接口
|
||||
# (Track → MOM 生产报废)要复用同一段逻辑,而视图里夹着 JWT 依赖,
|
||||
# 服务层不能反向依赖它。本视图只负责取请求、转响应。
|
||||
result = return_from_outbound_service(
|
||||
outbound_id=outbound_id,
|
||||
return_qty=data.get('return_qty'),
|
||||
is_defective=data.get('is_defective'),
|
||||
reason=(data.get('reason') or '').strip() or None,
|
||||
need_reissue=bool(data.get('need_reissue')),
|
||||
reissue_qty=data.get('reissue_qty'),
|
||||
reissue_applicant_id=data.get('reissue_applicant_id'),
|
||||
operator_name=operator_name,
|
||||
company_limit=get_current_company_filter(),
|
||||
)
|
||||
db.session.add(ledger)
|
||||
db.session.flush() # 先拿到 ledger.id,供在管台账回填
|
||||
|
||||
# 在管台账回填来源流水 id,形成「出库 → 退回流水 → 在管台账」的追溯闭环
|
||||
if goods is not None:
|
||||
goods.return_id = ledger.id
|
||||
|
||||
# ==================================================================
|
||||
# ---- 5. 补发(可选)----
|
||||
# 退回后申请人往往**仍然需要这件东西**(尤其是坏件 —— 原需求并未
|
||||
# 被满足)。勾选即自动生成一张**免审批**的出库单并关联回本笔退回,
|
||||
# 使「退回 → 补发」形成闭环;否则现场只能靠人记住再手建一张单,
|
||||
# 而那张单与原单看不出任何关系。
|
||||
#
|
||||
# ★ 库存不足时**整笔回滚**(下面的 reserve_for_items 会抛错)。
|
||||
# 若只让补发静默失败,「需要补发」的意图就丢了 —— 那正是本功能
|
||||
# 要解决的问题。回滚后库管会看到明确提示,可取消勾选重试。
|
||||
# ==================================================================
|
||||
reissue = None
|
||||
if need_reissue:
|
||||
# 单号生成器在 OutboundApprovalService 上(不在 OutboundService)
|
||||
from app.services.outbound_service import OutboundApprovalService
|
||||
from app.services.inventory_reservation import reserve_for_items
|
||||
from app.models.outbound import OutboundApproval
|
||||
|
||||
if reissue_qty is None:
|
||||
reissue_qty = return_qty # 默认与本次退回量一致
|
||||
try:
|
||||
reissue_qty = float(reissue_qty)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError('补发数量格式无效')
|
||||
if reissue_qty <= 0:
|
||||
raise ValueError('补发数量必须大于 0')
|
||||
if reissue_qty > return_qty:
|
||||
raise ValueError(
|
||||
f'补发数量({reissue_qty})不能大于本次退回数量({return_qty})'
|
||||
)
|
||||
|
||||
base = getattr(stock_row, 'base', None)
|
||||
if base is None:
|
||||
raise ValueError('原库存行的物料主数据已不存在,无法生成补发单')
|
||||
|
||||
# 提交即预占,strict=True —— 与出库申请同一口径,不足即整单失败
|
||||
reserved_items, _shortages = reserve_for_items(
|
||||
[{
|
||||
'base_id': base.id,
|
||||
'name': base.name or '',
|
||||
'spec_model': base.spec_model or '',
|
||||
'quantity': reissue_qty,
|
||||
}],
|
||||
company_limit=get_current_company_filter(),
|
||||
strict=True,
|
||||
)
|
||||
|
||||
# ★ 申请人(补发给谁)优先级:
|
||||
# ① 前端显式指定 reissue_applicant_id —— 现场最清楚该给谁;
|
||||
# ② 回退到原出库明细记录的 applicant_id(创建出库时从审批单带出的
|
||||
# 真实原申请人);
|
||||
# ③ 两者都没有 → **报错要求指定**。
|
||||
#
|
||||
# ★ 绝不回退为「当前操作人」:补发是**原申请人的需求**,挂到办理
|
||||
# 退回的库管名下逻辑不通 —— 那张单会出现在库管的「我的申请」里,
|
||||
# 而真正该拿东西的人什么也看不到。
|
||||
# ⚠ 存量出库明细的 applicant_id 为 NULL(历史无从回填),此时必须由
|
||||
# 库管在选择器里明确指定 —— 宁可多一步,也不猜错人。
|
||||
if reissue_applicant_id:
|
||||
try:
|
||||
_applicant = int(reissue_applicant_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError('补发申请人ID格式无效')
|
||||
from app.models.system import SysUser
|
||||
if not SysUser.query.get(_applicant):
|
||||
raise ValueError(f'补发申请人不存在(ID:{reissue_applicant_id})')
|
||||
elif outbound.applicant_id:
|
||||
_applicant = int(outbound.applicant_id)
|
||||
else:
|
||||
raise ValueError(
|
||||
'无法确定补发单申请人:这张出库单产生于「申请人」字段上线之前,'
|
||||
'请在上方选择「补发给谁」'
|
||||
)
|
||||
|
||||
reissue = OutboundApproval(
|
||||
request_no=OutboundApprovalService.generate_request_no(),
|
||||
applicant_id=_applicant,
|
||||
outbound_type=outbound.outbound_type,
|
||||
# 免审批:原需求已经批过一次,补发只是兑现它,重复审批是负担
|
||||
status=1,
|
||||
approved_at=beijing_time(),
|
||||
source_return_id=ledger.id,
|
||||
remark=(f'原单退回补发(原出库单 {outbound.outbound_no or outbound.id}'
|
||||
f',原领用人 {outbound.consumer_name or "未知"})'),
|
||||
)
|
||||
reissue.set_items(reserved_items)
|
||||
reissue.allowed_approvers = '[]'
|
||||
db.session.add(reissue)
|
||||
db.session.flush()
|
||||
|
||||
db.session.commit()
|
||||
|
||||
reissue = result['reissue']
|
||||
return jsonify({
|
||||
'code': 200,
|
||||
'msg': f'退回成功,{outcome}'
|
||||
+ (f';已生成补发单 {reissue.request_no}' if reissue else ''),
|
||||
'msg': f"退回成功,{result['outcome']}"
|
||||
+ (f";已生成补发单 {reissue['request_no']}" if reissue else ''),
|
||||
'data': {
|
||||
'outbound_id': outbound.id,
|
||||
'return_id': ledger.id,
|
||||
'return_type': ledger.return_type,
|
||||
'return_qty': return_qty,
|
||||
'returned_quantity': float(outbound.returned_quantity),
|
||||
'returnable_quantity': shipped - float(outbound.returned_quantity),
|
||||
'defective_goods_id': goods.id if goods is not None else None,
|
||||
'outbound_id': result['outbound_id'],
|
||||
'return_id': result['return_id'],
|
||||
'return_type': result['return_type'],
|
||||
'return_qty': result['return_qty'],
|
||||
'returned_quantity': result['returned_quantity'],
|
||||
'returnable_quantity': result['returnable_quantity'],
|
||||
'defective_goods_id': result['defective_goods_id'],
|
||||
# 补发单(未勾选时为 null)
|
||||
'reissue': ({
|
||||
'id': reissue.id,
|
||||
'request_no': reissue.request_no,
|
||||
'quantity': reissue_qty,
|
||||
} if reissue else None),
|
||||
'reissue': reissue,
|
||||
},
|
||||
}), 200
|
||||
|
||||
|
||||
Reference in New Issue
Block a user