ProviderService.php 11 KB

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