From b8cc0cbe77c1059537a10d5928c00d41de77593a Mon Sep 17 00:00:00 2001 From: sophie Date: Tue, 13 Oct 2026 08:45:24 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E8=AE=BE=E5=A4=87=E9=AA=8C=E6=94=B6?= =?UTF-8?q?=E9=A2=84=E8=AD=A6=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/equipment_acceptance/__init__.py | 28 +- backend/app/models/__init__.py | 2 + backend/app/models/equipment_acceptance.py | 29 +- .../equipment_acceptance/alert_notice.py | 90 ++++++ .../equipment_acceptance/alert_plan.py | 17 +- .../equipment_acceptance/alert_service.py | 273 ++++++++++++++--- .../equipment_acceptance/config_service.py | 55 +++- .../send_record_service.py | 117 +++++++- ...1f2_add_equipment_acceptance_send_files.py | 97 ++++++ .../test_equipment_acceptance_alert_notice.py | 58 ++++ .../test_equipment_acceptance_alert_plan.py | 1 + .../tests/test_equipment_acceptance_config.py | 18 +- docs/demand.md | 2 +- .../config-redesign-preview.html | 14 +- .../equipment-acceptance-warning/demand.md | 4 +- .../send-redesign-preview.html | 279 ++++++++++++++++++ .../equipment-acceptance-warning/technical.md | 6 +- docs/funclist.md | 6 +- .../api/equipment-acceptance.api.ts | 40 ++- .../views/EquipmentAcceptanceConfigPage.vue | 273 ++++++++++------- .../views/EquipmentAcceptanceSendsPage.vue | 106 ++++++- frontend/src/locales/en/admin.json | 19 +- frontend/src/locales/th/admin.json | 19 +- frontend/src/locales/zh-CN/admin.json | 19 +- frontend/src/locales/zh-TW/admin.json | 19 +- 25 files changed, 1398 insertions(+), 193 deletions(-) create mode 100644 backend/app/services/equipment_acceptance/alert_notice.py create mode 100644 backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py create mode 100644 backend/tests/test_equipment_acceptance_alert_notice.py create mode 100644 docs/features/equipment-acceptance-warning/send-redesign-preview.html diff --git a/backend/app/api/equipment_acceptance/__init__.py b/backend/app/api/equipment_acceptance/__init__.py index 61611cce..e108908b 100644 --- a/backend/app/api/equipment_acceptance/__init__.py +++ b/backend/app/api/equipment_acceptance/__init__.py @@ -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//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(): """分页查看发送记录。扫描写入后这里才有行。""" diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index e1704f81..34bd23d1 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/equipment_acceptance.py b/backend/app/models/equipment_acceptance.py index fdf90bd8..1483797f 100644 --- a/backend/app/models/equipment_acceptance.py +++ b/backend/app/models/equipment_acceptance.py @@ -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) diff --git a/backend/app/services/equipment_acceptance/alert_notice.py b/backend/app/services/equipment_acceptance/alert_notice.py new file mode 100644 index 00000000..7fa232ea --- /dev/null +++ b/backend/app/services/equipment_acceptance/alert_notice.py @@ -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 "—" diff --git a/backend/app/services/equipment_acceptance/alert_plan.py b/backend/app/services/equipment_acceptance/alert_plan.py index 9f7122f9..26655928 100644 --- a/backend/app/services/equipment_acceptance/alert_plan.py +++ b/backend/app/services/equipment_acceptance/alert_plan.py @@ -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( diff --git a/backend/app/services/equipment_acceptance/alert_service.py b/backend/app/services/equipment_acceptance/alert_service.py index fc86e93c..f0f521b5 100644 --- a/backend/app/services/equipment_acceptance/alert_service.py +++ b/backend/app/services/equipment_acceptance/alert_service.py @@ -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: diff --git a/backend/app/services/equipment_acceptance/config_service.py b/backend/app/services/equipment_acceptance/config_service.py index 021fdd8c..f85bf0ba 100644 --- a/backend/app/services/equipment_acceptance/config_service.py +++ b/backend/app/services/equipment_acceptance/config_service.py @@ -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"] diff --git a/backend/app/services/equipment_acceptance/send_record_service.py b/backend/app/services/equipment_acceptance/send_record_service.py index d9b7d7ce..57f41de6 100644 --- a/backend/app/services/equipment_acceptance/send_record_service.py +++ b/backend/app/services/equipment_acceptance/send_record_service.py @@ -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 [], } diff --git a/backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py b/backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py new file mode 100644 index 00000000..a7e2c7df --- /dev/null +++ b/backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py @@ -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)}, + ) diff --git a/backend/tests/test_equipment_acceptance_alert_notice.py b/backend/tests/test_equipment_acceptance_alert_notice.py new file mode 100644 index 00000000..136b7680 --- /dev/null +++ b/backend/tests/test_equipment_acceptance_alert_notice.py @@ -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 天", + "—", + "使用部门担当", + "吴敏", + "直接主管", + ] diff --git a/backend/tests/test_equipment_acceptance_alert_plan.py b/backend/tests/test_equipment_acceptance_alert_plan.py index ee3fd168..26fa2dad 100644 --- a/backend/tests/test_equipment_acceptance_alert_plan.py +++ b/backend/tests/test_equipment_acceptance_alert_plan.py @@ -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(): diff --git a/backend/tests/test_equipment_acceptance_config.py b/backend/tests/test_equipment_acceptance_config.py index 8e9df48c..19f9052c 100644 --- a/backend/tests/test_equipment_acceptance_config.py +++ b/backend/tests/test_equipment_acceptance_config.py @@ -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" diff --git a/docs/demand.md b/docs/demand.md index 034a54a8..10c7d8eb 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -22,7 +22,7 @@ ## 设备验收预警(2026-09) - 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。 -- 超过 30/37/44/51 天各发一次企业微信。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人汇总。 +- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。 - 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。 ## 合同付款预警 Agent(2026-08) diff --git a/docs/features/equipment-acceptance-warning/config-redesign-preview.html b/docs/features/equipment-acceptance-warning/config-redesign-preview.html index 3ca7dc9d..f4b3a74a 100644 --- a/docs/features/equipment-acceptance-warning/config-redesign-preview.html +++ b/docs/features/equipment-acceptance-warning/config-redesign-preview.html @@ -76,6 +76,9 @@ } .when { display: flex; flex-direction: column; gap: 8px; } .when b { font-size: 12px; color: var(--muted); font-weight: 700; } + .switch { display: flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 700; } + .when small { color: var(--muted); font-size: 12px; } + .round.off .people { opacity: 0.45; } .day { display: flex; align-items: center; @@ -267,10 +270,12 @@ -
+
第 4 轮 + + 默认关闭,不通知总经理
@@ -305,7 +310,12 @@
-

