-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
221 lines (178 loc) · 7.57 KB
/
Copy pathutils.py
File metadata and controls
221 lines (178 loc) · 7.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# -*- coding: utf-8 -*-
"""
ControlIA SaaS — Utility Functions
Text splitting, Google Maps API helpers, geo calculations, and phone sanitization.
REMOVED from V1:
- is_admin() → replaced by middleware.requiere_suscripcion
- is_blacklisted() → removed (no fixed business types in SaaS)
- ADMIN_ID import → removed
- BLACKLIST_KEYWORDS import → removed
"""
import re
import math
import json
import urllib.request
from urllib.parse import quote, urlencode
from config import GOOGLE_API_KEY, MAX_WAYPOINTS, logger
# =========================================================================
# TENANT HELPER
# =========================================================================
def get_vendedor_id(message):
"""Extract the vendor's Telegram chat_id from a message.
This is the universal Tenant ID across the entire SaaS."""
return message.from_user.id
# =========================================================================
# TEXT HELPERS
# =========================================================================
def safe_split(text, max_len=4000):
"""Split text for Telegram without breaking HTML tags."""
parts = []
while text:
if len(text) <= max_len:
parts.append(text)
break
idx = text[:max_len].rfind("\n\n")
if idx == -1:
idx = text[:max_len].rfind("\n")
if idx == -1:
idx = max_len
parts.append(text[:idx])
text = text[idx:].lstrip("\n")
return parts
def sanitize_phone_co(raw_phone):
"""Sanitize a Colombian phone number for WhatsApp links."""
phone = re.sub(r"[^0-9]", "", (raw_phone or "").strip())
if phone.startswith("57") and len(phone) > 10:
pass # Already has country code
elif len(phone) == 10:
phone = "57" + phone
elif len(phone) == 7:
phone = "571" + phone # Bogota landline
return phone
def format_cop(amount):
"""Format a number as Colombian Pesos: $1,234,567"""
try:
return f"${amount:,.0f}".replace(",", ".")
except (TypeError, ValueError):
return "$0"
# =========================================================================
# GOOGLE MAPS API
# =========================================================================
def google_api_get(base_url, params):
"""Make a GET request to a Google API and return parsed JSON."""
query = urlencode(params)
url = f"{base_url}?{query}"
req = urllib.request.Request(url, headers={"User-Agent": "ControlIA-SaaS/2.0"})
with urllib.request.urlopen(req, timeout=15) as resp:
return json.loads(resp.read().decode("utf-8"))
def geocode_address(address):
"""Convert an address string to (lat, lng) using Google Geocoding API."""
data = google_api_get(
"https://maps.googleapis.com/maps/api/geocode/json",
{"address": address, "region": "co", "key": GOOGLE_API_KEY}
)
if data.get("status") == "OK" and data.get("results"):
loc = data["results"][0]["geometry"]["location"]
return loc["lat"], loc["lng"]
return None, None
def search_nearby_places(lat, lng, keyword, radius=1500):
"""Search for businesses near coordinates using Google Places Nearby Search."""
data = google_api_get(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json",
{
"location": f"{lat},{lng}",
"radius": radius,
"keyword": keyword,
"language": "es",
"key": GOOGLE_API_KEY,
}
)
if data.get("status") in ("OK", "ZERO_RESULTS"):
return data.get("results", [])
return []
def haversine_distance(lat1, lng1, lat2, lng2):
"""Calculate distance in meters between two coordinates."""
R = 6371000 # Earth radius in meters
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lng2 - lng1)
a = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
# =========================================================================
# ROUTE BUILDING
# =========================================================================
def build_google_maps_url(origin, waypoints, destination, travel_mode):
"""Build a single Google Maps direction URL. Accepts strings or (lat,lng) tuples."""
def _encode(point):
if isinstance(point, (list, tuple)) and len(point) == 2:
return f"{point[0]},{point[1]}"
return quote(str(point), safe=",")
url = f"https://www.google.com/maps/dir/?api=1&travelmode={travel_mode}"
url += f"&origin={_encode(origin)}"
if waypoints:
encoded_wps = "|".join([_encode(w) for w in waypoints])
url += f"&waypoints={encoded_wps}"
url += f"&destination={_encode(destination)}"
return url
def build_walking_route(origin, stops, destination, stop_names=None):
"""
Build Google Maps walking route URLs with clear segment labels.
Args:
origin: Starting point (str or (lat,lng))
stops: List of waypoints ((lat,lng) tuples or address strings)
destination: End point (str or (lat,lng))
stop_names: Optional list of names for each stop (for labels)
Returns:
List of (label, url) tuples
"""
if not stops:
url = build_google_maps_url(origin, [], destination, "walking")
return [("🗺️ Ruta directa al destino", url)]
links = []
if len(stops) <= MAX_WAYPOINTS:
url = build_google_maps_url(origin, stops, destination, "walking")
total = len(stops)
links.append((f"🗺️ Ruta completa ({total} paradas)", url))
else:
# Split into segments with clear chaining
chunks = [stops[i:i + MAX_WAYPOINTS] for i in range(0, len(stops), MAX_WAYPOINTS)]
current_origin = origin
accumulated = 0
for idx, chunk in enumerate(chunks):
is_last = (idx == len(chunks) - 1)
if is_last:
chunk_dest = destination
dest_label = "→ DESTINO FINAL"
else:
chunk_dest = chunk[-1]
chunk = chunk[:-1]
dest_label = f"→ Parada #{accumulated + len(chunk) + 1}"
url = build_google_maps_url(current_origin, chunk, chunk_dest, "walking")
start_num = accumulated + 1
end_num = accumulated + len(chunk) + (1 if not is_last else 0)
label = f"🗺️ Tramo {idx + 1}: Paradas {start_num}-{end_num} {dest_label}"
links.append((label, url))
accumulated += len(chunk) + (1 if not is_last else 0)
if not is_last:
current_origin = chunk_dest
return links
def build_google_maps_links(origin, addresses, destination, travel_mode):
"""Build Google Maps URLs for driving routes (used by /ruta_camion)."""
if not addresses and not destination:
return []
all_stops = list(addresses)
links = []
if len(all_stops) <= MAX_WAYPOINTS:
url = build_google_maps_url(origin, all_stops, destination, travel_mode)
links.append(("Ruta", url))
else:
chunks = [all_stops[i:i + MAX_WAYPOINTS] for i in range(0, len(all_stops), MAX_WAYPOINTS)]
for idx, chunk in enumerate(chunks):
if idx == len(chunks) - 1:
url = build_google_maps_url(origin, chunk, destination, travel_mode)
else:
last_stop = chunk.pop()
url = build_google_maps_url(origin, chunk, last_stop, travel_mode)
origin = last_stop
links.append((f"Ruta {idx + 1}", url))
return links