feat: 项目经费进度播报助手首版 v1.0.1(track-fund-progress-default)
All checks were successful
技能自动化发布 / release (push) Successful in 7s
All checks were successful
技能自动化发布 / release (push) Successful in 7s
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, ""
|
||||
511
scripts/service/fund_service.py
Normal file
511
scripts/service/fund_service.py
Normal file
@@ -0,0 +1,511 @@
|
||||
"""项目经费执行监测与播报内核(唯一业务内核)。
|
||||
|
||||
三步计算(对齐《核心建设内容:各部门"Skill"深度需求规格书》财务处 Skill 002):
|
||||
Step 1 执行率计算:实际支出率 = 已报销/已到账;序时进度 = 已过天数/总执行天数
|
||||
Step 2 偏差诊断:低于序时进度超 lag_threshold → 严重滞后;高于 overshoot_threshold → 支出异常偏快
|
||||
Step 3 提醒与建议:暂付款账龄、结题临近、三段式播报摘要(规则模板,数字全部本地计算,不编造)
|
||||
|
||||
阈值存 alert_rules 表(管理员可调);播报结果写 progress_reports 并生成《经费执行简报》。
|
||||
播报仅作提醒,请以财务系统账面为准。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import date
|
||||
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
|
||||
|
||||
STATUS_LAG = "严重滞后"
|
||||
STATUS_OVERSHOOT = "支出异常偏快"
|
||||
STATUS_NORMAL = "正常"
|
||||
STATUS_INCOMPLETE = "待补录"
|
||||
STATUS_NO_FUND = "未到账"
|
||||
|
||||
_DEFAULT_RULES = {
|
||||
"lag_threshold": 0.10,
|
||||
"overshoot_threshold": 0.20,
|
||||
"pending_aging_days": 90.0,
|
||||
"closing_warn_days": 90.0,
|
||||
}
|
||||
|
||||
_KEY_ALIASES = {
|
||||
"projectNo": ("project_no", "项目编号", "编号"),
|
||||
"projectName": ("project_name", "项目名称", "名称"),
|
||||
"projectType": ("project_type", "项目类别", "类别"),
|
||||
"piName": ("pi_name", "负责人", "pi"),
|
||||
"department": ("department", "所属学院", "学院"),
|
||||
"totalApproved": ("total_approved", "总立项经费", "立项经费"),
|
||||
"totalReceived": ("total_received", "已到账金额", "已到账", "到账金额"),
|
||||
"totalSpent": ("total_spent", "已报销金额", "已报销", "报销金额"),
|
||||
"frozenAmount": ("frozen_amount", "冻结/暂付款", "暂付款金额", "冻结金额"),
|
||||
"frozenSince": ("frozen_since", "暂付款最早发生日", "暂付款日期"),
|
||||
"startDate": ("start_date", "执行期开始", "开始日期"),
|
||||
"endDate": ("end_date", "执行期结束", "结束日期"),
|
||||
"status": ("status", "项目状态", "状态"),
|
||||
"remark": ("remark", "备注"),
|
||||
}
|
||||
|
||||
_STATUS_RANK = {STATUS_INCOMPLETE: 0, STATUS_NO_FUND: 1, STATUS_NORMAL: 2, STATUS_OVERSHOOT: 3, STATUS_LAG: 4}
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _norm_project(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 _KEY_ALIASES:
|
||||
out.setdefault(camel, value)
|
||||
continue
|
||||
matched = False
|
||||
for canonical, aliases in _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 = re.sub(r"[元,,\s]", "", str(value).strip())
|
||||
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 ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y年%m月%d日"):
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
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 _wan(value: Optional[float]) -> str:
|
||||
if value is None:
|
||||
return "—"
|
||||
return f"{value / 10000:.2f} 万元"
|
||||
|
||||
|
||||
def _pct(value: Optional[float]) -> str:
|
||||
return "—" if value is None else f"{value * 100:.1f}%"
|
||||
|
||||
|
||||
def load_rules() -> dict[str, float]:
|
||||
"""读取预警阈值(缺失时回退缺省值)。"""
|
||||
rules = dict(_DEFAULT_RULES)
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT rule_key, threshold_value FROM alert_rules")
|
||||
for rule_key, threshold_value in cur.fetchall():
|
||||
try:
|
||||
rules[str(rule_key)] = float(threshold_value)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
finally:
|
||||
conn.close()
|
||||
return rules
|
||||
|
||||
|
||||
def _item(rule_id: str, name: str, level: str, detail: str, suggestion: str = "") -> dict[str, str]:
|
||||
return {"rule_id": rule_id, "name": name, "level": level, "detail": detail, "suggestion": suggestion}
|
||||
|
||||
|
||||
def _time_progress(start: Optional[date], end: Optional[date], as_of: date) -> Optional[float]:
|
||||
if not start or not end or end <= start:
|
||||
return None
|
||||
if as_of <= start:
|
||||
return 0.0
|
||||
if as_of >= end:
|
||||
return 1.0
|
||||
return round((as_of - start).days / (end - start).days, 4)
|
||||
|
||||
|
||||
def compute_project(project: dict[str, Any], rules: dict[str, float], as_of: date) -> dict[str, Any]:
|
||||
"""对单个项目执行三步计算,返回播报结果(不落库)。"""
|
||||
items: list[dict[str, str]] = []
|
||||
project_no = str(project.get("projectNo") or "").strip() or "未编号"
|
||||
project_name = str(project.get("projectName") or "").strip() or project_no
|
||||
|
||||
total_received = _to_float(project.get("totalReceived"))
|
||||
total_spent = _to_float(project.get("totalSpent"))
|
||||
total_approved = _to_float(project.get("totalApproved"))
|
||||
start = _parse_date(project.get("startDate"))
|
||||
end = _parse_date(project.get("endDate"))
|
||||
|
||||
# C3 台账完整性
|
||||
missing = [
|
||||
label
|
||||
for key, label in (
|
||||
("totalApproved", "总立项经费"),
|
||||
("totalReceived", "已到账金额"),
|
||||
("totalSpent", "已报销金额"),
|
||||
("startDate", "执行期开始"),
|
||||
("endDate", "执行期结束"),
|
||||
)
|
||||
if (
|
||||
_to_float(project.get(key)) is None
|
||||
if key.startswith("total")
|
||||
else project.get(key) in (None, "")
|
||||
)
|
||||
]
|
||||
if missing:
|
||||
items.append(
|
||||
_item(
|
||||
"C3",
|
||||
"台账完整性",
|
||||
"warn",
|
||||
f"以下台账字段缺失:{'、'.join(missing)},本期数字可能失真,请补录。",
|
||||
"请在数据管理“项目台账”中补齐后重新播报。",
|
||||
)
|
||||
)
|
||||
|
||||
# C1 实际支出率
|
||||
spend_rate: Optional[float] = None
|
||||
if total_received is not None and total_received <= 0:
|
||||
items.append(
|
||||
_item(
|
||||
"C1",
|
||||
"实际支出率",
|
||||
"warn",
|
||||
"经费尚未到账,无法计算执行率。",
|
||||
"到账后自动纳入正常播报;如长期未到账请联系财务处核实拨款进度。",
|
||||
)
|
||||
)
|
||||
elif total_received is not None and total_spent is not None:
|
||||
spend_rate = round(total_spent / total_received, 4)
|
||||
|
||||
# C2 序时进度
|
||||
time_progress = _time_progress(start, end, as_of)
|
||||
if time_progress is None:
|
||||
items.append(
|
||||
_item(
|
||||
"C2",
|
||||
"序时进度",
|
||||
"warn",
|
||||
"执行期起止缺失或无效,无法计算序时进度。",
|
||||
"请在项目台账补录执行期起止日期。",
|
||||
)
|
||||
)
|
||||
|
||||
# D1/D2/D3 偏差诊断
|
||||
status_tag = STATUS_NORMAL
|
||||
deviation: Optional[float] = None
|
||||
if spend_rate is not None and time_progress is not None:
|
||||
deviation = round(spend_rate - time_progress, 4)
|
||||
lag = float(rules.get("lag_threshold", _DEFAULT_RULES["lag_threshold"]))
|
||||
overshoot = float(rules.get("overshoot_threshold", _DEFAULT_RULES["overshoot_threshold"]))
|
||||
if deviation < -lag:
|
||||
status_tag = STATUS_LAG
|
||||
items.append(
|
||||
_item(
|
||||
"D1",
|
||||
"严重滞后",
|
||||
"alert",
|
||||
f"实际支出率 {_pct(spend_rate)} 低于序时进度 {_pct(time_progress)} 超过 {_pct(lag)},偏差 {_pct(deviation)}。",
|
||||
"请对照研究计划排查滞后原因;如确需调整,请尽早与财务处沟通预算调剂或申请延期。",
|
||||
)
|
||||
)
|
||||
elif deviation > overshoot:
|
||||
status_tag = STATUS_OVERSHOOT
|
||||
items.append(
|
||||
_item(
|
||||
"D2",
|
||||
"支出异常偏快",
|
||||
"warn",
|
||||
f"实际支出率 {_pct(spend_rate)} 高于序时进度 {_pct(time_progress)} 超过 {_pct(overshoot)},偏差 +{_pct(deviation)},存在年底经费不足风险。",
|
||||
"请合理安排后续支出节奏,避免年底突击花钱或经费提前耗尽。",
|
||||
)
|
||||
)
|
||||
else:
|
||||
status_tag = STATUS_NORMAL
|
||||
items.append(
|
||||
_item(
|
||||
"D3",
|
||||
"执行正常",
|
||||
"pass",
|
||||
f"实际支出率 {_pct(spend_rate)} 与序时进度 {_pct(time_progress)} 基本匹配(偏差 {_pct(deviation)})。",
|
||||
"",
|
||||
)
|
||||
)
|
||||
|
||||
# N1 暂付款账龄
|
||||
frozen_amount = _to_float(project.get("frozenAmount"))
|
||||
frozen_since = _parse_date(project.get("frozenSince"))
|
||||
if frozen_amount is not None and frozen_amount > 0:
|
||||
aging_days = (as_of - frozen_since).days if frozen_since else None
|
||||
pending_days = float(rules.get("pending_aging_days", _DEFAULT_RULES["pending_aging_days"]))
|
||||
if aging_days is None:
|
||||
items.append(
|
||||
_item(
|
||||
"N1",
|
||||
"暂付款冲销提醒",
|
||||
"info",
|
||||
f"项目有暂付款 {_wan(frozen_amount)},但台账未登记最早发生日,无法计算账龄。",
|
||||
"请补录暂付款发生日期,以便跟踪冲销时限。",
|
||||
)
|
||||
)
|
||||
elif aging_days > pending_days:
|
||||
items.append(
|
||||
_item(
|
||||
"N1",
|
||||
"暂付款冲销提醒",
|
||||
"info",
|
||||
f"暂付款 {_wan(frozen_amount)} 最早发生于 {frozen_since.isoformat()},账龄已 {aging_days} 天(超 {pending_days:.0f} 天)。",
|
||||
"请及时办理暂付款冲销或核销手续。",
|
||||
)
|
||||
)
|
||||
|
||||
# N2 结题临近
|
||||
if end:
|
||||
days_left = (end - as_of).days
|
||||
closing_days = float(rules.get("closing_warn_days", _DEFAULT_RULES["closing_warn_days"]))
|
||||
if days_left < 0:
|
||||
items.append(
|
||||
_item(
|
||||
"N2",
|
||||
"结题决算提醒",
|
||||
"info",
|
||||
f"项目执行期已于 {end.isoformat()} 结束。",
|
||||
"请尽快完成支出归集与结题决算。",
|
||||
)
|
||||
)
|
||||
elif days_left <= closing_days and (spend_rate is None or spend_rate < 0.8):
|
||||
rate_text = _pct(spend_rate) if spend_rate is not None else "暂无支出率"
|
||||
items.append(
|
||||
_item(
|
||||
"N2",
|
||||
"结题临近提醒",
|
||||
"info",
|
||||
f"距执行期结束({end.isoformat()})仅剩 {days_left} 天,当前支出率 {rate_text}。",
|
||||
"请尽快完成剩余科目报销,避免结题时经费大量沉淀。",
|
||||
)
|
||||
)
|
||||
|
||||
# 状态修正:无法计算时归为未到账/待补录
|
||||
if spend_rate is None and status_tag == STATUS_NORMAL:
|
||||
has_no_fund = any(i["rule_id"] == "C1" for i in items)
|
||||
status_tag = STATUS_NO_FUND if has_no_fund else STATUS_INCOMPLETE
|
||||
|
||||
suggestions = [i["suggestion"] for i in items if i.get("suggestion")]
|
||||
summary = _build_summary(project_no, project_name, total_approved, total_received, total_spent, as_of, spend_rate, time_progress, status_tag, items)
|
||||
|
||||
return {
|
||||
"project_no": project_no,
|
||||
"project_name": project_name,
|
||||
"pi_name": str(project.get("piName") or "").strip(),
|
||||
"department": str(project.get("department") or "").strip(),
|
||||
"project_type": str(project.get("projectType") or "").strip(),
|
||||
"total_approved": total_approved,
|
||||
"total_received": total_received,
|
||||
"total_spent": total_spent,
|
||||
"frozen_amount": frozen_amount,
|
||||
"frozen_since": _fmt_date(frozen_since),
|
||||
"start_date": _fmt_date(start),
|
||||
"end_date": _fmt_date(end),
|
||||
"as_of": as_of.isoformat(),
|
||||
"spend_rate": spend_rate,
|
||||
"time_progress": time_progress,
|
||||
"deviation": deviation,
|
||||
"status_tag": status_tag,
|
||||
"items": items,
|
||||
"suggestions": suggestions,
|
||||
"summary": summary,
|
||||
}
|
||||
|
||||
|
||||
def _join_sentences(segments: list[str]) -> str:
|
||||
"""拼接句子:去掉各段尾部句号,统一以“;”分隔并以“。”结尾。"""
|
||||
cleaned = [s.strip().rstrip("。").strip() for s in segments if s and s.strip()]
|
||||
return ";".join(cleaned) + "。" if cleaned else ""
|
||||
|
||||
|
||||
def _build_summary(
|
||||
project_no: str,
|
||||
project_name: str,
|
||||
total_approved: Optional[float],
|
||||
total_received: Optional[float],
|
||||
total_spent: Optional[float],
|
||||
as_of: date,
|
||||
spend_rate: Optional[float],
|
||||
time_progress: Optional[float],
|
||||
status_tag: str,
|
||||
items: list[dict[str, str]],
|
||||
) -> str:
|
||||
"""三段式播报摘要(模板注入,数字全部来自计算)。"""
|
||||
part1 = (
|
||||
f"您负责的《{project_name}》({project_no}):总立项经费 {_wan(total_approved)},"
|
||||
f"已到账 {_wan(total_received)},已报销 {_wan(total_spent)},"
|
||||
f"截至 {as_of.isoformat()} 实际支出率 {_pct(spend_rate)},序时进度 {_pct(time_progress)},"
|
||||
f"执行状态{status_tag}。"
|
||||
)
|
||||
diagnostics = [i for i in items if i["rule_id"] in ("D1", "D2", "D3", "N1", "N2", "C1", "C3")]
|
||||
if diagnostics:
|
||||
part2 = "诊断:" + _join_sentences([i["detail"] for i in diagnostics])
|
||||
else:
|
||||
part2 = "诊断:暂无特别事项。"
|
||||
suggestions = [i["suggestion"] for i in items if i.get("suggestion")]
|
||||
if suggestions:
|
||||
part3 = "建议:" + _join_sentences(suggestions[:3])
|
||||
else:
|
||||
part3 = "建议:按研究计划均衡安排支出,保持执行进度与时间进度匹配。"
|
||||
return f"{part1}\n{part2}\n{part3}"
|
||||
|
||||
|
||||
def _validate_projects(projects: list[dict[str, Any]]) -> None:
|
||||
if not projects:
|
||||
raise ValueError("项目台账为空:请先录入项目(add-project / import-projects)")
|
||||
if len(projects) > 500:
|
||||
raise ValueError(f"单次播报项目数过多({len(projects)} 个),上限 500 个")
|
||||
for idx, project in enumerate(projects):
|
||||
if not isinstance(project, dict):
|
||||
raise ValueError(f"第 {idx + 1} 个项目不是 JSON 对象")
|
||||
|
||||
|
||||
def _write_report(result: dict[str, Any], batch_no: str) -> str:
|
||||
from service.report_service import write_report_for_kernel
|
||||
|
||||
return write_report_for_kernel(result=result, batch_no=batch_no)
|
||||
|
||||
|
||||
def run_broadcast(projects_raw: list[dict[str, Any]], as_of: date, *, batch_no: str = "") -> dict[str, Any]:
|
||||
"""播报内核:逐项目三步计算 → 写库 → 生成《经费执行简报》。"""
|
||||
from service.report_service import build_monthly_brief
|
||||
|
||||
log = _log()
|
||||
init_db()
|
||||
projects = [_norm_project(p) for p in projects_raw]
|
||||
_validate_projects(projects)
|
||||
|
||||
batch_no = batch_no or now_unix().to_bytes(5, "big").hex() + uuid.uuid4().hex[:6]
|
||||
rules = load_rules()
|
||||
|
||||
if log:
|
||||
log.info("broadcast_kernel_start batch_no=%s count=%s as_of=%s stage=kernel", batch_no, len(projects), as_of.isoformat())
|
||||
|
||||
results = []
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for project in projects:
|
||||
result = compute_project(project, rules, as_of)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO progress_reports
|
||||
(batch_no, project_no, project_name, pi_name, as_of, spend_rate,
|
||||
time_progress, deviation, status_tag, summary, suggestions_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_no,
|
||||
result["project_no"],
|
||||
result["project_name"],
|
||||
result["pi_name"],
|
||||
result["as_of"],
|
||||
result["spend_rate"],
|
||||
result["time_progress"],
|
||||
result["deviation"],
|
||||
result["status_tag"],
|
||||
result["summary"],
|
||||
json.dumps(result["suggestions"], ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
report_id = int(cur.lastrowid)
|
||||
result["report_id"] = report_id
|
||||
result["batch_no"] = batch_no
|
||||
report_file = _write_report(result, batch_no)
|
||||
cur.execute("UPDATE progress_reports SET report_file = ? WHERE id = ?", (report_file, report_id))
|
||||
result["report_file"] = report_file
|
||||
results.append(result)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
counts: dict[str, int] = {}
|
||||
for result in results:
|
||||
counts[result["status_tag"]] = counts.get(result["status_tag"], 0) + 1
|
||||
brief_file = build_monthly_brief(batch_no=batch_no, results=results, as_of=as_of)
|
||||
|
||||
payload = {
|
||||
"ok": True,
|
||||
"batch_no": batch_no,
|
||||
"as_of": as_of.isoformat(),
|
||||
"count": len(results),
|
||||
"status_counts": counts,
|
||||
"brief_file": brief_file,
|
||||
"disclaimer": "播报仅作提醒,金额与执行进度请以财务系统账面为准。",
|
||||
"reports": results,
|
||||
}
|
||||
if log:
|
||||
log.info(
|
||||
"broadcast_kernel_done batch_no=%s count=%s lag=%s overshoot=%s stage=kernel",
|
||||
batch_no,
|
||||
len(results),
|
||||
counts.get(STATUS_LAG, 0),
|
||||
counts.get(STATUS_OVERSHOOT, 0),
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def query_projects(project_no: str = "", pi_name: str = "", include_all_status: bool = False) -> list[dict[str, Any]]:
|
||||
"""从台账取待播报项目(缺省全部在研;可按项目编号/负责人筛选)。"""
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
sql = "SELECT * FROM fund_projects WHERE 1=1"
|
||||
params: list[Any] = []
|
||||
if not include_all_status:
|
||||
sql += " AND status = '在研'"
|
||||
if project_no:
|
||||
sql += " AND project_no = ?"
|
||||
params.append(project_no)
|
||||
if pi_name:
|
||||
sql += " AND pi_name LIKE ?"
|
||||
params.append(f"%{pi_name}%")
|
||||
sql += " ORDER BY id"
|
||||
cur.execute(sql, params)
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
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
|
||||
322
scripts/service/project_service.py
Normal file
322
scripts/service/project_service.py
Normal file
@@ -0,0 +1,322 @@
|
||||
"""项目台账维护:录入(upsert)、批量导入、查询。
|
||||
|
||||
台账是播报的唯一数据源;金额单位元,日期 YYYY-MM-DD。
|
||||
project_no 唯一,重复导入按项目编号幂等更新(不覆盖未提供字段)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from service.fund_service import _norm_project, _parse_date, _to_float
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.timeutil import now_unix
|
||||
|
||||
_DATE_FIELDS = ("frozen_since", "start_date", "end_date")
|
||||
_NUMERIC_FIELDS = ("total_approved", "total_received", "total_spent", "frozen_amount")
|
||||
_TEXT_FIELDS = ("project_name", "project_type", "pi_name", "department", "status", "remark")
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _snake(name: str) -> str:
|
||||
"""camelCase → snake_case(_norm_project 输出 canonical camelCase 键)。"""
|
||||
return "".join("_" + ch.lower() if ch.isupper() else ch for ch in str(name)).lstrip("_")
|
||||
|
||||
|
||||
def upsert_project(fields: dict[str, Any]) -> dict[str, Any]:
|
||||
"""按 project_no 幂等写入台账;未提供的字段不覆盖已有值。"""
|
||||
project_no = str(fields.get("project_no") or "").strip()
|
||||
if not project_no:
|
||||
raise ValueError("项目编号(project_no)不能为空")
|
||||
|
||||
values: dict[str, Any] = {"project_no": project_no}
|
||||
for key in _NUMERIC_FIELDS:
|
||||
if key in fields and fields[key] not in (None, ""):
|
||||
number = _to_float(fields[key])
|
||||
if number is None or number < 0:
|
||||
raise ValueError(f"字段 {key} 必须是非负数字:{fields[key]}")
|
||||
values[key] = number
|
||||
for key in _DATE_FIELDS:
|
||||
if key in fields and fields[key] not in (None, ""):
|
||||
parsed = _parse_date(fields[key])
|
||||
if parsed is None:
|
||||
raise ValueError(f"字段 {key} 日期格式无效(应为 YYYY-MM-DD):{fields[key]}")
|
||||
values[key] = parsed.isoformat()
|
||||
for key in _TEXT_FIELDS:
|
||||
if key in fields and fields[key] is not None:
|
||||
values[key] = str(fields[key]).strip()
|
||||
if values.get("status") and values["status"] not in ("在研", "已结题", "暂缓"):
|
||||
raise ValueError(f"status 只接受 在研/已结题/暂缓:{values['status']}")
|
||||
if values.get("start_date") and values.get("end_date") and values["end_date"] <= values["start_date"]:
|
||||
raise ValueError("执行期结束日期必须晚于开始日期")
|
||||
|
||||
init_db()
|
||||
log = _log()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM fund_projects WHERE project_no = ?", (project_no,))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
project_id = int(row[0])
|
||||
set_clause = ", ".join(f"{key} = ?" for key in values if key != "project_no")
|
||||
params = [values[key] for key in values if key != "project_no"] + [now_unix(), project_id]
|
||||
cur.execute(
|
||||
f"UPDATE fund_projects SET {set_clause}, updated_at = ? WHERE id = ?",
|
||||
params,
|
||||
)
|
||||
action = "updated"
|
||||
else:
|
||||
columns = ", ".join(values.keys())
|
||||
placeholders = ", ".join("?" for _ in values)
|
||||
cur.execute(
|
||||
f"INSERT INTO fund_projects ({columns}, created_at, updated_at) VALUES ({placeholders}, ?, ?)",
|
||||
list(values.values()) + [now_unix(), now_unix()],
|
||||
)
|
||||
project_id = int(cur.lastrowid)
|
||||
action = "created"
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
if log:
|
||||
log.info("project_upserted project_no=%s action=%s stage=project", project_no, action)
|
||||
return {"ok": True, "project_no": project_no, "id": project_id, "action": action}
|
||||
|
||||
|
||||
def import_projects(projects_raw: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""批量导入台账(upsert),返回统计。"""
|
||||
if not isinstance(projects_raw, list) or not projects_raw:
|
||||
raise ValueError("导入内容应为非空 JSON 数组")
|
||||
if len(projects_raw) > 500:
|
||||
raise ValueError(f"单次导入项目数过多({len(projects_raw)}),上限 500 个")
|
||||
results = []
|
||||
for idx, raw in enumerate(projects_raw):
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"第 {idx + 1} 个项目不是 JSON 对象")
|
||||
normalized = {_snake(canonical): value for canonical, value in _norm_project(raw).items()}
|
||||
results.append(upsert_project(normalized))
|
||||
return {
|
||||
"ok": True,
|
||||
"count": len(results),
|
||||
"created": sum(1 for r in results if r["action"] == "created"),
|
||||
"updated": sum(1 for r in results if r["action"] == "updated"),
|
||||
"projects": results,
|
||||
}
|
||||
|
||||
|
||||
def list_projects(pi_name: str = "", status: str = "") -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
sql = "SELECT * FROM fund_projects WHERE 1=1"
|
||||
params: list[Any] = []
|
||||
if pi_name:
|
||||
sql += " AND pi_name LIKE ?"
|
||||
params.append(f"%{pi_name}%")
|
||||
if status:
|
||||
sql += " AND status = ?"
|
||||
params.append(status)
|
||||
sql += " ORDER BY id"
|
||||
cur.execute(sql, params)
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
|
||||
def get_project_by_id(project_id: int) -> dict[str, Any]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM fund_projects WHERE id = ?", (project_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"项目不存在:{project_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
return dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def parse_projects_json(raw: str) -> list[dict[str, Any]]:
|
||||
"""解析导入 JSON:'-'(stdin)/ 文件路径 / 内联数组或 {"projects": [...]} 包装。"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
raise ValueError("缺少导入 JSON(--projects-json)")
|
||||
if text == "-":
|
||||
text = sys.stdin.read().strip()
|
||||
elif text.startswith(("[", "{")):
|
||||
pass
|
||||
elif os.path.isfile(text):
|
||||
with open(text, encoding="utf-8") as f:
|
||||
text = f.read().strip()
|
||||
else:
|
||||
raise ValueError(f"--projects-json 不是有效文件路径或 JSON:{text[:80]}")
|
||||
try:
|
||||
payload = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"导入 JSON 解析失败:{exc}") from exc
|
||||
if isinstance(payload, dict) and isinstance(payload.get("projects"), list):
|
||||
payload = payload["projects"]
|
||||
if not isinstance(payload, list):
|
||||
raise ValueError("导入 JSON 应为对象数组或 {\"projects\": [...]}")
|
||||
return payload
|
||||
|
||||
|
||||
def list_reports(limit: int = 20, status_tag: str = "") -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
limit = max(1, min(int(limit), 200))
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if status_tag:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, batch_no, as_of, project_no, project_name, pi_name,
|
||||
spend_rate, time_progress, deviation, status_tag, summary, report_file, created_at
|
||||
FROM progress_reports WHERE status_tag = ? ORDER BY id DESC LIMIT ?
|
||||
""",
|
||||
(status_tag, limit),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, batch_no, as_of, project_no, project_name, pi_name,
|
||||
spend_rate, time_progress, deviation, status_tag, summary, report_file, created_at
|
||||
FROM progress_reports ORDER BY id DESC LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
|
||||
def get_report(report_id: int) -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM progress_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))
|
||||
finally:
|
||||
conn.close()
|
||||
try:
|
||||
report["suggestions"] = json.loads(report.get("suggestions_json") or "[]")
|
||||
except (TypeError, ValueError):
|
||||
report["suggestions"] = []
|
||||
return report
|
||||
|
||||
|
||||
def view_rules() -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT id, rule_key, display_name, threshold_value, description, updated_at FROM alert_rules ORDER BY id"
|
||||
)
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
|
||||
_KNOWN_RULE_KEYS = ("lag_threshold", "overshoot_threshold", "pending_aging_days", "closing_warn_days")
|
||||
|
||||
|
||||
def set_rule(rule_key: str, threshold_value: float) -> dict[str, Any]:
|
||||
"""按 rule_key 更新阈值(须为已知规则键,数值须为正)。"""
|
||||
rule_key = (rule_key or "").strip()
|
||||
if rule_key not in _KNOWN_RULE_KEYS:
|
||||
raise ValueError(f"未知规则键:{rule_key}(可选:{'、'.join(_KNOWN_RULE_KEYS)})")
|
||||
threshold_value = float(threshold_value)
|
||||
if threshold_value <= 0 or threshold_value >= 1.5:
|
||||
raise ValueError(f"阈值必须是 0~1.5 之间的正数:{threshold_value}")
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM alert_rules WHERE rule_key = ?", (rule_key,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"规则键尚未初始化:{rule_key}(请先执行 init-db)")
|
||||
cur.execute(
|
||||
"UPDATE alert_rules SET threshold_value = ?, updated_at = ? WHERE id = ?",
|
||||
(threshold_value, now_unix(), int(row[0])),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("rule_updated rule_key=%s value=%s stage=rules", rule_key, threshold_value)
|
||||
return {"ok": True, "rule_key": rule_key, "threshold_value": threshold_value}
|
||||
|
||||
|
||||
def stats() -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT COUNT(*) FROM fund_projects")
|
||||
project_total = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT status, COUNT(*) FROM fund_projects GROUP BY status")
|
||||
by_status = {str(r[0]): int(r[1]) for r in cur.fetchall()}
|
||||
cur.execute("SELECT status_tag, COUNT(*) FROM progress_reports GROUP BY status_tag")
|
||||
reports_by_tag = {str(r[0]): int(r[1]) for r in cur.fetchall()}
|
||||
cur.execute("SELECT COUNT(*) FROM progress_reports")
|
||||
report_total = int(cur.fetchone()[0])
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT project_no, project_name, pi_name, status_tag, spend_rate, time_progress, as_of
|
||||
FROM progress_reports
|
||||
WHERE status_tag = '严重滞后'
|
||||
ORDER BY deviation ASC LIMIT 5
|
||||
"""
|
||||
)
|
||||
lag_top = [
|
||||
{
|
||||
"project_no": r[0],
|
||||
"project_name": r[1],
|
||||
"pi_name": r[2],
|
||||
"status_tag": r[3],
|
||||
"spend_rate": r[4],
|
||||
"time_progress": r[5],
|
||||
"as_of": r[6],
|
||||
}
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
cur.execute("SELECT COALESCE(SUM(frozen_amount), 0) FROM fund_projects WHERE status = '在研'")
|
||||
frozen_total = float(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"ok": True,
|
||||
"project_total": project_total,
|
||||
"projects_by_status": by_status,
|
||||
"report_total": report_total,
|
||||
"reports_by_tag": reports_by_tag,
|
||||
"lag_top": lag_top,
|
||||
"frozen_total": frozen_total,
|
||||
}
|
||||
251
scripts/service/report_service.py
Normal file
251
scripts/service/report_service.py
Normal file
@@ -0,0 +1,251 @@
|
||||
"""《经费执行简报》HTML 组装。
|
||||
|
||||
- 每项目一份 `report-{report_id}.html`(含执行率 vs 序时进度 CSS 柱状图)
|
||||
- 月度播报另生成汇总页 `brief-{batch_no}.html`
|
||||
写入 `{skill_data}/html/`,宿主数据管理侧栏可预览;重建走固定 Action id `render-html`。
|
||||
`{{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.logging_config import get_skill_logger
|
||||
from util.timeutil import unix_to_iso
|
||||
|
||||
_PROGRESS_TEMPLATE_REL = "assets/html/progress-report.html"
|
||||
_BRIEF_TEMPLATE_REL = "assets/html/monthly-brief.html"
|
||||
|
||||
_STATUS_BADGE = {
|
||||
"严重滞后": "tag-lag",
|
||||
"支出异常偏快": "tag-overshoot",
|
||||
"正常": "tag-normal",
|
||||
"待补录": "tag-gray",
|
||||
"未到账": "tag-gray",
|
||||
}
|
||||
|
||||
|
||||
def _esc(value: Any) -> str:
|
||||
return html.escape(str(value if value is not None else "—"), quote=True)
|
||||
|
||||
|
||||
def _pct(value: Any) -> str:
|
||||
try:
|
||||
return f"{float(value) * 100:.1f}%"
|
||||
except (TypeError, ValueError):
|
||||
return "—"
|
||||
|
||||
|
||||
def _wan(value: Any) -> str:
|
||||
try:
|
||||
return f"{float(value) / 10000:.2f} 万元"
|
||||
except (TypeError, ValueError):
|
||||
return "—"
|
||||
|
||||
|
||||
def _bar(label: str, value: Any, fill_class: str) -> str:
|
||||
"""CSS 柱状图行:纯 div 宽度百分比,iframe 安全无 JS。"""
|
||||
try:
|
||||
ratio = max(0.0, min(float(value), 1.0))
|
||||
width = f"{ratio * 100:.1f}%"
|
||||
except (TypeError, ValueError):
|
||||
width = "0%"
|
||||
return (
|
||||
f'<div class="bar-row"><span class="bar-label">{_esc(label)}</span>'
|
||||
f'<div class="bar-track"><div class="bar-fill {fill_class}" style="width:{width}"></div></div>'
|
||||
f'<span class="bar-value">{_pct(value)}</span></div>'
|
||||
)
|
||||
|
||||
|
||||
def _suggestion_list(suggestions: Any) -> str:
|
||||
if isinstance(suggestions, str):
|
||||
try:
|
||||
suggestions = json.loads(suggestions)
|
||||
except (TypeError, ValueError):
|
||||
suggestions = []
|
||||
if not suggestions:
|
||||
return '<p class="muted">暂无特别建议。</p>'
|
||||
rows = "".join(f"<li>{_esc(s)}</li>" for s in suggestions)
|
||||
return f"<ol>{rows}</ol>"
|
||||
|
||||
|
||||
def _project_info_table(result: dict[str, Any]) -> str:
|
||||
fields = (
|
||||
("项目编号", "project_no"),
|
||||
("项目类别", "project_type"),
|
||||
("负责人", "pi_name"),
|
||||
("所属学院", "department"),
|
||||
("总立项经费", None),
|
||||
("已到账金额", None),
|
||||
("已报销金额", None),
|
||||
("冻结/暂付款", "frozen_amount"),
|
||||
("执行期", None),
|
||||
)
|
||||
rows = []
|
||||
for label, key in fields:
|
||||
if label == "总立项经费":
|
||||
value = _wan(result.get("total_approved"))
|
||||
elif label == "已到账金额":
|
||||
value = _wan(result.get("total_received"))
|
||||
elif label == "已报销金额":
|
||||
value = _wan(result.get("total_spent"))
|
||||
elif label == "执行期":
|
||||
value = f"{result.get('start_date') or '—'} ~ {result.get('end_date') or '—'}"
|
||||
else:
|
||||
value = result.get(key) or "—"
|
||||
rows.append(f"<tr><th>{_esc(label)}</th><td>{_esc(value)}</td></tr>")
|
||||
return f'<table class="info">{"".join(rows)}</table>'
|
||||
|
||||
|
||||
def build_progress_html(result: dict[str, Any], batch_no: str = "") -> str:
|
||||
"""组装单个项目的《经费执行简报》HTML 文本。"""
|
||||
status = str(result.get("status_tag") or "")
|
||||
badge = _STATUS_BADGE.get(status, "tag-gray")
|
||||
mark = {"严重滞后": "🔴 严重滞后", "支出异常偏快": "🟠 支出异常偏快", "正常": "🟢 正常"}.get(status, f"⚪ {status}")
|
||||
summary = str(result.get("summary") or "")
|
||||
parts = [p for p in summary.split("\n") if p.strip()]
|
||||
summary_html = "".join(f'<p class="para">{_esc(p)}</p>' for p in parts)
|
||||
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
<span class="tag {badge}">{mark}</span>
|
||||
<span class="muted">批次 {_esc(batch_no or result.get("batch_no"))} · 评估基准日 {_esc(result.get("as_of"))}</span>
|
||||
</div>
|
||||
<div class="section"><h2>执行进度对比</h2>
|
||||
{_bar("实际支出率", result.get("spend_rate"), "fill-spend")}
|
||||
{_bar("序时进度", result.get("time_progress"), "fill-time")}
|
||||
<p class="muted">偏差 = 实际支出率 − 序时进度 = {_esc(_pct(result.get("deviation")))}</p>
|
||||
</div>
|
||||
<div class="section"><h2>项目信息</h2>{_project_info_table(result)}</div>
|
||||
<div class="section"><h2>播报摘要</h2>{summary_html}</div>
|
||||
<div class="section"><h2>建议</h2>{_suggestion_list(result.get("suggestions"))}</div>
|
||||
<footer>本简报由项目台账数据自动生成,仅作提醒;金额与执行进度请以财务系统账面为准。</footer>
|
||||
"""
|
||||
|
||||
template = load_html_template(_PROGRESS_TEMPLATE_REL)
|
||||
return render_html_placeholders(
|
||||
template,
|
||||
{
|
||||
"TITLE": f"经费执行简报 · {result.get('project_name') or result.get('project_no') or ''}",
|
||||
"GENERATED_AT": "",
|
||||
"BODY": body,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def write_report_for_kernel(*, result: dict[str, Any], batch_no: str) -> str:
|
||||
"""内核路径:用内存数据直接组装并写出单项目简报,返回文件路径。"""
|
||||
html_text = build_progress_html(result, batch_no)
|
||||
log = get_skill_logger()
|
||||
path = write_html_page(f"report-{result['report_id']}.html", html_text)
|
||||
log.info("progress_report_written report_id=%s path=%s stage=report", result["report_id"], path)
|
||||
return path
|
||||
|
||||
|
||||
def build_report_for_report_id(report_id: int) -> str:
|
||||
"""按播报记录 id 从库中取数并重写 HTML(重建入口用)。"""
|
||||
from db.connection import get_conn
|
||||
|
||||
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 progress_reports WHERE id = ?", (report_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"播报记录不存在:{report_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
record = dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
result = _record_to_result(record)
|
||||
html_text = build_progress_html(result)
|
||||
path = write_html_page(f"report-{report_id}.html", html_text)
|
||||
log.info("report_render_done report_id=%s path=%s stage=render", report_id, path)
|
||||
return path
|
||||
|
||||
|
||||
def _record_to_result(record: dict[str, Any]) -> dict[str, Any]:
|
||||
"""把播报记录行还原为简报渲染所需的结果结构(金额从台账补齐)。"""
|
||||
from service.project_service import get_project_by_id
|
||||
|
||||
result = dict(record)
|
||||
try:
|
||||
project = get_project_by_id(int(record.get("project_id")))
|
||||
except (TypeError, ValueError):
|
||||
project = {}
|
||||
for key in (
|
||||
"project_type",
|
||||
"department",
|
||||
"total_approved",
|
||||
"total_received",
|
||||
"total_spent",
|
||||
"frozen_amount",
|
||||
"start_date",
|
||||
"end_date",
|
||||
):
|
||||
result.setdefault(key, project.get(key))
|
||||
try:
|
||||
result["suggestions"] = json.loads(record.get("suggestions_json") or "[]")
|
||||
except (TypeError, ValueError):
|
||||
result["suggestions"] = []
|
||||
return result
|
||||
|
||||
|
||||
def build_monthly_brief(*, batch_no: str, results: list[dict[str, Any]], as_of: Any) -> str:
|
||||
"""月度播报汇总页:全部项目的执行率/序时进度柱状图一览。"""
|
||||
log = get_skill_logger()
|
||||
rows = []
|
||||
order = {"严重滞后": 0, "支出异常偏快": 1, "正常": 2, "待补录": 3, "未到账": 4}
|
||||
for result in sorted(results, key=lambda r: order.get(str(r.get("status_tag")), 9)):
|
||||
status = str(result.get("status_tag") or "")
|
||||
badge = _STATUS_BADGE.get(status, "tag-gray")
|
||||
rows.append(
|
||||
"<tr>"
|
||||
f'<td class="nowrap">{_esc(result.get("project_no"))}</td>'
|
||||
f'<td>{_esc(result.get("project_name"))}<br/><span class="muted">{_esc(result.get("pi_name"))}</span></td>'
|
||||
f'<td class="nowrap"><span class="tag {badge}">{_esc(status)}</span></td>'
|
||||
f'<td>{_bar("支出", result.get("spend_rate"), "fill-spend")}{_bar("序时", result.get("time_progress"), "fill-time")}</td>'
|
||||
f'<td class="nowrap">{_esc(_pct(result.get("deviation")))}</td>'
|
||||
"</tr>"
|
||||
)
|
||||
if not rows:
|
||||
rows.append('<tr><td colspan="5" class="muted">本期无可播报项目。</td></tr>')
|
||||
|
||||
counts: dict[str, int] = {}
|
||||
for result in results:
|
||||
counts[str(result.get("status_tag"))] = counts.get(str(result.get("status_tag")), 0) + 1
|
||||
chips = " ".join(
|
||||
f'<span class="tag {_STATUS_BADGE.get(tag, "tag-gray")}">{_esc(tag)} × {num}</span>'
|
||||
for tag, num in sorted(counts.items(), key=lambda kv: order.get(kv[0], 9))
|
||||
)
|
||||
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
{chips or '<span class="muted">无</span>'}
|
||||
<span class="muted">批次 {_esc(batch_no)} · 评估基准日 {_esc(as_of)}</span>
|
||||
</div>
|
||||
<div class="section"><h2>全部项目进度一览(按状态排序)</h2>
|
||||
<table>
|
||||
<tr><th>项目编号</th><th>项目 / 负责人</th><th>状态</th><th>进度对比</th><th>偏差</th></tr>
|
||||
{"".join(rows)}
|
||||
</table>
|
||||
</div>
|
||||
<footer>本汇总由月度播报自动生成,仅作提醒;金额与执行进度请以财务系统账面为准。</footer>
|
||||
"""
|
||||
template = load_html_template(_BRIEF_TEMPLATE_REL)
|
||||
page = render_html_placeholders(
|
||||
template,
|
||||
{
|
||||
"TITLE": "月度经费执行汇总简报",
|
||||
"GENERATED_AT": str(as_of),
|
||||
"BODY": body,
|
||||
},
|
||||
)
|
||||
path = write_html_page(f"brief-{batch_no}.html", page)
|
||||
log.info("monthly_brief_written batch_no=%s path=%s stage=report", batch_no, path)
|
||||
return path
|
||||
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")
|
||||
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', '')}"
|
||||
)
|
||||
620
scripts/service/task_service.py
Normal file
620
scripts/service/task_service.py
Normal file
@@ -0,0 +1,620 @@
|
||||
"""任务编排层:job_context / emit / finish、鉴权与错误转换。
|
||||
|
||||
领域业务在 ``service/fund_service.py``(播报内核)、
|
||||
``service/project_service.py``(台账/规则/统计)、
|
||||
``service/report_service.py``(HTML 简报),由本模块调用;
|
||||
多入口(CLI / Action / 对话 / cron)复用同一内核,禁止按入口分叉业务。
|
||||
"""
|
||||
|
||||
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_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:
|
||||
"""模板演示入口:本技能主能力请使用 broadcast 等业务命令。"""
|
||||
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 这是模板演示入口,请使用 broadcast 命令执行经费进度播报。")
|
||||
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 cmd_add_project(
|
||||
*,
|
||||
project_no: str,
|
||||
name: str = "",
|
||||
project_type: str = "",
|
||||
pi: str = "",
|
||||
department: str = "",
|
||||
total_approved: Optional[float] = None,
|
||||
total_received: Optional[float] = None,
|
||||
total_spent: Optional[float] = None,
|
||||
frozen: Optional[float] = None,
|
||||
frozen_since: str = "",
|
||||
start: str = "",
|
||||
end: str = "",
|
||||
status: str = "",
|
||||
remark: str = "",
|
||||
) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.project_service import upsert_project
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=add_project project_no=%s stage=project", project_no)
|
||||
emit("开始写入项目台账", skill=SKILL_SLUG, stage="project")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=add_project stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("add_project_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
fields: dict[str, Any] = {"project_no": project_no}
|
||||
if name:
|
||||
fields["project_name"] = name
|
||||
if project_type:
|
||||
fields["project_type"] = project_type
|
||||
if pi:
|
||||
fields["pi_name"] = pi
|
||||
if department:
|
||||
fields["department"] = department
|
||||
for key, value in (
|
||||
("total_approved", total_approved),
|
||||
("total_received", total_received),
|
||||
("total_spent", total_spent),
|
||||
("frozen_amount", frozen),
|
||||
):
|
||||
if value is not None:
|
||||
fields[key] = value
|
||||
for key, value in (("frozen_since", frozen_since), ("start_date", start), ("end_date", end), ("status", status), ("remark", remark)):
|
||||
if value:
|
||||
fields[key] = value
|
||||
payload = upsert_project(fields)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"项目 {project_no} 已{'更新' if payload['action'] == 'updated' else '录入'}", skill=SKILL_SLUG, stage="project")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=add_project error_code=PROJECT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROJECT_INVALID", stage="project")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=add_project stage=project")
|
||||
finish(status="failed", message="台账写入异常,详见统一日志", skill=SKILL_SLUG, stage="project")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_import_projects(projects_json: str) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.project_service import import_projects, parse_projects_json
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=import_projects stage=project")
|
||||
emit("开始批量导入项目台账", skill=SKILL_SLUG, stage="project")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=import_projects stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("import_projects_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
projects = parse_projects_json(projects_json)
|
||||
payload = import_projects(projects)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"导入完成:新增 {payload['created']},更新 {payload['updated']}", skill=SKILL_SLUG, stage="project")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=import_projects error_code=PROJECT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROJECT_INVALID", stage="project")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=import_projects stage=project")
|
||||
finish(status="failed", message="台账导入异常,详见统一日志", skill=SKILL_SLUG, stage="project")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_list_projects(pi: str = "", status: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.project_service import list_projects
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_projects pi=%s status=%s", pi, status)
|
||||
try:
|
||||
projects = list_projects(pi_name=pi, status=status)
|
||||
_print_json({"ok": True, "count": len(projects), "projects": projects})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_projects")
|
||||
print("ERROR:QUERY_FAILED 台账查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 播报主命令
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_broadcast(
|
||||
*,
|
||||
project_no: str = "",
|
||||
pi: str = "",
|
||||
as_of: str = "",
|
||||
include_all_status: bool = False,
|
||||
) -> int:
|
||||
"""经费进度播报(同步):全部在研项目或指定项目。"""
|
||||
log = _get_task_logger()
|
||||
from datetime import date
|
||||
|
||||
from service.fund_service import query_projects, run_broadcast
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=broadcast project_no=%s pi=%s stage=broadcast", project_no, pi)
|
||||
emit("开始经费进度播报", skill=SKILL_SLUG, stage="broadcast")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=broadcast stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("broadcast_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
as_of_date = date.fromisoformat(as_of) if as_of else date.today()
|
||||
projects = query_projects(project_no=project_no, pi_name=pi, include_all_status=include_all_status)
|
||||
if not projects:
|
||||
message = "没有可播报的项目:请先录入台账(在研项目为空或筛选条件不匹配)"
|
||||
log.warning("task_failed task_type=broadcast error_code=NO_PROJECTS stage=broadcast")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="NO_PROJECTS", stage="broadcast")
|
||||
log.error("broadcast_no_projects stage=broadcast")
|
||||
print(f"ERROR:NO_PROJECTS {message}")
|
||||
return 1
|
||||
|
||||
result = run_broadcast(projects, as_of_date)
|
||||
payload = {k: v for k, v in result.items() if k != "reports"}
|
||||
payload["reports_brief"] = [
|
||||
{k: r[k] for k in ("report_id", "project_no", "project_name", "pi_name", "status_tag", "spend_rate", "time_progress", "deviation", "report_file")}
|
||||
for r in result["reports"]
|
||||
]
|
||||
_print_json(payload)
|
||||
emit(
|
||||
f"播报完成 {result['count']} 个项目:严重滞后 {result['status_counts'].get('严重滞后', 0)},"
|
||||
f"异常偏快 {result['status_counts'].get('支出异常偏快', 0)}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="broadcast",
|
||||
)
|
||||
finish(
|
||||
status="success",
|
||||
message=f"播报完成 {result['count']} 个项目,简报已生成",
|
||||
skill=SKILL_SLUG,
|
||||
stage="broadcast",
|
||||
batch_no=result["batch_no"],
|
||||
)
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=broadcast error_code=PROJECT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROJECT_INVALID", stage="broadcast")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=broadcast stage=broadcast")
|
||||
emit("播报失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="broadcast")
|
||||
finish(status="failed", message="播报执行异常,详见统一日志", skill=SKILL_SLUG, stage="broadcast")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_broadcast_monthly() -> int:
|
||||
"""月度播报(async Action 入口):全部在研项目逐项播报 + 汇总简报,任务中心可见进度。"""
|
||||
log = _get_task_logger()
|
||||
from datetime import date
|
||||
|
||||
from service.fund_service import query_projects, run_broadcast
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=broadcast_monthly stage=monthly")
|
||||
emit("开始月度经费播报", skill=SKILL_SLUG, stage="monthly")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=broadcast_monthly stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("broadcast_monthly_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
projects = query_projects()
|
||||
if not projects:
|
||||
message = "台账中没有“在研”项目,月度播报跳过"
|
||||
log.warning("task_failed task_type=broadcast_monthly error_code=NO_PROJECTS stage=monthly")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="NO_PROJECTS", stage="monthly")
|
||||
log.error("broadcast_monthly_no_projects stage=monthly")
|
||||
print(f"ERROR:NO_PROJECTS {message}")
|
||||
return 1
|
||||
|
||||
result = run_broadcast(projects, date.today())
|
||||
for index, report in enumerate(result["reports"], start=1):
|
||||
emit(
|
||||
f"[{index}/{len(result['reports'])}] {report['project_name']}:{report['status_tag']}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="monthly",
|
||||
)
|
||||
_print_json(
|
||||
{
|
||||
"ok": True,
|
||||
"batch_no": result["batch_no"],
|
||||
"as_of": result["as_of"],
|
||||
"count": result["count"],
|
||||
"status_counts": result["status_counts"],
|
||||
"brief_file": result["brief_file"],
|
||||
"reports_brief": [
|
||||
{k: r[k] for k in ("report_id", "project_no", "project_name", "pi_name", "status_tag", "summary")}
|
||||
for r in result["reports"]
|
||||
],
|
||||
}
|
||||
)
|
||||
finish(
|
||||
status="success",
|
||||
message=f"月度播报完成:{result['count']} 个项目,严重滞后 {result['status_counts'].get('严重滞后', 0)} 个",
|
||||
skill=SKILL_SLUG,
|
||||
stage="monthly",
|
||||
batch_no=result["batch_no"],
|
||||
)
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=broadcast_monthly stage=monthly")
|
||||
emit("月度播报失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="monthly")
|
||||
finish(status="failed", message="月度播报执行异常,详见统一日志", skill=SKILL_SLUG, stage="monthly")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 播报记录与阈值
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_list_reports(limit: int = 20, status_tag: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.project_service import list_reports
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_reports limit=%s status_tag=%s", limit, status_tag)
|
||||
try:
|
||||
reports = list_reports(limit=limit, status_tag=status_tag)
|
||||
_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.project_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_render_html(report_id: Optional[int] = None) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.report_service import build_report_for_report_id
|
||||
from service.project_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 = [{"report_id": rid, "path": build_report_for_report_id(rid)} for rid in targets]
|
||||
_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_view_rules() -> int:
|
||||
log = _get_task_logger()
|
||||
from service.project_service import view_rules
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=view_rules stage=rules")
|
||||
try:
|
||||
_print_json({"ok": True, "rules": view_rules()})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=view_rules")
|
||||
print("ERROR:QUERY_FAILED 预警规则查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_set_rule(rule_key: str, value: float) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.project_service import set_rule
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=set_rule rule_key=%s value=%s stage=rules", rule_key, value)
|
||||
emit("开始更新预警阈值", skill=SKILL_SLUG, stage="rules")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=set_rule stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("set_rule_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = set_rule(rule_key, float(value))
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"阈值 {rule_key} 已更新为 {value}", skill=SKILL_SLUG, stage="rules")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=set_rule error_code=RULE_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="RULE_INVALID", stage="rules")
|
||||
print(f"ERROR:RULE_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=set_rule stage=rules")
|
||||
finish(status="failed", message="阈值更新异常,详见统一日志", skill=SKILL_SLUG, stage="rules")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_stats() -> int:
|
||||
log = _get_task_logger()
|
||||
from service.project_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