221 lines
8.0 KiB
Python
221 lines
8.0 KiB
Python
"""
|
|
backend/app/services/contract_payment/ledger_focus.py
|
|
|
|
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
|
依赖: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_ACTIVE = "active"
|
|
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
|
|
LEDGER_FOCUS_VALUES = {
|
|
LEDGER_FOCUS_DUE,
|
|
LEDGER_FOCUS_OVERDUE,
|
|
LEDGER_FOCUS_ACTIVE,
|
|
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 "needs_completion"
|
|
if not node_list:
|
|
return "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 "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 LEDGER_FOCUS_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;待确认合同不进入台账汇总。未到期为付款日在 7 日以外且未逾期的未付合同;本月应付可与即将到期、逾期或未到期重叠。
|
|
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_ACTIVE: 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_ACTIVE:
|
|
buckets[LEDGER_FOCUS_ACTIVE].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 / active / 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))
|