ProviderService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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['recipient_name']) && ! empty($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 (isset($data['avatar']) && $data['avatar'] instanceof UploadedFile) {
  58. $media = $this->mediaService->replaceFile(
  59. newFile: $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' => $bankAccount['pix_key'] ?? null,
  96. 'bank_account_type' => $bankAccount['type'] ?? null,
  97. 'agency' => $bankAccount['branch_number'] ?? null,
  98. 'account' => $bankAccount['account_number'] ?? null,
  99. 'digit' => $bankAccount['account_check_digit'] ?? null,
  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['email'] ?? null;
  117. $phone = $data['phone'] ?? null;
  118. $code = $data['code'] ?? null;
  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['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['rg'] ?? null;
  151. $provider->document = $this->sanitizeDigits($data['document'] ?? null);
  152. $provider->birth_date = $data['birth_date'] ?? null;
  153. $provider->daily_price_8h = $data['daily_price_8h'] ?? null;
  154. $provider->daily_price_6h = $data['daily_price_6h'] ?? null;
  155. $provider->daily_price_4h = $data['daily_price_4h'] ?? null;
  156. $provider->daily_price_2h = $data['daily_price_2h'] ?? null;
  157. $provider->approval_status = ApprovalStatusEnum::PENDING->value;
  158. $provider->save();
  159. $provider->refresh();
  160. $provider->load('profileMedia', 'documentFrontMedia', 'documentBackMedia');
  161. $selfie = $this->mediaService->replaceFile(
  162. newFile: $data['selfie'],
  163. folder: "provider/avatar/{$provider->id}",
  164. source: 'provider',
  165. sourceId: $provider->id,
  166. old: $provider->profileMedia,
  167. );
  168. $provider->profile_media_id = $selfie->id;
  169. $front = $this->mediaService->replaceFile(
  170. newFile: $data['document_front'],
  171. folder: "provider/documentos/{$provider->id}",
  172. source: 'provider_document',
  173. sourceId: $provider->id,
  174. old: $provider->documentFrontMedia,
  175. filename: 'frente.'.$data['document_front']->getClientOriginalExtension(),
  176. );
  177. $provider->document_front_media_id = $front->id;
  178. $back = $this->mediaService->replaceFile(
  179. newFile: $data['document_back'],
  180. folder: "provider/documentos/{$provider->id}",
  181. source: 'provider_document',
  182. sourceId: $provider->id,
  183. old: $provider->documentBackMedia,
  184. filename: 'verso.'.$data['document_back']->getClientOriginalExtension(),
  185. );
  186. $provider->document_back_media_id = $back->id;
  187. $provider->save();
  188. $bankAccount = $data['recipient_default_bank_account'] ?? [];
  189. $hasBankData = ! empty($bankAccount['bank']) && ! empty($bankAccount['account_number']);
  190. if (! empty($data['recipient_name']) && $hasBankData && empty($provider->recipient_id)) {
  191. $this->pagarmeRecipientService->createRecipientForProvider($provider, $data);
  192. }
  193. Address::where('source', 'provider')->where('source_id', $provider->id)->delete();
  194. $this->createProviderAddress($provider->id, $data);
  195. ProviderServicesType::where('provider_id', $provider->id)->delete();
  196. $this->createProviderServicesTypes($provider->id, $data);
  197. ProviderWorkingDay::where('provider_id', $provider->id)->delete();
  198. $this->createProviderWorkingDays($provider->id, $data);
  199. if ((empty($user->email) && empty($user->phone)) || empty($user->code)) {
  200. throw new \Exception(__('messages.user_not_found_or_code_not_validated'));
  201. }
  202. $user->registration_complete = true;
  203. $user->validated_code = true;
  204. $user->code = null;
  205. $user->save();
  206. $result = $this->authService->createAppSession($user);
  207. DB::commit();
  208. return $result;
  209. } catch (\Exception $e) {
  210. DB::rollBack();
  211. Log::error('Error registering provider: '.$e->getMessage(), [
  212. 'data' => $data,
  213. ]);
  214. throw $e;
  215. }
  216. }
  217. public function updateBankAccount(int $id, array $bankAccountData): ?Provider
  218. {
  219. $provider = Provider::with(['user', 'addresses.city', 'addresses.state'])->find($id);
  220. if (! $provider) {
  221. return null;
  222. }
  223. $bankAccountData['holder_name'] = $bankAccountData['holder_name'] ?? $provider->user?->name;
  224. $bankAccountData['holder_document'] = $bankAccountData['holder_document'] ?? $provider->document;
  225. $bankAccountData['holder_type'] = $bankAccountData['holder_type'] ?? 'individual';
  226. if (empty($provider->recipient_id)) {
  227. $this->pagarmeRecipientService->createRecipientForProvider(
  228. $provider,
  229. $this->buildRecipientDataFromProvider($provider, $bankAccountData),
  230. );
  231. } else {
  232. $this->pagarmeRecipientService->updateDefaultBankAccount($provider, $bankAccountData);
  233. }
  234. return $provider->fresh(['user', 'profileMedia']);
  235. }
  236. //
  237. public function approve(int $id): Provider
  238. {
  239. [$provider, $wasAccepted] = DB::transaction(function () use ($id) {
  240. $provider = Provider::findOrFail($id);
  241. $wasAccepted = $provider->approval_status === ApprovalStatusEnum::ACCEPTED;
  242. $provider->update(['approval_status' => ApprovalStatusEnum::ACCEPTED->value]);
  243. return [$provider->fresh(['user', 'profileMedia']), $wasAccepted];
  244. });
  245. if (! $wasAccepted) {
  246. $this->sendApprovedEmail($provider);
  247. }
  248. return $provider;
  249. }
  250. public function reject(int $id): Provider
  251. {
  252. return DB::transaction(function () use ($id) {
  253. $provider = Provider::findOrFail($id);
  254. $provider->update(['approval_status' => ApprovalStatusEnum::REJECTED->value]);
  255. return $provider->fresh(['user', 'profileMedia']);
  256. });
  257. }
  258. //
  259. private function buildRecipientDataFromProvider(Provider $provider, array $bankAccountData): array
  260. {
  261. $address = $provider->addresses->first();
  262. return [
  263. 'recipient_name' => $provider->user?->name,
  264. 'recipient_email' => $provider->user?->email,
  265. 'recipient_document' => $provider->document,
  266. 'recipient_type' => 'individual',
  267. 'recipient_payment_mode' => 'bank_transfer',
  268. 'recipient_metadata' => [],
  269. 'recipient_default_bank_account' => $bankAccountData,
  270. 'birth_date' => $provider->birth_date,
  271. 'phone' => $provider->user?->phone,
  272. 'address' => $address?->address,
  273. 'number' => $address?->number,
  274. 'city' => $address?->city?->name,
  275. 'state' => $address?->state?->code,
  276. 'zip_code' => $address?->zip_code,
  277. ];
  278. }
  279. private function createProviderAddress(int $providerId, array $data): void
  280. {
  281. $state = null;
  282. $city = null;
  283. if (! empty($data['state'])) {
  284. $state = State::query()
  285. ->whereRaw('LOWER(code) = ?', [mb_strtolower($data['state'])])
  286. ->first();
  287. }
  288. if (! empty($data['city'])) {
  289. $cityQuery = City::query()
  290. ->whereRaw('LOWER(name) = ?', [mb_strtolower($data['city'])]);
  291. if ($state) {
  292. $cityQuery->where('state_id', $state->id);
  293. }
  294. $city = $cityQuery->first();
  295. }
  296. $address = new Address;
  297. $address->source = 'provider';
  298. $address->source_id = $providerId;
  299. $address->zip_code = $this->sanitizeDigits($data['zip_code'] ?? null);
  300. $address->address = $data['address'] ?? null;
  301. $address->number = $data['number'] ?? null;
  302. $address->district = $data['district'] ?? null;
  303. $address->has_complement = (bool) ($data['has_complement'] ?? false);
  304. $address->complement = $data['complement'] ?? null;
  305. $address->nickname = $data['nickname'] ?? null;
  306. $address->instructions = $data['instructions'] ?? null;
  307. $address->address_type = $data['address_type'] ?? 'home';
  308. $address->state_id = $state?->id;
  309. $address->city_id = $city?->id;
  310. $address->latitude = $data['latitude'] ?? null;
  311. $address->longitude = $data['longitude'] ?? null;
  312. $address->save();
  313. }
  314. private function createProviderServicesTypes(int $providerId, array $data): void
  315. {
  316. $serviceTypeIds = $data['services_types_ids'] ?? $data['service_types_ids'] ?? [];
  317. $uniqueIds = array_values(array_unique(array_map('intval', $serviceTypeIds)));
  318. foreach ($uniqueIds as $serviceTypeId) {
  319. ProviderServicesType::create([
  320. 'provider_id' => $providerId,
  321. 'service_type_id' => $serviceTypeId,
  322. ]);
  323. }
  324. }
  325. private function createProviderWorkingDays(int $providerId, array $data): void
  326. {
  327. $workingDays = $data['working_days'] ?? [];
  328. $seen = [];
  329. foreach ($workingDays as $workingDay) {
  330. $day = (int) ($workingDay['day'] ?? -1);
  331. $period = $workingDay['period'] ?? null;
  332. if ($day < 0 || $day > 6 || ! in_array($period, ['morning', 'afternoon'], true)) {
  333. continue;
  334. }
  335. $uniqueKey = $day.'-'.$period;
  336. if (isset($seen[$uniqueKey])) {
  337. continue;
  338. }
  339. $seen[$uniqueKey] = true;
  340. ProviderWorkingDay::create([
  341. 'provider_id' => $providerId,
  342. 'day' => $day,
  343. 'period' => $period,
  344. ]);
  345. }
  346. }
  347. //
  348. private function sanitizeDigits(?string $value): ?string
  349. {
  350. if ($value === null) {
  351. return null;
  352. }
  353. $digits = preg_replace('/\D+/', '', $value);
  354. return $digits === '' ? null : $digits;
  355. }
  356. private function sendApprovedEmail(Provider $provider): void
  357. {
  358. if (! empty($provider->user?->email)) {
  359. try {
  360. $this->emailService->sendProviderApproved(
  361. email: $provider->user->email,
  362. recipientName: $provider->user->name ?? '',
  363. locale: $provider->user->language?->value,
  364. );
  365. } catch (\Throwable $exception) {
  366. Log::error('Provider approval email failed', [
  367. 'provider_id' => $provider->id,
  368. 'user_id' => $provider->user?->id,
  369. 'email' => $provider->user?->email,
  370. 'error' => $exception->getMessage(),
  371. ]);
  372. }
  373. return;
  374. }
  375. Log::warning('Provider approval email skipped: provider user has no email', [
  376. 'provider_id' => $provider->id,
  377. 'user_id' => $provider->user?->id,
  378. ]);
  379. }
  380. }