SearchService.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Address;
  4. use App\Models\Client;
  5. use App\Models\Media;
  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. public function buscaPrestadores(?string $name = null, ?string $date = null): array
  15. {
  16. $user = Auth::user();
  17. $cliente = Client::where('user_id', $user->id)->first();
  18. $blockedProviderIds = ScheduleBusinessRules::getBlockedProviderIdsForClient($cliente->id);
  19. $providersWithWorkingDays = ScheduleBusinessRules::getProviderIdsWithWorkingDays();
  20. $clientPrimaryAddress = Address::where('source', 'client')
  21. ->where('source_id', $cliente->id)
  22. ->orderBy('is_primary', 'desc')
  23. ->first();
  24. $clientDistanceAddress = $this->addressForDistance($cliente->id, $clientPrimaryAddress);
  25. $distanceSelect = $this->distanceSelect(
  26. $clientDistanceAddress?->latitude !== null ? (float) $clientDistanceAddress->latitude : null,
  27. $clientDistanceAddress?->longitude !== null ? (float) $clientDistanceAddress->longitude : null,
  28. );
  29. $baseQuery = Provider::leftJoin(
  30. 'users as provider_user',
  31. 'provider_user.id',
  32. '=',
  33. 'providers.user_id'
  34. )
  35. ->visibleToCustomers()
  36. ->leftJoin(
  37. DB::raw("
  38. (
  39. SELECT DISTINCT ON (source_id)
  40. *
  41. FROM addresses
  42. WHERE source = 'provider'
  43. AND deleted_at IS NULL
  44. ORDER BY source_id, is_primary DESC
  45. ) AS provider_address
  46. "),
  47. 'provider_address.source_id',
  48. '=',
  49. 'providers.id'
  50. )
  51. ->whereNotNull('provider_address.id')
  52. ->whereNotIn('providers.id', $blockedProviderIds)
  53. ->whereIn('providers.id', $providersWithWorkingDays)
  54. ->whereNull('providers.deleted_at')
  55. ->whereNotNull('providers.daily_price_8h')
  56. ->whereNotNull('providers.daily_price_6h')
  57. ->whereNotNull('providers.daily_price_4h')
  58. ->whereNotNull('providers.daily_price_2h')
  59. ->when($name, fn ($q) => $q->where('provider_user.name', 'ILIKE', "%{$name}%"))
  60. ->select(
  61. 'providers.id as provider_id',
  62. 'providers.profile_media_id',
  63. 'provider_user.name as provider_name',
  64. 'provider_address.district',
  65. 'provider_address.latitude as provider_latitude',
  66. 'provider_address.longitude as provider_longitude',
  67. 'providers.average_rating',
  68. 'providers.total_services',
  69. 'providers.daily_price_8h',
  70. 'providers.daily_price_6h',
  71. 'providers.daily_price_4h',
  72. 'providers.daily_price_2h',
  73. 'providers.created_at',
  74. DB::raw("
  75. (
  76. SELECT COUNT(*)
  77. FROM reviews
  78. LEFT JOIN schedules
  79. ON schedules.id = reviews.schedule_id
  80. WHERE reviews.origin = 'provider'
  81. AND schedules.provider_id = providers.id
  82. ) AS total_reviews
  83. "),
  84. $distanceSelect,
  85. )
  86. ->orderByRaw('distance_km ASC NULLS LAST');
  87. $providers = (clone $baseQuery)
  88. ->when(
  89. $clientPrimaryAddress?->city_id,
  90. fn ($query, int $cityId) => $query->where('provider_address.city_id', $cityId)
  91. )
  92. ->get();
  93. if ($providers->isEmpty() && $clientPrimaryAddress?->city_id) {
  94. $providers = $baseQuery->get();
  95. }
  96. $filtered = $providers->when(
  97. $date,
  98. fn ($collection) => $collection->whereIn(
  99. 'provider_id',
  100. ScheduleBusinessRules::getAvailableProviderIdsForDate(
  101. $date,
  102. $collection->pluck('provider_id')
  103. )->toArray()
  104. )->values()
  105. );
  106. $mediaIds = $filtered->pluck('profile_media_id')->filter()->unique()->values();
  107. $mediaUrls = [];
  108. if ($mediaIds->isNotEmpty()) {
  109. Media::whereIn('id', $mediaIds)->get()->each(function ($media) use (&$mediaUrls) {
  110. $mediaUrls[$media->id] = $media->path
  111. ? Storage::temporaryUrl($media->path, now()->addMinutes(60))
  112. : null;
  113. });
  114. }
  115. return $filtered->map(function ($item) use ($mediaUrls) {
  116. $arr = is_array($item) ? $item : $item->toArray();
  117. $arr['profile_media_url'] = $mediaUrls[$arr['profile_media_id'] ?? null] ?? null;
  118. $arr['daily_price_8h'] = $this->applyCreditCardFee($arr['daily_price_8h'] ?? null);
  119. $arr['daily_price_6h'] = $this->applyCreditCardFee($arr['daily_price_6h'] ?? null);
  120. $arr['daily_price_4h'] = $this->applyCreditCardFee($arr['daily_price_4h'] ?? null);
  121. $arr['daily_price_2h'] = $this->applyCreditCardFee($arr['daily_price_2h'] ?? null);
  122. unset($arr['profile_media_id']);
  123. return $arr;
  124. })->values()->toArray();
  125. }
  126. //
  127. private function applyCreditCardFee(?float $price): ?float
  128. {
  129. if ($price === null) {
  130. return null;
  131. }
  132. $rate = $this->platformCreditCardFeeRate();
  133. return round($price * (1 + $rate), 2);
  134. }
  135. private function platformCreditCardFeeRate(): float
  136. {
  137. $rate = config('services.pagarme.platform_credit_card_fee_rate', 0.16);
  138. if (is_string($rate)) {
  139. $rate = str_replace(',', '.', trim($rate));
  140. }
  141. $rate = (float) $rate;
  142. return $rate > 1 ? $rate / 100 : $rate;
  143. }
  144. private function addressForDistance(int $clientId, ?Address $primaryAddress): ?Address
  145. {
  146. if ($primaryAddress?->latitude !== null && $primaryAddress?->longitude !== null) {
  147. return $primaryAddress;
  148. }
  149. return Address::where('source', 'client')
  150. ->where('source_id', $clientId)
  151. ->whereNotNull('latitude')
  152. ->whereNotNull('longitude')
  153. ->orderByDesc('is_primary')
  154. ->orderByDesc('id')
  155. ->first() ?? $primaryAddress;
  156. }
  157. private function distanceSelect(?float $clientLatitude, ?float $clientLongitude): \Illuminate\Contracts\Database\Query\Expression
  158. {
  159. return DistanceService::sqlExpression($clientLatitude, $clientLongitude);
  160. }
  161. }