ProviderService.php 13 KB

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