feat: 初始化高校人事请假考勤技能 (process-leave-attendance-default)
All checks were successful
技能自动化发布 / release (push) Successful in 15s
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:
137
scripts/cli/app.py
Normal file
137
scripts/cli/app.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""CLI:高校人事请假考勤命令分发。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from typing import List, Optional
|
||||
|
||||
from service.task_service import (
|
||||
cmd_calculate_leave,
|
||||
cmd_config_path,
|
||||
cmd_health,
|
||||
cmd_import_employees,
|
||||
cmd_init_db,
|
||||
cmd_render_html,
|
||||
cmd_run,
|
||||
cmd_version,
|
||||
)
|
||||
from util.argparse_zh import ZhArgumentParser
|
||||
from util.config_bootstrap import bootstrap_skill_config
|
||||
from util.constants import LOG_LOGGER_NAME, SKILL_SLUG
|
||||
from util.logging_config import get_skill_logger, setup_skill_logging
|
||||
|
||||
|
||||
def _cli_str_or_none(raw: Optional[str]) -> Optional[str]:
|
||||
if raw is None:
|
||||
return None
|
||||
v = str(raw).strip()
|
||||
return v or None
|
||||
|
||||
|
||||
def _handle_run(args: argparse.Namespace) -> int:
|
||||
tail = [str(x).strip() for x in (args.run_tail or []) if str(x).strip()]
|
||||
if len(tail) > 2:
|
||||
print("参数过多。")
|
||||
print("用法:python main.py run [target [input_id]] | run [-t target] [-i input_id]")
|
||||
return 1
|
||||
|
||||
t_target: Optional[str] = None
|
||||
t_input: Optional[str] = None
|
||||
if len(tail) == 2:
|
||||
t_target, t_input = tail[0], tail[1]
|
||||
elif len(tail) == 1:
|
||||
if tail[0].isdigit():
|
||||
t_input = tail[0]
|
||||
else:
|
||||
t_target = tail[0]
|
||||
|
||||
pick_t = _cli_str_or_none(getattr(args, "target", None))
|
||||
pick_i = _cli_str_or_none(getattr(args, "input_id", None))
|
||||
target = pick_t or t_target
|
||||
input_id = pick_i or t_input
|
||||
return cmd_run(target=target, input_id=input_id)
|
||||
|
||||
|
||||
def build_parser() -> ZhArgumentParser:
|
||||
p = ZhArgumentParser(
|
||||
prog="main.py",
|
||||
description="高校人事请假考勤:导入教职工、请假核算、审批与扣薪报告。",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
)
|
||||
sub = p.add_subparsers(dest="cmd", required=True, parser_class=ZhArgumentParser)
|
||||
|
||||
sp = sub.add_parser("run", help="兼容入口(需 calculate-leave 子命令)")
|
||||
sp.add_argument("--target", "-t", default=None, metavar="教职工id")
|
||||
sp.add_argument("--input-id", "-i", default=None, metavar="教职工id", dest="input_id")
|
||||
sp.add_argument("run_tail", nargs="*", metavar="位置参数")
|
||||
sp.set_defaults(handler=_handle_run)
|
||||
|
||||
sp = sub.add_parser("import-employees", help="从输入目录导入教职工 JSON")
|
||||
sp.add_argument("--file", "-f", default=None, metavar="JSON文件")
|
||||
sp.set_defaults(handler=lambda a: cmd_import_employees(file_path=a.file))
|
||||
|
||||
sp = sub.add_parser("calculate-leave", help="核算请假扣薪与审批层级")
|
||||
sp.add_argument("--employee-id", "-e", required=True, dest="employee_id")
|
||||
sp.add_argument("--leave-type", required=True, dest="leave_type")
|
||||
sp.add_argument("--start-date", required=True, dest="start_date")
|
||||
sp.add_argument("--end-date", required=True, dest="end_date")
|
||||
sp.add_argument("--has-certificate", default=None, dest="has_certificate")
|
||||
sp.add_argument("--certificate-type", default=None, dest="certificate_type")
|
||||
sp.set_defaults(
|
||||
handler=lambda a: cmd_calculate_leave(
|
||||
employee_id=a.employee_id,
|
||||
leave_type=a.leave_type,
|
||||
start_date=a.start_date,
|
||||
end_date=a.end_date,
|
||||
has_certificate=a.has_certificate,
|
||||
certificate_type=a.certificate_type,
|
||||
)
|
||||
)
|
||||
|
||||
sp = sub.add_parser("render-html", help="生成请假审批与扣薪 HTML 报告")
|
||||
sp.add_argument("--request-id", "-r", default=None, dest="request_id")
|
||||
sp.set_defaults(handler=lambda a: cmd_render_html(request_id=a.request_id))
|
||||
|
||||
sp = sub.add_parser("health", help="健康检查")
|
||||
sp.set_defaults(handler=lambda _a: cmd_health())
|
||||
|
||||
sp = sub.add_parser("config-path", help="输出配置与数据路径")
|
||||
sp.set_defaults(handler=lambda _a: cmd_config_path())
|
||||
|
||||
sp = sub.add_parser("version", help="版本信息")
|
||||
sp.set_defaults(handler=lambda _a: cmd_version())
|
||||
|
||||
sp = sub.add_parser("init-db", help="初始化数据库并同步示例数据")
|
||||
sp.set_defaults(handler=lambda _a: cmd_init_db())
|
||||
return p
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
argv = argv if argv is not None else sys.argv[1:]
|
||||
bootstrap_skill_config()
|
||||
setup_skill_logging(SKILL_SLUG, LOG_LOGGER_NAME)
|
||||
get_skill_logger().info("cli_start argv=%s", sys.argv)
|
||||
if not argv:
|
||||
print(
|
||||
"高校人事请假考勤 — 用法:python main.py import-employees | calculate-leave | "
|
||||
"render-html | health | version | init-db"
|
||||
)
|
||||
return 1
|
||||
short = {
|
||||
"run",
|
||||
"import-employees",
|
||||
"calculate-leave",
|
||||
"render-html",
|
||||
"health",
|
||||
"config-path",
|
||||
"version",
|
||||
"init-db",
|
||||
"-h",
|
||||
"--help",
|
||||
}
|
||||
if len(argv) == 2 and argv[0] not in short:
|
||||
return cmd_run(target=argv[0], input_id=argv[1])
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
return int(args.handler(args))
|
||||
54
scripts/db/connection.py
Normal file
54
scripts/db/connection.py
Normal file
@@ -0,0 +1,54 @@
|
||||
"""SQLite 连接与请假考勤业务表幂等初始化。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
|
||||
from db.display_metadata import init_display_metadata
|
||||
from db.leave_display_metadata import seed_leave_display_metadata
|
||||
from db.schema import BUSINESS_TABLES, TABLE_DDL
|
||||
from db.timestamp_columns import init_updated_at_trigger
|
||||
from util.runtime_paths import get_db_path
|
||||
|
||||
|
||||
def get_conn() -> sqlite3.Connection:
|
||||
return sqlite3.connect(get_db_path())
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for table_name, ddl in TABLE_DDL:
|
||||
cur.execute(ddl)
|
||||
init_updated_at_trigger(cur, table_name)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_leave_requests_employee
|
||||
ON leave_requests(employee_id, status)
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_leave_balances_employee
|
||||
ON leave_balances(employee_id, balance_type)
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_leave_policies_type
|
||||
ON leave_policies(leave_type)
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_attendance_holidays_date
|
||||
ON attendance_holidays(holiday_date)
|
||||
"""
|
||||
)
|
||||
init_display_metadata(cur)
|
||||
seed_leave_display_metadata(cur)
|
||||
_ = BUSINESS_TABLES
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
324
scripts/db/display_metadata.py
Normal file
324
scripts/db/display_metadata.py
Normal file
@@ -0,0 +1,324 @@
|
||||
"""匠厂数据管理展示元数据(_jiangchang_tables / _jiangchang_columns)。
|
||||
|
||||
SQLite 无原生表/字段 COMMENT;中文展示名称通过这两张元数据表提供给宿主「数据管理」页面。
|
||||
字段在界面上的顺序由 CREATE TABLE / PRAGMA table_info(cid) 决定,**不**使用 display_order 排序。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Iterable
|
||||
|
||||
# 宿主会隐藏这些表,不作为业务表展示(见 jiangchang electron/data-management/types.ts)
|
||||
INTERNAL_METADATA_TABLES = frozenset({"_jiangchang_tables", "_jiangchang_columns"})
|
||||
LEGACY_METADATA_TABLES = frozenset({"_schema_meta"})
|
||||
METADATA_TABLES = INTERNAL_METADATA_TABLES | LEGACY_METADATA_TABLES
|
||||
|
||||
DATETIME_UNIX_SECONDS = "datetime_unix_seconds"
|
||||
STANDARD_TIMESTAMP_COLUMNS = frozenset({"created_at", "updated_at"})
|
||||
|
||||
_JIANGCHANG_TABLES_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS _jiangchang_tables (
|
||||
table_name TEXT PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
grid_help TEXT,
|
||||
sort_order INTEGER,
|
||||
visible INTEGER NOT NULL DEFAULT 1,
|
||||
readonly INTEGER NOT NULL DEFAULT 0,
|
||||
default_sort_json TEXT,
|
||||
default_visible_columns_json TEXT
|
||||
)
|
||||
"""
|
||||
|
||||
_JIANGCHANG_COLUMNS_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS _jiangchang_columns (
|
||||
table_name TEXT NOT NULL,
|
||||
column_name TEXT NOT NULL,
|
||||
display_name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
grid_help TEXT,
|
||||
display_order INTEGER,
|
||||
visible INTEGER NOT NULL DEFAULT 1,
|
||||
searchable INTEGER NOT NULL DEFAULT 1,
|
||||
editable INTEGER NOT NULL DEFAULT 1,
|
||||
display_type TEXT,
|
||||
options_json TEXT,
|
||||
PRIMARY KEY (table_name, column_name)
|
||||
)
|
||||
"""
|
||||
|
||||
def _pragma_column_names(cursor, table_name: str) -> set[str]:
|
||||
cursor.execute(f"PRAGMA table_info({table_name!r})")
|
||||
return {str(row[1]) for row in cursor.fetchall()}
|
||||
|
||||
|
||||
def _ensure_jiangchang_tables_columns(cursor) -> None:
|
||||
"""旧库补列:CREATE IF NOT EXISTS 不会给已有表加新字段。"""
|
||||
cols = _pragma_column_names(cursor, "_jiangchang_tables")
|
||||
if "default_sort_json" not in cols:
|
||||
cursor.execute("ALTER TABLE _jiangchang_tables ADD COLUMN default_sort_json TEXT")
|
||||
if "default_visible_columns_json" not in cols:
|
||||
cursor.execute(
|
||||
"ALTER TABLE _jiangchang_tables ADD COLUMN default_visible_columns_json TEXT"
|
||||
)
|
||||
if "grid_help" not in cols:
|
||||
cursor.execute("ALTER TABLE _jiangchang_tables ADD COLUMN grid_help TEXT")
|
||||
|
||||
|
||||
def _ensure_jiangchang_columns_columns(cursor) -> None:
|
||||
cols = _pragma_column_names(cursor, "_jiangchang_columns")
|
||||
if "grid_help" not in cols:
|
||||
cursor.execute("ALTER TABLE _jiangchang_columns ADD COLUMN grid_help TEXT")
|
||||
|
||||
|
||||
def init_display_metadata_tables(cursor) -> None:
|
||||
cursor.execute(_JIANGCHANG_TABLES_DDL)
|
||||
cursor.execute(_JIANGCHANG_COLUMNS_DDL)
|
||||
_ensure_jiangchang_tables_columns(cursor)
|
||||
_ensure_jiangchang_columns_columns(cursor)
|
||||
|
||||
|
||||
def upsert_table_metadata(
|
||||
cursor,
|
||||
*,
|
||||
table_name: str,
|
||||
display_name: str,
|
||||
description: str | None = None,
|
||||
grid_help: str | None = None,
|
||||
visible: int = 1,
|
||||
readonly: int = 0,
|
||||
default_sort_json: str | None = None,
|
||||
default_visible_columns_json: str | None = None,
|
||||
) -> None:
|
||||
"""写入表级元数据。
|
||||
|
||||
default_sort_json: 宿主数据管理默认排序,JSON 数组,例如
|
||||
'[{"column":"sent_at","direction":"desc"},{"column":"id","direction":"desc"}]'
|
||||
为空则宿主回退到 updated_at → created_at → 主键。
|
||||
|
||||
default_visible_columns_json: 宿主数据管理默认展示列,JSON 字符串数组,例如
|
||||
'["stat_type","period","stage"]'
|
||||
为空则全显;用户改过「列」后以本机偏好为准(软默认,区别于 visible=0 硬隐藏)。
|
||||
|
||||
grid_help: 数据管理表格上方说明;空则不出横幅。与表单用的 description 独立,禁止互拷。
|
||||
"""
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO _jiangchang_tables (
|
||||
table_name, display_name, description, grid_help, visible, readonly,
|
||||
default_sort_json, default_visible_columns_json
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(table_name) DO UPDATE SET
|
||||
display_name = excluded.display_name,
|
||||
description = excluded.description,
|
||||
grid_help = excluded.grid_help,
|
||||
visible = excluded.visible,
|
||||
readonly = excluded.readonly,
|
||||
default_sort_json = excluded.default_sort_json,
|
||||
default_visible_columns_json = excluded.default_visible_columns_json
|
||||
""",
|
||||
(
|
||||
table_name,
|
||||
display_name,
|
||||
description,
|
||||
grid_help,
|
||||
visible,
|
||||
readonly,
|
||||
default_sort_json,
|
||||
default_visible_columns_json,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def upsert_column_metadata(
|
||||
cursor,
|
||||
*,
|
||||
table_name: str,
|
||||
column_name: str,
|
||||
display_name: str,
|
||||
description: str | None = None,
|
||||
grid_help: str | None = None,
|
||||
visible: int = 1,
|
||||
searchable: int = 1,
|
||||
editable: int = 1,
|
||||
display_type: str | None = None,
|
||||
options_json: str | None = None,
|
||||
) -> None:
|
||||
# display_order 保留为 NULL:宿主按 PRAGMA table_info cid 展示字段,不读 display_order。
|
||||
# grid_help: 表头「?」;空则不出。与表单用的 description 独立,禁止互拷。
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO _jiangchang_columns (
|
||||
table_name, column_name, display_name, description, grid_help,
|
||||
display_order, visible, searchable, editable, display_type, options_json
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(table_name, column_name) DO UPDATE SET
|
||||
display_name = excluded.display_name,
|
||||
description = excluded.description,
|
||||
grid_help = excluded.grid_help,
|
||||
display_order = NULL,
|
||||
visible = excluded.visible,
|
||||
searchable = excluded.searchable,
|
||||
editable = excluded.editable,
|
||||
display_type = excluded.display_type,
|
||||
options_json = excluded.options_json
|
||||
""",
|
||||
(
|
||||
table_name,
|
||||
column_name,
|
||||
display_name,
|
||||
description,
|
||||
grid_help,
|
||||
visible,
|
||||
searchable,
|
||||
editable,
|
||||
display_type,
|
||||
options_json,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def seed_column_metadata_batch(
|
||||
cursor,
|
||||
*,
|
||||
table_name: str,
|
||||
columns: Iterable[dict[str, object]],
|
||||
valid_column_names: Iterable[str] | None = None,
|
||||
) -> None:
|
||||
"""批量 upsert 字段元数据;传入 valid_column_names 时会在 upsert 后清理陈旧字段元数据。"""
|
||||
for column in columns:
|
||||
upsert_column_metadata(
|
||||
cursor,
|
||||
table_name=table_name,
|
||||
column_name=str(column["column_name"]),
|
||||
display_name=str(column["display_name"]),
|
||||
description=str(column["description"]) if column.get("description") else None,
|
||||
grid_help=str(column["grid_help"]) if column.get("grid_help") else None,
|
||||
visible=int(column.get("visible", 1)),
|
||||
searchable=int(column.get("searchable", 1)),
|
||||
editable=int(column.get("editable", 1)),
|
||||
display_type=str(column["display_type"]) if column.get("display_type") else None,
|
||||
options_json=str(column["options_json"]) if column.get("options_json") else None,
|
||||
)
|
||||
if valid_column_names is not None:
|
||||
prune_stale_column_metadata(cursor, table_name, valid_column_names)
|
||||
|
||||
|
||||
def prune_stale_column_metadata(cursor, table_name: str, valid_column_names: Iterable[str]) -> None:
|
||||
"""删除表中已不存在物理字段的元数据行(幂等初始化后不得残留旧字段)。"""
|
||||
valid = set(valid_column_names)
|
||||
cursor.execute(
|
||||
"SELECT column_name FROM _jiangchang_columns WHERE table_name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
for (column_name,) in cursor.fetchall():
|
||||
if str(column_name) not in valid:
|
||||
cursor.execute(
|
||||
"DELETE FROM _jiangchang_columns WHERE table_name = ? AND column_name = ?",
|
||||
(table_name, column_name),
|
||||
)
|
||||
|
||||
|
||||
def get_table_readonly(cursor, table_name: str) -> int | None:
|
||||
cursor.execute(
|
||||
"SELECT readonly FROM _jiangchang_tables WHERE table_name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return int(row[0] or 0)
|
||||
|
||||
|
||||
def get_column_editable(cursor, table_name: str, column_name: str) -> int | None:
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT editable FROM _jiangchang_columns
|
||||
WHERE table_name = ? AND column_name = ?
|
||||
""",
|
||||
(table_name, column_name),
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return int(row[0] or 0)
|
||||
|
||||
|
||||
def list_editable_business_columns(cursor, table_name: str) -> list[str]:
|
||||
"""返回 editable=1 的业务字段名(不含宿主侧主键/generated 等二次过滤)。"""
|
||||
physical = list_physical_column_names(cursor, table_name)
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT column_name, editable
|
||||
FROM _jiangchang_columns
|
||||
WHERE table_name = ?
|
||||
""",
|
||||
(table_name,),
|
||||
)
|
||||
editable_set = {
|
||||
str(column_name)
|
||||
for column_name, editable in cursor.fetchall()
|
||||
if editable is not None and int(editable) == 1
|
||||
}
|
||||
return [name for name in physical if name in editable_set]
|
||||
|
||||
|
||||
def table_allows_manual_create(cursor, table_name: str) -> bool:
|
||||
"""表级 readonly=0 且至少有一个 editable=1 字段时,宿主才应提供空白新增表单。"""
|
||||
readonly = get_table_readonly(cursor, table_name)
|
||||
if readonly is None or int(readonly) != 0:
|
||||
return False
|
||||
return bool(list_editable_business_columns(cursor, table_name))
|
||||
|
||||
|
||||
def init_display_metadata(cursor) -> None:
|
||||
init_display_metadata_tables(cursor)
|
||||
|
||||
|
||||
def drop_deprecated_user_table(
|
||||
cursor,
|
||||
table_name: str,
|
||||
*,
|
||||
triggers: Iterable[str] | None = None,
|
||||
) -> None:
|
||||
"""永久退役用户可见表:删 trigger、DROP 物理表、清理展示元数据(幂等)。
|
||||
|
||||
用于废弃 task_logs 等旧表。禁止只删元数据而保留物理表。
|
||||
见 references/SCHEMA.md「表增删改与退役」。
|
||||
"""
|
||||
for trigger_name in triggers or ():
|
||||
cursor.execute(f"DROP TRIGGER IF EXISTS {trigger_name}")
|
||||
default_updated_at = f"{table_name}_set_updated_at"
|
||||
cursor.execute(f"DROP TRIGGER IF EXISTS {default_updated_at}")
|
||||
cursor.execute(f"DROP TABLE IF EXISTS {_quote_identifier(table_name)}")
|
||||
cursor.execute(
|
||||
"DELETE FROM _jiangchang_columns WHERE table_name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
cursor.execute(
|
||||
"DELETE FROM _jiangchang_tables WHERE table_name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
|
||||
|
||||
def iter_user_tables(cursor) -> Iterable[str]:
|
||||
cursor.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
||||
)
|
||||
for (name,) in cursor.fetchall():
|
||||
if name in METADATA_TABLES:
|
||||
continue
|
||||
yield str(name)
|
||||
|
||||
|
||||
def _quote_identifier(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def list_physical_column_names(cursor, table_name: str) -> list[str]:
|
||||
cursor.execute(f"PRAGMA table_info({_quote_identifier(table_name)})")
|
||||
rows = cursor.fetchall()
|
||||
rows.sort(key=lambda row: int(row[0]))
|
||||
return [str(row[1]) for row in rows]
|
||||
592
scripts/db/display_metadata_validator.py
Normal file
592
scripts/db/display_metadata_validator.py
Normal file
@@ -0,0 +1,592 @@
|
||||
"""数据管理展示元数据校验(模板开发自检,不依赖宿主)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from db.display_metadata import (
|
||||
DATETIME_UNIX_SECONDS,
|
||||
METADATA_TABLES,
|
||||
STANDARD_TIMESTAMP_COLUMNS,
|
||||
iter_user_tables,
|
||||
list_editable_business_columns,
|
||||
list_physical_column_names,
|
||||
table_allows_manual_create,
|
||||
)
|
||||
from db.timestamp_columns import has_updated_at_trigger
|
||||
from util.constants import SKILL_SLUG
|
||||
from util.slug_naming import LEGACY_EXEMPT_SLUGS, validate_slug_semantics
|
||||
|
||||
_TEMPLATE_PLACEHOLDER_SLUGS = frozenset({"process-leave-attendance-default", "process_leave_attendance_default"})
|
||||
_ENGLISH_PLACEHOLDER_NAME_PATTERNS = (
|
||||
re.compile(r"^my\s+skill$", re.I),
|
||||
re.compile(r"^your[-_\s]?skill", re.I),
|
||||
re.compile(r"^skill[-_\s]?template$", re.I),
|
||||
re.compile(r"^[a-z0-9_-]+$"),
|
||||
)
|
||||
_KEBAB_SLUG = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
_CJK_RE = re.compile(r"[\u4e00-\u9fff]")
|
||||
_FK_DDL_PATTERN = re.compile(r"\bFOREIGN\s+KEY\b|\bREFERENCES\b", re.I)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ValidationReport:
|
||||
errors: list[str] = field(default_factory=list)
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return not self.errors
|
||||
|
||||
|
||||
def _has_cjk(text: str) -> bool:
|
||||
return bool(_CJK_RE.search(text))
|
||||
|
||||
|
||||
def _looks_like_raw_physical_name(display_name: str, physical_name: str) -> bool:
|
||||
if not display_name.strip():
|
||||
return True
|
||||
if display_name.strip().lower() == physical_name.strip().lower():
|
||||
return True
|
||||
compact = display_name.replace(" ", "").replace("_", "").lower()
|
||||
if compact == physical_name.replace("_", "").lower():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_frontmatter_field(text: str, field_name: str) -> str:
|
||||
parts = text.split("---", 2)
|
||||
if len(parts) < 2:
|
||||
return ""
|
||||
for line in parts[1].splitlines():
|
||||
match = re.match(rf"^{re.escape(field_name)}:\s*(.+)\s*$", line.strip())
|
||||
if match:
|
||||
return match.group(1).strip().strip("\"'")
|
||||
return ""
|
||||
|
||||
|
||||
def _parse_openclaw_slug(text: str) -> str:
|
||||
parts = text.split("---", 2)
|
||||
if len(parts) < 2:
|
||||
return ""
|
||||
lines = parts[1].splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
if re.match(r"^\s+openclaw:\s*$", line):
|
||||
for inner in lines[index + 1 :]:
|
||||
if inner.strip() and inner[0] not in (" ", "\t"):
|
||||
break
|
||||
match = re.match(r"^(\s+)slug:\s*(.+)\s*$", inner)
|
||||
if match:
|
||||
return match.group(2).strip().strip("\"'")
|
||||
return ""
|
||||
|
||||
|
||||
def parse_skill_frontmatter(skill_root: str) -> dict[str, str]:
|
||||
path = os.path.join(skill_root, "SKILL.md")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
return {
|
||||
"name": _parse_frontmatter_field(text, "name"),
|
||||
"slug": _parse_openclaw_slug(text),
|
||||
}
|
||||
|
||||
|
||||
def validate_skill_frontmatter(skill_root: str, *, allow_template_placeholders: bool = True) -> ValidationReport:
|
||||
report = ValidationReport()
|
||||
data = parse_skill_frontmatter(skill_root)
|
||||
name = str(data.get("name") or "").strip()
|
||||
slug = str(data.get("slug") or "").strip()
|
||||
|
||||
if not name:
|
||||
report.errors.append("SKILL.md frontmatter.name 缺失")
|
||||
elif not _has_cjk(name):
|
||||
if allow_template_placeholders and slug in _TEMPLATE_PLACEHOLDER_SLUGS:
|
||||
report.warnings.append("SKILL.md frontmatter.name 建议使用清晰的中文业务名称(模板占位可暂保留)")
|
||||
else:
|
||||
report.errors.append("SKILL.md frontmatter.name 应使用用户可见的中文业务名称")
|
||||
else:
|
||||
for pattern in _ENGLISH_PLACEHOLDER_NAME_PATTERNS:
|
||||
if pattern.fullmatch(name):
|
||||
if allow_template_placeholders and slug in _TEMPLATE_PLACEHOLDER_SLUGS:
|
||||
report.warnings.append(f"SKILL.md frontmatter.name 仍为占位风格:{name!r}")
|
||||
else:
|
||||
report.errors.append(f"SKILL.md frontmatter.name 不应为英文占位名:{name!r}")
|
||||
break
|
||||
|
||||
if not slug:
|
||||
report.errors.append("SKILL.md metadata.openclaw.slug 缺失")
|
||||
elif not _KEBAB_SLUG.fullmatch(slug):
|
||||
report.errors.append(f"metadata.openclaw.slug 必须为 kebab-case:{slug!r}")
|
||||
elif slug in _TEMPLATE_PLACEHOLDER_SLUGS and not allow_template_placeholders:
|
||||
report.errors.append(f"metadata.openclaw.slug 仍为模板占位:{slug!r}")
|
||||
|
||||
constants_slug = SKILL_SLUG.strip()
|
||||
if slug and constants_slug and slug != constants_slug:
|
||||
report.warnings.append(
|
||||
f"SKILL.md slug ({slug!r}) 与 util.constants.SKILL_SLUG ({constants_slug!r}) 不一致"
|
||||
)
|
||||
|
||||
if slug and slug not in LEGACY_EXEMPT_SLUGS and _KEBAB_SLUG.fullmatch(slug):
|
||||
naming_errors, naming_warnings = validate_slug_semantics(
|
||||
slug,
|
||||
strict=not allow_template_placeholders,
|
||||
)
|
||||
report.errors.extend(naming_errors)
|
||||
report.warnings.extend(naming_warnings)
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def _quote_identifier(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _table_column_info(cursor, table_name: str) -> dict[str, dict[str, object]]:
|
||||
cursor.execute(f"PRAGMA table_info({_quote_identifier(table_name)})")
|
||||
info: dict[str, dict[str, object]] = {}
|
||||
for row in cursor.fetchall():
|
||||
info[str(row[1])] = {
|
||||
"cid": int(row[0]),
|
||||
"name": str(row[1]),
|
||||
"type": str(row[2] or ""),
|
||||
"notnull": int(row[3] or 0),
|
||||
"dflt_value": row[4],
|
||||
"pk": int(row[5] or 0),
|
||||
}
|
||||
return info
|
||||
|
||||
|
||||
def _table_column_xinfo(cursor, table_name: str) -> dict[str, dict[str, object]]:
|
||||
"""PRAGMA table_xinfo 可识别 generated/hidden 字段(SQLite 3.31+)。"""
|
||||
cursor.execute(f"PRAGMA table_xinfo({_quote_identifier(table_name)})")
|
||||
info: dict[str, dict[str, object]] = {}
|
||||
for row in cursor.fetchall():
|
||||
hidden = int(row[6] or 0) if len(row) > 6 else 0
|
||||
info[str(row[1])] = {
|
||||
"cid": int(row[0]),
|
||||
"name": str(row[1]),
|
||||
"type": str(row[2] or ""),
|
||||
"notnull": int(row[3] or 0),
|
||||
"dflt_value": row[4],
|
||||
"pk": int(row[5] or 0),
|
||||
"hidden": hidden,
|
||||
}
|
||||
return info
|
||||
|
||||
|
||||
def _is_generated_column(xinfo: dict[str, object]) -> bool:
|
||||
hidden = int(xinfo.get("hidden") or 0)
|
||||
return hidden in (2, 3)
|
||||
|
||||
|
||||
def _is_blob_column(column_info: dict[str, object]) -> bool:
|
||||
return "BLOB" in str(column_info.get("type") or "").upper()
|
||||
|
||||
|
||||
def _default_uses_unixepoch(default_value: object) -> bool:
|
||||
if default_value is None:
|
||||
return False
|
||||
text = str(default_value).strip().lower()
|
||||
return "unixepoch" in text
|
||||
|
||||
|
||||
def validate_options_json(options_json: str | None) -> tuple[list[str], list[str]]:
|
||||
"""校验 options_json:静态枚举数组,或 lookup 对象。"""
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
if options_json is None or str(options_json).strip() == "":
|
||||
return errors, warnings
|
||||
try:
|
||||
parsed = json.loads(str(options_json))
|
||||
except json.JSONDecodeError as exc:
|
||||
errors.append(f"options_json 不是合法 JSON:{exc}")
|
||||
return errors, warnings
|
||||
|
||||
if isinstance(parsed, dict):
|
||||
for key in ("ref_table", "value_column", "label_column"):
|
||||
if not str(parsed.get(key) or "").strip():
|
||||
errors.append(f"options_json lookup 必须包含非空 {key}")
|
||||
ident = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||
for key in ("ref_table", "value_column", "label_column", "filter_column"):
|
||||
raw = parsed.get(key)
|
||||
if raw is None or raw == "":
|
||||
continue
|
||||
if not ident.match(str(raw)):
|
||||
errors.append(f"options_json.{key} 必须是安全标识符,当前为 {raw!r}")
|
||||
if parsed.get("filter_column") not in (None, "") and "filter_value" not in parsed:
|
||||
warnings.append("options_json lookup 声明了 filter_column 但未提供 filter_value")
|
||||
if "multiple" in parsed and not isinstance(parsed.get("multiple"), bool):
|
||||
errors.append("options_json lookup.multiple 必须是布尔值")
|
||||
return errors, warnings
|
||||
|
||||
if not isinstance(parsed, list):
|
||||
errors.append("options_json 必须是 JSON 数组(静态枚举)或对象(lookup)")
|
||||
return errors, warnings
|
||||
for index, item in enumerate(parsed):
|
||||
if not isinstance(item, dict):
|
||||
errors.append(f"options_json[{index}] 必须是对象")
|
||||
continue
|
||||
if "value" not in item or "label" not in item:
|
||||
errors.append(f"options_json[{index}] 必须包含 value 与 label")
|
||||
return errors, warnings
|
||||
|
||||
|
||||
def validate_filter_search_metadata(
|
||||
cursor,
|
||||
table_name: str,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""对可见但未开启 searchable 的枚举 / boolean 列给出软建议。"""
|
||||
warnings: list[str] = []
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT column_name, visible, searchable, display_type, options_json
|
||||
FROM _jiangchang_columns
|
||||
WHERE table_name = ?
|
||||
""",
|
||||
(table_name,),
|
||||
)
|
||||
for column_name, visible, searchable, display_type, options_json in cursor.fetchall():
|
||||
if visible is not None and int(visible) == 0:
|
||||
continue
|
||||
if searchable is not None and int(searchable) != 0:
|
||||
continue
|
||||
|
||||
display_type_norm = str(display_type or "").strip()
|
||||
is_boolean = display_type_norm == "boolean"
|
||||
|
||||
has_enum = False
|
||||
if options_json is not None and str(options_json).strip():
|
||||
opt_errors, _ = validate_options_json(options_json)
|
||||
if not opt_errors:
|
||||
try:
|
||||
parsed = json.loads(str(options_json))
|
||||
except json.JSONDecodeError:
|
||||
parsed = None
|
||||
has_enum = isinstance(parsed, list) and len(parsed) > 0
|
||||
|
||||
if not has_enum and not is_boolean:
|
||||
continue
|
||||
|
||||
warnings.append(
|
||||
f"{table_name}.{column_name}: 枚举/状态类列建议 searchable=1,"
|
||||
"以便宿主列筛选与按中文 label 全局搜索(见 references/SCHEMA.md)"
|
||||
)
|
||||
|
||||
return [], warnings
|
||||
|
||||
|
||||
def validate_column_permissions(
|
||||
cursor,
|
||||
table_name: str,
|
||||
*,
|
||||
physical_columns: list[str] | None = None,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""校验常见系统字段 editable=0,并识别技术上可写但不适合手工新增的表。"""
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
ordered = physical_columns or list_physical_column_names(cursor, table_name)
|
||||
column_info = _table_column_info(cursor, table_name)
|
||||
column_xinfo = _table_column_xinfo(cursor, table_name)
|
||||
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT column_name, editable, options_json
|
||||
FROM _jiangchang_columns
|
||||
WHERE table_name = ?
|
||||
""",
|
||||
(table_name,),
|
||||
)
|
||||
meta_by_column = {
|
||||
str(row[0]): {"editable": row[1], "options_json": row[2]}
|
||||
for row in cursor.fetchall()
|
||||
}
|
||||
|
||||
for column_name, meta in meta_by_column.items():
|
||||
physical = column_info.get(column_name) or {}
|
||||
xinfo = column_xinfo.get(column_name) or physical
|
||||
if not physical and column_name not in column_xinfo:
|
||||
continue
|
||||
|
||||
pk = int(physical.get("pk") or xinfo.get("pk") or 0)
|
||||
editable = meta["editable"]
|
||||
if pk and editable is not None and int(editable) != 0:
|
||||
errors.append(f"{table_name}.{column_name} 是主键,editable 应为 0")
|
||||
|
||||
if column_name == "id" and editable is not None and int(editable) != 0:
|
||||
errors.append(f"{table_name}.id 的 editable 应为 0(自增主键)")
|
||||
|
||||
if _is_generated_column(xinfo) and editable is not None and int(editable) != 0:
|
||||
errors.append(f"{table_name}.{column_name} 是 generated 字段,editable 应为 0")
|
||||
|
||||
if _is_blob_column(physical or xinfo) and editable is not None and int(editable) != 0:
|
||||
errors.append(f"{table_name}.{column_name} 是 BLOB 字段,editable 应为 0")
|
||||
|
||||
opt_errors, _ = validate_options_json(meta.get("options_json"))
|
||||
for item in opt_errors:
|
||||
errors.append(f"{table_name}.{column_name}: {item}")
|
||||
|
||||
cursor.execute(
|
||||
"SELECT readonly FROM _jiangchang_tables WHERE table_name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
readonly_row = cursor.fetchone()
|
||||
readonly = int(readonly_row[0]) if readonly_row else None
|
||||
editable_columns = list_editable_business_columns(cursor, table_name)
|
||||
if readonly == 0 and not editable_columns:
|
||||
warnings.append(
|
||||
f"{table_name}: 表级 readonly=0 但所有字段 editable=0,"
|
||||
"宿主不应打开空白新增表单;数据应由技能业务流程产生"
|
||||
)
|
||||
if readonly == 1 and editable_columns:
|
||||
warnings.append(
|
||||
f"{table_name}: 表级 readonly=1 但存在 editable=1 字段,"
|
||||
"宿主应以表级只读为准"
|
||||
)
|
||||
|
||||
return errors, warnings
|
||||
|
||||
|
||||
def _expected_timestamp_display_name(column_name: str) -> str:
|
||||
if column_name == "created_at":
|
||||
return "创建时间"
|
||||
if column_name == "updated_at":
|
||||
return "更新时间"
|
||||
return ""
|
||||
|
||||
|
||||
def validate_standard_timestamp_columns(
|
||||
cursor,
|
||||
table_name: str,
|
||||
*,
|
||||
physical_columns: list[str] | None = None,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
ordered = physical_columns or list_physical_column_names(cursor, table_name)
|
||||
column_info = _table_column_info(cursor, table_name)
|
||||
|
||||
for column_name in STANDARD_TIMESTAMP_COLUMNS:
|
||||
if column_name not in ordered:
|
||||
continue
|
||||
|
||||
physical = column_info.get(column_name)
|
||||
if not physical:
|
||||
errors.append(f"{table_name}.{column_name} 缺少物理字段定义")
|
||||
continue
|
||||
|
||||
if "INT" not in str(physical["type"]).upper():
|
||||
errors.append(
|
||||
f"{table_name}.{column_name} 字段类型应为 INTEGER(Unix 秒级时间戳),当前为 {physical['type']!r}"
|
||||
)
|
||||
|
||||
if column_name == "created_at" and not _default_uses_unixepoch(physical["dflt_value"]):
|
||||
errors.append(
|
||||
f"{table_name}.created_at 应设置数据库默认值 DEFAULT (unixepoch()),当前默认值为 {physical['dflt_value']!r}"
|
||||
)
|
||||
if column_name == "updated_at" and not _default_uses_unixepoch(physical["dflt_value"]):
|
||||
errors.append(
|
||||
f"{table_name}.updated_at 应设置数据库初始默认值 DEFAULT (unixepoch()),当前默认值为 {physical['dflt_value']!r}"
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT display_name, display_type, editable, searchable, display_order
|
||||
FROM _jiangchang_columns
|
||||
WHERE table_name = ? AND column_name = ?
|
||||
""",
|
||||
(table_name, column_name),
|
||||
)
|
||||
meta_row = cursor.fetchone()
|
||||
if not meta_row:
|
||||
errors.append(f"{table_name}.{column_name} 缺少 _jiangchang_columns 元数据")
|
||||
continue
|
||||
|
||||
display_name, display_type, editable, searchable, display_order = meta_row
|
||||
expected_name = _expected_timestamp_display_name(column_name)
|
||||
if str(display_name or "").strip() != expected_name:
|
||||
errors.append(
|
||||
f"{table_name}.{column_name} 的 display_name 应为 {expected_name!r},当前为 {display_name!r}"
|
||||
)
|
||||
if str(display_type or "").strip() != DATETIME_UNIX_SECONDS:
|
||||
errors.append(
|
||||
f"{table_name}.{column_name} 的 display_type 应为 {DATETIME_UNIX_SECONDS!r},当前为 {display_type!r}"
|
||||
)
|
||||
if editable is None or int(editable) != 0:
|
||||
errors.append(f"{table_name}.{column_name} 的 editable 应为 0(系统时间字段不可编辑)")
|
||||
if display_order is not None:
|
||||
errors.append(f"{table_name}.{column_name} 的 display_order 应为 NULL")
|
||||
if searchable is not None and int(searchable) != 0:
|
||||
warnings.append(f"{table_name}.{column_name} 的时间字段通常不必开启 searchable")
|
||||
|
||||
if "created_at" in ordered and "updated_at" in ordered:
|
||||
if ordered.index("updated_at") < ordered.index("created_at"):
|
||||
warnings.append(f"{table_name}: updated_at 不应出现在 created_at 之前")
|
||||
|
||||
if "updated_at" in ordered and not has_updated_at_trigger(cursor, table_name):
|
||||
errors.append(
|
||||
f"{table_name}.updated_at 缺少自动维护 trigger(期望 {table_name}_set_updated_at)"
|
||||
)
|
||||
|
||||
return errors, warnings
|
||||
|
||||
|
||||
def column_order_warnings(table_name: str, ordered_names: list[str]) -> list[str]:
|
||||
warnings: list[str] = []
|
||||
if "id" in ordered_names and ordered_names.index("id") != 0:
|
||||
warnings.append(f"{table_name}: 字段 id 通常应定义在 CREATE TABLE 的第一列")
|
||||
if "created_at" in ordered_names:
|
||||
idx = ordered_names.index("created_at")
|
||||
trailing = ordered_names[idx + 1 :]
|
||||
if trailing and trailing != ["updated_at"]:
|
||||
warnings.append(
|
||||
f"{table_name}: created_at 之后通常只应跟 updated_at,不应再放置其他业务字段"
|
||||
)
|
||||
if "updated_at" in ordered_names and "created_at" in ordered_names:
|
||||
if ordered_names.index("updated_at") < ordered_names.index("created_at"):
|
||||
warnings.append(f"{table_name}: updated_at 不应出现在 created_at 之前")
|
||||
return warnings
|
||||
|
||||
|
||||
def _table_exists(cursor, table_name: str) -> bool:
|
||||
cursor.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",
|
||||
(table_name,),
|
||||
)
|
||||
return cursor.fetchone() is not None
|
||||
|
||||
|
||||
def validate_no_sqlite_foreign_keys(cursor) -> tuple[list[str], list[str]]:
|
||||
"""业务表 DDL 不得含 FOREIGN KEY / REFERENCES(关联走 repository/service)。"""
|
||||
errors: list[str] = []
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT name, sql FROM sqlite_master
|
||||
WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
|
||||
"""
|
||||
)
|
||||
for table_name, sql in cursor.fetchall():
|
||||
if table_name in METADATA_TABLES:
|
||||
continue
|
||||
ddl = str(sql or "")
|
||||
if ddl and _FK_DDL_PATTERN.search(ddl):
|
||||
errors.append(
|
||||
f"业务表 {table_name!r} 的 DDL 含 SQLite FOREIGN KEY/REFERENCES;"
|
||||
"请改为业务 id 列 + repository/service 逻辑关联(见 references/SCHEMA.md)"
|
||||
)
|
||||
return errors, []
|
||||
|
||||
|
||||
def validate_display_metadata(conn: sqlite3.Connection, *, check_column_order: bool = True) -> ValidationReport:
|
||||
report = ValidationReport()
|
||||
cur = conn.cursor()
|
||||
|
||||
has_tables_meta = _table_exists(cur, "_jiangchang_tables")
|
||||
has_columns_meta = _table_exists(cur, "_jiangchang_columns")
|
||||
if not has_tables_meta:
|
||||
report.errors.append("缺少数据管理元数据表 _jiangchang_tables")
|
||||
if not has_columns_meta:
|
||||
report.errors.append("缺少数据管理元数据表 _jiangchang_columns")
|
||||
if not has_tables_meta or not has_columns_meta:
|
||||
return report
|
||||
|
||||
fk_errors, _ = validate_no_sqlite_foreign_keys(cur)
|
||||
report.errors.extend(fk_errors)
|
||||
|
||||
for table_name in iter_user_tables(cur):
|
||||
cur.execute(
|
||||
"SELECT display_name FROM _jiangchang_tables WHERE table_name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row or not str(row[0] or "").strip():
|
||||
report.errors.append(f"业务表 {table_name!r} 缺少 _jiangchang_tables.display_name")
|
||||
elif not _has_cjk(str(row[0])):
|
||||
report.errors.append(f"业务表 {table_name!r} 的 display_name 应使用中文业务名称")
|
||||
|
||||
physical_columns = list_physical_column_names(cur, table_name)
|
||||
if check_column_order:
|
||||
report.warnings.extend(column_order_warnings(table_name, physical_columns))
|
||||
|
||||
for column_name in physical_columns:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT display_name, visible
|
||||
FROM _jiangchang_columns
|
||||
WHERE table_name = ? AND column_name = ?
|
||||
""",
|
||||
(table_name, column_name),
|
||||
)
|
||||
col_row = cur.fetchone()
|
||||
if not col_row:
|
||||
report.errors.append(
|
||||
f"字段 {table_name}.{column_name} 缺少 _jiangchang_columns 元数据"
|
||||
)
|
||||
continue
|
||||
display_name = str(col_row[0] or "").strip()
|
||||
visible = col_row[1] is None or int(col_row[1]) != 0
|
||||
if visible and not display_name:
|
||||
report.errors.append(f"字段 {table_name}.{column_name} 的 display_name 为空")
|
||||
elif visible and _looks_like_raw_physical_name(display_name, column_name):
|
||||
report.errors.append(
|
||||
f"字段 {table_name}.{column_name} 的 display_name 不应直接等于英文物理名:{display_name!r}"
|
||||
)
|
||||
elif visible and not _has_cjk(display_name):
|
||||
report.errors.append(
|
||||
f"字段 {table_name}.{column_name} 的 display_name 应使用中文:{display_name!r}"
|
||||
)
|
||||
|
||||
ts_errors, ts_warnings = validate_standard_timestamp_columns(
|
||||
cur,
|
||||
table_name,
|
||||
physical_columns=physical_columns,
|
||||
)
|
||||
report.errors.extend(ts_errors)
|
||||
report.warnings.extend(ts_warnings)
|
||||
|
||||
perm_errors, perm_warnings = validate_column_permissions(
|
||||
cur,
|
||||
table_name,
|
||||
physical_columns=physical_columns,
|
||||
)
|
||||
report.errors.extend(perm_errors)
|
||||
report.warnings.extend(perm_warnings)
|
||||
|
||||
_, filter_warnings = validate_filter_search_metadata(cur, table_name)
|
||||
report.warnings.extend(filter_warnings)
|
||||
|
||||
cur.execute("SELECT table_name, column_name FROM _jiangchang_columns")
|
||||
for table_name, column_name in cur.fetchall():
|
||||
if table_name in METADATA_TABLES:
|
||||
continue
|
||||
cur.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
report.errors.append(f"元数据引用了不存在的表:{table_name!r}")
|
||||
continue
|
||||
physical = list_physical_column_names(cur, str(table_name))
|
||||
if str(column_name) not in physical:
|
||||
report.errors.append(f"元数据引用了不存在的字段:{table_name}.{column_name}")
|
||||
|
||||
cur.execute("SELECT table_name FROM _jiangchang_tables")
|
||||
for (table_name,) in cur.fetchall():
|
||||
if table_name in METADATA_TABLES:
|
||||
continue
|
||||
cur.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",
|
||||
(table_name,),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
report.errors.append(f"元数据引用了不存在的表:{table_name!r}")
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def validate_template_database(conn: sqlite3.Connection) -> ValidationReport:
|
||||
"""模板自检入口:校验展示元数据完整性,并扫描业务表 DDL 是否含 SQLite 外键。"""
|
||||
return validate_display_metadata(conn)
|
||||
442
scripts/db/leave_display_metadata.py
Normal file
442
scripts/db/leave_display_metadata.py
Normal file
@@ -0,0 +1,442 @@
|
||||
"""高校人事请假考勤:数据管理展示元数据。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from db.display_metadata import (
|
||||
DATETIME_UNIX_SECONDS,
|
||||
list_physical_column_names,
|
||||
seed_column_metadata_batch,
|
||||
upsert_table_metadata,
|
||||
)
|
||||
from db.schema import (
|
||||
ATTENDANCE_HOLIDAYS_TABLE,
|
||||
EMPLOYEES_TABLE,
|
||||
LEAVE_BALANCES_TABLE,
|
||||
LEAVE_POLICIES_TABLE,
|
||||
LEAVE_REQUESTS_TABLE,
|
||||
)
|
||||
|
||||
IS_ACTIVE_OPTIONS = (
|
||||
'[{"value":"1","label":"启用"},'
|
||||
'{"value":"0","label":"停用"}]'
|
||||
)
|
||||
|
||||
STATUS_OPTIONS = (
|
||||
'[{"value":"draft","label":"草稿"},'
|
||||
'{"value":"completed","label":"已完成"},'
|
||||
'{"value":"failed","label":"失败"}]'
|
||||
)
|
||||
|
||||
DAY_BASIS_OPTIONS = (
|
||||
'[{"value":"workday","label":"工作日"},'
|
||||
'{"value":"natural","label":"自然日"}]'
|
||||
)
|
||||
|
||||
POSITION_CATEGORY_OPTIONS = (
|
||||
'[{"value":"教师","label":"教师"},'
|
||||
'{"value":"行政","label":"行政"},'
|
||||
'{"value":"科研","label":"科研"}]'
|
||||
)
|
||||
|
||||
HOLIDAY_TYPE_OPTIONS = (
|
||||
'[{"value":"法定假日","label":"法定假日"},'
|
||||
'{"value":"寒暑假","label":"寒暑假"},'
|
||||
'{"value":"校庆","label":"校庆"},'
|
||||
'{"value":"周末","label":"周末"}]'
|
||||
)
|
||||
|
||||
APPROVAL_LEVEL_OPTIONS = (
|
||||
'[{"value":"系主任","label":"系主任"},'
|
||||
'{"value":"系主任+人事处","label":"系主任+人事处"},'
|
||||
'{"value":"系主任+人事处+校领导","label":"系主任+人事处+校领导"}]'
|
||||
)
|
||||
|
||||
BALANCE_TYPE_OPTIONS = (
|
||||
'[{"value":"annual","label":"年假"},'
|
||||
'{"value":"sick","label":"病假"},'
|
||||
'{"value":"marriage","label":"婚假"},'
|
||||
'{"value":"maternity","label":"产假"},'
|
||||
'{"value":"bereavement","label":"丧假"}]'
|
||||
)
|
||||
|
||||
REQUIRES_CERTIFICATE_OPTIONS = (
|
||||
'[{"value":"1","label":"是"},'
|
||||
'{"value":"0","label":"否"}]'
|
||||
)
|
||||
|
||||
CAN_OFFSET_OPTIONS = (
|
||||
'[{"value":"1","label":"是"},'
|
||||
'{"value":"0","label":"否"}]'
|
||||
)
|
||||
|
||||
|
||||
def _ts(column: str, label: str, *, editable: int = 0) -> dict[str, object]:
|
||||
return {
|
||||
"column_name": column,
|
||||
"display_name": label,
|
||||
"visible": 1,
|
||||
"searchable": 0,
|
||||
"editable": editable,
|
||||
"display_type": DATETIME_UNIX_SECONDS,
|
||||
}
|
||||
|
||||
|
||||
def _lookup(ref_table: str, value_column: str, label_column: str) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"ref_table": ref_table,
|
||||
"value_column": value_column,
|
||||
"label_column": label_column,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
|
||||
def _seed_table(cursor, table_name: str, columns: tuple[dict[str, object], ...]) -> None:
|
||||
physical = list_physical_column_names(cursor, table_name)
|
||||
seed_column_metadata_batch(
|
||||
cursor,
|
||||
table_name=table_name,
|
||||
columns=columns,
|
||||
valid_column_names=physical,
|
||||
)
|
||||
|
||||
|
||||
def seed_leave_display_metadata(cursor) -> None:
|
||||
upsert_table_metadata(
|
||||
cursor,
|
||||
table_name=EMPLOYEES_TABLE,
|
||||
display_name="教职工",
|
||||
description="教职工基本信息:部门、岗位、入职日期、月薪标准、年假余额",
|
||||
grid_help="可用「导入教职工」从 JSON 批量写入;停用教职工不参与请假核算。",
|
||||
readonly=0,
|
||||
)
|
||||
_seed_table(
|
||||
cursor,
|
||||
EMPLOYEES_TABLE,
|
||||
(
|
||||
{"column_name": "id", "display_name": "编号", "editable": 0, "searchable": 1},
|
||||
{"column_name": "name", "display_name": "姓名", "editable": 1, "searchable": 1},
|
||||
{"column_name": "employee_no", "display_name": "工号", "editable": 1, "searchable": 1},
|
||||
{"column_name": "department", "display_name": "部门", "editable": 1, "searchable": 1},
|
||||
{"column_name": "position", "display_name": "岗位", "editable": 1, "searchable": 1},
|
||||
{
|
||||
"column_name": "position_category",
|
||||
"display_name": "岗位类别",
|
||||
"editable": 1,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": POSITION_CATEGORY_OPTIONS,
|
||||
},
|
||||
{"column_name": "join_date", "display_name": "入职日期", "editable": 1, "searchable": 1},
|
||||
{
|
||||
"column_name": "monthly_salary",
|
||||
"display_name": "月薪标准",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "annual_leave_remaining",
|
||||
"display_name": "年假余额",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "is_active",
|
||||
"display_name": "启用",
|
||||
"editable": 1,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": IS_ACTIVE_OPTIONS,
|
||||
},
|
||||
{"column_name": "notes", "display_name": "备注", "editable": 1, "searchable": 1},
|
||||
_ts("created_at", "创建时间"),
|
||||
_ts("updated_at", "更新时间"),
|
||||
),
|
||||
)
|
||||
|
||||
upsert_table_metadata(
|
||||
cursor,
|
||||
table_name=LEAVE_POLICIES_TABLE,
|
||||
display_name="请假政策",
|
||||
description="各类假别的扣薪规则、审批阈值与证件要求",
|
||||
grid_help="按学校政策维护各类假别参数;核算时按 leave_type 匹配。",
|
||||
readonly=0,
|
||||
)
|
||||
_seed_table(
|
||||
cursor,
|
||||
LEAVE_POLICIES_TABLE,
|
||||
(
|
||||
{"column_name": "id", "display_name": "编号", "editable": 0, "searchable": 1},
|
||||
{"column_name": "leave_type", "display_name": "请假类型", "editable": 1, "searchable": 1},
|
||||
{
|
||||
"column_name": "max_days",
|
||||
"display_name": "最大可休天数",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "day_basis",
|
||||
"display_name": "计薪日基准",
|
||||
"editable": 1,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": DAY_BASIS_OPTIONS,
|
||||
},
|
||||
{
|
||||
"column_name": "paid_days",
|
||||
"display_name": "带薪天数",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "partial_pay_ratio",
|
||||
"display_name": "部分扣薪比例",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "unpaid_after_days",
|
||||
"display_name": "无薪起始天数",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "requires_certificate",
|
||||
"display_name": "需证件",
|
||||
"editable": 1,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": REQUIRES_CERTIFICATE_OPTIONS,
|
||||
},
|
||||
{
|
||||
"column_name": "can_offset_annual",
|
||||
"display_name": "可抵年假",
|
||||
"editable": 1,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": CAN_OFFSET_OPTIONS,
|
||||
},
|
||||
{
|
||||
"column_name": "approval_threshold_dept",
|
||||
"display_name": "系主任阈值",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "approval_threshold_hr",
|
||||
"display_name": "人事处阈值",
|
||||
"editable": 1,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{"column_name": "notes", "display_name": "备注", "editable": 1, "searchable": 1},
|
||||
_ts("created_at", "创建时间"),
|
||||
_ts("updated_at", "更新时间"),
|
||||
),
|
||||
)
|
||||
|
||||
upsert_table_metadata(
|
||||
cursor,
|
||||
table_name=ATTENDANCE_HOLIDAYS_TABLE,
|
||||
display_name="考勤日历",
|
||||
description="法定节假日、寒暑假、校庆等非工作日",
|
||||
grid_help="核算工作日时排除此处登记的日期。",
|
||||
readonly=0,
|
||||
)
|
||||
_seed_table(
|
||||
cursor,
|
||||
ATTENDANCE_HOLIDAYS_TABLE,
|
||||
(
|
||||
{"column_name": "id", "display_name": "编号", "editable": 0, "searchable": 1},
|
||||
{"column_name": "holiday_date", "display_name": "日期", "editable": 1, "searchable": 1},
|
||||
{"column_name": "holiday_name", "display_name": "名称", "editable": 1, "searchable": 1},
|
||||
{
|
||||
"column_name": "holiday_type",
|
||||
"display_name": "类型",
|
||||
"editable": 1,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": HOLIDAY_TYPE_OPTIONS,
|
||||
},
|
||||
_ts("created_at", "创建时间"),
|
||||
_ts("updated_at", "更新时间"),
|
||||
),
|
||||
)
|
||||
|
||||
upsert_table_metadata(
|
||||
cursor,
|
||||
table_name=LEAVE_REQUESTS_TABLE,
|
||||
display_name="请假记录",
|
||||
description="请假申请与核算结果(系统写入)",
|
||||
grid_help="在教职工表执行「请假核算」后查看扣薪明细与审批层级。",
|
||||
readonly=1,
|
||||
)
|
||||
_seed_table(
|
||||
cursor,
|
||||
LEAVE_REQUESTS_TABLE,
|
||||
(
|
||||
{"column_name": "id", "display_name": "编号", "editable": 0, "searchable": 1},
|
||||
{
|
||||
"column_name": "employee_id",
|
||||
"display_name": "教职工",
|
||||
"editable": 0,
|
||||
"searchable": 1,
|
||||
"display_type": "lookup",
|
||||
"options_json": _lookup(EMPLOYEES_TABLE, "id", "name"),
|
||||
},
|
||||
{"column_name": "leave_type", "display_name": "请假类型", "editable": 0, "searchable": 1},
|
||||
{"column_name": "start_date", "display_name": "开始日期", "editable": 0, "searchable": 1},
|
||||
{"column_name": "end_date", "display_name": "结束日期", "editable": 0, "searchable": 1},
|
||||
{
|
||||
"column_name": "has_certificate",
|
||||
"display_name": "附证件",
|
||||
"editable": 0,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": REQUIRES_CERTIFICATE_OPTIONS,
|
||||
},
|
||||
{"column_name": "certificate_type", "display_name": "证件类型", "editable": 0, "searchable": 1},
|
||||
{
|
||||
"column_name": "natural_days",
|
||||
"display_name": "自然日数",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "working_days",
|
||||
"display_name": "工作日数",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "monthly_salary",
|
||||
"display_name": "月薪",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "working_days_in_month",
|
||||
"display_name": "当月应出勤",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "daily_salary",
|
||||
"display_name": "日薪",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "deduction_amount",
|
||||
"display_name": "应扣工资",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "annual_leave_used",
|
||||
"display_name": "已抵年假",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "remaining_annual_leave",
|
||||
"display_name": "剩余年假",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "approval_level",
|
||||
"display_name": "审批层级",
|
||||
"editable": 0,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": APPROVAL_LEVEL_OPTIONS,
|
||||
},
|
||||
{
|
||||
"column_name": "status",
|
||||
"display_name": "状态",
|
||||
"editable": 0,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": STATUS_OPTIONS,
|
||||
},
|
||||
{"column_name": "params_json", "display_name": "参数(JSON)", "editable": 0, "searchable": 0},
|
||||
{"column_name": "summary", "display_name": "摘要", "editable": 0, "searchable": 1},
|
||||
{"column_name": "error_message", "display_name": "错误信息", "editable": 0, "searchable": 1},
|
||||
_ts("created_at", "创建时间"),
|
||||
_ts("updated_at", "更新时间"),
|
||||
),
|
||||
)
|
||||
|
||||
upsert_table_metadata(
|
||||
cursor,
|
||||
table_name=LEAVE_BALANCES_TABLE,
|
||||
display_name="假期余额",
|
||||
description="教职工各类假期余额(系统更新)",
|
||||
grid_help="核算后自动维护已用天数与剩余天数。",
|
||||
readonly=1,
|
||||
)
|
||||
_seed_table(
|
||||
cursor,
|
||||
LEAVE_BALANCES_TABLE,
|
||||
(
|
||||
{"column_name": "id", "display_name": "编号", "editable": 0, "searchable": 1},
|
||||
{
|
||||
"column_name": "employee_id",
|
||||
"display_name": "教职工",
|
||||
"editable": 0,
|
||||
"searchable": 1,
|
||||
"display_type": "lookup",
|
||||
"options_json": _lookup(EMPLOYEES_TABLE, "id", "name"),
|
||||
},
|
||||
{
|
||||
"column_name": "balance_type",
|
||||
"display_name": "假期类型",
|
||||
"editable": 0,
|
||||
"searchable": 1,
|
||||
"display_type": "enum",
|
||||
"options_json": BALANCE_TYPE_OPTIONS,
|
||||
},
|
||||
{
|
||||
"column_name": "total_days",
|
||||
"display_name": "总额度",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "used_days",
|
||||
"display_name": "已用",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
{
|
||||
"column_name": "remaining_days",
|
||||
"display_name": "剩余",
|
||||
"editable": 0,
|
||||
"searchable": 0,
|
||||
"display_type": "number",
|
||||
},
|
||||
_ts("created_at", "创建时间"),
|
||||
_ts("updated_at", "更新时间"),
|
||||
),
|
||||
)
|
||||
567
scripts/db/leave_repository.py
Normal file
567
scripts/db/leave_repository.py
Normal file
@@ -0,0 +1,567 @@
|
||||
"""高校人事请假考勤:业务数据访问。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from typing import Any, Optional
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from db.schema import (
|
||||
ATTENDANCE_HOLIDAYS_TABLE,
|
||||
EMPLOYEES_TABLE,
|
||||
LEAVE_BALANCES_TABLE,
|
||||
LEAVE_POLICIES_TABLE,
|
||||
LEAVE_REQUESTS_TABLE,
|
||||
)
|
||||
|
||||
|
||||
def ensure_db() -> None:
|
||||
init_db()
|
||||
|
||||
|
||||
def _row_dict(row: sqlite3.Row) -> dict[str, Any]:
|
||||
return {k: row[k] for k in row.keys()}
|
||||
|
||||
|
||||
def dumps_json(data: Any) -> str:
|
||||
return json.dumps(data, ensure_ascii=False)
|
||||
|
||||
|
||||
def loads_json(raw: Any, default: Any = None) -> Any:
|
||||
if raw is None or raw == "":
|
||||
return default if default is not None else {}
|
||||
if isinstance(raw, (dict, list)):
|
||||
return raw
|
||||
try:
|
||||
return json.loads(str(raw))
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
return default if default is not None else {}
|
||||
|
||||
|
||||
# ---------- employees ----------
|
||||
|
||||
def get_employee(employee_id: int) -> Optional[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"SELECT * FROM {EMPLOYEES_TABLE} WHERE id = ?", (employee_id,))
|
||||
row = cur.fetchone()
|
||||
return _row_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def find_employee_by_name(name: str) -> Optional[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"SELECT * FROM {EMPLOYEES_TABLE} WHERE name = ?", (name,))
|
||||
row = cur.fetchone()
|
||||
return _row_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_active_employees() -> list[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"SELECT * FROM {EMPLOYEES_TABLE} WHERE is_active = 1 ORDER BY id")
|
||||
return [_row_dict(r) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def count_employees() -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"SELECT COUNT(*) FROM {EMPLOYEES_TABLE}")
|
||||
return int(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_employee(payload: dict[str, Any]) -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
name = str(payload.get("name", "")).strip()
|
||||
if not name:
|
||||
raise ValueError("教职工姓名不能为空")
|
||||
employee_no = payload.get("employee_no")
|
||||
existing = None
|
||||
if employee_no:
|
||||
cur.execute(
|
||||
f"SELECT id FROM {EMPLOYEES_TABLE} WHERE employee_no = ?",
|
||||
(employee_no,),
|
||||
)
|
||||
existing = cur.fetchone()
|
||||
if existing is None:
|
||||
cur.execute(
|
||||
f"SELECT id FROM {EMPLOYEES_TABLE} WHERE name = ? AND "
|
||||
"(employee_no IS NULL OR employee_no = '')",
|
||||
(name,),
|
||||
)
|
||||
existing = cur.fetchone()
|
||||
if existing is not None:
|
||||
eid = int(existing[0])
|
||||
cur.execute(
|
||||
f"""UPDATE {EMPLOYEES_TABLE} SET
|
||||
name = ?, employee_no = ?, department = ?, position = ?,
|
||||
position_category = ?, join_date = ?, monthly_salary = ?,
|
||||
annual_leave_remaining = ?, is_active = ?, notes = ?,
|
||||
updated_at = unixepoch()
|
||||
WHERE id = ?""",
|
||||
(
|
||||
name,
|
||||
employee_no,
|
||||
payload.get("department"),
|
||||
payload.get("position"),
|
||||
payload.get("position_category"),
|
||||
payload.get("join_date"),
|
||||
float(payload.get("monthly_salary", 0) or 0),
|
||||
float(payload.get("annual_leave_remaining", 0) or 0),
|
||||
int(payload.get("is_active", 1)),
|
||||
payload.get("notes"),
|
||||
eid,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return eid
|
||||
cur.execute(
|
||||
f"""INSERT INTO {EMPLOYEES_TABLE} (
|
||||
name, employee_no, department, position, position_category,
|
||||
join_date, monthly_salary, annual_leave_remaining, is_active, notes
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
name,
|
||||
employee_no,
|
||||
payload.get("department"),
|
||||
payload.get("position"),
|
||||
payload.get("position_category"),
|
||||
payload.get("join_date"),
|
||||
float(payload.get("monthly_salary", 0) or 0),
|
||||
float(payload.get("annual_leave_remaining", 0) or 0),
|
||||
int(payload.get("is_active", 1)),
|
||||
payload.get("notes"),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_employee_annual_leave(employee_id: int, remaining: float) -> None:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"UPDATE {EMPLOYEES_TABLE} SET annual_leave_remaining = ?, "
|
||||
"updated_at = unixepoch() WHERE id = ?",
|
||||
(remaining, employee_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- leave_policies ----------
|
||||
|
||||
def get_policy(leave_type: str) -> Optional[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"SELECT * FROM {LEAVE_POLICIES_TABLE} WHERE leave_type = ?",
|
||||
(leave_type,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_policies() -> list[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"SELECT * FROM {LEAVE_POLICIES_TABLE} ORDER BY id")
|
||||
return [_row_dict(r) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def count_policies() -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"SELECT COUNT(*) FROM {LEAVE_POLICIES_TABLE}")
|
||||
return int(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_policy(payload: dict[str, Any]) -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
leave_type = str(payload.get("leave_type", "")).strip()
|
||||
if not leave_type:
|
||||
raise ValueError("请假类型不能为空")
|
||||
cur.execute(
|
||||
f"SELECT id FROM {LEAVE_POLICIES_TABLE} WHERE leave_type = ?",
|
||||
(leave_type,),
|
||||
)
|
||||
existing = cur.fetchone()
|
||||
if existing is not None:
|
||||
pid = int(existing[0])
|
||||
cur.execute(
|
||||
f"""UPDATE {LEAVE_POLICIES_TABLE} SET
|
||||
leave_type = ?, max_days = ?, day_basis = ?, paid_days = ?,
|
||||
partial_pay_ratio = ?, unpaid_after_days = ?,
|
||||
requires_certificate = ?, can_offset_annual = ?,
|
||||
approval_threshold_dept = ?, approval_threshold_hr = ?,
|
||||
notes = ?, updated_at = unixepoch()
|
||||
WHERE id = ?""",
|
||||
(
|
||||
leave_type,
|
||||
payload.get("max_days"),
|
||||
payload.get("day_basis", "workday"),
|
||||
float(payload.get("paid_days", 0) or 0),
|
||||
float(payload.get("partial_pay_ratio", 1.0) or 1.0),
|
||||
payload.get("unpaid_after_days"),
|
||||
int(payload.get("requires_certificate", 0)),
|
||||
int(payload.get("can_offset_annual", 0)),
|
||||
int(payload.get("approval_threshold_dept", 3)),
|
||||
int(payload.get("approval_threshold_hr", 10)),
|
||||
payload.get("notes"),
|
||||
pid,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return pid
|
||||
cur.execute(
|
||||
f"""INSERT INTO {LEAVE_POLICIES_TABLE} (
|
||||
leave_type, max_days, day_basis, paid_days, partial_pay_ratio,
|
||||
unpaid_after_days, requires_certificate, can_offset_annual,
|
||||
approval_threshold_dept, approval_threshold_hr, notes
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
leave_type,
|
||||
payload.get("max_days"),
|
||||
payload.get("day_basis", "workday"),
|
||||
float(payload.get("paid_days", 0) or 0),
|
||||
float(payload.get("partial_pay_ratio", 1.0) or 1.0),
|
||||
payload.get("unpaid_after_days"),
|
||||
int(payload.get("requires_certificate", 0)),
|
||||
int(payload.get("can_offset_annual", 0)),
|
||||
int(payload.get("approval_threshold_dept", 3)),
|
||||
int(payload.get("approval_threshold_hr", 10)),
|
||||
payload.get("notes"),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- attendance_holidays ----------
|
||||
|
||||
def list_holidays() -> list[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"SELECT * FROM {ATTENDANCE_HOLIDAYS_TABLE} ORDER BY holiday_date"
|
||||
)
|
||||
return [_row_dict(r) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def count_holidays() -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"SELECT COUNT(*) FROM {ATTENDANCE_HOLIDAYS_TABLE}")
|
||||
return int(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_holiday(payload: dict[str, Any]) -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
holiday_date = str(payload.get("holiday_date", "")).strip()
|
||||
if not holiday_date:
|
||||
raise ValueError("假日日期不能为空")
|
||||
cur.execute(
|
||||
f"SELECT id FROM {ATTENDANCE_HOLIDAYS_TABLE} WHERE holiday_date = ?",
|
||||
(holiday_date,),
|
||||
)
|
||||
existing = cur.fetchone()
|
||||
if existing is not None:
|
||||
hid = int(existing[0])
|
||||
cur.execute(
|
||||
f"""UPDATE {ATTENDANCE_HOLIDAYS_TABLE} SET
|
||||
holiday_date = ?, holiday_name = ?, holiday_type = ?,
|
||||
updated_at = unixepoch()
|
||||
WHERE id = ?""",
|
||||
(
|
||||
holiday_date,
|
||||
payload.get("holiday_name"),
|
||||
payload.get("holiday_type", "法定假日"),
|
||||
hid,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return hid
|
||||
cur.execute(
|
||||
f"""INSERT INTO {ATTENDANCE_HOLIDAYS_TABLE} (
|
||||
holiday_date, holiday_name, holiday_type
|
||||
) VALUES (?, ?, ?)""",
|
||||
(
|
||||
holiday_date,
|
||||
payload.get("holiday_name"),
|
||||
payload.get("holiday_type", "法定假日"),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- leave_requests ----------
|
||||
|
||||
def create_leave_request(payload: dict[str, Any]) -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"""INSERT INTO {LEAVE_REQUESTS_TABLE} (
|
||||
employee_id, leave_type, start_date, end_date,
|
||||
has_certificate, certificate_type, natural_days,
|
||||
working_days, monthly_salary, working_days_in_month,
|
||||
daily_salary, deduction_amount, annual_leave_used,
|
||||
remaining_annual_leave, approval_level, status,
|
||||
params_json, summary, error_message
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
int(payload.get("employee_id")),
|
||||
payload.get("leave_type"),
|
||||
payload.get("start_date"),
|
||||
payload.get("end_date"),
|
||||
int(payload.get("has_certificate", 0)),
|
||||
payload.get("certificate_type"),
|
||||
payload.get("natural_days"),
|
||||
payload.get("working_days"),
|
||||
payload.get("monthly_salary"),
|
||||
payload.get("working_days_in_month"),
|
||||
payload.get("daily_salary"),
|
||||
payload.get("deduction_amount"),
|
||||
payload.get("annual_leave_used"),
|
||||
payload.get("remaining_annual_leave"),
|
||||
payload.get("approval_level"),
|
||||
payload.get("status", "draft"),
|
||||
dumps_json(payload.get("params")) if payload.get("params") else None,
|
||||
payload.get("summary"),
|
||||
payload.get("error_message"),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_leave_request(request_id: int, **fields: Any) -> None:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
sets = []
|
||||
values: list[Any] = []
|
||||
for k, v in fields.items():
|
||||
if k == "params":
|
||||
sets.append("params_json = ?")
|
||||
values.append(dumps_json(v))
|
||||
elif k == "params_json":
|
||||
sets.append("params_json = ?")
|
||||
values.append(v)
|
||||
else:
|
||||
sets.append(f"{k} = ?")
|
||||
values.append(v)
|
||||
if not sets:
|
||||
return
|
||||
sets.append("updated_at = unixepoch()")
|
||||
values.append(request_id)
|
||||
cur.execute(
|
||||
f"UPDATE {LEAVE_REQUESTS_TABLE} SET {', '.join(sets)} WHERE id = ?",
|
||||
values,
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_request(request_id: int) -> Optional[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"SELECT * FROM {LEAVE_REQUESTS_TABLE} WHERE id = ?",
|
||||
(request_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_latest_completed_request(
|
||||
employee_id: Optional[int] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
if employee_id is not None:
|
||||
cur.execute(
|
||||
f"""SELECT * FROM {LEAVE_REQUESTS_TABLE}
|
||||
WHERE status = 'completed' AND employee_id = ?
|
||||
ORDER BY id DESC LIMIT 1""",
|
||||
(employee_id,),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
f"""SELECT * FROM {LEAVE_REQUESTS_TABLE}
|
||||
WHERE status = 'completed'
|
||||
ORDER BY id DESC LIMIT 1"""
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_requests_for_employee(employee_id: int) -> list[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"""SELECT * FROM {LEAVE_REQUESTS_TABLE}
|
||||
WHERE employee_id = ? ORDER BY id DESC""",
|
||||
(employee_id,),
|
||||
)
|
||||
return [_row_dict(r) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- leave_balances ----------
|
||||
|
||||
def get_balance(
|
||||
employee_id: int, balance_type: str
|
||||
) -> Optional[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"""SELECT * FROM {LEAVE_BALANCES_TABLE}
|
||||
WHERE employee_id = ? AND balance_type = ?""",
|
||||
(employee_id, balance_type),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_balance(payload: dict[str, Any]) -> int:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
employee_id = int(payload.get("employee_id"))
|
||||
balance_type = str(payload.get("balance_type", "")).strip()
|
||||
if not balance_type:
|
||||
raise ValueError("balance_type 不能为空")
|
||||
cur.execute(
|
||||
f"""SELECT id FROM {LEAVE_BALANCES_TABLE}
|
||||
WHERE employee_id = ? AND balance_type = ?""",
|
||||
(employee_id, balance_type),
|
||||
)
|
||||
existing = cur.fetchone()
|
||||
total_days = payload.get("total_days")
|
||||
used_days = float(payload.get("used_days", 0) or 0)
|
||||
remaining_days = payload.get("remaining_days")
|
||||
if existing is not None:
|
||||
bid = int(existing[0])
|
||||
cur.execute(
|
||||
f"""UPDATE {LEAVE_BALANCES_TABLE} SET
|
||||
total_days = ?, used_days = ?, remaining_days = ?,
|
||||
updated_at = unixepoch()
|
||||
WHERE id = ?""",
|
||||
(total_days, used_days, remaining_days, bid),
|
||||
)
|
||||
conn.commit()
|
||||
return bid
|
||||
cur.execute(
|
||||
f"""INSERT INTO {LEAVE_BALANCES_TABLE} (
|
||||
employee_id, balance_type, total_days, used_days, remaining_days
|
||||
) VALUES (?, ?, ?, ?, ?)""",
|
||||
(employee_id, balance_type, total_days, used_days, remaining_days),
|
||||
)
|
||||
conn.commit()
|
||||
return int(cur.lastrowid)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_balances_for_employee(employee_id: int) -> list[dict[str, Any]]:
|
||||
ensure_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
f"""SELECT * FROM {LEAVE_BALANCES_TABLE}
|
||||
WHERE employee_id = ? ORDER BY balance_type""",
|
||||
(employee_id,),
|
||||
)
|
||||
return [_row_dict(r) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
113
scripts/db/schema.py
Normal file
113
scripts/db/schema.py
Normal file
@@ -0,0 +1,113 @@
|
||||
"""高校人事请假考勤:业务表 DDL 与表名常量。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
EMPLOYEES_TABLE = "employees"
|
||||
LEAVE_POLICIES_TABLE = "leave_policies"
|
||||
ATTENDANCE_HOLIDAYS_TABLE = "attendance_holidays"
|
||||
LEAVE_REQUESTS_TABLE = "leave_requests"
|
||||
LEAVE_BALANCES_TABLE = "leave_balances"
|
||||
|
||||
BUSINESS_TABLES: tuple[str, ...] = (
|
||||
EMPLOYEES_TABLE,
|
||||
LEAVE_POLICIES_TABLE,
|
||||
ATTENDANCE_HOLIDAYS_TABLE,
|
||||
LEAVE_REQUESTS_TABLE,
|
||||
LEAVE_BALANCES_TABLE,
|
||||
)
|
||||
|
||||
EMPLOYEES_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS employees (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
employee_no TEXT,
|
||||
department TEXT,
|
||||
position TEXT,
|
||||
position_category TEXT,
|
||||
join_date TEXT,
|
||||
monthly_salary REAL NOT NULL DEFAULT 0,
|
||||
annual_leave_remaining REAL NOT NULL DEFAULT 0,
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
notes TEXT,
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
||||
)
|
||||
"""
|
||||
|
||||
LEAVE_POLICIES_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS leave_policies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
leave_type TEXT NOT NULL,
|
||||
max_days REAL,
|
||||
day_basis TEXT NOT NULL DEFAULT 'workday',
|
||||
paid_days REAL NOT NULL DEFAULT 0,
|
||||
partial_pay_ratio REAL NOT NULL DEFAULT 1.0,
|
||||
unpaid_after_days REAL,
|
||||
requires_certificate INTEGER NOT NULL DEFAULT 0,
|
||||
can_offset_annual INTEGER NOT NULL DEFAULT 0,
|
||||
approval_threshold_dept INTEGER NOT NULL DEFAULT 3,
|
||||
approval_threshold_hr INTEGER NOT NULL DEFAULT 10,
|
||||
notes TEXT,
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
||||
)
|
||||
"""
|
||||
|
||||
ATTENDANCE_HOLIDAYS_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS attendance_holidays (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
holiday_date TEXT NOT NULL,
|
||||
holiday_name TEXT,
|
||||
holiday_type TEXT NOT NULL DEFAULT '法定假日',
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
||||
)
|
||||
"""
|
||||
|
||||
LEAVE_REQUESTS_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS leave_requests (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
employee_id INTEGER NOT NULL,
|
||||
leave_type TEXT NOT NULL,
|
||||
start_date TEXT NOT NULL,
|
||||
end_date TEXT NOT NULL,
|
||||
has_certificate INTEGER NOT NULL DEFAULT 0,
|
||||
certificate_type TEXT,
|
||||
natural_days INTEGER,
|
||||
working_days INTEGER,
|
||||
monthly_salary REAL,
|
||||
working_days_in_month INTEGER,
|
||||
daily_salary REAL,
|
||||
deduction_amount REAL,
|
||||
annual_leave_used REAL,
|
||||
remaining_annual_leave REAL,
|
||||
approval_level TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'draft',
|
||||
params_json TEXT,
|
||||
summary TEXT,
|
||||
error_message TEXT,
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
||||
)
|
||||
"""
|
||||
|
||||
LEAVE_BALANCES_DDL = """
|
||||
CREATE TABLE IF NOT EXISTS leave_balances (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
employee_id INTEGER NOT NULL,
|
||||
balance_type TEXT NOT NULL,
|
||||
total_days REAL,
|
||||
used_days REAL NOT NULL DEFAULT 0,
|
||||
remaining_days REAL,
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
||||
)
|
||||
"""
|
||||
|
||||
TABLE_DDL: tuple[tuple[str, str], ...] = (
|
||||
(EMPLOYEES_TABLE, EMPLOYEES_DDL),
|
||||
(LEAVE_POLICIES_TABLE, LEAVE_POLICIES_DDL),
|
||||
(ATTENDANCE_HOLIDAYS_TABLE, ATTENDANCE_HOLIDAYS_DDL),
|
||||
(LEAVE_REQUESTS_TABLE, LEAVE_REQUESTS_DDL),
|
||||
(LEAVE_BALANCES_TABLE, LEAVE_BALANCES_DDL),
|
||||
)
|
||||
50
scripts/db/timestamp_columns.py
Normal file
50
scripts/db/timestamp_columns.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""标准时间字段:Unix 秒级时间戳、默认值与 updated_at 自动维护。
|
||||
|
||||
业务表若包含 created_at / updated_at,在 CREATE TABLE 后调用
|
||||
``init_updated_at_trigger(cursor, table_name)``。模板默认不建业务表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
STANDARD_TIMESTAMP_COLUMNS = frozenset({"created_at", "updated_at"})
|
||||
DATETIME_UNIX_SECONDS = "datetime_unix_seconds"
|
||||
|
||||
|
||||
def updated_at_trigger_name(table_name: str) -> str:
|
||||
return f"{table_name}_set_updated_at"
|
||||
|
||||
|
||||
def _quote_identifier(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def init_updated_at_trigger(cursor, table_name: str) -> None:
|
||||
"""幂等创建 {table}_set_updated_at:业务字段 UPDATE 后刷新 updated_at。"""
|
||||
trigger = updated_at_trigger_name(table_name)
|
||||
quoted = _quote_identifier(table_name)
|
||||
quoted_trigger = _quote_identifier(trigger)
|
||||
cursor.execute(
|
||||
f"""
|
||||
CREATE TRIGGER IF NOT EXISTS {quoted_trigger}
|
||||
AFTER UPDATE ON {quoted}
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
UPDATE {quoted}
|
||||
SET updated_at = unixepoch()
|
||||
WHERE id = NEW.id AND updated_at = OLD.updated_at;
|
||||
END
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def has_updated_at_trigger(cursor, table_name: str) -> bool:
|
||||
trigger_name = updated_at_trigger_name(table_name)
|
||||
cursor.execute(
|
||||
"""
|
||||
SELECT 1 FROM sqlite_master
|
||||
WHERE type = 'trigger' AND name = ? AND tbl_name = ?
|
||||
LIMIT 1
|
||||
""",
|
||||
(trigger_name, table_name),
|
||||
)
|
||||
return cursor.fetchone() is not None
|
||||
38
scripts/main.py
Normal file
38
scripts/main.py
Normal file
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
skill-template CLI 入口。
|
||||
|
||||
复制为新技能后,请修改注释与常量,但保留当前分层结构:
|
||||
cli(argv)→ service(业务编排)→ db(持久化)→ util(通用工具)。
|
||||
|
||||
jiangchang_skill_core 来自宿主共享 Python runtime 安装的 jiangchang-platform-kit,
|
||||
不在技能仓库内 vendored。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
if sys.platform == "win32":
|
||||
import io
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
|
||||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
|
||||
|
||||
_scripts_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
if _scripts_dir not in sys.path:
|
||||
sys.path.insert(0, _scripts_dir)
|
||||
|
||||
from jiangchang_skill_core.runtime_env import apply_cli_local_defaults
|
||||
|
||||
apply_cli_local_defaults()
|
||||
|
||||
from util.config_bootstrap import bootstrap_skill_config
|
||||
|
||||
bootstrap_skill_config()
|
||||
|
||||
from cli.app import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
179
scripts/service/employee_import_service.py
Normal file
179
scripts/service/employee_import_service.py
Normal 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
|
||||
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
|
||||
365
scripts/service/leave_service.py
Normal file
365
scripts/service/leave_service.py
Normal 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
|
||||
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, 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', '')}"
|
||||
)
|
||||
285
scripts/service/task_service.py
Normal file
285
scripts/service/task_service.py
Normal 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
|
||||
12
scripts/util/argparse_zh.py
Normal file
12
scripts/util/argparse_zh.py
Normal file
@@ -0,0 +1,12 @@
|
||||
"""argparse 中文错误说明。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
|
||||
class ZhArgumentParser(argparse.ArgumentParser):
|
||||
def error(self, message: str) -> None:
|
||||
print(f"参数错误:{message}\n请执行:python main.py -h 查看帮助", file=sys.stderr)
|
||||
self.exit(2)
|
||||
19
scripts/util/config_bootstrap.py
Normal file
19
scripts/util/config_bootstrap.py
Normal file
@@ -0,0 +1,19 @@
|
||||
"""技能配置初始化:.env.example 落盘与用户 .env 缺失项合并。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from jiangchang_skill_core import config
|
||||
|
||||
from util.constants import SKILL_SLUG, SKILL_VERSION
|
||||
from util.runtime_paths import get_skill_root
|
||||
|
||||
|
||||
def bootstrap_skill_config() -> str:
|
||||
"""确保用户数据目录 .env 存在,并追加 .env.example 中的新配置项。"""
|
||||
example_path = os.path.join(get_skill_root(), ".env.example")
|
||||
env_path = config.ensure_env_file(SKILL_SLUG, example_path)
|
||||
comment = f"{SKILL_SLUG} v{SKILL_VERSION}" if SKILL_VERSION else None
|
||||
config.merge_missing_env_keys(example_path, env_path, comment_skill=comment)
|
||||
return env_path
|
||||
6
scripts/util/constants.py
Normal file
6
scripts/util/constants.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""技能标识、版本与平台公共库约束(复制后请修改 slug/version/logger)。"""
|
||||
|
||||
SKILL_SLUG = "process-leave-attendance-default"
|
||||
SKILL_VERSION = "1.0.1"
|
||||
LOG_LOGGER_NAME = "openclaw.skill.process_leave_attendance_default"
|
||||
PLATFORM_KIT_MIN_VERSION = "1.2.11"
|
||||
21
scripts/util/logging_config.py
Normal file
21
scripts/util/logging_config.py
Normal file
@@ -0,0 +1,21 @@
|
||||
"""Re-export unified logging (implementation: jiangchang_skill_core.unified_logging)."""
|
||||
|
||||
from jiangchang_skill_core.unified_logging import (
|
||||
attach_unified_file_handler,
|
||||
ensure_trace_for_process,
|
||||
get_skill_log_file_path,
|
||||
get_skill_logger,
|
||||
get_unified_logs_dir,
|
||||
setup_skill_logging,
|
||||
subprocess_env_with_trace,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"attach_unified_file_handler",
|
||||
"ensure_trace_for_process",
|
||||
"get_skill_log_file_path",
|
||||
"get_skill_logger",
|
||||
"get_unified_logs_dir",
|
||||
"setup_skill_logging",
|
||||
"subprocess_env_with_trace",
|
||||
]
|
||||
155
scripts/util/runtime_paths.py
Normal file
155
scripts/util/runtime_paths.py
Normal file
@@ -0,0 +1,155 @@
|
||||
"""数据根、技能目录、兄弟技能根路径与用户数据子目录解析。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from jiangchang_skill_core.runtime_env import get_data_root, get_sibling_skills_root, get_user_id
|
||||
|
||||
from util.constants import SKILL_SLUG
|
||||
|
||||
_SCRIPTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# 用户可见的上行/下行目录(数据管理「输入/输出」文件浏览器)
|
||||
STANDARD_SUBDIR_INPUT = "input"
|
||||
STANDARD_SUBDIR_OUTPUT = "output"
|
||||
|
||||
# 宿主扫描的 HTML 报告页(数据管理侧栏 htmlPages,非 input/output 文件浏览器)
|
||||
STANDARD_SUBDIR_HTML = "html"
|
||||
|
||||
# 内部/可选目录(不上侧栏)
|
||||
STANDARD_SUBDIR_UPLOADS = "uploads"
|
||||
STANDARD_SUBDIR_CACHE = "cache"
|
||||
STANDARD_SUBDIR_TEMP = "temp"
|
||||
STANDARD_SUBDIR_RPA_ARTIFACTS = "rpa-artifacts"
|
||||
STANDARD_SUBDIR_VIDEOS = "videos"
|
||||
|
||||
CONFIG_KEY_INPUT_DIR = "SKILL_INPUT_DIR"
|
||||
CONFIG_KEY_OUTPUT_DIR = "SKILL_OUTPUT_DIR"
|
||||
CONFIG_KEY_UPLOAD_DIR = "SKILL_UPLOAD_DIR"
|
||||
CONFIG_KEY_CACHE_DIR = "SKILL_CACHE_DIR"
|
||||
CONFIG_KEY_TEMP_DIR = "SKILL_TEMP_DIR"
|
||||
|
||||
|
||||
def get_skill_root() -> str:
|
||||
return os.path.dirname(_SCRIPTS_DIR)
|
||||
|
||||
|
||||
def get_openclaw_root() -> str:
|
||||
return get_sibling_skills_root(_SCRIPTS_DIR)
|
||||
|
||||
|
||||
def get_skills_root() -> str:
|
||||
return get_sibling_skills_root(_SCRIPTS_DIR)
|
||||
|
||||
|
||||
def get_skill_data_dir() -> str:
|
||||
path = os.path.join(get_data_root(), get_user_id(), SKILL_SLUG)
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def get_db_path(filename: str | None = None) -> str:
|
||||
name = filename or f"{SKILL_SLUG}.db"
|
||||
return os.path.join(get_skill_data_dir(), name)
|
||||
|
||||
|
||||
def _normalize_subdir(value: str) -> str:
|
||||
cleaned = value.strip().strip("/\\")
|
||||
if not cleaned or cleaned.startswith(".."):
|
||||
raise ValueError(f"invalid skill data subdir: {value!r}")
|
||||
return cleaned.replace("/", os.sep).replace("\\", os.sep)
|
||||
|
||||
|
||||
def resolve_data_path(
|
||||
config_key: str | None,
|
||||
default_subdir: str,
|
||||
*,
|
||||
create: bool = True,
|
||||
) -> str:
|
||||
"""解析技能拥有路径:空配置 → 数据目录下 default_subdir;相对 → 相对数据目录;绝对 → 原样。"""
|
||||
from jiangchang_skill_core import config
|
||||
|
||||
base = get_skill_data_dir()
|
||||
raw = (config.get(config_key) or "").strip() if config_key else ""
|
||||
if not raw:
|
||||
path = os.path.join(base, _normalize_subdir(default_subdir))
|
||||
elif os.path.isabs(raw):
|
||||
path = os.path.abspath(os.path.expanduser(raw))
|
||||
else:
|
||||
path = os.path.join(base, _normalize_subdir(raw))
|
||||
|
||||
if create:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def resolve_input_path(raw_path: str, *, create_parent: bool = False) -> str:
|
||||
"""解析 CLI 输入路径:绝对路径原样;相对路径相对 {skill_data_dir}/input/。"""
|
||||
text = (raw_path or "").strip()
|
||||
if not text:
|
||||
return text
|
||||
expanded = os.path.expanduser(text)
|
||||
if os.path.isabs(expanded):
|
||||
return os.path.abspath(expanded)
|
||||
input_dir = get_input_dir(create=create_parent)
|
||||
return os.path.abspath(os.path.join(input_dir, os.path.normpath(expanded)))
|
||||
|
||||
|
||||
def get_input_dir(*, create: bool = True) -> str:
|
||||
"""上行:用户/Agent 放入的待处理文件(清单、CSV、产品表等)。"""
|
||||
return resolve_data_path(CONFIG_KEY_INPUT_DIR, STANDARD_SUBDIR_INPUT, create=create)
|
||||
|
||||
|
||||
def get_output_dir(*, create: bool = True) -> str:
|
||||
"""下行:技能/宿主交给用户拿走的文件(视频、报表、导出 CSV 等)。"""
|
||||
return resolve_data_path(CONFIG_KEY_OUTPUT_DIR, STANDARD_SUBDIR_OUTPUT, create=create)
|
||||
|
||||
|
||||
def get_uploads_dir(*, create: bool = True) -> str:
|
||||
return resolve_data_path(CONFIG_KEY_UPLOAD_DIR, STANDARD_SUBDIR_UPLOADS, create=create)
|
||||
|
||||
|
||||
def get_cache_dir(*, create: bool = True) -> str:
|
||||
return resolve_data_path(CONFIG_KEY_CACHE_DIR, STANDARD_SUBDIR_CACHE, create=create)
|
||||
|
||||
|
||||
def get_temp_dir(*, create: bool = True) -> str:
|
||||
return resolve_data_path(CONFIG_KEY_TEMP_DIR, STANDARD_SUBDIR_TEMP, create=create)
|
||||
|
||||
|
||||
def get_rpa_artifacts_dir(batch_id: str, *, create: bool = True) -> str:
|
||||
batch = (batch_id or "").strip() or "default"
|
||||
path = os.path.join(get_skill_data_dir(), STANDARD_SUBDIR_RPA_ARTIFACTS, batch)
|
||||
if create:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def get_videos_dir(*, create: bool = True) -> str:
|
||||
path = os.path.join(get_skill_data_dir(), STANDARD_SUBDIR_VIDEOS)
|
||||
if create:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def get_html_dir(*, create: bool = True) -> str:
|
||||
"""HTML 报告页目录:宿主扫描 `{skill_data}/html/*.html`(一层、非递归)。"""
|
||||
path = os.path.join(get_skill_data_dir(), STANDARD_SUBDIR_HTML)
|
||||
if create:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def list_resolved_data_paths() -> dict[str, str]:
|
||||
"""供 health / config-path 输出已解析的数据子目录(不创建目录)。"""
|
||||
return {
|
||||
"skill_data_dir": get_skill_data_dir(),
|
||||
"input_dir": get_input_dir(create=False),
|
||||
"output_dir": get_output_dir(create=False),
|
||||
"html_dir": get_html_dir(create=False),
|
||||
"uploads_dir": get_uploads_dir(create=False),
|
||||
"cache_dir": get_cache_dir(create=False),
|
||||
"temp_dir": get_temp_dir(create=False),
|
||||
"videos_dir": get_videos_dir(create=False),
|
||||
}
|
||||
227
scripts/util/slug_naming.py
Normal file
227
scripts/util/slug_naming.py
Normal file
@@ -0,0 +1,227 @@
|
||||
"""技能 slug 语义校验(verb-noun-platform 规范,见 development/NAMING.md)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
_KEBAB_SLUG = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||
_MAX_SLUG_LENGTH = 48
|
||||
_MIN_SEGMENTS = 3
|
||||
_MAX_SEGMENTS = 5
|
||||
_MAX_NOUN_SEGMENTS = 3
|
||||
|
||||
_SKILL_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
_NAMING_DIR = os.path.join(_SKILL_ROOT, "assets", "naming")
|
||||
|
||||
_BUILTIN_VERBS = frozenset(
|
||||
{
|
||||
"scrape",
|
||||
"receive",
|
||||
"download",
|
||||
"export",
|
||||
"add",
|
||||
"fill",
|
||||
"enter",
|
||||
"bind",
|
||||
"withdraw",
|
||||
"reconcile",
|
||||
"verify",
|
||||
"submit",
|
||||
"query",
|
||||
"process",
|
||||
"reply",
|
||||
"generate",
|
||||
"draft",
|
||||
"review",
|
||||
"confirm",
|
||||
"track",
|
||||
"upload",
|
||||
"match",
|
||||
"triage",
|
||||
"ship",
|
||||
"reprice",
|
||||
}
|
||||
)
|
||||
_BUILTIN_PLATFORMS = frozenset(
|
||||
{
|
||||
"amazon",
|
||||
"shopee",
|
||||
"xinghang",
|
||||
"alibaba",
|
||||
"kingdee",
|
||||
"icbc",
|
||||
"pingpong",
|
||||
"worldfirst",
|
||||
"paypal",
|
||||
"lianlian",
|
||||
"single-window",
|
||||
"export-rebate",
|
||||
"etax",
|
||||
}
|
||||
)
|
||||
_BUILTIN_SCOPES = frozenset({"all", "batch", "multi", "default"})
|
||||
|
||||
LEGACY_EXEMPT_SLUGS: frozenset[str] = frozenset(
|
||||
{
|
||||
"account-manager",
|
||||
"skill-template",
|
||||
"process-leave-attendance-default",
|
||||
"process_leave_attendance_default",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def load_wordlist(filename: str) -> frozenset[str]:
|
||||
"""从 assets/naming/{filename} 加载词表;文件不存在时 fallback 内置集合。"""
|
||||
fallbacks = {
|
||||
"verbs.txt": _BUILTIN_VERBS,
|
||||
"platforms.txt": _BUILTIN_PLATFORMS,
|
||||
"scopes.txt": _BUILTIN_SCOPES,
|
||||
}
|
||||
fallback = fallbacks.get(filename, frozenset())
|
||||
path = os.path.join(_NAMING_DIR, filename)
|
||||
if not os.path.isfile(path):
|
||||
return fallback
|
||||
words: set[str] = set()
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
word = line.strip()
|
||||
if word and not word.startswith("#"):
|
||||
words.add(word)
|
||||
return frozenset(words) if words else fallback
|
||||
|
||||
|
||||
def parse_slug_segments(slug: str) -> list[str]:
|
||||
"""按 '-' 分割;非法字符由上层 kebab 校验处理。"""
|
||||
slug = slug.strip()
|
||||
if not slug:
|
||||
return []
|
||||
return slug.split("-")
|
||||
|
||||
|
||||
def _match_platform_suffix(
|
||||
segments: list[str],
|
||||
platforms: frozenset[str],
|
||||
) -> tuple[str, int] | None:
|
||||
"""返回 (platform_name, platform_part_count) 或 None。"""
|
||||
for platform in sorted(platforms, key=lambda item: (-item.count("-"), item)):
|
||||
parts = platform.split("-")
|
||||
part_count = len(parts)
|
||||
if len(segments) < part_count + 2:
|
||||
continue
|
||||
if segments[-part_count:] == parts:
|
||||
return platform, part_count
|
||||
return None
|
||||
|
||||
|
||||
def classify_slug_form(segments: list[str], *, slug: str = "") -> str:
|
||||
"""
|
||||
返回: 'legacy_exempt' | 'standard' | 'scope' | 'invalid'
|
||||
|
||||
- legacy_exempt: slug in LEGACY_EXEMPT_SLUGS
|
||||
- standard: 末段匹配 platforms, 首段 in verbs, 3<=len<=5
|
||||
- scope: 末段 in scopes, 首段 in verbs, 3<=len<=5
|
||||
- invalid: 其他
|
||||
"""
|
||||
if slug in LEGACY_EXEMPT_SLUGS:
|
||||
return "legacy_exempt"
|
||||
|
||||
if not segments or not (_MIN_SEGMENTS <= len(segments) <= _MAX_SEGMENTS):
|
||||
return "invalid"
|
||||
|
||||
verbs = load_wordlist("verbs.txt")
|
||||
platforms = load_wordlist("platforms.txt")
|
||||
scopes = load_wordlist("scopes.txt")
|
||||
|
||||
if segments[0] not in verbs:
|
||||
return "invalid"
|
||||
|
||||
if segments[-1] in scopes:
|
||||
return "scope"
|
||||
|
||||
if _match_platform_suffix(segments, platforms) is not None:
|
||||
return "standard"
|
||||
|
||||
return "invalid"
|
||||
|
||||
|
||||
def validate_slug_semantics(
|
||||
slug: str,
|
||||
*,
|
||||
strict: bool = True,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""返回 (errors, warnings)。"""
|
||||
slug = slug.strip()
|
||||
if slug in LEGACY_EXEMPT_SLUGS:
|
||||
return [], []
|
||||
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
if not _KEBAB_SLUG.fullmatch(slug):
|
||||
msg = f"slug 必须为 kebab-case(小写字母、数字、连字符):{slug!r}"
|
||||
(errors if strict else warnings).append(msg)
|
||||
return errors, warnings
|
||||
|
||||
if len(slug) > _MAX_SLUG_LENGTH:
|
||||
msg = f"slug 长度不得超过 {_MAX_SLUG_LENGTH} 字符(当前 {len(slug)}):{slug!r}"
|
||||
(errors if strict else warnings).append(msg)
|
||||
|
||||
segments = parse_slug_segments(slug)
|
||||
segment_count = len(segments)
|
||||
|
||||
if segment_count < _MIN_SEGMENTS:
|
||||
msg = (
|
||||
f"slug 段数应为 {_MIN_SEGMENTS}~{_MAX_SEGMENTS}(verb-noun-platform),"
|
||||
f"当前为 {segment_count} 段:{slug!r};新技能禁止 2 段无平台形态(如 reconcile-finance)"
|
||||
)
|
||||
(errors if strict else warnings).append(msg)
|
||||
return errors, warnings
|
||||
|
||||
if segment_count > _MAX_SEGMENTS:
|
||||
msg = f"slug 段数不得超过 {_MAX_SEGMENTS}(当前 {segment_count}):{slug!r}"
|
||||
(errors if strict else warnings).append(msg)
|
||||
|
||||
verbs = load_wordlist("verbs.txt")
|
||||
platforms = load_wordlist("platforms.txt")
|
||||
scopes = load_wordlist("scopes.txt")
|
||||
|
||||
if segments[0] in platforms and segments[0] not in verbs:
|
||||
msg = f"平台名不应放在 slug 最前:{slug!r}(应为 verb-noun-platform)"
|
||||
(errors if strict else warnings).append(msg)
|
||||
|
||||
if segments[0] not in verbs:
|
||||
msg = f"slug 首段应为动词白名单中的词:{segments[0]!r}(slug={slug!r})"
|
||||
(errors if strict else warnings).append(msg)
|
||||
|
||||
form = classify_slug_form(segments, slug=slug)
|
||||
if form == "scope":
|
||||
if segments[-1] not in scopes:
|
||||
msg = f"slug 末段应为 scope 白名单中的词:{segments[-1]!r}(slug={slug!r})"
|
||||
(errors if strict else warnings).append(msg)
|
||||
noun_count = segment_count - 2
|
||||
elif form == "standard":
|
||||
platform_match = _match_platform_suffix(segments, platforms)
|
||||
if platform_match is None:
|
||||
msg = f"slug 末段应匹配平台白名单:{slug!r}"
|
||||
(errors if strict else warnings).append(msg)
|
||||
noun_count = 0
|
||||
else:
|
||||
_platform_name, platform_part_count = platform_match
|
||||
noun_count = segment_count - 1 - platform_part_count
|
||||
else:
|
||||
if segment_count >= _MIN_SEGMENTS:
|
||||
if segments[-1] not in scopes:
|
||||
platform_match = _match_platform_suffix(segments, platforms)
|
||||
if platform_match is None:
|
||||
msg = f"slug 末段应匹配平台或 scope 白名单:{slug!r}"
|
||||
(errors if strict else warnings).append(msg)
|
||||
noun_count = 0
|
||||
|
||||
if noun_count > _MAX_NOUN_SEGMENTS:
|
||||
warnings.append(
|
||||
f"slug 中间名词段建议不超过 {_MAX_NOUN_SEGMENTS} 个词(当前 {noun_count}):{slug!r}"
|
||||
)
|
||||
|
||||
return errors, warnings
|
||||
20
scripts/util/timeutil.py
Normal file
20
scripts/util/timeutil.py
Normal file
@@ -0,0 +1,20 @@
|
||||
"""时间戳与 ISO 展示。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def now_unix() -> int:
|
||||
return int(time.time())
|
||||
|
||||
|
||||
def unix_to_iso(ts: Optional[int]) -> Optional[str]:
|
||||
if ts is None:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromtimestamp(int(ts)).isoformat(timespec="seconds")
|
||||
except (ValueError, OSError, OverflowError):
|
||||
return None
|
||||
Reference in New Issue
Block a user