ProviderService.php 14 KB

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