""" backend/app/services/equipment_acceptance/alert_service.py 用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。 依赖:同步服务、E10 人员目录、E8 人员矩阵、alert_plan、alert_notice、发送记录模型、企微通知。 逻辑:扫描先同步 E10 和 E8,再按停留天数跨档。第 1 档主送使用部门担当,不按当前未办人。 第 4 轮关闭时不生成、也不发送总经理那一轮。 周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。 """ 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, make_person, resolve_account, resolve_configured_user, resolve_direct_wecom, ) 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__) _SETTING_ID = 1 _EVENT = "equipment_acceptance_warning" _UNSENT = ("pending", "failed") def generate_alerts() -> dict[str, Any]: """ 同步两个来源后生成或更新待发送记录。 核心逻辑:先拉最新快照,再按使用部门担当解析收件人。本函数不发企业微信。 Returns: sync 摘要,以及 created、updated、cancelled 条数。 """ from app.services.equipment_acceptance.sync_service import sync_acceptance_snapshots sync_result = sync_acceptance_snapshots() summary = refresh_pending_alerts() # 同步提交时已经取消的未发送,刷新阶段不会再数到,这里加回去。 summary["cancelled"] += int(sync_result.get("cancelled") or 0) summary["sync"] = sync_result return summary def refresh_pending_alerts( *, directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None = None, ) -> dict[str, Any]: """ 按本地快照刷新待发送记录。 核心逻辑:计时中的单据跨过哪一档就保留哪一档。第 4 轮关闭时最高只到第 3 档。已发送和已取消不改。 未计时或已停表的单据,把还没发出的记录改成已取消。 Args: directory: 测试注入的人员目录和经副理。空则查询 E10。 Returns: created、updated、cancelled。 """ orders = db.session.query(EquipmentAcceptanceOrder).all() e10_people, e10_deputies, e8_people, e8_matrix, e8_ok = _directories(orders, directory) users_by_job = _users_by_job(_job_numbers(orders, e10_people, e10_deputies, e8_people)) users_by_wecom = _users_by_wecom(_wecom_ids(e8_matrix)) 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() if row.order_id is not None } created = 0 updated = 0 cancelled = 0 for order in orders: if order.monitor_status != WATCHING: cancelled += cancel_unsent(order.id) continue if (order.oa_system or "e10") == "e8" and not e8_ok: continue for draft in _drafts( order, e10_people, e10_deputies, e8_people, e8_matrix, users_by_job, users_by_wecom, 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 if current is None: current = EquipmentAcceptanceSendRecord( order_id=order.id, tier=draft["tier"], threshold_days=draft["threshold_days"], status=draft["status"], created_at=datetime.utcnow(), ) db.session.add(current) existing[(order.id, draft["tier"])] = current created += 1 else: updated += 1 _apply_draft(current, order, draft) db.session.commit() return {"created": created, "updated": updated, "cancelled": cancelled} def cancel_unsent(order_id: int) -> int: """ 取消一张验收单上还没发出的预警。 核心逻辑:待发送和解析失败都还没出企业微信,停表后改成已取消。已发送的保留。 Args: order_id: 本地验收单主键。 Returns: 改成已取消的行数。 """ rows = ( db.session.query(EquipmentAcceptanceSendRecord) .filter( EquipmentAcceptanceSendRecord.order_id == order_id, EquipmentAcceptanceSendRecord.status.in_(_UNSENT), EquipmentAcceptanceSendRecord.sent_at.is_(None), ) .all() ) for row in rows: row.status = "cancelled" return len(rows) 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, 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: for person in list(row.recipients_json or []): wecom_id = str(person.get("wecom_userid") or "").strip() if person.get("error") or not wecom_id: continue buckets.setdefault(wecom_id, []).append((row, person)) agent = db.session.query(Agent).filter_by(agent_code="equipment_acceptance", is_active=True).first() 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_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=summary_message(lines), jump_path=jump_path, jump_params=jump_params, wecom_userid=wecom_id, ) except Exception: _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() for row in rows: ready = { str(person.get("wecom_userid") or "").strip() for person in list(row.recipients_json or []) if person.get("wecom_userid") and not person.get("error") } ready.discard("") if not ready: continue 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, ";".join(dict.fromkeys(hit))) records_failed += 1 elif ready <= sent_ids: row.status = "sent" row.sent_at = now records_sent += 1 db.session.commit() return { "sent": len(sent_ids), "failed": len(failed_reasons), "records_sent": records_sent, "records_failed": records_failed, } def _drafts( order: EquipmentAcceptanceOrder, e10_people: dict[int, dict[str, Any]], e10_deputies: dict[str, list[dict[str, Any]]], e8_people: dict[int, dict[str, Any]], e8_matrix: dict[str, dict[str, Any]], users_by_job: dict[str, User], users_by_wecom: dict[str, User], roles: dict[str, User | None], thresholds: tuple[int, int, int, int], *, max_tier: int = 4, ) -> list[dict[str, Any]]: """按使用部门担当展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。""" due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier) if not due: return [] owner, supervisors, deputy_people = _owner_seats( order, e10_people, e10_deputies, e8_people, e8_matrix, users_by_job, users_by_wecom ) applicant = _applicant(order, e10_people if (order.oa_system or "e10") != "e8" else e8_people, users_by_job) drafts: list[dict[str, Any]] = [] if 1 in due: drafts.append(assemble_tier( tier=1, threshold_days=thresholds[0], to_people=[owner], cc_people=[*supervisors, applicant], )) if 2 in due: drafts.append(assemble_tier( tier=2, threshold_days=thresholds[1], to_people=deputy_people, cc_people=[ resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"), resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"), ], )) if 3 in due: drafts.append(assemble_tier( tier=3, threshold_days=thresholds[2], to_people=[resolve_configured_user(slot="to", label="COO", user=roles.get("coo"), missing_error="未配置COO")], cc_people=[resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理")], )) if 4 in due: drafts.append(assemble_tier( tier=4, threshold_days=thresholds[3], to_people=[resolve_configured_user(slot="to", label="总经理", user=roles.get("executive"), missing_error="未配置总经理")], cc_people=[ resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"), resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"), ], )) return drafts def _owner_seats( order: EquipmentAcceptanceOrder, e10_people: dict[int, dict[str, Any]], e10_deputies: dict[str, list[dict[str, Any]]], e8_people: dict[int, dict[str, Any]], e8_matrix: dict[str, dict[str, Any]], users_by_job: dict[str, User], users_by_wecom: dict[str, User], ) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: """第 1 档主送和其上级。E8 的上级来自部门矩阵,E10 来自 employee 和审批矩阵。""" if (order.oa_system or "e10") == "e8": return _e8_owner_seats(order, e8_people, e8_matrix, users_by_job, users_by_wecom) return _e10_owner_seats(order, e10_people, e10_deputies, users_by_job) def _e10_owner_seats( order: EquipmentAcceptanceOrder, people: dict[int, dict[str, Any]], deputies: dict[str, list[dict[str, Any]]], users_by_job: dict[str, User], ) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: """E10 只取 sybmdd 这一名使用部门担当,不展开当前节点上的其他人。""" if not order.owner_oa_id: return ( make_person(slot="to", label="使用部门担当", error="没有使用部门担当"), [make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")], [make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")], ) fact = people.get(order.owner_oa_id) or {} name = fact.get("name") or order.owner_name job_num = fact.get("job_num") or order.owner_job_num shown = name or "使用部门担当" owner = resolve_account( slot="to", label="使用部门担当", name=name, job_num=job_num, user=users_by_job.get(str(job_num or "")), missing_job_error=f"{shown}没有工号", oa_employee_id=order.owner_oa_id, ) superior_id = fact.get("superior_id") if superior_id is None: supervisors = [make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管")] else: supervisors = [resolve_account( slot="cc", label="直接主管", name=fact.get("superior_name"), job_num=fact.get("superior_job_num"), user=users_by_job.get(str(fact.get("superior_job_num") or "")), missing_job_error=f"{shown}的直接主管没有工号", oa_employee_id=superior_id, )] found = deputies.get(str(fact.get("department_id") or ""), []) if not found: deputy_people = [make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理")] else: deputy_people = [ resolve_account( slot="to", label="经副理", name=item.get("name"), job_num=item.get("job_num"), user=users_by_job.get(str(item.get("job_num") or "")), missing_job_error=f"{shown}的经副理没有工号", oa_employee_id=item.get("oa_id"), ) for item in found ] return owner, supervisors, deputy_people def _e8_owner_seats( order: EquipmentAcceptanceOrder, people: dict[int, dict[str, Any]], matrix: dict[str, dict[str, Any]], users_by_job: dict[str, User], users_by_wecom: dict[str, User], ) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: """E8 的直接主管是矩阵 zz,经副理是 jfl。不是一行就不发这两个席位。""" if not order.owner_oa_id: return ( make_person(slot="to", label="使用部门担当", error="没有使用部门担当"), [make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")], [make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")], ) fact = people.get(order.owner_oa_id) or {} name = fact.get("name") or order.owner_name job_num = fact.get("job_num") or order.owner_job_num shown = name or "使用部门担当" owner = resolve_account( slot="to", label="使用部门担当", name=name, job_num=job_num, user=users_by_job.get(str(job_num or "")), missing_job_error=f"{shown}没有工号", oa_employee_id=order.owner_oa_id, ) seat = matrix.get(str(fact.get("department_id") or "")) if not seat or not seat.get("ok"): return ( owner, [make_person(slot="cc", label="直接主管", name=name, error=f"{shown}的部门矩阵不是一行")], [make_person(slot="to", label="经副理", name=name, error=f"{shown}的部门矩阵不是一行")], ) return owner, [_matrix_seat(seat.get("zz"), "cc", "直接主管", shown, users_by_wecom)], [ _matrix_seat(seat.get("jfl"), "to", "经副理", shown, users_by_wecom) ] def _matrix_seat( seat: dict[str, Any] | None, slot: str, label: str, owner_name: str, users_by_wecom: dict[str, User], ) -> dict[str, Any]: """矩阵人员按企微 userid 发送。空席位记失败。""" if not seat: return make_person(slot=slot, label=label, name=owner_name, error=f"{owner_name}没有{label}") wecom = str(seat.get("wecom_userid") or "") return resolve_direct_wecom( slot=slot, label=label, name=seat.get("name"), wecom_userid=wecom, user=users_by_wecom.get(wecom), oa_employee_id=seat.get("oa_id"), missing_error=f"{owner_name}没有{label}", ) def _applicant( order: EquipmentAcceptanceOrder, people: dict[int, dict[str, Any]], users_by_job: dict[str, User], ) -> dict[str, Any]: """采购担当是申请人。E8 用工号 workcode,E10 用工号 JOB_NUM,都对系统用户。""" fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None job_num = (fact or {}).get("job_num") or order.applicant_job_num return resolve_account( slot="cc", label="采购担当", name=(fact or {}).get("name") or order.applicant_name, job_num=job_num, user=users_by_job.get(str(job_num or "")), missing_job_error="没有申请人工号", oa_employee_id=order.applicant_oa_id, ) def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None: """把草稿写进未发送的记录。不改创建时间,也不填发送时间。""" row.acceptance_no = order.acceptance_no row.purchase_order_no = order.purchase_order_no row.threshold_days = draft["threshold_days"] row.to_text = draft["to_text"] row.cc_text = draft["cc_text"] row.recipients_json = draft["recipients"] row.status = draft["status"] row.error_message = draft["error_message"] def _directories( orders: list[EquipmentAcceptanceOrder], directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None, ) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]], dict[int, dict[str, Any]], dict[str, dict[str, Any]], bool]: """分开取 E10 和 E8 的人员。E8 查询失败时本轮不改写 E8 待发送。""" if directory is not None: return directory[0], directory[1], {}, {}, True e10_people, e10_deputies = _load_e10_directory(orders) try: e8_people, e8_matrix = _load_e8_directory(orders) return e10_people, e10_deputies, e8_people, e8_matrix, True except Exception as exc: _LOGGER.warning("equipment acceptance e8 directory skipped error=%s", type(exc).__name__) return e10_people, e10_deputies, {}, {}, False def _load_e10_directory( orders: list[EquipmentAcceptanceOrder], ) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]: """向 E10 要使用部门担当和申请人的主管、部门、经副理。不传入 E8 人员 ID。""" from app.services.equipment_acceptance.oa_repository import fetch_alert_directory ids: set[int] = set() for order in orders: if (order.oa_system or "e10") == "e8" or order.monitor_status != WATCHING: continue if order.owner_oa_id: ids.add(order.owner_oa_id) if order.applicant_oa_id: ids.add(order.applicant_oa_id) return fetch_alert_directory(sorted(ids)) def _load_e8_directory( orders: list[EquipmentAcceptanceOrder], ) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]: """向 E8 要使用部门担当和申请人。人员 ID 只进 HrmResource。""" from app.services.equipment_acceptance.e8_repository import fetch_e8_alert_directory ids: set[int] = set() for order in orders: if (order.oa_system or "e10") != "e8" or order.monitor_status != WATCHING: continue if order.owner_oa_id: ids.add(order.owner_oa_id) if order.applicant_oa_id: ids.add(order.applicant_oa_id) return fetch_e8_alert_directory(sorted(ids)) def _job_numbers( orders: list[EquipmentAcceptanceOrder], e10_people: dict[int, dict[str, Any]], e10_deputies: dict[str, list[dict[str, Any]]], e8_people: dict[int, dict[str, Any]], ) -> set[str]: """收集要对系统用户的工号。E8 矩阵人员不走工号。""" found: set[str] = set() for order in orders: if order.owner_job_num: found.add(order.owner_job_num) if order.applicant_job_num: found.add(order.applicant_job_num) for fact in (*e10_people.values(), *e8_people.values()): if fact.get("job_num"): found.add(str(fact["job_num"])) if fact.get("superior_job_num"): found.add(str(fact["superior_job_num"])) for group in e10_deputies.values(): for item in group: if item.get("job_num"): found.add(str(item["job_num"])) return found def _wecom_ids(matrix: dict[str, dict[str, Any]]) -> set[str]: """收集 E8 矩阵上的企业微信 userid,用来补系统用户主键。""" found: set[str] = set() for item in matrix.values(): if not item.get("ok"): continue for key in ("zz", "jfl"): seat = item.get(key) or {} wecom = str(seat.get("wecom_userid") or "").strip() if wecom: found.add(wecom) return found def _users_by_wecom(wecom_ids: set[str]) -> dict[str, User]: """按企业微信 userid 索引系统用户。""" if not wecom_ids: return {} rows = db.session.query(User).filter(User.wecom_userid.in_(wecom_ids)).all() return {str(row.wecom_userid): row for row in rows if row.wecom_userid} def _users_by_job(job_nums: set[str]) -> dict[str, User]: """用工号索引系统用户。""" if not job_nums: return {} rows = db.session.query(User).filter(User.employee_id.in_(job_nums)).all() return {str(row.employee_id): row for row in rows if row.employee_id} def _configured_users() -> dict[str, User | None]: """读取三个固定岗位。没选时对应值是空。""" setting = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID) ids = [] if setting is not None: ids = [item for item in (setting.buyer_manager_user_id, setting.coo_user_id, setting.executive_user_id) if item] found = _users_by_id(ids) if setting is None: return {"buyer": None, "coo": None, "executive": None} return { "buyer": found.get(setting.buyer_manager_user_id or 0), "coo": found.get(setting.coo_user_id or 0), "executive": found.get(setting.executive_user_id or 0), } def _users_by_id(user_ids: list[int]) -> dict[int, User]: """按主键取出系统用户。""" if not user_ids: return {} rows = db.session.query(User).filter(User.id.in_(user_ids)).all() 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: return {} grouped: dict[int, list[EquipmentAcceptanceOperator]] = {} rows = ( db.session.query(EquipmentAcceptanceOperator) .filter(EquipmentAcceptanceOperator.order_id.in_(order_ids)) .all() ) for row in rows: grouped.setdefault(row.order_id, []).append(row) return grouped def _recipient_user_ids(rows: list[EquipmentAcceptanceSendRecord]) -> list[int]: """从待发送收件人里取出系统用户主键。""" found: list[int] = [] for row in rows: for person in list(row.recipients_json or []): if person.get("user_id"): found.append(int(person["user_id"])) return found def _audit_user( entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]], users: dict[int, User], ) -> User | None: """取这名收件人在系统里的账号,供企微审计。没有账号时仍按企微 userid 发送。""" for _row, person in entries: user_id = person.get("user_id") if user_id and int(user_id) in users: return users[int(user_id)] return None 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], 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: 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) 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: """把新的失败原因接在原有原因后面。相同句子不重复。""" parts = [part for part in (current, extra) if part] unique: list[str] = [] for part in parts: if part not in unique: unique.append(part) return ";".join(unique)