每个逻辑站点一个排队任务,与采集共用并行数量;工参按拆除前后规则取本系统快照,指标暂用模拟数据;全部站点结束后写频段清退、低效拆除两份结果表。去掉原来的通用导出任务。
346 lines
13 KiB
Python
346 lines
13 KiB
Python
"""拆站清单:读取上传的清单或单个提交的表单,校验后按逻辑站点分组。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import csv
|
||
import io
|
||
import re
|
||
from dataclasses import dataclass, field
|
||
from datetime import date, datetime, timedelta
|
||
|
||
from openpyxl import Workbook, load_workbook
|
||
from openpyxl.styles import Alignment, Font, PatternFill
|
||
from openpyxl.utils import get_column_letter
|
||
|
||
from app.collect.io import decode_text
|
||
|
||
SHEET = "拆站清单"
|
||
MAX_ROWS = 5000
|
||
MAX_BYTES = 10 * 1024 * 1024
|
||
DIXIAO_KEYWORD = "低效拆除"
|
||
ORDER_TYPES = ("频段清退", "低效拆除")
|
||
KIND_LABELS = {"pinduan": "频段清退评估", "dixiao": "低效拆除评估"}
|
||
FIELDS: dict[str, tuple[str, ...]] = {
|
||
"county": ("区县", "县区"),
|
||
"cell_name": ("小区名", "小区名称"),
|
||
"cgi": ("CGI", "NCGI", "小区CGI"),
|
||
"sector": ("扇区",),
|
||
"site_name": ("物理站名(综资站点)", "物理站名", "综资站点"),
|
||
"applicant": ("发起人", "申请人"),
|
||
"retire_reason": ("是否已发邮件安排拆除", "退网原因"),
|
||
"need_date": ("需求日期", "计划退网时间", "拆除日期"),
|
||
"order_type": ("退网工单类型", "工单类型"),
|
||
}
|
||
TEMPLATE_COLUMNS = (
|
||
("区县", "", "台山市"),
|
||
("小区名", "建议填写;为空时按 CGI 从工参补齐", "江门台山现代技术学校F-ZLH-1"),
|
||
("CGI", "必填,如 460-00-679584-1", "460-00-679584-1"),
|
||
("扇区", "", ""),
|
||
("物理站名(综资站点)", "", ""),
|
||
("发起人", "", ""),
|
||
("是否已发邮件安排拆除", "写入结果表的「退网原因」", "站点搬迁"),
|
||
("需求日期", "必填,按拆除日期确定拆除前后的工参", "2026-10-15"),
|
||
("退网工单类型", "必填;含「低效拆除」的写入低效拆除评估,其余写入频段清退评估", "频段清退"),
|
||
)
|
||
CGI_PATTERN = re.compile(r"^\d{3}-\d{2}-\d+-\d+$")
|
||
EXCEL_EPOCH = date(1899, 12, 30)
|
||
|
||
|
||
class DemandError(ValueError):
|
||
pass
|
||
|
||
|
||
@dataclass
|
||
class DemandRow:
|
||
line: int
|
||
cgi: str
|
||
order_type: str
|
||
need_date: date | None
|
||
cell_name: str = ""
|
||
county: str = ""
|
||
sector: str = ""
|
||
site_name: str = ""
|
||
applicant: str = ""
|
||
retire_reason: str = ""
|
||
|
||
@property
|
||
def logical_site(self) -> str:
|
||
return re.sub(r"-\d+$", "", self.cell_name.strip())
|
||
|
||
def to_json(self) -> dict:
|
||
return {
|
||
"line": self.line,
|
||
"cgi": self.cgi,
|
||
"orderType": self.order_type,
|
||
"needDate": self.need_date.isoformat() if self.need_date else None,
|
||
"cellName": self.cell_name,
|
||
"county": self.county,
|
||
"sector": self.sector,
|
||
"siteName": self.site_name,
|
||
"applicant": self.applicant,
|
||
"retireReason": self.retire_reason,
|
||
}
|
||
|
||
@classmethod
|
||
def from_json(cls, data: dict) -> "DemandRow":
|
||
need = data.get("needDate")
|
||
return cls(
|
||
line=int(data.get("line") or 0),
|
||
cgi=str(data.get("cgi") or ""),
|
||
order_type=str(data.get("orderType") or ""),
|
||
need_date=date.fromisoformat(need) if need else None,
|
||
cell_name=str(data.get("cellName") or ""),
|
||
county=str(data.get("county") or ""),
|
||
sector=str(data.get("sector") or ""),
|
||
site_name=str(data.get("siteName") or ""),
|
||
applicant=str(data.get("applicant") or ""),
|
||
retire_reason=str(data.get("retireReason") or ""),
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class DemandSheet:
|
||
rows: list[DemandRow]
|
||
errors: list[dict]
|
||
sheet: str = ""
|
||
|
||
|
||
@dataclass
|
||
class SiteGroup:
|
||
"""一个评估对象:一个逻辑站点(清单里同站的几行),或按站点名提交的整站。"""
|
||
|
||
key: str
|
||
kind: str
|
||
order_type: str
|
||
removal: date
|
||
rows: list[DemandRow] = field(default_factory=list)
|
||
site: str = ""
|
||
|
||
@property
|
||
def cgis(self) -> list[str]:
|
||
return [row.cgi for row in self.rows if row.cgi]
|
||
|
||
|
||
def kind_of(order_type: str) -> str:
|
||
return "dixiao" if DIXIAO_KEYWORD in (order_type or "") else "pinduan"
|
||
|
||
|
||
def base_id(cgi: str) -> str:
|
||
"""CGI 去掉最后一段就是基站 ID,如 460-00-679584-1 → 460-00-679584。"""
|
||
match = re.match(r"^(\d+-\d+-\d+)-\d+$", (cgi or "").strip())
|
||
return match.group(1) if match else (cgi or "")
|
||
|
||
|
||
def parse_date(value: object) -> date | None:
|
||
if value is None or value == "":
|
||
return None
|
||
if isinstance(value, datetime):
|
||
return value.date()
|
||
if isinstance(value, date):
|
||
return value
|
||
if isinstance(value, (int, float)):
|
||
return _serial_date(float(value))
|
||
text = str(value).strip().replace("\t", "")
|
||
if not text:
|
||
return None
|
||
if re.fullmatch(r"\d+(\.\d+)?", text) and len(text) != 8:
|
||
return _serial_date(float(text))
|
||
text = re.sub(r"[年月]", "-", text).replace("日", "").replace("/", "-").replace(".", "-")
|
||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%Y%m%d"):
|
||
try:
|
||
return datetime.strptime(text, fmt).date()
|
||
except ValueError:
|
||
continue
|
||
raise ValueError(str(value))
|
||
|
||
|
||
def _serial_date(number: float) -> date | None:
|
||
if number < 1 or number > 2958465:
|
||
raise ValueError(str(number))
|
||
return EXCEL_EPOCH + timedelta(days=int(number))
|
||
|
||
|
||
def _norm(name: object) -> str:
|
||
return (
|
||
str(name or "")
|
||
.replace("\u3000", "")
|
||
.replace(" ", "")
|
||
.replace("\t", "")
|
||
.replace("(", "(")
|
||
.replace(")", ")")
|
||
.strip()
|
||
)
|
||
|
||
|
||
def _clean(value: object) -> str:
|
||
if value is None:
|
||
return ""
|
||
if isinstance(value, float) and value.is_integer():
|
||
value = int(value)
|
||
return str(value).replace("\t", "").strip()
|
||
|
||
|
||
def _column_map(headers: list[object]) -> dict[str, int]:
|
||
normalized = [_norm(header) for header in headers]
|
||
found: dict[str, int] = {}
|
||
for key, aliases in FIELDS.items():
|
||
for alias in aliases:
|
||
target = _norm(alias)
|
||
if target in normalized:
|
||
found[key] = normalized.index(target)
|
||
break
|
||
return found
|
||
|
||
|
||
def parse_demand(name: str, content: bytes) -> DemandSheet:
|
||
if len(content) > MAX_BYTES:
|
||
raise DemandError("清单文件超过 10MB")
|
||
lowered = (name or "").lower()
|
||
if lowered.endswith(".xlsx") or lowered.endswith(".xlsm"):
|
||
sheet, table = _read_xlsx(content)
|
||
elif lowered.endswith(".csv"):
|
||
sheet = ""
|
||
table = [(line, list(values)) for line, values in enumerate(csv.reader(io.StringIO(decode_text(content))), start=1)]
|
||
elif lowered.endswith(".xls"):
|
||
raise DemandError("请把 xls 另存为 xlsx 后再导入")
|
||
else:
|
||
raise DemandError("清单只支持 xlsx 或 csv")
|
||
return _rows_from_table(sheet, table)
|
||
|
||
|
||
def _read_xlsx(content: bytes) -> tuple[str, list[tuple[int, list[object]]]]:
|
||
"""按行号读出每一行,空行不会让后面的行号错位。"""
|
||
try:
|
||
workbook = load_workbook(io.BytesIO(content), data_only=True)
|
||
except Exception as exc:
|
||
raise DemandError("清单文件打不开,请确认是 xlsx") from exc
|
||
names = workbook.sheetnames
|
||
target = next((sheet for sheet in names if _norm(sheet) == SHEET), names[0] if names else None)
|
||
if target is None:
|
||
raise DemandError("清单里没有工作表")
|
||
table = [(cells[0].row, [cell.value for cell in cells]) for cells in workbook[target].iter_rows() if cells]
|
||
return target, table
|
||
|
||
|
||
def _rows_from_table(sheet: str, table: list[tuple[int, list[object]]]) -> DemandSheet:
|
||
header_index = None
|
||
columns: dict[str, int] = {}
|
||
for index, (_line, row) in enumerate(table[:10]):
|
||
mapped = _column_map(list(row))
|
||
if "cgi" in mapped:
|
||
header_index, columns = index, mapped
|
||
break
|
||
if header_index is None:
|
||
raise DemandError("清单表头里没有找到 CGI 列")
|
||
missing = [label for key, label in (("order_type", "退网工单类型"), ("need_date", "需求日期")) if key not in columns]
|
||
if missing:
|
||
raise DemandError(f"清单缺少列:{'、'.join(missing)}")
|
||
rows: list[DemandRow] = []
|
||
errors: list[dict] = []
|
||
seen: dict[str, int] = {}
|
||
for offset, raw in table[header_index + 1:]:
|
||
values = {key: (raw[col] if col < len(raw) else None) for key, col in columns.items()}
|
||
if all(_clean(value) == "" for value in values.values()):
|
||
continue
|
||
if len(rows) + len(errors) >= MAX_ROWS:
|
||
raise DemandError(f"一次最多导入 {MAX_ROWS} 行")
|
||
problems: list[str] = []
|
||
cgi = _clean(values.get("cgi"))
|
||
if not cgi:
|
||
problems.append("缺少 CGI")
|
||
elif not CGI_PATTERN.match(cgi):
|
||
problems.append(f"CGI 格式不对:{cgi}")
|
||
elif cgi in seen:
|
||
problems.append(f"CGI 与第 {seen[cgi]} 行重复")
|
||
order_type = _clean(values.get("order_type"))
|
||
if not order_type:
|
||
problems.append("缺少退网工单类型")
|
||
need_date = None
|
||
try:
|
||
need_date = parse_date(values.get("need_date"))
|
||
if need_date is None:
|
||
problems.append("缺少需求日期")
|
||
except ValueError:
|
||
problems.append(f"需求日期看不懂:{_clean(values.get('need_date'))}")
|
||
if problems:
|
||
errors.append({"line": offset, "cgi": cgi, "message": ";".join(problems)})
|
||
continue
|
||
seen[cgi] = offset
|
||
rows.append(
|
||
DemandRow(
|
||
line=offset,
|
||
cgi=cgi,
|
||
order_type=order_type,
|
||
need_date=need_date,
|
||
cell_name=_clean(values.get("cell_name")),
|
||
county=_clean(values.get("county")),
|
||
sector=_clean(values.get("sector")),
|
||
site_name=_clean(values.get("site_name")),
|
||
applicant=_clean(values.get("applicant")),
|
||
retire_reason=_clean(values.get("retire_reason")),
|
||
)
|
||
)
|
||
if not rows and not errors:
|
||
raise DemandError("清单里没有数据行")
|
||
return DemandSheet(rows=rows, errors=errors, sheet=sheet)
|
||
|
||
|
||
def group_rows(rows: list[DemandRow]) -> list[SiteGroup]:
|
||
"""同一逻辑站点、同一类评估的行归为一组;拆除日期取组内最早的一个。
|
||
|
||
没写小区名的行先跟同基站、有小区名的行归到一起,都没有小区名时按基站 ID 归组。
|
||
"""
|
||
named = {base_id(row.cgi): row.logical_site for row in rows if row.logical_site}
|
||
groups: dict[tuple[str, str], SiteGroup] = {}
|
||
for row in rows:
|
||
kind = kind_of(row.order_type)
|
||
key = row.logical_site or named.get(base_id(row.cgi)) or base_id(row.cgi)
|
||
group = groups.get((kind, key))
|
||
if group is None:
|
||
groups[(kind, key)] = SiteGroup(key=key, kind=kind, order_type=row.order_type, removal=row.need_date, rows=[row])
|
||
continue
|
||
group.rows.append(row)
|
||
if row.need_date and row.need_date < group.removal:
|
||
group.removal = row.need_date
|
||
return list(groups.values())
|
||
|
||
|
||
def summarize(groups: list[SiteGroup]) -> dict:
|
||
return {
|
||
"sites": len(groups),
|
||
"pinduan": sum(1 for group in groups if group.kind == "pinduan"),
|
||
"dixiao": sum(1 for group in groups if group.kind == "dixiao"),
|
||
"cells": sum(len(group.rows) for group in groups),
|
||
}
|
||
|
||
|
||
def template_workbook() -> bytes:
|
||
"""给用户下载的清单模板:表头 + 一行示例 + 填写说明。"""
|
||
workbook = Workbook()
|
||
sheet = workbook.active
|
||
sheet.title = SHEET
|
||
head_fill = PatternFill(fill_type="solid", start_color="DDEBF7", end_color="DDEBF7")
|
||
for col, (header, _hint, example) in enumerate(TEMPLATE_COLUMNS, start=1):
|
||
cell = sheet.cell(row=1, column=col, value=header)
|
||
cell.font = Font(bold=True)
|
||
cell.fill = head_fill
|
||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||
sheet.cell(row=2, column=col, value=example)
|
||
sheet.column_dimensions[get_column_letter(col)].width = max(12, len(header) * 2 + 4)
|
||
sheet.column_dimensions["B"].width = 36
|
||
sheet.column_dimensions["C"].width = 20
|
||
sheet.freeze_panes = "A2"
|
||
notes = workbook.create_sheet("填写说明")
|
||
notes.append(["列", "说明"])
|
||
for header, hint, _example in TEMPLATE_COLUMNS:
|
||
notes.append([header, hint or "选填"])
|
||
notes.append([])
|
||
notes.append(["分组", "同一逻辑站点(小区名去掉末尾 -数字)的几行作为一个评估对象;没有小区名时按 CGI 的基站 ID 归组。"])
|
||
notes.column_dimensions["A"].width = 22
|
||
notes.column_dimensions["B"].width = 72
|
||
for cell in notes[1]:
|
||
cell.font = Font(bold=True)
|
||
buffer = io.BytesIO()
|
||
workbook.save(buffer)
|
||
return buffer.getvalue()
|