71 lines
2.3 KiB
Python
71 lines
2.3 KiB
Python
"""
|
|
backend/app/services/voucher_check/profile_loader.py
|
|
|
|
用途:加载销售 Profile 并确保数据库中有对应已发布快照。
|
|
依赖:profiles 目录、models.VoucherCheckProfile。
|
|
逻辑:批次绑定 definition_json 快照;运行中不以表热更新覆盖已开始的批次。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from app import db
|
|
from app.core.errors import ValidationError
|
|
from app.models.voucher_check import VoucherCheckProfile
|
|
from app.services.voucher_check.profiles import PROFILE_CATALOG
|
|
|
|
|
|
def load_profile_definition(profile_code: str = "sales") -> dict[str, Any]:
|
|
"""
|
|
读取内置 Profile 定义的深拷贝。
|
|
核心逻辑:未知 profile_code 在批次开始前失败。
|
|
"""
|
|
code = str(profile_code or "sales").strip() or "sales"
|
|
definition = PROFILE_CATALOG.get(code)
|
|
if not definition:
|
|
raise ValidationError(
|
|
f"未知 Profile: {code}",
|
|
code="VOUCHER_CHECK.CONFIG_INVALID",
|
|
details={"profile_code": code},
|
|
)
|
|
snapshot = copy.deepcopy(definition)
|
|
if not snapshot.get("file_rules"):
|
|
raise ValidationError("Profile 缺少 file_rules", code="VOUCHER_CHECK.CONFIG_INVALID")
|
|
return snapshot
|
|
|
|
|
|
def ensure_published_profile(profile_code: str = "sales") -> VoucherCheckProfile:
|
|
"""
|
|
幂等写入已发布 Profile 行,供审计;批次仍使用内存快照。
|
|
"""
|
|
snapshot = load_profile_definition(profile_code)
|
|
code = str(snapshot["profile_code"])
|
|
version = str(snapshot["profile_version"])
|
|
row = (
|
|
db.session.query(VoucherCheckProfile)
|
|
.filter_by(profile_code=code, version=version)
|
|
.one_or_none()
|
|
)
|
|
now = datetime.utcnow()
|
|
if row is None:
|
|
row = VoucherCheckProfile(
|
|
profile_code=code,
|
|
version=version,
|
|
definition_json=snapshot,
|
|
status="published",
|
|
created_at=now,
|
|
updated_at=now,
|
|
)
|
|
db.session.add(row)
|
|
db.session.flush()
|
|
return row
|
|
if row.status != "published" or row.definition_json != snapshot:
|
|
row.definition_json = snapshot
|
|
row.status = "published"
|
|
row.updated_at = now
|
|
db.session.flush()
|
|
return row
|