ProviderService.php 10 KB

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