"""任务编排模板。 编排层:job_context / emit / checkpoint / finish、鉴权与错误转换。 过程看统一文件日志;进度/终态看任务中心;业务结果写入业务表(有才建)。 领域业务请放在 ``service/_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