294 lines
11 KiB
Python
294 lines
11 KiB
Python
"""
|
|
backend/app/services/procurement_contract/template_service.py
|
|
|
|
用途:采购合同标准模板库 CRUD、设默认、列表。
|
|
依赖:models.ContractTemplate、file_assets、db、errors。
|
|
逻辑:Admin API 调用;Chat 下拉读 enabled 列表。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from app import db
|
|
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
|
from app.core.response import utc_iso
|
|
from app.models import ContractReview, ContractTemplate, FileAsset, User
|
|
from app.services.file_assets.service import (
|
|
get_asset_for_user,
|
|
mark_asset_referenced,
|
|
read_asset_bytes,
|
|
release_asset_reference,
|
|
)
|
|
from app.services.procurement_contract import analyze
|
|
from app.services.procurement_contract.comparison_regions import (
|
|
preview_anchor_recognition,
|
|
validate_comparison_region_config,
|
|
)
|
|
|
|
|
|
def serialize_template(row: ContractTemplate) -> dict[str, Any]:
|
|
"""ORM → API dict。"""
|
|
return {
|
|
"id": row.id,
|
|
"name": row.name,
|
|
"version": row.version,
|
|
"file_name": row.file_name,
|
|
"file_asset_id": row.file_asset_id,
|
|
"contract_type": row.contract_type,
|
|
"applicable_scope": row.applicable_scope,
|
|
"change_note": row.change_note,
|
|
"comparison_region_config": row.comparison_region_config,
|
|
"status": row.status,
|
|
"is_default": bool(row.is_default),
|
|
"remark": row.remark,
|
|
"created_by": row.created_by,
|
|
"updated_by": row.updated_by,
|
|
"updated_by_name": _user_name(row.updated_by),
|
|
"created_at": utc_iso(row.created_at),
|
|
"updated_at": utc_iso(row.updated_at),
|
|
}
|
|
|
|
|
|
def list_templates(*, status: str | None = None) -> list[dict[str, Any]]:
|
|
"""列出模板;可按 status 过滤。"""
|
|
q = db.session.query(ContractTemplate)
|
|
if status:
|
|
q = q.filter(ContractTemplate.status == status)
|
|
rows = q.order_by(ContractTemplate.is_default.desc(), ContractTemplate.updated_at.desc()).all()
|
|
return [serialize_template(r) for r in rows]
|
|
|
|
|
|
def _user_name(user_id: int | None) -> str | None:
|
|
"""Resolve a user's display name for template metadata."""
|
|
if not user_id:
|
|
return None
|
|
user = db.session.get(User, user_id)
|
|
if not user:
|
|
return None
|
|
return user.real_name or user.username
|
|
|
|
|
|
def list_enabled_for_chat() -> list[dict[str, Any]]:
|
|
"""会话下拉:仅启用中的模板。"""
|
|
return list_templates(status="enabled")
|
|
|
|
|
|
def get_default_enabled_template() -> ContractTemplate | None:
|
|
"""Return the single enabled default template whose config controls compare-region partitioning."""
|
|
return (
|
|
db.session.query(ContractTemplate)
|
|
.filter(
|
|
ContractTemplate.status == "enabled",
|
|
ContractTemplate.is_default.is_(True),
|
|
)
|
|
.order_by(ContractTemplate.updated_at.desc())
|
|
.first()
|
|
)
|
|
|
|
|
|
def create_template(
|
|
*,
|
|
user_id: int,
|
|
name: str,
|
|
version: str,
|
|
file_asset_id: int | None = None,
|
|
file_asset_no: str | None = None,
|
|
remark: str | None = None,
|
|
is_default: bool = False,
|
|
status: str = "enabled",
|
|
contract_type: str = "general_procurement",
|
|
applicable_scope: str | None = None,
|
|
change_note: str | None = None,
|
|
comparison_region_config: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""
|
|
创建模板并可选设为默认。
|
|
Raises:
|
|
ValidationError: 参数非法或资产不可用。
|
|
"""
|
|
name = (name or "").strip()
|
|
version = (version or "").strip()
|
|
if not name or not version:
|
|
raise ValidationError("name and version are required")
|
|
if status not in ("enabled", "disabled"):
|
|
raise ValidationError("invalid status")
|
|
|
|
asset: FileAsset | None = None
|
|
if file_asset_id:
|
|
asset = db.session.get(FileAsset, file_asset_id)
|
|
elif file_asset_no:
|
|
asset = get_asset_for_user(file_asset_no, user_id)
|
|
if not asset or asset.deleted_at is not None:
|
|
raise ValidationError("file asset not found")
|
|
|
|
exists = (
|
|
db.session.query(ContractTemplate)
|
|
.filter(ContractTemplate.name == name, ContractTemplate.version == version)
|
|
.first()
|
|
)
|
|
if exists:
|
|
raise ValidationError("template name+version already exists")
|
|
|
|
if is_default and status == "enabled":
|
|
_clear_defaults()
|
|
|
|
row = ContractTemplate(
|
|
name=name,
|
|
version=version,
|
|
file_asset_id=asset.id,
|
|
file_name=asset.original_filename,
|
|
contract_type=(contract_type or "general_procurement").strip() or "general_procurement",
|
|
applicable_scope=(applicable_scope or "").strip() or None,
|
|
change_note=(change_note or "").strip() or None,
|
|
comparison_region_config=(
|
|
validate_comparison_region_config(comparison_region_config)
|
|
if comparison_region_config is not None
|
|
else None
|
|
),
|
|
status=status,
|
|
is_default=bool(is_default and status == "enabled"),
|
|
remark=(remark or "").strip() or None,
|
|
created_by=user_id,
|
|
updated_by=user_id,
|
|
)
|
|
db.session.add(row)
|
|
mark_asset_referenced(asset)
|
|
db.session.commit()
|
|
return serialize_template(row)
|
|
|
|
|
|
def update_template(template_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
|
"""更新模板元数据 / 启停 / 设默认。"""
|
|
row = db.session.get(ContractTemplate, template_id)
|
|
if not row:
|
|
raise NotFoundError("template not found")
|
|
|
|
if "name" in data and data["name"] is not None:
|
|
row.name = str(data["name"]).strip() or row.name
|
|
if "version" in data and data["version"] is not None:
|
|
row.version = str(data["version"]).strip() or row.version
|
|
if "remark" in data:
|
|
row.remark = (str(data["remark"]).strip() or None) if data["remark"] is not None else None
|
|
if "contract_type" in data and data["contract_type"] is not None:
|
|
row.contract_type = str(data["contract_type"]).strip() or row.contract_type
|
|
if "applicable_scope" in data:
|
|
row.applicable_scope = (str(data["applicable_scope"]).strip() or None) if data["applicable_scope"] is not None else None
|
|
if "change_note" in data:
|
|
row.change_note = (str(data["change_note"]).strip() or None) if data["change_note"] is not None else None
|
|
if "comparison_region_config" in data:
|
|
row.comparison_region_config = (
|
|
validate_comparison_region_config(data["comparison_region_config"])
|
|
if data["comparison_region_config"] is not None
|
|
else None
|
|
)
|
|
if "status" in data and data["status"] is not None:
|
|
status = str(data["status"])
|
|
if status not in ("enabled", "disabled"):
|
|
raise ValidationError("invalid status")
|
|
if status == "disabled" and row.is_default:
|
|
raise ValidationError("cannot disable default template; set another default first")
|
|
row.status = status
|
|
if data.get("is_default") is True:
|
|
if row.status != "enabled":
|
|
raise ValidationError("only enabled template can be default")
|
|
_clear_defaults()
|
|
row.is_default = True
|
|
elif data.get("is_default") is False:
|
|
row.is_default = False
|
|
|
|
row.updated_by = user_id
|
|
row.updated_at = datetime.utcnow()
|
|
db.session.commit()
|
|
return serialize_template(row)
|
|
|
|
|
|
def delete_template(template_id: int) -> dict[str, Any]:
|
|
"""
|
|
Delete a non-default template that is not referenced by review history.
|
|
|
|
Historical reviews retain their template relationship for audit and file download,
|
|
so referenced templates must be disabled rather than deleted.
|
|
|
|
Raises:
|
|
NotFoundError: The template does not exist.
|
|
ValidationError: The template is currently the default template.
|
|
ConflictError: One or more review history records reference the template.
|
|
"""
|
|
row = db.session.get(ContractTemplate, template_id)
|
|
if not row:
|
|
raise NotFoundError("template not found")
|
|
if row.is_default:
|
|
raise ValidationError("cannot delete default template")
|
|
review_count = (
|
|
db.session.query(ContractReview.id)
|
|
.filter(ContractReview.template_id == template_id)
|
|
.count()
|
|
)
|
|
if review_count:
|
|
raise ConflictError(
|
|
code="PROCUREMENT_CONTRACT.TEMPLATE_REFERENCED",
|
|
message="模板已被审查历史引用,无法删除;请停用该模板",
|
|
details={"template_id": template_id, "review_count": review_count},
|
|
)
|
|
asset = db.session.get(FileAsset, row.file_asset_id) if row.file_asset_id else None
|
|
db.session.delete(row)
|
|
if asset:
|
|
release_asset_reference(asset)
|
|
db.session.commit()
|
|
return {"deleted": True, "id": template_id}
|
|
|
|
|
|
def get_template_or_404(template_id: int) -> ContractTemplate:
|
|
"""取模板实体。"""
|
|
row = db.session.get(ContractTemplate, template_id)
|
|
if not row:
|
|
raise NotFoundError("template not found")
|
|
return row
|
|
|
|
|
|
def read_template_bytes(template: ContractTemplate) -> tuple[str, bytes]:
|
|
"""读取模板文件字节。"""
|
|
if not template.file_asset_id:
|
|
raise ValidationError("template has no file")
|
|
asset = db.session.get(FileAsset, template.file_asset_id)
|
|
if not asset:
|
|
raise NotFoundError("template file not found")
|
|
return asset.original_filename, read_asset_bytes(asset)
|
|
|
|
|
|
def preview_comparison_regions(template_id: int, config: Any) -> dict[str, Any]:
|
|
"""
|
|
Preview configured anchors against the stored Admin template without changing review baselines.
|
|
|
|
Args:
|
|
template_id: Admin template primary key.
|
|
config: Unsaved comparison-region config from the edit dialog.
|
|
|
|
Returns:
|
|
Recognition status for body, signature, and attachment anchors.
|
|
"""
|
|
template = get_template_or_404(template_id)
|
|
normalized = validate_comparison_region_config(config)
|
|
filename, data = read_template_bytes(template)
|
|
raw_text = analyze.extract_text_from_bytes(filename, data)
|
|
clean_text = analyze.clean_contract_text(raw_text)
|
|
if not clean_text or clean_text.startswith("[binary:"):
|
|
raise ValidationError(
|
|
"template text cannot be extracted for comparison-region preview",
|
|
code="PROCUREMENT_CONTRACT.COMPARISON_REGION_PREVIEW_FAILED",
|
|
)
|
|
result = preview_anchor_recognition(clean_text, normalized)
|
|
result["template_id"] = template.id
|
|
result["template_name"] = template.name
|
|
return result
|
|
|
|
|
|
def _clear_defaults() -> None:
|
|
"""清除所有默认标记。"""
|
|
db.session.query(ContractTemplate).filter(ContractTemplate.is_default.is_(True)).update(
|
|
{"is_default": False},
|
|
synchronize_session=False,
|
|
)
|