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