feat: 合同付款预警迁移到agent页面
This commit is contained in:
1 parent
ef6bc42c20
commit
4ce2defef0
49 files changed
+1052
-423
No files matched your search
@@ -2,10 +2,10 @@
|
||||
backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.core.response import ok
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent,
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentAlertBatch,
|
||||
ContractPaymentAttachment,
|
||||
@@ -41,6 +42,8 @@ from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
contract_payment_bp = Blueprint("contract_payment", __name__)
|
||||
|
||||
CONTRACT_PAYMENT_AGENT_CODE = "contract_payment"
|
||||
|
||||
|
||||
def _attachment_parse_priority(attachment: ContractPaymentAttachment) -> tuple[int, int]:
|
||||
"""
|
||||
@@ -74,35 +77,45 @@ def _require_user():
|
||||
return user
|
||||
|
||||
|
||||
def _user_has_contract_payment_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的合同付款预警 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=CONTRACT_PAYMENT_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_contract_payment_access():
|
||||
"""
|
||||
确保当前用户已登录且具备合同付款预警访问权限。
|
||||
|
||||
核心逻辑:登录校验之后读取 `contract_payment.access`;admin 角色默认具备,
|
||||
其他角色需在用户管理中显式授予。无权限时返回业务 403,而不是静默空数据。
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=contract_payment` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证且具备合同付款预警访问权限的用户。
|
||||
已认证且具备合同付款预警 Agent 授权(或 admin)的用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有 `contract_payment.access`。
|
||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not user.can_access_contract_payment():
|
||||
raise ForbiddenError(
|
||||
'Contract payment access required',
|
||||
code='CONTRACT_PAYMENT.FORBIDDEN',
|
||||
)
|
||||
return user
|
||||
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
'Contract payment agent permission required',
|
||||
code='CONTRACT_PAYMENT.FORBIDDEN',
|
||||
)
|
||||
|
||||
|
||||
def _require_contract_payment_admin():
|
||||
"""
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
|
||||
Args:
|
||||
@@ -262,7 +275,7 @@ def get_ledger_summary():
|
||||
Args:
|
||||
无。
|
||||
Returns:
|
||||
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
|
||||
标准成功 envelope,含 due、overdue、active、due_this_month。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
|
||||
|
||||
@@ -96,8 +96,6 @@ class User(Base):
|
||||
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
|
||||
# 合同付款预警工作台:admin 默认开;不新建角色,可给采购同事单独授予
|
||||
'contract_payment.access': self.role == 'admin',
|
||||
}
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
@@ -105,7 +103,7 @@ class User(Base):
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训、合同付款等业务权限硬编码在多个模块。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训等业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -123,7 +121,7 @@ class User(Base):
|
||||
保存用户显式配置的功能权限覆盖项。
|
||||
|
||||
用途:给管理后台用户编辑表单落库权限配置。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -145,10 +143,6 @@ class User(Base):
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def can_access_contract_payment(self) -> bool:
|
||||
"""判断当前用户是否可查看合同付款预警工作台并触发同步/扫描。"""
|
||||
return self.has_feature_permission('contract_payment.access')
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -12,5 +12,6 @@ from __future__ import annotations
|
||||
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
|
||||
'shipping_notice': 'shipping_notice',
|
||||
'file_check': 'file_check',
|
||||
'contract_payment': 'contract_payment',
|
||||
'in_transit_transfer': 'in_transit_transfer',
|
||||
}
|
||||
@@ -129,6 +129,22 @@ agent_types:
|
||||
file_upload: true
|
||||
human_confirm: false
|
||||
handler_config_schema: {}
|
||||
contract_payment:
|
||||
label: 合同付款预警
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: builtin
|
||||
models:
|
||||
- ContractPaymentContract
|
||||
- ContractPaymentAlert
|
||||
- ContractPaymentAlertBatch
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
streaming: false
|
||||
file_upload: false
|
||||
task_progress: false
|
||||
forced_capabilities:
|
||||
file_upload: false
|
||||
handler_config_schema: {}
|
||||
in_transit_transfer:
|
||||
label: 在途仓自动调拨
|
||||
conversation_mode_default: task_chat
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/agent_registry/handlers/bootstrap.py
|
||||
|
||||
用途:应用启动时加载 HANDLER_REGISTRY。
|
||||
依赖:handlers.shipping_notice 等领域 handler 模块。
|
||||
依赖:handlers.shipping_notice、handlers.contract_payment 等领域 handler 模块。
|
||||
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
|
||||
"""
|
||||
|
||||
@@ -29,12 +29,14 @@ def load_handlers() -> None:
|
||||
|
||||
import importlib
|
||||
|
||||
import app.services.agent_registry.handlers.contract_payment as contract_payment_mod
|
||||
import app.services.agent_registry.handlers.file_check as file_check_mod
|
||||
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
|
||||
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
|
||||
|
||||
importlib.reload(file_check_mod)
|
||||
importlib.reload(shipping_mod)
|
||||
importlib.reload(contract_payment_mod)
|
||||
importlib.reload(in_transit_transfer_mod)
|
||||
|
||||
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/contract_payment.py
|
||||
|
||||
用途:合同付款预警 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
|
||||
依赖:agent_registry.handlers.base / registry。
|
||||
逻辑:Chat 主区渲染台账 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
|
||||
from app.services.agent_registry.handlers.registry import register_handler
|
||||
|
||||
|
||||
@register_handler('contract_payment')
|
||||
class ContractPaymentHandler(AgentHandler):
|
||||
"""
|
||||
合同付款预警业务 Handler。
|
||||
|
||||
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入合同摘要。
|
||||
"""
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
"""第一期无领域 UI State;台账由独立 HTTP API 加载。"""
|
||||
return None
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/ledger_focus.py
|
||||
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、进行中、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/进行中互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,12 +20,12 @@ from app.models import ContractPaymentContract, ContractPaymentNode
|
||||
|
||||
LEDGER_FOCUS_DUE = "due"
|
||||
LEDGER_FOCUS_OVERDUE = "overdue"
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
|
||||
LEDGER_FOCUS_ACTIVE = "active"
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
|
||||
LEDGER_FOCUS_VALUES = {
|
||||
LEDGER_FOCUS_DUE,
|
||||
LEDGER_FOCUS_OVERDUE,
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION,
|
||||
LEDGER_FOCUS_ACTIVE,
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH,
|
||||
}
|
||||
_NEAR_DUE_DAYS = 7
|
||||
@@ -68,7 +68,7 @@ def classify_ledger_status(
|
||||
"""
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
|
||||
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
@@ -80,16 +80,16 @@ def classify_ledger_status(
|
||||
"""
|
||||
node_list = list(nodes)
|
||||
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
return "needs_completion"
|
||||
if not node_list:
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
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 LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
return "completed" if has_paid else "needs_completion"
|
||||
refs = [
|
||||
ref
|
||||
for node in active
|
||||
@@ -99,7 +99,7 @@ def classify_ledger_status(
|
||||
return LEDGER_FOCUS_OVERDUE
|
||||
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
|
||||
return LEDGER_FOCUS_DUE
|
||||
return "active"
|
||||
return LEDGER_FOCUS_ACTIVE
|
||||
|
||||
|
||||
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
|
||||
@@ -138,7 +138,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
"""
|
||||
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
|
||||
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。进行中为未到期且未逾期的未付合同;本月应付可与即将到期、逾期或进行中重叠。
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
@@ -154,7 +154,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
buckets: dict[str, set[int]] = {
|
||||
LEDGER_FOCUS_DUE: set(),
|
||||
LEDGER_FOCUS_OVERDUE: set(),
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
|
||||
LEDGER_FOCUS_ACTIVE: set(),
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
|
||||
}
|
||||
if not contracts:
|
||||
@@ -180,8 +180,8 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
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)
|
||||
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
|
||||
@@ -195,7 +195,7 @@ def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
due / overdue / needs_completion / due_this_month 的计数。
|
||||
due / overdue / active / due_this_month 的计数。
|
||||
"""
|
||||
buckets = collect_ledger_focus(session=session, today=today)
|
||||
return {key: len(ids) for key, ids in buckets.items()}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Seed contract_payment Chat Agent and migrate feature-permission grants.
|
||||
|
||||
Revision ID: cp8a9b0c1d2e
|
||||
Revises: fb26bc033d27
|
||||
Create Date: 2026-09-15 17:50:00.000000
|
||||
|
||||
用途:为合同付款预警注册 builtin Chat Agent,并把旧功能权限 `contract_payment.access`
|
||||
迁移为 user_agent_permissions;随后从 users.feature_permissions 去掉该键。
|
||||
依赖:agents、users、user_agent_permissions 表已存在。
|
||||
逻辑:先按 agent_code 复用已有实例(含停用);没有则插入。插入前把 agents.id
|
||||
序列对齐 MAX(id),避免本地库序列落后时撞主键。显式勾选过访问权的普通用户
|
||||
获得该 Agent;admin 仍按运行时角色看到全部 Agent,不必写关联表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
revision = "cp8a9b0c1d2e"
|
||||
down_revision = "fb26bc033d27"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
AGENT_CODE = "contract_payment"
|
||||
|
||||
|
||||
def _resync_agents_id_sequence() -> None:
|
||||
"""把 agents 主键序列对齐现有最大 id,避免 nextval 撞上已占用主键。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
op.execute(
|
||||
"""
|
||||
SELECT setval(
|
||||
pg_get_serial_sequence('public.agents', 'id'),
|
||||
COALESCE((SELECT MAX(id) FROM public.agents), 1),
|
||||
true
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _write_feature_permissions(conn, user_id: int, permissions: dict) -> None:
|
||||
"""把功能权限 JSON 写回 users;psycopg2 不能直接绑定 Python dict。"""
|
||||
conn.execute(
|
||||
text(
|
||||
"UPDATE users SET feature_permissions = CAST(:perms AS JSON) "
|
||||
"WHERE id = :user_id"
|
||||
),
|
||||
{"perms": json.dumps(permissions, ensure_ascii=False), "user_id": user_id},
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""插入或复用合同付款预警 Agent,并把旧功能权限授予改写为 Agent 授权。"""
|
||||
conn = op.get_bind()
|
||||
agent_id = conn.execute(
|
||||
text(
|
||||
"SELECT id FROM agents WHERE agent_code = :code "
|
||||
"ORDER BY id ASC LIMIT 1"
|
||||
),
|
||||
{"code": AGENT_CODE},
|
||||
).scalar()
|
||||
if agent_id is not None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE agents
|
||||
SET is_active = true,
|
||||
runtime_provider = 'builtin',
|
||||
conversation_mode = 'task_chat',
|
||||
dify_app_type = 'chatflow',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = :agent_id
|
||||
"""
|
||||
),
|
||||
{"agent_id": agent_id},
|
||||
)
|
||||
else:
|
||||
_resync_agents_id_sequence()
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO agents (
|
||||
name, description, type, is_active, is_aggregate,
|
||||
agent_code, runtime_provider, conversation_mode, dify_app_type,
|
||||
suggested_questions_style, sort_order, created_at, updated_at
|
||||
) VALUES (
|
||||
:name, :description, 'api', true, false,
|
||||
:code, 'builtin', 'task_chat', 'chatflow',
|
||||
'plain', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"name": "合同付款预警",
|
||||
"description": "查看采购合同台账、待确认项和周五付款预警汇总。",
|
||||
"code": AGENT_CODE,
|
||||
},
|
||||
)
|
||||
agent_id = conn.execute(
|
||||
text(
|
||||
"SELECT id FROM agents WHERE agent_code = :code AND is_active = true "
|
||||
"ORDER BY id ASC LIMIT 1"
|
||||
),
|
||||
{"code": AGENT_CODE},
|
||||
).scalar()
|
||||
|
||||
users = conn.execute(text("SELECT id, feature_permissions FROM users")).fetchall()
|
||||
for user_id, raw_permissions in users:
|
||||
permissions = raw_permissions if isinstance(raw_permissions, dict) else {}
|
||||
granted = bool(permissions.get("contract_payment.access"))
|
||||
if granted and agent_id is not None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO user_agent_permissions (user_id, agent_id)
|
||||
SELECT :user_id, :agent_id
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM user_agent_permissions
|
||||
WHERE user_id = :user_id AND agent_id = :agent_id
|
||||
)
|
||||
"""
|
||||
),
|
||||
{"user_id": user_id, "agent_id": agent_id},
|
||||
)
|
||||
if "contract_payment.access" in permissions:
|
||||
cleaned = {
|
||||
key: value
|
||||
for key, value in permissions.items()
|
||||
if key != "contract_payment.access"
|
||||
}
|
||||
_write_feature_permissions(conn, user_id, cleaned)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复功能权限键;不删除已创建的 Agent 实例,以免误伤运营配置。"""
|
||||
conn = op.get_bind()
|
||||
agent_id = conn.execute(
|
||||
text(
|
||||
"SELECT id FROM agents WHERE agent_code = :code "
|
||||
"ORDER BY id ASC LIMIT 1"
|
||||
),
|
||||
{"code": AGENT_CODE},
|
||||
).scalar()
|
||||
if agent_id is None:
|
||||
return
|
||||
granted_user_ids = conn.execute(
|
||||
text("SELECT user_id FROM user_agent_permissions WHERE agent_id = :agent_id"),
|
||||
{"agent_id": agent_id},
|
||||
).fetchall()
|
||||
for (user_id,) in granted_user_ids:
|
||||
row = conn.execute(
|
||||
text("SELECT feature_permissions FROM users WHERE id = :user_id"),
|
||||
{"user_id": user_id},
|
||||
).fetchone()
|
||||
permissions = dict(row[0] if row and isinstance(row[0], dict) else {})
|
||||
permissions["contract_payment.access"] = True
|
||||
_write_feature_permissions(conn, user_id, permissions)
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"""合并合同付款 Chat Agent 与立账凭证 PO 打印两条 Alembic 头。
|
||||
|
||||
用途:invoice-check 合入 dev 后,``vc4e5f6a7b8c`` 与 ``cp8a9b0c1d2e`` 并列成双 head,
|
||||
导致 ``flask db upgrade`` 无法解析默认 ``head``。
|
||||
依赖:``cp8a9b0c1d2e``(合同付款预警 Chat Agent seed)、
|
||||
``vc4e5f6a7b8c``(立账凭证 PO 订单生成周批 seed)。
|
||||
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "cp9b0c1d2e3f"
|
||||
down_revision = ("cp8a9b0c1d2e", "vc4e5f6a7b8c")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并合同付款 Agent seed 与 PO 打印排程 seed,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -19,7 +19,7 @@ def test_agent_type_catalog_contains_three_seed_types():
|
||||
"""Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。"""
|
||||
assert {
|
||||
'generic', 'shipping_notice', 'file_check',
|
||||
'procurement_contract_review', 'in_transit_transfer',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment',
|
||||
} <= set(AGENT_TYPE_CATALOG.keys())
|
||||
|
||||
|
||||
@@ -28,12 +28,13 @@ def test_list_type_catalog_includes_agent_code_and_label():
|
||||
catalog = list_type_catalog()
|
||||
assert len(catalog) >= 5
|
||||
codes = {entry['agent_code'] for entry in catalog}
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer'} <= codes
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment'} <= codes
|
||||
labels = {entry['label'] for entry in catalog}
|
||||
assert '通用问答 / 知识库' in labels
|
||||
assert '在途仓自动调拨' in labels
|
||||
assert '货代发货通知' in labels
|
||||
assert '文件检核' in labels
|
||||
assert '合同付款预警' in labels
|
||||
|
||||
|
||||
def test_get_catalog_entry_returns_runtime_handler_for_hybrid_types():
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_contract_payment.py
|
||||
|
||||
用途:验证 contract_payment 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.agent_registry import catalog_bindings
|
||||
from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_contract_payment_type_in_catalog():
|
||||
"""catalog 必须包含 contract_payment,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('contract_payment')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '合同付款预警'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 contract_payment 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['contract_payment'] == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 ContractPaymentHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('contract_payment')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'contract_payment'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_contract_payment_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'contract_payment' in catalog
|
||||
assert 'shipping_notice' in catalog
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_ledger_focus.py
|
||||
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,12 +11,12 @@ from __future__ import annotations
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -26,9 +26,22 @@ def _create_user(*, username: str) -> User:
|
||||
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.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
@@ -76,7 +89,8 @@ def _seed_focus_contracts() -> None:
|
||||
_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')
|
||||
active = _add_contract(contract_no='HT-FOCUS-ACTIVE')
|
||||
_add_node(active, due=date(2026, 11, 1))
|
||||
month = _add_contract(contract_no='HT-FOCUS-MONTH')
|
||||
_add_node(month, due=date(2026, 9, 28))
|
||||
db.session.commit()
|
||||
@@ -87,10 +101,10 @@ 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 两份。
|
||||
# 关键断言:即将到期 1、逾期 1、进行中 2(11/1 与 9/28)、本月应付为 9/14 与 9/28 两份。
|
||||
assert counts['due'] == 1
|
||||
assert counts['overdue'] == 1
|
||||
assert counts['needs_completion'] == 1
|
||||
assert counts['active'] == 2
|
||||
assert counts['due_this_month'] == 2
|
||||
|
||||
|
||||
@@ -106,12 +120,19 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
|
||||
headers = _auth_headers(user)
|
||||
overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers)
|
||||
active = client.get('/api/contract-payment/contracts?focus=active', 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)
|
||||
# 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。
|
||||
# 关键断言:逾期卡只筛出逾期合同;进行中含未到期的 11/1 与本月 9/28;汇总仍看全量台账。
|
||||
assert overdue.status_code == 200
|
||||
data = overdue.get_json()['data']
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE'
|
||||
assert {item['contract_no'] for item in active.get_json()['data']['items']} == {
|
||||
'HT-FOCUS-ACTIVE',
|
||||
'HT-FOCUS-MONTH',
|
||||
}
|
||||
assert summary.get_json()['data']['overdue'] == 1
|
||||
assert summary.get_json()['data']['active'] == 2
|
||||
assert 'needs_completion' not in summary.get_json()['data']
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
@@ -2,18 +2,18 @@
|
||||
backend/tests/test_contract_payment_list.py
|
||||
|
||||
用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。
|
||||
依赖:Flask test client、ContractPaymentContract、用户功能权限。
|
||||
依赖:Flask test client、ContractPaymentContract、Agent 授权。
|
||||
逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, User
|
||||
from app.models import Agent, ContractPaymentContract, User
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户,供列表接口走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -23,9 +23,22 @@ def _create_user(*, username: str) -> User:
|
||||
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.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
|
||||
@@ -1,31 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_permissions.py
|
||||
|
||||
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
|
||||
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。
|
||||
用途:验收合同付款预警改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 无需绑定即可查询;普通用户默认 403;授予 contract_payment Agent 后可查询台账,
|
||||
但不能触发同步/扫描/发送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _make_memory_user(*, role: str, overrides: dict | None = None) -> User:
|
||||
"""构造带功能权限覆盖的内存用户(不落库,仅测 has_feature_permission)。"""
|
||||
user = User(username=f'cp-{role}', role=role)
|
||||
if overrides is not None:
|
||||
user.feature_permissions = overrides
|
||||
return user
|
||||
|
||||
|
||||
def _create_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = 'user',
|
||||
feature_permissions: dict | None = None,
|
||||
) -> User:
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
"""创建落库用户,供 contract-payment API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
@@ -36,11 +24,39 @@ def _create_user(
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions(feature_permissions)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _ensure_contract_payment_agent() -> Agent:
|
||||
"""确保存在启用中的合同付款预警 Agent,供授权绑定。"""
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if agent:
|
||||
return agent
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _grant_contract_payment_agent(user: User) -> User:
|
||||
"""把合同付款预警 Agent 授权给指定用户并重新取出,避免会话分离后丢失关系。"""
|
||||
agent = _ensure_contract_payment_agent()
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
@@ -62,49 +78,16 @@ def _json_error(response) -> dict:
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_admin_default_has_contract_payment_access(app):
|
||||
"""admin 角色默认具备 contract_payment.access;普通用户默认无。"""
|
||||
with app.app_context():
|
||||
admin = _make_memory_user(role='admin')
|
||||
user = _make_memory_user(role='user')
|
||||
# 关键断言:不新建角色,仅功能键裁剪工作台访问。
|
||||
assert admin.can_access_contract_payment() is True
|
||||
assert user.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_explicit_grant_and_revoke_contract_payment_access(app):
|
||||
"""普通用户可被显式授予;admin 可被显式关闭。"""
|
||||
with app.app_context():
|
||||
granted = _make_memory_user(role='user', overrides={'contract_payment.access': True})
|
||||
revoked_admin = _make_memory_user(role='admin', overrides={'contract_payment.access': False})
|
||||
# 关键断言:显式覆盖优先于角色默认。
|
||||
assert granted.can_access_contract_payment() is True
|
||||
assert revoked_admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_set_feature_permissions_persists_contract_payment_override(app):
|
||||
"""用户表单保存时只持久化与角色默认值不同的 contract_payment.access。"""
|
||||
with app.app_context():
|
||||
user = User(username='cp-override', role='user')
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
# 关键断言:未知键被忽略,已知覆盖项写入 JSON。
|
||||
assert user.feature_permissions == {'contract_payment.access': True}
|
||||
assert user.can_access_contract_payment() is True
|
||||
|
||||
admin = User(username='cp-admin-override', role='admin')
|
||||
admin.set_feature_permissions({'contract_payment.access': False})
|
||||
assert admin.feature_permissions == {'contract_payment.access': False}
|
||||
assert admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
"""无权限用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
def test_contract_payment_api_forbids_user_without_agent(client, app):
|
||||
"""未授予 Agent 的普通用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='cp_api_denied')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(ordinary)
|
||||
|
||||
headers = _auth_headers(ordinary)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:登录不足够,专项权限缺失必须 403。
|
||||
# 关键断言:登录不足够,Agent 授权缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'CONTRACT_PAYMENT.FORBIDDEN'
|
||||
|
||||
@@ -114,29 +97,36 @@ def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_granted_user(client, app):
|
||||
"""显式授予后普通用户可以查询台账。"""
|
||||
"""授予 contract_payment Agent 后普通用户可以查询台账。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_granted',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_granted'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:授予后不再 403,返回标准成功 envelope。
|
||||
# 关键断言:Agent 授权后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_admin_without_agent_binding(client, app):
|
||||
"""平台 admin 即使未绑定该 Agent 也可查询台账。"""
|
||||
with app.app_context():
|
||||
admin = _create_user(username='cp_api_admin', role='admin')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(admin)
|
||||
|
||||
headers = _auth_headers(admin)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
assert list_res.status_code == 200
|
||||
assert list_res.get_json().get('success') is True
|
||||
|
||||
|
||||
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},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_jobs_denied'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
# 关键断言:访问权不等于操作权,手动任务仅管理员。
|
||||
|
||||
Reference in new issue
Block a user