ProviderService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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\DeviceToken;
  8. use App\Models\Provider;
  9. use App\Models\ProviderServicesType;
  10. use App\Models\ProviderWorkingDay;
  11. use App\Models\PushNotificationLog;
  12. use App\Models\State;
  13. use App\Models\User;
  14. use App\Notifications\Push\Prestador\Transacional\CadastroAprovadoPush;
  15. use Illuminate\Database\Eloquent\Collection;
  16. use Illuminate\Http\UploadedFile;
  17. use Illuminate\Pagination\LengthAwarePaginator;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Log;
  20. class ProviderService
  21. {
  22. public function __construct(
  23. private readonly AuthService $authService,
  24. private readonly ProviderBankAccountService $providerBankAccountService,
  25. private readonly MediaService $mediaService,
  26. private readonly EmailService $emailService,
  27. ) {}
  28. public function getAll(): Collection
  29. {
  30. $providers = Provider::query()
  31. ->with(['user', 'profileMedia'])
  32. ->join('users', 'providers.user_id', '=', 'users.id')
  33. ->select('providers.*')
  34. ->orderBy('users.name', 'asc')
  35. ->get();
  36. return $providers;
  37. }
  38. public function findById(int $id): ?Provider
  39. {
  40. return Provider::with(['user', 'profileMedia', 'documentFrontMedia', 'documentBackMedia'])->find($id);
  41. }
  42. public function create(array $data): Provider
  43. {
  44. return DB::transaction(function () use ($data) {
  45. $provider = Provider::create($data);
  46. if (! empty(data_get($data, 'recipient_name'))) {
  47. $this->providerBankAccountService->createPrimaryFromRecipientPayload($provider, $data);
  48. }
  49. return $provider->fresh(['user', 'profileMedia']);
  50. });
  51. }
  52. public function update(int $id, array $data): ?Provider
  53. {
  54. $model = $this->findById($id);
  55. if (! $model) {
  56. return null;
  57. }
  58. $wasAccepted = $model->approval_status === ApprovalStatusEnum::ACCEPTED;
  59. if (data_get($data, 'avatar') !== null && data_get($data, 'avatar') instanceof UploadedFile) {
  60. $media = $this->mediaService->replaceFile(
  61. newFile: data_get($data, 'avatar'),
  62. folder: "provider/avatar/{$model->id}",
  63. source: 'provider',
  64. sourceId: $model->id,
  65. old: $model->profileMedia,
  66. );
  67. $data['profile_media_id'] = $media->id;
  68. unset($data['avatar']);
  69. }
  70. $model->update($data);
  71. $provider = $model->fresh(['user', 'profileMedia']);
  72. if (! $wasAccepted && $provider->approval_status === ApprovalStatusEnum::ACCEPTED) {
  73. $this->notifyApproved($provider);
  74. }
  75. return $provider;
  76. }
  77. public function delete(int $id): bool
  78. {
  79. $model = $this->findById($id);
  80. if (! $model) {
  81. return false;
  82. }
  83. return $model->delete();
  84. }
  85. //
  86. public function getPending(int $page = 1, int $perPage = 10): LengthAwarePaginator
  87. {
  88. return Provider::query()
  89. ->where('approval_status', ApprovalStatusEnum::PENDING->value)
  90. ->with(['user', 'profileMedia'])
  91. ->orderBy('created_at', 'asc')
  92. ->paginate($perPage, ['*'], 'page', $page);
  93. }
  94. //
  95. public function register(array $data): array
  96. {
  97. try {
  98. DB::beginTransaction();
  99. $email = data_get($data, 'email');
  100. $phone = data_get($data, 'phone');
  101. $code = data_get($data, 'code');
  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_get($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 = Provider::withTrashed()->where('user_id', $user->id)->first();
  127. if (! $provider) {
  128. $provider = new Provider;
  129. $provider->user_id = $user->id;
  130. } elseif ($provider->trashed()) {
  131. $provider->restore();
  132. }
  133. $provider->rg = data_get($data, 'rg');
  134. $provider->document = $this->sanitizeDigits(data_get($data, 'document'));
  135. $provider->birth_date = data_get($data, 'birth_date');
  136. $provider->gender = data_get($data, 'gender');
  137. $provider->daily_price_8h = data_get($data, 'daily_price_8h');
  138. $provider->daily_price_6h = data_get($data, 'daily_price_6h');
  139. $provider->daily_price_4h = data_get($data, 'daily_price_4h');
  140. $provider->daily_price_2h = data_get($data, 'daily_price_2h');
  141. $provider->approval_status = ApprovalStatusEnum::PENDING->value;
  142. $provider->save();
  143. $provider->refresh();
  144. $provider->load('profileMedia', 'documentFrontMedia', 'documentBackMedia');
  145. $selfie = $this->mediaService->replaceFile(
  146. newFile: data_get($data, 'selfie'),
  147. folder: "provider/avatar/{$provider->id}",
  148. source: 'provider',
  149. sourceId: $provider->id,
  150. old: $provider->profileMedia,
  151. );
  152. $provider->profile_media_id = $selfie->id;
  153. $front = $this->mediaService->replaceFile(
  154. newFile: data_get($data, 'document_front'),
  155. folder: "provider/documentos/{$provider->id}",
  156. source: 'provider_document',
  157. sourceId: $provider->id,
  158. old: $provider->documentFrontMedia,
  159. filename: 'frente.'.data_get($data, 'document_front')->getClientOriginalExtension(),
  160. );
  161. $provider->document_front_media_id = $front->id;
  162. $back = $this->mediaService->replaceFile(
  163. newFile: data_get($data, 'document_back'),
  164. folder: "provider/documentos/{$provider->id}",
  165. source: 'provider_document',
  166. sourceId: $provider->id,
  167. old: $provider->documentBackMedia,
  168. filename: 'verso.'.data_get($data, 'document_back')->getClientOriginalExtension(),
  169. );
  170. $provider->document_back_media_id = $back->id;
  171. $provider->save();
  172. Address::where('source', 'provider')->where('source_id', $provider->id)->delete();
  173. $this->createProviderAddress($provider->id, $data);
  174. if (! empty(data_get($data, 'recipient_name'))) {
  175. $this->providerBankAccountService->createPrimaryFromRecipientPayload($provider, $data);
  176. }
  177. ProviderServicesType::where('provider_id', $provider->id)->delete();
  178. $this->createProviderServicesTypes($provider->id, $data);
  179. ProviderWorkingDay::where('provider_id', $provider->id)->delete();
  180. $this->createProviderWorkingDays($provider->id, $data);
  181. if ((empty($user->email) && empty($user->phone)) || empty($user->code)) {
  182. throw new \Exception(__('messages.user_not_found_or_code_not_validated'));
  183. }
  184. $user->registration_complete = true;
  185. $user->validated_code = true;
  186. $user->code = null;
  187. $user->save();
  188. $result = $this->authService->createAppSession($user);
  189. DB::commit();
  190. return $result;
  191. } catch (\Exception $e) {
  192. DB::rollBack();
  193. Log::error('Erro ao cadastrar prestador: '.$e->getMessage(), [
  194. 'data' => $data,
  195. ]);
  196. throw $e;
  197. }
  198. }
  199. //
  200. public function approve(int $id): Provider
  201. {
  202. [$provider, $wasAccepted] = DB::transaction(function () use ($id) {
  203. $provider = Provider::query()->lockForUpdate()->findOrFail($id);
  204. $wasAccepted = $provider->approval_status === ApprovalStatusEnum::ACCEPTED;
  205. $provider->update([
  206. 'approval_status' => ApprovalStatusEnum::ACCEPTED->value,
  207. 'selfie_verified' => true,
  208. ]);
  209. return [$provider->fresh(['user', 'profileMedia']), $wasAccepted];
  210. });
  211. if (! $wasAccepted) {
  212. $this->notifyApproved($provider);
  213. }
  214. return $provider;
  215. }
  216. public function reject(int $id): Provider
  217. {
  218. return DB::transaction(function () use ($id) {
  219. $provider = Provider::findOrFail($id);
  220. $provider->update(['approval_status' => ApprovalStatusEnum::REJECTED->value]);
  221. return $provider->fresh(['user', 'profileMedia']);
  222. });
  223. }
  224. //
  225. private function createProviderAddress(int $providerId, array $data): void
  226. {
  227. $state = null;
  228. $city = null;
  229. if (! empty(data_get($data, 'state'))) {
  230. $state = State::query()
  231. ->whereRaw('LOWER(code) = ?', [mb_strtolower(data_get($data, 'state'))])
  232. ->first();
  233. }
  234. if (! empty(data_get($data, 'city'))) {
  235. $cityQuery = City::query()
  236. ->whereRaw('LOWER(name) = ?', [mb_strtolower(data_get($data, 'city'))]);
  237. if ($state) {
  238. $cityQuery->where('state_id', $state->id);
  239. }
  240. $city = $cityQuery->first();
  241. }
  242. $address = new Address;
  243. $address->source = 'provider';
  244. $address->source_id = $providerId;
  245. $address->zip_code = $this->sanitizeDigits(data_get($data, 'zip_code'));
  246. $address->address = data_get($data, 'address');
  247. $address->number = data_get($data, 'number');
  248. $address->district = data_get($data, 'district');
  249. $address->has_complement = (bool) data_get($data, 'has_complement', false);
  250. $address->complement = data_get($data, 'complement');
  251. $address->nickname = data_get($data, 'nickname');
  252. $address->instructions = data_get($data, 'instructions');
  253. $address->address_type = data_get($data, 'address_type', 'home');
  254. $address->state_id = $state?->id;
  255. $address->city_id = $city?->id;
  256. $address->latitude = data_get($data, 'latitude');
  257. $address->longitude = data_get($data, 'longitude');
  258. $address->save();
  259. }
  260. private function createProviderServicesTypes(int $providerId, array $data): void
  261. {
  262. $serviceTypeIds = data_get($data, 'services_types_ids', data_get($data, 'service_types_ids', []));
  263. $uniqueIds = array_values(array_unique(array_map('intval', $serviceTypeIds)));
  264. foreach ($uniqueIds as $serviceTypeId) {
  265. ProviderServicesType::create([
  266. 'provider_id' => $providerId,
  267. 'service_type_id' => $serviceTypeId,
  268. ]);
  269. }
  270. }
  271. private function createProviderWorkingDays(int $providerId, array $data): void
  272. {
  273. $workingDays = data_get($data, 'working_days', []);
  274. $seen = [];
  275. foreach ($workingDays as $workingDay) {
  276. $day = (int) data_get($workingDay, 'day', -1);
  277. $period = data_get($workingDay, 'period');
  278. if ($day < 0 || $day > 6 || ! in_array($period, ['morning', 'afternoon'], true)) {
  279. continue;
  280. }
  281. $uniqueKey = $day.'-'.$period;
  282. if (data_get($seen, $uniqueKey) !== null) {
  283. continue;
  284. }
  285. $seen[$uniqueKey] = true;
  286. ProviderWorkingDay::create([
  287. 'provider_id' => $providerId,
  288. 'day' => $day,
  289. 'period' => $period,
  290. ]);
  291. }
  292. }
  293. //
  294. private function sanitizeDigits(?string $value): ?string
  295. {
  296. if ($value === null) {
  297. return null;
  298. }
  299. $digits = preg_replace('/\D+/', '', $value);
  300. return $digits === '' ? null : $digits;
  301. }
  302. /**
  303. * Efeitos colaterais da aprovação do cadastro do prestador.
  304. * Chamado apenas na transição para ACCEPTED, sempre fora da transação.
  305. */
  306. private function notifyApproved(Provider $provider): void
  307. {
  308. $this->sendApprovedEmail($provider);
  309. $this->sendApprovedPush($provider);
  310. }
  311. private function sendApprovedEmail(Provider $provider): void
  312. {
  313. if (! empty($provider->user?->email)) {
  314. try {
  315. $this->emailService->sendProviderApproved(
  316. email: $provider->user->email,
  317. recipientName: $provider->user->name ?? '',
  318. locale: $provider->user->language?->value,
  319. );
  320. } catch (\Throwable $exception) {
  321. Log::error('Falha ao enviar e-mail de aprovação do prestador', [
  322. 'provider_id' => $provider->id,
  323. 'user_id' => $provider->user?->id,
  324. 'email' => $provider->user?->email,
  325. 'error' => $exception->getMessage(),
  326. ]);
  327. }
  328. return;
  329. }
  330. Log::warning('E-mail de aprovação do prestador ignorado: usuário não possui e-mail', [
  331. 'provider_id' => $provider->id,
  332. 'user_id' => $provider->user?->id,
  333. ]);
  334. }
  335. private function sendApprovedPush(Provider $provider): void
  336. {
  337. $user = $provider->user;
  338. if (! $user) {
  339. Log::warning('Push de aprovação do prestador ignorado: prestador sem usuário', [
  340. 'provider_id' => $provider->id,
  341. ]);
  342. return;
  343. }
  344. $notification = new CadastroAprovadoPush;
  345. $alreadySent = PushNotificationLog::query()
  346. ->where('user_id', $user->id)
  347. ->where('label', $notification->label())
  348. ->exists();
  349. if ($alreadySent) {
  350. return;
  351. }
  352. $hasActiveToken = DeviceToken::query()
  353. ->where('user_id', $user->id)
  354. ->where('app_type', $notification->target()->value)
  355. ->where('active', true)
  356. ->exists();
  357. if (! $hasActiveToken) {
  358. Log::warning('Push de aprovação do prestador ignorado: usuário não possui device token ativo', [
  359. 'provider_id' => $provider->id,
  360. 'user_id' => $user->id,
  361. ]);
  362. return;
  363. }
  364. try {
  365. app(PushNotificationService::class)->sendToUser($user, $notification);
  366. } catch (\Throwable $exception) {
  367. Log::error('Falha ao enviar push de aprovação do prestador', [
  368. 'provider_id' => $provider->id,
  369. 'user_id' => $user->id,
  370. 'error' => $exception->getMessage(),
  371. ]);
  372. }
  373. }
  374. }