v1.1.0: 实现核心业务逻辑(扫描/任务书/派发/状态机)
新增(scripts/ 分层完整实现):
- scripts/util/{constants,date_util,runtime_paths,logging_setup}.py
- scripts/db/{connection,seed_data,repository}.py(SQLite + 5 张表 + 50 份样例合同)
- scripts/service/{scanner,task_generator,dispatcher,html_renderer}.py
- scripts/cli/app.py(argparse 子命令)
- scripts/templates/task.html.j2(Jinja2 渲染,无 jinja2 时降级到 str.replace)
- examples/{contracts_sample,performance_sample}.csv(本地样例数据)
修改:
- scripts/main.py:argparse + jiangchang_skill_core 降级
- SKILL.md:version 1.0.1 → 1.1.0
- CHANGELOG.md:加 v1.1.0 条目
- .env.example:加 DB_PATH / HTML_OUTPUT_DIR / JIANGCHANG_DATA_DIR
本地验证(9 个 CLI 命令全部 exit code = 0):
- health / version / config-path / init-db:基础 4 命令
- scan-expiring-contracts --thresholds 90,60,30:42 份可续聘 → 红 10 / 橙 10 / 黄 10,生成 30 任务
- render-html:写 output/<task_id>.html(4.9 KB)
- generate-renewal-task:单份合同任务书生成
- mark-contract-renewed:状态机更新 + 关闭 open alerts
- dispatch-task-notice:按单位/月份派发 payload(dry-run 模式)
业务规则(AI 续聘建议本地版,规则顺序判断):
1. 师德 < 60 → non_renew
2. 近 3 年考核有不合格(< 60)→ observe
3. 全部 >= 80 且逐年上升 → renew
4. 其他 → observe
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
134
scripts/db/connection.py
Normal file
134
scripts/db/connection.py
Normal file
@@ -0,0 +1,134 @@
|
||||
"""SQLite 连接 + DDL 定义 + init_db()。
|
||||
|
||||
5 张表:
|
||||
- contracts: 合同台账
|
||||
- performance_records: 近 3 年业绩记录
|
||||
- alerts: 预警记录
|
||||
- renewal_tasks: 续聘任务
|
||||
- dispatch_log: 派发日志
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from util.runtime_paths import ensure_dirs, get_db_path
|
||||
|
||||
# DDL:所有 IF NOT EXISTS,幂等可重入
|
||||
DDL_STATEMENTS: tuple[str, ...] = (
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS contracts (
|
||||
contract_id TEXT PRIMARY KEY,
|
||||
employee_id TEXT NOT NULL,
|
||||
teacher_name TEXT NOT NULL,
|
||||
unit_id TEXT NOT NULL,
|
||||
unit_name TEXT NOT NULL,
|
||||
position TEXT NOT NULL,
|
||||
contract_type TEXT NOT NULL,
|
||||
contract_start TEXT NOT NULL,
|
||||
contract_end TEXT NOT NULL,
|
||||
trial_period_end TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT '可续聘',
|
||||
last_material_id TEXT,
|
||||
renewed_at TEXT
|
||||
);
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS performance_records (
|
||||
record_id TEXT PRIMARY KEY,
|
||||
contract_id TEXT NOT NULL,
|
||||
year INTEGER NOT NULL,
|
||||
performance_score REAL NOT NULL,
|
||||
moral_teaching_score REAL NOT NULL,
|
||||
research_score REAL NOT NULL,
|
||||
teaching_score REAL NOT NULL,
|
||||
FOREIGN KEY (contract_id) REFERENCES contracts(contract_id)
|
||||
);
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS idx_perf_contract ON performance_records(contract_id);",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS alerts (
|
||||
alert_id TEXT PRIMARY KEY,
|
||||
contract_id TEXT NOT NULL,
|
||||
alert_level TEXT NOT NULL,
|
||||
days_to_expire INTEGER NOT NULL,
|
||||
scan_id TEXT NOT NULL,
|
||||
generated_at TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'open',
|
||||
FOREIGN KEY (contract_id) REFERENCES contracts(contract_id)
|
||||
);
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS idx_alerts_contract ON alerts(contract_id);",
|
||||
"CREATE INDEX IF NOT EXISTS idx_alerts_status ON alerts(status);",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS renewal_tasks (
|
||||
task_id TEXT PRIMARY KEY,
|
||||
contract_id TEXT NOT NULL,
|
||||
alert_id TEXT,
|
||||
ai_suggestion TEXT NOT NULL,
|
||||
suggestion_reason TEXT NOT NULL,
|
||||
performance_summary TEXT NOT NULL,
|
||||
materials_checklist TEXT NOT NULL,
|
||||
generated_at TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
FOREIGN KEY (contract_id) REFERENCES contracts(contract_id),
|
||||
FOREIGN KEY (alert_id) REFERENCES alerts(alert_id)
|
||||
);
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS idx_tasks_contract ON renewal_tasks(contract_id);",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS dispatch_log (
|
||||
log_id TEXT PRIMARY KEY,
|
||||
unit_id TEXT NOT NULL,
|
||||
month TEXT NOT NULL,
|
||||
task_ids TEXT NOT NULL,
|
||||
dispatched_at TEXT NOT NULL,
|
||||
payload_path TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'dry_run'
|
||||
);
|
||||
""",
|
||||
"CREATE INDEX IF NOT EXISTS idx_dispatch_unit_month ON dispatch_log(unit_id, month);",
|
||||
)
|
||||
|
||||
|
||||
def get_connection(db_path: Path | None = None) -> sqlite3.Connection:
|
||||
"""获取 SQLite 连接。"""
|
||||
ensure_dirs()
|
||||
path = db_path or get_db_path()
|
||||
conn = sqlite3.connect(str(path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA foreign_keys = ON;")
|
||||
return conn
|
||||
|
||||
|
||||
def init_db(db_path: Path | None = None) -> dict[str, int]:
|
||||
"""建表 + 加载种子数据。返回表行数 dict。"""
|
||||
ensure_dirs()
|
||||
conn = get_connection(db_path)
|
||||
try:
|
||||
for ddl in DDL_STATEMENTS:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
|
||||
# 加载种子(如果 contracts 表为空)
|
||||
from db.seed_data import load_seed_if_empty
|
||||
|
||||
load_seed_if_empty(conn)
|
||||
|
||||
# 统计
|
||||
counts = {
|
||||
"contracts": conn.execute("SELECT COUNT(*) AS n FROM contracts").fetchone()["n"],
|
||||
"performance_records": conn.execute("SELECT COUNT(*) AS n FROM performance_records").fetchone()["n"],
|
||||
"alerts": conn.execute("SELECT COUNT(*) AS n FROM alerts").fetchone()["n"],
|
||||
"renewal_tasks": conn.execute("SELECT COUNT(*) AS n FROM renewal_tasks").fetchone()["n"],
|
||||
"dispatch_log": conn.execute("SELECT COUNT(*) AS n FROM dispatch_log").fetchone()["n"],
|
||||
}
|
||||
return counts
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def table_names() -> Iterable[str]:
|
||||
return ("contracts", "performance_records", "alerts", "renewal_tasks", "dispatch_log")
|
||||
195
scripts/db/repository.py
Normal file
195
scripts/db/repository.py
Normal file
@@ -0,0 +1,195 @@
|
||||
"""CRUD 仓储:contracts / performance_records / alerts / renewal_tasks / dispatch_log。
|
||||
|
||||
所有方法接收一个外部传入的 sqlite3.Connection,调用方负责事务边界。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
# ---------- contracts ----------
|
||||
|
||||
def list_active_contracts(conn: sqlite3.Connection) -> list[sqlite3.Row]:
|
||||
"""列出 status='可续聘' 的合同。"""
|
||||
return conn.execute(
|
||||
"SELECT * FROM contracts WHERE status = '可续聘' ORDER BY contract_end ASC"
|
||||
).fetchall()
|
||||
|
||||
|
||||
def get_contract(conn: sqlite3.Connection, contract_id: str) -> sqlite3.Row | None:
|
||||
return conn.execute(
|
||||
"SELECT * FROM contracts WHERE contract_id = ?", (contract_id,)
|
||||
).fetchone()
|
||||
|
||||
|
||||
def update_contract_status(
|
||||
conn: sqlite3.Connection,
|
||||
contract_id: str,
|
||||
status: str,
|
||||
material_id: str | None = None,
|
||||
) -> int:
|
||||
"""更新合同状态。material_id 仅在 status='已续签' 时写入。"""
|
||||
renewed_at = datetime.now().isoformat(timespec="seconds") if status == "已续签" else None
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE contracts
|
||||
SET status = ?,
|
||||
last_material_id = COALESCE(?, last_material_id),
|
||||
renewed_at = COALESCE(?, renewed_at)
|
||||
WHERE contract_id = ?
|
||||
""",
|
||||
(status, material_id, renewed_at, contract_id),
|
||||
)
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
# ---------- performance ----------
|
||||
|
||||
def list_performance_by_contract(
|
||||
conn: sqlite3.Connection, contract_id: str
|
||||
) -> list[sqlite3.Row]:
|
||||
"""某合同的业绩记录,按年份升序。"""
|
||||
return conn.execute(
|
||||
"SELECT * FROM performance_records WHERE contract_id = ? ORDER BY year ASC",
|
||||
(contract_id,),
|
||||
).fetchall()
|
||||
|
||||
|
||||
# ---------- alerts ----------
|
||||
|
||||
def insert_alert(
|
||||
conn: sqlite3.Connection,
|
||||
alert_id: str,
|
||||
contract_id: str,
|
||||
level: str,
|
||||
days_to_expire: int,
|
||||
scan_id: str,
|
||||
) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO alerts
|
||||
(alert_id, contract_id, alert_level, days_to_expire, scan_id, generated_at, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'open')
|
||||
""",
|
||||
(
|
||||
alert_id,
|
||||
contract_id,
|
||||
level,
|
||||
days_to_expire,
|
||||
scan_id,
|
||||
datetime.now().isoformat(timespec="seconds"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def close_open_alerts_for_contract(conn: sqlite3.Connection, contract_id: str) -> int:
|
||||
"""将某合同所有 open 状态的 alerts 关闭(关联 '已续签' 等终态)。"""
|
||||
cur = conn.execute(
|
||||
"UPDATE alerts SET status = 'closed' WHERE contract_id = ? AND status = 'open'",
|
||||
(contract_id,),
|
||||
)
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
def list_open_alerts_by_unit_month(
|
||||
conn: sqlite3.Connection, unit_id: str, month: str
|
||||
) -> list[sqlite3.Row]:
|
||||
"""按单位/月份列出关联合同的 open alerts(用于派发汇总)。"""
|
||||
sql = """
|
||||
SELECT a.alert_id, a.contract_id, a.alert_level, a.days_to_expire,
|
||||
c.contract_end, c.teacher_name, c.unit_name
|
||||
FROM alerts a
|
||||
JOIN contracts c ON c.contract_id = a.contract_id
|
||||
WHERE a.status = 'open'
|
||||
AND c.unit_id = ?
|
||||
"""
|
||||
params: list[Any] = [unit_id]
|
||||
if month:
|
||||
sql += " AND substr(c.contract_end, 1, 7) = ?"
|
||||
params.append(month)
|
||||
sql += " ORDER BY c.contract_end ASC"
|
||||
return conn.execute(sql, params).fetchall()
|
||||
|
||||
|
||||
# ---------- renewal_tasks ----------
|
||||
|
||||
def insert_task(
|
||||
conn: sqlite3.Connection,
|
||||
task_id: str,
|
||||
contract_id: str,
|
||||
alert_id: str,
|
||||
suggestion: str,
|
||||
reason: str,
|
||||
summary: str,
|
||||
checklist: list[str],
|
||||
) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO renewal_tasks
|
||||
(task_id, contract_id, alert_id, ai_suggestion, suggestion_reason,
|
||||
performance_summary, materials_checklist, generated_at, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
|
||||
""",
|
||||
(
|
||||
task_id,
|
||||
contract_id,
|
||||
alert_id,
|
||||
suggestion,
|
||||
reason,
|
||||
summary,
|
||||
json.dumps(checklist, ensure_ascii=False),
|
||||
datetime.now().isoformat(timespec="seconds"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def get_task(conn: sqlite3.Connection, task_id: str) -> sqlite3.Row | None:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT t.*, c.teacher_name, c.unit_name, c.position, c.contract_type,
|
||||
c.contract_start, c.contract_end, c.employee_id
|
||||
FROM renewal_tasks t
|
||||
JOIN contracts c ON c.contract_id = t.contract_id
|
||||
WHERE t.task_id = ?
|
||||
""",
|
||||
(task_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
# ---------- dispatch_log ----------
|
||||
|
||||
def insert_dispatch_log(
|
||||
conn: sqlite3.Connection,
|
||||
log_id: str,
|
||||
unit_id: str,
|
||||
month: str,
|
||||
task_ids: list[str],
|
||||
payload_path: str,
|
||||
status: str = "dry_run",
|
||||
) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO dispatch_log
|
||||
(log_id, unit_id, month, task_ids, dispatched_at, payload_path, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
log_id,
|
||||
unit_id,
|
||||
month,
|
||||
json.dumps(task_ids, ensure_ascii=False),
|
||||
datetime.now().isoformat(timespec="seconds"),
|
||||
payload_path,
|
||||
status,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def list_dispatch_logs(conn: sqlite3.Connection) -> list[sqlite3.Row]:
|
||||
return conn.execute(
|
||||
"SELECT * FROM dispatch_log ORDER BY dispatched_at DESC"
|
||||
).fetchall()
|
||||
90
scripts/db/seed_data.py
Normal file
90
scripts/db/seed_data.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""种子数据加载:从 examples/contracts_sample.csv 和 performance_sample.csv 读入。
|
||||
|
||||
只在 contracts 表为空时执行,幂等。
|
||||
真实部署应替换为人事系统 API 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from util.logging_setup import get_skill_logger
|
||||
from util.runtime_paths import get_examples_dir
|
||||
|
||||
logger = get_skill_logger()
|
||||
|
||||
|
||||
def _read_csv(path: Path) -> list[dict[str, str]]:
|
||||
with open(path, "r", encoding="utf-8", newline="") as f:
|
||||
return list(csv.DictReader(f))
|
||||
|
||||
|
||||
def load_seed_if_empty(conn: sqlite3.Connection) -> tuple[int, int]:
|
||||
"""如果 contracts 表为空,从 CSV 加载种子数据。返回 (合同数, 业绩数)。"""
|
||||
n = conn.execute("SELECT COUNT(*) AS n FROM contracts").fetchone()["n"]
|
||||
if n > 0:
|
||||
logger.info("seed_data: contracts 表已有 %d 条记录,跳过加载", n)
|
||||
return (n, 0)
|
||||
|
||||
examples_dir = get_examples_dir()
|
||||
contracts_csv = examples_dir / "contracts_sample.csv"
|
||||
performance_csv = examples_dir / "performance_sample.csv"
|
||||
|
||||
if not contracts_csv.exists() or not performance_csv.exists():
|
||||
logger.warning("seed_data: 样例 CSV 不存在 %s / %s", contracts_csv, performance_csv)
|
||||
return (0, 0)
|
||||
|
||||
contracts = _read_csv(contracts_csv)
|
||||
performance = _read_csv(performance_csv)
|
||||
|
||||
with conn:
|
||||
conn.executemany(
|
||||
"""
|
||||
INSERT OR REPLACE INTO contracts
|
||||
(contract_id, employee_id, teacher_name, unit_id, unit_name,
|
||||
position, contract_type, contract_start, contract_end,
|
||||
trial_period_end, status, last_material_id, renewed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)
|
||||
""",
|
||||
[
|
||||
(
|
||||
c["contract_id"],
|
||||
c["employee_id"],
|
||||
c["teacher_name"],
|
||||
c["unit_id"],
|
||||
c["unit_name"],
|
||||
c["position"],
|
||||
c["contract_type"],
|
||||
c["contract_start"],
|
||||
c["contract_end"],
|
||||
c["trial_period_end"],
|
||||
c["status"],
|
||||
)
|
||||
for c in contracts
|
||||
],
|
||||
)
|
||||
conn.executemany(
|
||||
"""
|
||||
INSERT OR REPLACE INTO performance_records
|
||||
(record_id, contract_id, year, performance_score,
|
||||
moral_teaching_score, research_score, teaching_score)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
[
|
||||
(
|
||||
p["record_id"],
|
||||
p["contract_id"],
|
||||
int(p["year"]),
|
||||
float(p["performance_score"]),
|
||||
float(p["moral_teaching_score"]),
|
||||
float(p["research_score"]),
|
||||
float(p["teaching_score"]),
|
||||
)
|
||||
for p in performance
|
||||
],
|
||||
)
|
||||
|
||||
logger.info("seed_data: 加载 %d 份合同 / %d 条业绩记录", len(contracts), len(performance))
|
||||
return (len(contracts), len(performance))
|
||||
Reference in New Issue
Block a user