fix: 设备验收预警优化
This commit is contained in:
1 parent
7e7bcbd388
commit
b8cc0cbe77
25 files changed
+1398
-193
No files matched your search
@@ -3,12 +3,14 @@ backend/app/api/equipment_acceptance/__init__.py
|
||||
|
||||
用途:设备验收预警的 Chat 作业面接口。
|
||||
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录和配置;同步、扫描、发送和保存配置仅平台管理员。
|
||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, g, request
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
@@ -19,7 +21,7 @@ from app.services.equipment_acceptance.config_service import (
|
||||
save_acceptance_config,
|
||||
)
|
||||
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
||||
from app.services.equipment_acceptance.send_record_service import list_send_records
|
||||
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
|
||||
from app.services.equipment_acceptance.sync_service import (
|
||||
get_acceptance_order,
|
||||
list_acceptance_orders,
|
||||
@@ -157,6 +159,26 @@ def send_equipment_acceptance_alerts():
|
||||
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
||||
def list_equipment_acceptance_send_files():
|
||||
"""列出最近按收件人归档的 Excel。不含文件字节。"""
|
||||
_require_equipment_acceptance_access()
|
||||
return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files/<int:file_id>/excel", methods=["GET"])
|
||||
def download_equipment_acceptance_send_file(file_id: int):
|
||||
"""下载一份当时发给收件人的设备验收预警 Excel。"""
|
||||
_require_equipment_acceptance_access()
|
||||
row = get_send_file(file_id)
|
||||
return send_file(
|
||||
BytesIO(row.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/sends", methods=["GET"])
|
||||
def list_equipment_acceptance_sends():
|
||||
"""分页查看发送记录。扫描写入后这里才有行。"""
|
||||
|
||||
@@ -242,6 +242,7 @@ from app.models.equipment_acceptance import (
|
||||
EquipmentAcceptanceNode,
|
||||
EquipmentAcceptanceOperator,
|
||||
EquipmentAcceptanceOrder,
|
||||
EquipmentAcceptanceSendFile,
|
||||
EquipmentAcceptanceSendRecord,
|
||||
EquipmentAcceptanceSetting,
|
||||
)
|
||||
@@ -445,6 +446,7 @@ __all__ = [
|
||||
'EquipmentAcceptanceNode',
|
||||
'EquipmentAcceptanceOperator',
|
||||
'EquipmentAcceptanceSetting',
|
||||
'EquipmentAcceptanceSendFile',
|
||||
'EquipmentAcceptanceSendRecord',
|
||||
'TransferRun',
|
||||
'TransferSourceJob',
|
||||
|
||||
@@ -4,8 +4,9 @@ backend/app/models/equipment_acceptance.py
|
||||
用途:设备验收预警的本地同步快照和可改配置。
|
||||
依赖:models.base.Base、users。
|
||||
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||
配置表只存四档天数和三个固定岗位的系统用户。发送时刻不在这张表。
|
||||
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
||||
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
||||
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
||||
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||
"""
|
||||
|
||||
@@ -14,7 +15,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, String, Text, UniqueConstraint
|
||||
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, LargeBinary, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -116,6 +117,7 @@ class EquipmentAcceptanceSetting(Base):
|
||||
day_2: Mapped[int] = mapped_column(nullable=False, default=37)
|
||||
day_3: Mapped[int] = mapped_column(nullable=False, default=44)
|
||||
day_4: Mapped[int] = mapped_column(nullable=False, default=51)
|
||||
round_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
@@ -154,3 +156,26 @@ class EquipmentAcceptanceSendRecord(Base):
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
|
||||
|
||||
class EquipmentAcceptanceSendFile(Base):
|
||||
"""一位收件人一次发送留下的 Excel。字节与当时发给企业微信的文件相同。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_send_files"
|
||||
__table_args__ = (
|
||||
Index("ix_equipment_acceptance_send_files_created", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
recipient_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
recipient_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
send_record_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="sent")
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/alert_notice.py
|
||||
|
||||
用途:把一名收件人的待发送记录收成企微汇总文案和 Excel 明细。
|
||||
依赖:openpyxl。
|
||||
逻辑:发送服务按企业微信账号调用。卡片只写张数,逐张明细进工作簿。不写主送、抄送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font
|
||||
|
||||
NOTICE_HEADERS = (
|
||||
"验收单号",
|
||||
"采购单号",
|
||||
"申请人",
|
||||
"轮次",
|
||||
"停留天数",
|
||||
"当前节点",
|
||||
"当前处理人",
|
||||
"通知身份",
|
||||
)
|
||||
NOTICE_FILE_NAME = "设备验收停留提醒.xlsx"
|
||||
|
||||
|
||||
def summary_message(lines: list[dict[str, Any]]) -> str:
|
||||
"""
|
||||
拼一名收件人的文字卡片。第一行写已逾期的验收单张数,不列单号。
|
||||
|
||||
核心逻辑:一张发送记录算一张。同一轮次的张数写在一起,顺序跟传入的明细一致。
|
||||
Args:
|
||||
lines: 已按发送记录去重的明细。每项含 threshold_days。
|
||||
Returns:
|
||||
卡片正文。没有明细时仍返回可发送的空汇总。
|
||||
"""
|
||||
counts: dict[int, int] = {}
|
||||
order: list[int] = []
|
||||
for line in lines:
|
||||
day = int(line.get("threshold_days") or 0)
|
||||
if day not in counts:
|
||||
order.append(day)
|
||||
counts[day] = 0
|
||||
counts[day] += 1
|
||||
detail = ",".join(f"超过 {day} 天 {counts[day]} 张" for day in order) or "无"
|
||||
return f"共 {len(lines)} 张验收单已逾期。\n{detail}。\n明细见下一条文件。"
|
||||
|
||||
|
||||
def build_notice_workbook(lines: list[dict[str, Any]]) -> bytes:
|
||||
"""
|
||||
生成这名收件人的验收停留明细。
|
||||
|
||||
核心逻辑:一行对应一张发送记录。通知身份写他为什么收到,不写主送或抄送。
|
||||
Args:
|
||||
lines: 验收单号、采购单号、申请人、轮次天数、停留天数、当前节点、当前处理人和通知身份。
|
||||
Returns:
|
||||
xlsx 字节。
|
||||
"""
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "停留提醒"
|
||||
sheet.append(list(NOTICE_HEADERS))
|
||||
for cell in sheet[1]:
|
||||
cell.font = Font(bold=True)
|
||||
for line in lines:
|
||||
dwell = line.get("dwell_days")
|
||||
sheet.append([
|
||||
_cell(line.get("acceptance_no")),
|
||||
_cell(line.get("purchase_order_no")),
|
||||
_cell(line.get("applicant")),
|
||||
f"超过 {int(line.get('threshold_days') or 0)} 天",
|
||||
"—" if dwell is None or dwell == "" else dwell,
|
||||
_cell(line.get("node_name")),
|
||||
_cell(line.get("handlers")),
|
||||
_cell(line.get("identity")),
|
||||
])
|
||||
sheet.freeze_panes = "A2"
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
output = BytesIO()
|
||||
workbook.save(output)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def _cell(value: Any) -> str:
|
||||
"""空值写成横线,避免 Excel 里出现空白列。"""
|
||||
text = str(value or "").strip()
|
||||
return text or "—"
|
||||
@@ -11,20 +11,31 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
|
||||
def due_tiers(dwell_days: int | None, thresholds: tuple[int, int, int, int]) -> list[int]:
|
||||
def due_tiers(
|
||||
dwell_days: int | None,
|
||||
thresholds: tuple[int, int, int, int],
|
||||
*,
|
||||
max_tier: int = 4,
|
||||
) -> list[int]:
|
||||
"""
|
||||
按累计天数给出已经跨过的档位。
|
||||
|
||||
核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。
|
||||
第 4 轮关闭时最高只到第 3 档,超过第 4 档天数也不产生总经理那一轮。
|
||||
Args:
|
||||
dwell_days: 签核自然日。没有计时起点时为空。
|
||||
thresholds: 四个天数,对应第 1 到第 4 档。
|
||||
max_tier: 允许的最高档,1 到 4。第 4 轮未启用时传 3。
|
||||
Returns:
|
||||
档位号 1 到 4 的列表。没有跨档时为空。
|
||||
档位号列表。没有跨档时为空。
|
||||
"""
|
||||
if dwell_days is None:
|
||||
return []
|
||||
return [index + 1 for index, day in enumerate(thresholds) if dwell_days > day]
|
||||
return [
|
||||
index + 1
|
||||
for index, day in enumerate(thresholds)
|
||||
if dwell_days > day and index + 1 <= max_tier
|
||||
]
|
||||
|
||||
|
||||
def make_person(
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/config_service.py
|
||||
|
||||
用途:读写设备验收预警配置:四档天数和三个固定岗位。
|
||||
用途:读写设备验收预警配置:四档天数、第 4 轮开关和三个固定岗位。
|
||||
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
|
||||
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
|
||||
没有配置行时按冻结默认值 30/37/44/51 返回,不把姓名写进代码。
|
||||
没有配置行时按冻结默认值 30/37/44/51 返回,第 4 轮默认关闭,不把姓名写进代码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +29,44 @@ _ROLE_FIELDS = (
|
||||
_MAX_DAY = 3650
|
||||
|
||||
|
||||
def is_round_4_enabled() -> bool:
|
||||
"""
|
||||
读取第 4 轮是否启用。
|
||||
|
||||
核心逻辑:没有配置行或字段为假时关闭。关闭后扫描不生成、发送不推出总经理那一轮。
|
||||
Returns:
|
||||
启用为 True。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
if row is None:
|
||||
return False
|
||||
return bool(row.round_4_enabled)
|
||||
|
||||
|
||||
def parse_round_4_enabled(raw: Any) -> bool:
|
||||
"""
|
||||
校验第 4 轮开关。
|
||||
|
||||
核心逻辑:缺省按关闭处理,避免旧请求误打开总经理提醒。传入值必须是布尔。
|
||||
Args:
|
||||
raw: 接口里的 round_4_enabled。缺省为 None。
|
||||
Returns:
|
||||
是否启用第 4 轮。
|
||||
|
||||
Raises:
|
||||
ValidationError: 传入了布尔以外的值。
|
||||
"""
|
||||
if raw is None:
|
||||
return False
|
||||
if not isinstance(raw, bool):
|
||||
raise ValidationError(
|
||||
"第 4 轮开关必须是是否启用",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||
details={"field": "round_4_enabled"},
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def reminder_days() -> tuple[int, int, int, int]:
|
||||
"""
|
||||
读取四档天数。
|
||||
@@ -65,12 +103,13 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
|
||||
Args:
|
||||
include_candidates: 为 True 时附带在职用户,供选人弹窗使用。
|
||||
Returns:
|
||||
days、三个岗位用户主键、已选用户、候选人和更新时间。
|
||||
days、第 4 轮开关、三个岗位用户主键、已选用户、候选人和更新时间。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
selected_ids = _selected_ids(row)
|
||||
return {
|
||||
"days": list(_days_of(row)),
|
||||
"round_4_enabled": False if row is None else bool(row.round_4_enabled),
|
||||
"buyer_manager_user_id": None if row is None else row.buyer_manager_user_id,
|
||||
"coo_user_id": None if row is None else row.coo_user_id,
|
||||
"executive_user_id": None if row is None else row.executive_user_id,
|
||||
@@ -82,12 +121,12 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
|
||||
|
||||
def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]:
|
||||
"""
|
||||
保存四档天数和三个岗位用户。
|
||||
保存四档天数、第 4 轮开关和三个岗位用户。
|
||||
|
||||
核心逻辑:天数必须逐档增大。岗位为空表示未选;有值时必须是已存在的系统用户。
|
||||
保存后只影响以后的预警,这里不改历史发送记录。
|
||||
核心逻辑:天数必须逐档增大。第 4 轮缺省为关闭。岗位为空表示未选;有值时必须是已存在的系统用户。
|
||||
保存后只影响以后的预警,这里不改历史发送记录。已有的待发送第 4 轮在发送时会被跳过。
|
||||
Args:
|
||||
payload: days 为四个整数;三个岗位字段为用户主键或空。
|
||||
payload: days 为四个整数;round_4_enabled 为布尔;三个岗位字段为用户主键或空。
|
||||
updated_by: 操作人的系统用户主键。
|
||||
Returns:
|
||||
与读取接口相同的配置,并带候选人。
|
||||
@@ -96,12 +135,14 @@ def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[
|
||||
ValidationError: 天数不合法,或岗位用户不存在。
|
||||
"""
|
||||
days = validate_reminder_days(payload.get("days"))
|
||||
round_4_enabled = parse_round_4_enabled(payload.get("round_4_enabled"))
|
||||
role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS}
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
if row is None:
|
||||
row = EquipmentAcceptanceSetting(id=_SETTING_ID)
|
||||
db.session.add(row)
|
||||
row.day_1, row.day_2, row.day_3, row.day_4 = days
|
||||
row.round_4_enabled = round_4_enabled
|
||||
row.buyer_manager_user_id = role_ids["buyer_manager_user_id"]
|
||||
row.coo_user_id = role_ids["coo_user_id"]
|
||||
row.executive_user_id = role_ids["executive_user_id"]
|
||||
|
||||
@@ -2,17 +2,20 @@
|
||||
backend/app/services/equipment_acceptance/send_record_service.py
|
||||
|
||||
用途:分页读取设备验收预警的发送记录。
|
||||
依赖:extensions.db、EquipmentAcceptanceSendRecord、utc_iso。
|
||||
逻辑:由 GET /api/equipment-acceptance/sends 调用。待发送由扫描写入,本模块只读取。
|
||||
依赖:extensions.db、EquipmentAcceptanceSendRecord、EquipmentAcceptanceSendFile、utc_iso。
|
||||
逻辑:由发送记录列表和 Excel 下载接口调用。列表按 send_record_ids 把 Excel 挂到对应行,不读文件字节。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import defer
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.core.response import utc_iso
|
||||
from app.extensions import db
|
||||
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
|
||||
from app.models.equipment_acceptance import EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord
|
||||
|
||||
|
||||
def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
|
||||
@@ -36,21 +39,122 @@ def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
file_rows = _file_rows_for([row.id for row in rows])
|
||||
return {
|
||||
"items": [send_record_payload(row) for row in rows],
|
||||
"items": [
|
||||
send_record_payload(row, _files_for_record(row.id, file_rows))
|
||||
for row in rows
|
||||
],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
}
|
||||
|
||||
|
||||
def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
|
||||
def list_send_files(*, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""
|
||||
列出最近留下的收件人 Excel,不含文件字节。
|
||||
|
||||
核心逻辑:按创建时间倒序。发送失败的文件也返回,方便对照当时准备发出的明细。
|
||||
Args:
|
||||
limit: 最多返回条数,上限 50。
|
||||
Returns:
|
||||
文件名、收件人、状态和发送时间。
|
||||
"""
|
||||
limit = min(50, max(1, limit))
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceSendFile)
|
||||
.order_by(EquipmentAcceptanceSendFile.created_at.desc(), EquipmentAcceptanceSendFile.id.desc())
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
return [send_file_payload(row) for row in rows]
|
||||
|
||||
|
||||
def get_send_file(file_id: int) -> EquipmentAcceptanceSendFile:
|
||||
"""
|
||||
取出一份已归档的 Excel。
|
||||
|
||||
Args:
|
||||
file_id: 文件行主键。
|
||||
Returns:
|
||||
含字节的文件行。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 记录不存在或没有文件内容。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSendFile, file_id)
|
||||
if row is None or not row.excel_file_data:
|
||||
raise NotFoundError("设备验收预警附件不存在")
|
||||
return row
|
||||
|
||||
|
||||
def send_file_payload(row: EquipmentAcceptanceSendFile) -> dict[str, Any]:
|
||||
"""列表用的文件摘要。不返回 Excel 字节。"""
|
||||
return {
|
||||
"id": row.id,
|
||||
"recipient_name": row.recipient_name,
|
||||
"excel_file_name": row.excel_file_name,
|
||||
"excel_file_size": row.excel_file_size,
|
||||
"status": row.status,
|
||||
"sent_at": utc_iso(row.sent_at),
|
||||
"created_at": utc_iso(row.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _file_rows_for(record_ids: list[int]) -> list[EquipmentAcceptanceSendFile]:
|
||||
"""
|
||||
取出可能挂在这些发送记录上的 Excel 摘要。
|
||||
|
||||
核心逻辑:延迟加载文件字节,只留下文件名和记录编号,避免列表把整份 xlsx 读进内存。
|
||||
Args:
|
||||
record_ids: 当前页发送记录主键。为空时不查。
|
||||
Returns:
|
||||
归档文件行,不含 excel_file_data。
|
||||
"""
|
||||
if not record_ids:
|
||||
return []
|
||||
return (
|
||||
db.session.query(EquipmentAcceptanceSendFile)
|
||||
.options(defer(EquipmentAcceptanceSendFile.excel_file_data))
|
||||
.order_by(EquipmentAcceptanceSendFile.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _files_for_record(record_id: int, file_rows: list[EquipmentAcceptanceSendFile]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
挑出包含这条发送记录的 Excel。
|
||||
|
||||
核心逻辑:send_record_ids 里有这条记录才挂上。没有文件名的不展示。
|
||||
Args:
|
||||
record_id: 发送记录主键。
|
||||
file_rows: 已去掉文件字节的归档行。
|
||||
Returns:
|
||||
下载按钮需要的 id 和文件名。
|
||||
"""
|
||||
found: list[dict[str, Any]] = []
|
||||
for row in file_rows:
|
||||
ids = {int(item) for item in list(row.send_record_ids or []) if item}
|
||||
if record_id in ids and row.excel_file_name:
|
||||
found.append({
|
||||
"id": row.id,
|
||||
"excel_file_name": row.excel_file_name,
|
||||
})
|
||||
return found
|
||||
|
||||
|
||||
def send_record_payload(
|
||||
row: EquipmentAcceptanceSendRecord,
|
||||
files: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把一条发送记录收成接口数据。
|
||||
|
||||
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。
|
||||
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。Excel 只带文件名和主键。
|
||||
Args:
|
||||
row: 本地发送记录。
|
||||
files: 这份记录出现过的归档 Excel。
|
||||
Returns:
|
||||
页签表格用的字段。
|
||||
"""
|
||||
@@ -68,4 +172,5 @@ def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
|
||||
"sent_at": utc_iso(row.sent_at),
|
||||
"error_message": row.error_message,
|
||||
"created_at": utc_iso(row.created_at),
|
||||
"files": files or [],
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
"""补齐设备验收预警的企微事件、第 4 轮开关和 Excel 归档。
|
||||
|
||||
Revision ID: eah8c9d0e1f2
|
||||
Revises: b7a2b2155155
|
||||
Create Date: 2026-10-13 14:30:00.000000
|
||||
|
||||
用途:把尚未提交的三步收成一次升级。已有库如果停在本版本,结构已经齐,不会重跑。
|
||||
依赖:b7a2b2155155、app_settings、equipment_acceptance_settings、users。
|
||||
逻辑:企微事件名单末尾补上 equipment_acceptance_warning;第 4 轮默认关闭;按收件人留下发送时的 Excel。
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
revision = "eah8c9d0e1f2"
|
||||
down_revision = "b7a2b2155155"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_KEY = "WECOM_NOTIFY_EVENTS"
|
||||
_EVENT = "equipment_acceptance_warning"
|
||||
|
||||
|
||||
def _split_events(raw: str | None) -> list[str]:
|
||||
"""按逗号拆开事件名单,去掉空白项。"""
|
||||
return [part.strip() for part in str(raw or "").split(",") if part.strip()]
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""补上企微事件、第 4 轮开关,并建立按收件人归档 Excel 的表。"""
|
||||
_append_wecom_event()
|
||||
op.add_column(
|
||||
"equipment_acceptance_settings",
|
||||
sa.Column("round_4_enabled", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
)
|
||||
op.create_table(
|
||||
"equipment_acceptance_send_files",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("recipient_user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("recipient_name", sa.String(length=200), nullable=True),
|
||||
sa.Column("excel_file_name", sa.String(length=255), nullable=True),
|
||||
sa.Column("excel_file_data", sa.LargeBinary(), nullable=True),
|
||||
sa.Column("excel_file_size", sa.Integer(), nullable=True),
|
||||
sa.Column("send_record_ids", sa.JSON(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"], ondelete="SET NULL"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_equipment_acceptance_send_files_created",
|
||||
"equipment_acceptance_send_files",
|
||||
["created_at"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""按相反顺序去掉 Excel 归档、第 4 轮开关和企微事件。"""
|
||||
op.drop_index("ix_equipment_acceptance_send_files_created", table_name="equipment_acceptance_send_files")
|
||||
op.drop_table("equipment_acceptance_send_files")
|
||||
op.drop_column("equipment_acceptance_settings", "round_4_enabled")
|
||||
_remove_wecom_event()
|
||||
|
||||
|
||||
def _append_wecom_event() -> None:
|
||||
"""已有事件名单时在末尾补上设备验收预警。没有这一行则不插入。"""
|
||||
bind = op.get_bind()
|
||||
if "app_settings" not in sa.inspect(bind).get_table_names():
|
||||
return
|
||||
row = bind.execute(text("SELECT value FROM app_settings WHERE key = :key"), {"key": _KEY}).fetchone()
|
||||
if row is None:
|
||||
return
|
||||
events = _split_events(row[0])
|
||||
if _EVENT in events:
|
||||
return
|
||||
events.append(_EVENT)
|
||||
bind.execute(
|
||||
text("UPDATE app_settings SET value = :value, updated_at = CURRENT_TIMESTAMP WHERE key = :key"),
|
||||
{"key": _KEY, "value": ",".join(events)},
|
||||
)
|
||||
|
||||
|
||||
def _remove_wecom_event() -> None:
|
||||
"""从已保存的企微事件名单里去掉设备验收预警。没有这一行时不处理。"""
|
||||
bind = op.get_bind()
|
||||
if "app_settings" not in sa.inspect(bind).get_table_names():
|
||||
return
|
||||
row = bind.execute(text("SELECT value FROM app_settings WHERE key = :key"), {"key": _KEY}).fetchone()
|
||||
if row is None:
|
||||
return
|
||||
events = [part for part in _split_events(row[0]) if part != _EVENT]
|
||||
bind.execute(
|
||||
text("UPDATE app_settings SET value = :value, updated_at = CURRENT_TIMESTAMP WHERE key = :key"),
|
||||
{"key": _KEY, "value": ",".join(events)},
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
tests/test_equipment_acceptance_alert_notice.py
|
||||
|
||||
用途:锁定设备验收企微汇总文案和 Excel 列。
|
||||
依赖:alert_notice、openpyxl。
|
||||
逻辑:不连数据库,不发企业微信。卡片只写张数。工作簿含申请人,不写主送。
|
||||
"""
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.alert_notice import (
|
||||
NOTICE_HEADERS,
|
||||
build_notice_workbook,
|
||||
summary_message,
|
||||
)
|
||||
|
||||
|
||||
def test_summary_counts_rounds_without_listing_orders():
|
||||
"""第一行写已逾期张数。正文不出现验收单号,也不写主送。"""
|
||||
text = summary_message([
|
||||
{"threshold_days": 30},
|
||||
{"threshold_days": 30},
|
||||
{"threshold_days": 37},
|
||||
])
|
||||
assert text == "共 3 张验收单已逾期。\n超过 30 天 2 张,超过 37 天 1 张。\n明细见下一条文件。"
|
||||
assert "主送" not in text
|
||||
assert "20260210" not in text
|
||||
|
||||
|
||||
def test_workbook_includes_applicant_and_identity():
|
||||
"""Excel 列与原型一致。通知身份保留角色名,停留天数为空时写横线。"""
|
||||
data = build_notice_workbook([{
|
||||
"acceptance_no": "20260210000001",
|
||||
"purchase_order_no": "1111",
|
||||
"applicant": "孙浩",
|
||||
"threshold_days": 30,
|
||||
"dwell_days": None,
|
||||
"node_name": "使用部门担当",
|
||||
"handlers": "吴敏",
|
||||
"identity": "直接主管",
|
||||
}])
|
||||
sheet = load_workbook(BytesIO(data)).active
|
||||
assert [cell.value for cell in sheet[1]] == list(NOTICE_HEADERS)
|
||||
assert [cell.value for cell in sheet[2]] == [
|
||||
"20260210000001",
|
||||
"1111",
|
||||
"孙浩",
|
||||
"超过 30 天",
|
||||
"—",
|
||||
"使用部门担当",
|
||||
"吴敏",
|
||||
"直接主管",
|
||||
]
|
||||
@@ -30,6 +30,7 @@ def test_due_tiers_use_strictly_greater_than_threshold():
|
||||
assert due_tiers(31, _DAYS) == [1]
|
||||
assert due_tiers(51, _DAYS) == [1, 2, 3]
|
||||
assert due_tiers(52, _DAYS) == [1, 2, 3, 4]
|
||||
assert due_tiers(52, _DAYS, max_tier=3) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_tier_one_keeps_missing_supervisor_as_failure():
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
"""
|
||||
tests/test_equipment_acceptance_config.py
|
||||
|
||||
用途:锁定设备验收预警四档天数的保存前校验。
|
||||
依赖:config_service.validate_reminder_days、ValidationError。
|
||||
逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。
|
||||
用途:锁定设备验收预警四档天数和第 4 轮开关的保存前校验。
|
||||
依赖:config_service.validate_reminder_days、parse_round_4_enabled、ValidationError。
|
||||
逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。第 4 轮缺省关闭。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.equipment_acceptance.config_service import validate_reminder_days
|
||||
from app.services.equipment_acceptance.config_service import parse_round_4_enabled, validate_reminder_days
|
||||
|
||||
|
||||
def test_default_reminder_days_pass():
|
||||
@@ -30,3 +30,13 @@ def test_days_reject_bool_and_wrong_length():
|
||||
validate_reminder_days([True, 37, 44, 51])
|
||||
with pytest.raises(ValidationError):
|
||||
validate_reminder_days([30, 37, 44])
|
||||
|
||||
|
||||
def test_round_4_defaults_off_and_rejects_non_bool():
|
||||
"""未传开关时按关闭处理。数字 1 不能当成启用,避免误通知总经理。"""
|
||||
assert parse_round_4_enabled(None) is False
|
||||
assert parse_round_4_enabled(False) is False
|
||||
assert parse_round_4_enabled(True) is True
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_round_4_enabled(1)
|
||||
assert caught.value.code == "EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID"
|
||||
Reference in new issue
Block a user