""" Erzeugung der mandantenspezifischen Polyline-Datei ``str2pl-.js``. """ import ast import json import os import tempfile from pathlib import Path from flask import current_app from cmbnet.models.streets import StreetModel from cmbnet.utils.geo_utils import parse_bbox, to_float from cmbnet.utils.helpers import str2pl_filename class Str2PlService: """Erzeugt das JavaScript-Dict der Straßen-Polylines für einen Mandanten.""" @staticmethod def generate_for_tenant(tenant_id, tenant_code): """Schreibt ``static/js/str2pl-.js`` neu. Als Geometriequelle dient die gemeinsame ``str2pl.js``. Nur Straßen, die in der Datenbank des Mandanten vorhanden sind, werden übernommen. Bei gesetztem Zusatz wird der Key `` `` erzeugt; die Geometrie stammt weiterhin vom Namen ohne Zusatz. Segmente außerhalb der Straßen-Bounding-Box werden verworfen; aneinanderhängende Segmente mit identischen Endpunkten werden zusammengefasst. Rückgabe: Statistik-Dict für die Rückmeldung an die Oberfläche. """ static_folder = Path(current_app.static_folder) target = static_folder / str2pl_filename(tenant_code) source = static_folder / 'js' / 'str2pl.js' if not source.is_file(): # Falls die gemeinsame Datei fehlt, kann eine bereits vorhandene # mandantenspezifische Datei als Quelle dienen. source = target if not source.is_file(): raise FileNotFoundError( 'Weder str2pl.js noch eine mandantenspezifische ' 'Polyline-Datei gefunden.' ) source_data = _load_polylines(source) source_by_name = {} for key, value in source_data.items(): normalized = str(key).strip().casefold() if normalized and normalized not in source_by_name: source_by_name[normalized] = value streets = StreetModel.get_all_by_tenant(tenant_id) output = {} stats = { 'streets_total': len(streets), 'streets_with_geometry': 0, 'streets_without_geometry': 0, 'segments_written': 0, 'segments_outside_bbox': 0, 'segments_merged': 0, } for street in streets: name = str(street['name'] or '').strip() if not name: continue zusatz = str(street['zusatz'] or '').strip() output_key = f'{name} {zusatz}' if zusatz else name bounds = parse_bbox(street['bbox']) source_segments = _find_source_segments( source_by_name, name, zusatz ) segments = [] if isinstance(source_segments, list): oriented = _orient_segments(source_segments, bounds) kept = [] for segment in oriented: if bounds and not _segment_intersects_bbox(segment, bounds): stats['segments_outside_bbox'] += 1 continue kept.append(segment) merged = _merge_segments(kept) stats['segments_merged'] += max(len(kept) - len(merged), 0) segments = [ [[lat, lon] for lat, lon in segment] for segment in merged ] if segments: stats['streets_with_geometry'] += 1 else: stats['streets_without_geometry'] += 1 # Auch Straßen ohne passende Quelle werden mit einer leeren Liste # aufgenommen, damit das Dict ausschließlich die Straßen der # Datenbank enthält. Der Key enthält bei geteilten Straßen den # Zusatz; die Laufzeit fällt bei fehlendem Key auf den Namen zurück. if output_key in output: output[output_key] = output[output_key] + segments else: output[output_key] = segments stats['segments_written'] = sum(len(value) for value in output.values()) _write_polyline_file(target, output, tenant_code) return stats def _load_polylines(path): """Liest ``window.STRASSE2POLYLINES = { ... };`` als Python-Dict.""" text = path.read_text(encoding='utf-8') start = text.find('{') end = text.rfind('}') if start < 0 or end <= start: raise ValueError('Polyline-Datei enthält kein JavaScript-Objekt') body = text[start:end + 1] try: data = ast.literal_eval(body) except (SyntaxError, ValueError) as exc: raise ValueError(f'Polyline-Datei konnte nicht gelesen werden: {exc}') from exc if not isinstance(data, dict): raise ValueError('Polyline-Datei enthält kein Straßen-Dict') return data def _find_source_segments(source_by_name, name, zusatz): """Sucht die Ursprungsgeometrie einer Straße. Bevorzugt wird immer der Straßenname ohne Zusatz. Nur wenn dafür keine Geometrie existiert, wird der exakte Key aus Name und Zusatz verwendet. """ candidates = [name] if zusatz: candidates.append(f'{name} {zusatz}') for candidate in candidates: segments = source_by_name.get(str(candidate).strip().casefold()) if isinstance(segments, list): return segments return None def _orient_segments(segments, bounds): """Wandelt Segmentpunkte in die Reihenfolge ``[lat, lon]`` um. Das mitgelieferte Fragment enthält historisch ``[lat, lon]``, die Spezifikation nennt dagegen ``[lon, lat]``. Anhand der Straßen-Bounding-Box wird die passende Reihenfolge je Straße bestimmt. """ if bounds is None: return _clean_segments(segments, swap=False) direct = _count_inside(segments, bounds, swap=False) swapped = _count_inside(segments, bounds, swap=True) return _clean_segments(segments, swap=swapped > direct) def _count_inside(segments, bounds, swap): lat_min, lat_max, lon_min, lon_max = bounds count = 0 for segment in segments: if not isinstance(segment, (list, tuple)): continue for point in segment: if not isinstance(point, (list, tuple)) or len(point) < 2: continue first = to_float(point[0]) second = to_float(point[1]) if first is None or second is None: continue lat, lon = (second, first) if swap else (first, second) if lat_min <= lat <= lat_max and lon_min <= lon <= lon_max: count += 1 return count def _clean_segments(segments, swap): result = [] for segment in segments: if not isinstance(segment, (list, tuple)): continue points = [] for point in segment: if not isinstance(point, (list, tuple)) or len(point) < 2: continue first = to_float(point[0]) second = to_float(point[1]) if first is None or second is None: continue lat, lon = (second, first) if swap else (first, second) points.append((lat, lon)) if len(points) >= 2: result.append(points) return result def _segment_intersects_bbox(segment, bounds): """Prüft, ob das Segment die Straßen-Bounding-Box berührt.""" lat_min, lat_max, lon_min, lon_max = bounds lats = [point[0] for point in segment] lons = [point[1] for point in segment] return not ( max(lats) < lat_min or min(lats) > lat_max or max(lons) < lon_min or min(lons) > lon_max ) def _merge_segments(segments): """Fasst Segmente mit identischen Endpunkten zu einem Segment zusammen.""" merged = [list(segment) for segment in segments] changed = True while changed: changed = False for index in range(len(merged)): for other in range(index + 1, len(merged)): joined = _join_segments(merged[index], merged[other]) if joined is None: continue merged[index] = joined del merged[other] changed = True break if changed: break return merged def _join_segments(first, second): """Verbindet zwei Segmente, wenn sie einen Endpunkt teilen.""" if not first or not second: return None if first[-1] == second[0]: return first[:-1] + second if first[-1] == second[-1]: return first[:-1] + second[::-1] if first[0] == second[-1]: return second[:-1] + first if first[0] == second[0]: return first[::-1] + second[1:] return None def _write_polyline_file(target, data, tenant_code): """Schreibt die Polyline-Datei atomar.""" content = ( '// Automatisch erzeugt durch die CMBNet-Straßenverwaltung ' f'für Mandant {tenant_code}.\n' 'window.STRASSE2POLYLINES = ' + json.dumps(data, ensure_ascii=False, indent=4) + ';\n' ) target.parent.mkdir(parents=True, exist_ok=True) fd, temp_name = tempfile.mkstemp( dir=str(target.parent), prefix=f'.{target.name}.', suffix='.tmp' ) try: with os.fdopen(fd, 'w', encoding='utf-8') as handle: handle.write(content) os.replace(temp_name, target) except Exception: try: os.unlink(temp_name) except OSError: pass raise