326 lines
12 KiB
Python
326 lines
12 KiB
Python
"""入库服务:把 Excel 落到 gongcan / flow / demand 三张表。"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Callable
|
||
|
||
import polars as pl
|
||
|
||
from . import config, readers
|
||
from .db import Database
|
||
from .sources import Source
|
||
|
||
GONGCAN_COLS = ["cgi", "cell_name", "lat", "lon", "site_name", "tech", "version"]
|
||
FLOW_COLS = [
|
||
"ts",
|
||
"cgi",
|
||
"traffic_gb",
|
||
"rrc_max",
|
||
"mr_weak_pct",
|
||
"access_rate",
|
||
"drop_rate",
|
||
"freq",
|
||
"freq_band",
|
||
"bandwidth",
|
||
"sector_name",
|
||
"high_traffic_warn",
|
||
"high_load_expand",
|
||
"rrc_max_abs",
|
||
"util_peak",
|
||
"mr_total",
|
||
"mr_weak_cnt",
|
||
"unicom_cov",
|
||
"telecom_cov",
|
||
"weak_cell",
|
||
"worse_unicom",
|
||
"worse_telecom",
|
||
"source",
|
||
]
|
||
DEMAND_COLS = [
|
||
"id",
|
||
"county",
|
||
"logical_site",
|
||
"cell_name",
|
||
"cgi",
|
||
"sector",
|
||
"site_name",
|
||
"applicant",
|
||
"retire_reason",
|
||
"need_date",
|
||
"order_type",
|
||
]
|
||
|
||
Progress = Callable[[str, int], None]
|
||
|
||
|
||
def _noop(_msg: str, _pct: int) -> None: # pragma: no cover
|
||
return None
|
||
|
||
|
||
def gongcan_version(path: Path) -> str:
|
||
"""工参版本号:优先取文件名里的日期(``4G小区工参202608030849`` → ``202608``),
|
||
解析不出来时退回文件修改时间。写入 gongcan.version,决定增量导入的覆盖优先级。"""
|
||
m = re.search(r"(20\d{2})(\d{2})\d{2}", Path(path).stem)
|
||
if m:
|
||
return f"{m.group(1)}{m.group(2)}"
|
||
return datetime.fromtimestamp(Path(path).stat().st_mtime).strftime("%Y%m")
|
||
|
||
|
||
# ---------------------------------------------------------------- 写库工具
|
||
def _write(
|
||
db: Database,
|
||
table: str,
|
||
df: pl.DataFrame,
|
||
columns: list[str],
|
||
*,
|
||
replace_where: tuple[str, tuple] | None = None,
|
||
conflict: list[str] | None = None,
|
||
) -> int:
|
||
df = df.select(columns)
|
||
if df.height == 0:
|
||
return 0
|
||
if replace_where:
|
||
db.execute(f"DELETE FROM {table} WHERE {replace_where[0]}", replace_where[1])
|
||
|
||
cols = ", ".join(columns)
|
||
if db.dialect == "duckdb":
|
||
conn = db.connect()
|
||
conn.register("_stage_df", df.to_arrow())
|
||
try:
|
||
stmt = f"INSERT INTO {table} ({cols}) SELECT {cols} FROM _stage_df"
|
||
if conflict:
|
||
sets = ", ".join(
|
||
f"{c} = COALESCE(excluded.{c}, {table}.{c})"
|
||
for c in columns
|
||
if c not in conflict
|
||
)
|
||
stmt += f" ON CONFLICT ({', '.join(conflict)}) DO UPDATE SET {sets}"
|
||
db.execute(stmt)
|
||
finally:
|
||
conn.unregister("_stage_df")
|
||
else:
|
||
ph = ", ".join(["?"] * len(columns))
|
||
stmt = f"INSERT INTO {table} ({cols}) VALUES ({ph})"
|
||
if conflict:
|
||
sets = ", ".join(
|
||
f"{c} = COALESCE(EXCLUDED.{c}, {table}.{c})" for c in columns if c not in conflict
|
||
)
|
||
stmt += f" ON CONFLICT ({', '.join(conflict)}) DO UPDATE SET {sets}"
|
||
db.executemany(stmt, df.rows())
|
||
return df.height
|
||
|
||
|
||
# ---------------------------------------------------------------- 主流程
|
||
def run_import(
|
||
db: Database,
|
||
source: Source,
|
||
progress: Progress | None = None,
|
||
*,
|
||
kinds: set[str] | None = None,
|
||
) -> dict:
|
||
"""导入 Excel。
|
||
|
||
``kinds`` 指定只处理哪几类(``gongcan`` / ``flow`` / ``demand``),
|
||
传 ``None`` 表示全部处理。前端把「工参」和「流量数据」拆成两个入口,
|
||
就是靠这个参数区分的。
|
||
|
||
写入语义:
|
||
* 工参 —— **单表增量**。同一 CGI 以版本较新的一条为准;
|
||
新导入的版本若比库内旧,只补库里没有的 CGI,不覆盖已有数据。
|
||
所以「先导 10 月、再导 8 月」和「先 8 月、后 10 月」结果一致。
|
||
* 流量 —— 按 ``(ts, cgi)`` 互补 upsert,天然追加。
|
||
* 清单 —— 全量替换(清单是同一份,追加会撞主键)。
|
||
"""
|
||
progress = progress or _noop
|
||
files = source.files()
|
||
progress(f"发现 {len(files)} 个 Excel 文件", 2)
|
||
if not files:
|
||
raise ValueError(f"来源 {source.kind}:{source.ref} 下没有可用的 .xlsx 文件")
|
||
|
||
want = {k.lower() for k in kinds} if kinds else None
|
||
|
||
def _want(kind_name: str) -> bool:
|
||
return want is None or kind_name in want
|
||
|
||
gongcan_files: list[dict] = []
|
||
flows: list[pl.DataFrame] = []
|
||
demands: list[tuple[object, pl.DataFrame]] = []
|
||
items: list[dict] = []
|
||
skipped: list[str] = []
|
||
dropped_type = 0
|
||
|
||
total = len(files)
|
||
for idx, f in enumerate(files, 1):
|
||
pct = 5 + int(idx / total * 60)
|
||
progress(f"[{idx}/{total}] 识别 {f.name}", pct)
|
||
try:
|
||
kind, info = readers.sniff(f.path)
|
||
except Exception as exc: # noqa: BLE001
|
||
if want is None:
|
||
skipped.append(f"{f.name}:读取失败({exc})")
|
||
items.append({"file": f.name, "origin": f.origin, "kind": "error", "message": str(exc)})
|
||
continue
|
||
|
||
if not _want(kind):
|
||
continue
|
||
|
||
if kind == "gongcan":
|
||
gstats: dict = {}
|
||
tech, df = readers.read_gongcan(f.path, stats=gstats)
|
||
ver = gongcan_version(f.path)
|
||
gongcan_files.append(
|
||
{"path": f.path, "name": f.name, "tech": tech, "version": ver, "df": df}
|
||
)
|
||
item = {
|
||
"file": f.name,
|
||
"origin": f.origin,
|
||
"kind": "gongcan",
|
||
"tech": tech,
|
||
"version": ver,
|
||
"rows": df.height,
|
||
"rows_raw": gstats.get("rows_raw"),
|
||
}
|
||
if gstats.get("dropped_site_type"):
|
||
item["dropped_site_type"] = gstats["dropped_site_type"]
|
||
if config.GONGCAN_EXCLUDE_SITE_TYPES and not gstats.get("site_type_column"):
|
||
skipped.append(
|
||
f"{f.name}:工参没有「站点类型」列,未做 {config.GONGCAN_EXCLUDE_SITE_TYPES} 过滤"
|
||
)
|
||
items.append(item)
|
||
dropped_type += gstats.get("dropped_site_type", 0) or 0
|
||
progress(
|
||
f"[{idx}/{total}] {tech} 工参 {df.height} 行(版本 {ver})"
|
||
+ (
|
||
f",按站点类型剔除 {gstats['dropped_site_type']} 行"
|
||
if gstats.get("dropped_site_type")
|
||
else ""
|
||
),
|
||
pct,
|
||
)
|
||
elif kind == "flow":
|
||
df = readers.read_flow(f.path)
|
||
if df is None or df.height == 0:
|
||
skipped.append(f"{f.name}:未解析出有效流量数据")
|
||
continue
|
||
df = df.with_columns(pl.lit(f.name).alias("source"))
|
||
flows.append(df)
|
||
items.append(
|
||
{
|
||
"file": f.name,
|
||
"origin": f.origin,
|
||
"kind": "flow",
|
||
"rows": df.height,
|
||
"metrics": [c for c in readers.FLOW_METRICS if df[c].null_count() < df.height],
|
||
"start": str(df["ts"].min()),
|
||
}
|
||
)
|
||
elif kind == "demand":
|
||
df = readers.read_demand(f.path)
|
||
demands.append((f, df))
|
||
items.append({"file": f.name, "origin": f.origin, "kind": "demand", "rows": df.height})
|
||
elif kind == "template":
|
||
items.append({"file": f.name, "origin": f.origin, "kind": "template", "message": "模板文件,不入库"})
|
||
else:
|
||
skipped.append(f"{f.name}:无法识别的表结构(表头不在支持范围内)")
|
||
items.append({"file": f.name, "origin": f.origin, "kind": "unknown", "message": "表头不匹配"})
|
||
|
||
# ---- 工参(单表增量)
|
||
# 同一 CGI 以版本较新的一条为准;若本次导入的版本比库内旧,只补库里没有的 CGI。
|
||
# 这样先导 10 月再导 8 月 = 10 月全量 + 8 月独有;顺序颠倒结果也一样。
|
||
gongcan_rows = 0
|
||
gongcan_added = 0
|
||
gongcan_skipped = 0
|
||
versions: list[str] = []
|
||
if gongcan_files and _want("gongcan"):
|
||
versions = sorted({g["version"] for g in gongcan_files})
|
||
progress(f"写入工参表 gongcan(增量,版本 {'、'.join(versions)})", 70)
|
||
frames = [
|
||
g["df"].with_columns(pl.lit(g["version"]).alias("version")) for g in gongcan_files
|
||
]
|
||
df = pl.concat(frames, how="diagonal_relaxed")
|
||
# 同一批文件里同一 CGI 出现在多个版本时,取版本最大的
|
||
df = df.sort("version").unique(subset=["cgi"], keep="last")
|
||
|
||
existing = db.query_frame("SELECT cgi, version AS old_version FROM gongcan")
|
||
if existing.height:
|
||
before = df.height
|
||
df = (
|
||
df.join(existing, on="cgi", how="left")
|
||
.filter(
|
||
pl.col("old_version").is_null()
|
||
| (
|
||
pl.col("version").fill_null("")
|
||
> pl.col("old_version").fill_null("")
|
||
)
|
||
)
|
||
.drop("old_version")
|
||
)
|
||
gongcan_skipped = before - df.height
|
||
gongcan_added = df.height
|
||
gongcan_rows = _write(db, "gongcan", df, GONGCAN_COLS, conflict=["cgi"])
|
||
|
||
# ---- 流量
|
||
progress("写入流量表 flow", 80)
|
||
flow_rows = 0
|
||
if flows and _want("flow"):
|
||
df = pl.concat(flows, how="diagonal_relaxed")
|
||
df = df.group_by(["ts", "cgi"]).agg(
|
||
[pl.col(c).drop_nulls().last().alias(c) for c in readers.FLOW_METRICS]
|
||
+ [pl.col(c).drop_nulls().last().alias(c) for c in readers.FLOW_EXTRA]
|
||
+ [pl.col("source").last().alias("source")]
|
||
)
|
||
flow_rows = _write(db, "flow", df, FLOW_COLS, conflict=["ts", "cgi"])
|
||
|
||
# ---- 需求清单
|
||
progress("写入需求清单表 demand", 90)
|
||
demand_rows = 0
|
||
if demands and _want("demand"):
|
||
# 多份清单并存时取「最后修改时间最新」的一份(旧版本常被改名后留在目录里)
|
||
src_file, df = max(demands, key=lambda t: t[0].path.stat().st_mtime)
|
||
if len(demands) > 1:
|
||
names = "、".join(f.name for f, _ in demands)
|
||
skipped.append(f"发现 {len(demands)} 份需求清单({names}),仅使用最新的:{src_file.name}")
|
||
demand_rows = _write(db, "demand", df, DEMAND_COLS, replace_where=("1=1", ()))
|
||
|
||
progress("入库完成", 100)
|
||
return {
|
||
"source": source.kind,
|
||
"source_ref": source.ref,
|
||
"files": total,
|
||
"gongcan_rows": gongcan_rows,
|
||
"gongcan_dropped_site_type": dropped_type,
|
||
"gongcan_versions": versions,
|
||
"gongcan_added": gongcan_added,
|
||
"gongcan_skipped": gongcan_skipped,
|
||
"flow_rows": flow_rows,
|
||
"demand_rows": demand_rows,
|
||
"items": items,
|
||
"skipped": skipped,
|
||
}
|
||
|
||
|
||
def stats(db: Database) -> dict:
|
||
rng = db.query_one("SELECT min(ts) AS a, max(ts) AS b FROM flow") or {"a": None, "b": None}
|
||
try: # 老库可能还没有 version 列
|
||
vers = [r["version"] for r in db.query(
|
||
"SELECT DISTINCT version FROM gongcan WHERE version IS NOT NULL ORDER BY version"
|
||
)]
|
||
except Exception: # noqa: BLE001
|
||
vers = []
|
||
return {
|
||
"gongcan": db.scalar("SELECT count(*) FROM gongcan") or 0,
|
||
"gongcan_4g": db.scalar("SELECT count(*) FROM gongcan WHERE tech = '4G'") or 0,
|
||
"gongcan_5g": db.scalar("SELECT count(*) FROM gongcan WHERE tech = '5G'") or 0,
|
||
"gongcan_versions": vers,
|
||
"flow": db.scalar("SELECT count(*) FROM flow") or 0,
|
||
"flow_points": db.scalar("SELECT count(DISTINCT ts) FROM flow") or 0,
|
||
"demand": db.scalar("SELECT count(*) FROM demand") or 0,
|
||
"flow_time_range": {
|
||
"a": rng["a"].strftime("%Y-%m-%d %H:%M:%S") if rng["a"] else None,
|
||
"b": rng["b"].strftime("%Y-%m-%d %H:%M:%S") if rng["b"] else None,
|
||
},
|
||
"database": db.dialect,
|
||
}
|