290 lines
11 KiB
Python
290 lines
11 KiB
Python
"""
|
||
backend/app/services/procurement_contract/rule_service.py
|
||
|
||
Purpose: Manage procurement contract risk rules used by compare and solo review.
|
||
Dependencies: ContractRiskRule model, SQLAlchemy session, unified AppError classes.
|
||
Flow: Admin CRUD persists configurable red-line rules; review_service loads enabled rules for analysis.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Any
|
||
from uuid import uuid4
|
||
|
||
from app import db
|
||
from app.core.errors import NotFoundError, ValidationError
|
||
from app.core.response import utc_iso
|
||
from app.models import ContractRiskRule
|
||
|
||
DEFAULT_CONTRACT_TYPE = "general_procurement"
|
||
VALID_RISK_LEVELS = {"high", "medium", "low"}
|
||
VALID_STATUS = {"enabled", "disabled"}
|
||
VALID_TRIGGER_TYPES = {"keyword_missing", "keyword_present"}
|
||
# Keep categories stable because they drive result grouping, de-duplication and policy replacement.
|
||
VALID_CLAUSE_CATEGORIES = {
|
||
"payment",
|
||
"delivery",
|
||
"acceptance",
|
||
"warranty",
|
||
"liability",
|
||
"jurisdiction",
|
||
"dispute",
|
||
"ip",
|
||
"other",
|
||
}
|
||
BUILTIN_RULE_CODES = {
|
||
"payment_acceptance_required",
|
||
"acceptance_process_required",
|
||
"liability_required",
|
||
"jurisdiction_required",
|
||
"warranty_required",
|
||
}
|
||
|
||
|
||
def serialize_rule(row: ContractRiskRule) -> dict[str, Any]:
|
||
"""Convert a risk rule ORM row into API response data."""
|
||
return {
|
||
"id": row.id,
|
||
"code": row.code,
|
||
"rule_kind": "builtin" if row.code in BUILTIN_RULE_CODES else "custom",
|
||
"contract_type": row.contract_type,
|
||
"clause_category": row.clause_category,
|
||
"title": row.title,
|
||
"keywords": row.keywords or [],
|
||
"trigger_type": row.trigger_type,
|
||
"risk_level": row.risk_level,
|
||
"risk_hint": row.risk_hint,
|
||
"suggestion": row.suggestion,
|
||
"negotiation_text": row.negotiation_text,
|
||
"status": row.status,
|
||
"sort_order": row.sort_order,
|
||
"created_at": utc_iso(row.created_at),
|
||
"updated_at": utc_iso(row.updated_at),
|
||
}
|
||
|
||
|
||
def _normalize_keywords(raw: Any) -> list[str]:
|
||
"""Normalize JSON/list/string keywords into a unique non-empty string list."""
|
||
if isinstance(raw, str):
|
||
items = [p.strip() for p in raw.replace(",", ",").split(",")]
|
||
elif isinstance(raw, list):
|
||
items = [str(p).strip() for p in raw]
|
||
else:
|
||
items = []
|
||
seen: set[str] = set()
|
||
result: list[str] = []
|
||
for item in items:
|
||
if item and item not in seen:
|
||
seen.add(item)
|
||
result.append(item)
|
||
return result
|
||
|
||
|
||
def _validate_clause_category(category: str) -> str:
|
||
"""
|
||
Validate and normalize a rule category used by the contract analyzer.
|
||
|
||
Args:
|
||
category: Stable category code selected in the admin form; free-form labels are not supported.
|
||
|
||
Returns:
|
||
A validated category code.
|
||
|
||
Raises:
|
||
ValidationError: If the category cannot participate in result grouping safely.
|
||
"""
|
||
normalized = category.strip().lower()
|
||
if normalized not in VALID_CLAUSE_CATEGORIES:
|
||
raise ValidationError("invalid clause_category")
|
||
return normalized
|
||
|
||
|
||
def _generate_custom_rule_code(category: str) -> str:
|
||
"""
|
||
Generate an opaque code for a custom keyword rule.
|
||
|
||
The code is an internal identifier only. Generating it server-side prevents administrators from
|
||
accidentally using a built-in code that carries compound business logic.
|
||
|
||
Args:
|
||
category: Validated clause category used to make the generated code traceable.
|
||
|
||
Returns:
|
||
Globally unique custom rule code.
|
||
"""
|
||
return f"custom_{category}_{uuid4().hex[:12]}"
|
||
|
||
|
||
def list_rules(
|
||
*,
|
||
contract_type: str | None = None,
|
||
status: str | None = None,
|
||
clause_category: str | None = None,
|
||
) -> list[dict[str, Any]]:
|
||
"""List risk rules with optional filters."""
|
||
q = db.session.query(ContractRiskRule)
|
||
if contract_type:
|
||
q = q.filter(ContractRiskRule.contract_type == contract_type)
|
||
if status:
|
||
q = q.filter(ContractRiskRule.status == status)
|
||
if clause_category:
|
||
q = q.filter(ContractRiskRule.clause_category == clause_category)
|
||
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
|
||
return [serialize_rule(r) for r in rows]
|
||
|
||
|
||
def get_enabled_rules(contract_type: str | None = None) -> list[dict[str, Any]]:
|
||
"""
|
||
Load enabled rules for analysis.
|
||
Rules for the requested contract type are used first; general procurement rules are included as fallback.
|
||
"""
|
||
normalized = (contract_type or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE
|
||
q = db.session.query(ContractRiskRule).filter(ContractRiskRule.status == "enabled")
|
||
if normalized != DEFAULT_CONTRACT_TYPE:
|
||
q = q.filter(ContractRiskRule.contract_type.in_([normalized, DEFAULT_CONTRACT_TYPE]))
|
||
else:
|
||
q = q.filter(ContractRiskRule.contract_type == DEFAULT_CONTRACT_TYPE)
|
||
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
|
||
return [serialize_rule(r) for r in rows]
|
||
|
||
|
||
def create_rule(*, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||
"""
|
||
Create a custom keyword-based contract risk rule.
|
||
|
||
Built-in codes are reserved for compound procurement checks. Custom rules receive an internal
|
||
generated code so their keywords cannot accidentally change a built-in rule's semantics.
|
||
|
||
Args:
|
||
user_id: Administrator creating the rule.
|
||
data: Rule display fields, category, keywords and trigger configuration; code is optional.
|
||
|
||
Returns:
|
||
Serialized newly created rule.
|
||
|
||
Raises:
|
||
ValidationError: If category, keywords or enum fields are invalid, or a built-in code is supplied.
|
||
"""
|
||
code = str(data.get("code") or "").strip()
|
||
title = str(data.get("title") or "").strip()
|
||
category = _validate_clause_category(str(data.get("clause_category") or ""))
|
||
risk_level = str(data.get("risk_level") or "").strip()
|
||
risk_hint = str(data.get("risk_hint") or "").strip()
|
||
suggestion = str(data.get("suggestion") or "").strip()
|
||
keywords = _normalize_keywords(data.get("keywords"))
|
||
trigger_type = str(data.get("trigger_type") or "keyword_missing").strip()
|
||
status = str(data.get("status") or "enabled").strip()
|
||
if not title:
|
||
raise ValidationError("title is required")
|
||
if not keywords:
|
||
raise ValidationError("keywords are required")
|
||
if risk_level not in VALID_RISK_LEVELS:
|
||
raise ValidationError("invalid risk_level")
|
||
if trigger_type not in VALID_TRIGGER_TYPES:
|
||
raise ValidationError("invalid trigger_type")
|
||
if status not in VALID_STATUS:
|
||
raise ValidationError("invalid status")
|
||
if code:
|
||
if code in BUILTIN_RULE_CODES:
|
||
raise ValidationError("built-in rule code is reserved")
|
||
raise ValidationError("custom rule code is generated by server")
|
||
code = _generate_custom_rule_code(category)
|
||
exists = db.session.query(ContractRiskRule).filter(ContractRiskRule.code == code).first()
|
||
if exists:
|
||
raise ValidationError("rule code already exists")
|
||
row = ContractRiskRule(
|
||
code=code,
|
||
contract_type=str(data.get("contract_type") or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE,
|
||
clause_category=category,
|
||
title=title,
|
||
keywords=keywords,
|
||
trigger_type=trigger_type,
|
||
risk_level=risk_level,
|
||
risk_hint=risk_hint,
|
||
suggestion=suggestion,
|
||
negotiation_text=(str(data.get("negotiation_text") or "").strip() or None),
|
||
status=status,
|
||
sort_order=int(data.get("sort_order") or 100),
|
||
created_by=user_id,
|
||
updated_by=user_id,
|
||
)
|
||
db.session.add(row)
|
||
db.session.commit()
|
||
return serialize_rule(row)
|
||
|
||
|
||
def update_rule(rule_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||
"""
|
||
Update an existing risk rule without changing its detection semantics.
|
||
|
||
Built-in rules may keep editable display and risk guidance fields, but their category, keywords and
|
||
trigger remain fixed because those fields are coupled to compound analyzer logic.
|
||
|
||
Args:
|
||
rule_id: Existing rule primary key.
|
||
user_id: Administrator making the change.
|
||
data: Partial editable rule payload.
|
||
|
||
Returns:
|
||
Serialized updated rule.
|
||
|
||
Raises:
|
||
NotFoundError: If the rule does not exist.
|
||
ValidationError: If enum values are invalid or a built-in detection definition is changed.
|
||
"""
|
||
row = db.session.get(ContractRiskRule, rule_id)
|
||
if not row:
|
||
raise NotFoundError("risk rule not found")
|
||
if row.code in BUILTIN_RULE_CODES:
|
||
if "clause_category" in data and _validate_clause_category(str(data.get("clause_category") or "")) != row.clause_category:
|
||
raise ValidationError("built-in rule definition is read-only")
|
||
if "keywords" in data and _normalize_keywords(data.get("keywords")) != list(row.keywords or []):
|
||
raise ValidationError("built-in rule definition is read-only")
|
||
if "trigger_type" in data and str(data.get("trigger_type") or "").strip() != row.trigger_type:
|
||
raise ValidationError("built-in rule definition is read-only")
|
||
for key in ("contract_type", "clause_category", "title", "risk_hint", "suggestion", "negotiation_text"):
|
||
if key in data:
|
||
value = str(data.get(key) or "").strip()
|
||
if key != "negotiation_text" and not value:
|
||
raise ValidationError(f"{key} is required")
|
||
if key == "clause_category":
|
||
value = _validate_clause_category(value)
|
||
setattr(row, key, value or None)
|
||
if "keywords" in data:
|
||
keywords = _normalize_keywords(data.get("keywords"))
|
||
if not keywords:
|
||
raise ValidationError("keywords are required")
|
||
row.keywords = keywords
|
||
if "trigger_type" in data:
|
||
trigger_type = str(data.get("trigger_type") or "").strip()
|
||
if trigger_type not in VALID_TRIGGER_TYPES:
|
||
raise ValidationError("invalid trigger_type")
|
||
row.trigger_type = trigger_type
|
||
if "risk_level" in data:
|
||
risk_level = str(data.get("risk_level") or "").strip()
|
||
if risk_level not in VALID_RISK_LEVELS:
|
||
raise ValidationError("invalid risk_level")
|
||
row.risk_level = risk_level
|
||
if "status" in data:
|
||
status = str(data.get("status") or "").strip()
|
||
if status not in VALID_STATUS:
|
||
raise ValidationError("invalid status")
|
||
row.status = status
|
||
if "sort_order" in data:
|
||
row.sort_order = int(data.get("sort_order") or 100)
|
||
row.updated_by = user_id
|
||
row.updated_at = datetime.utcnow()
|
||
db.session.commit()
|
||
return serialize_rule(row)
|
||
|
||
|
||
def delete_rule(rule_id: int) -> dict[str, Any]:
|
||
"""Delete a risk rule."""
|
||
row = db.session.get(ContractRiskRule, rule_id)
|
||
if not row:
|
||
raise NotFoundError("risk rule not found")
|
||
db.session.delete(row)
|
||
db.session.commit()
|
||
return {"deleted": True, "id": rule_id}
|