fix(contract-payment): fix comments of contract payment plan
This commit is contained in:
1 parent
60d4f06018
commit
1c0654c6f8
25 files changed
+956
-76
No files matched your search
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要和同步 API。
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点与本周待发送摘要;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:所有接口要求已登录且具备 `contract_payment.access`(admin 默认开,可显式授予普通用户)。
|
||||
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,6 +29,11 @@ from app.models import (
|
||||
FileAsset,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary
|
||||
from app.services.contract_payment.ledger_focus import (
|
||||
LEDGER_FOCUS_VALUES,
|
||||
apply_ledger_focus,
|
||||
ledger_focus_counts,
|
||||
)
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
@@ -92,6 +98,30 @@ def _require_contract_payment_access():
|
||||
return user
|
||||
|
||||
|
||||
def _require_contract_payment_admin():
|
||||
"""
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError(
|
||||
'Admin privilege required for contract payment jobs',
|
||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
"""
|
||||
序列化合同台账、付款节点及预警记录,供列表和详情共用。
|
||||
@@ -170,7 +200,7 @@ def list_contracts():
|
||||
"""
|
||||
查询合同台账。
|
||||
|
||||
核心逻辑:支持合同编号、流程编号、采购单号和解析状态筛选,并按 offset 分页返回台账,避免工作台一次加载全部合同。
|
||||
核心逻辑:支持合同编号、流程编号、采购单号、供应商名称、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
|
||||
Args:
|
||||
无。筛选条件从 query string 读取。
|
||||
Returns:
|
||||
@@ -185,6 +215,7 @@ def list_contracts():
|
||||
ContractPaymentContract.contract_no.ilike(like)
|
||||
| ContractPaymentContract.workflow_no.ilike(like)
|
||||
| ContractPaymentContract.purchase_order_no.ilike(like)
|
||||
| ContractPaymentContract.supplier_name.ilike(like)
|
||||
)
|
||||
parse_status = str(request.args.get("parse_status") or "").strip()
|
||||
review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
|
||||
@@ -195,6 +226,13 @@ def list_contracts():
|
||||
else:
|
||||
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
|
||||
query = query.filter_by(parse_status="parsed")
|
||||
focus = str(request.args.get("focus") or "").strip()
|
||||
if focus:
|
||||
if review_only:
|
||||
raise ValidationError("待确认列表不支持汇总卡筛选", details={"focus": focus})
|
||||
if focus not in LEDGER_FOCUS_VALUES:
|
||||
raise ValidationError("不支持的汇总卡筛选", details={"focus": focus})
|
||||
query = apply_ledger_focus(query, focus, session=db.session)
|
||||
page = max(_query_int("page", default=1), 1)
|
||||
page_size = min(max(_query_int("page_size", default=20), 1), 100)
|
||||
total = query.count()
|
||||
@@ -215,6 +253,21 @@ def list_contracts():
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/summary", methods=["GET"])
|
||||
def get_ledger_summary():
|
||||
"""
|
||||
查询合同台账四张汇总卡的合同份数。
|
||||
|
||||
核心逻辑:始终统计全部已解析台账,不跟页面 keyword;口径与点卡片过滤列表共用 ledger_focus。
|
||||
Args:
|
||||
无。
|
||||
Returns:
|
||||
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
def _query_int(key: str, *, default: int) -> int:
|
||||
"""读取正整数查询参数;非法值回退默认值,防止分页接口返回 500。"""
|
||||
try:
|
||||
@@ -279,12 +332,15 @@ def enqueue_sync():
|
||||
"""
|
||||
将 OA 合同、验收和厂商预付款请款同步任务入队。
|
||||
|
||||
核心逻辑:仅管理员可入队;force / reparse_existing 仍走同一 Job,避免普通授权用户改写 OA 字段。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
data = request.get_json(silent=True) or {}
|
||||
force_value = data.get("force", False)
|
||||
if not isinstance(force_value, bool):
|
||||
@@ -303,12 +359,15 @@ def enqueue_alert_scan():
|
||||
"""
|
||||
将四阶段三轮合同付款预警扫描任务入队。
|
||||
|
||||
核心逻辑:仅管理员可手动补扫;日常扫描仍由排程触发。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
job_id = enqueue(JobType.CONTRACT_PAYMENT_ALERT, {}, domain="procurement_contract", business_ref="daily-alert", created_by_id=user.id, message="等待计算合同付款预警")
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
@@ -331,12 +390,15 @@ def get_alert_summary():
|
||||
def enqueue_weekly_alert_send():
|
||||
"""将合同付款预警周汇总发送任务入队。
|
||||
|
||||
核心逻辑:仅管理员可手动补发;周五 18:00 排程不受此限制。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
job_id = enqueue(
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
|
||||
{},
|
||||
|
||||
@@ -280,22 +280,24 @@ def _node_paid_date(node: ContractPaymentNode) -> str | None:
|
||||
|
||||
|
||||
def _build_excel(items) -> tuple[bytes, dict[str, object]]:
|
||||
"""生成收件人专属逐笔付款预警明细 Excel。"""
|
||||
"""生成收件人专属逐笔付款预警明细 Excel。
|
||||
|
||||
核心逻辑:按合同/节点逐行输出;「收件人」列写该批次实际收件人姓名,「状态」列写中文,不再输出岗位名称或 pending 英文码。
|
||||
"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "付款预警明细"
|
||||
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件岗位", "状态"]
|
||||
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件人", "状态"]
|
||||
ws.append(headers)
|
||||
for cell in ws[1]:
|
||||
cell.font = Font(bold=True)
|
||||
counts = Counter()
|
||||
for alert, contract, node, _user in items:
|
||||
role = _ALERT_RULES[node.node_type][alert.alert_round - 1][1]
|
||||
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}次", _role_label(role), alert.status,
|
||||
f"第{alert.alert_round}次", _recipient_display_name(user), _alert_status_label(alert.status),
|
||||
])
|
||||
counts[node.node_type] += 1
|
||||
ws.freeze_panes = "A2"
|
||||
@@ -305,6 +307,25 @@ def _build_excel(items) -> tuple[bytes, dict[str, object]]:
|
||||
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 "无"
|
||||
@@ -464,6 +485,22 @@ def _node_label(node_type: str) -> str:
|
||||
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
|
||||
|
||||
|
||||
def _role_label(role: str) -> str:
|
||||
"""返回提醒岗位中文名称。"""
|
||||
return {"owner": "采购负责人", "department_head": "采购部负责人", "procurement_leader": "采购分管领导"}.get(role, role)
|
||||
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())
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/ledger_focus.py
|
||||
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy.orm import Query, Session
|
||||
from sqlalchemy.sql.expression import false
|
||||
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode
|
||||
|
||||
LEDGER_FOCUS_DUE = "due"
|
||||
LEDGER_FOCUS_OVERDUE = "overdue"
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
|
||||
LEDGER_FOCUS_VALUES = {
|
||||
LEDGER_FOCUS_DUE,
|
||||
LEDGER_FOCUS_OVERDUE,
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION,
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH,
|
||||
}
|
||||
_NEAR_DUE_DAYS = 7
|
||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
|
||||
def business_today(*, today: date | None = None) -> date:
|
||||
"""
|
||||
返回汇总卡使用的业务日(上海日历)。
|
||||
|
||||
Args:
|
||||
today: 测试注入的业务日;缺省为 Asia/Shanghai 当天。
|
||||
Returns:
|
||||
用于 7 日内到期、逾期和本月判断的日期。
|
||||
"""
|
||||
return today or datetime.now(_SHANGHAI).date()
|
||||
|
||||
|
||||
def node_due_reference(due_date: date | None, anchor_date: date | None) -> date | None:
|
||||
"""
|
||||
付款节点到期判断基准日。
|
||||
|
||||
核心逻辑:与前台 paymentStatus.nodeDueReference 一致,优先 due_date,否则回退 anchor_date。
|
||||
Args:
|
||||
due_date: 节点到期日。
|
||||
anchor_date: 节点锚点日。
|
||||
Returns:
|
||||
可用于比较的日期;两者皆空时为 None。
|
||||
"""
|
||||
return due_date or anchor_date
|
||||
|
||||
|
||||
def classify_ledger_status(
|
||||
*,
|
||||
contract_status: str | None,
|
||||
parse_status: str | None,
|
||||
nodes: Iterable[dict[str, Any]],
|
||||
today: date,
|
||||
) -> str:
|
||||
"""
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
parse_status: 解析状态。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
||||
today: 业务日。
|
||||
Returns:
|
||||
overdue / due / active / completed / needs_completion。
|
||||
"""
|
||||
node_list = list(nodes)
|
||||
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
if not node_list:
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
||||
if not active:
|
||||
has_paid = any(
|
||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||
for node in node_list
|
||||
)
|
||||
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
refs = [
|
||||
ref
|
||||
for node in active
|
||||
if (ref := node_due_reference(node.get("due_date"), node.get("anchor_date")))
|
||||
]
|
||||
if any((ref - today).days < 0 for ref in refs):
|
||||
return LEDGER_FOCUS_OVERDUE
|
||||
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
|
||||
return LEDGER_FOCUS_DUE
|
||||
return "active"
|
||||
|
||||
|
||||
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
|
||||
"""
|
||||
合同是否有未付节点的到期日落在本自然月。
|
||||
|
||||
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
Args:
|
||||
nodes: 轻量节点 dict。
|
||||
today: 业务日,用于确定自然月。
|
||||
Returns:
|
||||
存在本月未付到期节点时为 True。
|
||||
"""
|
||||
month_start = today.replace(day=1)
|
||||
month_end = date(today.year + 1, 1, 1) if today.month == 12 else date(today.year, today.month + 1, 1)
|
||||
for node in nodes:
|
||||
if str(node.get("status") or "").strip().lower() != "active":
|
||||
continue
|
||||
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
||||
if ref and month_start <= ref < month_end:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
|
||||
"""把 ORM 节点收成分类所需的轻量字段。"""
|
||||
return {
|
||||
"status": node.status,
|
||||
"due_date": node.due_date,
|
||||
"anchor_date": node.anchor_date,
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
}
|
||||
|
||||
|
||||
def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict[str, set[int]]:
|
||||
"""
|
||||
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
|
||||
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
四个 focus 键到合同 ID 集合的映射。
|
||||
"""
|
||||
as_of = business_today(today=today)
|
||||
contracts = (
|
||||
session.query(ContractPaymentContract.id, ContractPaymentContract.status, ContractPaymentContract.parse_status)
|
||||
.filter(ContractPaymentContract.parse_status == "parsed")
|
||||
.all()
|
||||
)
|
||||
buckets: dict[str, set[int]] = {
|
||||
LEDGER_FOCUS_DUE: set(),
|
||||
LEDGER_FOCUS_OVERDUE: set(),
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
|
||||
}
|
||||
if not contracts:
|
||||
return buckets
|
||||
contract_ids = [row.id for row in contracts]
|
||||
nodes_by_contract: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
node_rows = (
|
||||
session.query(ContractPaymentNode)
|
||||
.filter(ContractPaymentNode.contract_id.in_(contract_ids))
|
||||
.all()
|
||||
)
|
||||
for node in node_rows:
|
||||
nodes_by_contract[node.contract_id].append(_node_payload(node))
|
||||
for row in contracts:
|
||||
nodes = nodes_by_contract.get(row.id, [])
|
||||
status = classify_ledger_status(
|
||||
contract_status=row.status,
|
||||
parse_status=row.parse_status,
|
||||
nodes=nodes,
|
||||
today=as_of,
|
||||
)
|
||||
if status == LEDGER_FOCUS_DUE:
|
||||
buckets[LEDGER_FOCUS_DUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_OVERDUE:
|
||||
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
|
||||
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
|
||||
if has_unpaid_due_this_month(nodes, as_of):
|
||||
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
|
||||
return buckets
|
||||
|
||||
|
||||
def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[str, int]:
|
||||
"""
|
||||
返回四张汇总卡的合同份数。
|
||||
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
due / overdue / needs_completion / due_this_month 的计数。
|
||||
"""
|
||||
buckets = collect_ledger_focus(session=session, today=today)
|
||||
return {key: len(ids) for key, ids in buckets.items()}
|
||||
|
||||
|
||||
def apply_ledger_focus(query: Query, focus: str, *, session: Session, today: date | None = None) -> Query:
|
||||
"""
|
||||
按汇总卡口径把台账查询限制到对应合同 ID。
|
||||
|
||||
核心逻辑:空集合时强制无结果,避免 SQL IN () 退化成不过滤。
|
||||
Args:
|
||||
query: 已按解析状态/关键词过滤的合同查询。
|
||||
focus: 四个合法口径之一。
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
叠加 ID 过滤后的查询。
|
||||
"""
|
||||
ids = collect_ledger_focus(session=session, today=today).get(focus) or set()
|
||||
if not ids:
|
||||
return query.filter(false())
|
||||
return query.filter(ContractPaymentContract.id.in_(ids))
|
||||
Reference in new issue
Block a user