from sqlalchemy.ext.asyncio import AsyncSession from exceptions.exception import ServiceException from module_admin.entity.vo.user_vo import CurrentUserModel from module_business.dao.master_dao import MasterDao from module_business.dao.usage_fifo_dao import UsageFifoDao from module_business.domain.fifo_policy import requires_fifo_skip_reason from module_business.domain.test_batch_scope import TestBatchScope, assert_record_in_scope from module_business.entity.vo.usage_fifo_vo import UsageFifoRecommendationModel from module_business.service.usage_service import UsageService class UsageFifoService: @staticmethod async def recommendation( db: AsyncSession, identifier: str, user: CurrentUserModel, scope: TestBatchScope, *, tunnel_id: int | None = None, ) -> UsageFifoRecommendationModel: # 复用扫码入口的现场授权、当前批次与可用状态校验;客户端不指定查询现场。 pallet = await UsageService.scan_usage_pallet_services(db, identifier, user, scope) inventory = await MasterDao.get_pallet_inventory(db, pallet.pallet_id, scope) if inventory is None: raise ServiceException(message='托盘库存不存在') assert_record_in_scope(inventory, scope, '库存') target_tunnel_id = pallet.tunnel_id trace_no = pallet.trace_no if tunnel_id is not None: tunnel = await MasterDao.get_tunnel(db, tunnel_id, scope) if tunnel is None or tunnel.site_id != pallet.site_id or tunnel.status != '0': raise ServiceException(message='请选择托盘当前现场的启用隧道') assert_record_in_scope(tunnel, scope, '隧道') if pallet.tunnel_id is not None and pallet.tunnel_id != tunnel_id: raise ServiceException(message='托盘已入其他隧道') target_tunnel_id, trace_no = tunnel_id, tunnel.current_trace_no candidate, unknown = await UsageFifoDao.recommendation( db, site_id=pallet.site_id, strain_id=pallet.strain_id, tunnel_id=target_tunnel_id, trace_no=trace_no, scope=scope, ) message = '当前无可确定到货顺序的同品种托盘' if candidate: message = f'先到先用建议:托盘 {candidate["pallet_code"]},批次 {candidate["batch_no"]},余量 {candidate["remaining_packages"]} 包' if unknown: message += f';另有 {unknown} 托盘未登记实际收货时间,请人工核对先后顺序' needs_reason = requires_fifo_skip_reason(pallet.pallet_id, inventory.site_arrived_at, candidate) if needs_reason: message += ';使用当前托盘需填写跳过先到托盘的原因' return UsageFifoRecommendationModel( recommended=candidate, unknown_arrival_count=unknown, requires_skip_reason=needs_reason, message=message, )