ZipCodeCoordinatesService.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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::debug('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. $origin = $this->resolve($originLatitude, $originLongitude, $originZipCode);
  39. $target = $this->resolve($targetLatitude, $targetLongitude, $targetZipCode);
  40. return DistanceService::calculate(
  41. $origin['latitude'] ?? null,
  42. $origin['longitude'] ?? null,
  43. $target['latitude'] ?? null,
  44. $target['longitude'] ?? null,
  45. );
  46. }
  47. public function findByZipCode(?string $zipCode): ?array
  48. {
  49. $zipCode = $this->normalize($zipCode);
  50. if ($zipCode === null) {
  51. Log::info('ZipCodeCoordinates skipped lookup: invalid zip code');
  52. return null;
  53. }
  54. if (array_key_exists($zipCode, $this->resolvedZipCodes)) {
  55. Log::debug('ZipCodeCoordinates memory cache hit', [
  56. 'zip_code' => $zipCode,
  57. 'found' => $this->resolvedZipCodes[$zipCode] !== null,
  58. ]);
  59. return $this->resolvedZipCodes[$zipCode];
  60. }
  61. if ($this->restoreFromCache($zipCode)) {
  62. Log::debug('ZipCodeCoordinates persistent cache hit', [
  63. 'zip_code' => $zipCode,
  64. 'found' => $this->resolvedZipCodes[$zipCode] !== null,
  65. ]);
  66. return $this->resolvedZipCodes[$zipCode];
  67. }
  68. Log::info('ZipCodeCoordinates Brasil API lookup required', [
  69. 'zip_code' => $zipCode,
  70. 'mode' => 'single',
  71. ]);
  72. $coordinates = $this->requestCoordinates($zipCode);
  73. $this->remember($zipCode, $coordinates);
  74. return $coordinates;
  75. }
  76. public function preload(iterable $zipCodes): void
  77. {
  78. $pending = [];
  79. foreach ($zipCodes as $zipCode) {
  80. $zipCode = $this->normalize($zipCode);
  81. if (
  82. $zipCode === null
  83. || array_key_exists($zipCode, $this->resolvedZipCodes)
  84. || $this->restoreFromCache($zipCode)
  85. ) {
  86. continue;
  87. }
  88. $pending[$zipCode] = $zipCode;
  89. }
  90. if ($pending === []) {
  91. Log::debug('ZipCodeCoordinates preload skipped: no pending zip codes');
  92. return;
  93. }
  94. Log::info('ZipCodeCoordinates Brasil API lookup required', [
  95. 'mode' => 'preload',
  96. 'pending_count' => count($pending),
  97. 'zip_codes_sample' => array_slice(array_values($pending), 0, 20),
  98. ]);
  99. try {
  100. $baseUrl = rtrim((string) config('services.brasil_api.base_url'), '/');
  101. $responses = Http::pool(fn (Pool $pool) => array_map(
  102. fn (string $zipCode) => $pool
  103. ->as($zipCode)
  104. ->acceptJson()
  105. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  106. ->timeout((int) config('services.brasil_api.timeout', 3))
  107. ->get("{$baseUrl}/api/cep/v2/{$zipCode}"),
  108. $pending,
  109. ));
  110. } catch (Throwable $exception) {
  111. Log::warning('ZipCodeCoordinates Brasil API preload failed', [
  112. 'pending_count' => count($pending),
  113. 'error' => $exception->getMessage(),
  114. ]);
  115. $responses = [];
  116. }
  117. foreach ($pending as $zipCode) {
  118. $response = $responses[$zipCode] ?? null;
  119. $coordinates = $response instanceof Response
  120. ? $this->coordinatesFromResponse($response)
  121. : null;
  122. Log::info('ZipCodeCoordinates Brasil API preload response', [
  123. 'zip_code' => $zipCode,
  124. 'has_response' => $response instanceof Response,
  125. 'status' => $response instanceof Response ? $response->status() : null,
  126. 'found' => $coordinates !== null,
  127. 'coordinates' => $coordinates,
  128. ]);
  129. $this->remember($zipCode, $coordinates);
  130. }
  131. }
  132. private function normalize(?string $zipCode): ?string
  133. {
  134. $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
  135. return strlen($zipCode) === 8 ? $zipCode : null;
  136. }
  137. private function restoreFromCache(string $zipCode): bool
  138. {
  139. $cached = Cache::get("zip-code-coordinates:{$zipCode}");
  140. if (! is_array($cached) || ! array_key_exists('found', $cached)) {
  141. return false;
  142. }
  143. $this->resolvedZipCodes[$zipCode] = $cached['found']
  144. ? $cached['coordinates']
  145. : null;
  146. return true;
  147. }
  148. private function remember(string $zipCode, ?array $coordinates): void
  149. {
  150. $this->resolvedZipCodes[$zipCode] = $coordinates;
  151. Cache::put(
  152. "zip-code-coordinates:{$zipCode}",
  153. [
  154. 'found' => $coordinates !== null,
  155. 'coordinates' => $coordinates,
  156. ],
  157. now()->addSeconds(
  158. $coordinates !== null
  159. ? (int) config('services.brasil_api.cep_cache_ttl', 2592000)
  160. : (int) config('services.brasil_api.cep_failure_cache_ttl', 600)
  161. )
  162. );
  163. }
  164. private function requestCoordinates(string $zipCode): ?array
  165. {
  166. try {
  167. Log::info('ZipCodeCoordinates calling Brasil API', [
  168. 'zip_code' => $zipCode,
  169. 'base_url' => rtrim((string) config('services.brasil_api.base_url'), '/'),
  170. ]);
  171. $response = Http::baseUrl(rtrim((string) config('services.brasil_api.base_url'), '/'))
  172. ->acceptJson()
  173. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  174. ->timeout((int) config('services.brasil_api.timeout', 3))
  175. ->get("api/cep/v2/{$zipCode}");
  176. $coordinates = $this->coordinatesFromResponse($response);
  177. Log::info('ZipCodeCoordinates Brasil API response', [
  178. 'zip_code' => $zipCode,
  179. 'status' => $response->status(),
  180. 'found' => $coordinates !== null,
  181. 'coordinates' => $coordinates,
  182. ]);
  183. return $coordinates;
  184. } catch (Throwable $exception) {
  185. Log::warning('ZipCodeCoordinates Brasil API request failed', [
  186. 'zip_code' => $zipCode,
  187. 'error' => $exception->getMessage(),
  188. ]);
  189. return null;
  190. }
  191. }
  192. private function coordinatesFromResponse(Response $response): ?array
  193. {
  194. if (! $response->successful()) {
  195. return null;
  196. }
  197. $latitude = $response->json('location.coordinates.latitude');
  198. $longitude = $response->json('location.coordinates.longitude');
  199. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  200. return null;
  201. }
  202. $latitude = (float) $latitude;
  203. $longitude = (float) $longitude;
  204. if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
  205. return null;
  206. }
  207. return compact('latitude', 'longitude');
  208. }
  209. }