效果图,尚未接到现有页面。

+

效果图。第 4 轮开关已接到现有配置页,默认关闭。

+ diff --git a/docs/features/equipment-acceptance-warning/demand.md b/docs/features/equipment-acceptance-warning/demand.md index bcb4c1f7..45646869 100644 --- a/docs/features/equipment-acceptance-warning/demand.md +++ b/docs/features/equipment-acceptance-warning/demand.md @@ -60,6 +60,8 @@ | 超过 44 天 | COO | 采购经副理 | | 超过 51 天 | 总经理 | COO、采购经副理 | +第 4 轮在配置里单独开关,默认关闭。关闭时不生成、也不发送总经理这一轮。打开后,下一次扫描才按超过第 4 档的天数产生待发送。前 3 轮不受这个开关影响。 + 人员解析: - 担当、直接主管、经副理取**当前节点处理人**及其上级,不固定成「使用部门担当」本人。 @@ -70,7 +72,7 @@ ## 6. 推送 -已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总。渠道只有企业微信。 +已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总卡片,并紧跟一份只含该收件人明细的 Excel。这份 Excel 按收件人归档,挂在发送记录表的 Excel 附件列上,点文件名再下载。卡片不逐条列出验收单,也不区分主送和抄送。渠道只有企业微信。 ## 7. 数据来源 diff --git a/docs/features/equipment-acceptance-warning/send-redesign-preview.html b/docs/features/equipment-acceptance-warning/send-redesign-preview.html new file mode 100644 index 00000000..b3ad67cb --- /dev/null +++ b/docs/features/equipment-acceptance-warning/send-redesign-preview.html @@ -0,0 +1,279 @@ + + + + + 设备验收预警 · 发送效果图 + + + +
+

设备验收预警 · 发送效果图

+

效果图,尚未接到现有页面。同一个人只收一条汇总卡片,明细在下一条 Excel。不再区分主送和抄送。

+ +
+
+
+

sophie 收到的企业微信

+

她这一轮有 18 张单,卡片里不逐条列出。

+
+
+
+
设备验收预警
+
+

19:52

+
+

设备验收停留提醒

+

共 18 张验收单。 +超过 30 天 12 张,超过 37 天 4 张,超过 44 天 2 张。 +明细见下一条文件。

+
查看详情›
+
+
+
XLS
+
+ 设备验收停留提醒.xlsx + 28.4 KB +
+
+
+
+
+
+ +
+
+

附件里的前 8 行

+

只含 sophie 本人要看的单。通知身份说明她为什么会收到,不再写主送、抄送。

