SearchService.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\GenderEnum;
  4. use App\Models\Address;
  5. use App\Models\Client;
  6. use App\Models\Provider;
  7. use App\Rules\ScheduleBusinessRules;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Storage;
  11. class SearchService
  12. {
  13. public function __construct(
  14. private readonly ZipCodeCoordinatesService $zipCodeCoordinatesService,
  15. ) {}
  16. public function buscaPrestadores(?string $name = null, ?string $date = null): array
  17. {
  18. $user = Auth::user();
  19. $cliente = Client::where('user_id', $user->id)->first();
  20. $blockedProviderIds = ScheduleBusinessRules::getBlockedProviderIdsForClient($cliente->id);
  21. $providersWithWorkingDays = ScheduleBusinessRules::getProviderIdsWithWorkingDays();
  22. $clientPrimaryAddress = Address::where('source', 'client')
  23. ->where('source_id', $cliente->id)
  24. ->orderByDesc('is_primary')
  25. ->orderByDesc('id')
  26. ->first();
  27. $clientDistanceAddress = $this->addressForDistance($cliente->id, $clientPrimaryAddress);
  28. $clientCoordinates = $this->zipCodeCoordinatesService->resolve(
  29. $clientDistanceAddress?->latitude !== null ? (float) $clientDistanceAddress->latitude : null,
  30. $clientDistanceAddress?->longitude !== null ? (float) $clientDistanceAddress->longitude : null,
  31. $clientDistanceAddress?->zip_code,
  32. );
  33. $distanceSelect = $this->distanceSelect(
  34. data_get($clientCoordinates, 'latitude'),
  35. data_get($clientCoordinates, 'longitude'),
  36. );
  37. $baseQuery = Provider::leftJoin(
  38. 'users as provider_user',
  39. 'provider_user.id',
  40. '=',
  41. 'providers.user_id'
  42. )
  43. ->visibleToCustomers()
  44. ->leftJoin(
  45. DB::raw("
  46. (
  47. SELECT DISTINCT ON (source_id)
  48. *
  49. FROM addresses
  50. WHERE source = 'provider'
  51. AND deleted_at IS NULL
  52. ORDER BY
  53. source_id,
  54. (latitude IS NOT NULL AND longitude IS NOT NULL) DESC,
  55. is_primary DESC,
  56. id DESC
  57. ) AS provider_address
  58. "),
  59. 'provider_address.source_id',
  60. '=',
  61. 'providers.id'
  62. )
  63. ->whereNotNull('provider_address.id')
  64. ->whereNotIn('providers.id', $blockedProviderIds)
  65. ->whereIn('providers.id', $providersWithWorkingDays)
  66. ->whereNull('providers.deleted_at')
  67. ->whereNotNull('providers.daily_price_8h')
  68. ->whereNotNull('providers.daily_price_6h')
  69. ->whereNotNull('providers.daily_price_4h')
  70. ->whereNotNull('providers.daily_price_2h')
  71. ->when($name, fn ($q) => $q->where('provider_user.name', 'ILIKE', "%{$name}%"))
  72. ->select(
  73. 'providers.id',
  74. 'providers.id as provider_id',
  75. 'providers.profile_media_id',
  76. 'provider_user.name as provider_name',
  77. 'providers.gender',
  78. 'provider_address.zip_code as provider_zip_code',
  79. 'provider_address.district',
  80. 'provider_address.latitude as provider_latitude',
  81. 'provider_address.longitude as provider_longitude',
  82. 'providers.average_rating',
  83. 'providers.total_services',
  84. 'providers.daily_price_8h',
  85. 'providers.daily_price_6h',
  86. 'providers.daily_price_4h',
  87. 'providers.daily_price_2h',
  88. 'providers.created_at',
  89. DB::raw("
  90. (
  91. SELECT COUNT(*)
  92. FROM reviews
  93. LEFT JOIN schedules
  94. ON schedules.id = reviews.schedule_id
  95. WHERE reviews.origin = 'provider'
  96. AND schedules.provider_id = providers.id
  97. ) AS total_reviews
  98. "),
  99. $distanceSelect,
  100. )
  101. ->orderByRaw('distance_km ASC NULLS LAST');
  102. $providers = (clone $baseQuery)
  103. ->when(
  104. $clientPrimaryAddress?->city_id,
  105. fn ($query, int $cityId) => $query->where('provider_address.city_id', $cityId)
  106. )
  107. ->get();
  108. if ($providers->isEmpty() && $clientPrimaryAddress?->city_id) {
  109. $providers = $baseQuery->get();
  110. }
  111. $this->zipCodeCoordinatesService->preload(
  112. $providers->whereNull('distance_km')->pluck('provider_zip_code')
  113. );
  114. $providers->each(function ($provider) use ($clientDistanceAddress) {
  115. if ($provider->distance_km !== null) {
  116. return;
  117. }
  118. $provider->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  119. $clientDistanceAddress?->latitude !== null ? (float) $clientDistanceAddress->latitude : null,
  120. $clientDistanceAddress?->longitude !== null ? (float) $clientDistanceAddress->longitude : null,
  121. $clientDistanceAddress?->zip_code,
  122. $provider->provider_latitude !== null ? (float) $provider->provider_latitude : null,
  123. $provider->provider_longitude !== null ? (float) $provider->provider_longitude : null,
  124. $provider->provider_zip_code,
  125. );
  126. });
  127. $providers = $providers
  128. ->sortBy(fn ($provider) => $provider->distance_km ?? PHP_FLOAT_MAX)
  129. ->values();
  130. $filtered = $providers->when(
  131. $date,
  132. fn ($collection) => $collection->whereIn(
  133. 'provider_id',
  134. ScheduleBusinessRules::getAvailableProviderIdsForDate(
  135. $date,
  136. $collection->pluck('provider_id')
  137. )->toArray()
  138. )->values()
  139. );
  140. $filtered->load('profileMedia');
  141. return $filtered->map(function ($item) {
  142. $arr = is_array($item) ? $item : $item->toArray();
  143. $arr['profile_media_url'] = $item->profileMedia?->path
  144. ? Storage::temporaryUrl($item->profileMedia->path, now()->addMinutes(60))
  145. : null;
  146. $arr['gender_label'] = GenderEnum::labelFor(data_get($arr, 'gender'));
  147. $arr['daily_price_8h_base'] = data_get($arr, 'daily_price_8h');
  148. $arr['daily_price_6h_base'] = data_get($arr, 'daily_price_6h');
  149. $arr['daily_price_4h_base'] = data_get($arr, 'daily_price_4h');
  150. $arr['daily_price_2h_base'] = data_get($arr, 'daily_price_2h');
  151. $arr['daily_price_8h'] = $this->applyCreditCardFee(data_get($arr, 'daily_price_8h'));
  152. $arr['daily_price_6h'] = $this->applyCreditCardFee(data_get($arr, 'daily_price_6h'));
  153. $arr['daily_price_4h'] = $this->applyCreditCardFee(data_get($arr, 'daily_price_4h'));
  154. $arr['daily_price_2h'] = $this->applyCreditCardFee(data_get($arr, 'daily_price_2h'));
  155. unset(
  156. $arr['id'],
  157. $arr['profile_media_id'],
  158. $arr['profile_media'],
  159. $arr['provider_zip_code'],
  160. );
  161. return $arr;
  162. })->values()->toArray();
  163. }
  164. //
  165. private function applyCreditCardFee(?float $price): ?float
  166. {
  167. if ($price === null) {
  168. return null;
  169. }
  170. $rate = $this->platformCreditCardFeeRate();
  171. return round($price * (1 + $rate), 2);
  172. }
  173. private function platformCreditCardFeeRate(): float
  174. {
  175. $rate = config('services.pagarme.platform_credit_card_fee_rate', 0.16);
  176. if (is_string($rate)) {
  177. $rate = str_replace(',', '.', trim($rate));
  178. }
  179. $rate = (float) $rate;
  180. return $rate > 1 ? $rate / 100 : $rate;
  181. }
  182. private function addressForDistance(int $clientId, ?Address $primaryAddress): ?Address
  183. {
  184. if ($primaryAddress?->latitude !== null && $primaryAddress?->longitude !== null) {
  185. return $primaryAddress;
  186. }
  187. return Address::where('source', 'client')
  188. ->where('source_id', $clientId)
  189. ->whereNotNull('latitude')
  190. ->whereNotNull('longitude')
  191. ->orderByDesc('is_primary')
  192. ->orderByDesc('id')
  193. ->first() ?? $primaryAddress;
  194. }
  195. private function distanceSelect(?float $clientLatitude, ?float $clientLongitude): \Illuminate\Contracts\Database\Query\Expression
  196. {
  197. return DistanceService::sqlExpression($clientLatitude, $clientLongitude);
  198. }
  199. }