"""种子数据加载:从 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))