ProviderService.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\ApprovalStatusEnum;
  4. use App\Enums\UserTypeEnum;
  5. use App\Models\Address;
  6. use App\Models\City;
  7. use App\Models\Provider;
  8. use App\Models\ProviderServicesType;
  9. use App\Models\ProviderWorkingDay;
  10. use App\Models\State;
  11. use App\Models\User;
  12. use App\Services\Pagarme\PagarmeRecipientService;
  13. use Illuminate\Database\Eloquent\Collection;
  14. use Illuminate\Pagination\LengthAwarePaginator;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. class ProviderService
  18. {
  19. public function __construct(
  20. private readonly AuthService $authService,
  21. private readonly PagarmeRecipientService $pagarmeRecipientService,
  22. ) {}
  23. public function getAll(): Collection
  24. {
  25. $providers = Provider::query()
  26. ->with(['user', 'profileMedia'])
  27. ->orderBy('created_at', 'desc')
  28. ->get();
  29. return $providers;
  30. }
  31. public function findById(int $id): ?Provider
  32. {
  33. return Provider::with(['user', 'profileMedia'])->find($id);
  34. }
  35. public function create(array $data): Provider
  36. {
  37. return DB::transaction(function () use ($data) {
  38. $provider = Provider::create($data);
  39. if (! empty($data['recipient_code'])) {
  40. $this->pagarmeRecipientService->createRecipientForProvider($provider, $data);
  41. }
  42. return $provider->fresh(['user', 'profileMedia']);
  43. });
  44. }
  45. public function update(int $id, array $data): ?Provider
  46. {
  47. $model = $this->findById($id);
  48. if (!$model) {
  49. return null;
  50. }
  51. $model->update($data);
  52. return $model->fresh(['user', 'profileMedia']);
  53. }
  54. public function updateBankAccount(int $id, array $bankAccountData): ?Provider
  55. {
  56. $provider = $this->findById($id);
  57. if (! $provider) {
  58. return null;
  59. }
  60. $this->pagarmeRecipientService->updateDefaultBankAccount($provider, $bankAccountData);
  61. return $provider->fresh(['user', 'profileMedia']);
  62. }
  63. public function delete(int $id): bool
  64. {
  65. $model = $this->findById($id);
  66. if (!$model) {
  67. return false;
  68. }
  69. return $model->delete();
  70. }
  71. public function getPending(int $page = 1, int $perPage = 10): LengthAwarePaginator
  72. {
  73. return Provider::query()
  74. ->where('approval_status', ApprovalStatusEnum::PENDING->value)
  75. ->with(['user', 'profileMedia'])
  76. ->orderBy('created_at', 'asc')
  77. ->paginate($perPage, ['*'], 'page', $page);
  78. }
  79. public function approve(int $id): Provider
  80. {
  81. return DB::transaction(function () use ($id) {
  82. $provider = Provider::findOrFail($id);
  83. $provider->update(['approval_status' => ApprovalStatusEnum::ACCEPTED->value]);
  84. return $provider->fresh(['user', 'profileMedia']);
  85. });
  86. }
  87. public function reject(int $id): Provider
  88. {
  89. return DB::transaction(function () use ($id) {
  90. $provider = Provider::findOrFail($id);
  91. $provider->update(['approval_status' => ApprovalStatusEnum::REJECTED->value]);
  92. return $provider->fresh(['user', 'profileMedia']);
  93. });
  94. }
  95. public function register(array $data): ?array
  96. {
  97. try {
  98. DB::beginTransaction();
  99. $email = $data['email'] ?? null;
  100. $phone = $data['phone'] ?? null;
  101. $code = $data['code'] ?? null;
  102. $user = User::query()
  103. ->where('type', UserTypeEnum::PROVIDER->value)
  104. ->where('code', $code)
  105. ->where(function ($query) use ($email, $phone) {
  106. if (!empty($email)) {
  107. $query->orWhere('email', $email);
  108. }
  109. if (!empty($phone)) {
  110. $query->orWhere('phone', $phone);
  111. }
  112. })
  113. ->latest('id')
  114. ->first();
  115. if (!$user) {
  116. throw new \Exception(__('messages.user_not_found_or_code_not_validated'));
  117. }
  118. $user->name = $data['name'];
  119. if (empty($user->email) && !empty($email)) {
  120. $user->email = $email;
  121. }
  122. if (empty($user->phone) && !empty($phone)) {
  123. $user->phone = $phone;
  124. }
  125. $user->save();
  126. $provider = new Provider();
  127. $provider->user_id = $user->id;
  128. $provider->rg = $data['rg'] ?? null;
  129. $provider->document = $this->sanitizeDigits($data['document'] ?? null);
  130. $provider->birth_date = $data['birth_date'] ?? null;
  131. $provider->daily_price_8h = $data['daily_price_8h'] ?? null;
  132. $provider->daily_price_6h = $data['daily_price_6h'] ?? null;
  133. $provider->daily_price_4h = $data['daily_price_4h'] ?? null;
  134. $provider->daily_price_2h = $data['daily_price_2h'] ?? null;
  135. $provider->approval_status = ApprovalStatusEnum::PENDING->value;
  136. $provider->selfie_media_base64 = $data['selfie_base64'] ?? null;
  137. $provider->document_front_media_base64 = $data['document_front_base64'] ?? null;
  138. $provider->document_back_media_base64 = $data['document_back_base64'] ?? null;
  139. $provider->save();
  140. $provider->refresh();
  141. $this->pagarmeRecipientService->createRecipientForProvider($provider, $data);
  142. $this->createProviderAddress($provider->id, $data);
  143. $this->createProviderServicesTypes($provider->id, $data);
  144. $this->createProviderWorkingDays($provider->id, $data);
  145. if (empty($user->email) || empty($user->code)) {
  146. throw new \Exception(__('messages.user_not_found_or_code_not_validated'));
  147. }
  148. $result = $this->authService->loginWithEmail(
  149. email: $user->email,
  150. code: $user->code,
  151. );
  152. DB::commit();
  153. return $result;
  154. } catch (\Exception $e) {
  155. DB::rollBack();
  156. Log::error('Error registering provider: ' . $e->getMessage(), [
  157. 'data' => $data,
  158. ]);
  159. throw $e;
  160. }
  161. }
  162. private function createProviderAddress(int $providerId, array $data): void
  163. {
  164. $state = null;
  165. $city = null;
  166. if (!empty($data['state'])) {
  167. $state = State::query()
  168. ->whereRaw('LOWER(code) = ?', [mb_strtolower($data['state'])])
  169. ->first();
  170. }
  171. if (!empty($data['city'])) {
  172. $cityQuery = City::query()
  173. ->whereRaw('LOWER(name) = ?', [mb_strtolower($data['city'])]);
  174. if ($state) {
  175. $cityQuery->where('state_id', $state->id);
  176. }
  177. $city = $cityQuery->first();
  178. }
  179. $address = new Address();
  180. $address->source = 'provider';
  181. $address->source_id = $providerId;
  182. $address->zip_code = $this->sanitizeDigits($data['zip_code'] ?? null);
  183. $address->address = $data['address'] ?? null;
  184. $address->has_complement = (bool) ($data['has_complement'] ?? false);
  185. $address->complement = $data['complement'] ?? null;
  186. $address->nickname = $data['nickname'] ?? null;
  187. $address->instructions = $data['instructions'] ?? null;
  188. $address->address_type = $data['address_type'] ?? 'home';
  189. $address->state_id = $state?->id;
  190. $address->city_id = $city?->id;
  191. $address->save();
  192. }
  193. private function createProviderServicesTypes(int $providerId, array $data): void
  194. {
  195. $serviceTypeIds = $data['services_types_ids'] ?? $data['service_types_ids'] ?? [];
  196. $uniqueIds = array_values(array_unique(array_map('intval', $serviceTypeIds)));
  197. foreach ($uniqueIds as $serviceTypeId) {
  198. ProviderServicesType::create([
  199. 'provider_id' => $providerId,
  200. 'service_type_id' => $serviceTypeId,
  201. ]);
  202. }
  203. }
  204. private function createProviderWorkingDays(int $providerId, array $data): void
  205. {
  206. $workingDays = $data['working_days'] ?? [];
  207. $seen = [];
  208. foreach ($workingDays as $workingDay) {
  209. $day = (int) ($workingDay['day'] ?? -1);
  210. $period = $workingDay['period'] ?? null;
  211. if ($day < 0 || $day > 6 || !in_array($period, ['morning', 'afternoon'], true)) {
  212. continue;
  213. }
  214. $uniqueKey = $day . '-' . $period;
  215. if (isset($seen[$uniqueKey])) {
  216. continue;
  217. }
  218. $seen[$uniqueKey] = true;
  219. ProviderWorkingDay::create([
  220. 'provider_id' => $providerId,
  221. 'day' => $day,
  222. 'period' => $period,
  223. ]);
  224. }
  225. }
  226. private function sanitizeDigits(?string $value): ?string
  227. {
  228. if ($value === null) {
  229. return null;
  230. }
  231. $digits = preg_replace('/\D+/', '', $value);
  232. return $digits === '' ? null : $digits;
  233. }
  234. }