feat: 结题报告初稿助手首版 v1.0.1(draft-closing-report-default)
All checks were successful
技能自动化发布 / release (push) Successful in 6s
All checks were successful
技能自动化发布 / release (push) Successful in 6s
This commit is contained in:
86
scripts/service/docx_service.py
Normal file
86
scripts/service/docx_service.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""Word 初稿渲染(python-docx)。
|
||||
|
||||
初稿结构:封面信息 → 目录骨架 → 六章(3/4/5 章自动成文,1/2/6 章素材要点 + [待补充] 占位)。
|
||||
写入技能 output/ 目录(用户可取)。python-docx 为技能特有依赖(requirements.txt 声明)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.runtime_paths import get_output_dir
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _check_docx_available() -> None:
|
||||
try:
|
||||
import docx # noqa: F401
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"python-docx 未安装(技能依赖安装异常);请重新安装技能,或先用 HTML 预览查看初稿内容。"
|
||||
) from exc
|
||||
|
||||
|
||||
def write_docx(project: dict[str, Any], sections: dict[str, list[str]], batch_no: str) -> str:
|
||||
"""生成《结题报告(初稿)》docx,返回文件路径。"""
|
||||
_check_docx_available()
|
||||
import docx
|
||||
from docx.shared import Pt
|
||||
|
||||
log = _log()
|
||||
log.info("docx_render_start project_no=%s stage=docx", project.get("project_no"))
|
||||
|
||||
document = docx.Document()
|
||||
|
||||
title = document.add_heading("结题报告(初稿)", level=0)
|
||||
title.alignment = 1
|
||||
|
||||
info_table = document.add_table(rows=0, cols=2)
|
||||
info_table.style = "Table Grid"
|
||||
for label, value in (
|
||||
("项目名称", project.get("project_name")),
|
||||
("项目编号", project.get("project_no")),
|
||||
("项目负责人", project.get("pi_name")),
|
||||
("所属学院", project.get("department")),
|
||||
("项目类型", project.get("program")),
|
||||
("执行周期", f"{project.get('start_date') or '—'} ~ {project.get('end_date') or '—'}"),
|
||||
("生成批次", batch_no),
|
||||
):
|
||||
row = info_table.add_row().cells
|
||||
row[0].text = str(label)
|
||||
row[1].text = str(value if value not in (None, "") else "—")
|
||||
|
||||
document.add_heading("目录(骨架,终稿请按本单位模板调整)", level=1)
|
||||
for section_title in sections:
|
||||
document.add_paragraph(section_title, style="List Number")
|
||||
|
||||
for section_title, paragraphs in sections.items():
|
||||
document.add_heading(section_title, level=1)
|
||||
for paragraph in paragraphs:
|
||||
text = str(paragraph)
|
||||
p = document.add_paragraph()
|
||||
run = p.add_run(text)
|
||||
if text.startswith("[待补充"):
|
||||
run.font.color.rgb = None # 占位文本以提示语区分,不依赖颜色
|
||||
run.italic = True
|
||||
|
||||
notice = document.add_paragraph()
|
||||
notice_run = notice.add_run(
|
||||
"说明:本初稿由结题报告初稿助手按台账数据自动生成;数字章节(完成情况/决算/成果清单)请逐项核对,"
|
||||
"叙事章节仅提供素材要点,须由项目负责人本人撰写终稿;严禁引入台账之外的成果或结论。"
|
||||
)
|
||||
notice_run.font.size = Pt(9)
|
||||
|
||||
project_no = str(project.get("project_no") or "未编号")
|
||||
filename = f"结题报告初稿-{project_no}.docx"
|
||||
path = get_output_dir() + "/" + filename
|
||||
document.save(path)
|
||||
log.info("docx_render_done project_no=%s path=%s stage=docx", project_no, path)
|
||||
return path
|
||||
354
scripts/service/draft_service.py
Normal file
354
scripts/service/draft_service.py
Normal file
@@ -0,0 +1,354 @@
|
||||
"""结题报告初稿生成内核(唯一业务内核)。
|
||||
|
||||
五步组装(对齐《核心建设内容:各部门"Skill"深度需求规格书》科研处 Skill 002):
|
||||
C1 指标对比:按成果类型汇总实际数量 vs 预期指标 → 超额完成/持平/未达标/数据待补
|
||||
C2 完成情况章节:逐指标成文 + 成果明细(来源标注)
|
||||
C3 决算转换:按科目汇总金额与占比,生成规范描述句(金额不改写)
|
||||
C4 素材要点:代表性成果与年度报告摘句逐条提取(标注来源)
|
||||
C5 骨架组装:通用结题结构,叙事章节只放素材要点 + [待补充] 指引
|
||||
W1 数据完整性:缺数据生成占位,不阻塞整稿
|
||||
|
||||
红线:初稿中每个数字都来自台账;严禁编造数据与虚构论文结论。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
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
|
||||
|
||||
_PLACEHOLDER = "[待补充:请结合素材要点与原始报告撰写,注意引用本人成果]"
|
||||
|
||||
_EXPENSE_SENTENCE_TEMPLATES = {
|
||||
"设备费": "购置/使用科研设备",
|
||||
"材料费": "采购实验材料",
|
||||
"测试化验加工费": "开展测试化验与加工",
|
||||
"燃料动力费": "支付燃料动力费用",
|
||||
"差旅费": "赴外开展调研与学术交流",
|
||||
"会议费": "组织/参加学术会议",
|
||||
"国际合作与交流费": "开展国际合作与交流",
|
||||
"出版/文献/信息传播/知识产权事务费": "支付出版与知识产权事务费用",
|
||||
"劳务费": "支付参与项目的研究生与临时聘用人员劳务",
|
||||
"专家咨询费": "支付专家咨询费用",
|
||||
"其他": "其他与项目研究直接相关的支出",
|
||||
}
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _wan(value: Optional[float]) -> str:
|
||||
if value is None:
|
||||
return "—"
|
||||
return f"{value / 10000:.2f} 万元"
|
||||
|
||||
|
||||
def _camel(name: str) -> str:
|
||||
parts = str(name).split("_")
|
||||
if len(parts) <= 1:
|
||||
return str(name)
|
||||
head, *rest = parts
|
||||
return head + "".join(p[:1].upper() + p[1:] for p in rest if p)
|
||||
|
||||
|
||||
def _snake(name: str) -> str:
|
||||
return "".join("_" + ch.lower() if ch.isupper() else ch for ch in str(name)).lstrip("_")
|
||||
|
||||
|
||||
def _norm_project(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
aliases = {
|
||||
"projectNo": ("project_no", "项目编号"),
|
||||
"projectName": ("project_name", "项目名称"),
|
||||
"piName": ("pi_name", "负责人"),
|
||||
"department": ("department", "学院", "所属学院"),
|
||||
"program": ("program", "项目类型", "资助渠道"),
|
||||
"startDate": ("start_date", "执行期开始", "开始日期"),
|
||||
"endDate": ("end_date", "执行期结束", "结束日期"),
|
||||
"expected": ("expected_json", "预期成果指标", "预期指标"),
|
||||
"annualReportExcerpt": ("annual_report_excerpt", "年度报告摘句", "年度报告"),
|
||||
"status": ("status", "状态"),
|
||||
}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in raw.items():
|
||||
out.setdefault(str(key), value)
|
||||
for canonical, names in aliases.items():
|
||||
if str(key) in names or _camel(str(key)) == canonical:
|
||||
out.setdefault(canonical, value)
|
||||
return out
|
||||
|
||||
|
||||
def _norm_achievement(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
aliases = {
|
||||
"projectNo": ("project_no", "项目编号"),
|
||||
"achievementType": ("achievement_type", "成果类型", "类型"),
|
||||
"title": ("title", "成果名称", "标题"),
|
||||
"venueOrNo": ("venue_or_no", "期刊/专利号", "期刊", "专利号"),
|
||||
"achDate": ("ach_date", "日期", "发表日期"),
|
||||
"isRepresentative": ("is_representative", "代表性成果"),
|
||||
"note": ("note", "备注"),
|
||||
}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in raw.items():
|
||||
out.setdefault(str(key), value)
|
||||
for canonical, names in aliases.items():
|
||||
if str(key) in names or _camel(str(key)) == canonical:
|
||||
out.setdefault(canonical, value)
|
||||
return out
|
||||
|
||||
|
||||
def _norm_expense(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
aliases = {
|
||||
"projectNo": ("project_no", "项目编号"),
|
||||
"category": ("category", "科目"),
|
||||
"amount": ("amount", "金额"),
|
||||
"occurredDate": ("occurred_date", "发生日期"),
|
||||
"description": ("description", "原始摘要", "描述"),
|
||||
}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in raw.items():
|
||||
out.setdefault(str(key), value)
|
||||
for canonical, names in aliases.items():
|
||||
if str(key) in names or _camel(str(key)) == canonical:
|
||||
out.setdefault(canonical, value)
|
||||
return out
|
||||
|
||||
|
||||
def _c1_compare(expected: list[dict[str, Any]], achievements: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""C1:按类型对比预期指标与实际成果。"""
|
||||
counts: dict[str, int] = {}
|
||||
for ach in achievements:
|
||||
ach_type = str(ach.get("achievement_type") or "").strip()
|
||||
counts[ach_type] = counts.get(ach_type, 0) + 1
|
||||
rows = []
|
||||
for item in expected:
|
||||
item_type = str(item.get("type") or "").strip()
|
||||
target = item.get("target")
|
||||
try:
|
||||
target_v = int(float(target))
|
||||
except (TypeError, ValueError):
|
||||
target_v = None
|
||||
unit = str(item.get("unit") or "项")
|
||||
actual = counts.get(item_type)
|
||||
if target_v is None:
|
||||
verdict, detail = "数据待补", f"预期指标未配置数值(类型:{item_type})"
|
||||
elif actual is None:
|
||||
verdict, detail = "未达标", f"预期 {target_v} {unit},台账中未录入该类成果"
|
||||
else:
|
||||
if actual > target_v:
|
||||
verdict = "超额完成"
|
||||
elif actual == target_v:
|
||||
verdict = "持平"
|
||||
else:
|
||||
verdict = "未达标"
|
||||
detail = f"预期 {target_v} {unit},实际 {actual} {unit},{verdict}"
|
||||
rows.append({"type": item_type, "target": target_v, "unit": unit, "actual": actual, "verdict": verdict, "detail": detail})
|
||||
return rows
|
||||
|
||||
|
||||
def _c3_expense_sentences(expenses: list[dict[str, Any]], total_approved: Optional[float]) -> tuple[list[dict[str, Any]], str]:
|
||||
"""C3:按科目汇总并生成规范描述句。返回 (rows, 汇总段落)。"""
|
||||
by_category: dict[str, float] = {}
|
||||
for item in expenses:
|
||||
try:
|
||||
amount = float(item.get("amount") or 0)
|
||||
except (TypeError, ValueError):
|
||||
amount = 0.0
|
||||
category = str(item.get("category") or "其他").strip() or "其他"
|
||||
by_category[category] = by_category.get(category, 0.0) + amount
|
||||
total = round(sum(by_category.values()), 2)
|
||||
rows = []
|
||||
sentences = []
|
||||
for category, amount in sorted(by_category.items(), key=lambda kv: -kv[1]):
|
||||
ratio = round(amount / total, 4) if total > 0 else 0.0
|
||||
action = _EXPENSE_SENTENCE_TEMPLATES.get(category, f"开展{category}相关支出")
|
||||
sentence = f"{action},支出 {_wan(amount)},占比 {ratio * 100:.1f}%"
|
||||
rows.append({"category": category, "amount": round(amount, 2), "ratio": ratio, "sentence": sentence})
|
||||
sentences.append(sentence)
|
||||
if not rows:
|
||||
return [], "经费决算明细尚未录入,请在补录后重新生成初稿(W1)。"
|
||||
tail = f"。项目决算合计支出 {_wan(total)}。"
|
||||
if total_approved is not None:
|
||||
tail += "支出总额控制在立项经费范围内。" if total <= total_approved else "支出总额超出立项经费,请补充说明。"
|
||||
return rows, "本项目经费支出按科目如下:" + ";".join(sentences) + "。" + tail
|
||||
|
||||
|
||||
def _c4_narrative_points(achievements: list[dict[str, Any]], excerpt: str) -> list[dict[str, str]]:
|
||||
"""C4:从代表性成果与年度报告摘句提取叙事素材要点。"""
|
||||
points = []
|
||||
for ach in achievements:
|
||||
if ach.get("is_representative"):
|
||||
title = str(ach.get("title") or "").strip()
|
||||
venue = str(ach.get("venue_or_no") or "").strip()
|
||||
points.append({"source": "成果清单", "point": f"代表性成果:{title}" + (f"({venue})" if venue else "")})
|
||||
for sentence in str(excerpt or "").replace(";", "。").split("。"):
|
||||
sentence = sentence.strip()
|
||||
if sentence:
|
||||
points.append({"source": "年度报告", "point": sentence})
|
||||
return points
|
||||
|
||||
|
||||
def build_draft_sections(
|
||||
project: dict[str, Any],
|
||||
achievements: list[dict[str, Any]],
|
||||
expenses: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""组装初稿各章节数据(纯计算,不落库不出文件)。"""
|
||||
import json as _json
|
||||
|
||||
project = _norm_project(project)
|
||||
raw_expected = project.get("expected_json")
|
||||
if raw_expected in (None, ""):
|
||||
raw_expected = project.get("expected") or project.get("expectedJson") or []
|
||||
if isinstance(raw_expected, str):
|
||||
try:
|
||||
expected = _json.loads(raw_expected)
|
||||
except (TypeError, ValueError):
|
||||
expected = []
|
||||
elif isinstance(raw_expected, list):
|
||||
expected = raw_expected
|
||||
else:
|
||||
expected = []
|
||||
if isinstance(expected, dict):
|
||||
expected = expected.get("indicators") or []
|
||||
|
||||
achievements = [{_snake(k): v for k, v in _norm_achievement(a).items()} for a in achievements]
|
||||
expenses = [{_snake(k): v for k, v in _norm_expense(e).items()} for e in expenses]
|
||||
|
||||
completion = _c1_compare(expected, achievements)
|
||||
expense_rows, expense_paragraph = _c3_expense_sentences(expenses, None)
|
||||
excerpt = project.get("annual_report_excerpt") or project.get("annualReportExcerpt") or ""
|
||||
narrative_points = _c4_narrative_points(achievements, str(excerpt))
|
||||
|
||||
achievement_lines = []
|
||||
for ach in achievements:
|
||||
title = str(ach.get("title") or "").strip()
|
||||
venue = str(ach.get("venue_or_no") or "").strip()
|
||||
ach_date = str(ach.get("ach_date") or "").strip()
|
||||
line = f"{ach.get('achievement_type')}:{title}" + (f"({venue},{ach_date})" if venue or ach_date else "")
|
||||
achievement_lines.append(line + "。来源:成果清单")
|
||||
|
||||
sections = {
|
||||
"1. 研究背景与目标": [_PLACEHOLDER],
|
||||
"2. 研究内容与进展": (
|
||||
[f"· {p['point']}(来源:{p['source']})" for p in narrative_points] or [f"· {_PLACEHOLDER}"]
|
||||
) + [_PLACEHOLDER],
|
||||
"3. 预期成果完成情况": [f"{row['type']}:{row['detail']}。来源:预期指标与成果清单" for row in completion]
|
||||
or ["预期成果指标未配置,请在项目台账补录后重新生成(W1)。"],
|
||||
"4. 经费决算说明": [expense_paragraph, "明细:"] + [f"· {row['sentence']}" for row in expense_rows],
|
||||
"5. 成果清单": achievement_lines or ["成果清单尚未录入,请在补录后重新生成初稿(W1)。"],
|
||||
"6. 存在问题与展望": [_PLACEHOLDER],
|
||||
}
|
||||
return {
|
||||
"completion": completion,
|
||||
"expense_rows": expense_rows,
|
||||
"expense_paragraph": expense_paragraph,
|
||||
"narrative_points": narrative_points,
|
||||
"achievement_lines": achievement_lines,
|
||||
"sections": sections,
|
||||
}
|
||||
|
||||
|
||||
def run_draft(project_raw: dict[str, Any], achievements: list[dict[str, Any]], expenses: list[dict[str, Any]], *, batch_no: str = "") -> dict[str, Any]:
|
||||
"""初稿内核:三步生成 → 写 docx + HTML 预览 → 落库。"""
|
||||
from service.docx_service import write_docx
|
||||
from service.report_service import write_preview_for_kernel
|
||||
|
||||
log = _log()
|
||||
init_db()
|
||||
project = _norm_project(project_raw)
|
||||
project_no = str(project.get("project_no") or "").strip()
|
||||
if not project_no:
|
||||
raise ValueError("项目编号(project_no)不能为空")
|
||||
batch_no = batch_no or now_unix().to_bytes(5, "big").hex() + uuid.uuid4().hex[:6]
|
||||
|
||||
if log:
|
||||
log.info("draft_kernel_start batch_no=%s project_no=%s stage=kernel", batch_no, project_no)
|
||||
|
||||
sections_data = build_draft_sections(project, achievements, expenses)
|
||||
sections = sections_data["sections"]
|
||||
|
||||
draft_file = write_docx(project, sections, batch_no)
|
||||
|
||||
draft = {
|
||||
"project_no": project_no,
|
||||
"project_name": str(project.get("project_name") or ""),
|
||||
"batch_no": batch_no,
|
||||
"sections": sections,
|
||||
"completion": sections_data["completion"],
|
||||
"narrative_points": sections_data["narrative_points"],
|
||||
}
|
||||
preview_file = write_preview_for_kernel(draft=draft)
|
||||
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO report_drafts
|
||||
(batch_no, project_no, project_name, completion_json, narrative_points_json, draft_file, preview_file)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_no,
|
||||
project_no,
|
||||
str(project.get("project_name") or ""),
|
||||
json.dumps(sections_data["completion"], ensure_ascii=False),
|
||||
json.dumps(sections_data["narrative_points"], ensure_ascii=False),
|
||||
draft_file,
|
||||
preview_file,
|
||||
),
|
||||
)
|
||||
draft_id = int(cur.lastrowid)
|
||||
cur.execute(
|
||||
"UPDATE closing_projects SET status = '初稿已生成', updated_at = ? WHERE project_no = ?",
|
||||
(now_unix(), project_no),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
payload = {
|
||||
"ok": True,
|
||||
"batch_no": batch_no,
|
||||
"draft_id": draft_id,
|
||||
"project_no": project_no,
|
||||
"draft_file": draft_file,
|
||||
"preview_file": preview_file,
|
||||
"completion": sections_data["completion"],
|
||||
"narrative_points_count": len(sections_data["narrative_points"]),
|
||||
"disclaimer": "初稿由台账数据与模板生成;数据章节请核对,叙事章节须本人终审,严禁引入台账之外的成果。",
|
||||
}
|
||||
if log:
|
||||
log.info("draft_kernel_done batch_no=%s project_no=%s draft_id=%s stage=kernel", batch_no, project_no, draft_id)
|
||||
return payload
|
||||
|
||||
|
||||
def query_pending_projects(project_no: str = "") -> list[dict[str, Any]]:
|
||||
"""读取待结题项目(可按项目编号筛选),附成果与决算数量。"""
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if project_no:
|
||||
cur.execute("SELECT * FROM closing_projects WHERE project_no = ?", (project_no,))
|
||||
else:
|
||||
cur.execute("SELECT * FROM closing_projects WHERE status = '待结题' ORDER BY id")
|
||||
columns = [d[0] for d in cur.description]
|
||||
projects = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
for project in projects:
|
||||
pno = project.get("project_no")
|
||||
cur.execute("SELECT COUNT(*) FROM achievements WHERE project_no = ?", (pno,))
|
||||
project["achievement_count"] = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT COUNT(*) FROM expense_items WHERE project_no = ?", (pno,))
|
||||
project["expense_count"] = int(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
return projects
|
||||
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
|
||||
313
scripts/service/ledger_service.py
Normal file
313
scripts/service/ledger_service.py
Normal file
@@ -0,0 +1,313 @@
|
||||
"""结题项目 / 成果清单 / 决算明细 / 初稿记录 的维护与查询。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from service.draft_service import _norm_achievement, _norm_expense, _norm_project
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.timeutil import now_unix
|
||||
|
||||
_PROJECT_TEXT_FIELDS = ("project_name", "pi_name", "department", "program", "start_date", "end_date", "annual_report_excerpt", "status")
|
||||
_KNOWN_STATUS = ("待结题", "初稿已生成", "已提交")
|
||||
_KNOWN_ACH_TYPES = ("论文", "专利", "人才培养", "其他")
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _snake(name: str) -> str:
|
||||
return "".join("_" + ch.lower() if ch.isupper() else ch for ch in str(name)).lstrip("_")
|
||||
|
||||
|
||||
def _to_float(value: Any) -> Optional[float]:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def upsert_project(fields: dict[str, Any]) -> dict[str, Any]:
|
||||
fields = {_snake(k): v for k, v in _norm_project(fields).items()}
|
||||
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 _PROJECT_TEXT_FIELDS:
|
||||
if fields.get(key) not in (None, ""):
|
||||
values[key] = str(fields[key]).strip()
|
||||
if values.get("status") and values["status"] not in _KNOWN_STATUS:
|
||||
raise ValueError(f"status 只接受 {'、'.join(_KNOWN_STATUS)}:{values['status']}")
|
||||
if fields.get("expected_json") not in (None, ""):
|
||||
raw = fields["expected_json"]
|
||||
try:
|
||||
expected = json.loads(raw) if isinstance(raw, str) else raw
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f"预期指标 JSON 解析失败:{exc}") from exc
|
||||
if not isinstance(expected, list):
|
||||
raise ValueError("预期指标应为数组,如 [{\"type\":\"论文\",\"target\":3,\"unit\":\"篇\"}]")
|
||||
values["expected_json"] = json.dumps(expected, ensure_ascii=False)
|
||||
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM closing_projects WHERE project_no = ?", (project_no,))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
project_id = int(row[0])
|
||||
set_clause = ", ".join(f"{k} = ?" for k in values if k != "project_no")
|
||||
cur.execute(
|
||||
f"UPDATE closing_projects SET {set_clause}, updated_at = ? WHERE id = ?",
|
||||
[values[k] for k in values if k != "project_no"] + [now_unix(), project_id],
|
||||
)
|
||||
action = "updated"
|
||||
else:
|
||||
columns = ", ".join(values.keys())
|
||||
placeholders = ", ".join("?" for _ in values)
|
||||
cur.execute(
|
||||
f"INSERT INTO closing_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()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("closing_project_upserted project_no=%s action=%s stage=ledger", project_no, action)
|
||||
return {"ok": True, "project_no": project_no, "id": project_id, "action": action}
|
||||
|
||||
|
||||
def upsert_achievement(fields: dict[str, Any]) -> dict[str, Any]:
|
||||
achievement = {_snake(k): v for k, v in _norm_achievement(fields).items()}
|
||||
project_no = str(achievement.get("project_no") or "").strip()
|
||||
title = str(achievement.get("title") or "").strip()
|
||||
ach_type = str(achievement.get("achievement_type") or "").strip()
|
||||
if not project_no:
|
||||
raise ValueError("项目编号(project_no)不能为空")
|
||||
if not ach_type:
|
||||
raise ValueError("成果类型(achievement_type)不能为空")
|
||||
if ach_type not in _KNOWN_ACH_TYPES:
|
||||
raise ValueError(f"成果类型只接受 {'、'.join(_KNOWN_ACH_TYPES)}:{ach_type}")
|
||||
if not title:
|
||||
raise ValueError("成果名称(title)不能为空")
|
||||
|
||||
values = {
|
||||
"project_no": project_no,
|
||||
"achievement_type": ach_type,
|
||||
"title": title,
|
||||
"venue_or_no": str(achievement.get("venue_or_no") or "").strip(),
|
||||
"ach_date": str(achievement.get("ach_date") or "").strip(),
|
||||
"is_representative": 1 if str(achievement.get("is_representative") or "").strip() in ("1", "true", "True", "是") else 0,
|
||||
"note": str(achievement.get("note") or "").strip(),
|
||||
}
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM closing_projects WHERE project_no = ?", (project_no,))
|
||||
if not cur.fetchone():
|
||||
raise ValueError(f"项目不存在,请先录入结题项目:{project_no}")
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO achievements
|
||||
(project_no, achievement_type, title, venue_or_no, ach_date, is_representative, note, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
list(values.values()) + [now_unix(), now_unix()],
|
||||
)
|
||||
achievement_id = int(cur.lastrowid)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("achievement_added project_no=%s type=%s stage=ledger", project_no, ach_type)
|
||||
return {"ok": True, "id": achievement_id, "project_no": project_no, "title": title}
|
||||
|
||||
|
||||
def upsert_expense(fields: dict[str, Any]) -> dict[str, Any]:
|
||||
expense = {_snake(k): v for k, v in _norm_expense(fields).items()}
|
||||
project_no = str(expense.get("project_no") or "").strip()
|
||||
category = str(expense.get("category") or "").strip()
|
||||
amount = _to_float(expense.get("amount"))
|
||||
if not project_no:
|
||||
raise ValueError("项目编号(project_no)不能为空")
|
||||
if not category:
|
||||
raise ValueError("科目(category)不能为空")
|
||||
if amount is None or amount < 0:
|
||||
raise ValueError(f"金额必须是非负数字:{fields.get('amount')}")
|
||||
|
||||
values = {
|
||||
"project_no": project_no,
|
||||
"category": category,
|
||||
"amount": round(amount, 2),
|
||||
"occurred_date": str(expense.get("occurred_date") or "").strip(),
|
||||
"description": str(expense.get("description") or "").strip(),
|
||||
}
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM closing_projects WHERE project_no = ?", (project_no,))
|
||||
if not cur.fetchone():
|
||||
raise ValueError(f"项目不存在,请先录入结题项目:{project_no}")
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO expense_items
|
||||
(project_no, category, amount, occurred_date, description, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
list(values.values()) + [now_unix(), now_unix()],
|
||||
)
|
||||
expense_id = int(cur.lastrowid)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("expense_added project_no=%s category=%s stage=ledger", project_no, category)
|
||||
return {"ok": True, "id": expense_id, "project_no": project_no, "category": category, "amount": values["amount"]}
|
||||
|
||||
|
||||
def _import_generic(rows: Any, upsert, label: str) -> dict[str, Any]:
|
||||
if not isinstance(rows, list) or not rows:
|
||||
raise ValueError(f"导入内容应为非空 JSON 数组({label})")
|
||||
if len(rows) > 500:
|
||||
raise ValueError(f"单次导入条数过多({len(rows)}),上限 500 条")
|
||||
results = []
|
||||
for idx, raw in enumerate(rows):
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"第 {idx + 1} 条不是 JSON 对象")
|
||||
results.append(upsert(raw))
|
||||
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"),
|
||||
"items": results,
|
||||
}
|
||||
|
||||
|
||||
def import_projects(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
return _import_generic(rows, lambda row: upsert_project({_snake(k): v for k, v in _norm_project(row).items()}), "结题项目")
|
||||
|
||||
|
||||
def import_achievements(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
return _import_generic(rows, lambda row: upsert_achievement({_snake(k): v for k, v in _norm_achievement(row).items()}), "成果清单")
|
||||
|
||||
|
||||
def import_expenses(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
return _import_generic(rows, lambda row: upsert_expense({_snake(k): v for k, v in _norm_expense(row).items()}), "决算明细")
|
||||
|
||||
|
||||
def list_projects(status: str = "") -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if status:
|
||||
cur.execute("SELECT * FROM closing_projects WHERE status = ? ORDER BY id", (status,))
|
||||
else:
|
||||
cur.execute("SELECT * FROM closing_projects 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
|
||||
|
||||
|
||||
def list_achievements(project_no: str) -> list[dict[str, Any]]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM achievements WHERE project_no = ? ORDER BY id", (project_no,))
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
|
||||
def list_expenses(project_no: str) -> list[dict[str, Any]]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM expense_items WHERE project_no = ? ORDER BY id", (project_no,))
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
|
||||
def list_drafts(limit: int = 20) -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
limit = max(1, min(int(limit), 200))
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT id, batch_no, project_no, project_name, draft_file, preview_file, created_at FROM report_drafts 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_draft(draft_id: int) -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM report_drafts WHERE id = ?", (draft_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"初稿记录不存在:{draft_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
draft = dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
for key in ("completion_json", "narrative_points_json"):
|
||||
try:
|
||||
draft[key[:-5]] = json.loads(draft.get(key) or "[]")
|
||||
except (TypeError, ValueError):
|
||||
draft[key[:-5]] = []
|
||||
return draft
|
||||
|
||||
|
||||
def stats() -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT status, COUNT(*) FROM closing_projects GROUP BY status")
|
||||
by_status = {str(r[0]): int(r[1]) for r in cur.fetchall()}
|
||||
cur.execute("SELECT COUNT(*) FROM achievements")
|
||||
achievement_total = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT COUNT(*) FROM expense_items")
|
||||
expense_total = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT COUNT(*) FROM report_drafts")
|
||||
draft_total = int(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"ok": True,
|
||||
"projects_by_status": by_status,
|
||||
"achievement_total": achievement_total,
|
||||
"expense_total": expense_total,
|
||||
"draft_total": draft_total,
|
||||
}
|
||||
104
scripts/service/report_service.py
Normal file
104
scripts/service/report_service.py
Normal file
@@ -0,0 +1,104 @@
|
||||
"""初稿 HTML 预览组装。
|
||||
|
||||
与 Word 初稿同构内容写入 `{skill_data}/html/draft-{id}.html`,宿主侧栏可预览;
|
||||
重建走固定 Action id `render-html`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
|
||||
_TEMPLATE_REL = "assets/html/draft-preview.html"
|
||||
|
||||
|
||||
def _esc(value: Any) -> str:
|
||||
import html
|
||||
|
||||
return html.escape(str(value if value is not None else "—"), quote=True)
|
||||
|
||||
|
||||
def _sections_html(sections: dict[str, list[str]]) -> str:
|
||||
parts = []
|
||||
for title, paragraphs in (sections or {}).items():
|
||||
items = "".join(f"<p class='para{' placeholder' if p.startswith('[待补充') else ''}'>{_esc(p)}</p>" for p in paragraphs)
|
||||
parts.append(f"<div class='section'><h2>{_esc(title)}</h2>{items}</div>")
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def build_preview_html(draft: dict[str, Any]) -> str:
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
<span class="tag tier-info">初稿</span>
|
||||
<span class="muted">项目 {_esc(draft.get("project_no"))} · 批次 {_esc(draft.get("batch_no"))}</span>
|
||||
</div>
|
||||
<div class="section"><h2>生成说明</h2>
|
||||
<p class="para">数据章节(完成情况/决算/成果清单)由台账自动生成,请逐项核对;叙事章节仅提供素材要点,须由项目负责人本人终审。</p>
|
||||
</div>
|
||||
{_sections_html(draft.get("sections") or {})}
|
||||
<footer>本预览与 Word 初稿同构;严禁引入台账之外的成果或结论。以本单位结题报告模板为准。</footer>
|
||||
"""
|
||||
template = load_html_template(_TEMPLATE_REL)
|
||||
return render_html_placeholders(
|
||||
template,
|
||||
{
|
||||
"TITLE": f"结题报告初稿预览 · {draft.get('project_name') or draft.get('project_no') or ''}",
|
||||
"GENERATED_AT": "",
|
||||
"BODY": body,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def write_preview_for_kernel(*, draft: dict[str, Any]) -> str:
|
||||
html_text = build_preview_html(draft)
|
||||
log = get_skill_logger()
|
||||
path = write_html_page("draft-preview.html", html_text)
|
||||
log.info("draft_preview_written project_no=%s path=%s stage=report", draft.get("project_no"), path)
|
||||
return path
|
||||
|
||||
|
||||
def build_preview_for_draft_id(draft_id: int) -> str:
|
||||
"""按初稿记录 id 重建 HTML 预览(重建入口用)。"""
|
||||
from db.connection import get_conn
|
||||
|
||||
log = get_skill_logger()
|
||||
log.info("preview_render_start draft_id=%s stage=render", draft_id)
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM report_drafts WHERE id = ?", (draft_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"初稿记录不存在:{draft_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
record = dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
try:
|
||||
completion = json.loads(record.get("completion_json") or "[]")
|
||||
except (TypeError, ValueError):
|
||||
completion = []
|
||||
try:
|
||||
narrative_points = json.loads(record.get("narrative_points_json") or "[]")
|
||||
except (TypeError, ValueError):
|
||||
narrative_points = []
|
||||
|
||||
sections: dict[str, list[str]] = {
|
||||
"完成情况(自动生成)": [f"{row.get('type')}:{row.get('detail')}" for row in completion] or ["指标未配置(W1)。"],
|
||||
"叙事素材要点": [f"· {p.get('point')}(来源:{p.get('source')})" for p in narrative_points] or ["无素材,请补录成果/年度报告摘句。"],
|
||||
"Word 初稿": [f"文件:{record.get('draft_file') or '—'}(output 目录可取)"],
|
||||
}
|
||||
draft = {
|
||||
"project_no": record.get("project_no"),
|
||||
"project_name": record.get("project_name"),
|
||||
"batch_no": record.get("batch_no"),
|
||||
"sections": sections,
|
||||
}
|
||||
html_text = build_preview_html(draft)
|
||||
path = write_html_page(f"draft-{draft_id}.html", html_text)
|
||||
log.info("preview_render_done draft_id=%s path=%s stage=render", draft_id, 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', '')}"
|
||||
)
|
||||
625
scripts/service/task_service.py
Normal file
625
scripts/service/task_service.py
Normal file
@@ -0,0 +1,625 @@
|
||||
"""任务编排层:job_context / emit / finish、鉴权与错误转换。
|
||||
|
||||
领域业务在 ``service/draft_service.py``(初稿内核)、
|
||||
``service/ledger_service.py``(台账/记录)、``service/docx_service.py``(Word 渲染)、
|
||||
``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 这是模板演示入口,请使用 draft-report 命令生成结题报告初稿。")
|
||||
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:
|
||||
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()})
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 台账维护
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _parse_json_arg(raw: str, label: str) -> list[dict[str, Any]]:
|
||||
import sys
|
||||
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
raise ValueError(f"缺少导入 JSON({label})")
|
||||
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"{label} 不是有效文件路径或 JSON:{text[:80]}")
|
||||
try:
|
||||
payload = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"导入 JSON 解析失败:{exc}") from exc
|
||||
if isinstance(payload, dict):
|
||||
for key in ("projects", "achievements", "expenses", "items"):
|
||||
if isinstance(payload.get(key), list):
|
||||
payload = payload[key]
|
||||
break
|
||||
else:
|
||||
payload = [payload]
|
||||
if not isinstance(payload, list):
|
||||
raise ValueError(f"{label} 应为对象数组")
|
||||
return payload
|
||||
|
||||
|
||||
def cmd_add_project(
|
||||
*,
|
||||
project_no: str,
|
||||
name: str = "",
|
||||
pi: str = "",
|
||||
department: str = "",
|
||||
program: str = "",
|
||||
start: str = "",
|
||||
end: str = "",
|
||||
expected_json: str = "",
|
||||
excerpt: str = "",
|
||||
status: str = "",
|
||||
) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import upsert_project
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=add_project project_no=%s stage=ledger", project_no)
|
||||
emit("开始写入结题项目", skill=SKILL_SLUG, stage="ledger")
|
||||
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")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
fields: dict[str, Any] = {"project_no": project_no}
|
||||
for key, value in (("project_name", name), ("pi_name", pi), ("department", department), ("program", program), ("start_date", start), ("end_date", end), ("expected_json", expected_json), ("annual_report_excerpt", excerpt), ("status", status)):
|
||||
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="ledger")
|
||||
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="ledger")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=add_project stage=ledger")
|
||||
finish(status="failed", message="项目写入异常,详见统一日志", skill=SKILL_SLUG, stage="ledger")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_add_achievement(
|
||||
*,
|
||||
project_no: str,
|
||||
ach_type: str,
|
||||
title: str,
|
||||
venue: str = "",
|
||||
date: str = "",
|
||||
representative: str = "",
|
||||
note: str = "",
|
||||
) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import upsert_achievement
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=add_achievement project_no=%s stage=ledger", project_no)
|
||||
emit("开始写入成果", skill=SKILL_SLUG, stage="ledger")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=add_achievement stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = upsert_achievement(
|
||||
{"project_no": project_no, "achievement_type": ach_type, "title": title, "venue_or_no": venue, "ach_date": date, "is_representative": representative, "note": note}
|
||||
)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"成果已录入:{title[:20]}", skill=SKILL_SLUG, stage="ledger")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=add_achievement error_code=PROJECT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROJECT_INVALID", stage="ledger")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=add_achievement stage=ledger")
|
||||
finish(status="failed", message="成果写入异常,详见统一日志", skill=SKILL_SLUG, stage="ledger")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_add_expense(*, project_no: str, category: str, amount: float, date: str = "", description: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import upsert_expense
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=add_expense project_no=%s stage=ledger", project_no)
|
||||
emit("开始写入决算明细", skill=SKILL_SLUG, stage="ledger")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=add_expense stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = upsert_expense({"project_no": project_no, "category": category, "amount": amount, "occurred_date": date, "description": description})
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"决算明细已录入:{category} {payload['amount']} 元", skill=SKILL_SLUG, stage="ledger")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=add_expense error_code=PROJECT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROJECT_INVALID", stage="ledger")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=add_expense stage=ledger")
|
||||
finish(status="failed", message="决算写入异常,详见统一日志", skill=SKILL_SLUG, stage="ledger")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_import(projects_json: str = "", achievements_json: str = "", expenses_json: str = "") -> int:
|
||||
"""统一导入入口:projects/achievements/expenses 三类 JSON(至少提供一个)。"""
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import import_achievements, import_expenses, import_projects
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=import stage=ledger")
|
||||
emit("开始批量导入结题数据", skill=SKILL_SLUG, stage="ledger")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=import stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
summary: dict[str, Any] = {"ok": True}
|
||||
if projects_json:
|
||||
summary["projects"] = import_projects(_parse_json_arg(projects_json, "--projects-json"))
|
||||
if achievements_json:
|
||||
summary["achievements"] = import_achievements(_parse_json_arg(achievements_json, "--achievements-json"))
|
||||
if expenses_json:
|
||||
summary["expenses"] = import_expenses(_parse_json_arg(expenses_json, "--expenses-json"))
|
||||
if len(summary) == 1:
|
||||
raise ValueError("至少提供一个导入 JSON(--projects-json / --achievements-json / --expenses-json)")
|
||||
_print_json(summary)
|
||||
finish(status="success", message="批量导入完成", skill=SKILL_SLUG, stage="ledger")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=import error_code=PROJECT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROJECT_INVALID", stage="ledger")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=import stage=ledger")
|
||||
finish(status="failed", message="批量导入异常,详见统一日志", skill=SKILL_SLUG, stage="ledger")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_list(kind: str = "projects", project_no: str = "", status: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import list_achievements, list_expenses, list_projects
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list kind=%s project_no=%s", kind, project_no)
|
||||
try:
|
||||
if kind == "achievements":
|
||||
rows = list_achievements(project_no)
|
||||
elif kind == "expenses":
|
||||
rows = list_expenses(project_no)
|
||||
else:
|
||||
rows = list_projects(status=status)
|
||||
_print_json({"ok": True, "count": len(rows), "rows": rows})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list")
|
||||
print("ERROR:QUERY_FAILED 台账查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 初稿生成
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_draft_report(*, project_no: str) -> int:
|
||||
"""结题报告初稿(主命令,同步):指定项目生成 Word 初稿 + HTML 预览。"""
|
||||
log = _get_task_logger()
|
||||
from service.draft_service import query_pending_projects, run_draft
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=draft_report project_no=%s stage=draft", project_no)
|
||||
emit("开始生成结题报告初稿", skill=SKILL_SLUG, stage="draft")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=draft_report stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
projects = query_pending_projects(project_no=project_no)
|
||||
if not projects:
|
||||
message = f"未找到该项目(编号 {project_no})或项目状态不是“待结题”"
|
||||
log.warning("task_failed task_type=draft_report error_code=PROJECT_NOT_FOUND stage=draft")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="PROJECT_NOT_FOUND", stage="draft")
|
||||
print(f"ERROR:PROJECT_NOT_FOUND {message}")
|
||||
return 1
|
||||
project = projects[0]
|
||||
achievements = []
|
||||
expenses = []
|
||||
from service.ledger_service import list_achievements, list_expenses
|
||||
|
||||
achievements = list_achievements(project_no)
|
||||
expenses = list_expenses(project_no)
|
||||
|
||||
result = run_draft(project, achievements, expenses)
|
||||
_print_json(result)
|
||||
finish(
|
||||
status="success",
|
||||
message=f"初稿已生成:{result['draft_file']}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="draft",
|
||||
batch_no=result["batch_no"],
|
||||
)
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=draft_report error_code=PROJECT_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROJECT_INVALID", stage="draft")
|
||||
print(f"ERROR:PROJECT_INVALID {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=draft_report stage=draft")
|
||||
emit("初稿生成失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="draft")
|
||||
finish(status="failed", message="初稿生成异常,详见统一日志", skill=SKILL_SLUG, stage="draft")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_draft_batch_pending() -> int:
|
||||
"""批量初稿(async Action 入口):为全部“待结题”项目生成初稿,任务中心可见进度。"""
|
||||
log = _get_task_logger()
|
||||
from service.draft_service import query_pending_projects, run_draft
|
||||
from service.ledger_service import list_achievements, list_expenses
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=draft_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=draft_batch stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
projects = query_pending_projects()
|
||||
if not projects:
|
||||
message = "没有“待结题”状态的项目,批量生成跳过"
|
||||
log.warning("task_failed task_type=draft_batch error_code=PROJECT_NOT_FOUND stage=batch")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="PROJECT_NOT_FOUND", stage="batch")
|
||||
print(f"ERROR:PROJECT_NOT_FOUND {message}")
|
||||
return 1
|
||||
|
||||
drafts = []
|
||||
for index, project in enumerate(projects, start=1):
|
||||
emit(f"[{index}/{len(projects)}] {project.get('project_name') or project.get('project_no')}", skill=SKILL_SLUG, stage="batch")
|
||||
try:
|
||||
result = run_draft(project, list_achievements(project["project_no"]), list_expenses(project["project_no"]))
|
||||
drafts.append({"draft_id": result["draft_id"], "project_no": result["project_no"], "draft_file": result["draft_file"]})
|
||||
except Exception:
|
||||
log.exception("draft_batch_item_failed project_no=%s", project.get("project_no"))
|
||||
_print_json({"ok": True, "count": len(drafts), "drafts": drafts})
|
||||
finish(status="success", message=f"批量初稿完成 {len(drafts)}/{len(projects)} 个项目", skill=SKILL_SLUG, stage="batch")
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=draft_batch stage=batch")
|
||||
emit("批量初稿失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="batch")
|
||||
finish(status="failed", message="批量初稿执行异常,详见统一日志", skill=SKILL_SLUG, stage="batch")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 记录与统计
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_list_drafts(limit: int = 20) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import list_drafts
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_drafts limit=%s", limit)
|
||||
try:
|
||||
drafts = list_drafts(limit=limit)
|
||||
_print_json({"ok": True, "count": len(drafts), "drafts": drafts})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_drafts")
|
||||
print("ERROR:QUERY_FAILED 初稿记录查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_show_draft(draft_id: int) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import get_draft
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=show_draft draft_id=%s", draft_id)
|
||||
try:
|
||||
draft = get_draft(int(draft_id))
|
||||
_print_json({"ok": True, "draft": draft})
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=show_draft error_code=DRAFT_NOT_FOUND detail=%s", exc)
|
||||
print(f"ERROR:DRAFT_NOT_FOUND {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=show_draft")
|
||||
print("ERROR:QUERY_FAILED 初稿记录查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_render_html(report_id: Optional[int] = None) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_service import list_drafts
|
||||
from service.report_service import build_preview_for_draft_id
|
||||
|
||||
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 = [d["id"] for d in list_drafts(limit=10)]
|
||||
if not targets:
|
||||
log.warning("task_failed task_type=render_html error_code=DRAFT_NOT_FOUND stage=render")
|
||||
finish(status="failed", message="暂无可重建的初稿记录", skill=SKILL_SLUG, error_code="DRAFT_NOT_FOUND", stage="render")
|
||||
print("ERROR:DRAFT_NOT_FOUND 暂无可重建的初稿记录")
|
||||
return 1
|
||||
written = [{"draft_id": did, "path": build_preview_for_draft_id(did)} for did in targets]
|
||||
_print_json({"ok": True, "count": len(written), "previews": 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=DRAFT_NOT_FOUND detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="DRAFT_NOT_FOUND", stage="render")
|
||||
print(f"ERROR:DRAFT_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_stats() -> int:
|
||||
log = _get_task_logger()
|
||||
from service.ledger_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