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))
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_ledger_focus.py
|
||||
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='user',
|
||||
status='active',
|
||||
real_name=f'{username}-实名',
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成测试鉴权头。"""
|
||||
return {
|
||||
'X-User-Id': str(user.id),
|
||||
'X-Username': user.username,
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def _add_contract(*, contract_no: str, status: str = 'active') -> ContractPaymentContract:
|
||||
"""写入一份已进入台账的合同。"""
|
||||
contract = ContractPaymentContract(
|
||||
contract_no=contract_no,
|
||||
parse_status='parsed',
|
||||
status=status,
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
return contract
|
||||
|
||||
|
||||
def _add_node(contract: ContractPaymentContract, *, due: date | None, node_status: str = 'active') -> None:
|
||||
"""写入一个付款节点,供汇总卡按到期日分类。"""
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code=f'prepayment-{contract.id}',
|
||||
node_type='prepayment',
|
||||
status=node_status,
|
||||
due_date=due,
|
||||
offset_days=0,
|
||||
reminder_days=14,
|
||||
))
|
||||
|
||||
|
||||
def _seed_focus_contracts() -> None:
|
||||
"""构造四张汇总卡各自至少命中一份的台账合同。"""
|
||||
today = date(2026, 9, 10)
|
||||
due = _add_contract(contract_no='HT-FOCUS-DUE')
|
||||
_add_node(due, due=today.replace(day=14))
|
||||
overdue = _add_contract(contract_no='HT-FOCUS-OVERDUE')
|
||||
_add_node(overdue, due=date(2026, 8, 20))
|
||||
_add_contract(contract_no='HT-FOCUS-NEEDS')
|
||||
month = _add_contract(contract_no='HT-FOCUS-MONTH')
|
||||
_add_node(month, due=date(2026, 9, 28))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_ledger_focus_counts_by_contract(app):
|
||||
"""四张汇总卡均按合同计数;本月应付只含本自然月未付合同。"""
|
||||
with app.app_context():
|
||||
_seed_focus_contracts()
|
||||
counts = ledger_focus_counts(session=db.session, today=date(2026, 9, 10))
|
||||
# 关键断言:即将到期 1、逾期 1、待补充 1、本月应付为 9/14 与 9/28 两份。
|
||||
assert counts['due'] == 1
|
||||
assert counts['overdue'] == 1
|
||||
assert counts['needs_completion'] == 1
|
||||
assert counts['due_this_month'] == 2
|
||||
|
||||
|
||||
def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
"""点汇总卡后列表只返回对应合同;汇总接口不跟 keyword。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.contract_payment.ledger_focus.business_today',
|
||||
lambda today=None: today or date(2026, 9, 10),
|
||||
)
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_focus_list')
|
||||
_seed_focus_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers)
|
||||
summary = client.get('/api/contract-payment/contracts/summary', headers=headers)
|
||||
empty = client.get('/api/contract-payment/contracts?focus=overdue&keyword=NO-SUCH', headers=headers)
|
||||
# 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。
|
||||
assert overdue.status_code == 200
|
||||
data = overdue.get_json()['data']
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE'
|
||||
assert summary.get_json()['data']['overdue'] == 1
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_list.py
|
||||
|
||||
用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。
|
||||
依赖:Flask test client、ContractPaymentContract、用户功能权限。
|
||||
逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, User
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='user',
|
||||
status='active',
|
||||
real_name=f'{username}-实名',
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成测试鉴权头。"""
|
||||
return {
|
||||
'X-User-Id': str(user.id),
|
||||
'X-Username': user.username,
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def _seed_parsed_contracts() -> None:
|
||||
"""写入两份已进入台账的合同,供应商名称可区分。"""
|
||||
db.session.add_all(
|
||||
[
|
||||
ContractPaymentContract(
|
||||
contract_no='HT-20260903-30622-0',
|
||||
workflow_no='5203-2609020001',
|
||||
purchase_order_no='5203-2609020001',
|
||||
supplier_name='诺亘(上海)工业自动化有限公司',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
ContractPaymentContract(
|
||||
contract_no='HT-20260903-30612-0',
|
||||
workflow_no='5203-2608270005',
|
||||
purchase_order_no='5203-2608270005',
|
||||
supplier_name='无锡市质谨机电科技有限公司',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
]
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_list_contracts_filters_by_supplier_name(client, app):
|
||||
"""关键词命中供应商名称时只返回对应合同,不误伤其他供应商。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_list_supplier')
|
||||
_seed_parsed_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
res = client.get('/api/contract-payment/contracts?keyword=诺亘', headers=headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()['data']
|
||||
# 关键断言:供应商模糊匹配生效,且仍走 parsed 台账口径。
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['supplier_name'] == '诺亘(上海)工业自动化有限公司'
|
||||
assert data['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
|
||||
|
||||
def test_list_contracts_keyword_still_matches_contract_and_po(client, app):
|
||||
"""合同号、采购单号原有检索不能被供应商筛选挤掉。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_list_keyword')
|
||||
_seed_parsed_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
by_po = client.get('/api/contract-payment/contracts?keyword=5203-2608270005', headers=headers)
|
||||
by_contract = client.get('/api/contract-payment/contracts?keyword=HT-20260903-30622-0', headers=headers)
|
||||
# 关键断言:原合同号/采购单号路径仍精确命中。
|
||||
assert by_po.get_json()['data']['total'] == 1
|
||||
assert by_po.get_json()['data']['items'][0]['purchase_order_no'] == '5203-2608270005'
|
||||
assert by_contract.get_json()['data']['total'] == 1
|
||||
assert by_contract.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_parse.py
|
||||
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配及周汇总摘要。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信。
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
@@ -17,10 +17,17 @@ from app.models import (
|
||||
ContractPaymentNode,
|
||||
User,
|
||||
)
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.services.contract_payment.alert_service import (
|
||||
bind_contract_owner_from_applicant,
|
||||
build_weekly_alert_summary,
|
||||
generate_alerts,
|
||||
_alert_status_label,
|
||||
_build_excel,
|
||||
_recipient_display_name,
|
||||
)
|
||||
from app.services.contract_payment import parse_service
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
|
||||
@@ -549,6 +556,81 @@ def test_weekly_alert_summary_counts_pending_and_next_friday(app):
|
||||
assert at_send_time["next_send_at"] == "2026-09-11T10:00:00Z"
|
||||
|
||||
|
||||
def test_weekly_excel_writes_recipient_real_name_not_role(app):
|
||||
"""关键断言:企微 Excel 列名为「收件人」,单元格写系统用户真实姓名,不再写岗位名称。"""
|
||||
with app.app_context():
|
||||
owner = User(
|
||||
username="excel-owner",
|
||||
email="excel-owner@example.com",
|
||||
status="active",
|
||||
real_name="张三",
|
||||
)
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-EXCEL-1",
|
||||
purchase_order_no="PO-1",
|
||||
supplier_name="苏州供应商",
|
||||
owner_user_id=owner.id,
|
||||
status="active",
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
node = ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code="shipment",
|
||||
node_type="shipment",
|
||||
status="active",
|
||||
due_date=date(2026, 9, 1),
|
||||
)
|
||||
db.session.add(node)
|
||||
db.session.flush()
|
||||
alert = ContractPaymentAlert(
|
||||
contract_id=contract.id,
|
||||
node_id=node.id,
|
||||
trigger_key="round:1:date:2026-09-01",
|
||||
recipient_user_id=owner.id,
|
||||
alert_round=1,
|
||||
status="pending",
|
||||
)
|
||||
db.session.add(alert)
|
||||
db.session.commit()
|
||||
|
||||
data, summary = _build_excel([(alert, contract, node, owner)])
|
||||
wb = load_workbook(BytesIO(data))
|
||||
headers = [cell.value for cell in wb.active[1]]
|
||||
row = [cell.value for cell in wb.active[2]]
|
||||
|
||||
assert "收件岗位" not in headers
|
||||
assert headers[10] == "收件人"
|
||||
assert row[10] == "张三"
|
||||
assert row[11] == "待发送"
|
||||
assert "pending" not in row
|
||||
assert "采购负责人" not in row
|
||||
assert summary["total"] == 1
|
||||
|
||||
|
||||
def test_recipient_display_name_falls_back_to_username(app):
|
||||
"""关键断言:真实姓名为空时 Excel 收件人回退用户名,而不是岗位标签。"""
|
||||
with app.app_context():
|
||||
named = User(username="buyer", email="named@example.com", status="active", real_name="李采购")
|
||||
unnamed = User(username="buyer02", email="unnamed@example.com", status="active", real_name=" ")
|
||||
|
||||
assert _recipient_display_name(named) == "李采购"
|
||||
assert _recipient_display_name(unnamed) == "buyer02"
|
||||
assert _recipient_display_name(None) == "—"
|
||||
|
||||
|
||||
def test_alert_status_label_uses_chinese():
|
||||
"""关键断言:Excel 状态列把 pending/sent/failed 写成中文,未知码保留原文。"""
|
||||
assert _alert_status_label("pending") == "待发送"
|
||||
assert _alert_status_label("sent") == "已发送"
|
||||
assert _alert_status_label("failed") == "发送失败"
|
||||
assert _alert_status_label("resolved") == "已关闭"
|
||||
assert _alert_status_label("unknown-code") == "unknown-code"
|
||||
assert _alert_status_label(None) == "—"
|
||||
|
||||
|
||||
def test_erp_payment_amount_matches_the_corresponding_stage():
|
||||
"""关键断言:不同金额的 ERP 付款必须分别匹配同金额付款阶段。"""
|
||||
paid_node_ids = resolve_paid_node_ids(
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_permissions.py
|
||||
|
||||
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
|
||||
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账;关闭 admin 覆盖后同样 403。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -128,3 +128,23 @@ def test_contract_payment_api_allows_granted_user(client, app):
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_contract_payment_jobs_require_admin(client, app):
|
||||
"""已授权的普通用户可查台账,但不能触发同步、扫描或周汇总发送。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_jobs_denied',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
# 关键断言:访问权不等于操作权,手动任务仅管理员。
|
||||
for path in (
|
||||
'/api/contract-payment/sync',
|
||||
'/api/contract-payment/alerts/run',
|
||||
'/api/contract-payment/alerts/weekly-run',
|
||||
):
|
||||
res = client.post(path, headers=headers, json={})
|
||||
assert res.status_code == 403, path
|
||||
assert _json_error(res)['code'] == 'CONTRACT_PAYMENT.ADMIN_REQUIRED'
|
||||
Reference in new issue
Block a user