ProviderService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 Illuminate\Database\Eloquent\Collection;
  13. use Illuminate\Http\UploadedFile;
  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 ProviderBankAccountService $providerBankAccountService,
  22. private readonly MediaService $mediaService,
  23. private readonly EmailService $emailService,
  24. ) {}
  25. public function getAll(): Collection
  26. {
  27. $providers = Provider::query()
  28. ->with(['user', 'profileMedia'])
  29. ->join('users', 'providers.user_id', '=', 'users.id')
  30. ->select('providers.*')
  31. ->orderBy('users.name', 'asc')
  32. ->get();
  33. return $providers;
  34. }
  35. public function findById(int $id): ?Provider
  36. {
  37. return Provider::with(['user', 'profileMedia', 'documentFrontMedia', 'documentBackMedia'])->find($id);
  38. }
  39. public function create(array $data): Provider
  40. {
  41. return DB::transaction(function () use ($data) {
  42. $provider = Provider::create($data);
  43. if (! empty(data_get($data, 'recipient_name'))) {
  44. $this->providerBankAccountService->createPrimaryFromRecipientPayload($provider, $data);
  45. }
  46. return $provider->fresh(['user', 'profileMedia']);
  47. });
  48. }
  49. public function update(int $id, array $data): ?Provider
  50. {
  51. $model = $this->findById($id);
  52. if (! $model) {
  53. return null;
  54. }
  55. $wasAccepted = $model->approval_status === ApprovalStatusEnum::ACCEPTED;
  56. if (data_get($data, 'avatar') !== null && data_get($data, 'avatar') instanceof UploadedFile) {
  57. $media = $this->mediaService->replaceFile(
  58. newFile: data_get($data, 'avatar'),
  59. folder: "provider/avatar/{$model->id}",
  60. source: 'provider',
  61. sourceId: $model->id,
  62. old: $model->profileMedia,
  63. );
  64. $data['profile_media_id'] = $media->id;
  65. unset($data['avatar']);
  66. }
  67. $model->update($data);
  68. $provider = $model->fresh(['user', 'profileMedia']);
  69. if (! $wasAccepted && $provider->approval_status === ApprovalStatusEnum::ACCEPTED) {
  70. $this->sendApprovedEmail($provider);
  71. }
  72. return $provider;
  73. }
  74. public function delete(int $id): bool
  75. {
  76. $model = $this->findById($id);
  77. if (! $model) {
  78. return false;
  79. }
  80. return $model->delete();
  81. }
  82. //
  83. public function getPending(int $page = 1, int $perPage = 10): LengthAwarePaginator
  84. {
  85. return Provider::query()
  86. ->where('approval_status', ApprovalStatusEnum::PENDING->value)
  87. ->with(['user', 'profileMedia'])
  88. ->orderBy('created_at', 'asc')
  89. ->paginate($perPage, ['*'], 'page', $page);
  90. }
  91. //
  92. public function register(array $data): array
  93. {
  94. try {
  95. DB::beginTransaction();
  96. $email = data_get($data, 'email');
  97. $phone = data_get($data, 'phone');
  98. $code = data_get($data, 'code');
  99. $user = User::query()
  100. ->where('type', UserTypeEnum::PROVIDER->value)
  101. ->where('code', $code)
  102. ->where(function ($query) use ($email, $phone) {
  103. if (! empty($email)) {
  104. $query->orWhere('email', $email);
  105. }
  106. if (! empty($phone)) {
  107. $query->orWhere('phone', $phone);
  108. }
  109. })
  110. ->latest('id')
  111. ->first();
  112. if (! $user) {
  113. throw new \Exception(__('messages.user_not_found_or_code_not_validated'));
  114. }
  115. $user->name = data_get($data, 'name');
  116. if (empty($user->email) && ! empty($email)) {
  117. $user->email = $email;
  118. }
  119. if (empty($user->phone) && ! empty($phone)) {
  120. $user->phone = $phone;
  121. }
  122. $user->save();
  123. $provider = Provider::withTrashed()->where('user_id', $user->id)->first();
  124. if (! $provider) {
  125. $provider = new Provider;
  126. $provider->user_id = $user->id;
  127. } elseif ($provider->trashed()) {
  128. $provider->restore();
  129. }
  130. $provider->rg = data_get($data, 'rg');
  131. $provider->document = $this->sanitizeDigits(data_get($data, 'document'));
  132. $provider->birth_date = data_get($data, 'birth_date');
  133. $provider->gender = data_get($data, 'gender');
  134. $provider->daily_price_8h = data_get($data, 'daily_price_8h');
  135. $provider->daily_price_6h = data_get($data, 'daily_price_6h');
  136. $provider->daily_price_4h = data_get($data, 'daily_price_4h');
  137. $provider->daily_price_2h = data_get($data, 'daily_price_2h');
  138. $provider->approval_status = ApprovalStatusEnum::PENDING->value;
  139. $provider->save();
  140. $provider->refresh();
  141. $provider->load('profileMedia', 'documentFrontMedia', 'documentBackMedia');
  142. $selfie = $this->mediaService->replaceFile(
  143. newFile: data_get($data, 'selfie'),
  144. folder: "provider/avatar/{$provider->id}",
  145. source: 'provider',
  146. sourceId: $provider->id,
  147. old: $provider->profileMedia,
  148. );
  149. $provider->profile_media_id = $selfie->id;
  150. $front = $this->mediaService->replaceFile(
  151. newFile: data_get($data, 'document_front'),
  152. folder: "provider/documentos/{$provider->id}",
  153. source: 'provider_document',
  154. sourceId: $provider->id,
  155. old: $provider->documentFrontMedia,
  156. filename: 'frente.'.data_get($data, 'document_front')->getClientOriginalExtension(),
  157. );
  158. $provider->document_front_media_id = $front->id;
  159. $back = $this->mediaService->replaceFile(
  160. newFile: data_get($data, 'document_back'),
  161. folder: "provider/documentos/{$provider->id}",
  162. source: 'provider_document',
  163. sourceId: $provider->id,
  164. old: $provider->documentBackMedia,
  165. filename: 'verso.'.data_get($data, 'document_back')->getClientOriginalExtension(),
  166. );
  167. $provider->document_back_media_id = $back->id;
  168. $provider->save();
  169. Address::where('source', 'provider')->where('source_id', $provider->id)->delete();
  170. $this->createProviderAddress($provider->id, $data);
  171. if (! empty(data_get($data, 'recipient_name'))) {
  172. $this->providerBankAccountService->createPrimaryFromRecipientPayload($provider, $data);
  173. }
  174. ProviderServicesType::where('provider_id', $provider->id)->delete();
  175. $this->createProviderServicesTypes($provider->id, $data);
  176. ProviderWorkingDay::where('provider_id', $provider->id)->delete();
  177. $this->createProviderWorkingDays($provider->id, $data);
  178. if ((empty($user->email) && empty($user->phone)) || empty($user->code)) {
  179. throw new \Exception(__('messages.user_not_found_or_code_not_validated'));
  180. }
  181. $user->registration_complete = true;
  182. $user->validated_code = true;
  183. $user->code = null;
  184. $user->save();
  185. $result = $this->authService->createAppSession($user);
  186. DB::commit();
  187. return $result;
  188. } catch (\Exception $e) {
  189. DB::rollBack();
  190. Log::error('Erro ao cadastrar prestador: '.$e->getMessage(), [
  191. 'data' => $data,
  192. ]);
  193. throw $e;
  194. }
  195. }
  196. //
  197. public function approve(int $id): Provider
  198. {
  199. [$provider, $wasAccepted] = DB::transaction(function () use ($id) {
  200. $provider = Provider::query()->lockForUpdate()->findOrFail($id);
  201. $wasAccepted = $provider->approval_status === ApprovalStatusEnum::ACCEPTED;
  202. $provider->update([
  203. 'approval_status' => ApprovalStatusEnum::ACCEPTED->value,
  204. 'selfie_verified' => true,
  205. ]);
  206. return [$provider->fresh(['user', 'profileMedia']), $wasAccepted];
  207. });
  208. if (! $wasAccepted) {
  209. $this->sendApprovedEmail($provider);
  210. }
  211. return $provider;
  212. }
  213. public function reject(int $id): Provider
  214. {
  215. return DB::transaction(function () use ($id) {
  216. $provider = Provider::findOrFail($id);
  217. $provider->update(['approval_status' => ApprovalStatusEnum::REJECTED->value]);
  218. return $provider->fresh(['user', 'profileMedia']);
  219. });
  220. }
  221. //
  222. private function createProviderAddress(int $providerId, array $data): void
  223. {
  224. $state = null;
  225. $city = null;
  226. if (! empty(data_get($data, 'state'))) {
  227. $state = State::query()
  228. ->whereRaw('LOWER(code) = ?', [mb_strtolower(data_get($data, 'state'))])
  229. ->first();
  230. }
  231. if (! empty(data_get($data, 'city'))) {
  232. $cityQuery = City::query()
  233. ->whereRaw('LOWER(name) = ?', [mb_strtolower(data_get($data, 'city'))]);
  234. if ($state) {
  235. $cityQuery->where('state_id', $state->id);
  236. }
  237. $city = $cityQuery->first();
  238. }
  239. $address = new Address;
  240. $address->source = 'provider';
  241. $address->source_id = $providerId;
  242. $address->zip_code = $this->sanitizeDigits(data_get($data, 'zip_code'));
  243. $address->address = data_get($data, 'address');
  244. $address->number = data_get($data, 'number');
  245. $address->district = data_get($data, 'district');
  246. $address->has_complement = (bool) data_get($data, 'has_complement', false);
  247. $address->complement = data_get($data, 'complement');
  248. $address->nickname = data_get($data, 'nickname');
  249. $address->instructions = data_get($data, 'instructions');
  250. $address->address_type = data_get($data, 'address_type', 'home');
  251. $address->state_id = $state?->id;
  252. $address->city_id = $city?->id;
  253. $address->latitude = data_get($data, 'latitude');
  254. $address->longitude = data_get($data, 'longitude');
  255. $address->save();
  256. }
  257. private function createProviderServicesTypes(int $providerId, array $data): void
  258. {
  259. $serviceTypeIds = data_get($data, 'services_types_ids', data_get($data, 'service_types_ids', []));
  260. $uniqueIds = array_values(array_unique(array_map('intval', $serviceTypeIds)));
  261. foreach ($uniqueIds as $serviceTypeId) {
  262. ProviderServicesType::create([
  263. 'provider_id' => $providerId,
  264. 'service_type_id' => $serviceTypeId,
  265. ]);
  266. }
  267. }
  268. private function createProviderWorkingDays(int $providerId, array $data): void
  269. {
  270. $workingDays = data_get($data, 'working_days', []);
  271. $seen = [];
  272. foreach ($workingDays as $workingDay) {
  273. $day = (int) data_get($workingDay, 'day', -1);
  274. $period = data_get($workingDay, 'period');
  275. if ($day < 0 || $day > 6 || ! in_array($period, ['morning', 'afternoon'], true)) {
  276. continue;
  277. }
  278. $uniqueKey = $day.'-'.$period;
  279. if (data_get($seen, $uniqueKey) !== null) {
  280. continue;
  281. }
  282. $seen[$uniqueKey] = true;
  283. ProviderWorkingDay::create([
  284. 'provider_id' => $providerId,
  285. 'day' => $day,
  286. 'period' => $period,
  287. ]);
  288. }
  289. }
  290. //
  291. private function sanitizeDigits(?string $value): ?string
  292. {
  293. if ($value === null) {
  294. return null;
  295. }
  296. $digits = preg_replace('/\D+/', '', $value);
  297. return $digits === '' ? null : $digits;
  298. }
  299. private function sendApprovedEmail(Provider $provider): void
  300. {
  301. if (! empty($provider->user?->email)) {
  302. try {
  303. $this->emailService->sendProviderApproved(
  304. email: $provider->user->email,
  305. recipientName: $provider->user->name ?? '',
  306. locale: $provider->user->language?->value,
  307. );
  308. } catch (\Throwable $exception) {
  309. Log::error('Falha ao enviar e-mail de aprovação do prestador', [
  310. 'provider_id' => $provider->id,
  311. 'user_id' => $provider->user?->id,
  312. 'email' => $provider->user?->email,
  313. 'error' => $exception->getMessage(),
  314. ]);
  315. }
  316. return;
  317. }
  318. Log::warning('E-mail de aprovação do prestador ignorado: usuário não possui e-mail', [
  319. 'provider_id' => $provider->id,
  320. 'user_id' => $provider->user?->id,
  321. ]);
  322. }
  323. }