feat: 工资查询助手首版 v1.0.105

基于 skill-template 脚手架开发,包含:
- payroll_config(费率配置,可编辑)+ payslip_snapshots(解析历史,只读)2 张业务表
- 全国默认 + 北上广 4 套费率(社保/公积金/个税起征点/7 级税率表)
- 5 个业务 Action:calculate-payslip-simple / calculate-payslip-full / explain-term / view-config / edit-config
- 个税累计预扣法计算,支持多月历史累加
- 20 个薪资名词库(社保/公积金/个税/全勤/加班费等)
- 完整市场文档(README/TUTORIAL/DEMO/CHANGELOG)
- 296 测试全部通过
This commit is contained in:
skill-dev
2026-09-07 17:02:05 +08:00
commit 3db196e49d
205 changed files with 29927 additions and 0 deletions

View File

@@ -0,0 +1,147 @@
"""费率配置读取服务。
从 payroll_config 表读取指定地区的费率;地区未单独插入时回退到全国默认。
"""
from __future__ import annotations
import json
from typing import Any
from db.connection import get_conn
from util.logging_config import get_skill_logger
log = get_skill_logger()
def get_config_value(config_key: str, region: str = "default") -> float | str | None:
"""读取单个配置项的值。
优先取 (config_key, region);若该地区无记录,回退到 (config_key, 'default')。
"""
conn = get_conn()
try:
cur = conn.cursor()
cur.execute(
"SELECT config_value FROM payroll_config WHERE config_key=? AND region=?",
(config_key, region),
)
row = cur.fetchone()
if row is None and region != "default":
cur.execute(
"SELECT config_value FROM payroll_config WHERE config_key=? AND region='default'",
(config_key,),
)
row = cur.fetchone()
if row is None:
return None
return row[0]
finally:
conn.close()
def get_tax_brackets(region: str = "default") -> list[dict[str, Any]]:
"""读取 7 级累计预扣税率表。"""
raw = get_config_value("tax_brackets_json", region)
if raw is None or not isinstance(raw, str):
return []
try:
brackets = json.loads(raw)
return brackets if isinstance(brackets, list) else []
except (json.JSONDecodeError, TypeError):
return []
def get_region_config(region: str = "default") -> dict[str, Any]:
"""读取一个地区的全部费率配置,返回 dict。"""
keys = [
"social_pension_rate",
"social_medical_rate",
"social_unemployment_rate",
"social_base_min",
"social_base_max",
"housing_fund_rate",
"housing_fund_base_min",
"housing_fund_base_max",
"tax_threshold",
]
result: dict[str, Any] = {"region": region}
for key in keys:
result[key] = get_config_value(key, region)
result["tax_brackets"] = get_tax_brackets(region)
return result
def list_all_config(region: str | None = None) -> list[dict[str, Any]]:
"""列出费率配置(供 view-config Action)。
region 为 None 时列出全部地区;否则只列该地区(含回退默认值)。
"""
conn = get_conn()
try:
cur = conn.cursor()
if region is None:
cur.execute(
"SELECT config_key, region, config_value, display_name, description FROM payroll_config ORDER BY region, config_key"
)
else:
cur.execute(
"SELECT config_key, region, config_value, display_name, description FROM payroll_config WHERE region=? ORDER BY config_key",
(region,),
)
rows = cur.fetchall()
return [
{
"config_key": r[0],
"region": r[1],
"config_value": r[2],
"display_name": r[3],
"description": r[4],
}
for r in rows
]
finally:
conn.close()
def update_config_value(config_key: str, region: str, config_value: float) -> dict[str, Any]:
"""更新单个费率配置(供 edit-config Action)。
返回 {ok, skill, config_key, region, old_value, new_value}。
"""
log.info("config_update key=%s region=%s value=%s", config_key, region, config_value)
conn = get_conn()
try:
cur = conn.cursor()
cur.execute(
"SELECT config_value FROM payroll_config WHERE config_key=? AND region=?",
(config_key, region),
)
row = cur.fetchone()
if row is None:
return {
"ok": False,
"skill": "query-payslip-default",
"error_code": "CONFIG_NOT_FOUND",
"error": f"配置项 {config_key}(地区 {region})不存在",
}
old_value = row[0]
cur.execute(
"""
UPDATE payroll_config
SET config_value=?, updated_at=strftime('%s','now')
WHERE config_key=? AND region=?
""",
(config_value, config_key, region),
)
conn.commit()
return {
"ok": True,
"skill": "query-payslip-default",
"config_key": config_key,
"region": region,
"old_value": old_value,
"new_value": config_value,
}
finally:
conn.close()

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,95 @@
"""名词解释服务。
从 assets/glossary.json 读取词条,按 key/display/category 查询。
不做 LLM 生成,纯静态数据查询。
"""
from __future__ import annotations
import json
from typing import Any, Optional
from util.constants import SKILL_SLUG
from util.logging_config import get_skill_logger
from util.runtime_paths import get_skill_root
log = get_skill_logger()
def _load_glossary() -> list[dict[str, Any]]:
"""从 assets/glossary.json 加载全部词条。"""
glossary_path = get_skill_root() / "assets" / "glossary.json"
try:
with open(glossary_path, "r", encoding="utf-8") as f:
data = json.load(f)
terms = data.get("terms", []) if isinstance(data, dict) else []
return terms if isinstance(terms, list) else []
except (FileNotFoundError, json.JSONDecodeError, OSError):
return []
def explain_term(term: str) -> dict[str, Any]:
"""查询单个名词解释。
支持按 key(精确)或 display(包含)匹配。
未命中返回结构化空(ok=True, found=False)。
"""
log.info("glossary_explain term=%s", term)
terms = _load_glossary()
term_lower = (term or "").strip().lower()
hit: Optional[dict[str, Any]] = None
for t in terms:
if str(t.get("key", "")).lower() == term_lower:
hit = t
break
if term_lower in str(t.get("display", "")).lower():
hit = t
break
if hit is None:
return {
"ok": True,
"skill": SKILL_SLUG,
"found": False,
"term": term,
"explanation": None,
"suggestions": [str(t.get("display", "")) for t in terms[:5]],
}
return {
"ok": True,
"skill": SKILL_SLUG,
"found": True,
"term": term,
"key": hit.get("key"),
"display": hit.get("display"),
"category": hit.get("category"),
"explanation": hit.get("explanation"),
"example": hit.get("example"),
}
def list_terms(category: str | None = None) -> dict[str, Any]:
"""列出全部或按分类的词条。"""
terms = _load_glossary()
if category:
filtered = [t for t in terms if str(t.get("category", "")).lower() == category.lower()]
else:
filtered = terms
return {
"ok": True,
"skill": SKILL_SLUG,
"count": len(filtered),
"categories": sorted({str(t.get("category", "")) for t in terms}),
"terms": [
{
"key": t.get("key"),
"display": t.get("display"),
"category": t.get("category"),
"explanation": t.get("explanation"),
"example": t.get("example"),
}
for t in filtered
],
}

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,328 @@
"""工资条核算引擎(唯一业务内核)。
职责:
- 接收结构化字段(应发项、扣除项、period、自报实发)
- 确定性核算:应发合计 / 扣除合计 / 实发 / 核对差异
- 缺扣除项时按费率估算(社保/公积金/个税累计预扣)
- 落库到 payslip_snapshots(含完整明细 JSON)
不做:LLM 文本解析、自然语言生成。
"""
from __future__ import annotations
import json
import time
from typing import Any, Optional
from db.connection import get_conn, init_db
from service.config_service import get_config_value
from service.tax_service import compute_cumulative_tax
from util.constants import SKILL_SLUG
from util.logging_config import get_skill_logger
def _clamp_base(base: float, lower: float, upper: float) -> float:
"""按上下限裁剪缴费基数。"""
if base < lower:
return lower
if base > upper:
return upper
return base
def _estimate_social(base_salary: float, region: str = "default") -> dict[str, Any]:
"""按费率估算社保个人部分。"""
pension_rate = float(get_config_value("social_pension_rate", region) or 0.08)
medical_rate = float(get_config_value("social_medical_rate", region) or 0.02)
unemploy_rate = float(get_config_value("social_unemployment_rate", region) or 0.005)
base_min = float(get_config_value("social_base_min", region) or 5000)
base_max = float(get_config_value("social_base_max", region) or 30000)
base = _clamp_base(base_salary, base_min, base_max)
pension = round(base * pension_rate, 2)
medical = round(base * medical_rate, 2)
unemployment = round(base * unemploy_rate, 2)
personal_total = round(pension + medical + unemployment, 2)
return {
"base_used": round(base, 2),
"pension": pension,
"medical": medical,
"unemployment": unemployment,
"personal_total": personal_total,
"estimated": True,
}
def _estimate_housing_fund(base_salary: float, region: str = "default") -> dict[str, Any]:
"""按费率估算公积金个人部分。"""
rate = float(get_config_value("housing_fund_rate", region) or 0.07)
base_min = float(get_config_value("housing_fund_base_min", region) or 2500)
base_max = float(get_config_value("housing_fund_base_max", region) or 30000)
base = _clamp_base(base_salary, base_min, base_max)
personal = round(base * rate, 2)
return {
"base_used": round(base, 2),
"personal_rate": rate,
"personal": personal,
"estimated": True,
}
def calculate_payslip(
*,
base_salary: float = 0.0,
performance: float = 0.0,
full_attendance: float = 0.0,
meal_allowance: float = 0.0,
transport_allowance: float = 0.0,
overtime_pay: float = 0.0,
other_gross: float = 0.0,
# 扣除项(可选,None 表示缺值→估算)
social_personal: Optional[float] = None,
housing_fund_personal: Optional[float] = None,
tax: Optional[float] = None,
leave_deduction: float = 0.0,
other_deduction: float = 0.0,
period: str = "",
reported_net: Optional[float] = None,
raw_payload: str = "",
region: str = "default",
) -> dict[str, Any]:
"""工资条核算入口。
缺扣除项时按费率估算;估算项标 estimated=True,note 附"仅供参考"。
落库到 payslip_snapshots,返回结构化 JSON。
"""
log = get_skill_logger()
log.info(
"payslip_calculate_start period=%s base=%s reported_net=%s region=%s",
period, base_salary, reported_net, region,
)
# 确保 DB 已初始化(agent/CLI 都可能首次调用)
init_db()
# 应发合计
bonus_total = round(performance + full_attendance, 2)
allowance_total = round(meal_allowance + transport_allowance, 2)
gross_total = round(
base_salary + performance + full_attendance
+ meal_allowance + transport_allowance + overtime_pay + other_gross,
2,
)
# 扣除项:缺失则估算
estimated = False
social_detail: dict[str, Any]
if social_personal is None:
social_detail = _estimate_social(base_salary, region)
estimated = True
else:
social_detail = {"personal_total": round(float(social_personal), 2), "estimated": False}
housing_detail: dict[str, Any]
if housing_fund_personal is None:
housing_detail = _estimate_housing_fund(base_salary, region)
estimated = True
else:
housing_detail = {"personal": round(float(housing_fund_personal), 2), "estimated": False}
# 个税:缺失则按累计预扣估算
tax_detail: dict[str, Any]
if tax is None:
social_for_tax = float(social_detail.get("personal_total", 0))
housing_for_tax = float(housing_detail.get("personal", 0))
tax_result = compute_cumulative_tax(
current_gross=gross_total,
period=period or "1970-01",
current_social=social_for_tax,
current_housing_fund=housing_for_tax,
region=region,
)
tax_detail = {
"actual": tax_result["actual_tax"],
"cumulative_taxable": tax_result["cumulative_taxable"],
"brackets_used": tax_result["brackets_used"],
"has_history": tax_result["has_history"],
"estimated": True,
"note": tax_result["note"],
}
estimated = True
else:
tax_detail = {"actual": round(float(tax), 2), "estimated": False}
social_total = float(social_detail.get("personal_total", 0))
housing_total = float(housing_detail.get("personal", 0))
tax_total = float(tax_detail.get("actual", 0))
leave_total = float(leave_deduction)
other_ded_total = float(other_deduction)
deduction_total = round(
social_total + housing_total + tax_total + leave_total + other_ded_total, 2
)
net_salary = round(gross_total - deduction_total, 2)
# 核对
check: dict[str, Any] = {"reported": None, "calculated": net_salary, "match": None, "diff": None}
if reported_net is not None:
reported_net = round(float(reported_net), 2)
diff = round(reported_net - net_salary, 2)
check = {
"reported": reported_net,
"calculated": net_salary,
"match": abs(diff) < 0.01,
"diff": diff,
}
# 完整明细(供历史查询与个税累计)
detail = {
"gross": {
"base_salary": base_salary,
"performance": performance,
"full_attendance": full_attendance,
"meal_allowance": meal_allowance,
"transport_allowance": transport_allowance,
"overtime_pay": overtime_pay,
"other_gross": other_gross,
"bonus_total": bonus_total,
"allowance_total": allowance_total,
"total": gross_total,
},
"deduction": {
"social": social_detail,
"housing_fund": housing_detail,
"tax": tax_detail,
"leave": leave_total,
"other": other_ded_total,
"total": deduction_total,
},
"net": net_salary,
"check": check,
"region": region,
}
estimates = []
if estimated:
notes = []
if social_detail.get("estimated"):
estimates.append({"item": "社保个人", "value": social_total, "note": "按费率估算,仅供参考"})
if housing_detail.get("estimated"):
estimates.append({"item": "公积金个人", "value": housing_total, "note": "按费率估算,仅供参考"})
if tax_detail.get("estimated"):
estimates.append({"item": "个税", "value": tax_total, "note": tax_detail.get("note", "仅供参考")})
if not estimates:
notes.append("所有扣除项均已由用户给定,无估算")
else:
estimates.append({"item": "无估算", "value": 0, "note": "所有扣除项均由用户给定"})
# 落库
snapshot_date = int(time.time())
conn = get_conn()
snapshot_id = None
try:
cur = conn.cursor()
cur.execute(
"""
INSERT INTO payslip_snapshots (
snapshot_date, period, base_salary,
gross_total, deduction_total, net_salary,
reported_net, check_match, check_diff,
detail_json, raw_payload
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
snapshot_date, period or None, base_salary,
gross_total, deduction_total, net_salary,
reported_net,
int(check["match"]) if check["match"] is not None else None,
check["diff"],
json.dumps(detail, ensure_ascii=False),
raw_payload or None,
),
)
snapshot_id = cur.lastrowid
conn.commit()
finally:
conn.close()
log.info(
"payslip_calculate_done period=%s gross=%s deduction=%s net=%s match=%s snapshot_id=%s",
period, gross_total, deduction_total, net_salary, check["match"], snapshot_id,
)
return {
"ok": True,
"skill": SKILL_SLUG,
"period": period,
"gross": detail["gross"],
"deduction": detail["deduction"],
"net": net_salary,
"check": check,
"estimates": estimates,
"snapshot_id": snapshot_id,
}
def calculate_payslip_simple(
*,
base_salary: float,
period: str,
reported_net: Optional[float] = None,
region: str = "default",
) -> dict[str, Any]:
"""快速估算:仅基本工资+period,按费率估全部扣除项。"""
return calculate_payslip(
base_salary=base_salary,
period=period,
reported_net=reported_net,
region=region,
)
def list_snapshots(period: str | None = None, limit: int = 50) -> list[dict[str, Any]]:
"""列出解析历史(供数据管理 / CLI 查看)。"""
conn = get_conn()
try:
cur = conn.cursor()
if period:
cur.execute(
"""
SELECT id, snapshot_date, period, base_salary, gross_total,
deduction_total, net_salary, reported_net, check_match, check_diff
FROM payslip_snapshots WHERE period=?
ORDER BY snapshot_date DESC LIMIT ?
""",
(period, limit),
)
else:
cur.execute(
"""
SELECT id, snapshot_date, period, base_salary, gross_total,
deduction_total, net_salary, reported_net, check_match, check_diff
FROM payslip_snapshots
ORDER BY snapshot_date DESC LIMIT ?
""",
(limit,),
)
rows = cur.fetchall()
return [
{
"id": r[0],
"snapshot_date": r[1],
"period": r[2],
"base_salary": r[3],
"gross_total": r[4],
"deduction_total": r[5],
"net_salary": r[6],
"reported_net": r[7],
"check_match": r[8],
"check_diff": r[9],
}
for r in rows
]
finally:
conn.close()

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

View 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', '')}"
)

View File

@@ -0,0 +1,387 @@
"""任务编排模板。
编排层:job_context / emit / checkpoint / finish、鉴权与错误转换。
过程看统一文件日志;进度/终态看任务中心;业务结果写入业务表(有才建)。
领域业务请放在 ``service/<domain>_service.py``,由本模块调用;多入口(CLI/Action/cron)复用同一内核。
复制后在 cmd_run(或 cmd_sync_*)中接线到真实 domain service,勿按 toolbar/cron/agent 分叉业务。
"""
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_data_dir, get_skill_root
from db.connection import init_db
def _get_task_logger():
try:
return get_skill_logger()
except RuntimeError:
setup_skill_logging(SKILL_SLUG, LOG_LOGGER_NAME)
return get_skill_logger()
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_data_dir()
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:
"""通用任务执行入口模板。复制后请实现真实业务逻辑。"""
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 这是模板仓库,请复制后在 scripts/service/task_service.py 中实现 cmd_run 的真实业务逻辑。")
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.dumps(
{
"skill": SKILL_SLUG,
"env_path": env_path,
"example_path": os.path.abspath(example_path),
},
ensure_ascii=False,
)
)
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.dumps({"version": SKILL_VERSION, "skill": SKILL_SLUG}, ensure_ascii=False))
return 0
def cmd_init_db() -> int:
"""幂等创建/迁移本地 SQLite 与数据管理元数据(宿主 install/upgrade 可调用)。"""
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.dumps(
{
"ok": True,
"skill": SKILL_SLUG,
"db_path": get_db_path(),
},
ensure_ascii=False,
)
)
return 0
def _parse_float_or_none(value: Optional[str]) -> Optional[float]:
if value is None or value == "":
return None
try:
return float(value)
except ValueError:
return None
def cmd_calculate_full(
*,
base_salary: float = 0.0,
performance: float = 0.0,
full_attendance: float = 0.0,
meal_allowance: float = 0.0,
transport_allowance: float = 0.0,
overtime_pay: float = 0.0,
other_gross: float = 0.0,
social_personal: Optional[float] = None,
housing_fund_personal: Optional[float] = None,
tax: Optional[float] = None,
leave_deduction: float = 0.0,
other_deduction: float = 0.0,
period: str = "",
reported_net: Optional[float] = None,
raw_payload: str = "",
region: str = "default",
) -> int:
"""精确核算:全字段核算,缺失项按费率估算。"""
log = _get_task_logger()
from service.payslip_service import calculate_payslip
with job_context(skill=SKILL_SLUG):
log.info("task_start task_type=calculate_full period=%s region=%s", period, region)
emit("开始核算工资", skill=SKILL_SLUG, stage="calculate")
try:
ok, reason = check_entitlement(SKILL_SLUG)
if not ok:
log.warning("entitlement_failed task_type=calculate_full")
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
return 1
result = calculate_payslip(
base_salary=base_salary, performance=performance, full_attendance=full_attendance,
meal_allowance=meal_allowance, transport_allowance=transport_allowance,
overtime_pay=overtime_pay, other_gross=other_gross,
social_personal=social_personal, housing_fund_personal=housing_fund_personal,
tax=tax, leave_deduction=leave_deduction, other_deduction=other_deduction,
period=period, reported_net=reported_net, raw_payload=raw_payload, region=region,
)
print(json.dumps(result, ensure_ascii=False))
finish(
status="success",
message=f"应发 {result['gross']['total']},扣除 {result['deduction']['total']},实发 {result['net']}",
skill=SKILL_SLUG, stage="calculate",
)
return 0
except JobStopped:
raise
except Exception:
log.exception("task_failed task_type=calculate_full")
emit("核算失败", type="warn", skill=SKILL_SLUG, stage="calculate")
finish(status="failed", message="核算执行异常", skill=SKILL_SLUG, stage="calculate")
return 1
def cmd_calculate_simple(
*,
base_salary: float,
period: str,
reported_net: Optional[float] = None,
region: str = "default",
) -> int:
"""快速估算:仅基本工资+period,按费率估全部扣除。"""
log = _get_task_logger()
from service.payslip_service import calculate_payslip_simple
with job_context(skill=SKILL_SLUG):
log.info("task_start task_type=calculate_simple period=%s base=%s", period, base_salary)
emit("开始估算工资", skill=SKILL_SLUG, stage="calculate_simple")
try:
ok, reason = check_entitlement(SKILL_SLUG)
if not ok:
log.warning("entitlement_failed task_type=calculate_simple")
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
return 1
result = calculate_payslip_simple(
base_salary=base_salary, period=period, reported_net=reported_net, region=region,
)
print(json.dumps(result, ensure_ascii=False))
finish(
status="success",
message=f"估算实发 {result['net']}(仅供参考)",
skill=SKILL_SLUG, stage="calculate_simple",
)
return 0
except JobStopped:
raise
except Exception:
log.exception("task_failed task_type=calculate_simple")
emit("估算失败", type="warn", skill=SKILL_SLUG, stage="calculate_simple")
finish(status="failed", message="估算执行异常", skill=SKILL_SLUG, stage="calculate_simple")
return 1
def cmd_explain(term: str) -> int:
"""名词解释。"""
log = _get_task_logger()
from service.glossary_service import explain_term
with job_context(skill=SKILL_SLUG):
log.info("task_start task_type=explain term=%s", term)
try:
result = explain_term(term)
print(json.dumps(result, ensure_ascii=False))
return 0
except Exception:
log.exception("task_failed task_type=explain")
return 1
def cmd_view_config(region: Optional[str] = None) -> int:
"""查看费率配置。"""
log = _get_task_logger()
from service.config_service import list_all_config
with job_context(skill=SKILL_SLUG):
log.info("task_start task_type=view_config region=%s", region)
try:
result = list_all_config(region)
print(json.dumps({"ok": True, "skill": SKILL_SLUG, "count": len(result), "items": result}, ensure_ascii=False))
return 0
except Exception:
log.exception("task_failed task_type=view_config")
return 1
def cmd_edit_config(config_key: str, region: str, config_value: float) -> int:
"""编辑费率配置(仅管理员)。"""
log = _get_task_logger()
from service.config_service import update_config_value
with job_context(skill=SKILL_SLUG):
log.info("task_start task_type=edit_config key=%s region=%s", config_key, region)
emit("开始更新费率", skill=SKILL_SLUG, stage="edit_config")
try:
ok, reason = check_entitlement(SKILL_SLUG)
if not ok:
log.warning("entitlement_failed task_type=edit_config")
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
return 1
result = update_config_value(config_key, region, config_value)
print(json.dumps(result, ensure_ascii=False))
if result.get("ok"):
finish(status="success", message=f"已更新 {config_key}", skill=SKILL_SLUG, stage="edit_config")
return 0
else:
finish(status="failed", message=result.get("error", ""), skill=SKILL_SLUG, stage="edit_config")
return 1
except JobStopped:
raise
except Exception:
log.exception("task_failed task_type=edit_config")
finish(status="failed", message="更新执行异常", skill=SKILL_SLUG, stage="edit_config")
return 1

View File

@@ -0,0 +1,161 @@
"""个税累计预扣计算服务。
按"累计预扣法"计算当月个税:
累计预扣预缴应纳税所得额 = 累计收入 - 累计减除费用 - 累计专项扣除 - 累计专项附加扣除 - 累计依法确定的其他扣除
当月应预扣预缴税额 = (累计预扣预缴应纳税所得额 × 预扣率 - 速算扣除数) - 已预扣预缴税额
简化假设:
- 专项附加扣除与其他扣除暂不计入(数据不可得)
- 累计减除费用 = 5000 × 当年至本月份数
- 累计专项扣除 = 累计社保+公积金个人部分(从历史 snapshots 读取)
"""
from __future__ import annotations
import time
from typing import Any
from service.config_service import get_config_value, get_tax_brackets
from db.connection import get_conn
from util.logging_config import get_skill_logger
log = get_skill_logger()
def _month_index(period: str) -> int:
"""从 'YYYY-MM' 提取月份数(1-12)。"""
try:
return int(period.split("-")[1])
except (ValueError, IndexError):
return 1
def _year_of_period(period: str) -> str:
"""从 'YYYY-MM' 提取年份。"""
try:
return period.split("-")[0]
except (ValueError, IndexError):
return "1970"
def get_cumulative_deduction_before(period: str) -> dict[str, float]:
"""读取同一年的历史 snapshots,累计社保/公积金个人部分。
period 之前的同一年 snapshots(按 period 字符串排序 < 当前 period)。
返回 {social_cum, housing_fund_cum, tax_cum}。
"""
year = _year_of_period(period)
conn = get_conn()
try:
cur = conn.cursor()
cur.execute(
"""
SELECT detail_json FROM payslip_snapshots
WHERE period LIKE ? AND period < ?
ORDER BY period ASC
""",
(f"{year}-%", period),
)
import json
social_cum = 0.0
housing_fund_cum = 0.0
tax_cum = 0.0
for (detail_str,) in cur.fetchall():
if not detail_str:
continue
try:
detail = json.loads(detail_str)
except (json.JSONDecodeError, TypeError):
continue
ded = detail.get("deduction", {}) if isinstance(detail, dict) else {}
social_cum += float(ded.get("social", {}).get("personal_total", 0) or 0)
housing_fund_cum += float(ded.get("housing_fund", {}).get("personal", 0) or 0)
tax_cum += float(ded.get("tax", {}).get("actual", 0) or 0)
return {"social_cum": social_cum, "housing_fund_cum": housing_fund_cum, "tax_cum": tax_cum}
finally:
conn.close()
def compute_cumulative_tax(
*,
current_gross: float,
period: str,
current_social: float,
current_housing_fund: float,
region: str = "default",
) -> dict[str, Any]:
"""按累计预扣法计算当月个税。
返回 {
actual_tax: float, # 本次应预扣个税
cumulative_income: float,
cumulative_deduction: float,
cumulative_taxable: float,
cumulative_tax: float, # 累计应预扣
prior_tax_paid: float, # 之前已预扣
brackets_used: dict, # 命中的税率档
has_history: bool, # 是否有历史累计数据
note: str,
}
"""
log.info(
"tax_compute_start period=%s gross=%s social=%s housing=%s region=%s",
period, current_gross, current_social, current_housing_fund, region,
)
threshold = get_config_value("tax_threshold", region) or 5000
brackets = get_tax_brackets(region)
month_idx = _month_index(period)
cumulative_threshold = float(threshold) * month_idx
prior = get_cumulative_deduction_before(period)
has_history = prior["social_cum"] > 0 or prior["tax_cum"] > 0
cumulative_income = current_gross + prior.get("income_cum", 0.0) if has_history else current_gross
# 简化:累计专项扣除 = 累计社保+公积金个人
cumulative_special_deduction = (
prior["social_cum"] + prior["housing_fund_cum"]
+ current_social + current_housing_fund
)
cumulative_taxable = cumulative_income - cumulative_threshold - cumulative_special_deduction
if cumulative_taxable < 0:
cumulative_taxable = 0.0
cumulative_tax = 0.0
bracket_hit = None
if brackets and cumulative_taxable > 0:
for bracket in brackets:
upper = bracket.get("upper")
rate = float(bracket.get("rate", 0))
quick = float(bracket.get("quick_deduction", 0))
if upper is None or cumulative_taxable <= float(upper):
cumulative_tax = cumulative_taxable * rate - quick
bracket_hit = bracket
break
if bracket_hit is None and brackets:
bracket_hit = brackets[-1]
rate = float(bracket_hit.get("rate", 0))
quick = float(bracket_hit.get("quick_deduction", 0))
cumulative_tax = cumulative_taxable * rate - quick
cumulative_tax = max(0.0, cumulative_tax)
prior_tax_paid = prior["tax_cum"] if has_history else 0.0
actual_tax = max(0.0, cumulative_tax - prior_tax_paid)
note = "仅供参考,非官方数据"
if not has_history:
note = "仅供参考(无累计历史数据,累计按本月单月计算),非官方数据"
return {
"actual_tax": round(actual_tax, 2),
"cumulative_income": round(cumulative_income, 2),
"cumulative_threshold": round(cumulative_threshold, 2),
"cumulative_special_deduction": round(cumulative_special_deduction, 2),
"cumulative_taxable": round(cumulative_taxable, 2),
"cumulative_tax": round(cumulative_tax, 2),
"prior_tax_paid": round(prior_tax_paid, 2),
"brackets_used": bracket_hit,
"has_history": has_history,
"note": note,
}