ProviderService.php 16 KB

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