Feat: 后端新增基础资料与业务管理只读汇总接口

为 Web 端改版提供名称、统计和看板数据。只新增只读查询、扩展列表与详情
返回字段;写接口、托盘状态机和幂等键规则均未改动,未新增权限标识。

- 基础资料:列表补充名称与汇总,客户详情返回现场树,托盘详情返回最近流转,
  托盘列表支持按流转阶段筛选和二维码精确匹配;新增现场、产线、隧道的上级
  资料选项接口;Excel 导入支持 preview 只校验不写入
- 发货出库:列表支持 keyword、receiptState 筛选并补充名称、托盘数、包数和
  菌种构成;详情明细补充托盘号、菌种、批次
- 首次入库:列表与详情补充名称、托盘数、托盘当前状态;新增 /summary
- 托盘退回:列表支持 keyword 并补充名称与托盘汇总,详情补充托盘号和隧道;
  新增 /summary、/site-options
- 工厂装填:列表支持 keyword 并补充托盘号、仓库、操作人;新增 /summary、
  /batches、/batches/detail
- 客户现场使用:列表支持 keyword、fifoSkipped 并补充名称和被跳过的先到托盘号;
  新增 /site-options、/site-board 以及 usage-fifo 的 /queue
- 先到先用 DAO 抽出公共候选条件与排序,建议查询生成的 SQL 与改动前一致
- 新增各汇总 DAO 的单元测试,同步更新路由权限与模型字段契约测试

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-18 05:03:10 -07:00
co-authored by Claude Opus 5.5
parent 80a71b48ce
commit 3050ccdc4e
51 changed files with 6545 additions and 103 deletions
@@ -1,7 +1,7 @@
import hashlib
import json
import secrets
from datetime import datetime
from datetime import datetime, timedelta
from typing import Any, NoReturn
from sqlalchemy.exc import IntegrityError
@@ -11,6 +11,7 @@ from common.vo import CrudResponseModel, PageModel
from exceptions.exception import PermissionException, ServiceException
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_business.dao.access_dao import AccessDao
from module_business.dao.filling_summary_dao import FillingSummaryDao
from module_business.dao.inventory_dao import InventoryDao
from module_business.dao.master_dao import MasterDao
from module_business.dao.operation_dao import OperationDao
@@ -22,8 +23,14 @@ from module_business.entity.do.operation_do import BizFillingRecord, BizPalletEv
from module_business.entity.vo.master_vo import StrainPageQueryModel
from module_business.entity.vo.operation_vo import (
BusinessOptionModel,
FillingBatchDetailModel,
FillingBatchDetailQueryModel,
FillingBatchModel,
FillingBatchPageQueryModel,
FillingCreateModel,
FillingListItemModel,
FillingModel,
FillingOverviewModel,
FillingPageQueryModel,
PalletScanResponseModel,
)
@@ -34,6 +41,9 @@ from module_business.service.test_batch_access_service import TestBatchAccessSer
class FillingService:
"""仓库内单托盘即时装填服务层。"""
# 有效期剩余不超过该天数的在仓批次视为临期
NEAR_EXPIRY_DAYS = 14
@staticmethod
def _current_identity(current_user: CurrentUserModel) -> tuple[int, str]:
user = current_user.user
@@ -187,7 +197,7 @@ class FillingService:
current_user: CurrentUserModel,
test_scope: TestBatchScope,
is_page: bool = True,
) -> PageModel | list[FillingModel]:
) -> PageModel | list[FillingListItemModel]:
warehouse_ids = await cls._warehouse_scope(query_db, current_user)
if (
warehouse_ids is not None
@@ -203,11 +213,81 @@ class FillingService:
is_page=is_page,
)
rows = result.rows if isinstance(result, PageModel) else result
models = [FillingModel.model_validate(record) for record in rows]
records = [FillingModel.model_validate(record) for record in rows]
# 仅对本页已按数据范围筛出的记录补充托盘编号、仓库与操作人名称
summaries = await FillingSummaryDao.get_list_summaries(
query_db,
[record.filling_id for record in records],
test_scope,
)
models = [
FillingListItemModel.model_validate({**record.model_dump(), **summaries.get(record.filling_id, {})})
for record in records
]
if isinstance(result, PageModel):
return result.model_copy(update={'rows': models})
return models
@classmethod
async def get_filling_batches_services(
cls,
query_db: AsyncSession,
query_object: FillingBatchPageQueryModel,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> PageModel:
warehouse_ids = await cls._warehouse_scope(query_db, current_user)
batches, total = await FillingSummaryDao.get_batch_page(query_db, query_object, warehouse_ids, test_scope)
return PageModel(
rows=[FillingBatchModel.model_validate(batch) for batch in batches],
pageNum=query_object.page_num,
pageSize=query_object.page_size,
total=total,
hasNext=query_object.page_num * query_object.page_size < total,
)
@classmethod
async def get_filling_batch_detail_services(
cls,
query_db: AsyncSession,
query_object: FillingBatchDetailQueryModel,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> FillingBatchDetailModel:
warehouse_ids = await cls._warehouse_scope(query_db, current_user)
batch = await FillingSummaryDao.get_batch_detail(
query_db,
query_object.strain_id,
query_object.batch_no,
warehouse_ids,
test_scope,
)
if batch is None:
if cls._is_admin(current_user):
raise ServiceException(message='生产批次不存在')
raise PermissionException(data='', message='无权访问该生产批次')
return FillingBatchDetailModel.model_validate(batch)
@classmethod
async def get_filling_overview_services(
cls,
query_db: AsyncSession,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> FillingOverviewModel:
warehouse_ids = await cls._warehouse_scope(query_db, current_user)
today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
overview = await FillingSummaryDao.get_overview(
query_db,
warehouse_ids,
test_scope,
today_start,
today_start.replace(day=1),
(today_start + timedelta(days=cls.NEAR_EXPIRY_DAYS)).date(),
cls.NEAR_EXPIRY_DAYS,
)
return FillingOverviewModel.model_validate(overview)
@classmethod
async def filling_detail_services(
cls,
@@ -11,6 +11,7 @@ from common.vo import CrudResponseModel, PageModel
from exceptions.exception import PermissionException, ServiceException, ServiceWarning
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_business.dao.access_dao import AccessDao
from module_business.dao.inbound_summary_dao import InboundSummaryDao
from module_business.dao.inventory_dao import InventoryDao
from module_business.dao.master_dao import MasterDao
from module_business.dao.operation_dao import OperationDao
@@ -29,7 +30,10 @@ from module_business.entity.vo.operation_vo import (
BusinessOptionModel,
ConfirmCommandModel,
InboundCreateModel,
InboundItemModel,
InboundListItemModel,
InboundModel,
InboundOverviewModel,
InboundPageQueryModel,
InboundScanQueryModel,
InboundUpdateModel,
@@ -245,7 +249,7 @@ class InboundService:
current_user: CurrentUserModel,
test_scope: TestBatchScope,
is_page: bool = True,
) -> PageModel | list[InboundModel]:
) -> PageModel | list[InboundListItemModel]:
warehouse_ids = await cls._warehouse_scope(query_db, current_user)
if (
warehouse_ids is not None
@@ -262,7 +266,17 @@ class InboundService:
is_page=is_page,
)
rows = result.rows if isinstance(result, PageModel) else result
models = [InboundModel.model_validate(record) for record in rows]
records = [InboundModel.model_validate(record) for record in rows]
# 仅对本页已按数据范围筛出的单据补充名称与托盘数
summaries = await InboundSummaryDao.get_list_summaries(
query_db,
[record.inbound_id for record in records],
test_scope,
)
models = [
InboundListItemModel.model_validate({**record.model_dump(), **summaries.get(record.inbound_id, {})})
for record in records
]
if isinstance(result, PageModel):
return result.model_copy(update={'rows': models})
return models
@@ -284,7 +298,31 @@ class InboundService:
)
if inbound is None:
cls._raise_inbound_not_accessible(current_user)
return InboundModel.model_validate(inbound)
model = InboundModel.model_validate(inbound)
if not model.items:
return model
# 托盘编号与当前状态只读展示,不参与任何写入或校验
identities = await InboundSummaryDao.get_item_identities(query_db, model.inbound_id, test_scope)
return model.model_copy(
update={
'items': [
InboundItemModel.model_validate({**item.model_dump(), **identities.get(item.inbound_item_id, {})})
for item in model.items
]
}
)
@classmethod
async def get_inbound_overview_services(
cls,
query_db: AsyncSession,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> InboundOverviewModel:
warehouse_ids = await cls._warehouse_scope(query_db, current_user)
month_start = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
overview = await InboundSummaryDao.get_overview(query_db, warehouse_ids, test_scope, month_start)
return InboundOverviewModel.model_validate(overview)
@classmethod
async def get_warehouse_options_services(
@@ -15,6 +15,7 @@ from exceptions.exception import PermissionException, ServiceException
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_business.dao.master_dao import MasterDao
from module_business.domain.test_batch_scope import TestBatchScope
from module_business.entity.vo.master_summary_vo import MasterImportPreviewModel, MasterImportPreviewRowModel
from module_business.entity.vo.master_vo import (
CustomerModel,
LineModel,
@@ -33,6 +34,11 @@ _MAX_IMPORT_BYTES = 5 * 1024 * 1024
_MAX_IMPORT_ROWS = 5000
_STATUS_TO_VALUE = {'正常': '0', '停用': '1'}
_VALUE_TO_STATUS = {'0': '正常', '1': '停用'}
_PREVIEW_MESSAGES: dict[ImportOutcome, str] = {
'add': '校验通过,将新增',
'update': '{code}已存在,将按文件内容更新',
'skip': '{code}已存在,保持原资料不变',
}
@dataclass(frozen=True)
@@ -245,6 +251,65 @@ class MasterExcelService:
raise ServiceException(message='导入失败,数据已全部回滚') from exc
return CrudResponseModel(is_success=True, message=cls._summary(added, updated, skipped, details))
@classmethod
async def preview_import(
cls,
db: AsyncSession,
resource: MasterExcelResource,
file: UploadFile,
update_support: bool,
current_user: CurrentUserModel,
scope: TestBatchScope,
) -> MasterImportPreviewModel:
"""走与正式导入完全相同的逐行校验,最后整体回滚,返回每行将发生的结果。"""
spec = _SPECS[resource]
parsed_rows = await cls._read_upload(resource, file)
rows: list[MasterImportPreviewRowModel] = []
try:
if resource == 'pallet':
await PalletService._prepare_test_write(db, current_user, scope)
else:
await MasterService._prepare_test_write(db, current_user, scope)
for row in parsed_rows:
values = [row.values.get(header, '') for header in spec.headers]
try:
outcome, _ = await cls._apply_row(db, resource, row, update_support, current_user, scope)
except ServiceException as exc:
rows.append(
MasterImportPreviewRowModel(
excel_row=row.excel_row,
outcome='error',
message=exc.message or '校验失败',
values=values,
)
)
continue
rows.append(
MasterImportPreviewRowModel(
excel_row=row.excel_row,
outcome=outcome,
message=_PREVIEW_MESSAGES[outcome].format(code=spec.code_header),
values=values,
)
)
except Exception as exc:
if isinstance(exc, (ServiceException, PermissionException)):
raise
raise ServiceException(message='导入校验失败,请稍后重试') from exc
finally:
await db.rollback()
counts = {outcome: sum(1 for row in rows if row.outcome == outcome) for outcome in _PREVIEW_MESSAGES}
return MasterImportPreviewModel(
headers=list(spec.headers),
update_support=update_support,
total_rows=len(rows),
add_count=counts['add'],
update_count=counts['update'],
skip_count=counts['skip'],
error_count=sum(1 for row in rows if row.outcome == 'error'),
rows=rows,
)
@classmethod
async def _read_upload(cls, resource: MasterExcelResource, file: UploadFile) -> list[ParsedRow]:
spec = _SPECS[resource]
@@ -0,0 +1,89 @@
from collections.abc import Awaitable, Callable
from typing import Any, Literal
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from common.vo import PageModel
from module_business.dao.master_summary_dao import MasterSummaryDao
from module_business.domain.test_batch_scope import TestBatchScope
from module_business.entity.vo.master_summary_vo import (
CustomerDetailModel,
CustomerListItemModel,
LineListItemModel,
MasterParentOptionModel,
PalletDetailModel,
PalletListItemModel,
SiteListItemModel,
StrainListItemModel,
TunnelListItemModel,
WarehouseListItemModel,
)
from module_business.entity.vo.master_vo import CustomerModel, PalletModel
SummaryResource = Literal['strain', 'customer', 'site', 'line', 'tunnel', 'warehouse', 'pallet']
_SummaryLoader = Callable[[AsyncSession, list[int], TestBatchScope], Awaitable[dict[int, dict[str, Any]]]]
_ENRICHERS: dict[SummaryResource, tuple[str, _SummaryLoader, type[BaseModel]]] = {
'strain': ('strain_id', MasterSummaryDao.get_strain_summaries, StrainListItemModel),
'customer': ('customer_id', MasterSummaryDao.get_customer_summaries, CustomerListItemModel),
'site': ('site_id', MasterSummaryDao.get_site_summaries, SiteListItemModel),
'line': ('line_id', MasterSummaryDao.get_line_summaries, LineListItemModel),
'tunnel': ('tunnel_id', MasterSummaryDao.get_tunnel_summaries, TunnelListItemModel),
'warehouse': ('warehouse_id', MasterSummaryDao.get_warehouse_summaries, WarehouseListItemModel),
'pallet': ('pallet_id', MasterSummaryDao.get_pallet_summaries, PalletListItemModel),
}
class MasterSummaryService:
"""为基础资料页面补充只读汇总。导出与写入仍使用原主数据模型。"""
@classmethod
async def enrich_page(
cls,
db: AsyncSession,
resource: SummaryResource,
page: PageModel,
scope: TestBatchScope,
) -> PageModel:
id_field, loader, item_model = _ENRICHERS[resource]
rows = list(page.rows)
summaries = await loader(db, [getattr(row, id_field) for row in rows], scope)
enriched = [
item_model.model_validate({**row.model_dump(), **summaries.get(getattr(row, id_field), {})})
for row in rows
]
return page.model_copy(update={'rows': enriched})
@classmethod
async def customer_detail(
cls,
db: AsyncSession,
customer: CustomerModel,
scope: TestBatchScope,
) -> CustomerDetailModel:
sites = await MasterSummaryDao.get_customer_site_tree(db, customer.customer_id, scope)
return CustomerDetailModel.model_validate({**customer.model_dump(), 'sites': sites})
@classmethod
async def pallet_detail(
cls,
db: AsyncSession,
pallet: PalletModel,
scope: TestBatchScope,
) -> PalletDetailModel:
summaries = await MasterSummaryDao.get_pallet_summaries(db, [pallet.pallet_id], scope)
events = await MasterSummaryDao.get_pallet_recent_events(db, pallet.pallet_id, scope)
return PalletDetailModel.model_validate(
{**pallet.model_dump(), **summaries.get(pallet.pallet_id, {}), 'recent_events': events}
)
@classmethod
async def customer_options(cls, db: AsyncSession, scope: TestBatchScope) -> list[MasterParentOptionModel]:
rows = await MasterSummaryDao.list_customer_options(db, scope)
return [MasterParentOptionModel.model_validate(row) for row in rows]
@classmethod
async def site_options(cls, db: AsyncSession, scope: TestBatchScope) -> list[MasterParentOptionModel]:
rows = await MasterSummaryDao.list_site_options(db, scope)
return [MasterParentOptionModel.model_validate(row) for row in rows]
@@ -16,6 +16,7 @@ from module_business.dao.access_dao import AccessDao
from module_business.dao.inventory_dao import InventoryDao
from module_business.dao.master_dao import MasterDao
from module_business.dao.operation_dao import OperationDao
from module_business.dao.return_summary_dao import ReturnSummaryDao
from module_business.domain.enums import PalletEventType, PalletFlowState, ReturnStatus
from module_business.domain.pallet_state_machine import PalletStateMachine
from module_business.domain.test_batch_scope import TestBatchScope, assert_record_in_scope
@@ -32,10 +33,14 @@ from module_business.entity.vo.operation_vo import (
BusinessOptionModel,
PalletScanResponseModel,
ReturnConfirmModel,
ReturnItemModel,
ReturnListItemModel,
ReturnModel,
ReturnOverviewModel,
ReturnPageQueryModel,
ReturnRequestModel,
ReturnScanQueryModel,
ReturnSiteOptionModel,
)
from module_business.service.access_service import AccessService
from module_business.service.test_batch_access_service import TestBatchAccessService
@@ -211,7 +216,7 @@ class ReturnService:
current_user: CurrentUserModel,
test_scope: TestBatchScope,
is_page: bool = True,
) -> PageModel | list[ReturnModel]:
) -> PageModel | list[ReturnListItemModel]:
site_ids, warehouse_ids = await cls._scopes(query_db, current_user)
if site_ids == [] and warehouse_ids == []:
if is_page:
@@ -233,7 +238,17 @@ class ReturnService:
is_page=is_page,
)
rows = result.rows if isinstance(result, PageModel) else result
models = [ReturnModel.model_validate(record) for record in rows]
records = [ReturnModel.model_validate(record) for record in rows]
# 仅对本页已按数据范围筛出的单据补充名称与托盘汇总
summaries = await ReturnSummaryDao.get_list_summaries(
query_db,
[record.return_id for record in records],
test_scope,
)
models = [
ReturnListItemModel.model_validate({**record.model_dump(), **summaries.get(record.return_id, {})})
for record in records
]
if isinstance(result, PageModel):
return result.model_copy(update={'rows': models})
return models
@@ -257,7 +272,42 @@ class ReturnService:
if return_order is None:
cls._raise_return_not_accessible(current_user)
assert_record_in_scope(return_order, test_scope, '退回单')
return ReturnModel.model_validate(return_order)
model = ReturnModel.model_validate(return_order)
if not model.items:
return model
# 托盘编号与隧道名称只读展示,不参与确认核对;核对仍只使用托盘ID
identities = await ReturnSummaryDao.get_item_identities(query_db, model.return_id, test_scope)
return model.model_copy(
update={
'items': [
ReturnItemModel.model_validate({**item.model_dump(), **identities.get(item.return_item_id, {})})
for item in model.items
]
}
)
@classmethod
async def get_return_overview_services(
cls,
query_db: AsyncSession,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> ReturnOverviewModel:
site_ids, warehouse_ids = await cls._scopes(query_db, current_user)
month_start = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
overview = await ReturnSummaryDao.get_overview(query_db, site_ids, warehouse_ids, test_scope, month_start)
return ReturnOverviewModel.model_validate(overview)
@classmethod
async def get_site_options_services(
cls,
query_db: AsyncSession,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> list[ReturnSiteOptionModel]:
site_ids, warehouse_ids = await cls._scopes(query_db, current_user)
options = await ReturnSummaryDao.get_site_options(query_db, site_ids, warehouse_ids, test_scope)
return [ReturnSiteOptionModel.model_validate(option) for option in options]
@classmethod
async def get_warehouse_options_services(
@@ -14,6 +14,8 @@ from module_business.dao.access_dao import AccessDao
from module_business.dao.inventory_dao import InventoryDao
from module_business.dao.master_dao import MasterDao
from module_business.dao.operation_dao import OperationDao
from module_business.dao.shipment_label_dao import ShipmentLabelDao
from module_business.dao.shipment_summary_dao import ShipmentSummaryDao
from module_business.domain.enums import DocumentStatus, PalletEventType, PalletFlowState
from module_business.domain.pallet_state_machine import PalletStateMachine
from module_business.domain.test_batch_scope import TestBatchScope, assert_record_in_scope
@@ -31,6 +33,7 @@ from module_business.entity.vo.operation_vo import (
ConfirmCommandModel,
PalletScanResponseModel,
ShipmentCreateModel,
ShipmentListItemModel,
ShipmentModel,
ShipmentPageQueryModel,
ShipmentScanQueryModel,
@@ -254,7 +257,7 @@ class ShipmentService:
current_user: CurrentUserModel,
test_scope: TestBatchScope,
is_page: bool = True,
) -> PageModel | list[ShipmentModel]:
) -> PageModel | list[ShipmentListItemModel]:
warehouse_ids, site_ids = await cls._scopes(query_db, current_user)
if (
warehouse_ids is not None
@@ -288,7 +291,17 @@ class ShipmentService:
is_page=is_page,
)
rows = result.rows if isinstance(result, PageModel) else result
models = [ShipmentModel.model_validate(record) for record in rows]
records = [ShipmentModel.model_validate(record) for record in rows]
# 仅对本页已按数据范围筛出的单据补充名称与汇总
summaries = await ShipmentSummaryDao.get_list_summaries(
query_db,
[record.shipment_id for record in records],
test_scope,
)
models = [
ShipmentListItemModel.model_validate({**record.model_dump(), **summaries.get(record.shipment_id, {})})
for record in records
]
if isinstance(result, PageModel):
return result.model_copy(update={'rows': models})
return models
@@ -311,7 +324,35 @@ class ShipmentService:
)
if shipment is None:
cls._raise_shipment_not_accessible(current_user)
return ShipmentModel.model_validate(shipment)
model = ShipmentModel.model_validate(shipment)
identities = await cls._item_identities(query_db, shipment, test_scope)
if not identities:
return model
return model.model_copy(
update={
'items': [
item.model_copy(update=identities.get(item.shipment_item_id, {}))
for item in model.items
]
}
)
@staticmethod
async def _item_identities(
query_db: AsyncSession,
shipment: BizShipmentOrder,
test_scope: TestBatchScope,
) -> dict[int, dict[str, str | None]]:
"""为详情明细补充托盘编号与菌种批次,只读展示,不参与任何写入或数量计算。"""
identities: dict[int, dict[str, str | None]] = {}
for item, pallet, filling, _quantity in await ShipmentLabelDao.get_label_sources(query_db, shipment, test_scope):
identities[item.shipment_item_id] = {
'pallet_code': getattr(pallet, 'pallet_code', None),
'strain_code': getattr(filling, 'strain_code_snapshot', None),
'strain_name': getattr(filling, 'strain_name_snapshot', None),
'batch_no': getattr(filling, 'batch_no', None),
}
return identities
@classmethod
async def get_warehouse_options_services(
@@ -6,7 +6,8 @@ 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.entity.vo.usage_fifo_vo import UsageFifoQueueModel, UsageFifoRecommendationModel
from module_business.service.access_service import AccessService
from module_business.service.usage_service import UsageService
@@ -52,3 +53,19 @@ class UsageFifoService:
recommended=candidate, unknown_arrival_count=unknown,
requires_skip_reason=needs_reason, message=message,
)
@staticmethod
async def queue(
db: AsyncSession,
site_id: int,
user: CurrentUserModel,
scope: TestBatchScope,
) -> UsageFifoQueueModel:
"""现场待使用队列(只读):与建议共用候选条件和排序,仅包含尚未入隧的托盘。"""
await AccessService.assert_site_access(db, user, site_id)
site = await MasterDao.get_site(db, site_id, scope)
if site is None:
raise ServiceException(message='客户现场不存在')
assert_record_in_scope(site, scope, '现场')
strains = await UsageFifoDao.queue(db, site_id=site_id, scope=scope)
return UsageFifoQueueModel.model_validate({'site_id': site_id, 'strains': strains})
@@ -3,7 +3,7 @@
import hashlib
import json
import secrets
from datetime import datetime
from datetime import datetime, timedelta
from typing import Any, NoReturn
from sqlalchemy.exc import IntegrityError
@@ -17,6 +17,7 @@ from module_business.dao.inventory_dao import InventoryDao
from module_business.dao.master_dao import MasterDao
from module_business.dao.operation_dao import OperationDao
from module_business.dao.usage_fifo_dao import UsageFifoDao
from module_business.dao.usage_summary_dao import UsageSummaryDao
from module_business.domain.enums import PalletEventType, PalletFlowState
from module_business.domain.fifo_policy import requires_fifo_skip_reason
from module_business.domain.pallet_state_machine import PalletStateMachine
@@ -29,8 +30,11 @@ from module_business.entity.vo.operation_vo import (
TunnelEntryCreateModel,
TunnelEntrySuccessResponseModel,
UsageCreateModel,
UsageListItemModel,
UsageModel,
UsagePageQueryModel,
UsageSiteBoardModel,
UsageSiteOptionModel,
UsageSuccessResponseModel,
)
from module_business.service.access_service import AccessService
@@ -279,7 +283,7 @@ class UsageService:
current_user: CurrentUserModel,
test_scope: TestBatchScope,
is_page: bool = True,
) -> PageModel | list[UsageModel]:
) -> PageModel | list[UsageListItemModel]:
site_ids = await cls._site_scope(query_db, current_user)
if site_ids is not None and query_object.site_id is not None and query_object.site_id not in site_ids:
raise PermissionException(data='', message='无权访问该客户现场')
@@ -301,11 +305,56 @@ class UsageService:
is_page=is_page,
)
rows = result.rows if isinstance(result, PageModel) else result
models = [UsageModel.model_validate(record) for record in rows]
records = [UsageModel.model_validate(record) for record in rows]
# 仅对本页已按数据范围筛出的记录补充名称;不改变记录本身
summaries = await UsageSummaryDao.get_list_summaries(
query_db,
[record.usage_id for record in records],
test_scope,
)
models = [
UsageListItemModel.model_validate({**record.model_dump(), **summaries.get(record.usage_id, {})})
for record in records
]
if isinstance(result, PageModel):
return result.model_copy(update={'rows': models})
return models
@classmethod
async def get_site_options_services(
cls,
query_db: AsyncSession,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> list[UsageSiteOptionModel]:
site_ids = await cls._site_scope(query_db, current_user)
options = await UsageSummaryDao.get_site_options(query_db, site_ids, test_scope)
return [UsageSiteOptionModel.model_validate(option) for option in options]
@classmethod
async def get_site_board_services(
cls,
query_db: AsyncSession,
site_id: int,
current_user: CurrentUserModel,
test_scope: TestBatchScope,
) -> UsageSiteBoardModel:
cls._current_identity(current_user)
await AccessService.assert_site_access(query_db, current_user, site_id)
site = await MasterDao.get_site(query_db, site_id, test_scope)
if site is None:
raise ServiceException(message='客户现场不存在')
assert_record_in_scope(site, test_scope, '现场')
today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
board = await UsageSummaryDao.get_site_board(
query_db,
site,
test_scope,
today_start,
today_start - timedelta(days=6),
)
return UsageSiteBoardModel.model_validate(board)
@classmethod
async def usage_detail_services(
cls,