ZipCodeCoordinatesService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. Log::info('ZipCodeCoordinates Brasil API lookup required', [
  88. 'zip_code' => $zipCode,
  89. 'mode' => 'single',
  90. ]);
  91. $coordinates = $this->requestCoordinates($zipCode);
  92. $this->remember($zipCode, $coordinates);
  93. return $coordinates;
  94. }
  95. public function preload(iterable $zipCodes): void
  96. {
  97. $pending = [];
  98. foreach ($zipCodes as $zipCode) {
  99. $zipCode = $this->normalize($zipCode);
  100. if (
  101. $zipCode === null
  102. || array_key_exists($zipCode, $this->resolvedZipCodes)
  103. || $this->restoreFromCache($zipCode)
  104. ) {
  105. continue;
  106. }
  107. $pending[$zipCode] = $zipCode;
  108. }
  109. if ($pending === []) {
  110. Log::info('ZipCodeCoordinates preload skipped: no pending zip codes');
  111. return;
  112. }
  113. Log::info('ZipCodeCoordinates Brasil API lookup required', [
  114. 'mode' => 'preload',
  115. 'pending_count' => count($pending),
  116. 'zip_codes_sample' => array_slice(array_values($pending), 0, 20),
  117. 'connect_timeout' => (int) config('services.brasil_api.connect_timeout', 2),
  118. 'timeout' => (int) config('services.brasil_api.timeout', 3),
  119. 'ip_resolve' => 'ipv4',
  120. ]);
  121. try {
  122. $baseUrl = rtrim((string) config('services.brasil_api.base_url'), '/');
  123. $startedAt = microtime(true);
  124. $responses = Http::pool(fn (Pool $pool) => array_map(
  125. fn (string $zipCode) => $pool
  126. ->as($zipCode)
  127. ->acceptJson()
  128. ->withUserAgent($this->brasilApiUserAgent())
  129. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  130. ->timeout((int) config('services.brasil_api.timeout', 3))
  131. ->withOptions($this->curlForceIpv4Options())
  132. ->get("{$baseUrl}/api/cep/v2/{$zipCode}"),
  133. $pending,
  134. ));
  135. } catch (Throwable $exception) {
  136. Log::warning('ZipCodeCoordinates Brasil API preload failed', [
  137. 'pending_count' => count($pending),
  138. 'elapsed_ms' => isset($startedAt) ? round((microtime(true) - $startedAt) * 1000, 2) : null,
  139. 'error' => $exception->getMessage(),
  140. ]);
  141. $responses = [];
  142. }
  143. foreach ($pending as $zipCode) {
  144. $response = $responses[$zipCode] ?? null;
  145. $coordinates = $response instanceof Response
  146. ? $this->coordinatesFromResponse($response)
  147. : null;
  148. Log::info('ZipCodeCoordinates Brasil API preload response', [
  149. 'zip_code' => $zipCode,
  150. 'has_response' => $response instanceof Response,
  151. 'status' => $response instanceof Response ? $response->status() : null,
  152. 'elapsed_ms' => isset($startedAt) ? round((microtime(true) - $startedAt) * 1000, 2) : null,
  153. 'found' => $coordinates !== null,
  154. 'coordinates' => $coordinates,
  155. ]);
  156. $this->remember($zipCode, $coordinates);
  157. }
  158. }
  159. private function normalize(?string $zipCode): ?string
  160. {
  161. $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
  162. return strlen($zipCode) === 8 ? $zipCode : null;
  163. }
  164. private function restoreFromCache(string $zipCode): bool
  165. {
  166. $cacheKey = "zip-code-coordinates:{$zipCode}";
  167. $cached = Cache::get($cacheKey);
  168. if (! is_array($cached) || ! array_key_exists('found', $cached)) {
  169. return false;
  170. }
  171. if (! $cached['found']) {
  172. Cache::forget($cacheKey);
  173. Log::info('ZipCodeCoordinates negative cache ignored', [
  174. 'zip_code' => $zipCode,
  175. 'reason' => 'retry_lookup_after_previous_failure',
  176. ]);
  177. return false;
  178. }
  179. $this->resolvedZipCodes[$zipCode] = $cached['found']
  180. ? $cached['coordinates']
  181. : null;
  182. return true;
  183. }
  184. private function remember(string $zipCode, ?array $coordinates): void
  185. {
  186. $this->resolvedZipCodes[$zipCode] = $coordinates;
  187. if ($coordinates === null) {
  188. Log::info('ZipCodeCoordinates failure not cached', [
  189. 'zip_code' => $zipCode,
  190. ]);
  191. return;
  192. }
  193. Cache::put(
  194. "zip-code-coordinates:{$zipCode}",
  195. [
  196. 'found' => $coordinates !== null,
  197. 'coordinates' => $coordinates,
  198. ],
  199. now()->addSeconds(
  200. (int) config('services.brasil_api.cep_cache_ttl', 2592000)
  201. )
  202. );
  203. }
  204. private function requestCoordinates(string $zipCode): ?array
  205. {
  206. $startedAt = microtime(true);
  207. try {
  208. Log::info('ZipCodeCoordinates calling Brasil API', [
  209. 'zip_code' => $zipCode,
  210. 'base_url' => rtrim((string) config('services.brasil_api.base_url'), '/'),
  211. 'user_agent' => $this->brasilApiUserAgent(),
  212. 'connect_timeout' => (int) config('services.brasil_api.connect_timeout', 2),
  213. 'timeout' => (int) config('services.brasil_api.timeout', 3),
  214. 'ip_resolve' => 'ipv4',
  215. ]);
  216. $baseUrl = rtrim((string) config('services.brasil_api.base_url'), '/');
  217. $response = Http::acceptJson()
  218. ->withUserAgent($this->brasilApiUserAgent())
  219. ->withOptions($this->curlForceIpv4Options())
  220. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  221. ->timeout((int) config('services.brasil_api.timeout', 3))
  222. ->get("{$baseUrl}/api/cep/v2/{$zipCode}");
  223. $coordinates = $this->coordinatesFromResponse($response);
  224. Log::info('ZipCodeCoordinates Brasil API response', [
  225. 'zip_code' => $zipCode,
  226. 'status' => $response->status(),
  227. 'elapsed_ms' => round((microtime(true) - $startedAt) * 1000, 2),
  228. 'found' => $coordinates !== null,
  229. 'coordinates' => $coordinates,
  230. ]);
  231. return $coordinates;
  232. } catch (Throwable $exception) {
  233. Log::warning('ZipCodeCoordinates Brasil API request failed', [
  234. 'zip_code' => $zipCode,
  235. 'elapsed_ms' => round((microtime(true) - $startedAt) * 1000, 2),
  236. 'error' => $exception->getMessage(),
  237. ]);
  238. return null;
  239. }
  240. }
  241. private function curlForceIpv4Options(): array
  242. {
  243. if (! defined('CURLOPT_IPRESOLVE') || ! defined('CURL_IPRESOLVE_V4')) {
  244. return [];
  245. }
  246. return [
  247. 'curl' => [
  248. CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
  249. ],
  250. ];
  251. }
  252. private function brasilApiUserAgent(): string
  253. {
  254. return 'insomnia/11.3.0';
  255. }
  256. private function coordinatesFromResponse(Response $response): ?array
  257. {
  258. if (! $response->successful()) {
  259. return null;
  260. }
  261. $latitude = $response->json('location.coordinates.latitude');
  262. $longitude = $response->json('location.coordinates.longitude');
  263. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  264. return null;
  265. }
  266. $latitude = (float) $latitude;
  267. $longitude = (float) $longitude;
  268. if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
  269. return null;
  270. }
  271. return compact('latitude', 'longitude');
  272. }
  273. }