Files
maps-saas/scripts/update_routing_engine.py
T

175 lines
7.3 KiB
Python

import re
def update_file(filepath):
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Match from // Sovereign In-App Routing Engine down to document.getElementById('stopNavBtn').addEventListener
pattern = r'// Sovereign In-App Routing Engine.*?(?=document\.getElementById\(\'stopNavBtn\'\)\.addEventListener)'
new_code = '''// Sovereign In-App Routing Engine (Strict 100% In-House, Zero Google Maps)
const SOVEREIGN_MAP_API_KEY = new URLSearchParams(window.location.search).get('key') || localStorage.getItem('map_admin_key') || localStorage.getItem('intaleq_api_key') || '';
function isPointInCountry(lat, lng, country) {
if (country === 'العراق') return lat >= 29.0 && lat <= 37.5 && lng >= 38.5 && lng <= 49.0;
if (country === 'الأردن') return lat >= 29.1 && lat <= 33.4 && lng >= 34.8 && lng <= 39.3;
if (country === 'سوريا') return lat >= 32.3 && lat <= 37.4 && lng >= 35.6 && lng <= 42.4;
if (country === 'مصر') return lat >= 21.9 && lat <= 31.7 && lng >= 24.7 && lng <= 36.9;
return false;
}
function startSovereignNavigation(lm) {
document.getElementById('landmarkDrawer').style.display = 'none';
const [gateLng, gateLat] = lm.gate;
// Authoritative national routing origins [lng, lat]
const defaultHubs = {
'العراق': [44.3661, 33.3152], // بغداد - ساحة النسور
'الأردن': [35.9106, 31.9539], // عمان - الدوار الرابع
'سوريا': [36.2765, 33.5138], // دمشق - ساحة الأمويين
'مصر': [31.2357, 30.0444] // القاهرة - ميدان التحرير
};
const fallbackHub = defaultHubs[lm.country] || defaultHubs['العراق'];
function computeAndDraw(startLng, startLat) {
// If start point is outside the landmark's sovereign road graph, snap start to national hub
if (!isPointInCountry(startLat, startLng, lm.country)) {
startLng = fallbackHub[0];
startLat = fallbackHub[1];
}
const queryParams = `fromLat=${startLat}&fromLng=${startLng}&toLat=${gateLat}&toLng=${gateLng}&profile=car&steps=true&locale=ar&key=${SOVEREIGN_MAP_API_KEY}`;
// Target local API or direct sovereign production endpoint
const isServerEnv = window.location.hostname.includes('intaleqapp.com') || window.location.port === '3201' || window.location.port === '3204';
const primaryUrl = isServerEnv
? `/api/maps/route?${queryParams}`
: `http://188.68.36.205:3200/api/maps/route?${queryParams}`;
const fallbackUrl = `http://188.68.36.205:3200/api/maps/route?${queryParams}`;
function requestRoute(urlToFetch, isFallback) {
return fetch(urlToFetch, {
headers: { 'x-api-key': SOVEREIGN_MAP_API_KEY }
})
.then(r => {
if (!r.ok) throw new Error('HTTP ' + r.status);
return r.json();
})
.catch(err => {
if (!isFallback && urlToFetch !== fallbackUrl) {
console.warn('Retrying routing via sovereign fallback endpoint...', err);
return requestRoute(fallbackUrl, true);
}
throw err;
});
}
requestRoute(primaryUrl, false)
.then(data => {
if (!data || !data.points) throw new Error('No road geometry returned');
const coords = typeof data.points === 'string' ? decodePolyline(data.points) : data.points;
if (!coords || coords.length < 2) throw new Error('Empty polyline nodes');
const distKm = (data.distance / 1000).toFixed(1);
const etaMins = Math.round(data.duration ? data.duration / 60 : (data.time ? data.time / 60000 : (parseFloat(distKm) / 75) * 60));
const routeName = data.routeName || 'شبكة الطرق الوطنية السريعة';
const instruction = (data.instructions && data.instructions.length > 1)
? `${routeName} • ${data.instructions[1].text}`
: `🛣️ ${routeName} مباشرة إلى بوابة الموقع ومواقف الحافلات`;
drawRouteOnMap(coords, distKm, etaMins, lm, instruction, routeName);
})
.catch(err => {
console.error('Sovereign routing engine error:', err);
alert('تم استدعاء مسار الطرق، يرجى التحقق من اتصال محرك التوجيه السيادي.');
});
}
// 1. Calculate immediately from national hub for zero-latency response
computeAndDraw(fallbackHub[0], fallbackHub[1]);
// 2. If live GPS is granted and inside the same country, refine route seamlessly
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
pos => {
if (isPointInCountry(pos.coords.latitude, pos.coords.longitude, lm.country)) {
computeAndDraw(pos.coords.longitude, pos.coords.latitude);
}
},
err => console.log('Geolocation note:', err.message),
{ timeout: 2500 }
);
}
}
function drawRouteOnMap(coords, distKm, etaMins, lm, instruction, routeName) {
const geojson = {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: coords
}
};
if (map.getSource('sovereign-route')) {
map.getSource('sovereign-route').setData(geojson);
} else {
map.addSource('sovereign-route', {
type: 'geojson',
data: geojson
});
map.addLayer({
id: 'sovereign-route-casing',
type: 'line',
source: 'sovereign-route',
layout: { 'line-join': 'round', 'line-cap': 'round' },
paint: {
'line-color': '#0369a1',
'line-width': 8,
'line-opacity': 0.85
}
});
map.addLayer({
id: 'sovereign-route-core',
type: 'line',
source: 'sovereign-route',
layout: { 'line-join': 'round', 'line-cap': 'round' },
paint: {
'line-color': '#38bdf8',
'line-width': 4.5
}
});
}
const bounds = coords.reduce((b, coord) => b.extend(coord), new maplibregl.LngLatBounds(coords[0], coords[0]));
map.fitBounds(bounds, { padding: 90, pitch: 40, bearing: 5, duration: 1800 });
document.getElementById('navDestName').innerText = `بوابة ${lm.name_ar} (نقطة العبور ومواقف الحافلات)`;
document.getElementById('navDistance').innerText = distKm;
document.getElementById('navEta').innerText = etaMins;
document.getElementById('navInstruction').innerText = instruction || 'اسلك المسار المضاء نحو نقطة الوصول';
document.getElementById('sovereignNavHud').style.display = 'block';
}
'''
new_content = re.sub(pattern, new_code, content, flags=re.DOTALL)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f'Updated {filepath}')
files = [
'apps/dashboard/tourism.html',
'apps/dashboard/tourism/index.html',
'apps/web/public/tourism.html',
'apps/web/public/tourism/index.html'
]
for fp in files:
update_file(fp)