feat: 初始化高校人事请假考勤技能 (process-leave-attendance-default)
All checks were successful
技能自动化发布 / release (push) Successful in 15s

基于 skill-template 脚手架开发,包含:
- 5 张业务表(教职工、请假政策、考勤日历、请假记录、假期余额)
- 请假核算引擎(扣薪计算、审批层级判定、年假抵扣)
- CLI 入口(import-employees / calculate-leave / render-html)
- HTML 审批与扣薪报告生成
- 示例数据与完整测试套件(295 tests passed)
This commit is contained in:
chenfuqiang
2026-09-07 16:59:24 +08:00
commit ee2a4d9e22
206 changed files with 29510 additions and 0 deletions

View File

@@ -0,0 +1,179 @@
"""教职工导入:从 input/教职工库 读取 JSON,并可选播种示例政策与假日。"""
from __future__ import annotations
import json
import os
import shutil
from typing import Any
from db import leave_repository as repo
from util.logging_config import get_skill_logger
from util.runtime_paths import get_input_dir, get_skill_root, resolve_input_path
IMPORT_SUBDIR = "教职工库"
def _log():
try:
return get_skill_logger()
except RuntimeError:
return None
def get_builtin_samples_dir() -> str:
return os.path.join(get_skill_root(), "assets", "samples")
def get_employees_input_dir(*, create: bool = True) -> str:
path = os.path.join(get_input_dir(create=create), IMPORT_SUBDIR)
if create:
os.makedirs(path, exist_ok=True)
return path
def ensure_builtin_samples(*, overwrite: bool = False) -> list[str]:
"""将 assets/samples/示例教职工.json 复制到 input/教职工库(若不存在)。"""
src_dir = get_builtin_samples_dir()
dst_dir = get_employees_input_dir(create=True)
copied: list[str] = []
employee_src = os.path.join(src_dir, "示例教职工.json")
employee_dst = os.path.join(dst_dir, "示例教职工.json")
if os.path.isfile(employee_src) and (overwrite or not os.path.isfile(employee_dst)):
shutil.copy2(employee_src, employee_dst)
copied.append("示例教职工.json")
seed_sample_policies_if_empty()
seed_sample_holidays_if_empty()
log = _log()
if log and copied:
log.info("employee_samples_synced count=%s", len(copied))
return copied
def seed_sample_policies_if_empty() -> int:
if repo.count_policies() > 0:
return 0
path = os.path.join(get_builtin_samples_dir(), "示例政策.json")
if not os.path.isfile(path):
return 0
with open(path, encoding="utf-8") as f:
data = json.load(f)
count = 0
for policy in data.get("policies") or []:
repo.upsert_policy(policy)
count += 1
log = _log()
if log:
log.info("sample_policies_seeded count=%s", count)
return count
def seed_sample_holidays_if_empty() -> int:
if repo.count_holidays() > 0:
return 0
path = os.path.join(get_builtin_samples_dir(), "示例政策.json")
if not os.path.isfile(path):
return 0
with open(path, encoding="utf-8") as f:
data = json.load(f)
count = 0
for holiday in data.get("holidays") or []:
repo.upsert_holiday(holiday)
count += 1
log = _log()
if log:
log.info("sample_holidays_seeded count=%s", count)
return count
def resolve_employees_file(raw: str) -> str:
text = (raw or "").strip().strip('"').strip("'")
if not text:
raise ValueError("请选择教职工文件(input/教职工库/ 下的 .json)。")
if "{{" in text or "}}" in text:
raise ValueError("未选择有效文件。请选择 input/教职工库/ 目录下的 JSON。")
if os.path.isabs(text) and os.path.isfile(text):
return os.path.abspath(text)
candidate = resolve_input_path(text, create_parent=False)
if os.path.isfile(candidate):
return candidate
packs = get_employees_input_dir(create=True)
by_name = os.path.abspath(os.path.join(packs, os.path.basename(text)))
if os.path.isfile(by_name):
return by_name
under = os.path.abspath(os.path.join(packs, text.replace("\\", "/").lstrip("/")))
if os.path.isfile(under):
return under
raise ValueError(
f"找不到教职工文件:{text}。请放到「输入目录/{IMPORT_SUBDIR}/」后重新选择。"
)
def _normalize_employee(item: dict[str, Any]) -> dict[str, Any]:
return {
"name": str(item.get("name") or "").strip(),
"employee_no": str(item.get("employee_no") or "").strip() or None,
"department": str(item.get("department") or "").strip() or None,
"position": str(item.get("position") or "").strip() or None,
"position_category": str(item.get("position_category") or "").strip() or None,
"join_date": str(item.get("join_date") or "").strip() or None,
"monthly_salary": float(item.get("monthly_salary", 0) or 0),
"annual_leave_remaining": float(item.get("annual_leave_remaining", 0) or 0),
"is_active": item.get("is_active", 1),
"notes": str(item.get("notes") or "").strip() or None,
}
def import_employees_json(file_path: str) -> dict[str, Any]:
path = resolve_employees_file(file_path)
with open(path, encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
items = data.get("employees") or data.get("items") or []
if not items and data.get("name"):
items = [data]
elif isinstance(data, list):
items = data
else:
raise ValueError("教职工 JSON 格式无效:应为数组或含 employees 字段的对象。")
created = 0
updated = 0
skipped = 0
for raw in items:
if not isinstance(raw, dict):
skipped += 1
continue
payload = _normalize_employee(raw)
if not payload["name"]:
skipped += 1
continue
before = repo.find_employee_by_name(payload["name"])
repo.upsert_employee(payload)
if before:
updated += 1
else:
created += 1
ensure_builtin_samples(overwrite=False)
result = {
"ok": True,
"file": path,
"created": created,
"updated": updated,
"skipped": skipped,
"total": created + updated,
"message": f"已导入教职工:新增 {created},更新 {updated},跳过 {skipped}。",
}
log = _log()
if log:
log.info(
"employees_imported created=%s updated=%s skipped=%s file=%s",
created,
updated,
skipped,
path,
)
return result

View 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, ""

View 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

View File

@@ -0,0 +1,365 @@
"""高校人事请假考勤:领域服务(核算引擎与报告生成)。"""
from __future__ import annotations
import calendar
import html
from datetime import date, datetime
from typing import Any, Optional
from db import leave_repository as repo
from service.employee_import_service import IMPORT_SUBDIR, ensure_builtin_samples
from service.html_page_service import (
HOST_HTML_RENDER_ACTION_ID,
load_html_template,
render_html_placeholders,
write_html_page,
)
from util.logging_config import get_skill_logger
from util.timeutil import now_unix
def _log():
try:
return get_skill_logger()
except RuntimeError:
return None
def ensure_ready() -> None:
ensure_builtin_samples(overwrite=False)
def _parse_date(text: str) -> date:
try:
return datetime.strptime(text.strip(), "%Y-%m-%d").date()
except (ValueError, AttributeError) as exc:
raise ValueError(f"日期格式无效:{text!r}(需 YYYY-MM-DD)") from exc
def _load_holiday_dates() -> set[str]:
holidays = repo.list_holidays()
return {h["holiday_date"] for h in holidays if h.get("holiday_date")}
def _count_working_days(start: date, end: date, holiday_dates: set[str]) -> int:
count = 0
cur = start
while cur <= end:
iso = cur.isoformat()
if cur.weekday() < 5 and iso not in holiday_dates:
count += 1
cur = date.fromordinal(cur.toordinal() + 1)
return count
def _working_days_in_month(d: date, holiday_dates: set[str]) -> int:
_, last_day = calendar.monthrange(d.year, d.month)
count = 0
for day in range(1, last_day + 1):
cur = date(d.year, d.month, day)
iso = cur.isoformat()
if cur.weekday() < 5 and iso not in holiday_dates:
count += 1
return count
def _determine_approval_level(
working_days: int, policy: dict[str, Any], leave_type: str
) -> str:
if leave_type in ("产假", "育假"):
return "系主任+人事处+校领导"
threshold_dept = int(policy.get("approval_threshold_dept", 3))
threshold_hr = int(policy.get("approval_threshold_hr", 10))
if working_days <= threshold_dept:
return "系主任"
if working_days <= threshold_hr:
return "系主任+人事处"
return "系主任+人事处+校领导"
def calculate_leave(
employee_id: int,
*,
leave_type: str,
start_date: str,
end_date: str,
has_certificate: bool = False,
certificate_type: Optional[str] = None,
) -> dict[str, Any]:
ensure_ready()
employee = repo.get_employee(int(employee_id))
if not employee:
raise ValueError(f"找不到教职工 id={employee_id}。请先在「教职工」表中新增或导入。")
policy = repo.get_policy(leave_type)
if not policy:
raise ValueError(
f"未知请假类型:{leave_type}。请在「请假政策」表中配置该类型后重试。"
)
if int(policy.get("requires_certificate", 0)) and not has_certificate:
raise ValueError(f"请假类型「{leave_type}」需附证明文件,请提供后重试。")
start = _parse_date(start_date)
end = _parse_date(end_date)
if end < start:
raise ValueError("结束日期不能早于开始日期。")
natural_days = (end - start).days + 1
holiday_dates = _load_holiday_dates()
working_days = _count_working_days(start, end, holiday_dates)
day_basis = str(policy.get("day_basis", "workday"))
billable_days = natural_days if day_basis == "natural" else working_days
monthly_salary = float(employee.get("monthly_salary", 0) or 0)
working_days_in_month = _working_days_in_month(start, holiday_dates)
if working_days_in_month <= 0:
working_days_in_month = 21.75
daily_salary = monthly_salary / working_days_in_month if working_days_in_month else 0.0
paid_days = float(policy.get("paid_days", 0) or 0)
partial_ratio = float(policy.get("partial_pay_ratio", 1.0) or 1.0)
unpaid_after = policy.get("unpaid_after_days")
unpaid_after_days = float(unpaid_after) if unpaid_after is not None else None
if billable_days <= paid_days:
deduction_amount = 0.0
elif unpaid_after_days is not None and billable_days > unpaid_after_days:
partial_days = max(unpaid_after_days - paid_days, 0)
unpaid_days = billable_days - unpaid_after_days
deduction_amount = (
daily_salary * partial_days * (1 - partial_ratio)
+ daily_salary * unpaid_days
)
else:
partial_days = billable_days - paid_days
deduction_amount = daily_salary * partial_days * (1 - partial_ratio)
annual_leave_used = 0.0
remaining_annual_leave = float(employee.get("annual_leave_remaining", 0) or 0)
if int(policy.get("can_offset_annual", 0)) and remaining_annual_leave > 0:
offset_days = min(billable_days, remaining_annual_leave)
deduction_amount = max(deduction_amount - offset_days * daily_salary, 0.0)
annual_leave_used = offset_days
remaining_annual_leave = remaining_annual_leave - offset_days
approval_level = _determine_approval_level(working_days, policy, leave_type)
params = {
"employee_id": employee_id,
"leave_type": leave_type,
"start_date": start_date,
"end_date": end_date,
"has_certificate": has_certificate,
"certificate_type": certificate_type,
"policy_id": policy.get("id"),
"day_basis": day_basis,
}
request_id = repo.create_leave_request(
{
"employee_id": employee_id,
"leave_type": leave_type,
"start_date": start_date,
"end_date": end_date,
"has_certificate": 1 if has_certificate else 0,
"certificate_type": certificate_type,
"natural_days": natural_days,
"working_days": working_days,
"monthly_salary": monthly_salary,
"working_days_in_month": working_days_in_month,
"daily_salary": round(daily_salary, 2),
"deduction_amount": round(deduction_amount, 2),
"annual_leave_used": annual_leave_used,
"remaining_annual_leave": remaining_annual_leave,
"approval_level": approval_level,
"status": "draft",
"params": params,
"summary": f"{employee.get('name')}「{leave_type}」{start_date}~{end_date}({working_days}工作日)核算中…",
}
)
try:
summary = (
f"{employee.get('name')}「{leave_type}」{start_date}~{end_date}"
f"({natural_days}自然日/{working_days}工作日)"
f"应扣 {round(deduction_amount, 2)} 元,审批:{approval_level}"
)
repo.update_leave_request(
request_id,
status="completed",
summary=summary,
)
if annual_leave_used > 0:
repo.update_employee_annual_leave(employee_id, remaining_annual_leave)
balance_type = _map_balance_type(leave_type)
existing = repo.get_balance(employee_id, balance_type)
used = float(existing["used_days"]) if existing else 0.0
repo.upsert_balance(
{
"employee_id": employee_id,
"balance_type": balance_type,
"total_days": policy.get("max_days"),
"used_days": used + billable_days,
"remaining_days": (
float(policy.get("max_days", 0) or 0) - used - billable_days
if policy.get("max_days") is not None
else None
),
}
)
except Exception as exc:
repo.update_leave_request(
request_id,
status="failed",
error_message=str(exc),
)
raise
payload = {
"ok": True,
"request_id": request_id,
"employee_id": employee_id,
"employee_name": employee.get("name"),
"department": employee.get("department"),
"leave_type": leave_type,
"start_date": start_date,
"end_date": end_date,
"natural_days": natural_days,
"working_days": working_days,
"monthly_salary": monthly_salary,
"working_days_in_month": working_days_in_month,
"daily_salary": round(daily_salary, 2),
"deduction_amount": round(deduction_amount, 2),
"annual_leave_used": annual_leave_used,
"remaining_annual_leave": remaining_annual_leave,
"approval_level": approval_level,
"certificate_type": certificate_type,
"message": summary,
}
log = _log()
if log:
log.info(
"leave_calculated request_id=%s employee_id=%s deduction=%s approval=%s",
request_id,
employee_id,
round(deduction_amount, 2),
approval_level,
)
return payload
def _map_balance_type(leave_type: str) -> str:
mapping = {
"病假": "sick",
"长期病假": "sick",
"事假": "annual",
"婚假": "marriage",
"产假": "maternity",
"育假": "maternity",
"丧假": "bereavement",
}
return mapping.get(leave_type, "annual")
def build_leave_report_html(request_id: int) -> str:
req = repo.get_request(int(request_id))
if not req:
raise ValueError(f"找不到请假记录 id={request_id}。")
employee = repo.get_employee(int(req["employee_id"])) if req.get("employee_id") else None
name = html.escape(str(employee.get("name", "")) if employee else "")
department = html.escape(str(employee.get("department", "")) if employee else "")
position = html.escape(str(employee.get("position", "")) if employee else "")
rows = [
("申请人", f"{name}({department})"),
("岗位", position or "—"),
("请假类型", html.escape(str(req.get("leave_type", "")))),
("请假日期", f"{req.get('start_date', '')} 至 {req.get('end_date', '')}(共 {req.get('natural_days', 0)} 个自然日)"),
("实际工作日", f"{req.get('working_days', 0)} 天"),
("当月应出勤", f"{req.get('working_days_in_month', 0)} 天"),
("日薪", f"{req.get('daily_salary', 0)} 元"),
("应扣工资", f"{req.get('deduction_amount', 0)} 元"),
("已抵年假", f"{req.get('annual_leave_used', 0)} 天"),
("剩余年假", f"{req.get('remaining_annual_leave', 0)} 天"),
("审批层级", html.escape(str(req.get("approval_level", "")))),
("证件类型", html.escape(str(req.get("certificate_type") or "无"))),
("状态", html.escape(str(req.get("status", "")))),
]
rows_html = "".join(
f"<tr><th>{label}</th><td>{value}</td></tr>" for label, value in rows
)
summary = html.escape(str(req.get("summary", "")))
approval_hint = (
"若涉及产假/育假或超过 10 天,需校领导审批并报人事处存档。"
if "校领导" in str(req.get("approval_level", ""))
else "请将审批表与证明文件交至对应审批人。"
)
body = f"""
<section class="card">
<h2>请假审批与扣薪计算报告</h2>
<table class="meta-table">{rows_html}</table>
</section>
<section class="card">
<h2>审批流程</h2>
<p>{approval_hint}</p>
<p class="muted">已自动生成审批表,需附相关证件原件。</p>
</section>
<section class="card">
<h2>后续处理</h2>
<ul>
<li>考勤记录已更新:本次请假 {req.get('working_days', 0)} 个工作日。</li>
<li>假期余额已同步更新。</li>
<li>摘要:{summary}</li>
</ul>
</section>
"""
return body
def render_leave_report(request_id: Optional[int] = None) -> dict[str, Any]:
ensure_ready()
rid: Optional[int] = None
if request_id is not None and str(request_id).strip():
text = str(request_id).strip()
if "{{" in text or "}}" in text:
text = ""
if text:
try:
rid = int(text)
except ValueError as exc:
raise ValueError(f"参数 request_id 必须是整数,当前为 {text!r}") from exc
if rid is None:
latest = repo.get_latest_completed_request()
if not latest:
raise ValueError("暂无已完成的请假核算记录,请先执行「请假核算」。")
rid = int(latest["id"])
body = build_leave_report_html(rid)
template = load_html_template("assets/html/leave-report.html")
page = render_html_placeholders(
template,
{
"TITLE": f"请假审批与扣薪报告 #{rid}",
"GENERATED_AT": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"BODY": body,
},
)
filename = f"leave-report-{rid}-{now_unix()}.html"
path = write_html_page(filename, page)
payload = {
"ok": True,
"request_id": rid,
"html_path": path,
"filename": filename,
"action_id": HOST_HTML_RENDER_ACTION_ID,
"message": f"已生成请假报告:{filename}",
}
log = _log()
if log:
log.info("leave_report_rendered request_id=%s path=%s", rid, path)
return payload

View File

@@ -0,0 +1,84 @@
"""任务运行辅助:录屏信息组装与 CLI 输出(通用模板,无业务逻辑)。"""
from __future__ import annotations
from typing import Any, 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]:
"""将录屏 session.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', '')}"
)

View File

@@ -0,0 +1,285 @@
"""任务编排:鉴权、进度 emit、请假考勤领域调度。"""
from __future__ import annotations
import json
import os
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 db.connection import init_db
from service.employee_import_service import IMPORT_SUBDIR, ensure_builtin_samples
from service.entitlement_service import check_entitlement
from service.leave_service import calculate_leave, render_leave_report
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_data_dir, get_skill_root
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, indent=2))
_FINISH_RESERVED = frozenset(
{"status", "message", "skill", "error_code", "stage", "ok", "type", "schema_version"}
)
def _finish_success(message: str, payload: Optional[dict[str, Any]] = None, **extra: Any) -> None:
body: dict[str, Any] = {}
if payload:
body.update({k: v for k, v in payload.items() if k not in _FINISH_RESERVED})
body.update({k: v for k, v in extra.items() if k not in _FINISH_RESERVED})
finish(status="success", message=message, skill=SKILL_SLUG, **body)
def _parse_int(raw: Optional[str], name: str) -> int:
if raw is None or not str(raw).strip():
raise ValueError(f"缺少参数: {name}")
text = str(raw).strip()
if "{{" in text or "}}" in text:
raise ValueError(f"参数 {name} 未正确代入(收到 {text!r})。请选中行后再操作。")
try:
return int(text)
except ValueError as exc:
raise ValueError(f"参数 {name} 必须是整数,当前为 {text!r}") from exc
def _parse_optional_int(raw: Optional[str], name: str) -> Optional[int]:
if raw is None or not str(raw).strip():
return None
text = str(raw).strip()
if "{{" in text or "}}" in text:
return None
return _parse_int(raw, name)
def _check_entitlement_or_fail(log, task_type: str) -> bool:
ok, reason = check_entitlement(SKILL_SLUG)
if ok:
return True
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 False
def _parse_bool(raw: Optional[str]) -> bool:
if raw is None:
return False
text = str(raw).strip().lower()
if "{{" in text or "}}" in text:
return False
return text in ("1", "true", "yes", "是", "y")
def cmd_calculate_leave(
employee_id: Optional[str] = None,
leave_type: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
has_certificate: Optional[str] = None,
certificate_type: Optional[str] = None,
) -> int:
log = _get_task_logger()
task_type = "calculate-leave"
with job_context(skill=SKILL_SLUG):
log.info(
"task_start task_type=%s employee_id=%s leave_type=%s",
task_type,
employee_id,
leave_type,
)
emit("开始核算请假", skill=SKILL_SLUG, stage="calculate")
try:
if not _check_entitlement_or_fail(log, task_type):
return 1
eid = _parse_int(employee_id, "employee_id")
lt = (leave_type or "").strip()
if not lt or "{{" in lt:
raise ValueError("缺少参数: leave_type")
sd = (start_date or "").strip()
if not sd or "{{" in sd:
raise ValueError("缺少参数: start_date")
ed = (end_date or "").strip()
if not ed or "{{" in ed:
raise ValueError("缺少参数: end_date")
ct = (certificate_type or "").strip()
if "{{" in ct or "}}" in ct:
ct = None
payload = calculate_leave(
eid,
leave_type=lt,
start_date=sd,
end_date=ed,
has_certificate=_parse_bool(has_certificate),
certificate_type=ct or None,
)
_finish_success(str(payload.get("message") or "核算完成"), payload)
print("OK")
_print_json(payload)
return 0
except ValueError as exc:
log.warning("task_failed task_type=%s msg=%s", task_type, exc)
print(f"ERROR:{exc}")
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="VALIDATION")
return 1
except JobStopped:
raise
except Exception:
log.exception("task_failed task_type=%s", task_type)
finish(status="failed", message="请假核算失败", skill=SKILL_SLUG, stage="calculate")
return 1
def cmd_import_employees(file_path: Optional[str] = None) -> int:
log = _get_task_logger()
task_type = "import-employees"
with job_context(skill=SKILL_SLUG):
log.info("task_start task_type=%s file=%s", task_type, file_path)
emit("导入教职工", skill=SKILL_SLUG, stage="import")
try:
if not _check_entitlement_or_fail(log, task_type):
return 1
from service.employee_import_service import import_employees_json
path = (file_path or "").strip() or "示例教职工.json"
payload = import_employees_json(path)
_finish_success(str(payload.get("message") or "教职工已导入"), payload)
print("OK")
_print_json(payload)
return 0
except ValueError as exc:
log.warning("task_failed task_type=%s msg=%s", task_type, exc)
print(f"ERROR:{exc}")
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="VALIDATION")
return 1
except Exception:
log.exception("task_failed task_type=%s", task_type)
finish(status="failed", message="导入教职工失败", skill=SKILL_SLUG, stage="import")
return 1
def cmd_render_html(request_id: Optional[str] = None) -> int:
log = _get_task_logger()
emit("生成请假报告", skill=SKILL_SLUG, stage="report")
try:
rid = _parse_optional_int(request_id, "request_id")
payload = render_leave_report(rid)
log.info("render_html_ok path=%s", payload.get("html_path"))
print("OK")
_print_json(payload)
return 0
except ValueError as exc:
log.warning("render_html_failed msg=%s", exc)
print(f"ERROR:{exc}")
return 1
def cmd_run(target: Optional[str] = None, input_id: Optional[str] = None) -> int:
"""兼容入口:需 employee_id(来自 target 或 input_id)。"""
log = _get_task_logger()
employee_raw = target or input_id
if not employee_raw or not str(employee_raw).strip():
msg = "缺少参数: employee_id(run 需指定教职工编号,或使用 calculate-leave)"
log.warning("task_failed task_type=run msg=%s", msg)
print(f"ERROR:{msg}")
return 1
print("ERROR:run 入口仅兼容旧调用,请使用 calculate-leave 子命令并提供完整参数。")
return 1
def cmd_health() -> int:
log = _get_task_logger()
try:
init_db()
ensure_builtin_samples(overwrite=False)
except Exception as exc: # noqa: BLE001
log.warning("health_init_db_failed msg=%s", exc)
print(f"ERROR:init_db {exc}")
return 1
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)
log.info("health_ok status=%s", health_status)
return 1 if runtime.has_fatal_issues else 0
def cmd_version() -> int:
print(json.dumps({"version": SKILL_VERSION, "skill": SKILL_SLUG}, ensure_ascii=False))
return 0
def cmd_config_path() -> int:
example_path = os.path.join(get_skill_root(), ".env.example")
env_path = config.get_env_file_path() or ""
data = get_skill_data_dir()
print(
json.dumps(
{
"skill": SKILL_SLUG,
"env_path": env_path,
"example_path": os.path.abspath(example_path),
"data_dir": data,
"employees_dir": f"input/{IMPORT_SUBDIR}",
},
ensure_ascii=False,
)
)
return 0
def cmd_init_db() -> int:
try:
init_db()
ensure_builtin_samples(overwrite=False)
except Exception as exc: # noqa: BLE001
print(json.dumps({"ok": False, "skill": SKILL_SLUG, "error": str(exc)}, ensure_ascii=False))
return 1
print(
json.dumps(
{
"ok": True,
"skill": SKILL_SLUG,
"db_path": get_db_path(),
"employees_dir": f"input/{IMPORT_SUBDIR}",
},
ensure_ascii=False,
)
)
return 0