ZipCodeCoordinatesService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Http\Client\Pool;
  4. use Illuminate\Http\Client\Response;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Http;
  7. use Illuminate\Support\Facades\Log;
  8. use Throwable;
  9. class ZipCodeCoordinatesService
  10. {
  11. private array $resolvedZipCodes = [];
  12. public function resolve(?float $latitude, ?float $longitude, ?string $zipCode): ?array
  13. {
  14. Log::info('ZipCodeCoordinates resolve entered', [
  15. 'has_latitude' => $latitude !== null,
  16. 'has_longitude' => $longitude !== null,
  17. 'zip_code' => $this->normalize($zipCode),
  18. ]);
  19. if ($latitude !== null && $longitude !== null) {
  20. Log::info('ZipCodeCoordinates resolve using address coordinates', [
  21. 'latitude' => $latitude,
  22. 'longitude' => $longitude,
  23. 'zip_code' => $this->normalize($zipCode),
  24. ]);
  25. return compact('latitude', 'longitude');
  26. }
  27. Log::info('ZipCodeCoordinates fallback to zip code lookup', [
  28. 'zip_code' => $this->normalize($zipCode),
  29. 'has_latitude' => $latitude !== null,
  30. 'has_longitude' => $longitude !== null,
  31. 'reason' => 'missing_address_coordinates',
  32. ]);
  33. return $this->findByZipCode($zipCode);
  34. }
  35. public function calculateDistance(
  36. ?float $originLatitude,
  37. ?float $originLongitude,
  38. ?string $originZipCode,
  39. ?float $targetLatitude,
  40. ?float $targetLongitude,
  41. ?string $targetZipCode,
  42. ): ?float {
  43. Log::info('ZipCodeCoordinates calculate distance requested', [
  44. 'origin_has_latitude' => $originLatitude !== null,
  45. 'origin_has_longitude' => $originLongitude !== null,
  46. 'origin_zip_code' => $this->normalize($originZipCode),
  47. 'target_has_latitude' => $targetLatitude !== null,
  48. 'target_has_longitude' => $targetLongitude !== null,
  49. 'target_zip_code' => $this->normalize($targetZipCode),
  50. ]);
  51. $origin = $this->resolve($originLatitude, $originLongitude, $originZipCode);
  52. $target = $this->resolve($targetLatitude, $targetLongitude, $targetZipCode);
  53. $distance = DistanceService::calculate(
  54. $origin['latitude'] ?? null,
  55. $origin['longitude'] ?? null,
  56. $target['latitude'] ?? null,
  57. $target['longitude'] ?? null,
  58. );
  59. Log::info('ZipCodeCoordinates calculate distance result', [
  60. 'origin_found' => $origin !== null,
  61. 'target_found' => $target !== null,
  62. 'distance_km' => $distance,
  63. ]);
  64. return $distance;
  65. }
  66. public function findByZipCode(?string $zipCode): ?array
  67. {
  68. $zipCode = $this->normalize($zipCode);
  69. if ($zipCode === null) {
  70. Log::info('ZipCodeCoordinates skipped lookup: invalid zip code');
  71. return null;
  72. }
  73. if (array_key_exists($zipCode, $this->resolvedZipCodes)) {
  74. Log::info('ZipCodeCoordinates memory cache hit', [
  75. 'zip_code' => $zipCode,
  76. 'found' => $this->resolvedZipCodes[$zipCode] !== null,
  77. ]);
  78. return $this->resolvedZipCodes[$zipCode];
  79. }
  80. if ($this->restoreFromCache($zipCode)) {
  81. Log::info('ZipCodeCoordinates persistent cache hit', [
  82. 'zip_code' => $zipCode,
  83. 'found' => $this->resolvedZipCodes[$zipCode] !== null,
  84. ]);
  85. return $this->resolvedZipCodes[$zipCode];
  86. }
  87. if (! $this->googleGeocodingIsConfigured()) {
  88. Log::warning('ZipCodeCoordinates Google Geocoding skipped: API key is not configured');
  89. return $this->resolvedZipCodes[$zipCode] = null;
  90. }
  91. Log::info('ZipCodeCoordinates Google Geocoding lookup required', [
  92. 'zip_code' => $zipCode,
  93. 'mode' => 'single',
  94. ]);
  95. $coordinates = $this->requestCoordinates($zipCode);
  96. $this->remember($zipCode, $coordinates);
  97. return $coordinates;
  98. }
  99. public function preload(iterable $zipCodes): void
  100. {
  101. $pending = [];
  102. foreach ($zipCodes as $zipCode) {
  103. $zipCode = $this->normalize($zipCode);
  104. if (
  105. $zipCode === null
  106. || array_key_exists($zipCode, $this->resolvedZipCodes)
  107. || $this->restoreFromCache($zipCode)
  108. ) {
  109. continue;
  110. }
  111. $pending[$zipCode] = $zipCode;
  112. }
  113. if ($pending === []) {
  114. Log::info('ZipCodeCoordinates preload skipped: no pending zip codes');
  115. return;
  116. }
  117. if (! $this->googleGeocodingIsConfigured()) {
  118. Log::warning('ZipCodeCoordinates Google Geocoding preload skipped: API key is not configured', [
  119. 'pending_count' => count($pending),
  120. ]);
  121. foreach ($pending as $zipCode) {
  122. $this->resolvedZipCodes[$zipCode] = null;
  123. }
  124. return;
  125. }
  126. Log::info('ZipCodeCoordinates Google Geocoding lookup required', [
  127. 'mode' => 'preload',
  128. 'pending_count' => count($pending),
  129. 'zip_codes_sample' => array_slice(array_values($pending), 0, 20),
  130. 'connect_timeout' => (int) config('services.google_geocoding.connect_timeout', 2),
  131. 'timeout' => (int) config('services.google_geocoding.timeout', 5),
  132. 'ip_resolve' => 'ipv4',
  133. ]);
  134. try {
  135. $baseUrl = rtrim((string) config('services.google_geocoding.base_url'), '/');
  136. $startedAt = microtime(true);
  137. $responses = Http::pool(fn (Pool $pool) => array_map(
  138. fn (string $zipCode) => $pool
  139. ->as($zipCode)
  140. ->acceptJson()
  141. ->connectTimeout((int) config('services.google_geocoding.connect_timeout', 2))
  142. ->timeout((int) config('services.google_geocoding.timeout', 5))
  143. ->withOptions($this->curlForceIpv4Options())
  144. ->get("{$baseUrl}/maps/api/geocode/json", $this->googleQuery($zipCode)),
  145. $pending,
  146. ));
  147. } catch (Throwable $exception) {
  148. Log::warning('ZipCodeCoordinates Google Geocoding preload failed', [
  149. 'pending_count' => count($pending),
  150. 'elapsed_ms' => isset($startedAt) ? round((microtime(true) - $startedAt) * 1000, 2) : null,
  151. 'error' => $exception->getMessage(),
  152. ]);
  153. $responses = [];
  154. }
  155. foreach ($pending as $zipCode) {
  156. $response = $responses[$zipCode] ?? null;
  157. $coordinates = $response instanceof Response
  158. ? $this->coordinatesFromResponse($response)
  159. : null;
  160. Log::info('ZipCodeCoordinates Google Geocoding preload response', [
  161. 'zip_code' => $zipCode,
  162. 'has_response' => $response instanceof Response,
  163. 'status' => $response instanceof Response ? $response->status() : null,
  164. 'elapsed_ms' => isset($startedAt) ? round((microtime(true) - $startedAt) * 1000, 2) : null,
  165. 'found' => $coordinates !== null,
  166. 'coordinates' => $coordinates,
  167. 'body' => $coordinates === null && $response instanceof Response
  168. ? $response->json()
  169. : null,
  170. ]);
  171. $this->remember($zipCode, $coordinates);
  172. }
  173. }
  174. //
  175. private function coordinatesFromResponse(Response $response): ?array
  176. {
  177. if (! $response->successful()) {
  178. return null;
  179. }
  180. if ($response->json('status') !== 'OK') {
  181. return null;
  182. }
  183. $latitude = $response->json('results.0.geometry.location.lat');
  184. $longitude = $response->json('results.0.geometry.location.lng');
  185. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  186. return null;
  187. }
  188. $latitude = (float) $latitude;
  189. $longitude = (float) $longitude;
  190. if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
  191. return null;
  192. }
  193. return compact('latitude', 'longitude');
  194. }
  195. private function curlForceIpv4Options(): array
  196. {
  197. if (! defined('CURLOPT_IPRESOLVE') || ! defined('CURL_IPRESOLVE_V4')) {
  198. return [];
  199. }
  200. return [
  201. 'curl' => [
  202. CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
  203. ],
  204. ];
  205. }
  206. private function googleGeocodingIsConfigured(): bool
  207. {
  208. return trim((string) config('services.google_geocoding.api_key')) !== '';
  209. }
  210. private function googleQuery(string $zipCode): array
  211. {
  212. return [
  213. 'components' => "postal_code:{$zipCode}|country:BR",
  214. 'language' => 'pt-BR',
  215. 'region' => 'br',
  216. 'key' => (string) config('services.google_geocoding.api_key'),
  217. ];
  218. }
  219. private function normalize(?string $zipCode): ?string
  220. {
  221. $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
  222. return strlen($zipCode) === 8 ? $zipCode : null;
  223. }
  224. private function remember(string $zipCode, ?array $coordinates): void
  225. {
  226. $this->resolvedZipCodes[$zipCode] = $coordinates;
  227. if ($coordinates === null) {
  228. Log::info('ZipCodeCoordinates failure not cached', [
  229. 'zip_code' => $zipCode,
  230. ]);
  231. return;
  232. }
  233. Cache::put(
  234. "zip-code-coordinates:{$zipCode}",
  235. [
  236. 'found' => $coordinates !== null,
  237. 'coordinates' => $coordinates,
  238. ],
  239. now()->addSeconds(
  240. (int) config('services.google_geocoding.cache_ttl', 2592000)
  241. )
  242. );
  243. }
  244. private function requestCoordinates(string $zipCode): ?array
  245. {
  246. $startedAt = microtime(true);
  247. try {
  248. Log::info('ZipCodeCoordinates calling Google Geocoding', [
  249. 'zip_code' => $zipCode,
  250. 'base_url' => rtrim((string) config('services.google_geocoding.base_url'), '/'),
  251. 'connect_timeout' => (int) config('services.google_geocoding.connect_timeout', 2),
  252. 'timeout' => (int) config('services.google_geocoding.timeout', 5),
  253. 'ip_resolve' => 'ipv4',
  254. ]);
  255. $baseUrl = rtrim((string) config('services.google_geocoding.base_url'), '/');
  256. $response = Http::acceptJson()
  257. ->withOptions($this->curlForceIpv4Options())
  258. ->connectTimeout((int) config('services.google_geocoding.connect_timeout', 2))
  259. ->timeout((int) config('services.google_geocoding.timeout', 5))
  260. ->get("{$baseUrl}/maps/api/geocode/json", $this->googleQuery($zipCode));
  261. $coordinates = $this->coordinatesFromResponse($response);
  262. Log::info('ZipCodeCoordinates Google Geocoding response', [
  263. 'zip_code' => $zipCode,
  264. 'status' => $response->status(),
  265. 'elapsed_ms' => round((microtime(true) - $startedAt) * 1000, 2),
  266. 'found' => $coordinates !== null,
  267. 'coordinates' => $coordinates,
  268. 'body' => $coordinates === null ? $response->json() : null,
  269. ]);
  270. return $coordinates;
  271. } catch (Throwable $exception) {
  272. Log::warning('ZipCodeCoordinates Google Geocoding request failed', [
  273. 'zip_code' => $zipCode,
  274. 'elapsed_ms' => round((microtime(true) - $startedAt) * 1000, 2),
  275. 'error' => $exception->getMessage(),
  276. ]);
  277. return null;
  278. }
  279. }
  280. private function restoreFromCache(string $zipCode): bool
  281. {
  282. $cacheKey = "zip-code-coordinates:{$zipCode}";
  283. $cached = Cache::get($cacheKey);
  284. if (! is_array($cached) || ! array_key_exists('found', $cached)) {
  285. return false;
  286. }
  287. if (! $cached['found']) {
  288. Cache::forget($cacheKey);
  289. Log::info('ZipCodeCoordinates negative cache ignored', [
  290. 'zip_code' => $zipCode,
  291. 'reason' => 'retry_lookup_after_previous_failure',
  292. ]);
  293. return false;
  294. }
  295. $this->resolvedZipCodes[$zipCode] = $cached['found']
  296. ? $cached['coordinates']
  297. : null;
  298. return true;
  299. }
  300. }