Files
shanxia2.0/backend/app/services/pl_plan_archive_zip_export.py
T

126 lines
3.9 KiB
Python

from __future__ import annotations
import hashlib
import json
import re
from typing import Any, Mapping, Optional, Sequence
from urllib.parse import unquote, urlparse
ARCHIVE_ZIP_ATTACH_COL_MAX = 20
ARCHIVE_ZIP_MAX_FILES = 2000
ARCHIVE_ZIP_MAX_BYTES = 500 * 1024 * 1024
def sanitize_zip_segment(raw: str) -> str:
value = re.sub(r'[\\/:*?"<>|]+', "_", str(raw or "").strip())
value = re.sub(r"\s+", " ", value).strip()
return value or "未命名"
def short_hash(text: str, *, n: int = 6) -> str:
return hashlib.sha1(str(text or "").encode("utf-8")).hexdigest()[:n]
def guess_ext_from_url(url: str) -> str:
path = unquote(urlparse(str(url or "").split("?", 1)[0]).path)
name = path.rsplit("/", 1)[-1]
if "." not in name:
return "bin"
ext = name.rsplit(".", 1)[-1].lower()
if not ext or len(ext) > 8 or "/" in ext:
return "bin"
return ext
def build_attachment_filename(row_no: int, label: str, url: str) -> str:
return (
f"{int(row_no):02d}_{sanitize_zip_segment(label)}_"
f"{short_hash(url)}.{guess_ext_from_url(url)}"
)
def first_row_no_by_plan_id(rows: Sequence[Mapping[str, Any]]) -> dict[str, int]:
out: dict[str, int] = {}
for row in rows:
plan_id = str(row.get("planId") or "").strip()
if not plan_id or plan_id in out:
continue
try:
out[plan_id] = int(row.get("rowNo") or 0)
except (TypeError, ValueError):
out[plan_id] = 0
return out
def build_hyperlink_formula(rel_path: str, display: str) -> str:
path = str(rel_path).replace('"', '""')
text = sanitize_zip_segment(display).replace('"', '""')
return f'=HYPERLINK("{path}","{text}")'
def parse_url_list(raw: Optional[str]) -> list[str]:
if not raw:
return []
text = str(raw).strip()
if not text:
return []
try:
parsed = json.loads(text)
if isinstance(parsed, list):
return [str(x).strip() for x in parsed if str(x).strip()]
except json.JSONDecodeError:
pass
return [p.strip() for p in text.split(",") if p.strip()]
def collect_hazard_cert_items(products: Sequence[Any]) -> list[dict[str, str]]:
out: list[dict[str, str]] = []
for product in products or []:
pname = sanitize_zip_segment(getattr(product, "product_name", None) or "")
specs = (
("购买证", getattr(product, "purchase_cert_url", None)),
("运输证", getattr(product, "transport_cert_url", None)),
("合法使用证明", getattr(product, "legal_use_cert_url", None)),
)
for base_label, raw in specs:
for url in parse_url_list(raw):
label = base_label if not pname or pname == "未命名" else f"{base_label}·{pname}"
out.append({"url": url, "label": label})
return out
def merge_plan_attachment_items(
document_items: Sequence[Mapping[str, str]],
hazard_items: Sequence[Mapping[str, str]],
) -> list[dict[str, str]]:
seen: set[str] = set()
out: list[dict[str, str]] = []
for item in list(document_items or []) + list(hazard_items or []):
url = str(item.get("url") or "").strip()
if not url or url in seen:
continue
seen.add(url)
out.append({"url": url, "label": str(item.get("label") or "附件")})
return out
def load_plan_products_by_plan_ids(db, *, tenant_no: str, plan_ids: list[str]):
from app.models.pl_models import PlPlanProduct
if not plan_ids:
return {}
rows = (
db.query(PlPlanProduct)
.filter(
PlPlanProduct.plan_id.in_(plan_ids),
PlPlanProduct.tenant_no == tenant_no,
PlPlanProduct.del_flag == 0,
)
.order_by(PlPlanProduct.order_num, PlPlanProduct.create_time)
.all()
)
grouped: dict[str, list] = {pid: [] for pid in plan_ids}
for row in rows:
grouped.setdefault(row.plan_id, []).append(row)
return grouped