Merge branch 'dev' into picture-feedback

This commit is contained in:
HTEWJ\26070045 committed 2026-10-29 11:04:59 +08:00
commit 34ad40778b
180 files changed
+13262 -5333

No files matched your search

@@ -1,19 +1,24 @@
"""
backend/app/services/equipment_acceptance/sync_service.py
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
停表时取消该单未发送的预警。操作人不保存 isremark。
用途:把 E10 和 E8 验收单快照写入本地表,并提供管理员查询。
依赖:extensions.db、sqlalchemy.or_、equipment_acceptance 模型、snapshot_rules、source_group、e8_group、oa_repository、e8_repository。
逻辑:两个来源分开拉取。一边失败不改另一边的快照,也不把失败来源标成消失。
只保留未归档单据。归档单不写入;该来源本次结果里没有的本地单删除,并取消未发送预警。
主表按 oa_system + request_id 更新,并写入流程编号和标题。子表整批替换。停表时取消未发送预警。
列表查询由 api/equipment_acceptance 调用。单号关键字同时匹配流程编号、验收单号和采购单号,再与申请人取交集。
"""
from __future__ import annotations
import logging
from collections import Counter
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
from sqlalchemy import or_
from app.core.errors import NotFoundError, ValidationError
from app.core.response import utc_iso
from app.extensions import db
@@ -25,12 +30,15 @@ from app.models.equipment_acceptance import (
from app.services.equipment_acceptance.config_service import first_reminder_day
from app.services.equipment_acceptance.snapshot_rules import (
MONITOR_STATUSES,
STOPPED_ARCHIVED,
classify_monitor_status,
dwell_days,
)
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
_LOGGER = logging.getLogger(__name__)
_SHANGHAI = ZoneInfo("Asia/Shanghai")
_ARCHIVED_FLOW = 3
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
_STOPPED_STATUSES = (
"stopped_returned",
@@ -42,34 +50,107 @@ _STOPPED_STATUSES = (
)
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
def sync_acceptance_snapshots(
rows: list[dict[str, Any]] | None = None,
*,
e8_rows: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
同步验收单快照。
同步 E10 和 E8 验收单快照。
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
核心逻辑:未传入行时分别读两个来源。一边查询失败只跳过这一边,不把已有快照标成消失。
只保留未归档单据。该来源本次没返回的本地单删掉。只传入 rows 时只同步 E10,方便既有测试注入联表行。
Args:
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
rows: 已取好的 E10 联表行。None 时访问 E10。
e8_rows: 已取好的 E8 联表行。与 rows 同时为 None 时才访问 E8。
Returns:
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
两边合计的写入、跳过、消失和取消条数,以及 e10、e8 各自的结果。
"""
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)
fetch_live = rows is None and e8_rows is None
e10_rows, e10_ok, e10_error = _source_rows("e10", rows, fetch_live)
e8_input, e8_ok, e8_error = _source_rows("e8", e8_rows, fetch_live)
as_of = datetime.now(_SHANGHAI).date()
e10_result = _apply_source("e10", e10_rows, e10_ok, e10_error, as_of, group_acceptance_rows)
from app.services.equipment_acceptance.e8_group import group_e8_rows
e8_result = _apply_source("e8", e8_input, e8_ok, e8_error, as_of, group_e8_rows)
db.session.commit()
cancelled = e10_result["cancelled"] + e8_result["cancelled"]
counts: Counter[str] = Counter(e10_result["by_status"])
counts.update(e8_result["by_status"])
return {
"upserted": e10_result["upserted"] + e8_result["upserted"],
"skipped_without_request_id": (
e10_result["skipped_without_request_id"] + e8_result["skipped_without_request_id"]
),
"absent": e10_result["absent"] + e8_result["absent"],
"cancelled": cancelled,
"by_status": dict(counts),
"e10": e10_result,
"e8": e8_result,
}
def _source_rows(
source: str,
injected: list[dict[str, Any]] | None,
fetch_live: bool,
) -> tuple[list[dict[str, Any]] | None, bool, str | None]:
"""取一个来源的行。注入的行视为成功。实时查询失败时不标消失。"""
if injected is not None:
return injected, True, None
if not fetch_live:
return None, False, None
try:
if source == "e10":
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
return fetch_acceptance_rows(), True, None
from app.services.equipment_acceptance.e8_repository import fetch_e8_acceptance_rows
return fetch_e8_acceptance_rows(), True, None
except Exception as exc:
_LOGGER.warning("equipment acceptance %s sync skipped error=%s", source, type(exc).__name__)
return None, False, type(exc).__name__
def _apply_source(
source: str,
rows: list[dict[str, Any]] | None,
ok: bool,
error: str | None,
as_of,
grouper,
) -> dict[str, Any]:
"""把一个来源的未归档草稿写入。该来源这次没返回的本地单删除。"""
if not ok or rows is None:
return {
"ok": False,
"error": error,
"upserted": 0,
"skipped_without_request_id": 0,
"absent": 0,
"cancelled": 0,
"by_status": {},
}
drafts, skipped = grouper(rows)
counts: Counter[str] = Counter()
request_ids: list[int] = []
cancelled = 0
for draft in drafts:
# [STEP] 归档单不落本地。查询已排除;这里再挡一层,避免注入行把归档单写回来。
if draft.flow_status_raw == _ARCHIVED_FLOW:
continue
draft.oa_system = source
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()
absent, cancelled_missing = _drop_missing(request_ids, source)
cancelled += cancelled_missing
return {
"ok": True,
"error": None,
"upserted": len(drafts),
"skipped_without_request_id": skipped,
"absent": absent,
@@ -84,17 +165,23 @@ def list_acceptance_orders(
focus: str | None,
page: int,
page_size: int,
keyword: str | None = None,
applicant: str | None = None,
) -> dict[str, Any]:
"""
分页列出本地快照。
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
核心逻辑:focus 按全部、进行中、已逾期、不再提醒、未开始过滤。
keyword 在流程编号、验收单号、采购单号里任一包含即命中,再与申请人姓名取交集。
已归档不列出。已逾期是计时中且签核天数超过第 1 档。
汇总不看当前状态分组,但跟着单号关键字和申请人走,也不计归档。
Args:
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
focus: watching、overdue、stopped、not_started 或空。
page: 从 1 开始。
page_size: 每页条数,上限 100。
keyword: 流程编号、验收单号或采购单号的包含匹配。空白表示不筛。
applicant: 申请人姓名的包含匹配。空白表示不筛。
Returns:
items、total、page、page_size、summary。
@@ -106,7 +193,11 @@ def list_acceptance_orders(
reminder_day = first_reminder_day()
page = max(1, page)
page_size = min(100, max(1, page_size))
query = db.session.query(EquipmentAcceptanceOrder)
query = _apply_search(
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
keyword=keyword,
applicant=applicant,
)
if ledger_focus:
query = _apply_focus(query, ledger_focus, reminder_day)
elif status:
@@ -131,7 +222,7 @@ def list_acceptance_orders(
"page": page,
"page_size": page_size,
"pages": pages,
"summary": _ledger_summary(reminder_day),
"summary": _ledger_summary(reminder_day, keyword=keyword, applicant=applicant),
}
@@ -160,20 +251,25 @@ def get_acceptance_order(order_id: int) -> dict[str, Any]:
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
"""
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
按来源和流程实例更新主表,并替换该单的节点和操作人。
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
E10 与 E8 的 request_id 可以相同,必须连 oa_system 一起查。
Returns:
更新后的验收单,以及本次改成已取消的发送记录条数。
"""
order = (
db.session.query(EquipmentAcceptanceOrder)
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
.filter(
EquipmentAcceptanceOrder.oa_system == draft.oa_system,
EquipmentAcceptanceOrder.request_id == draft.request_id,
)
.one_or_none()
)
now = datetime.utcnow()
if order is None:
order = EquipmentAcceptanceOrder(
oa_system=draft.oa_system,
request_id=draft.request_id,
monitor_status="excluded",
synced_at=now,
@@ -185,6 +281,9 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
order.acceptance_no = draft.acceptance_no
order.purchase_order_no = draft.purchase_order_no
order.contract_no = draft.contract_no
order.flow_no = draft.flow_no
order.request_title = draft.request_title
order.request_created_at = draft.request_created_at
order.timer_started_at = draft.timer_started_at
order.can_accept = draft.can_accept
order.cannot_accept_note = draft.cannot_accept_note
@@ -254,12 +353,45 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
return order, cancelled
def _mark_absent(request_ids: list[int]) -> int:
"""把这次没拉到的单据标成源里不存在。"""
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
def _drop_missing(request_ids: list[int], oa_system: str) -> tuple[int, int]:
"""
删除这个来源里本次未归档结果没有的本地单。
核心逻辑:查询已不含归档。本地还在、结果里没有的单,视为已归档或已从 OA 消失。
先取消未发送预警,再删主表。节点和操作人随外键级联删除。已发送记录保留,只解开验收单外键。
不改另一个来源。查询失败的来源不会进到这里。
Returns:
删除张数,以及取消的未发送条数。
"""
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.oa_system == oa_system)
if request_ids:
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
gone = query.all()
if not gone:
return 0, 0
from app.services.equipment_acceptance.alert_service import cancel_unsent
cancelled = 0
for order in gone:
cancelled += cancel_unsent(order.id)
db.session.delete(order)
return len(gone), cancelled
def _without_archived(query):
"""
列表和汇总都不展示已归档。
核心逻辑:状态已是归档的不显示。流程原值已是 3 的也不显示,
避免退回或无法验收优先落成别的状态后,归档单仍留在列表里。
"""
return query.filter(
EquipmentAcceptanceOrder.monitor_status != STOPPED_ARCHIVED,
or_(
EquipmentAcceptanceOrder.flow_status_raw.is_(None),
EquipmentAcceptanceOrder.flow_status_raw != _ARCHIVED_FLOW,
),
)
def _clean_focus(focus: str | None) -> str | None:
@@ -290,9 +422,65 @@ def _apply_focus(query, focus: str, reminder_day: int):
)
def _ledger_summary(reminder_day: int) -> dict[str, int]:
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
base = db.session.query(EquipmentAcceptanceOrder)
def _clean_search(value: str | None) -> str | None:
"""去掉首尾空白。空白视为不筛选。过长时只保留前 100 字,避免把整段说明送进 LIKE。"""
text = str(value or "").strip()
if not text:
return None
return text[:100]
def _contains_pattern(text: str) -> str:
"""
把用户输入收成包含匹配,并把 LIKE 通配符当成普通字符。
核心逻辑:% 和 _ 要能搜出单号里的原字符,不能变成任意匹配。
Args:
text: 已经去掉空白的搜索词。
Returns:
带前后百分号、且转义过的模式。
"""
escaped = text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
return f"%{escaped}%"
def _apply_search(query, *, keyword: str | None, applicant: str | None):
"""
按单号关键字和申请人收窄查询。
核心逻辑:关键字在流程编号、验收单号、采购单号三者取并集;申请人再与这个结果取交集。
比较不区分大小写。空值不加入条件。
"""
number = _clean_search(keyword)
if number:
pattern = _contains_pattern(number)
query = query.filter(or_(
EquipmentAcceptanceOrder.flow_no.ilike(pattern, escape="\\"),
EquipmentAcceptanceOrder.acceptance_no.ilike(pattern, escape="\\"),
EquipmentAcceptanceOrder.purchase_order_no.ilike(pattern, escape="\\"),
))
person = _clean_search(applicant)
if person:
query = query.filter(
EquipmentAcceptanceOrder.applicant_name.ilike(_contains_pattern(person), escape="\\"),
)
return query
def _ledger_summary(
reminder_day: int,
*,
keyword: str | None = None,
applicant: str | None = None,
) -> dict[str, int]:
"""统计未归档单据的进行中、已逾期、不再提醒、未开始。不看状态分组,但跟着单号和申请人走。"""
base = _apply_search(
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
keyword=keyword,
applicant=applicant,
)
return {
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
"overdue": base.filter(
@@ -359,9 +547,13 @@ def _order_payload(
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
payload: dict[str, Any] = {
"id": order.id,
"oa_system": order.oa_system,
"acceptance_no": order.acceptance_no,
"purchase_order_no": order.purchase_order_no,
"contract_no": order.contract_no,
"flow_no": order.flow_no,
"request_title": order.request_title,
"request_created_at": utc_iso(order.request_created_at),
"timer_started_at": utc_iso(order.timer_started_at),
"dwell_days": order.dwell_days,
"can_accept": order.can_accept,