ZipCodeCoordinatesService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. if ($latitude !== null && $longitude !== null) {
  15. Log::info('ZipCodeCoordinates resolve using address coordinates', [
  16. 'latitude' => $latitude,
  17. 'longitude' => $longitude,
  18. 'zip_code' => $this->normalize($zipCode),
  19. ]);
  20. return compact('latitude', 'longitude');
  21. }
  22. Log::info('ZipCodeCoordinates fallback to zip code lookup', [
  23. 'zip_code' => $this->normalize($zipCode),
  24. 'has_latitude' => $latitude !== null,
  25. 'has_longitude' => $longitude !== null,
  26. 'reason' => 'missing_address_coordinates',
  27. ]);
  28. return $this->findByZipCode($zipCode);
  29. }
  30. public function calculateDistance(
  31. ?float $originLatitude,
  32. ?float $originLongitude,
  33. ?string $originZipCode,
  34. ?float $targetLatitude,
  35. ?float $targetLongitude,
  36. ?string $targetZipCode,
  37. ): ?float {
  38. Log::info('ZipCodeCoordinates calculate distance requested', [
  39. 'origin_has_latitude' => $originLatitude !== null,
  40. 'origin_has_longitude' => $originLongitude !== null,
  41. 'origin_zip_code' => $this->normalize($originZipCode),
  42. 'target_has_latitude' => $targetLatitude !== null,
  43. 'target_has_longitude' => $targetLongitude !== null,
  44. 'target_zip_code' => $this->normalize($targetZipCode),
  45. ]);
  46. $origin = $this->resolve($originLatitude, $originLongitude, $originZipCode);
  47. $target = $this->resolve($targetLatitude, $targetLongitude, $targetZipCode);
  48. $distance = DistanceService::calculate(
  49. $origin['latitude'] ?? null,
  50. $origin['longitude'] ?? null,
  51. $target['latitude'] ?? null,
  52. $target['longitude'] ?? null,
  53. );
  54. Log::info('ZipCodeCoordinates calculate distance result', [
  55. 'origin_found' => $origin !== null,
  56. 'target_found' => $target !== null,
  57. 'distance_km' => $distance,
  58. ]);
  59. return $distance;
  60. }
  61. public function findByZipCode(?string $zipCode): ?array
  62. {
  63. $zipCode = $this->normalize($zipCode);
  64. if ($zipCode === null) {
  65. Log::info('ZipCodeCoordinates skipped lookup: invalid zip code');
  66. return null;
  67. }
  68. if (array_key_exists($zipCode, $this->resolvedZipCodes)) {
  69. Log::info('ZipCodeCoordinates memory cache hit', [
  70. 'zip_code' => $zipCode,
  71. 'found' => $this->resolvedZipCodes[$zipCode] !== null,
  72. ]);
  73. return $this->resolvedZipCodes[$zipCode];
  74. }
  75. if ($this->restoreFromCache($zipCode)) {
  76. Log::info('ZipCodeCoordinates persistent cache hit', [
  77. 'zip_code' => $zipCode,
  78. 'found' => $this->resolvedZipCodes[$zipCode] !== null,
  79. ]);
  80. return $this->resolvedZipCodes[$zipCode];
  81. }
  82. Log::info('ZipCodeCoordinates Brasil API lookup required', [
  83. 'zip_code' => $zipCode,
  84. 'mode' => 'single',
  85. ]);
  86. $coordinates = $this->requestCoordinates($zipCode);
  87. $this->remember($zipCode, $coordinates);
  88. return $coordinates;
  89. }
  90. public function preload(iterable $zipCodes): void
  91. {
  92. $pending = [];
  93. foreach ($zipCodes as $zipCode) {
  94. $zipCode = $this->normalize($zipCode);
  95. if (
  96. $zipCode === null
  97. || array_key_exists($zipCode, $this->resolvedZipCodes)
  98. || $this->restoreFromCache($zipCode)
  99. ) {
  100. continue;
  101. }
  102. $pending[$zipCode] = $zipCode;
  103. }
  104. if ($pending === []) {
  105. Log::info('ZipCodeCoordinates preload skipped: no pending zip codes');
  106. return;
  107. }
  108. Log::info('ZipCodeCoordinates Brasil API lookup required', [
  109. 'mode' => 'preload',
  110. 'pending_count' => count($pending),
  111. 'zip_codes_sample' => array_slice(array_values($pending), 0, 20),
  112. 'connect_timeout' => (int) config('services.brasil_api.connect_timeout', 2),
  113. 'timeout' => (int) config('services.brasil_api.timeout', 3),
  114. 'ip_resolve' => 'ipv4',
  115. ]);
  116. try {
  117. $baseUrl = rtrim((string) config('services.brasil_api.base_url'), '/');
  118. $startedAt = microtime(true);
  119. $responses = Http::pool(fn (Pool $pool) => array_map(
  120. fn (string $zipCode) => $pool
  121. ->as($zipCode)
  122. ->acceptJson()
  123. ->withUserAgent($this->brasilApiUserAgent())
  124. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  125. ->timeout((int) config('services.brasil_api.timeout', 3))
  126. ->withOptions($this->curlForceIpv4Options())
  127. ->get("{$baseUrl}/api/cep/v2/{$zipCode}"),
  128. $pending,
  129. ));
  130. } catch (Throwable $exception) {
  131. Log::warning('ZipCodeCoordinates Brasil API preload failed', [
  132. 'pending_count' => count($pending),
  133. 'elapsed_ms' => isset($startedAt) ? round((microtime(true) - $startedAt) * 1000, 2) : null,
  134. 'error' => $exception->getMessage(),
  135. ]);
  136. $responses = [];
  137. }
  138. foreach ($pending as $zipCode) {
  139. $response = $responses[$zipCode] ?? null;
  140. $coordinates = $response instanceof Response
  141. ? $this->coordinatesFromResponse($response)
  142. : null;
  143. Log::info('ZipCodeCoordinates Brasil API preload response', [
  144. 'zip_code' => $zipCode,
  145. 'has_response' => $response instanceof Response,
  146. 'status' => $response instanceof Response ? $response->status() : null,
  147. 'elapsed_ms' => isset($startedAt) ? round((microtime(true) - $startedAt) * 1000, 2) : null,
  148. 'found' => $coordinates !== null,
  149. 'coordinates' => $coordinates,
  150. ]);
  151. $this->remember($zipCode, $coordinates);
  152. }
  153. }
  154. private function normalize(?string $zipCode): ?string
  155. {
  156. $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
  157. return strlen($zipCode) === 8 ? $zipCode : null;
  158. }
  159. private function restoreFromCache(string $zipCode): bool
  160. {
  161. $cached = Cache::get("zip-code-coordinates:{$zipCode}");
  162. if (! is_array($cached) || ! array_key_exists('found', $cached)) {
  163. return false;
  164. }
  165. $this->resolvedZipCodes[$zipCode] = $cached['found']
  166. ? $cached['coordinates']
  167. : null;
  168. return true;
  169. }
  170. private function remember(string $zipCode, ?array $coordinates): void
  171. {
  172. $this->resolvedZipCodes[$zipCode] = $coordinates;
  173. Cache::put(
  174. "zip-code-coordinates:{$zipCode}",
  175. [
  176. 'found' => $coordinates !== null,
  177. 'coordinates' => $coordinates,
  178. ],
  179. now()->addSeconds(
  180. $coordinates !== null
  181. ? (int) config('services.brasil_api.cep_cache_ttl', 2592000)
  182. : (int) config('services.brasil_api.cep_failure_cache_ttl', 600)
  183. )
  184. );
  185. }
  186. private function requestCoordinates(string $zipCode): ?array
  187. {
  188. $startedAt = microtime(true);
  189. try {
  190. Log::info('ZipCodeCoordinates calling Brasil API', [
  191. 'zip_code' => $zipCode,
  192. 'base_url' => rtrim((string) config('services.brasil_api.base_url'), '/'),
  193. 'user_agent' => $this->brasilApiUserAgent(),
  194. 'connect_timeout' => (int) config('services.brasil_api.connect_timeout', 2),
  195. 'timeout' => (int) config('services.brasil_api.timeout', 3),
  196. 'ip_resolve' => 'ipv4',
  197. ]);
  198. $baseUrl = rtrim((string) config('services.brasil_api.base_url'), '/');
  199. $response = Http::acceptJson()
  200. ->withUserAgent($this->brasilApiUserAgent())
  201. ->withOptions($this->curlForceIpv4Options())
  202. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  203. ->timeout((int) config('services.brasil_api.timeout', 3))
  204. ->get("{$baseUrl}/api/cep/v2/{$zipCode}");
  205. $coordinates = $this->coordinatesFromResponse($response);
  206. Log::info('ZipCodeCoordinates Brasil API response', [
  207. 'zip_code' => $zipCode,
  208. 'status' => $response->status(),
  209. 'elapsed_ms' => round((microtime(true) - $startedAt) * 1000, 2),
  210. 'found' => $coordinates !== null,
  211. 'coordinates' => $coordinates,
  212. ]);
  213. return $coordinates;
  214. } catch (Throwable $exception) {
  215. Log::warning('ZipCodeCoordinates Brasil API request failed', [
  216. 'zip_code' => $zipCode,
  217. 'elapsed_ms' => round((microtime(true) - $startedAt) * 1000, 2),
  218. 'error' => $exception->getMessage(),
  219. ]);
  220. return null;
  221. }
  222. }
  223. private function curlForceIpv4Options(): array
  224. {
  225. if (! defined('CURLOPT_IPRESOLVE') || ! defined('CURL_IPRESOLVE_V4')) {
  226. return [];
  227. }
  228. return [
  229. 'curl' => [
  230. CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
  231. ],
  232. ];
  233. }
  234. private function brasilApiUserAgent(): string
  235. {
  236. return 'insomnia/11.3.0';
  237. }
  238. private function coordinatesFromResponse(Response $response): ?array
  239. {
  240. if (! $response->successful()) {
  241. return null;
  242. }
  243. $latitude = $response->json('location.coordinates.latitude');
  244. $longitude = $response->json('location.coordinates.longitude');
  245. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  246. return null;
  247. }
  248. $latitude = (float) $latitude;
  249. $longitude = (float) $longitude;
  250. if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
  251. return null;
  252. }
  253. return compact('latitude', 'longitude');
  254. }
  255. }