665 lines
29 KiB
Python
665 lines
29 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.integrations.wecom.notify import (
|
||
send_wecom_event_message,
|
||
send_wecom_file_message,
|
||
upload_wecom_temp_media,
|
||
)
|
||
from app.services.contract_payment.erp_payment_service import (
|
||
erp_schema_for_company,
|
||
fetch_paid_records,
|
||
normalize_purchase_order_no,
|
||
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()
|
||
)
|
||
payable_orders = [
|
||
(normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
|
||
for node, contract in rows
|
||
if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
|
||
]
|
||
paid_records = fetch_paid_records(payable_orders)
|
||
paid_node_dates: dict[int, str | None] = {}
|
||
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
||
for node, contract in rows:
|
||
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
|
||
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
||
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
|
||
for ledger_key, payment_nodes in nodes_by_ledger.items():
|
||
paid_node_dates.update(resolve_paid_node_dates(
|
||
[(node.id, node.node_type, node.amount) for node in payment_nodes],
|
||
paid_records.get(ledger_key, []),
|
||
))
|
||
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, reason: str = "erp_paid") -> int:
|
||
"""将某节点未发送的提醒标记为已关闭,保留历史发送记录。"""
|
||
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": reason}
|
||
return len(rows)
|
||
|
||
|
||
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
|
||
"""
|
||
把一个未付的预付款或出货款手动标为已付。
|
||
|
||
核心逻辑:只改这一阶段。写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||
验收款、质保款和已经付款的阶段不能标记。
|
||
|
||
Args:
|
||
contract_id: 合同台账主键。
|
||
node_id: 付款节点主键,必须属于该合同。
|
||
payload: paid_date 必填,remark 可选。
|
||
operator_id: 操作人用户 ID,写入证据供审计。
|
||
|
||
Returns:
|
||
更新后的合同。
|
||
|
||
Raises:
|
||
NotFoundError: 合同或节点不存在。
|
||
ValidationError: 阶段类型、状态或付款日期不合法。
|
||
"""
|
||
from app.core.errors import NotFoundError, ValidationError
|
||
|
||
contract = db.session.get(ContractPaymentContract, contract_id)
|
||
if contract is None:
|
||
raise NotFoundError("合同不存在")
|
||
node = db.session.get(ContractPaymentNode, node_id)
|
||
if node is None or node.contract_id != contract.id:
|
||
raise NotFoundError("付款节点不存在")
|
||
if node.node_type not in {"prepayment", "shipment"}:
|
||
raise ValidationError("只有预付款和出货款可以手动标为已付")
|
||
if node.status == "paid":
|
||
raise ValidationError("该阶段已是已付")
|
||
if node.status != "active":
|
||
raise ValidationError("该阶段当前不能标为已付")
|
||
raw_date = str(payload.get("paid_date") or "").strip()[:10]
|
||
try:
|
||
paid_date = date.fromisoformat(raw_date)
|
||
except ValueError:
|
||
raise ValidationError("请填写付款日期") from None
|
||
remark = str(payload.get("remark") or "").strip()
|
||
if len(remark) > 500:
|
||
raise ValidationError("说明不能超过 500 字")
|
||
node.status = "paid"
|
||
node.evidence_json = {
|
||
**(node.evidence_json or {}),
|
||
"paid_at": paid_date.isoformat(),
|
||
"paid_source": "manual",
|
||
"paid_remark": remark or None,
|
||
"paid_by": operator_id,
|
||
}
|
||
_resolve_pending_alerts(node_id=node.id, reason="manual_paid")
|
||
db.session.commit()
|
||
return contract
|
||
|
||
|
||
_FAILURE_REASON_LABELS: dict[str, str] = {
|
||
"notify_disabled": "企业微信通知未启用",
|
||
"event_disabled": "合同付款预警通知事件未启用",
|
||
"user_unbound": "收件人未绑定企业微信账号",
|
||
"textcard_failed": "企业微信卡片发送失败",
|
||
"file_upload_failed": "企业微信附件上传失败",
|
||
"file_failed": "企业微信附件发送失败",
|
||
"unknown": "发送失败",
|
||
}
|
||
|
||
|
||
def _append_failure_reason(reasons: list[dict[str, str]], code: str, detail: str = "") -> None:
|
||
"""向失败原因列表追加一条去重后的记录。
|
||
|
||
核心逻辑:压缩 detail 空白并截断到 500 字;code 与 detail 都相同则跳过。
|
||
|
||
Args:
|
||
reasons: 正在组装的原因列表,就地修改。
|
||
code: 前端可翻译的原因编码。
|
||
detail: 企微或异常返回的补充说明,可为空。
|
||
"""
|
||
normalized = " ".join(str(detail or "").split())[:500]
|
||
if any(item["code"] == code and item["detail"] == normalized for item in reasons):
|
||
return
|
||
reasons.append({"code": code, "detail": normalized})
|
||
|
||
|
||
def describe_batch_failure(trace: dict | None, *, fallback: str | None = None) -> list[dict[str, str]]:
|
||
"""把周汇总企微发送轨迹整理成可展示的失败原因。
|
||
|
||
核心逻辑:优先识别卡片失败、附件上传异常和附件发送失败;「未绑定企微」只保留一条。
|
||
轨迹无法识别时回退到已保存的 error_message,避免历史失败批次没有原因可看。
|
||
|
||
Args:
|
||
trace: 批次 wecom_trace_json。非字典时忽略。
|
||
fallback: 轨迹无法识别时使用的已存错误文本。
|
||
|
||
Returns:
|
||
原因列表。每项含 code 与 detail;没有可展示原因时返回空列表。
|
||
"""
|
||
reasons: list[dict[str, str]] = []
|
||
# [STEP 1] 卡片发送失败优先按已知原因码归类,企微 errmsg 放在 detail。
|
||
if isinstance(trace, dict):
|
||
textcard = trace.get("textcard") if isinstance(trace.get("textcard"), dict) else {}
|
||
if textcard and not textcard.get("ok"):
|
||
reason = str(textcard.get("reason") or "").strip()
|
||
raw = textcard.get("raw") if isinstance(textcard.get("raw"), dict) else {}
|
||
errmsg = str(raw.get("errmsg") or "").strip()
|
||
if reason in {"notify_disabled", "event_disabled", "user_unbound"}:
|
||
_append_failure_reason(reasons, reason)
|
||
else:
|
||
_append_failure_reason(reasons, "textcard_failed", errmsg)
|
||
|
||
# [STEP 2] 附件失败与卡片失败分开记录;未绑定账号不重复展示。
|
||
file_error = str(trace.get("file_error") or "").strip()
|
||
if file_error:
|
||
_append_failure_reason(reasons, "file_upload_failed", file_error)
|
||
else:
|
||
file_result = trace.get("file") if isinstance(trace.get("file"), dict) else {}
|
||
errcode = file_result.get("errcode")
|
||
if errcode not in (None, 0, "0"):
|
||
errmsg = str(file_result.get("errmsg") or "").strip()
|
||
if errmsg == "user_unbound":
|
||
_append_failure_reason(reasons, "user_unbound")
|
||
else:
|
||
_append_failure_reason(reasons, "file_failed", errmsg or str(errcode))
|
||
|
||
if reasons:
|
||
return reasons
|
||
stored = " ".join(str(fallback or "").split())
|
||
if stored:
|
||
_append_failure_reason(reasons, "unknown", stored[:2000])
|
||
return reasons
|
||
|
||
|
||
def render_batch_failure_message(reasons: list[dict[str, str]]) -> str:
|
||
"""把失败原因编码拼成写入批次审计字段的中文摘要。
|
||
|
||
核心逻辑:使用固定中文标签,detail 非空时接在标签后,多条以分号连接。
|
||
|
||
Args:
|
||
reasons: describe_batch_failure 的返回值。
|
||
|
||
Returns:
|
||
最长 2000 字的中文摘要;没有原因时返回空字符串。
|
||
"""
|
||
parts: list[str] = []
|
||
for item in reasons:
|
||
label = _FAILURE_REASON_LABELS.get(str(item.get("code") or ""), "发送失败")
|
||
detail = str(item.get("detail") or "").strip()
|
||
parts.append(f"{label}:{detail}" if detail else label)
|
||
return ";".join(parts)[:2000]
|
||
|
||
|
||
def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
|
||
"""按收件人发送本周合同付款预警汇总及 Excel 明细。
|
||
|
||
AI 触发时机:每周五 18:00 的排程或管理员补发时调用。
|
||
核心逻辑:每位收件人每周只产生一个批次;企微正文仅发送总笔数和阶段数量,逐笔信息写入附件。
|
||
发送失败时把卡片和附件的原因写入 error_message,并把 sent_at 记为最近一次尝试时间,供周汇总页查看。
|
||
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.sent_at = datetime.utcnow()
|
||
batch.error_message = render_batch_failure_message(describe_batch_failure(trace)) or 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())
|