SearchService.php 7.3 KB

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