feat: 票据合规预审助手首版 v1.0.0(verify-invoice-default)
This commit is contained in:
46
scripts/service/entitlement_service.py
Normal file
46
scripts/service/entitlement_service.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""在线鉴权(可选模板)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import requests
|
||||
from jiangchang_skill_core import config
|
||||
|
||||
|
||||
def check_entitlement(skill_slug: str) -> Tuple[bool, str]:
|
||||
auth_base = (config.get("JIANGCHANG_AUTH_BASE_URL") or "").strip().rstrip("/")
|
||||
if not auth_base:
|
||||
return True, ""
|
||||
user_id = (config.get("JIANGCHANG_USER_ID") or "").strip()
|
||||
if not user_id:
|
||||
return False, "鉴权失败:缺少用户身份(JIANGCHANG_USER_ID)"
|
||||
|
||||
auth_api_key = (config.get("JIANGCHANG_AUTH_API_KEY") or "").strip()
|
||||
timeout = int((config.get("JIANGCHANG_AUTH_TIMEOUT_SECONDS") or "5").strip())
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if auth_api_key:
|
||||
headers["Authorization"] = f"Bearer {auth_api_key}"
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"skill_slug": skill_slug,
|
||||
"trace_id": (config.get("JIANGCHANG_TRACE_ID") or "").strip(),
|
||||
"context": {"entry": "main.py"},
|
||||
}
|
||||
try:
|
||||
res = requests.post(f"{auth_base}/api/entitlements/check", json=payload, headers=headers, timeout=timeout)
|
||||
except requests.RequestException as exc:
|
||||
return False, f"鉴权请求失败:{exc}"
|
||||
if res.status_code != 200:
|
||||
return False, f"鉴权服务异常:HTTP {res.status_code}"
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
return False, "鉴权服务异常:返回非 JSON"
|
||||
code = body.get("code")
|
||||
data = body.get("data") or {}
|
||||
if code != 200:
|
||||
return False, str(body.get("msg") or "鉴权失败")
|
||||
if not data.get("allow", False):
|
||||
return False, str(data.get("reason") or "未购买或已过期")
|
||||
return True, ""
|
||||
78
scripts/service/html_page_service.py
Normal file
78
scripts/service/html_page_service.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""技能 HTML 报告页:写入 `{skill_data}/html/*.html`(宿主扫描预览)。
|
||||
|
||||
契约要点(权威说明见 `references/ACTIONS.md`「HTML 页面报告」):
|
||||
|
||||
- 目录:仅一层 `html/*.html`(非递归)
|
||||
- 重新生成 Action id 必须为 `render-html`(宿主硬编码)
|
||||
- 页面布局底线见 `references/ACTIONS.md`「宿主预览布局」;模板壳 `assets/html/example-report.html`
|
||||
- 成功后建议 `steps: refreshCatalog` 以重扫侧栏
|
||||
- 本模块只提供路径/模板/原子写;业务 KPI/表格由各技能自行填充
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Mapping
|
||||
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.runtime_paths import get_html_dir, get_skill_root
|
||||
|
||||
# Host Data Management looks up this exact Skill Action id for「重新生成」.
|
||||
HOST_HTML_RENDER_ACTION_ID = "render-html"
|
||||
|
||||
_UNSAFE_NAME = re.compile(r"[\\/]|^\.\.|\.\.$")
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def assert_html_filename(filename: str) -> str:
|
||||
name = (filename or "").strip()
|
||||
if not name.lower().endswith(".html"):
|
||||
raise ValueError(f"html filename must end with .html: {filename!r}")
|
||||
if _UNSAFE_NAME.search(name) or "/" in name or "\\" in name:
|
||||
raise ValueError(f"html filename must be a basename only: {filename!r}")
|
||||
if len(name) > 200:
|
||||
raise ValueError(f"html filename too long: {filename!r}")
|
||||
return name
|
||||
|
||||
|
||||
def html_page_path(filename: str, *, create_dir: bool = True) -> str:
|
||||
return os.path.join(get_html_dir(create=create_dir), assert_html_filename(filename))
|
||||
|
||||
|
||||
def load_html_template(relative_under_skill_root: str) -> str:
|
||||
"""Load UTF-8 template from skill root (e.g. ``assets/html/example-report.html``)."""
|
||||
rel = (relative_under_skill_root or "").strip().replace("\\", "/")
|
||||
if not rel or rel.startswith("/") or ".." in rel.split("/"):
|
||||
raise ValueError(f"invalid template path: {relative_under_skill_root!r}")
|
||||
path = os.path.join(get_skill_root(), *rel.split("/"))
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def render_html_placeholders(template: str, mapping: Mapping[str, str]) -> str:
|
||||
"""Replace ``{{KEY}}`` tokens. Unknown keys are left as-is."""
|
||||
page = template
|
||||
for key, value in mapping.items():
|
||||
page = page.replace("{{" + str(key) + "}}", str(value))
|
||||
return page
|
||||
|
||||
|
||||
def write_html_page(filename: str, html: str) -> str:
|
||||
"""Atomically write UTF-8 HTML under ``html/``. Returns absolute path."""
|
||||
dest = html_page_path(filename, create_dir=True)
|
||||
tmp = dest + ".tmp"
|
||||
text = html if isinstance(html, str) else str(html)
|
||||
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, dest)
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("html_page_written path=%s bytes=%s", dest, len(text.encode("utf-8")))
|
||||
return dest
|
||||
774
scripts/service/prereview_service.py
Normal file
774
scripts/service/prereview_service.py
Normal file
@@ -0,0 +1,774 @@
|
||||
"""票据合规预审规则引擎(唯一业务内核)。
|
||||
|
||||
四步审核(对齐《核心建设内容:各部门"Skill"深度需求规格书》财务处 Skill 001):
|
||||
Step 1 字段完整性校验(F1-F4)
|
||||
Step 2 三方交叉验真(V1 真伪状态 / V2 购买方税号白名单 / V3 日期逻辑)
|
||||
Step 3 经费标准硬约束(S1 住宿费上限 / S2 交通等级 / S3 项目归属)
|
||||
Step 4 风控标记(R1 连号 / R2 同商家集中开票 / R3 节假日开票)
|
||||
|
||||
每条规则输出 {rule_id, name, level, detail, rule_ref};level ∈ pass/warn/reject。
|
||||
总判定:任一 reject → 驳回;有 warn → 待确认;否则 通过。
|
||||
预审结果仅作提示,不构成最终报销结论;真伪以人工/官方查验为准。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Optional
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from util.cny_amount import parse_cny_upper
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.timeutil import now_unix
|
||||
|
||||
_VERDICT_PASS = "通过"
|
||||
_VERDICT_WARN = "待确认"
|
||||
_VERDICT_REJECT = "驳回"
|
||||
|
||||
_DATE_PATTERNS = ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y年%m月%d日")
|
||||
|
||||
# 发票号码已知位数:数电票 20 位;增值税普/专票 8 位;旧版 10/12 位
|
||||
_KNOWN_NUMBER_LENGTHS = {8, 10, 12, 20}
|
||||
|
||||
_INVOICE_KEY_ALIASES = {
|
||||
"invoiceType": ("invoice_type", "发票类型", "type"),
|
||||
"invoiceCode": ("invoice_code", "发票代码"),
|
||||
"invoiceNumber": ("invoice_number", "invoice_no", "发票号码"),
|
||||
"issueDate": ("issue_date", "开票日期", "date"),
|
||||
"amount": ("amount", "金额", "total_amount", "价税合计"),
|
||||
"amountInWords": ("amount_in_words", "大写金额", "amount_words"),
|
||||
"taxRate": ("tax_rate", "税率"),
|
||||
"buyerName": ("buyer_name", "购买方名称", "buyer"),
|
||||
"buyerTaxNo": ("buyer_tax_no", "购买方税号", "buyer_tax_id"),
|
||||
"sellerName": ("seller_name", "销售方名称", "seller"),
|
||||
"sellerTaxNo": ("seller_tax_no", "销售方税号", "seller_tax_id"),
|
||||
"expenseCategory": ("expense_category", "category", "费用类别"),
|
||||
"city": ("city", "城市", "消费城市"),
|
||||
"days": ("days", "天数", "住宿天数"),
|
||||
"ticketClass": ("ticket_class", "座位等级", "席别", "舱位等级"),
|
||||
"manualVerifyResult": ("manual_verify_result", "查验结果", "人工查验结果"),
|
||||
}
|
||||
|
||||
_TICKET_CLASS_LEVELS = (
|
||||
(("商务座", "头等舱"), 3),
|
||||
(("一等座", "软卧", "公务舱", "一等舱"), 2),
|
||||
(("二等座", "硬座", "硬卧", "软座", "经济舱"), 1),
|
||||
)
|
||||
|
||||
_CHECK_PLATFORM_HINT = "全国增值税发票查验平台(inv-veri.chinatax.gov.cn)"
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _norm_invoice(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""将输入发票字段归一化为 camelCase 键(兼容 snake_case 与常见中文键)。"""
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in raw.items():
|
||||
camel = _camel(key)
|
||||
if camel in _INVOICE_KEY_ALIASES:
|
||||
out.setdefault(camel, value)
|
||||
continue
|
||||
matched = False
|
||||
for canonical, aliases in _INVOICE_KEY_ALIASES.items():
|
||||
if key in aliases:
|
||||
out.setdefault(canonical, value)
|
||||
matched = True
|
||||
break
|
||||
if not matched:
|
||||
out.setdefault(camel, value)
|
||||
return out
|
||||
|
||||
|
||||
def _camel(name: str) -> str:
|
||||
parts = re.split(r"[\s_]+", str(name).strip())
|
||||
if len(parts) <= 1:
|
||||
return str(name)
|
||||
head, *rest = parts
|
||||
return head + "".join(p[:1].upper() + p[1:] for p in rest)
|
||||
|
||||
|
||||
def _to_float(value: Any) -> Optional[float]:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
text = str(value).strip()
|
||||
text = re.sub(r"[¥¥元人民币\s,,]", "", text)
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_date(value: Any) -> Optional[date]:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
text = str(value).strip()
|
||||
for pattern in _DATE_PATTERNS:
|
||||
try:
|
||||
return datetime.strptime(text, pattern).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _fmt_date(value: Optional[date]) -> str:
|
||||
return value.isoformat() if value else ""
|
||||
|
||||
|
||||
def _load_whitelist_taxnos() -> set[str]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT tax_no FROM taxid_whitelist")
|
||||
return {str(row[0]).strip().upper() for row in cur.fetchall()}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _load_holiday_dates() -> set[str]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT holiday_date FROM holiday_calendar")
|
||||
return {str(row[0]) for row in cur.fetchall()}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _resolve_city_tier(city: str) -> Optional[tuple[str, str]]:
|
||||
"""按城市名归档城市等级,返回 (city_tier, basis)。"""
|
||||
if not city:
|
||||
return None
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT city_tier, city_example FROM expense_standards WHERE category = '住宿费' GROUP BY city_tier, city_example"
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
for city_tier, city_example in rows:
|
||||
names = [n.strip() for n in str(city_example or "").split(",") if n.strip()]
|
||||
if city in names:
|
||||
return city_tier, "标准库城市示例"
|
||||
return None
|
||||
|
||||
|
||||
def _lookup_standard(category: str, city_tier: Optional[str], staff_title: Optional[str]) -> Optional[dict[str, Any]]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
sql = "SELECT city_tier, staff_title, max_amount, unit, basis_doc, clause FROM expense_standards WHERE category = ?"
|
||||
params: list[Any] = [category]
|
||||
if city_tier:
|
||||
sql += " AND city_tier = ?"
|
||||
params.append(city_tier)
|
||||
if staff_title:
|
||||
sql += " AND staff_title = ?"
|
||||
params.append(staff_title)
|
||||
cur.execute(sql + " LIMIT 1", params)
|
||||
row = cur.fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"city_tier": row[0],
|
||||
"staff_title": row[1],
|
||||
"max_amount": float(row[2]),
|
||||
"unit": row[3] or "",
|
||||
"basis_doc": row[4] or "",
|
||||
"clause": row[5] or "",
|
||||
}
|
||||
|
||||
|
||||
def _ref(basis_doc: str, clause: str) -> str:
|
||||
if basis_doc and clause:
|
||||
return f"{basis_doc}{clause}"
|
||||
return basis_doc or clause or ""
|
||||
|
||||
|
||||
def _item(rule_id: str, name: str, level: str, detail: str, rule_ref: str = "") -> dict[str, str]:
|
||||
return {"rule_id": rule_id, "name": name, "level": level, "detail": detail, "rule_ref": rule_ref}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 1 字段完整性校验
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _check_field_completeness(inv: dict[str, Any], today: date) -> list[dict[str, str]]:
|
||||
items: list[dict[str, str]] = []
|
||||
missing = [
|
||||
label
|
||||
for key, label in (
|
||||
("invoiceNumber", "发票号码"),
|
||||
("issueDate", "开票日期"),
|
||||
("amount", "金额"),
|
||||
("sellerName", "销售方名称"),
|
||||
)
|
||||
if inv.get(key) in (None, "")
|
||||
]
|
||||
if missing:
|
||||
items.append(
|
||||
_item(
|
||||
"F1",
|
||||
"必填字段齐全",
|
||||
"warn",
|
||||
f"以下关键字段缺失或为空:{'、'.join(missing)}。请重新拍摄/补录后再提交报销。",
|
||||
"票据预审·字段校验",
|
||||
)
|
||||
)
|
||||
|
||||
number = str(inv.get("invoiceNumber") or "").strip().replace(" ", "")
|
||||
if number and not number.isdigit():
|
||||
items.append(_item("F2", "发票号码格式", "warn", f"发票号码含非数字字符:{number}", "票据预审·字段校验"))
|
||||
elif number and len(number) not in _KNOWN_NUMBER_LENGTHS:
|
||||
items.append(
|
||||
_item(
|
||||
"F2",
|
||||
"发票号码格式",
|
||||
"warn",
|
||||
f"发票号码 {len(number)} 位,不属于已知位数(数电票 20 位、普/专票 8 位、旧版 10/12 位),疑似异常,请人工核验票面。",
|
||||
"票据预审·字段校验",
|
||||
)
|
||||
)
|
||||
|
||||
issue_date = _parse_date(inv.get("issueDate"))
|
||||
raw_date = str(inv.get("issueDate") or "").strip()
|
||||
if raw_date and issue_date is None:
|
||||
items.append(_item("F3", "开票日期合法性", "reject", f"开票日期无法解析:{raw_date}(应为 YYYY-MM-DD)", "票据预审·字段校验"))
|
||||
elif issue_date and issue_date > today:
|
||||
items.append(_item("F3", "开票日期合法性", "reject", f"开票日期 {issue_date.isoformat()} 晚于今日,票面异常。", "票据预审·字段校验"))
|
||||
elif issue_date:
|
||||
items.append(_item("F3", "开票日期合法性", "pass", f"开票日期 {issue_date.isoformat()} 合法。", "票据预审·字段校验"))
|
||||
|
||||
amount = _to_float(inv.get("amount"))
|
||||
words = str(inv.get("amountInWords") or "").strip()
|
||||
if amount is not None and words:
|
||||
words_value = parse_cny_upper(words)
|
||||
if words_value is None:
|
||||
items.append(_item("F4", "大小写金额一致", "warn", f"大写金额“{words}”无法解析,请人工核对大小写金额。", "票据预审·字段校验"))
|
||||
elif abs(words_value - amount) > 0.01:
|
||||
items.append(
|
||||
_item(
|
||||
"F4",
|
||||
"大小写金额一致",
|
||||
"reject",
|
||||
f"大写金额 {words_value:.2f} 元与小写金额 {amount:.2f} 元不一致,票面异常。",
|
||||
"票据预审·字段校验",
|
||||
)
|
||||
)
|
||||
else:
|
||||
items.append(_item("F4", "大小写金额一致", "pass", f"大小写金额一致({amount:.2f} 元)。", "票据预审·字段校验"))
|
||||
return items
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 2 三方交叉验真
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _check_cross_verification(
|
||||
inv: dict[str, Any],
|
||||
context: dict[str, Any],
|
||||
whitelist: set[str],
|
||||
today: date,
|
||||
) -> list[dict[str, str]]:
|
||||
items: list[dict[str, str]] = []
|
||||
|
||||
verify = str(inv.get("manualVerifyResult") or "").strip().lower()
|
||||
if verify in ("fail", "false", "不符", "假票", "查验不符"):
|
||||
items.append(_item("V1", "发票真伪", "reject", "人工查验结果为“不符”,判定为问题票据。", _CHECK_PLATFORM_HINT))
|
||||
elif verify in ("pass", "true", "通过", "真票", "查验通过"):
|
||||
items.append(_item("V1", "发票真伪", "pass", "人工查验结果为“通过”。", _CHECK_PLATFORM_HINT))
|
||||
else:
|
||||
items.append(
|
||||
_item(
|
||||
"V1",
|
||||
"发票真伪",
|
||||
"warn",
|
||||
f"尚未查验真伪:请经办人到{_CHECK_PLATFORM_HINT}录入票面信息核验,并在本报告回填查验结果。",
|
||||
_CHECK_PLATFORM_HINT,
|
||||
)
|
||||
)
|
||||
|
||||
buyer_tax_no = str(inv.get("buyerTaxNo") or "").strip()
|
||||
if not buyer_tax_no:
|
||||
items.append(_item("V2", "购买方税号白名单", "warn", "票面缺少购买方税号,无法进行白名单比对,请补录抬头信息。", "票据预审·税号白名单"))
|
||||
elif buyer_tax_no.strip().upper() in whitelist:
|
||||
buyer_name = str(inv.get("buyerName") or "").strip()
|
||||
items.append(_item("V2", "购买方税号白名单", "pass", f"购买方税号在我校准予报销白名单内{('(' + buyer_name + ')') if buyer_name else ''}。", "票据预审·税号白名单"))
|
||||
else:
|
||||
items.append(
|
||||
_item(
|
||||
"V2",
|
||||
"购买方税号白名单",
|
||||
"reject",
|
||||
f"购买方税号 {buyer_tax_no} 不在我校准予报销税号白名单内,抬头开错,须换开后方可报销。",
|
||||
"票据预审·税号白名单",
|
||||
)
|
||||
)
|
||||
|
||||
issue_date = _parse_date(inv.get("issueDate"))
|
||||
trip_start = _parse_date(context.get("trip_start"))
|
||||
trip_end = _parse_date(context.get("trip_end"))
|
||||
if issue_date and trip_start:
|
||||
window_end = trip_end or trip_start
|
||||
if issue_date < trip_start:
|
||||
items.append(
|
||||
_item(
|
||||
"V3",
|
||||
"日期逻辑(先审批后出行)",
|
||||
"warn",
|
||||
f"开票日期 {issue_date.isoformat()} 早于出差开始日 {trip_start.isoformat()},请核实行程与审批单(先审批后出行)。",
|
||||
"票据预审·日期逻辑",
|
||||
)
|
||||
)
|
||||
elif issue_date > window_end + timedelta(days=1):
|
||||
items.append(
|
||||
_item(
|
||||
"V3",
|
||||
"日期逻辑(先审批后出行)",
|
||||
"warn",
|
||||
f"开票日期 {issue_date.isoformat()} 晚于出差结束日 {window_end.isoformat()}(含 1 天宽限),请核实行程。",
|
||||
"票据预审·日期逻辑",
|
||||
)
|
||||
)
|
||||
else:
|
||||
items.append(
|
||||
_item(
|
||||
"V3",
|
||||
"日期逻辑(先审批后出行)",
|
||||
"pass",
|
||||
f"开票日期落在出差区间 [{trip_start.isoformat()}, {(trip_end or trip_start).isoformat()}] 内。",
|
||||
"票据预审·日期逻辑",
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 3 经费标准硬约束
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _check_expense_standards(inv: dict[str, Any], context: dict[str, Any]) -> list[dict[str, str]]:
|
||||
items: list[dict[str, str]] = []
|
||||
category = str(inv.get("expenseCategory") or "").strip()
|
||||
amount = _to_float(inv.get("amount"))
|
||||
staff_title = str(context.get("staff_title") or "").strip()
|
||||
|
||||
if "住宿" in category and amount is not None:
|
||||
city = str(context.get("trip_city") or inv.get("city") or "").strip()
|
||||
tier_info = _resolve_city_tier(city) if city else None
|
||||
if not city:
|
||||
items.append(
|
||||
_item(
|
||||
"S1",
|
||||
"住宿费标准比对",
|
||||
"warn",
|
||||
"未提供消费城市,无法匹配住宿费标准,请补录城市后重新预审或人工对照《差旅费管理办法》。",
|
||||
_ref("《差旅费管理办法》", "第十条"),
|
||||
)
|
||||
)
|
||||
elif not tier_info:
|
||||
items.append(
|
||||
_item(
|
||||
"S1",
|
||||
"住宿费标准比对",
|
||||
"warn",
|
||||
f"城市“{city}”不在标准库城市等级中,无法匹配住宿费标准,请人工对照《差旅费管理办法》或请管理员维护该城市。",
|
||||
_ref("《差旅费管理办法》", "第十条"),
|
||||
)
|
||||
)
|
||||
else:
|
||||
standard = _lookup_standard("住宿费", tier_info[0], staff_title or None)
|
||||
days = _to_float(inv.get("days")) or 1.0
|
||||
days = max(days, 1.0)
|
||||
if not standard:
|
||||
items.append(
|
||||
_item(
|
||||
"S1",
|
||||
"住宿费标准比对",
|
||||
"warn",
|
||||
f"未匹配到“{tier_info[0]}/{staff_title or '未提供职级'}”的住宿费标准,请人工对照《差旅费管理办法》。",
|
||||
_ref("《差旅费管理办法》", "第十条"),
|
||||
)
|
||||
)
|
||||
else:
|
||||
per_day = amount / days
|
||||
limit = standard["max_amount"]
|
||||
ref = _ref(standard["basis_doc"], standard["clause"])
|
||||
if per_day > limit + 0.001:
|
||||
items.append(
|
||||
_item(
|
||||
"S1",
|
||||
"住宿费标准比对",
|
||||
"reject",
|
||||
(
|
||||
f"住宿费折合 {per_day:.2f} 元/人/天,超过“{standard['city_tier']}/{standard['staff_title']}”"
|
||||
f"上限 {limit:.2f} 元/人/天,超标 {per_day - limit:.2f} 元。"
|
||||
),
|
||||
ref,
|
||||
)
|
||||
)
|
||||
else:
|
||||
items.append(
|
||||
_item(
|
||||
"S1",
|
||||
"住宿费标准比对",
|
||||
"pass",
|
||||
f"住宿费折合 {per_day:.2f} 元/人/天,未超“{standard['city_tier']}/{standard['staff_title']}”上限 {limit:.2f} 元/人/天。",
|
||||
ref,
|
||||
)
|
||||
)
|
||||
|
||||
if "交通" in category or "出租" in str(inv.get("invoiceType") or ""):
|
||||
ticket_class = str(inv.get("ticketClass") or "").strip()
|
||||
standard = _lookup_standard("交通费", None, staff_title or None)
|
||||
if ticket_class and standard:
|
||||
class_level = _ticket_class_level(ticket_class)
|
||||
ref = _ref(standard["basis_doc"], standard["clause"])
|
||||
if class_level is None:
|
||||
items.append(_item("S2", "交通席位等级", "warn", f"席位/舱位等级“{ticket_class}”无法识别,请人工对照职级可乘等级。", ref))
|
||||
elif class_level > standard["max_amount"]:
|
||||
items.append(
|
||||
_item(
|
||||
"S2",
|
||||
"交通席位等级",
|
||||
"warn",
|
||||
f"“{ticket_class}”等级高于“{standard['staff_title']}”可乘等级(代码 {standard['max_amount']:.0f}),请确认是否符合职级规定或已获审批。",
|
||||
ref,
|
||||
)
|
||||
)
|
||||
else:
|
||||
items.append(_item("S2", "交通席位等级", "pass", f"“{ticket_class}”符合“{standard['staff_title']}”可乘等级。", ref))
|
||||
|
||||
project_no = str(context.get("project_no") or "").strip()
|
||||
if project_no:
|
||||
items.append(
|
||||
_item(
|
||||
"S3",
|
||||
"项目经费归属",
|
||||
"pass",
|
||||
f"本笔将计入预算项目 {project_no};项目余额校验待财务系统对接后启用。",
|
||||
"票据预审·项目归属",
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _ticket_class_level(ticket_class: str) -> Optional[int]:
|
||||
for keywords, level in _TICKET_CLASS_LEVELS:
|
||||
if any(k in ticket_class for k in keywords):
|
||||
return level
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 4 风控标记
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _check_holiday(inv: dict[str, Any], holidays: set[str]) -> list[dict[str, str]]:
|
||||
items: list[dict[str, str]] = []
|
||||
issue_date = _parse_date(inv.get("issueDate"))
|
||||
if not issue_date:
|
||||
return items
|
||||
iso = issue_date.isoformat()
|
||||
if iso in holidays:
|
||||
items.append(
|
||||
_item("R3", "节假日开票", "warn", f"开票日期 {iso} 为法定节假日,请核实消费真实性。", "票据预审·风控标记")
|
||||
)
|
||||
elif issue_date.weekday() >= 5:
|
||||
items.append(
|
||||
_item("R3", "节假日开票", "warn", f"开票日期 {iso} 为周末({'周六' if issue_date.weekday() == 5 else '周日'}),请核实消费真实性。", "票据预审·风控标记")
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _check_batch_risks(invoices: list[dict[str, Any]]) -> dict[int, list[dict[str, str]]]:
|
||||
"""R1 连号发票 + R2 同商家集中开票(批内)。返回 invoice index → items。"""
|
||||
extra: dict[int, list[dict[str, str]]] = {}
|
||||
|
||||
# R1:同发票代码且号码连续(差值 ≤ 2)
|
||||
numeric_by_code: dict[str, list[tuple[int, int]]] = {}
|
||||
for idx, inv in enumerate(invoices):
|
||||
code = str(inv.get("invoiceCode") or "").strip() or "-"
|
||||
number = str(inv.get("invoiceNumber") or "").strip()
|
||||
if number.isdigit():
|
||||
numeric_by_code.setdefault(code, []).append((idx, int(number)))
|
||||
for _code, entries in numeric_by_code.items():
|
||||
for idx, number in entries:
|
||||
peers = [n for j, n in entries if j != idx and abs(n - number) <= 2]
|
||||
if peers:
|
||||
extra.setdefault(idx, []).append(
|
||||
_item(
|
||||
"R1",
|
||||
"连号发票",
|
||||
"warn",
|
||||
f"与本批发票号码连号(相邻号码:{', '.join(str(p) for p in sorted(set(peers)))}),请核实是否拆分消费。",
|
||||
"票据预审·风控标记",
|
||||
)
|
||||
)
|
||||
|
||||
# R2:同商家集中开票(批内按销方税号,缺税号回退销方名称)
|
||||
sellers: dict[str, list[int]] = {}
|
||||
for idx, inv in enumerate(invoices):
|
||||
key = str(inv.get("sellerTaxNo") or "").strip().upper() or str(inv.get("sellerName") or "").strip()
|
||||
if key:
|
||||
sellers.setdefault(key, []).append(idx)
|
||||
for _key, idx_list in sellers.items():
|
||||
if len(idx_list) >= 3:
|
||||
sample_name = str(invoices[idx_list[0]].get("sellerName") or "同一销售方").strip()
|
||||
for idx in idx_list:
|
||||
extra.setdefault(idx, []).append(
|
||||
_item(
|
||||
"R2",
|
||||
"同商家集中开票",
|
||||
"warn",
|
||||
f"本批有 {len(idx_list)} 张发票来自“{sample_name}”,存在集中开票情形,请核实消费真实性。",
|
||||
"票据预审·风控标记",
|
||||
)
|
||||
)
|
||||
return extra
|
||||
|
||||
|
||||
def _check_seller_history(inv: dict[str, Any]) -> Optional[dict[str, str]]:
|
||||
"""R2 历史扩展:该销方近 30 天(含本张)累计 ≥ 5 张 → 黄灯。"""
|
||||
seller_tax_no = str(inv.get("sellerTaxNo") or "").strip()
|
||||
if not seller_tax_no:
|
||||
return None
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*) FROM invoice_records
|
||||
WHERE seller_tax_no = ? AND created_at >= ?
|
||||
""",
|
||||
(seller_tax_no, now_unix() - 30 * 24 * 3600),
|
||||
)
|
||||
history = int(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
if history + 1 >= 5:
|
||||
seller_name = str(inv.get("sellerName") or seller_tax_no).strip()
|
||||
return _item(
|
||||
"R2",
|
||||
"同商家集中开票",
|
||||
"warn",
|
||||
f"销售方“{seller_name}”近 30 天累计开票 {history + 1} 张(含本张),存在集中开票情形,请核实消费真实性。",
|
||||
"票据预审·风控标记",
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 内核入口
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _decide(items: list[dict[str, str]]) -> str:
|
||||
levels = {i["level"] for i in items}
|
||||
if "reject" in levels:
|
||||
return _VERDICT_REJECT
|
||||
if "warn" in levels:
|
||||
return _VERDICT_WARN
|
||||
return _VERDICT_PASS
|
||||
|
||||
|
||||
def _summarize(verdict: str, invoice_number: str, items: list[dict[str, str]]) -> str:
|
||||
rejects = [i for i in items if i["level"] == "reject"]
|
||||
warns = [i for i in items if i["level"] == "warn"]
|
||||
if verdict == _VERDICT_REJECT:
|
||||
return f"发票 {invoice_number} 预审驳回:{';'.join(i['name'] for i in rejects[:3])}"
|
||||
if verdict == _VERDICT_WARN:
|
||||
return f"发票 {invoice_number} 待确认:{';'.join(i['name'] for i in warns[:3])}"
|
||||
return f"发票 {invoice_number} 预审通过,全部检查项通过。"
|
||||
|
||||
|
||||
def _validate_input(invoices: list[dict[str, Any]]) -> None:
|
||||
if not invoices:
|
||||
raise ValueError("发票字段为空:请提供至少一张发票的结构化字段 JSON")
|
||||
if len(invoices) > 50:
|
||||
raise ValueError(f"单批发票数量过多({len(invoices)} 张),单批上限 50 张")
|
||||
for idx, inv in enumerate(invoices):
|
||||
if not isinstance(inv, dict):
|
||||
raise ValueError(f"第 {idx + 1} 张发票字段不是 JSON 对象")
|
||||
|
||||
|
||||
def run_prereview(invoices_raw: list[dict[str, Any]], context: dict[str, Any]) -> dict[str, Any]:
|
||||
"""预审内核:四步审核 → 写库 → 生成《初审意见单》HTML。"""
|
||||
from service.report_service import write_report_for_kernel
|
||||
|
||||
log = _log()
|
||||
init_db()
|
||||
invoices = [_norm_invoice(inv) for inv in invoices_raw]
|
||||
_validate_input(invoices)
|
||||
|
||||
batch_no = now_unix().to_bytes(5, "big").hex() + uuid.uuid4().hex[:6]
|
||||
today = date.today()
|
||||
whitelist = _load_whitelist_taxnos()
|
||||
holidays = _load_holiday_dates()
|
||||
|
||||
if log:
|
||||
log.info("prereview_kernel_start batch_no=%s count=%s stage=kernel", batch_no, len(invoices))
|
||||
|
||||
batch_extra = _check_batch_risks(invoices)
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for idx, inv in enumerate(invoices):
|
||||
items: list[dict[str, str]] = []
|
||||
items.extend(_check_field_completeness(inv, today))
|
||||
items.extend(_check_cross_verification(inv, context, whitelist, today))
|
||||
items.extend(_check_expense_standards(inv, context))
|
||||
items.extend(_check_holiday(inv, holidays))
|
||||
items.extend(batch_extra.get(idx, []))
|
||||
|
||||
seller_key = str(inv.get("sellerTaxNo") or "").strip()
|
||||
if seller_key:
|
||||
history_item = _check_seller_history(inv)
|
||||
if history_item and not any(i["rule_id"] == "R2" for i in items):
|
||||
items.append(history_item)
|
||||
|
||||
verdict = _decide(items)
|
||||
invoice_number = str(inv.get("invoiceNumber") or "").strip() or f"未提供-{idx + 1}"
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO invoice_records
|
||||
(batch_no, invoice_type, invoice_code, invoice_number, issue_date, amount,
|
||||
amount_in_words, tax_rate, buyer_name, buyer_tax_no, seller_name, seller_tax_no,
|
||||
expense_category, city, days, purpose, project_no, trip_context_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_no,
|
||||
str(inv.get("invoiceType") or ""),
|
||||
str(inv.get("invoiceCode") or ""),
|
||||
invoice_number,
|
||||
_fmt_date(_parse_date(inv.get("issueDate"))),
|
||||
_to_float(inv.get("amount")),
|
||||
str(inv.get("amountInWords") or ""),
|
||||
_to_float(inv.get("taxRate")),
|
||||
str(inv.get("buyerName") or ""),
|
||||
str(inv.get("buyerTaxNo") or ""),
|
||||
str(inv.get("sellerName") or ""),
|
||||
str(inv.get("sellerTaxNo") or ""),
|
||||
str(inv.get("expenseCategory") or ""),
|
||||
str(inv.get("city") or ""),
|
||||
int(_to_float(inv.get("days")) or 0),
|
||||
str(context.get("purpose") or ""),
|
||||
str(context.get("project_no") or ""),
|
||||
json.dumps(context, ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
invoice_id = int(cur.lastrowid)
|
||||
|
||||
summary = _summarize(verdict, invoice_number, items)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO prereview_reports
|
||||
(batch_no, invoice_id, invoice_number, seller_name, amount, verdict,
|
||||
pass_json, warn_json, reject_json, summary)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_no,
|
||||
invoice_id,
|
||||
invoice_number,
|
||||
str(inv.get("sellerName") or ""),
|
||||
_to_float(inv.get("amount")),
|
||||
verdict,
|
||||
json.dumps([i for i in items if i["level"] == "pass"], ensure_ascii=False),
|
||||
json.dumps([i for i in items if i["level"] == "warn"], ensure_ascii=False),
|
||||
json.dumps([i for i in items if i["level"] == "reject"], ensure_ascii=False),
|
||||
summary,
|
||||
),
|
||||
)
|
||||
report_id = int(cur.lastrowid)
|
||||
|
||||
report_view = {
|
||||
"id": report_id,
|
||||
"batch_no": batch_no,
|
||||
"invoice_number": invoice_number,
|
||||
"seller_name": str(inv.get("sellerName") or ""),
|
||||
"amount": _to_float(inv.get("amount")),
|
||||
"verdict": verdict,
|
||||
"summary": summary,
|
||||
"verify_status": "待查验",
|
||||
"created_at": now_unix(),
|
||||
"pass_json": json.dumps([i for i in items if i["level"] == "pass"], ensure_ascii=False),
|
||||
"warn_json": json.dumps([i for i in items if i["level"] == "warn"], ensure_ascii=False),
|
||||
"reject_json": json.dumps([i for i in items if i["level"] == "reject"], ensure_ascii=False),
|
||||
}
|
||||
invoice_view = {
|
||||
"invoice_type": str(inv.get("invoiceType") or ""),
|
||||
"invoice_code": str(inv.get("invoiceCode") or ""),
|
||||
"invoice_number": invoice_number,
|
||||
"issue_date": _fmt_date(_parse_date(inv.get("issueDate"))),
|
||||
"amount": _to_float(inv.get("amount")),
|
||||
"buyer_name": str(inv.get("buyerName") or ""),
|
||||
"buyer_tax_no": str(inv.get("buyerTaxNo") or ""),
|
||||
"seller_name": str(inv.get("sellerName") or ""),
|
||||
"seller_tax_no": str(inv.get("sellerTaxNo") or ""),
|
||||
"expense_category": str(inv.get("expenseCategory") or ""),
|
||||
"city": str(inv.get("city") or ""),
|
||||
}
|
||||
report_file = write_report_for_kernel(
|
||||
report_id=report_id,
|
||||
report=report_view,
|
||||
invoice=invoice_view,
|
||||
context=context,
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE prereview_reports SET report_file = ? WHERE id = ?",
|
||||
(report_file, report_id),
|
||||
)
|
||||
|
||||
results.append(
|
||||
{
|
||||
"report_id": report_id,
|
||||
"batch_no": batch_no,
|
||||
"invoice_id": invoice_id,
|
||||
"invoice_number": invoice_number,
|
||||
"verdict": verdict,
|
||||
"summary": summary,
|
||||
"items": items,
|
||||
"report_file": report_file,
|
||||
}
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
counts = {v: sum(1 for r in results if r["verdict"] == v) for v in (_VERDICT_PASS, _VERDICT_WARN, _VERDICT_REJECT)}
|
||||
payload = {
|
||||
"ok": True,
|
||||
"batch_no": batch_no,
|
||||
"count": len(results),
|
||||
"verdict_counts": counts,
|
||||
"disclaimer": "预审结果仅作提示,不构成最终报销结论;发票真伪以官方查验结果为准。",
|
||||
"reports": results,
|
||||
}
|
||||
if log:
|
||||
log.info(
|
||||
"prereview_kernel_done batch_no=%s pass=%s warn=%s reject=%s stage=kernel",
|
||||
batch_no,
|
||||
counts[_VERDICT_PASS],
|
||||
counts[_VERDICT_WARN],
|
||||
counts[_VERDICT_REJECT],
|
||||
)
|
||||
return payload
|
||||
182
scripts/service/report_service.py
Normal file
182
scripts/service/report_service.py
Normal file
@@ -0,0 +1,182 @@
|
||||
"""《初审意见单》HTML 报告组装。
|
||||
|
||||
写入 `{skill_data}/html/report-{report_id}.html`,宿主数据管理侧栏可预览;
|
||||
重新生成走固定 Action id `render-html`(见 references/ACTIONS.md)。
|
||||
`{{BODY}}` 内数据一律经 html.escape 转义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from service.html_page_service import load_html_template, render_html_placeholders, write_html_page
|
||||
from util.timeutil import unix_to_iso
|
||||
|
||||
_TEMPLATE_REL = "assets/html/prereview-report.html"
|
||||
|
||||
_LEVEL_BADGE = {"pass": "✅", "warn": "⚠️", "reject": "❌"}
|
||||
|
||||
|
||||
def _esc(value: Any) -> str:
|
||||
return html.escape(str(value if value is not None else ""), quote=True)
|
||||
|
||||
|
||||
def _items_rows(items_json: str) -> str:
|
||||
try:
|
||||
items = json.loads(items_json) if items_json else []
|
||||
except (TypeError, ValueError):
|
||||
items = []
|
||||
if not items:
|
||||
return '<tr><td colspan="3" class="muted">无</td></tr>'
|
||||
rows = []
|
||||
for item in items:
|
||||
badge = _LEVEL_BADGE.get(str(item.get("level") or ""), "•")
|
||||
ref = str(item.get("rule_ref") or "")
|
||||
ref_cell = f'<span class="ref">依据:{_esc(ref)}</span>' if ref else ""
|
||||
rows.append(
|
||||
"<tr>"
|
||||
f'<td class="nowrap">{badge} {_esc(item.get("rule_id"))}</td>'
|
||||
f'<td>{_esc(item.get("name"))}<br/><span class="muted">{_esc(item.get("detail"))}</span>{ref_cell}</td>'
|
||||
f'<td class="nowrap">{_esc(item.get("level"))}</td>'
|
||||
"</tr>"
|
||||
)
|
||||
return "".join(rows)
|
||||
|
||||
|
||||
def _info_table(inv: dict[str, Any]) -> str:
|
||||
fields = (
|
||||
("发票类型", "invoice_type"),
|
||||
("发票代码", "invoice_code"),
|
||||
("发票号码", "invoice_number"),
|
||||
("开票日期", "issue_date"),
|
||||
("金额(元)", "amount"),
|
||||
("购买方名称", "buyer_name"),
|
||||
("购买方税号", "buyer_tax_no"),
|
||||
("销售方名称", "seller_name"),
|
||||
("销售方税号", "seller_tax_no"),
|
||||
("费用类别", "expense_category"),
|
||||
("消费城市", "city"),
|
||||
)
|
||||
rows = "".join(
|
||||
f"<tr><th>{_esc(label)}</th><td>{_esc(inv.get(key) if inv.get(key) not in (None, '') else '—')}</td></tr>"
|
||||
for label, key in fields
|
||||
)
|
||||
return f'<table class="info">{rows}</table>'
|
||||
|
||||
|
||||
def _context_table(context: dict[str, Any]) -> str:
|
||||
fields = (
|
||||
("报销事由", "purpose"),
|
||||
("预算项目编号", "project_no"),
|
||||
("出差开始", "trip_start"),
|
||||
("出差结束", "trip_end"),
|
||||
("目的地", "trip_city"),
|
||||
("职级", "staff_title"),
|
||||
)
|
||||
rows = []
|
||||
for label, key in fields:
|
||||
value = str(context.get(key) or "").strip()
|
||||
if value:
|
||||
rows.append(f"<tr><th>{_esc(label)}</th><td>{_esc(value)}</td></tr>")
|
||||
if not rows:
|
||||
return ""
|
||||
return f'<table class="info">{"".join(rows)}</table>'
|
||||
|
||||
|
||||
def build_report_html(
|
||||
*,
|
||||
report: dict[str, Any],
|
||||
invoice: dict[str, Any],
|
||||
context: dict[str, Any],
|
||||
) -> str:
|
||||
"""组装完整《初审意见单》HTML 文本。"""
|
||||
verdict = str(report.get("verdict") or "")
|
||||
badge = {"通过": "verdict-pass", "待确认": "verdict-warn", "驳回": "verdict-reject"}.get(verdict, "verdict-warn")
|
||||
mark = {"通过": "✅ 通过", "待确认": "⚠️ 待确认", "驳回": "❌ 驳回"}.get(verdict, verdict)
|
||||
|
||||
verify_status = str(report.get("verify_status") or "待查验")
|
||||
verify_note = str(report.get("verify_note") or "")
|
||||
created = unix_to_iso(report.get("created_at"))
|
||||
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
<span class="verdict {badge}">{mark}</span>
|
||||
<span class="muted">批次 {_esc(report.get("batch_no"))} · 报告编号 {_esc(report.get("id"))} · 生成于 {_esc(created or "")}</span>
|
||||
</div>
|
||||
<p class="summary">{_esc(report.get("summary"))}</p>
|
||||
<div class="section"><h2>发票信息</h2>{_info_table(invoice)}</div>
|
||||
<div class="section"><h2>报销上下文</h2>{_context_table(context) or '<p class="muted">未提供差旅/项目上下文。</p>'}</div>
|
||||
<div class="section"><h2>❌ 驳回项(必须整改)</h2><table><tr><th>规则</th><th>说明</th><th>级别</th></tr>{_items_rows(report.get("reject_json") or "")}</table></div>
|
||||
<div class="section"><h2>⚠️ 待确认项(请核实)</h2><table><tr><th>规则</th><th>说明</th><th>级别</th></tr>{_items_rows(report.get("warn_json") or "")}</table></div>
|
||||
<div class="section"><h2>✅ 通过项</h2><table><tr><th>规则</th><th>说明</th><th>级别</th></tr>{_items_rows(report.get("pass_json") or "")}</table></div>
|
||||
<div class="section"><h2>真伪查验</h2>
|
||||
<p>当前状态:<strong>{_esc(verify_status)}</strong>{(" · 备注:" + _esc(verify_note)) if verify_note else ""}</p>
|
||||
<p class="muted">请经办人到全国增值税发票查验平台(inv-veri.chinatax.gov.cn)核验票面真伪后,在数据管理“初审意见”表回填查验结果。</p>
|
||||
</div>
|
||||
<footer>本《初审意见单》由票据合规预审助手自动生成,预审结果不构成最终报销结论,请以财务处人工审核为准。</footer>
|
||||
"""
|
||||
|
||||
template = load_html_template(_TEMPLATE_REL)
|
||||
return render_html_placeholders(
|
||||
template,
|
||||
{
|
||||
"TITLE": f"初审意见单 · 发票 {report.get('invoice_number') or ''}",
|
||||
"GENERATED_AT": created or "",
|
||||
"BODY": body,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def build_report_for_invoice(report_id: int, batch_no: str = "") -> str:
|
||||
"""按报告编号从库中取数并写出 HTML,返回文件绝对路径(重建入口用)。"""
|
||||
from db.connection import get_conn
|
||||
from util.logging_config import get_skill_logger
|
||||
|
||||
log = get_skill_logger()
|
||||
log.info("report_render_start report_id=%s stage=render", report_id)
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM prereview_reports WHERE id = ?", (report_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"初审报告不存在:{report_id}")
|
||||
report = _row_to_dict(cur, "prereview_reports", row)
|
||||
invoice = {}
|
||||
if report.get("invoice_id"):
|
||||
cur.execute("SELECT * FROM invoice_records WHERE id = ?", (report["invoice_id"],))
|
||||
irow = cur.fetchone()
|
||||
if irow:
|
||||
invoice = _row_to_dict(cur, "invoice_records", irow)
|
||||
context: dict[str, Any] = {}
|
||||
try:
|
||||
context = json.loads(invoice.get("trip_context_json") or "{}")
|
||||
except (TypeError, ValueError):
|
||||
context = {}
|
||||
html_text = build_report_html(report=report, invoice=invoice, context=context)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
filename = f"report-{report_id}.html"
|
||||
path = write_html_page(filename, html_text)
|
||||
log.info("report_render_done report_id=%s path=%s stage=render", report_id, path)
|
||||
return path
|
||||
|
||||
|
||||
def write_report_for_kernel(
|
||||
*,
|
||||
report_id: int,
|
||||
report: dict[str, Any],
|
||||
invoice: dict[str, Any],
|
||||
context: dict[str, Any],
|
||||
) -> str:
|
||||
"""内核路径:用事务内内存数据直接组装并写出 HTML(不回查未提交的行)。"""
|
||||
html_text = build_report_html(report=report, invoice=invoice, context=context)
|
||||
return write_html_page(f"report-{report_id}.html", html_text)
|
||||
|
||||
|
||||
def _row_to_dict(cursor, table_name: str, row) -> dict[str, Any]:
|
||||
columns = [desc[0] for desc in cursor.description]
|
||||
return dict(zip(columns, row))
|
||||
57
scripts/service/sibling_bridge.py
Normal file
57
scripts/service/sibling_bridge.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""兄弟技能 CLI 调用工具。
|
||||
|
||||
通过子进程调用同级其他 skill 的 main.py,并解析 JSON 输出。
|
||||
具体调用哪些兄弟技能,由复制后的业务 skill 在 service 层按需决定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from util.logging_config import subprocess_env_with_trace
|
||||
from util.runtime_paths import get_skills_root
|
||||
|
||||
|
||||
def call_sibling_json(skill_slug: str, args: List[str]) -> Optional[Dict[str, Any]]:
|
||||
"""通用兄弟技能调用器。
|
||||
|
||||
Args:
|
||||
skill_slug: 兄弟技能的 slug(即同级目录名)。
|
||||
args: 传给 main.py 的命令行参数列表。
|
||||
|
||||
Returns:
|
||||
若兄弟技能输出可解析的 JSON 对象则返回 dict;否则返回 None。
|
||||
"""
|
||||
script_path = os.path.join(get_skills_root(), skill_slug, "scripts", "main.py")
|
||||
if not os.path.isfile(script_path):
|
||||
return None
|
||||
proc = subprocess.run(
|
||||
[sys.executable, script_path, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
env=subprocess_env_with_trace(),
|
||||
)
|
||||
raw = (proc.stdout or "").strip()
|
||||
if not raw or raw.startswith("ERROR"):
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def get_sibling_main_path(skill_slug: str) -> str:
|
||||
"""获取兄弟技能的 main.py 绝对路径。
|
||||
|
||||
使用示例(在 task_service.py 中):
|
||||
from service.sibling_bridge import get_sibling_main_path, call_sibling_json
|
||||
result = call_sibling_json("account-manager", ["list", "--limit", "10"])
|
||||
"""
|
||||
return os.path.join(get_skills_root(), skill_slug, "scripts", "main.py")
|
||||
366
scripts/service/standards_service.py
Normal file
366
scripts/service/standards_service.py
Normal file
@@ -0,0 +1,366 @@
|
||||
"""经费标准库 / 税号白名单 / 节假日 / 初审记录 的查询与维护。
|
||||
|
||||
预审内核只读本模块数据;维护操作(改标准、增删白名单、查验回填)在此实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from typing import Any, Optional
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.timeutil import now_unix
|
||||
|
||||
VERIFY_PENDING = "待查验"
|
||||
VERIFY_PASS = "已查验通过"
|
||||
VERIFY_FAIL = "已查验不符"
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def list_standards(category: Optional[str] = None) -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if category:
|
||||
cur.execute(
|
||||
"SELECT id, category, city_tier, city_example, staff_title, max_amount, unit, basis_doc, clause, effective_date FROM expense_standards WHERE category = ? ORDER BY category, city_tier, staff_title",
|
||||
(category,),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"SELECT id, category, city_tier, city_example, staff_title, max_amount, unit, basis_doc, clause, effective_date FROM expense_standards ORDER BY category, city_tier, staff_title"
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [
|
||||
{
|
||||
"id": r[0],
|
||||
"category": r[1],
|
||||
"city_tier": r[2],
|
||||
"city_example": r[3],
|
||||
"staff_title": r[4],
|
||||
"max_amount": r[5],
|
||||
"unit": r[6],
|
||||
"basis_doc": r[7],
|
||||
"clause": r[8],
|
||||
"effective_date": r[9],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def upsert_standard(
|
||||
*,
|
||||
category: str,
|
||||
city_tier: str,
|
||||
staff_title: str,
|
||||
max_amount: float,
|
||||
unit: str = "",
|
||||
basis_doc: str = "",
|
||||
clause: str = "",
|
||||
city_example: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""按 (类别, 城市等级, 职级) 幂等更新标准值。"""
|
||||
if not category or not city_tier or not staff_title:
|
||||
raise ValueError("类别 / 城市等级 / 职级 均不能为空")
|
||||
if max_amount <= 0:
|
||||
raise ValueError("标准值必须大于 0")
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT id FROM expense_standards WHERE category = ? AND city_tier = ? AND staff_title = ?",
|
||||
(category, city_tier, staff_title),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE expense_standards
|
||||
SET max_amount = ?, unit = ?, basis_doc = ?, clause = ?,
|
||||
city_example = COALESCE(NULLIF(?, ''), city_example), updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(max_amount, unit, basis_doc, clause, city_example, now_unix(), int(row[0])),
|
||||
)
|
||||
standard_id = int(row[0])
|
||||
action = "updated"
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO expense_standards
|
||||
(category, city_tier, city_example, staff_title, max_amount, unit, basis_doc, clause, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(category, city_tier, city_example, staff_title, max_amount, unit, basis_doc, clause, now_unix(), now_unix()),
|
||||
)
|
||||
standard_id = int(cur.lastrowid)
|
||||
action = "created"
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info(
|
||||
"standard_upserted standard_id=%s action=%s category=%s tier=%s title=%s stage=standard",
|
||||
standard_id,
|
||||
action,
|
||||
category,
|
||||
city_tier,
|
||||
staff_title,
|
||||
)
|
||||
return {"ok": True, "id": standard_id, "action": action, "category": category, "city_tier": city_tier, "staff_title": staff_title, "max_amount": max_amount}
|
||||
|
||||
|
||||
def list_whitelist() -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id, tax_no, org_name, note, created_at FROM taxid_whitelist ORDER BY id")
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [{"id": r[0], "tax_no": r[1], "org_name": r[2], "note": r[3], "created_at": r[4]} for r in rows]
|
||||
|
||||
|
||||
def add_whitelist(tax_no: str, org_name: str, note: str = "") -> dict[str, Any]:
|
||||
tax_no = (tax_no or "").strip()
|
||||
if not tax_no:
|
||||
raise ValueError("税号不能为空")
|
||||
if not org_name:
|
||||
raise ValueError("单位名称不能为空")
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM taxid_whitelist WHERE tax_no = ?", (tax_no,))
|
||||
if cur.fetchone():
|
||||
raise ValueError(f"税号已存在:{tax_no}")
|
||||
cur.execute(
|
||||
"INSERT INTO taxid_whitelist (tax_no, org_name, note, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
|
||||
(tax_no, org_name, note, now_unix(), now_unix()),
|
||||
)
|
||||
whitelist_id = int(cur.lastrowid)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {"ok": True, "id": whitelist_id, "tax_no": tax_no, "org_name": org_name}
|
||||
|
||||
|
||||
def remove_whitelist(tax_no: str) -> dict[str, Any]:
|
||||
tax_no = (tax_no or "").strip()
|
||||
if not tax_no:
|
||||
raise ValueError("税号不能为空")
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("DELETE FROM taxid_whitelist WHERE tax_no = ?", (tax_no,))
|
||||
deleted = cur.rowcount
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
if not deleted:
|
||||
raise ValueError(f"白名单中不存在该税号:{tax_no}")
|
||||
return {"ok": True, "removed": tax_no}
|
||||
|
||||
|
||||
def list_holidays(year: Optional[str] = None) -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if year:
|
||||
cur.execute(
|
||||
"SELECT id, holiday_date, holiday_name FROM holiday_calendar WHERE holiday_date LIKE ? ORDER BY holiday_date",
|
||||
(f"{year}%",),
|
||||
)
|
||||
else:
|
||||
cur.execute("SELECT id, holiday_date, holiday_name FROM holiday_calendar ORDER BY holiday_date")
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [{"id": r[0], "holiday_date": r[1], "holiday_name": r[2]} for r in rows]
|
||||
|
||||
|
||||
def list_reports(limit: int = 20, verdict: Optional[str] = None) -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
limit = max(1, min(int(limit), 200))
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if verdict:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, batch_no, invoice_number, seller_name, amount, verdict, verify_status, summary, report_file, created_at
|
||||
FROM prereview_reports WHERE verdict = ? ORDER BY id DESC LIMIT ?
|
||||
""",
|
||||
(verdict, limit),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, batch_no, invoice_number, seller_name, amount, verdict, verify_status, summary, report_file, created_at
|
||||
FROM prereview_reports ORDER BY id DESC LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [
|
||||
{
|
||||
"id": r[0],
|
||||
"batch_no": r[1],
|
||||
"invoice_number": r[2],
|
||||
"seller_name": r[3],
|
||||
"amount": r[4],
|
||||
"verdict": r[5],
|
||||
"verify_status": r[6],
|
||||
"summary": r[7],
|
||||
"report_file": r[8],
|
||||
"created_at": r[9],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def get_report(report_id: int) -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM prereview_reports WHERE id = ?", (report_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"初审报告不存在:{report_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
report = dict(zip(columns, row))
|
||||
invoice: dict[str, Any] = {}
|
||||
if report.get("invoice_id"):
|
||||
cur.execute("SELECT * FROM invoice_records WHERE id = ?", (report["invoice_id"],))
|
||||
irow = cur.fetchone()
|
||||
if irow:
|
||||
icolumns = [d[0] for d in cur.description]
|
||||
invoice = dict(zip(icolumns, irow))
|
||||
finally:
|
||||
conn.close()
|
||||
for key in ("pass_json", "warn_json", "reject_json"):
|
||||
try:
|
||||
report[key] = json.loads(report.get(key) or "[]")
|
||||
except (TypeError, ValueError):
|
||||
report[key] = []
|
||||
report["invoice"] = invoice
|
||||
return report
|
||||
|
||||
|
||||
def mark_verified(report_id: int, result: str, note: str = "") -> dict[str, Any]:
|
||||
"""回填人工查验结果;查验“不符”则结论升级为驳回。"""
|
||||
result = (result or "").strip().lower()
|
||||
if result not in ("pass", "fail"):
|
||||
raise ValueError("查验结果只接受 pass / fail")
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id, verdict, reject_json FROM prereview_reports WHERE id = ?", (report_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"初审报告不存在:{report_id}")
|
||||
_report_id, verdict, reject_json = int(row[0]), str(row[1]), row[2] or "[]"
|
||||
|
||||
if result == "pass":
|
||||
verify_status = VERIFY_PASS
|
||||
else:
|
||||
verify_status = VERIFY_FAIL
|
||||
try:
|
||||
rejects = json.loads(reject_json)
|
||||
except (TypeError, ValueError):
|
||||
rejects = []
|
||||
rejects.append(
|
||||
{
|
||||
"rule_id": "V1",
|
||||
"name": "发票真伪",
|
||||
"level": "reject",
|
||||
"detail": "人工查验回填:票面信息与查验平台不符,判定为问题票据。",
|
||||
"rule_ref": "全国增值税发票查验平台(inv-veri.chinatax.gov.cn)",
|
||||
}
|
||||
)
|
||||
reject_json = json.dumps(rejects, ensure_ascii=False)
|
||||
|
||||
new_verdict = "驳回" if result == "fail" else verdict
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE prereview_reports
|
||||
SET verify_status = ?, verify_note = ?, verify_updated_at = ?,
|
||||
verdict = ?, reject_json = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(verify_status, note, now_unix(), new_verdict, reject_json, report_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info(
|
||||
"verify_marked report_id=%s result=%s verdict=%s stage=verify",
|
||||
report_id,
|
||||
result,
|
||||
new_verdict,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"report_id": report_id,
|
||||
"verify_status": verify_status,
|
||||
"verdict": new_verdict,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
def stats() -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT verdict, COUNT(*) FROM prereview_reports GROUP BY verdict")
|
||||
by_verdict = {str(r[0]): int(r[1]) for r in cur.fetchall()}
|
||||
cur.execute("SELECT COUNT(*) FROM invoice_records")
|
||||
invoice_total = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT COUNT(*) FROM taxid_whitelist")
|
||||
whitelist_total = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT COUNT(*) FROM expense_standards")
|
||||
standards_total = int(cur.fetchone()[0])
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT seller_name, COUNT(*) AS cnt FROM invoice_records
|
||||
WHERE seller_name != ''
|
||||
GROUP BY seller_name ORDER BY cnt DESC LIMIT 5
|
||||
"""
|
||||
)
|
||||
top_sellers = [{"seller_name": r[0], "count": int(r[1])} for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
total_reports = sum(by_verdict.values())
|
||||
return {
|
||||
"ok": True,
|
||||
"invoice_total": invoice_total,
|
||||
"report_total": total_reports,
|
||||
"verdict_counts": by_verdict,
|
||||
"reject_rate": round(by_verdict.get("驳回", 0) / total_reports, 4) if total_reports else 0.0,
|
||||
"whitelist_total": whitelist_total,
|
||||
"standards_total": standards_total,
|
||||
"top_sellers": top_sellers,
|
||||
}
|
||||
84
scripts/service/task_run_support.py
Normal file
84
scripts/service/task_run_support.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""任务运行辅助:录屏信息组装与 CLI 输出(通用模板,无业务逻辑)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
def build_video_info(
|
||||
video_summary: dict[str, Any],
|
||||
compose_context_before: Optional[dict[str, Any]] = None,
|
||||
compose_context_after: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""将 RpaVideoSession.summary() 转为 finish() / CLI 可用的 video 块。"""
|
||||
return {
|
||||
"enabled": video_summary.get("enabled", False),
|
||||
"path": video_summary.get("path"),
|
||||
"capture_path": video_summary.get("capture_path"),
|
||||
"record_log_path": video_summary.get("record_log_path"),
|
||||
"warnings": list(video_summary.get("warnings") or []),
|
||||
"voiceover_path": video_summary.get("voiceover_path"),
|
||||
"music_path": video_summary.get("music_path"),
|
||||
"audio_warnings": list(video_summary.get("audio_warnings") or []),
|
||||
"compose_context": {
|
||||
**(compose_context_before or {}),
|
||||
"after_compose": compose_context_after or {},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def merge_video_into_result_summary(
|
||||
payload: dict[str, Any],
|
||||
video_info: Optional[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""把 video artifact 字段写入 finish() 结果对象(video / video_path 等)。"""
|
||||
if not video_info:
|
||||
return payload
|
||||
payload = dict(payload)
|
||||
payload["video"] = video_info
|
||||
payload["video_path"] = video_info.get("path")
|
||||
payload["raw_video"] = video_info.get("capture_path")
|
||||
payload["video_log"] = video_info.get("record_log_path")
|
||||
payload["video_warnings"] = list(video_info.get("warnings") or [])
|
||||
payload["voiceover_path"] = video_info.get("voiceover_path")
|
||||
payload["music_path"] = video_info.get("music_path")
|
||||
payload["audio_warnings"] = list(video_info.get("audio_warnings") or [])
|
||||
return payload
|
||||
|
||||
|
||||
def _print_video_summary(video_block: Optional[dict[str, Any]]) -> None:
|
||||
"""任务完成后在 CLI 打印录屏路径、日志与诊断信息。"""
|
||||
if not isinstance(video_block, dict) or not video_block.get("enabled"):
|
||||
return
|
||||
record_log = video_block.get("record_log_path")
|
||||
if record_log:
|
||||
print(f"录屏日志:{record_log}")
|
||||
path = video_block.get("path")
|
||||
if path:
|
||||
print(f"录屏路径:{path}")
|
||||
else:
|
||||
print("录屏路径:未生成")
|
||||
warnings = video_block.get("warnings") or []
|
||||
if warnings:
|
||||
print(f"视频诊断:{'; '.join(str(w) for w in warnings)}")
|
||||
capture = video_block.get("capture_path")
|
||||
if capture:
|
||||
print(f"原始录屏路径:{capture}")
|
||||
voiceover = video_block.get("voiceover_path")
|
||||
if voiceover:
|
||||
print(f"旁白路径:{voiceover}")
|
||||
music = video_block.get("music_path")
|
||||
if music:
|
||||
print(f"背景音乐:{music}")
|
||||
audio_warnings = video_block.get("audio_warnings") or []
|
||||
if audio_warnings:
|
||||
print(f"音频诊断:{'; '.join(str(w) for w in audio_warnings)}")
|
||||
compose_ctx = video_block.get("compose_context")
|
||||
if isinstance(compose_ctx, dict):
|
||||
print(
|
||||
"视频合成上下文:"
|
||||
f"media_assets_root={compose_ctx.get('media_assets_root', '')}; "
|
||||
f"ffmpeg_path={compose_ctx.get('ffmpeg_path', '')}; "
|
||||
f"background_music_issue={compose_ctx.get('background_music_issue') or ''}; "
|
||||
f"background_music_sample_path={compose_ctx.get('background_music_sample_path', '')}"
|
||||
)
|
||||
699
scripts/service/task_service.py
Normal file
699
scripts/service/task_service.py
Normal file
@@ -0,0 +1,699 @@
|
||||
"""任务编排层:job_context / emit / finish、鉴权与错误转换。
|
||||
|
||||
领域业务在 ``service/prereview_service.py``(预审内核)、
|
||||
``service/standards_service.py``(标准库/白名单/查验回填)、
|
||||
``service/report_service.py``(HTML 意见单),由本模块调用;
|
||||
多入口(CLI / Action / 对话)复用同一内核,禁止按入口分叉业务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from jiangchang_skill_core import collect_runtime_diagnostics, config, format_runtime_health_lines
|
||||
from jiangchang_skill_core.activity import JobStopped, emit, finish, job_context
|
||||
|
||||
from jiangchang_skill_core.rpa.video_session import RpaVideoSession
|
||||
from service.entitlement_service import check_entitlement
|
||||
from service.task_run_support import (
|
||||
_print_video_summary,
|
||||
build_video_info,
|
||||
merge_video_into_result_summary,
|
||||
)
|
||||
from util.constants import LOG_LOGGER_NAME, PLATFORM_KIT_MIN_VERSION, SKILL_SLUG, SKILL_VERSION
|
||||
from util.logging_config import get_skill_logger, setup_skill_logging
|
||||
from util.runtime_paths import get_db_path, get_input_dir, get_skill_root
|
||||
from db.connection import init_db
|
||||
|
||||
|
||||
def _get_task_logger():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
setup_skill_logging(SKILL_SLUG, LOG_LOGGER_NAME)
|
||||
return get_skill_logger()
|
||||
|
||||
|
||||
def _print_json(payload: dict[str, Any]) -> None:
|
||||
print(json.dumps(payload, ensure_ascii=False))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 模板演示入口(保留:满足 POLICY-RPA-003 录屏集成与 CLI run 契约;不承载本技能业务)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _run_template_demo(target: Optional[str], input_id: Optional[str]) -> tuple[int, dict[str, Any]]:
|
||||
"""最小 RpaVideoSession 示范:不启动浏览器、不执行业务,仅演示录屏包裹范式。"""
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
data_dir = get_skill_root()
|
||||
|
||||
async with RpaVideoSession(
|
||||
skill_slug=SKILL_SLUG,
|
||||
skill_data_dir=data_dir,
|
||||
batch_id=batch_id,
|
||||
title="开始执行示例任务",
|
||||
closing_title="示例任务执行完成",
|
||||
) as video:
|
||||
video.add_step("准备执行示例任务")
|
||||
if target:
|
||||
video.add_step(f"接收目标参数:{target}")
|
||||
if input_id:
|
||||
video.add_step(f"接收输入标识:{input_id}")
|
||||
video.add_step("示例任务执行完成")
|
||||
|
||||
video_summary = video.summary()
|
||||
video_info = build_video_info(video_summary, {}, {})
|
||||
return 1, video_info
|
||||
|
||||
|
||||
def cmd_run(target: Optional[str] = None, input_id: Optional[str] = None) -> int:
|
||||
"""模板演示入口:本技能主能力请使用 prereview 等业务命令。"""
|
||||
log = _get_task_logger()
|
||||
task_type = "demo"
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info(
|
||||
"task_start task_type=%s target_id=%s input_id=%s stage=run",
|
||||
task_type,
|
||||
target,
|
||||
input_id,
|
||||
)
|
||||
emit("开始处理任务", skill=SKILL_SLUG, stage="run")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning(
|
||||
"entitlement_failed task_type=%s stage=auth error_code=ENTITLEMENT_DENIED",
|
||||
task_type,
|
||||
)
|
||||
emit("鉴权失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="auth")
|
||||
finish(
|
||||
status="failed",
|
||||
message=reason,
|
||||
skill=SKILL_SLUG,
|
||||
error_code="ENTITLEMENT_DENIED",
|
||||
stage="auth",
|
||||
)
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
log.info("entitlement_ok task_type=%s stage=auth", task_type)
|
||||
log.info("rpa_start stage=demo_prepare task_type=%s", task_type)
|
||||
log.info("task_run_demo_start target_id=%s input_id=%s stage=demo_prepare", target, input_id)
|
||||
rc, video_info = asyncio.run(_run_template_demo(target, input_id))
|
||||
log.info("rpa_done stage=demo_prepare status=ok")
|
||||
log.info(
|
||||
"task_run_demo_done target_id=%s input_id=%s stage=demo_finish status=failed",
|
||||
target,
|
||||
input_id,
|
||||
)
|
||||
_print_video_summary(video_info)
|
||||
|
||||
summary_payload = merge_video_into_result_summary(
|
||||
{
|
||||
"template_demo": True,
|
||||
"target": target,
|
||||
"input_id": input_id,
|
||||
},
|
||||
video_info,
|
||||
)
|
||||
|
||||
log.warning(
|
||||
"task_failed task_type=%s stage=demo_finish error_code=TEMPLATE_STUB",
|
||||
task_type,
|
||||
)
|
||||
finish(
|
||||
status="failed",
|
||||
message="模板演示入口未承载本技能业务",
|
||||
skill=SKILL_SLUG,
|
||||
error_code="TEMPLATE_STUB",
|
||||
**summary_payload,
|
||||
)
|
||||
print("ERROR:TEMPLATE_STUB 这是模板演示入口,请使用 prereview 命令执行票据合规预审。")
|
||||
return rc
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception(
|
||||
"task_failed task_type=%s target_id=%s input_id=%s",
|
||||
task_type,
|
||||
target,
|
||||
input_id,
|
||||
)
|
||||
emit("任务失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="run")
|
||||
finish(
|
||||
status="failed",
|
||||
message="任务执行异常,详见统一日志",
|
||||
skill=SKILL_SLUG,
|
||||
stage="run",
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 基础命令
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_config_path() -> int:
|
||||
example_path = os.path.join(get_skill_root(), ".env.example")
|
||||
env_path = config.get_env_file_path() or ""
|
||||
_print_json(
|
||||
{
|
||||
"skill": SKILL_SLUG,
|
||||
"env_path": env_path,
|
||||
"example_path": os.path.abspath(example_path),
|
||||
}
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_health() -> int:
|
||||
runtime = collect_runtime_diagnostics(
|
||||
skill_slug=SKILL_SLUG,
|
||||
platform_kit_min_version=PLATFORM_KIT_MIN_VERSION,
|
||||
skill_root=get_skill_root(),
|
||||
)
|
||||
example_path = os.path.join(get_skill_root(), ".env.example")
|
||||
env_path = config.get_env_file_path() or ""
|
||||
env_exists = bool(env_path and os.path.isfile(env_path))
|
||||
|
||||
health_status = "failed" if runtime.has_fatal_issues else "ok"
|
||||
lines = [
|
||||
f"{SKILL_SLUG} health: {health_status}",
|
||||
*format_runtime_health_lines(runtime),
|
||||
f"env_path: {env_path}",
|
||||
f"env_exists: {env_exists}",
|
||||
f"example_path: {os.path.abspath(example_path)}",
|
||||
]
|
||||
for line in lines:
|
||||
print(line)
|
||||
return 1 if runtime.has_fatal_issues else 0
|
||||
|
||||
|
||||
def cmd_version() -> int:
|
||||
_print_json({"version": SKILL_VERSION, "skill": SKILL_SLUG})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_init_db() -> int:
|
||||
"""幂等创建/迁移本地 SQLite 与数据管理元数据(宿主 install/upgrade 可调用)。"""
|
||||
log = _get_task_logger()
|
||||
try:
|
||||
seeded = init_db()
|
||||
except Exception as exc: # noqa: BLE001 — CLI 边界,统一成可机读失败
|
||||
print(
|
||||
json.dumps(
|
||||
{"ok": False, "skill": SKILL_SLUG, "error": str(exc)},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 1
|
||||
_print_json(
|
||||
{
|
||||
"ok": True,
|
||||
"skill": SKILL_SLUG,
|
||||
"db_path": get_db_path(),
|
||||
"seeded": seeded,
|
||||
}
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 预审主命令
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _load_invoice_payload(invoice_json: str) -> list[dict[str, Any]]:
|
||||
"""解析 --invoice-json:支持 '-'(stdin)、文件路径、内联 JSON。"""
|
||||
from service.prereview_service import _norm_invoice
|
||||
|
||||
raw = (invoice_json or "").strip()
|
||||
if not raw:
|
||||
raise ValueError("缺少发票字段 JSON(--invoice-json)")
|
||||
if raw == "-":
|
||||
import sys
|
||||
|
||||
raw = sys.stdin.read().strip()
|
||||
elif raw.startswith(("[", "{")):
|
||||
pass
|
||||
elif os.path.isfile(raw):
|
||||
with open(raw, encoding="utf-8") as f:
|
||||
raw = f.read().strip()
|
||||
else:
|
||||
raise ValueError(f"--invoice-json 不是有效文件路径或 JSON:{raw[:80]}")
|
||||
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"发票字段 JSON 解析失败:{exc}") from exc
|
||||
|
||||
if isinstance(payload, dict):
|
||||
# 兼容 {"invoices": [...]} 包装
|
||||
if isinstance(payload.get("invoices"), list):
|
||||
payload = payload["invoices"]
|
||||
else:
|
||||
payload = [payload]
|
||||
if not isinstance(payload, list):
|
||||
raise ValueError("发票字段 JSON 应为对象或对象数组")
|
||||
return [_norm_invoice(item) for item in payload]
|
||||
|
||||
|
||||
def cmd_prereview(
|
||||
*,
|
||||
invoice_json: str,
|
||||
purpose: str = "",
|
||||
project_no: str = "",
|
||||
trip_start: str = "",
|
||||
trip_end: str = "",
|
||||
trip_city: str = "",
|
||||
staff_title: str = "",
|
||||
) -> int:
|
||||
"""票据合规预审主命令:四步审核 → JSON 结果 + 写库 + 《初审意见单》。"""
|
||||
log = _get_task_logger()
|
||||
from service.prereview_service import run_prereview
|
||||
|
||||
context = {
|
||||
"purpose": purpose,
|
||||
"project_no": project_no,
|
||||
"trip_start": trip_start,
|
||||
"trip_end": trip_end,
|
||||
"trip_city": trip_city,
|
||||
"staff_title": staff_title,
|
||||
}
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=prereview stage=prereview")
|
||||
emit("开始票据合规预审", skill=SKILL_SLUG, stage="prereview")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=prereview stage=auth error_code=ENTITLEMENT_DENIED")
|
||||
emit("鉴权失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("prereview_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
log.info("entitlement_ok task_type=prereview stage=auth")
|
||||
try:
|
||||
invoices = _load_invoice_payload(invoice_json)
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=prereview stage=input error_code=INVOICE_INVALID detail=%s", exc)
|
||||
finish(
|
||||
status="failed",
|
||||
message=str(exc),
|
||||
skill=SKILL_SLUG,
|
||||
error_code="INVOICE_INVALID",
|
||||
stage="input",
|
||||
)
|
||||
log.error("prereview_invalid_input stage=input")
|
||||
print(f"ERROR:INVOICE_INVALID {exc}")
|
||||
return 1
|
||||
|
||||
result = run_prereview(invoices, context)
|
||||
_print_json(result)
|
||||
counts = result["verdict_counts"]
|
||||
emit(
|
||||
f"预审完成:通过 {counts.get('通过', 0)},待确认 {counts.get('待确认', 0)},驳回 {counts.get('驳回', 0)}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="prereview",
|
||||
)
|
||||
finish(
|
||||
status="success",
|
||||
message=(
|
||||
f"预审完成 {result['count']} 张:通过 {counts.get('通过', 0)},"
|
||||
f"待确认 {counts.get('待确认', 0)},驳回 {counts.get('驳回', 0)}"
|
||||
),
|
||||
skill=SKILL_SLUG,
|
||||
stage="prereview",
|
||||
batch_no=result["batch_no"],
|
||||
)
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=prereview stage=prereview")
|
||||
emit("预审失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="prereview")
|
||||
finish(status="failed", message="预审执行异常,详见统一日志", skill=SKILL_SLUG, stage="prereview")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_prereview_batch_input() -> int:
|
||||
"""批量预审 input/ 目录下的发票 JSON 文件(async Action 入口,任务中心可见进度)。"""
|
||||
log = _get_task_logger()
|
||||
from service.prereview_service import run_prereview
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=prereview_batch stage=batch")
|
||||
emit("开始批量预审", skill=SKILL_SLUG, stage="batch")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=prereview_batch stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("prereview_batch_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
input_dir = get_input_dir()
|
||||
files = sorted(
|
||||
os.path.join(input_dir, name)
|
||||
for name in os.listdir(input_dir)
|
||||
if name.lower().endswith(".json")
|
||||
)
|
||||
if not files:
|
||||
message = f"input 目录没有可预审的 JSON 文件:{input_dir}"
|
||||
log.warning("task_failed task_type=prereview_batch stage=batch error_code=INVOICE_INPUT_MISSING")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="INVOICE_INPUT_MISSING", stage="batch")
|
||||
log.error("prereview_batch_no_input stage=batch")
|
||||
print(f"ERROR:INVOICE_INPUT_MISSING {message}")
|
||||
return 1
|
||||
|
||||
all_results = []
|
||||
for index, path in enumerate(files, start=1):
|
||||
emit(f"处理 {index}/{len(files)}:{os.path.basename(path)}", skill=SKILL_SLUG, stage="batch")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if isinstance(payload, dict):
|
||||
invoices = payload.get("invoices") or [payload]
|
||||
context = payload.get("context") or {}
|
||||
else:
|
||||
invoices, context = payload, {}
|
||||
result = run_prereview(invoices, {k: str(v or "") for k, v in context.items()})
|
||||
all_results.append({"file": os.path.basename(path), "batch_no": result["batch_no"], "verdict_counts": result["verdict_counts"]})
|
||||
|
||||
_print_json({"ok": True, "files": len(all_results), "results": all_results})
|
||||
finish(status="success", message=f"批量预审完成,共处理 {len(all_results)} 个文件", skill=SKILL_SLUG, stage="batch")
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except json.JSONDecodeError as exc:
|
||||
log.exception("task_failed task_type=prereview_batch stage=batch error_code=INVOICE_INVALID")
|
||||
finish(status="failed", message=f"input 目录 JSON 解析失败:{exc}", skill=SKILL_SLUG, error_code="INVOICE_INVALID", stage="batch")
|
||||
print(f"ERROR:INVOICE_INVALID input 目录 JSON 解析失败:{exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=prereview_batch stage=batch")
|
||||
emit("批量预审失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="batch")
|
||||
finish(status="failed", message="批量预审执行异常,详见统一日志", skill=SKILL_SLUG, stage="batch")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 报告与查验回填
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_render_html(report_id: Optional[int] = None) -> int:
|
||||
"""重建《初审意见单》HTML;缺省重建最近 10 份。"""
|
||||
log = _get_task_logger()
|
||||
from service.report_service import build_report_for_invoice
|
||||
from service.standards_service import list_reports
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=render_html report_id=%s stage=render", report_id)
|
||||
try:
|
||||
if report_id:
|
||||
targets = [int(report_id)]
|
||||
else:
|
||||
targets = [r["id"] for r in list_reports(limit=10)]
|
||||
if not targets:
|
||||
log.warning("task_failed task_type=render_html error_code=REPORT_NOT_FOUND stage=render")
|
||||
finish(status="failed", message="暂无可重建的初审报告", skill=SKILL_SLUG, error_code="REPORT_NOT_FOUND", stage="render")
|
||||
print("ERROR:REPORT_NOT_FOUND 暂无可重建的初审报告")
|
||||
return 1
|
||||
written = []
|
||||
for rid in targets:
|
||||
written.append({"report_id": rid, "path": build_report_for_invoice(rid, "")})
|
||||
_print_json({"ok": True, "count": len(written), "reports": written})
|
||||
finish(status="success", message=f"已重建 {len(written)} 份初审意见单", skill=SKILL_SLUG, stage="render")
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=render_html error_code=REPORT_NOT_FOUND detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="REPORT_NOT_FOUND", stage="render")
|
||||
print(f"ERROR:REPORT_NOT_FOUND {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=render_html stage=render")
|
||||
finish(status="failed", message="意见单重建异常,详见统一日志", skill=SKILL_SLUG, stage="render")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_list_reports(limit: int = 20, verdict: Optional[str] = None) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import list_reports
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_reports limit=%s verdict=%s", limit, verdict)
|
||||
try:
|
||||
reports = list_reports(limit=limit, verdict=verdict)
|
||||
_print_json({"ok": True, "count": len(reports), "reports": reports})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_reports")
|
||||
print("ERROR:QUERY_FAILED 初审记录查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_show_report(report_id: int) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import get_report
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=show_report report_id=%s", report_id)
|
||||
try:
|
||||
report = get_report(int(report_id))
|
||||
_print_json({"ok": True, "report": report})
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=show_report error_code=REPORT_NOT_FOUND detail=%s", exc)
|
||||
print(f"ERROR:REPORT_NOT_FOUND {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=show_report")
|
||||
print("ERROR:QUERY_FAILED 初审报告查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_mark_verified(report_id: int, result: str, note: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import mark_verified
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=mark_verified report_id=%s result=%s", report_id, result)
|
||||
emit("开始回填查验结果", skill=SKILL_SLUG, stage="verify")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=mark_verified stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("mark_verified_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = mark_verified(int(report_id), result, note)
|
||||
_print_json(payload)
|
||||
finish(
|
||||
status="success",
|
||||
message=f"报告 {report_id} 查验结果已回填:{payload['verify_status']}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="verify",
|
||||
)
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=mark_verified error_code=VERIFY_INPUT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="VERIFY_INPUT_INVALID", stage="verify")
|
||||
print(f"ERROR:VERIFY_INPUT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=mark_verified stage=verify")
|
||||
finish(status="failed", message="查验回填异常,详见统一日志", skill=SKILL_SLUG, stage="verify")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 标准库 / 白名单 / 节假日 / 统计
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_view_standards(category: Optional[str] = None) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import list_standards
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=view_standards category=%s", category)
|
||||
try:
|
||||
standards = list_standards(category)
|
||||
_print_json({"ok": True, "count": len(standards), "standards": standards})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=view_standards")
|
||||
print("ERROR:QUERY_FAILED 标准库查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_set_standard(
|
||||
*,
|
||||
category: str,
|
||||
city_tier: str,
|
||||
staff_title: str,
|
||||
max_amount: float,
|
||||
unit: str = "",
|
||||
basis_doc: str = "",
|
||||
clause: str = "",
|
||||
city_example: str = "",
|
||||
) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import upsert_standard
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=set_standard category=%s tier=%s title=%s", category, city_tier, staff_title)
|
||||
emit("开始更新经费标准", skill=SKILL_SLUG, stage="standard")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=set_standard stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("set_standard_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = upsert_standard(
|
||||
category=category,
|
||||
city_tier=city_tier,
|
||||
staff_title=staff_title,
|
||||
max_amount=float(max_amount),
|
||||
unit=unit,
|
||||
basis_doc=basis_doc,
|
||||
clause=clause,
|
||||
city_example=city_example,
|
||||
)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"标准已更新:{category}/{city_tier}/{staff_title}", skill=SKILL_SLUG, stage="standard")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=set_standard error_code=STANDARD_INPUT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="STANDARD_INPUT_INVALID", stage="standard")
|
||||
print(f"ERROR:STANDARD_INPUT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=set_standard stage=standard")
|
||||
finish(status="failed", message="标准更新异常,详见统一日志", skill=SKILL_SLUG, stage="standard")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_list_whitelist() -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import list_whitelist
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_whitelist")
|
||||
try:
|
||||
items = list_whitelist()
|
||||
_print_json({"ok": True, "count": len(items), "items": items})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_whitelist")
|
||||
print("ERROR:QUERY_FAILED 白名单查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_add_whitelist(tax_no: str, org_name: str, note: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import add_whitelist
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=add_whitelist tax_no=%s", tax_no)
|
||||
emit("开始新增白名单税号", skill=SKILL_SLUG, stage="whitelist")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=add_whitelist stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("add_whitelist_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = add_whitelist(tax_no, org_name, note)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"已新增税号 {payload['tax_no']}", skill=SKILL_SLUG, stage="whitelist")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=add_whitelist error_code=WHITELIST_INPUT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="WHITELIST_INPUT_INVALID", stage="whitelist")
|
||||
print(f"ERROR:WHITELIST_INPUT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=add_whitelist stage=whitelist")
|
||||
finish(status="failed", message="白名单新增异常,详见统一日志", skill=SKILL_SLUG, stage="whitelist")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_remove_whitelist(tax_no: str) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import remove_whitelist
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=remove_whitelist tax_no=%s", tax_no)
|
||||
emit("开始删除白名单税号", skill=SKILL_SLUG, stage="whitelist")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=remove_whitelist stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("remove_whitelist_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = remove_whitelist(tax_no)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"已删除税号 {payload['removed']}", skill=SKILL_SLUG, stage="whitelist")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=remove_whitelist error_code=WHITELIST_INPUT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="WHITELIST_INPUT_INVALID", stage="whitelist")
|
||||
print(f"ERROR:WHITELIST_INPUT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=remove_whitelist stage=whitelist")
|
||||
finish(status="failed", message="白名单删除异常,详见统一日志", skill=SKILL_SLUG, stage="whitelist")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_list_holidays(year: Optional[str] = None) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import list_holidays
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_holidays year=%s", year)
|
||||
try:
|
||||
items = list_holidays(year)
|
||||
_print_json({"ok": True, "count": len(items), "holidays": items})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_holidays")
|
||||
print("ERROR:QUERY_FAILED 节假日查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_stats() -> int:
|
||||
log = _get_task_logger()
|
||||
from service.standards_service import stats
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=stats")
|
||||
try:
|
||||
_print_json(stats())
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=stats")
|
||||
print("ERROR:QUERY_FAILED 统计查询异常,详见统一日志")
|
||||
return 1
|
||||
Reference in New Issue
Block a user