359 lines
15 KiB
Python
359 lines
15 KiB
Python
"""Import ERP HRAO_FILE departments into the local department tree.
|
||
|
||
Purpose: one-shot import of the Tiptop department master (ERP `dc.HRAO_FILE`) exported as
|
||
CSV from DBeaver into the local `departments` tree, upserting by department code (hrao01).
|
||
Dependencies: Flask app context, SQLAlchemy models, csv/json stdlib (no Oracle driver).
|
||
Flow: dry-run is the default and only prints a validation report; pass `--apply` to write.
|
||
hrao06 parent codes resolve to hrao01 after all rows are upserted; dangling parents and
|
||
cycles fall back to top-level with a report. Local rows whose code is absent from the ERP
|
||
file are kept untouched (per the agreed merge policy). `users.department` links by name
|
||
text, so renames are reported for manual re-linking instead of being rewritten here.
|
||
|
||
Usage (from backend/):
|
||
python scripts/import_departments_from_hrao.py --file scripts/data/hrao_departments.csv
|
||
python scripts/import_departments_from_hrao.py --file ... --apply
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import sys
|
||
from collections import Counter
|
||
from pathlib import Path
|
||
from typing import Any, Optional
|
||
|
||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||
if str(BACKEND_ROOT) not in sys.path:
|
||
sys.path.insert(0, str(BACKEND_ROOT))
|
||
|
||
from app import create_app
|
||
from app.extensions import db
|
||
from app.models import Department, User
|
||
|
||
DEFAULT_CSV = Path("scripts/data/hrao_departments.csv")
|
||
DEFAULT_COMPANY_MAP = Path("scripts/data/hrao_company_map.json")
|
||
HIDDEN_MODES = ("ignore", "n_is_hidden", "not_y_is_hidden")
|
||
|
||
|
||
def _clean(value: Any) -> str:
|
||
"""Trim a CSV cell to a normalized string ('' for None)."""
|
||
return str(value or "").strip()
|
||
|
||
|
||
def _read_csv(path: Path) -> list[dict[str, str]]:
|
||
"""Read the DBeaver CSV export; headers are normalized to lowercase (utf-8 with BOM tolerated).
|
||
|
||
Args:
|
||
path: CSV file exported from `SELECT hrao00, hrao01, hrao02, hrao03, hrao06, hrao09, ... FROM dc.HRAO_FILE`.
|
||
Returns:
|
||
List of row dicts keyed by lowercase column names (hrao00 ...).
|
||
Raises:
|
||
SystemExit: file missing or no recognizable hrao01 header.
|
||
"""
|
||
if not path.exists():
|
||
raise SystemExit(f"CSV not found: {path}\n先在 DBeaver 导出 HRAO 查询结果为 CSV(UTF-8),再放到该路径。")
|
||
import csv
|
||
|
||
with path.open(encoding="utf-8-sig", newline="") as fh:
|
||
reader = csv.DictReader(fh)
|
||
rows = [
|
||
{(k or "").strip().lower(): (v or "") for k, v in raw.items()}
|
||
for raw in reader
|
||
]
|
||
if rows and not any("hrao01" in row for row in rows[:1]):
|
||
raise SystemExit(f"CSV 首行未找到 hrao01 列头,请确认导出来自 HRAO_FILE 查询:{path}")
|
||
return rows
|
||
|
||
|
||
def _load_company_map(path: Path) -> dict[str, str]:
|
||
"""Load hrao00 -> company display name mapping from a JSON file.
|
||
|
||
Raises:
|
||
SystemExit: mapping file missing (with a template hint).
|
||
"""
|
||
if not path.exists():
|
||
raise SystemExit(
|
||
f"公司映射文件不存在:{path}\n"
|
||
'请创建 JSON:{"0002": "苏州和信精密科技有限公司", ...}(hrao00 -> 公司中文名)。'
|
||
)
|
||
data = json.loads(path.read_text(encoding="utf-8"))
|
||
return {_clean(k): _clean(v) for k, v in data.items() if _clean(k)}
|
||
|
||
|
||
def _parse_hidden(hrao08: str, mode: str) -> bool:
|
||
"""Map hrao08 (在组织框架图中显示否) to is_hidden per the chosen mode.
|
||
|
||
Args:
|
||
mode: ignore(默认,全部不隐藏)| n_is_hidden(N=不显示→隐藏)| not_y_is_hidden(非 Y 即隐藏)。
|
||
"""
|
||
flag = _clean(hrao08).upper()
|
||
if mode == "n_is_hidden":
|
||
return flag == "N"
|
||
if mode == "not_y_is_hidden":
|
||
return flag != "Y"
|
||
return False
|
||
|
||
|
||
def _normalize_rows(
|
||
raw_rows: list[dict[str, str]], hidden_mode: str
|
||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||
"""Normalize CSV rows into import payloads; duplicate hrao01 keeps the first occurrence.
|
||
|
||
Returns:
|
||
(rows, problems) — rows keyed by code with name/company_code/parent_code/sort_order/is_hidden.
|
||
"""
|
||
rows: dict[str, dict[str, Any]] = {}
|
||
problems: list[str] = []
|
||
for raw in raw_rows:
|
||
code = _clean(raw.get("hrao01"))
|
||
name = _clean(raw.get("hrao02")) or _clean(raw.get("hrao03"))
|
||
if not code:
|
||
problems.append(f"跳过:hrao01 为空(hrao02={_clean(raw.get('hrao02'))!r})")
|
||
continue
|
||
if not name:
|
||
problems.append(f"跳过:{code} 部门名称为空(hrao02/hrao03 均空)")
|
||
continue
|
||
if code in rows:
|
||
problems.append(f"跳过重复编码:{code} 第二次出现({name!r}),保留首行")
|
||
continue
|
||
sort_raw = _clean(raw.get("hrao09"))
|
||
parent = _clean(raw.get("hrao06"))
|
||
rows[code] = {
|
||
"code": code,
|
||
"name": name,
|
||
"company_code": _clean(raw.get("hrao00")),
|
||
"parent_code": parent if parent and parent != "0" else None,
|
||
"sort_order": int(sort_raw) if sort_raw.isdigit() else 0,
|
||
"is_hidden": _parse_hidden(raw.get("hrao08"), hidden_mode),
|
||
}
|
||
return list(rows.values()), problems
|
||
|
||
|
||
def _resolve_parents(rows: list[dict[str, Any]]) -> tuple[dict[str, Optional[str]], list[str]]:
|
||
"""Resolve each row's parent code; dangling/self references fall back to top-level.
|
||
|
||
Returns:
|
||
(parent_by_code, problems) — parent codes or None for top-level.
|
||
"""
|
||
codes = {r["code"] for r in rows}
|
||
parent_by_code: dict[str, Optional[str]] = {}
|
||
problems: list[str] = []
|
||
for row in rows:
|
||
parent = row["parent_code"]
|
||
if parent is not None and (parent not in codes or parent == row["code"]):
|
||
problems.append(f"悬空上级:{row['code']} {row['name']} 的 hrao06={parent!r} 匹配不到 hrao01,按顶级导入")
|
||
parent = None
|
||
parent_by_code[row["code"]] = parent
|
||
return parent_by_code, problems
|
||
|
||
|
||
def _break_cycles(
|
||
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||
) -> tuple[dict[str, Optional[str]], list[str]]:
|
||
"""Rows caught in a parent cycle (e.g. A->B->A) are detached to top-level.
|
||
|
||
Returns:
|
||
(parent_by_code, problems)
|
||
"""
|
||
problems: list[str] = []
|
||
for row in rows:
|
||
seen: set[str] = set()
|
||
cursor: Optional[str] = row["code"]
|
||
cyclic = False
|
||
while cursor and parent_by_code.get(cursor):
|
||
if cursor in seen:
|
||
cyclic = True
|
||
break
|
||
seen.add(cursor)
|
||
cursor = parent_by_code[cursor]
|
||
if cyclic:
|
||
name = next(r["name"] for r in rows if r["code"] == row["code"])
|
||
problems.append(f"成环:{row['code']} {name} 的上级链形成环,整链按顶级导入")
|
||
parent_by_code[row["code"]] = None
|
||
return parent_by_code, problems
|
||
|
||
|
||
def _find_name_conflicts(
|
||
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||
) -> list[str]:
|
||
"""Same-parent (or same-company top-level) duplicate names would fail sibling validation."""
|
||
buckets: Counter = Counter()
|
||
for row in rows:
|
||
parent = parent_by_code[row["code"]]
|
||
company = row["company_code"] if parent is None else parent
|
||
buckets[(company, parent, row["name"])] += 1
|
||
return [
|
||
f"同级重名:{name!r}(公司/父={key})出现 {count} 次,需人工改名后再导入"
|
||
for (key, _, name), count in buckets.items()
|
||
if count > 1
|
||
]
|
||
|
||
|
||
def plan_import(
|
||
rows: list[dict[str, Any]],
|
||
company_map: dict[str, str],
|
||
allow_unmapped: bool,
|
||
) -> tuple[dict[str, Any], list[str]]:
|
||
"""Diff ERP rows against local departments into an upsert plan.
|
||
|
||
Args:
|
||
rows: normalized ERP rows.
|
||
company_map: hrao00 -> company display name.
|
||
allow_unmapped: when False, unmapped hrao00 aborts the plan (apply refuses).
|
||
Returns:
|
||
(plan, problems) — plan holds inserts/updates/kept/dangling etc. for the reporter.
|
||
"""
|
||
problems: list[str] = []
|
||
unmapped = sorted({r["company_code"] for r in rows if r["company_code"] and r["company_code"] not in company_map})
|
||
if unmapped and not allow_unmapped:
|
||
problems.append(f"未映射的公司编码:{unmapped}(补 hrao_company_map.json 或加 --allow-unmapped)")
|
||
|
||
for row in rows:
|
||
row["company"] = company_map.get(row["company_code"])
|
||
|
||
local_by_code = {d.code: d for d in db.session.query(Department).all()}
|
||
inserts = [r for r in rows if r["code"] not in local_by_code]
|
||
updates = [
|
||
{"local": local_by_code[r["code"]], "row": r}
|
||
for r in rows
|
||
if r["code"] in local_by_code
|
||
]
|
||
kept = sorted(set(local_by_code) - {r["code"] for r in rows})
|
||
|
||
renames = []
|
||
for item in updates:
|
||
old_name = item["local"].name
|
||
if old_name != item["row"]["name"]:
|
||
linked = db.session.query(User).filter(User.department == old_name).count()
|
||
renames.append((old_name, item["row"]["name"], linked))
|
||
|
||
plan = {
|
||
"inserts": inserts,
|
||
"updates": updates,
|
||
"kept": kept,
|
||
"renames": renames,
|
||
"unmapped": unmapped,
|
||
}
|
||
return plan, problems
|
||
|
||
|
||
def apply_plan(plan: dict[str, Any], parent_by_code: dict[str, Optional[str]]) -> tuple[int, int]:
|
||
"""Execute the plan in one transaction; parents are linked after ids exist.
|
||
|
||
Returns:
|
||
(created, updated) row counts.
|
||
"""
|
||
code_to_id = {d.code: d.id for d in db.session.query(Department).all()}
|
||
created = updated = 0
|
||
# [STEP 1] 先落行(parent_id 暂空),拿到主键后再统一挂父,避免插入顺序依赖
|
||
for row in plan["inserts"]:
|
||
dept = Department(
|
||
name=row["name"],
|
||
code=row["code"],
|
||
company=row["company"],
|
||
parent_id=None,
|
||
sort_order=row["sort_order"],
|
||
is_hidden=row["is_hidden"],
|
||
)
|
||
db.session.add(dept)
|
||
db.session.flush()
|
||
code_to_id[row["code"]] = dept.id
|
||
created += 1
|
||
# [STEP 2] 更新已存在行(按编码 upsert,保留本地多余行)
|
||
for item in plan["updates"]:
|
||
local, row = item["local"], item["row"]
|
||
local.name = row["name"]
|
||
local.company = row["company"]
|
||
local.sort_order = row["sort_order"]
|
||
local.is_hidden = row["is_hidden"]
|
||
updated += 1
|
||
# [STEP 3] 挂上级:本地已有编码或本次新插入的编码都可作为父
|
||
for row in plan["inserts"] + [i["row"] for i in plan["updates"]]:
|
||
parent_code = parent_by_code[row["code"]]
|
||
if parent_code:
|
||
db.session.get(Department, code_to_id[row["code"]]).parent_id = code_to_id.get(parent_code)
|
||
db.session.commit()
|
||
return created, updated
|
||
|
||
|
||
def _print_report(
|
||
rows: list[dict[str, Any]],
|
||
plan: dict[str, Any],
|
||
problems: list[str],
|
||
company_map: dict[str, str],
|
||
raw_rows: list[dict[str, str]],
|
||
) -> None:
|
||
"""Print the dry-run/apply report; problem lines always warn before the summary."""
|
||
companies = Counter(r["company_code"] for r in rows)
|
||
print("== 公司分布(hrao00 -> 行数)==")
|
||
for code, count in sorted(companies.items()):
|
||
print(f" {code or '(空)'} x{count} -> {company_map.get(code, '(未映射)')}")
|
||
if plan["unmapped"]:
|
||
print(f" ⚠ 未映射编码:{plan['unmapped']}")
|
||
print(f"== 汇总 == ERP 行 {len(rows)};插入 {len(plan['inserts'])};更新 {len(plan['updates'])};本地保留 {len(plan['kept'])}")
|
||
if plan["renames"]:
|
||
print("== 更名(users.department 按名称关联,需人工重挂)==")
|
||
for old, new, linked in plan["renames"]:
|
||
print(f" {old!r} -> {new!r}(名下员工 {linked} 人)")
|
||
for line in problems:
|
||
print(f" ⚠ {line}")
|
||
if not any("⚠" in line for line in problems) and not plan["renames"]:
|
||
print(" (无告警)")
|
||
# hrao 标志位分布,帮助确认 is_hidden 映射是否正确
|
||
for col in ("hrao05", "hrao07", "hrao08"):
|
||
dist = Counter(_clean(r.get(col)).upper() for r in raw_rows)
|
||
print(f"== {col} 取值分布 == {dict(dist)}")
|
||
|
||
|
||
def main() -> None:
|
||
"""Parse args, build the plan, and write only with --apply (single transaction)."""
|
||
parser = argparse.ArgumentParser(description="Import ERP HRAO_FILE departments (CSV) into the local tree")
|
||
parser.add_argument("--file", type=Path, default=DEFAULT_CSV, help="DBeaver 导出的 HRAO CSV 路径")
|
||
parser.add_argument("--company-map", type=Path, default=DEFAULT_COMPANY_MAP, help="hrao00 -> 公司名 JSON")
|
||
parser.add_argument("--hidden-mode", choices=HIDDEN_MODES, default="ignore",
|
||
help="hrao08 -> is_hidden 映射;默认 ignore(不隐藏)")
|
||
parser.add_argument("--allow-unmapped", action="store_true", help="允许未映射公司编码(company 置空)")
|
||
parser.add_argument("--company", action="append", default=None,
|
||
help="只导入指定 hrao00 的公司(可多次传入,如 --company 0003);缺省导入全部")
|
||
parser.add_argument("--apply", action="store_true", help="真正写库;缺省仅 dry-run 预览")
|
||
args = parser.parse_args()
|
||
|
||
company_map = _load_company_map(args.company_map)
|
||
raw_rows = _read_csv(args.file)
|
||
rows, problems = _normalize_rows(raw_rows, args.hidden_mode)
|
||
if args.company:
|
||
wanted = {c.strip() for c in args.company}
|
||
missing = wanted - {r["company_code"] for r in rows}
|
||
if missing:
|
||
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||
rows = [r for r in rows if r["company_code"] in wanted]
|
||
if args.company:
|
||
wanted = {c.strip() for c in args.company}
|
||
missing = wanted - {r["company_code"] for r in rows}
|
||
if missing:
|
||
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||
rows = [r for r in rows if r["company_code"] in wanted]
|
||
parent_by_code, parent_problems = _resolve_parents(rows)
|
||
parent_by_code, cycle_problems = _break_cycles(rows, parent_by_code)
|
||
problems += parent_problems + cycle_problems
|
||
problems += _find_name_conflicts(rows, parent_by_code)
|
||
|
||
app = create_app()
|
||
with app.app_context():
|
||
plan, plan_problems = plan_import(rows, company_map, args.allow_unmapped)
|
||
problems += plan_problems
|
||
_print_report(rows, plan, problems, company_map, raw_rows)
|
||
fatal = [p for p in problems if "需人工" in p or "未映射的公司编码" in p]
|
||
if args.apply and not fatal:
|
||
created, updated = apply_plan(plan, parent_by_code)
|
||
print(f"✅ 已写入:插入 {created},更新 {updated}(事务已提交)")
|
||
elif args.apply:
|
||
raise SystemExit("存在需人工处理的告警,已阻止写库;处理后重试或加对应参数。")
|
||
else:
|
||
print("(dry-run 未写库;确认无误后加 --apply 执行)")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|