fix: 区域表缺少编号列或米数不符时拒绝创建
This commit is contained in:
@@ -8,49 +8,74 @@ from pathlib import Path
|
||||
|
||||
from app.shared.ids import normalize_id
|
||||
|
||||
_HEADER_KEYS = {
|
||||
"栅格id",
|
||||
"20米栅格id",
|
||||
"grid20_id",
|
||||
"grid50_id",
|
||||
"grid_id",
|
||||
"栅格",
|
||||
"栅格编号",
|
||||
"20米栅格id",
|
||||
"50米栅格id",
|
||||
_ID_COLUMN_MESSAGE = "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
|
||||
_EXACT_HEADERS = {
|
||||
"栅格id": None,
|
||||
"20米栅格id": 20,
|
||||
"50米栅格id": 50,
|
||||
"grid20id": 20,
|
||||
"grid50id": 50,
|
||||
"gridid": None,
|
||||
"栅格": None,
|
||||
"栅格编号": None,
|
||||
}
|
||||
|
||||
|
||||
def _header_index(header: list[str]) -> int | None:
|
||||
for index, name in enumerate(header):
|
||||
key = name.strip().lower().replace(" ", "").replace("_", "")
|
||||
raw = name.strip().lower().replace(" ", "")
|
||||
if raw in _HEADER_KEYS or key in {"栅格id", "20米栅格id", "50米栅格id", "grid20id", "grid50id", "gridid"}:
|
||||
return index
|
||||
if "栅格" in name and "id" in raw:
|
||||
return index
|
||||
return None
|
||||
def _column_meter(name: str) -> tuple[bool, int | None]:
|
||||
raw = name.strip().lower().replace(" ", "").replace("\u3000", "")
|
||||
key = raw.replace("_", "")
|
||||
if key in _EXACT_HEADERS:
|
||||
return True, _EXACT_HEADERS[key]
|
||||
if "栅格" in name and "id" in raw:
|
||||
if "20" in key:
|
||||
return True, 20
|
||||
if "50" in key:
|
||||
return True, 50
|
||||
return True, None
|
||||
return False, None
|
||||
|
||||
|
||||
def parse_table(rows: list[list]) -> tuple[list[str], int]:
|
||||
def _expected_meter(grid_size: str | None) -> int | None:
|
||||
if grid_size is None:
|
||||
return None
|
||||
if grid_size == "GRID20":
|
||||
return 20
|
||||
if grid_size == "GRID50":
|
||||
return 50
|
||||
raise ValueError("栅格只支持 20米或50米")
|
||||
|
||||
|
||||
def parse_table(rows: list[list], grid_size: str | None = None) -> tuple[list[str], int]:
|
||||
if not rows:
|
||||
return [], 0
|
||||
header = ["" if cell is None else str(cell).strip() for cell in rows[0]]
|
||||
column = _header_index(header)
|
||||
start = 0
|
||||
if column is None:
|
||||
column = 0
|
||||
if not normalize_id(header[0] if header else ""):
|
||||
start = 1
|
||||
index: int | None = None
|
||||
meter: int | None = None
|
||||
for position, name in enumerate(header):
|
||||
matched, found = _column_meter(name)
|
||||
if matched:
|
||||
index = position
|
||||
meter = found
|
||||
break
|
||||
if index is None:
|
||||
filled = [cell for cell in header if cell]
|
||||
if len(filled) > 1:
|
||||
raise ValueError(_ID_COLUMN_MESSAGE)
|
||||
index = 0
|
||||
start = 0 if normalize_id(header[0] if header else "") else 1
|
||||
else:
|
||||
start = 1
|
||||
expected = _expected_meter(grid_size)
|
||||
if meter is not None and expected is not None and meter != expected:
|
||||
raise ValueError(f"表头是{meter}米栅格,与所选的{expected}米不一致")
|
||||
found: list[str] = []
|
||||
seen: set[str] = set()
|
||||
duplicates = 0
|
||||
for row in rows[start:]:
|
||||
if column >= len(row):
|
||||
if index >= len(row):
|
||||
continue
|
||||
grid_id = normalize_id(row[column])
|
||||
grid_id = normalize_id(row[index])
|
||||
if not grid_id:
|
||||
continue
|
||||
if grid_id in seen:
|
||||
@@ -70,7 +95,7 @@ def _decode_csv(raw: bytes) -> str:
|
||||
return raw.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def parse_upload(path: Path) -> list[str]:
|
||||
def parse_upload(path: Path, grid_size: str | None = None) -> tuple[list[str], int]:
|
||||
if path.suffix.lower() != ".csv":
|
||||
raise ValueError("区域表只支持 CSV")
|
||||
text = _decode_csv(path.read_bytes())
|
||||
@@ -80,4 +105,5 @@ def parse_upload(path: Path) -> list[str]:
|
||||
except csv.Error:
|
||||
dialect = csv.excel
|
||||
reader = csv.reader(io.StringIO(text), dialect)
|
||||
return parse_table([list(row) for row in reader if any(str(cell).strip() for cell in row)])
|
||||
rows = [list(row) for row in reader if any(str(cell).strip() for cell in row)]
|
||||
return parse_table(rows, grid_size)
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from app.features.download.ids import parse_table
|
||||
from app.features.download.journal import CsvJournal, explain_os_error
|
||||
from app.platform.client import NqiError
|
||||
|
||||
@@ -136,6 +137,23 @@ def test_file_errors_use_chinese(tmp_path: Path, monkeypatch):
|
||||
journal.close()
|
||||
|
||||
|
||||
def test_area_table_rules():
|
||||
try:
|
||||
parse_table([["序号", "栅格编码"], ["1", "541927061"]])
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
else:
|
||||
raise AssertionError("多列且没有编号列时应拒绝")
|
||||
assert parse_table([["541927061"], ["544536471"]]) == (["541927061", "544536471"], 0)
|
||||
try:
|
||||
parse_table([["20米栅格ID"], ["12"]], "GRID50")
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "表头是20米栅格,与所选的50米不一致"
|
||||
else:
|
||||
raise AssertionError("米数不一致时应拒绝")
|
||||
assert parse_table([["栅格ID", "备注"], ["12", "a"]], "GRID50") == (["12"], 0)
|
||||
|
||||
|
||||
def _patch_fsync(monkeypatch):
|
||||
calls = []
|
||||
original = os.fsync
|
||||
|
||||
Reference in New Issue
Block a user