Files
syops/backend/app/services/contract_payment/alert_service.py
T

507 lines
22 KiB
Python

"""
services/contract_payment/alert_service.py
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;摘要接口与周五发送使用同一 pending 口径。
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
"""
from __future__ import annotations
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from io import BytesIO
from uuid import uuid4
from flask import current_app
from openpyxl import Workbook
from openpyxl.styles import Font
from sqlalchemy import func
from app import db
from app.models import (
ContractPaymentAlert,
ContractPaymentAlertBatch,
ContractPaymentContract,
ContractPaymentEvent,
ContractPaymentNode,
User,
)
from app.services.wecom_notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
)
from app.services.contract_payment.erp_payment_service import fetch_paid_records, resolve_paid_node_dates
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
from app.services.schedule.timezone_util import compute_next_run_at
@dataclass(frozen=True)
class _AlertRecipient:
"""扫描时解析出的收件人:系统用户 + 可选 OA/企微 userid。"""
user: User
oa_wecom_userid: str | None = None
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
"acceptance": ((30, "owner"), (40, "department_head"), (60, "procurement_leader")),
"warranty": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
}
def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[str, int]:
"""每日扫描付款节点并生成 pending 预警,不直接发送企微。
AI 触发时机:每日排程或管理员手动执行扫描时调用。
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
Args:
today: 业务日期,未传时使用服务器日期。
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
Returns:
created、pending、skipped、resolved 四项计数。
"""
_ = send
today = today or date.today()
created = skipped = resolved = 0
supervisors = SupervisorMatrixCache()
rows = (
db.session.query(ContractPaymentNode, ContractPaymentContract)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentNode.contract_id)
.filter(ContractPaymentNode.status == "active", ContractPaymentContract.status == "active")
.all()
)
paid_records = fetch_paid_records(
contract.purchase_order_no
for _node, contract in rows
if _node.node_type in {"prepayment", "shipment"}
)
paid_node_dates: dict[int, str | None] = {}
nodes_by_purchase_order: dict[str, list[ContractPaymentNode]] = defaultdict(list)
for node, contract in rows:
purchase_order_no = str(contract.purchase_order_no or "").strip()
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
nodes_by_purchase_order[purchase_order_no].append(node)
for purchase_order_no, payment_nodes in nodes_by_purchase_order.items():
paid_node_dates.update(resolve_paid_node_dates(
[(node.id, node.node_type, node.amount) for node in payment_nodes],
paid_records.get(purchase_order_no, []),
))
for node, contract in rows:
anchor = _anchor_date(contract=contract, node=node)
if anchor is None:
skipped += 1
continue
erp_paid = node.id in paid_node_dates
if erp_paid:
node.status = "paid"
# [STEP 1] 记录 ERP 付款日期,供详情页付款计划展示“已付 + 日期”。
node.evidence_json = {**(node.evidence_json or {}), "paid_at": paid_node_dates.get(node.id)}
for alert_round, (offset_days, recipient_role) in enumerate(_ALERT_RULES.get(node.node_type, ()), start=1):
scheduled_date = anchor + timedelta(days=offset_days)
if today < scheduled_date:
continue
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
if erp_paid:
resolved += _resolve_pending_alerts(node_id=node.id)
break
recipients = _resolve_recipients(
contract=contract, recipient_role=recipient_role, supervisors=supervisors
)
if not recipients:
skipped += 1
continue
for recipient in recipients:
trigger_key = f"round:{alert_round}:date:{scheduled_date.isoformat()}"
exists = db.session.query(ContractPaymentAlert.id).filter_by(
node_id=node.id, trigger_key=trigger_key, recipient_user_id=recipient.user.id
).first()
if exists:
continue
message_json = {"scheduled_date": scheduled_date.isoformat()}
if recipient.oa_wecom_userid:
message_json["oa_wecom_userid"] = recipient.oa_wecom_userid
db.session.add(ContractPaymentAlert(
contract_id=contract.id,
node_id=node.id,
trigger_key=trigger_key,
alert_round=alert_round,
scheduled_at=datetime.combine(scheduled_date, datetime.min.time()),
recipient_user_id=recipient.user.id,
status="pending",
message_json=message_json,
))
created += 1
db.session.commit()
return {"created": created, "pending": created, "sent": 0, "skipped": skipped, "resolved": resolved}
def _resolve_pending_alerts(*, node_id: int) -> int:
"""将某节点未发送的提醒标记为已按 ERP 付款关闭,保留历史发送记录。"""
rows = db.session.query(ContractPaymentAlert).filter_by(node_id=node_id, status="pending").all()
for alert in rows:
alert.status = "resolved"
alert.message_json = {**(alert.message_json or {}), "resolved_reason": "erp_paid"}
return len(rows)
def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
"""按收件人发送本周合同付款预警汇总及 Excel 明细。
AI 触发时机:每周五 18:00 的排程或管理员补发时调用。
核心逻辑:每位收件人每周只产生一个批次;企微正文仅发送总笔数和阶段数量,逐笔信息写入附件。
Args:
today: 用于确定 ISO 周标识,测试可显式传入。
Returns:
batches、sent、failed、alerts 四项计数。
"""
today = today or date.today()
week_key = today.strftime("%G-W%V")
rows = (
db.session.query(ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentAlert.contract_id)
.join(ContractPaymentNode, ContractPaymentNode.id == ContractPaymentAlert.node_id)
.join(User, User.id == ContractPaymentAlert.recipient_user_id)
.filter(ContractPaymentAlert.status == "pending", ContractPaymentContract.status == "active")
.order_by(ContractPaymentAlert.recipient_user_id, ContractPaymentAlert.scheduled_at, ContractPaymentAlert.id)
.all()
)
grouped: dict[int, list[tuple[ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User]]] = defaultdict(list)
for row in rows:
grouped[row[0].recipient_user_id].append(row)
batches = sent = failed = detail_count = 0
for recipient_id, items in grouped.items():
batch = db.session.query(ContractPaymentAlertBatch).filter_by(week_key=week_key, recipient_user_id=recipient_id).first()
if batch and batch.status == "sent":
continue
if batch is None:
batch = ContractPaymentAlertBatch(
batch_no=f"CPAW-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid4().hex[:8].upper()}",
week_key=week_key,
recipient_user_id=recipient_id,
status="sending",
)
db.session.add(batch)
db.session.flush()
batches += 1
workbook_data, summary = _build_excel(items)
batch.summary_json = summary
batch.excel_file_name = f"合同付款预警明细-{week_key}-{recipient_id}.xlsx"
batch.excel_file_data = workbook_data
batch.excel_file_size = len(workbook_data)
user = items[0][3]
wecom_userid = _batch_wecom_userid(items, user)
result = send_wecom_event_message(
event_type="contract_payment_warning",
user=user,
title=f"合同付款预警汇总({summary['total']}笔)",
content=_build_summary_message(summary),
jump_path="/workspace/contract-payment",
jump_params={"batch_no": batch.batch_no},
wecom_userid=wecom_userid,
)
trace = {"textcard": result}
try:
media_id = upload_wecom_temp_media(workbook_data, batch.excel_file_name)
file_result = (
send_wecom_file_message(wecom_userid, media_id)
if wecom_userid
else {"errcode": -1, "errmsg": "user_unbound"}
)
trace["file"] = file_result
except Exception as exc:
trace["file_error"] = str(exc)
file_result = {"errcode": -1}
batch.wecom_trace_json = trace
if result.get("ok") and file_result.get("errcode") == 0:
batch.status = "sent"
batch.sent_at = datetime.utcnow()
for alert, *_ in items:
alert.status = "sent"
alert.sent_at = datetime.utcnow()
alert.message_json = {**(alert.message_json or {}), "batch_no": batch.batch_no}
detail_count += 1
sent += 1
else:
batch.status = "failed"
batch.error_message = str(trace)[:2000]
failed += 1
db.session.commit()
return {"batches": batches, "sent": sent, "failed": failed, "alerts": detail_count}
def build_weekly_alert_summary(*, now: datetime | None = None) -> dict[str, object]:
"""返回本周待发送笔数和下一次周五汇总发送时间。
核心逻辑:待发送口径与 `send_weekly_alerts` 一致(pending + 合同 active);
下次发送时刻复用排程 Cron `0 18 * * 5` 与上海时区,当前时刻已过本周五 18:00 则指向下周五。
Args:
now: 可选 UTC naive 基准时刻,测试可注入;未传时使用当前时间。
Returns:
pending_count、UTC ISO 的 next_send_at,以及业务时区名称。
"""
pending_count = (
db.session.query(ContractPaymentAlert)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentAlert.contract_id)
.filter(ContractPaymentAlert.status == "pending", ContractPaymentContract.status == "active")
.count()
)
timezone_name = str(current_app.config.get("CONTRACT_PAYMENT_ALERT_TIMEZONE") or "Asia/Shanghai").strip() or "Asia/Shanghai"
cron = str(current_app.config.get("CONTRACT_PAYMENT_ALERT_WEEKLY_CRON") or "0 18 * * 5").strip() or "0 18 * * 5"
next_utc = compute_next_run_at(cron, base_utc_naive=now, timezone_name=timezone_name)
next_send_at = None
if next_utc is not None:
next_send_at = next_utc.replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z")
return {
"pending_count": pending_count,
"next_send_at": next_send_at,
"timezone": timezone_name,
}
def _node_paid_date(node: ContractPaymentNode) -> str | None:
"""返回节点实际付款日期(ERP apa_file 的 paid_at);节点未付时返回 None。
用于 Excel 「付款日期」列:只有已付节点才展示付款日期,未付显示「—」,
避免把「到期日」(due_date)误标为付款日期。
"""
if str(node.status or "").strip().lower() != "paid":
return None
return (node.evidence_json or {}).get("paid_at")
def _build_excel(items) -> tuple[bytes, dict[str, object]]:
"""生成收件人专属逐笔付款预警明细 Excel。
核心逻辑:按合同/节点逐行输出;「收件人」列写该批次实际收件人姓名,「状态」列写中文,不再输出岗位名称或 pending 英文码。
"""
wb = Workbook()
ws = wb.active
ws.title = "付款预警明细"
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件人", "状态"]
ws.append(headers)
for cell in ws[1]:
cell.font = Font(bold=True)
counts = Counter()
for alert, contract, node, user in items:
ws.append([
contract.contract_no or "待解析", contract.purchase_order_no or "—", contract.supplier_name or "—",
str(contract.total_amount or ""), _node_label(node.node_type), str(node.amount or ""),
str(node.percentage or ""), _node_paid_date(node) or "—", (node.due_date or node.anchor_date).isoformat() if (node.due_date or node.anchor_date) else "—",
f"第{alert.alert_round}次", _recipient_display_name(user), _alert_status_label(alert.status),
])
counts[node.node_type] += 1
ws.freeze_panes = "A2"
ws.auto_filter.ref = ws.dimensions
output = BytesIO()
wb.save(output)
return output.getvalue(), {"total": len(items), "stages": {_node_label(k): v for k, v in counts.items()}}
def _recipient_display_name(user: User | None) -> str:
"""
返回 Excel「收件人」列展示的人名。
核心逻辑:优先真实姓名;姓名为空时回退用户名,避免再写出岗位名称。
Args:
user: 本行预警对应的系统用户;缺失时写「—」。
Returns:
去空白后的姓名或用户名;都没有时为「—」。
"""
if user is None:
return "—"
name = str(getattr(user, "real_name", None) or "").strip()
if name:
return name
username = str(getattr(user, "username", None) or "").strip()
return username or "—"
def _build_summary_message(summary: dict[str, object]) -> str:
stages = summary.get("stages") or {}
detail = "、".join(f"{key}{value}笔" for key, value in stages.items()) or "无"
return f"本周需关注付款 {summary.get('total', 0)} 笔\n阶段汇总:{detail}\n详细合同与付款信息请查看随附 Excel。"
def _anchor_date(*, contract: ContractPaymentContract, node: ContractPaymentNode) -> date | None:
"""返回付款节点的提醒规则锚点日期;缺少事实时返回 None。"""
if node.node_type == "prepayment":
return contract.oa_archive_at.date() if contract.oa_archive_at else None
if node.node_type == "shipment":
return node.due_date or contract.delivery_due_date
if node.node_type == "acceptance":
event = db.session.query(ContractPaymentEvent).filter_by(contract_id=contract.id, event_type="acceptance_archive").order_by(ContractPaymentEvent.event_date.asc()).first()
return event.event_date if event else None
if node.node_type == "warranty":
return node.due_date
return None
def bind_contract_owner_from_applicant(contract: ContractPaymentContract) -> User | None:
"""
将合同第一轮收件人绑定为台账申请人对应的系统用户。
核心逻辑:用 OA/台账上的申请人姓名对 `users.real_name` 做去空白后的精确匹配;
仅当且仅有一名 active 用户时写入 `owner_user_id`。匹配失败、姓名为空或重名时清空
`owner_user_id`,禁止继续使用默认管理员或其他兜底账号。
Args:
contract: 已带 applicant_name 的合同主记录。
Returns:
唯一匹配到的系统用户;无法唯一确定时返回 None。
"""
name = str(contract.applicant_name or "").strip()
if not name:
contract.owner_user_id = None
return None
matches = (
db.session.query(User)
.filter(User.status == "active", func.trim(User.real_name) == name)
.order_by(User.id.asc())
.all()
)
if len(matches) != 1:
current_app.logger.warning(
"contract_payment applicant mapping skipped contract_id=%s applicant=%s matches=%s",
getattr(contract, "id", None),
name,
len(matches),
)
contract.owner_user_id = None
return None
user = matches[0]
contract.owner_user_id = user.id
return user
def _batch_wecom_userid(
items: list[tuple[ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User]],
user: User,
) -> str | None:
"""
解析本周批次实际发送的企业微信 userid。
核心逻辑:第二、三轮优先用 OA 矩阵写入的 `oa_wecom_userid`(即 HrmResource.id);
没有时回退系统用户已绑定的 wecom_userid。第一轮通常走后者。
"""
for alert, *_rest in items:
raw = (alert.message_json or {}).get("oa_wecom_userid")
text = str(raw or "").strip()
if text:
return text
bound = str(getattr(user, "wecom_userid", None) or "").strip()
return bound or None
def _resolve_recipients(
*,
contract: ContractPaymentContract,
recipient_role: str,
supervisors: SupervisorMatrixCache,
) -> list[_AlertRecipient]:
"""
根据轮次岗位解析有效收件人。
核心逻辑:第一轮按申请人真实姓名唯一匹配系统用户。第二轮用矩阵 zz、第三轮用 jfl,
该 OA id 同时作为企微 userid;再映射到系统用户以便写入 recipient_user_id。
查不到或无法唯一确定时跳过该轮,不向第一轮申请人或其他全局名单兜底。
"""
if recipient_role == "owner":
user = bind_contract_owner_from_applicant(contract)
return [_AlertRecipient(user=user)] if user else []
matrix = supervisors.get(contract.applicant_name)
if matrix is None or not matrix.ok:
return []
oa_id = matrix.round2_oa_id if recipient_role == "department_head" else matrix.round3_oa_id
lastname = matrix.round2_name if recipient_role == "department_head" else matrix.round3_name
user = _user_for_oa_wecom_id(oa_id, lastname)
if user is None:
current_app.logger.warning(
"contract_payment supervisor recipient missing role=%s contract_id=%s oa_id=%s",
recipient_role,
getattr(contract, "id", None),
oa_id,
)
return []
return [_AlertRecipient(user=user, oa_wecom_userid=str(oa_id))]
def _user_for_oa_wecom_id(oa_id: int | None, lastname: str | None) -> User | None:
"""
将 OA/企微 userid 映射为系统用户。
核心逻辑:优先 `users.wecom_userid` 精确等于 OA id;未绑定时再用主管 lastname
对 `users.real_name` 做唯一匹配,以便满足预警表的用户外键。重名或都未命中则放弃。
"""
if oa_id is None:
return None
wecom = str(oa_id)
by_wecom = (
db.session.query(User)
.filter(User.status == "active", User.wecom_userid == wecom)
.order_by(User.id.asc())
.all()
)
if len(by_wecom) == 1:
return by_wecom[0]
if len(by_wecom) > 1:
current_app.logger.warning(
"contract_payment supervisor wecom_userid not unique oa_id=%s matches=%s",
wecom,
len(by_wecom),
)
return None
name = str(lastname or "").strip()
if not name:
return None
by_name = (
db.session.query(User)
.filter(User.status == "active", func.trim(User.real_name) == name)
.order_by(User.id.asc())
.all()
)
if len(by_name) == 1:
return by_name[0]
current_app.logger.warning(
"contract_payment supervisor user mapping skipped oa_id=%s lastname=%s matches=%s",
wecom,
name,
len(by_name),
)
return None
def _node_label(node_type: str) -> str:
"""返回付款阶段中文名称。"""
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
def _alert_status_label(status: str | None) -> str:
"""返回预警状态的中文名称,供企微 Excel「状态」列使用。
核心逻辑:与工作台 alertStatus 口径一致;未知编码原样回写,避免掩盖新增状态。
Args:
status: 预警记录内部状态码。
Returns:
中文状态;空值写「—」。
"""
code = str(status or "").strip().lower()
if not code:
return "—"
return {
"pending": "待发送",
"sent": "已发送",
"failed": "发送失败",
"resolved": "已关闭",
"sending": "发送中",
}.get(code, str(status).strip())