fix: 设备验收预警优化
This commit is contained in:
1 parent
7e7bcbd388
commit
b8cc0cbe77
25 files changed
+1398
-193
No files matched your search
@@ -2,8 +2,9 @@
|
||||
backend/app/services/equipment_acceptance/alert_service.py
|
||||
|
||||
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||
依赖:同步服务、OA 人员目录、alert_plan、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10,再按停留天数跨档。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,15 +12,23 @@ from __future__ import annotations
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.equipment_acceptance import (
|
||||
EquipmentAcceptanceNode,
|
||||
EquipmentAcceptanceOperator,
|
||||
EquipmentAcceptanceOrder,
|
||||
EquipmentAcceptanceSendFile,
|
||||
EquipmentAcceptanceSendRecord,
|
||||
EquipmentAcceptanceSetting,
|
||||
)
|
||||
from app.models.user import User
|
||||
from app.services.equipment_acceptance.alert_notice import (
|
||||
NOTICE_FILE_NAME,
|
||||
build_notice_workbook,
|
||||
summary_message,
|
||||
)
|
||||
from app.services.equipment_acceptance.alert_plan import (
|
||||
assemble_tier,
|
||||
due_tiers,
|
||||
@@ -27,7 +36,7 @@ from app.services.equipment_acceptance.alert_plan import (
|
||||
resolve_account,
|
||||
resolve_configured_user,
|
||||
)
|
||||
from app.services.equipment_acceptance.config_service import reminder_days
|
||||
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
|
||||
from app.services.equipment_acceptance.snapshot_rules import WATCHING
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -61,7 +70,7 @@ def refresh_pending_alerts(
|
||||
"""
|
||||
按本地快照刷新待发送记录。
|
||||
|
||||
核心逻辑:计时中的单据跨过哪一档就保留哪一档。已发送和已取消不改。
|
||||
核心逻辑:计时中的单据跨过哪一档就保留哪一档。第 4 轮关闭时最高只到第 3 档。已发送和已取消不改。
|
||||
未计时或已停表的单据,把还没发出的记录改成已取消。
|
||||
Args:
|
||||
directory: 测试注入的人员目录和经副理。空则查询 E10。
|
||||
@@ -74,6 +83,7 @@ def refresh_pending_alerts(
|
||||
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
||||
roles = _configured_users()
|
||||
thresholds = reminder_days()
|
||||
max_tier = 4 if is_round_4_enabled() else 3
|
||||
existing = {
|
||||
(row.order_id, row.tier): row
|
||||
for row in db.session.query(EquipmentAcceptanceSendRecord).all()
|
||||
@@ -86,7 +96,16 @@ def refresh_pending_alerts(
|
||||
if order.monitor_status != WATCHING:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
continue
|
||||
for draft in _drafts(order, operators.get(order.id, []), people, deputies, users_by_job, roles, thresholds):
|
||||
for draft in _drafts(
|
||||
order,
|
||||
operators.get(order.id, []),
|
||||
people,
|
||||
deputies,
|
||||
users_by_job,
|
||||
roles,
|
||||
thresholds,
|
||||
max_tier=max_tier,
|
||||
):
|
||||
current = existing.get((order.id, draft["tier"]))
|
||||
if current is not None and current.status in ("sent", "cancelled"):
|
||||
continue
|
||||
@@ -136,24 +155,37 @@ def send_pending_alerts() -> dict[str, Any]:
|
||||
"""
|
||||
把待发送记录按收件人合并成一条企业微信。
|
||||
|
||||
核心逻辑:同一个人本轮只收一条。解析失败的人不改发给别人。已取消和已发送不参与。
|
||||
核心逻辑:同一个人本轮只收一条汇总卡片和一份 Excel。卡片只写张数,明细在文件里。
|
||||
解析失败的人不改发给别人。已取消和已发送不参与。
|
||||
第 4 轮关闭时,已生成的待发送第 4 轮也不发出,避免通知总经理。
|
||||
卡片或附件任一失败都记失败原因,并打一条 warning 日志。
|
||||
每位收件人的 Excel 都写入 equipment_acceptance_send_files,发送失败也保留。
|
||||
Returns:
|
||||
成功人数、失败人数,以及对应的记录条数。
|
||||
"""
|
||||
from app.models import Agent
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import (
|
||||
send_wecom_event_message,
|
||||
send_wecom_file_message,
|
||||
upload_wecom_temp_media,
|
||||
)
|
||||
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceSendRecord)
|
||||
.filter(EquipmentAcceptanceSendRecord.status == "pending")
|
||||
.all()
|
||||
)
|
||||
if not is_round_4_enabled():
|
||||
rows = [row for row in rows if row.tier != 4]
|
||||
orders = {
|
||||
order.id: order
|
||||
for order in db.session.query(EquipmentAcceptanceOrder)
|
||||
.filter(EquipmentAcceptanceOrder.id.in_([row.order_id for row in rows if row.order_id]))
|
||||
.all()
|
||||
} if rows else {}
|
||||
order_ids = [row.order_id for row in rows if row.order_id]
|
||||
nodes = _nodes_by_order(order_ids)
|
||||
operators = _operators_by_order(order_ids)
|
||||
users = _users_by_id(_recipient_user_ids(rows))
|
||||
buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {}
|
||||
for row in rows:
|
||||
@@ -166,24 +198,58 @@ def send_pending_alerts() -> dict[str, Any]:
|
||||
jump_path = f"/chat/{agent.id}" if agent is not None else "/workspace"
|
||||
jump_params = {"view": "sends"} if agent is not None else None
|
||||
sent_ids: set[str] = set()
|
||||
failed_ids: set[str] = set()
|
||||
failed_reasons: dict[str, str] = {}
|
||||
for wecom_id, entries in buckets.items():
|
||||
user = _audit_user(entries, users)
|
||||
lines = _notice_lines(entries, orders, nodes, operators)
|
||||
workbook = build_notice_workbook(lines)
|
||||
archived = _archive_send_file(user, entries, workbook)
|
||||
failure = ""
|
||||
try:
|
||||
result = send_wecom_event_message(
|
||||
event_type=_EVENT,
|
||||
user=user,
|
||||
title="设备验收停留提醒",
|
||||
content=_message(entries, orders),
|
||||
content=summary_message(lines),
|
||||
jump_path=jump_path,
|
||||
jump_params=jump_params,
|
||||
wecom_userid=wecom_id,
|
||||
)
|
||||
ok = bool(result.get("ok"))
|
||||
except Exception:
|
||||
_LOGGER.warning("equipment acceptance wecom send failed")
|
||||
ok = False
|
||||
(sent_ids if ok else failed_ids).add(wecom_id)
|
||||
_LOGGER.exception("equipment acceptance wecom send failed")
|
||||
failure = "企业微信发送异常"
|
||||
result = {}
|
||||
if not failure and not result.get("ok"):
|
||||
failure = _wecom_failure_text(result)
|
||||
_LOGGER.warning(
|
||||
"equipment acceptance wecom send failed reason=%s trace_id=%s detail=%s",
|
||||
result.get("reason"),
|
||||
result.get("trace_id"),
|
||||
failure,
|
||||
)
|
||||
if not failure:
|
||||
try:
|
||||
media_id = upload_wecom_temp_media(workbook, archived.excel_file_name or NOTICE_FILE_NAME)
|
||||
file_result = send_wecom_file_message(wecom_id, media_id)
|
||||
except Exception:
|
||||
_LOGGER.exception("equipment acceptance wecom file upload failed")
|
||||
failure = "企业微信附件上传失败"
|
||||
file_result = {}
|
||||
if not failure and file_result.get("errcode") != 0:
|
||||
failure = _file_failure_text(file_result)
|
||||
_LOGGER.warning(
|
||||
"equipment acceptance wecom file failed errcode=%s errmsg=%s",
|
||||
file_result.get("errcode"),
|
||||
failure,
|
||||
)
|
||||
if failure:
|
||||
failed_reasons[wecom_id] = failure
|
||||
archived.status = "failed"
|
||||
archived.error_message = failure
|
||||
else:
|
||||
sent_ids.add(wecom_id)
|
||||
archived.status = "sent"
|
||||
archived.sent_at = datetime.utcnow()
|
||||
records_sent = 0
|
||||
records_failed = 0
|
||||
now = datetime.utcnow()
|
||||
@@ -196,9 +262,10 @@ def send_pending_alerts() -> dict[str, Any]:
|
||||
ready.discard("")
|
||||
if not ready:
|
||||
continue
|
||||
if ready & failed_ids:
|
||||
hit = [failed_reasons[item] for item in ready if item in failed_reasons]
|
||||
if hit:
|
||||
row.status = "failed"
|
||||
row.error_message = _join_error(row.error_message, "企业微信发送失败")
|
||||
row.error_message = _join_error(row.error_message, ";".join(dict.fromkeys(hit)))
|
||||
records_failed += 1
|
||||
elif ready <= sent_ids:
|
||||
row.status = "sent"
|
||||
@@ -207,7 +274,7 @@ def send_pending_alerts() -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
return {
|
||||
"sent": len(sent_ids),
|
||||
"failed": len(failed_ids),
|
||||
"failed": len(failed_reasons),
|
||||
"records_sent": records_sent,
|
||||
"records_failed": records_failed,
|
||||
}
|
||||
@@ -221,9 +288,11 @@ def _drafts(
|
||||
users_by_job: dict[str, User],
|
||||
roles: dict[str, User | None],
|
||||
thresholds: tuple[int, int, int, int],
|
||||
*,
|
||||
max_tier: int = 4,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按当前处理人展开四档里已经跨过的档。"""
|
||||
due = due_tiers(order.dwell_days, thresholds)
|
||||
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
|
||||
if not due:
|
||||
return []
|
||||
handlers: list[dict[str, Any]] = []
|
||||
@@ -410,6 +479,21 @@ def _users_by_id(user_ids: list[int]) -> dict[int, User]:
|
||||
return {row.id: row for row in rows}
|
||||
|
||||
|
||||
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))
|
||||
.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:
|
||||
@@ -447,28 +531,145 @@ def _audit_user(
|
||||
return None
|
||||
|
||||
|
||||
def _message(
|
||||
def _archive_send_file(
|
||||
user: User | None,
|
||||
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||
workbook: bytes,
|
||||
) -> EquipmentAcceptanceSendFile:
|
||||
"""
|
||||
把这次准备发给一名收件人的 Excel 先落库。
|
||||
|
||||
核心逻辑:发送成功或失败都保留同一份字节,并记下里面的发送记录,供表格列下载。不保存企微 userid。
|
||||
Args:
|
||||
user: 系统用户。对不上账号时只留姓名。
|
||||
entries: 这名收件人的发送记录和席位,用来取展示名。
|
||||
workbook: xlsx 字节。
|
||||
Returns:
|
||||
已加入当前事务、尚未提交的文件行。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
name = _recipient_display_name(user, entries)
|
||||
row = EquipmentAcceptanceSendFile(
|
||||
recipient_user_id=None if user is None else user.id,
|
||||
recipient_name=name or None,
|
||||
excel_file_name=_archive_file_name(name, now),
|
||||
excel_file_data=workbook,
|
||||
excel_file_size=len(workbook),
|
||||
send_record_ids=[row.id for row, _person in entries if row.id],
|
||||
status="pending",
|
||||
created_at=now,
|
||||
)
|
||||
db.session.add(row)
|
||||
return row
|
||||
|
||||
|
||||
def _recipient_display_name(
|
||||
user: User | None,
|
||||
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||
) -> str:
|
||||
"""优先用系统姓名,没有账号时用收件人席位上的名字。"""
|
||||
if user is not None:
|
||||
named = str(user.real_name or user.username or "").strip()
|
||||
if named:
|
||||
return named
|
||||
for _row, person in entries:
|
||||
named = str(person.get("name") or "").strip()
|
||||
if named:
|
||||
return named
|
||||
return ""
|
||||
|
||||
|
||||
def _archive_file_name(recipient_name: str, moment: datetime) -> str:
|
||||
"""文件名带上海日期和收件人,避免多次发送都叫同一个名字。"""
|
||||
local = moment.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Shanghai"))
|
||||
safe = "".join(char for char in recipient_name if char not in '\\/:*?"<>|').strip() or "收件人"
|
||||
return f"设备验收停留提醒-{local:%Y%m%d}-{safe}.xlsx"[:255]
|
||||
|
||||
|
||||
def _notice_lines(
|
||||
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||
orders: dict[int, EquipmentAcceptanceOrder],
|
||||
) -> str:
|
||||
"""拼一名收件人本轮要看的验收单。过长时截断。"""
|
||||
lines: list[str] = []
|
||||
seen: set[int] = set()
|
||||
nodes: dict[int, list[EquipmentAcceptanceNode]],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
把一名收件人的发送记录收成 Excel 行。
|
||||
|
||||
核心逻辑:同一条发送记录只占一行。通知身份用角色名,例如当前处理人、直接主管,不写主送或抄送。
|
||||
Args:
|
||||
entries: 这名收件人挂到的发送记录和对应席位。
|
||||
orders: 验收单主键到快照。
|
||||
nodes: 验收单主键到当前节点。
|
||||
operators: 验收单主键到当前处理人。
|
||||
Returns:
|
||||
传给汇总文案和 Excel 的明细行。
|
||||
"""
|
||||
grouped: dict[int, dict[str, Any]] = {}
|
||||
order_keys: list[int] = []
|
||||
for row, person in entries:
|
||||
if row.id in seen:
|
||||
continue
|
||||
seen.add(row.id)
|
||||
label = str(person.get("label") or "").strip()
|
||||
bucket = grouped.get(row.id)
|
||||
if bucket is None:
|
||||
bucket = {"row": row, "labels": []}
|
||||
grouped[row.id] = bucket
|
||||
order_keys.append(row.id)
|
||||
if label and label not in bucket["labels"]:
|
||||
bucket["labels"].append(label)
|
||||
lines: list[dict[str, Any]] = []
|
||||
for key in order_keys:
|
||||
row = grouped[key]["row"]
|
||||
order = orders.get(row.order_id or 0)
|
||||
days = "—" if order is None or order.dwell_days is None else str(order.dwell_days)
|
||||
role = "主送" if person.get("slot") == "to" else "抄送"
|
||||
lines.append(
|
||||
f"{role} {row.acceptance_no or '—'},采购单 {row.purchase_order_no or '—'},"
|
||||
f"停留 {days} 天,超过 {row.threshold_days} 天"
|
||||
)
|
||||
text = "\n".join(lines[:12])
|
||||
if len(lines) > 12:
|
||||
text = f"{text}\n另有 {len(lines) - 12} 条"
|
||||
return text[:500]
|
||||
node_names = _unique_text(node.node_name for node in nodes.get(row.order_id or 0, []))
|
||||
handler_names = _unique_text(operator.handler_name for operator in operators.get(row.order_id or 0, []))
|
||||
lines.append({
|
||||
"acceptance_no": row.acceptance_no,
|
||||
"purchase_order_no": row.purchase_order_no,
|
||||
"applicant": None if order is None else order.applicant_name,
|
||||
"threshold_days": row.threshold_days,
|
||||
"dwell_days": None if order is None else order.dwell_days,
|
||||
"node_name": "、".join(node_names),
|
||||
"handlers": "、".join(handler_names),
|
||||
"identity": "、".join(grouped[key]["labels"]),
|
||||
})
|
||||
return lines
|
||||
|
||||
|
||||
def _unique_text(values) -> list[str]:
|
||||
"""按出现顺序去掉空白和重复名称。"""
|
||||
found: list[str] = []
|
||||
for value in values:
|
||||
text = str(value or "").strip()
|
||||
if text and text not in found:
|
||||
found.append(text)
|
||||
return found
|
||||
|
||||
|
||||
def _file_failure_text(result: dict[str, Any]) -> str:
|
||||
"""把企微文件消息的返回收成失败原因。不写入 userid。"""
|
||||
code = result.get("errcode")
|
||||
message = str(result.get("errmsg") or "").strip()
|
||||
text = f"企业微信附件发送失败 {code} {message}".strip()
|
||||
return text[:255]
|
||||
|
||||
|
||||
def _wecom_failure_text(result: dict[str, Any]) -> str:
|
||||
"""把企微发送结果收成页面和日志都能看的失败原因。不写入 userid。"""
|
||||
reason = str(result.get("reason") or "")
|
||||
if reason == "notify_disabled":
|
||||
return "企业微信通知总开关已关闭"
|
||||
if reason == "event_disabled":
|
||||
return "未开启设备验收预警的企业微信事件"
|
||||
if reason == "user_unbound":
|
||||
return "收件人未绑定企业微信"
|
||||
raw = result.get("raw") if isinstance(result.get("raw"), dict) else {}
|
||||
if reason == "send_failed":
|
||||
code = raw.get("errcode")
|
||||
message = str(raw.get("errmsg") or "").strip()
|
||||
text = f"企业微信返回 {code} {message}".strip()
|
||||
return text[:255]
|
||||
if reason == "exception":
|
||||
return "企业微信发送异常"
|
||||
return "企业微信发送失败"
|
||||
|
||||
|
||||
def _join_error(current: str | None, extra: str) -> str:
|
||||
|
||||
Reference in new issue
Block a user