feat(equipment-acceptance): 设备验收预警
This commit is contained in:
1 parent
239d373503
commit
86fc8a2c06
48 files changed
+6196
-82
No files matched your search
@@ -0,0 +1,412 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/sync_service.py
|
||||
|
||||
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
|
||||
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
|
||||
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
|
||||
停表时取消该单未发送的预警。操作人不保存 isremark。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.extensions import db
|
||||
from app.models.equipment_acceptance import (
|
||||
EquipmentAcceptanceNode,
|
||||
EquipmentAcceptanceOperator,
|
||||
EquipmentAcceptanceOrder,
|
||||
)
|
||||
from app.services.equipment_acceptance.config_service import first_reminder_day
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
MONITOR_STATUSES,
|
||||
classify_monitor_status,
|
||||
dwell_days,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
|
||||
|
||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
|
||||
_STOPPED_STATUSES = (
|
||||
"stopped_returned",
|
||||
"stopped_cannot_accept",
|
||||
"stopped_archived",
|
||||
"stopped_force_finished",
|
||||
"stopped_voided",
|
||||
"stopped_revoked",
|
||||
)
|
||||
|
||||
|
||||
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
同步验收单快照。
|
||||
|
||||
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
|
||||
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
|
||||
Args:
|
||||
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
|
||||
Returns:
|
||||
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
|
||||
"""
|
||||
if rows is None:
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||
|
||||
rows = fetch_acceptance_rows()
|
||||
drafts, skipped = group_acceptance_rows(rows)
|
||||
as_of = datetime.now(_SHANGHAI).date()
|
||||
counts: Counter[str] = Counter()
|
||||
request_ids: list[int] = []
|
||||
cancelled = 0
|
||||
for draft in drafts:
|
||||
order, cancelled_now = _upsert_order(draft, as_of=as_of)
|
||||
request_ids.append(order.request_id)
|
||||
counts[order.monitor_status] += 1
|
||||
cancelled += cancelled_now
|
||||
absent = _mark_absent(request_ids)
|
||||
db.session.commit()
|
||||
return {
|
||||
"upserted": len(drafts),
|
||||
"skipped_without_request_id": skipped,
|
||||
"absent": absent,
|
||||
"cancelled": cancelled,
|
||||
"by_status": dict(counts),
|
||||
}
|
||||
|
||||
|
||||
def list_acceptance_orders(
|
||||
*,
|
||||
monitor_status: str | None,
|
||||
focus: str | None,
|
||||
page: int,
|
||||
page_size: int,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出本地快照。
|
||||
|
||||
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
|
||||
Args:
|
||||
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
|
||||
focus: watching、overdue、stopped、not_started 或空。
|
||||
page: 从 1 开始。
|
||||
page_size: 每页条数,上限 100。
|
||||
Returns:
|
||||
items、total、page、page_size、summary。
|
||||
|
||||
Raises:
|
||||
ValidationError: focus 或监控状态不是已定义值。
|
||||
"""
|
||||
status = _clean_status(monitor_status)
|
||||
ledger_focus = _clean_focus(focus)
|
||||
reminder_day = first_reminder_day()
|
||||
page = max(1, page)
|
||||
page_size = min(100, max(1, page_size))
|
||||
query = db.session.query(EquipmentAcceptanceOrder)
|
||||
if ledger_focus:
|
||||
query = _apply_focus(query, ledger_focus, reminder_day)
|
||||
elif status:
|
||||
query = query.filter(EquipmentAcceptanceOrder.monitor_status == status)
|
||||
total = query.count()
|
||||
orders = (
|
||||
query.order_by(EquipmentAcceptanceOrder.synced_at.desc(), EquipmentAcceptanceOrder.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
order_ids = [order.id for order in orders]
|
||||
nodes = _nodes_by_order(order_ids)
|
||||
operators = _operators_by_order(order_ids)
|
||||
pages = (total + page_size - 1) // page_size if total else 1
|
||||
return {
|
||||
"items": [
|
||||
_order_payload(order, nodes.get(order.id, []), operators.get(order.id, []), reminder_day)
|
||||
for order in orders
|
||||
],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"summary": _ledger_summary(reminder_day),
|
||||
}
|
||||
|
||||
|
||||
def get_acceptance_order(order_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
读取一张验收单快照,含当前节点和操作人原值。
|
||||
|
||||
Args:
|
||||
order_id: 本地主键。
|
||||
Returns:
|
||||
快照详情。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 记录不存在。
|
||||
"""
|
||||
order = db.session.get(EquipmentAcceptanceOrder, order_id)
|
||||
if order is None:
|
||||
raise NotFoundError("设备验收同步记录不存在", code="EQUIPMENT_ACCEPTANCE.NOT_FOUND")
|
||||
return _order_payload(
|
||||
order,
|
||||
_nodes_by_order([order.id]).get(order.id, []),
|
||||
_operators_by_order([order.id]).get(order.id, []),
|
||||
first_reminder_day(),
|
||||
)
|
||||
|
||||
|
||||
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
|
||||
"""
|
||||
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
|
||||
|
||||
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
|
||||
Returns:
|
||||
更新后的验收单,以及本次改成已取消的发送记录条数。
|
||||
"""
|
||||
order = (
|
||||
db.session.query(EquipmentAcceptanceOrder)
|
||||
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
|
||||
.one_or_none()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if order is None:
|
||||
order = EquipmentAcceptanceOrder(
|
||||
request_id=draft.request_id,
|
||||
monitor_status="excluded",
|
||||
synced_at=now,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(order)
|
||||
db.session.flush()
|
||||
order.acceptance_no = draft.acceptance_no
|
||||
order.purchase_order_no = draft.purchase_order_no
|
||||
order.contract_no = draft.contract_no
|
||||
order.timer_started_at = draft.timer_started_at
|
||||
order.can_accept = draft.can_accept
|
||||
order.cannot_accept_note = draft.cannot_accept_note
|
||||
order.is_returned = draft.is_returned
|
||||
order.flow_status_raw = draft.flow_status_raw
|
||||
order.finished_at = draft.finished_at
|
||||
order.request_id = draft.request_id
|
||||
order.request_match_count = draft.request_match_count
|
||||
order.owner_oa_id = draft.owner_oa_id
|
||||
order.owner_name = draft.owner_name
|
||||
order.owner_job_num = draft.owner_job_num
|
||||
order.equip_oa_id = draft.equip_oa_id
|
||||
order.equip_name = draft.equip_name
|
||||
order.equip_job_num = draft.equip_job_num
|
||||
order.applicant_oa_id = draft.applicant_oa_id
|
||||
order.applicant_name = draft.applicant_name
|
||||
order.applicant_job_num = draft.applicant_job_num
|
||||
order.monitor_status = classify_monitor_status(
|
||||
can_accept=draft.can_accept,
|
||||
is_returned=draft.is_returned,
|
||||
flow_status=draft.flow_status_raw,
|
||||
timer_started=draft.timer_started_at is not None,
|
||||
)
|
||||
order.dwell_days = dwell_days(
|
||||
timer_started_at=draft.timer_started_at,
|
||||
flow_status=draft.flow_status_raw,
|
||||
finished_at=draft.finished_at,
|
||||
as_of=as_of,
|
||||
)
|
||||
order.present_in_source = True
|
||||
order.synced_at = now
|
||||
order.updated_at = now
|
||||
cancelled = 0
|
||||
if order.monitor_status != "watching":
|
||||
from app.services.equipment_acceptance.alert_service import cancel_unsent
|
||||
|
||||
cancelled = cancel_unsent(order.id)
|
||||
# [STEP] 先从会话里删掉旧子行,再插入本次节点和操作人,避免批量 delete 后旧对象被重新写回
|
||||
for node in db.session.query(EquipmentAcceptanceNode).filter(EquipmentAcceptanceNode.order_id == order.id).all():
|
||||
db.session.delete(node)
|
||||
for operator in (
|
||||
db.session.query(EquipmentAcceptanceOperator)
|
||||
.filter(EquipmentAcceptanceOperator.order_id == order.id)
|
||||
.all()
|
||||
):
|
||||
db.session.delete(operator)
|
||||
db.session.flush()
|
||||
for node in draft.nodes:
|
||||
db.session.add(
|
||||
EquipmentAcceptanceNode(
|
||||
order_id=order.id,
|
||||
node_id=node.node_id,
|
||||
node_name=node.node_name,
|
||||
node_type=node.node_type,
|
||||
)
|
||||
)
|
||||
for operator in draft.operators:
|
||||
db.session.add(
|
||||
EquipmentAcceptanceOperator(
|
||||
order_id=order.id,
|
||||
node_id=operator.node_id,
|
||||
user_id=operator.user_id,
|
||||
handler_name=operator.handler_name,
|
||||
handler_job_num=operator.handler_job_num,
|
||||
)
|
||||
)
|
||||
return order, cancelled
|
||||
|
||||
|
||||
def _mark_absent(request_ids: list[int]) -> int:
|
||||
"""把这次没拉到的单据标成源里不存在。"""
|
||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
|
||||
if request_ids:
|
||||
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
|
||||
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
|
||||
|
||||
|
||||
def _clean_focus(focus: str | None) -> str | None:
|
||||
"""空白视为全部。未知分组拒绝,避免把原型筛选项写错后悄悄查出空表。"""
|
||||
value = str(focus or "").strip()
|
||||
if not value or value == "all":
|
||||
return None
|
||||
if value not in _LEDGER_FOCUSES:
|
||||
raise ValidationError(
|
||||
"未知的设备验收列表分组",
|
||||
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||
details={"focus": value},
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _apply_focus(query, focus: str, reminder_day: int):
|
||||
"""按停留列表分组过滤。已逾期只含计时中且超过当前第 1 档的单据。"""
|
||||
if focus == "watching":
|
||||
return query.filter(EquipmentAcceptanceOrder.monitor_status == "watching")
|
||||
if focus == "not_started":
|
||||
return query.filter(EquipmentAcceptanceOrder.monitor_status == "not_started")
|
||||
if focus == "stopped":
|
||||
return query.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES))
|
||||
return query.filter(
|
||||
EquipmentAcceptanceOrder.monitor_status == "watching",
|
||||
EquipmentAcceptanceOrder.dwell_days > reminder_day,
|
||||
)
|
||||
|
||||
|
||||
def _ledger_summary(reminder_day: int) -> dict[str, int]:
|
||||
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
|
||||
base = db.session.query(EquipmentAcceptanceOrder)
|
||||
return {
|
||||
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
|
||||
"overdue": base.filter(
|
||||
EquipmentAcceptanceOrder.monitor_status == "watching",
|
||||
EquipmentAcceptanceOrder.dwell_days > reminder_day,
|
||||
).count(),
|
||||
"stopped": base.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES)).count(),
|
||||
"not_started": base.filter(EquipmentAcceptanceOrder.monitor_status == "not_started").count(),
|
||||
}
|
||||
|
||||
|
||||
def _clean_status(monitor_status: str | None) -> str | None:
|
||||
"""空白过滤视为不筛选。未知状态拒绝,避免把撤回等未定义值写进查询。"""
|
||||
status = str(monitor_status or "").strip()
|
||||
if not status:
|
||||
return None
|
||||
if status not in MONITOR_STATUSES:
|
||||
raise ValidationError(
|
||||
"未知的设备验收监控状态",
|
||||
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||
details={"monitor_status": status},
|
||||
)
|
||||
return status
|
||||
|
||||
|
||||
def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]:
|
||||
"""一次取出当前页的节点,避免逐单查询。"""
|
||||
if not order_ids:
|
||||
return {}
|
||||
grouped: dict[int, list[EquipmentAcceptanceNode]] = {}
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceNode)
|
||||
.filter(EquipmentAcceptanceNode.order_id.in_(order_ids))
|
||||
.order_by(EquipmentAcceptanceNode.id.asc())
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
grouped.setdefault(row.order_id, []).append(row)
|
||||
return grouped
|
||||
|
||||
|
||||
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
|
||||
"""一次取出当前页的操作人,避免逐单查询。"""
|
||||
if not order_ids:
|
||||
return {}
|
||||
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceOperator)
|
||||
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
|
||||
.order_by(EquipmentAcceptanceOperator.id.asc())
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
grouped.setdefault(row.order_id, []).append(row)
|
||||
return grouped
|
||||
|
||||
|
||||
def _order_payload(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
nodes: list[EquipmentAcceptanceNode],
|
||||
operators: list[EquipmentAcceptanceOperator],
|
||||
reminder_day: int,
|
||||
) -> dict[str, Any]:
|
||||
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
|
||||
payload: dict[str, Any] = {
|
||||
"id": order.id,
|
||||
"acceptance_no": order.acceptance_no,
|
||||
"purchase_order_no": order.purchase_order_no,
|
||||
"contract_no": order.contract_no,
|
||||
"timer_started_at": utc_iso(order.timer_started_at),
|
||||
"dwell_days": order.dwell_days,
|
||||
"can_accept": order.can_accept,
|
||||
"cannot_accept_note": order.cannot_accept_note,
|
||||
"is_returned": order.is_returned,
|
||||
"flow_status_raw": order.flow_status_raw,
|
||||
"finished_at": utc_iso(order.finished_at),
|
||||
"request_id": _id_text(order.request_id),
|
||||
"request_match_count": order.request_match_count,
|
||||
"owner_oa_id": _id_text(order.owner_oa_id),
|
||||
"owner_name": order.owner_name,
|
||||
"owner_job_num": order.owner_job_num,
|
||||
"equip_oa_id": _id_text(order.equip_oa_id),
|
||||
"equip_name": order.equip_name,
|
||||
"equip_job_num": order.equip_job_num,
|
||||
"applicant_oa_id": _id_text(order.applicant_oa_id),
|
||||
"applicant_name": order.applicant_name,
|
||||
"applicant_job_num": order.applicant_job_num,
|
||||
"monitor_status": order.monitor_status,
|
||||
"overdue": order.monitor_status == "watching" and (order.dwell_days or 0) > reminder_day,
|
||||
"present_in_source": order.present_in_source,
|
||||
"synced_at": utc_iso(order.synced_at),
|
||||
"nodes": [
|
||||
{
|
||||
"node_id": _id_text(node.node_id),
|
||||
"node_name": node.node_name,
|
||||
"node_type": node.node_type,
|
||||
}
|
||||
for node in nodes
|
||||
],
|
||||
"operators": [
|
||||
{
|
||||
"node_id": _id_text(item.node_id),
|
||||
"user_id": _id_text(item.user_id),
|
||||
"handler_name": item.handler_name,
|
||||
"handler_job_num": item.handler_job_num,
|
||||
}
|
||||
for item in operators
|
||||
],
|
||||
}
|
||||
return payload
|
||||
|
||||
|
||||
def _id_text(value: int | None) -> str | None:
|
||||
"""OA 长整型主键序列化成字符串。"""
|
||||
if value is None:
|
||||
return None
|
||||
return str(value)
|
||||
Reference in new issue
Block a user