ZipCodeCoordinatesService.php 10.0 KB

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