+
+
+ + + + + + + + + + + + + + + + + + + + + + + +
验收单号采购单号申请人轮次停留天数当前节点当前处理人通知身份
202602100000011111孙浩超过 30 天31使用部门担当吴敏直接主管
20260211000008CG-0881李文超过 30 天33品质担当林可直接主管
20260212000015CG-0902周洋超过 30 天36公用主管sophie当前处理人
20260213000022CG-0910孙浩超过 37 天40设备管理部周宁采购经副理
20260214000031CG-0933陈敏超过 37 天41品质经理何倩采购经副理
20260215000040CG-0948刘洋超过 44 天46COO陈立采购经副理
20260216000052CG-0961王磊超过 30 天32使用部门经理赵凯直接主管
20260217000060CG-0977孙浩超过 30 天35固定资产管理人孙浩采购担当
+
+

文件内共 18 行。同一张单若第 1 轮和第 2 轮都还没发过,会各占一行。停留天数是发送当时的天数。

+
+
+ +
+
+ 停留情况 + 发送记录 + 预警配置 +
+
+

每日扫描生成待发送。每周五 18:00 按人汇总,每人一条卡片加一份 Excel。这里仍是一条记录对应一张单的一轮。

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
验收单号采购单号轮次收件人结果发送时间
202602100000011111超过 30 天吴敏、sophie、孙浩已发送2026-10-12 18:55:18
20260212000015CG-0902超过 37 天孙经理、COO、赵琴待发送—
20260215000040CG-0948超过 44 天COO、赵琴发送失败—
+
+

页面上的「导出 Excel」是当前列表里的全部记录。个人在企业微信里收到的文件只含他自己的行。

