ProviderService.php 17 KB

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