+
+
+ + diff --git a/docs/features/equipment-acceptance-warning/technical.md b/docs/features/equipment-acceptance-warning/technical.md index bbda39fe..1e6f4622 100644 --- a/docs/features/equipment-acceptance-warning/technical.md +++ b/docs/features/equipment-acceptance-warning/technical.md @@ -412,7 +412,7 @@ LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid; 页面入口与合同付款预警相同:迁移写入内置 Chat Agent,`agent_code=equipment_acceptance`,`conversation_mode=task_chat`。对话页按该编码替换消息列表和输入框,页签是停留情况、发送记录和预警配置。普通用户要在用户管理里授予该 Agent 后才看得到。 -`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。 +`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`round_4_enabled` 默认关闭,关闭时扫描不生成第 4 轮,发送也会跳过已经待发送的第 4 轮。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。 ## 9. 扫描与发送 @@ -423,11 +423,11 @@ LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid; - 超过第 1 档:主送当前处理人,抄送其 `employee.SUPERIOR` 和申请人。 - 超过第 2 档:主送各处理人部门的经副理,抄送配置里的 COO 和采购经副理。 - 超过第 3 档:主送 COO,抄送采购经副理。 -- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。 +- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。配置里的第 4 轮开关默认关闭,关闭时这一档不产生、也不发送。 人员 ID 先对 `eteams.dbo.employee`,再用 `JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。矩阵 `relate_id` 和 E10 人员 ID 都不是企微 userid。没有工号、对不上用户、没绑企微、没有主管或经副理、三个岗位没选,都记在该席位上,不改发给别人。至少有一名可发的人时状态是待发送;一个都没有则整档失败。 -每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号合并成一条文本卡片,标题「设备验收停留提醒」,事件 `equipment_acceptance_warning`。卡片过长时先留 12 行,其余写成「另有 N 条」。发送成功改为已发送。有人失败则整档改为失败,并附上「企业微信发送失败」;下次扫描会按当前处理人重算并回到待发送。已发出的企业微信不撤回。 +每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号先收一条文本卡片,标题「设备验收停留提醒」,正文先写共多少张验收单已逾期,再写各轮次数量,事件 `equipment_acceptance_warning`。紧跟着一条文件消息《设备验收停留提醒.xlsx》,列是验收单号、采购单号、申请人、轮次、停留天数、当前节点、当前处理人、通知身份。卡片不写主送、抄送,也不逐条列出验收单。卡片和文件都成功才改为已发送。任一失败则整档改为失败,并写上卡片或附件的原因;下次扫描会按当前处理人重算并回到待发送。每位收件人的 Excel 写入 `equipment_acceptance_send_files`,并记下对应的发送记录。发送失败也保留。发送记录表用 Excel 附件列下载,同一行可有多份。已发出的企业微信不撤回。 停表(归档、退回、撤回、作废、无法验收,以及强制结束)时,待发送和解析失败且还没 `sent_at` 的行改为已取消。 diff --git a/docs/funclist.md b/docs/funclist.md index c3518059..27407db2 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -48,9 +48,9 @@ | 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 | | 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 验收单、流程状态、当前节点和操作人。按 `sfkyzcys`、`sfzfth`、`flowstatus` 3/4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 | | 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。有权限的用户看列表和详情,同步按钮只给平台管理员。 | -| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,采购经副理、COO、总经理选择系统用户。发送时刻不在此页,以后由排程 Cron 配置,默认每周五 18:00。 | -| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果和发送时间。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 | -| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人汇总一条企业微信。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 | +| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:00。 | +| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 | +| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人发送一条汇总卡片和一份 Excel 明细。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 | ## 知识库同步状态校验 diff --git a/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts index f1c2006c..70974f3a 100644 --- a/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts +++ b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts @@ -4,9 +4,9 @@ * 依赖:统一 requestJson;后端 /api/equipment-acceptance。 * 逻辑:Chat 作业面调用。同步只读 E10。配置只保存天数和系统用户,不保存发送时刻。 * 保存配置自行声明 Content-Type: application/json,供 Flask get_json 解析。 - * 发送记录只读已落库的行,扫描尚未写入时列表为空。 + * 发送记录只读已落库的行。每位收件人的 Excel 可再下载。 */ -import { requestJson } from '@/shared/api/client'; +import { requestBlob, requestJson } from '@/shared/api/client'; export interface EquipmentAcceptanceNode { node_id?: string | null; @@ -150,6 +150,7 @@ export interface EquipmentAcceptanceSendRecord { sent_at?: string | null; error_message?: string | null; created_at?: string | null; + files?: Array<{ id: number; excel_file_name?: string | null }>; } export interface EquipmentAcceptanceSendListResponse { @@ -166,6 +167,33 @@ export interface EquipmentAcceptanceSendListResponse { * @param params.pageSize - 每页条数 * @returns 当前页记录和总数 */ +export interface EquipmentAcceptanceSendFile { + id: number; + recipient_name?: string | null; + excel_file_name?: string | null; + excel_file_size?: number | null; + status: string; + sent_at?: string | null; + created_at?: string | null; +} + +/** + * 列出最近按收件人归档的 Excel。不含文件内容。 + * @returns 文件摘要 + */ +export function listEquipmentAcceptanceSendFiles() { + return requestJson<{ items: EquipmentAcceptanceSendFile[] }>('/api/equipment-acceptance/send-files'); +} + +/** + * 下载一份当时发给收件人的 Excel。 + * @param fileId - 归档文件主键 + * @returns 文件字节和文件名 + */ +export function downloadEquipmentAcceptanceSendFile(fileId: number) { + return requestBlob(`/api/equipment-acceptance/send-files/${fileId}/excel`); +} + export function listEquipmentAcceptanceSends(params?: { page?: number; pageSize?: number }) { const search = new URLSearchParams(); if (params?.page) search.set('page', String(params.page)); @@ -185,6 +213,7 @@ export interface EquipmentAcceptanceConfigUser { export interface EquipmentAcceptanceConfig { days: number[]; + round_4_enabled?: boolean; buyer_manager_user_id?: number | null; coo_user_id?: number | null; executive_user_id?: number | null; @@ -202,9 +231,10 @@ export function getEquipmentAcceptanceConfig() { } /** - * 保存四档天数和三个岗位的系统用户。仅平台管理员。 - * 核心逻辑:岗位传用户主键或 null,不传姓名。 + * 保存四档天数、第 4 轮开关和三个岗位的系统用户。仅平台管理员。 + * 核心逻辑:岗位传用户主键或 null,不传姓名。第 4 轮关闭时不通知总经理。 * @param payload.days - 四个逐档增大的天数 + * @param payload.round4Enabled - 是否启用第 4 轮 * @param payload.buyerManagerUserId - 采购经副理 * @param payload.cooUserId - COO * @param payload.executiveUserId - 总经理对应岗位 @@ -212,6 +242,7 @@ export function getEquipmentAcceptanceConfig() { */ export function saveEquipmentAcceptanceConfig(payload: { days: number[]; + round4Enabled: boolean; buyerManagerUserId: number | null; cooUserId: number | null; executiveUserId: number | null; @@ -221,6 +252,7 @@ export function saveEquipmentAcceptanceConfig(payload: { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ days: payload.days, + round_4_enabled: payload.round4Enabled, buyer_manager_user_id: payload.buyerManagerUserId, coo_user_id: payload.cooUserId, executive_user_id: payload.executiveUserId, diff --git a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue index 3dc5e222..e78af866 100644 --- a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue +++ b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue @@ -1,8 +1,8 @@