/ app / Http / Services / EntityService.php
EntityService.php
  1  <?php
  2  
  3  namespace App\Http\Services;
  4  
  5  use App\Enums\EntityTypeEnum;
  6  use App\Events\EntityUpdated;
  7  use App\Models\Entity;
  8  use Exception;
  9  use Illuminate\Database\Eloquent\Builder;
 10  use Illuminate\Http\UploadedFile;
 11  use Illuminate\Support\Facades\DB;
 12  use Illuminate\Support\Facades\Log;
 13  use Illuminate\Support\Facades\Storage;
 14  
 15  class EntityService
 16  {
 17      /**
 18       * Search resources
 19       *
 20       * @return Builder
 21       */
 22      public static function search(string $searchString, string $sortField, string $sortDirection, array|null $filters)
 23      {
 24          $entitiesQuery = Entity::with(['type']);
 25  
 26          if ($filters && $filters['withTrashed']) {
 27              $entitiesQuery->withTrashed();
 28          }
 29  
 30          $entitiesQuery->where(function ($query) use ($searchString) {
 31              $query->where('name', 'like', '%' . $searchString . '%')
 32                  ->orWhere('code', 'like', '%' . $searchString . '%')
 33                  ->orWhere('nif', 'like', '%' . $searchString . '%')
 34                  ->orWhere('notification_number', 'like', '%' . $searchString . '%')
 35                  ->orWhere('authorization_number', 'like', '%' . $searchString . '%');
 36          });
 37  
 38          if ($filters && $filters['created_at_since']) {
 39              $entitiesQuery->where('created_at', '>=', $filters['created_at_since']);
 40          }
 41  
 42          if ($filters && $filters['created_at_to']) {
 43              $entitiesQuery->where('created_at', '<=', $filters['created_at_to']);
 44          }
 45  
 46          if ($filters && $filters['entity_type']) {
 47              $entitiesQuery->whereIn('entity_type_id', $filters['entity_type']);
 48          }
 49  
 50          if ($filters && $filters['country']) {
 51              $entitiesQuery->whereHas('contactInfo', function ($query) use ($filters) {
 52                  $query->whereIn('country_id', $filters['country']);
 53              });
 54          }
 55  
 56          if ($sortField && $sortDirection) {
 57              $entitiesQuery->orderBy($sortField, $sortDirection);
 58          }
 59  
 60          return $entitiesQuery;
 61      }
 62  
 63      /**
 64       * Display a listing of the resource.
 65       *
 66       * @return Entity|null
 67       */
 68      public static function find(int $entityId): ?Entity
 69      {
 70          return Entity::where('id', $entityId)->first();
 71      }
 72  
 73      /**
 74       * Display a listing of the resource.
 75       *
 76       * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
 77       */
 78      public static function index()
 79      {
 80          return Entity::orderBy('name', 'asc')->paginate(10);
 81      }
 82  
 83      /**
 84       * Create a resource
 85       *
 86       * @param array $entityData
 87       * @return bool|Exception
 88       * @throws \Throwable
 89       */
 90      public static function create(array $entityData, array $contactInfo): bool|Exception
 91      {
 92          try {
 93              DB::beginTransaction();
 94  
 95              $entity = Entity::create(
 96                  $entityData
 97              );
 98              $entity->contactInfo()->create($contactInfo);
 99  
100              DB::commit();
101  
102              return true;
103          } catch (Exception $e) {
104              DB::rollBack();
105              logger()->error($e);
106              throw new Exception($e->getMessage());
107          }
108      }
109  
110  
111      public static function update(array $data, array $contactInfo, int $entityId, ?UploadedFile $logo = null): bool
112      {
113          // Validate input data
114          if (empty($data) && empty($contactInfo)) {
115              throw \Illuminate\Validation\ValidationException::withMessages([
116                  'data' => [__('entities.notifications.update.error.empty_data')]
117              ]);
118          }
119          DB::beginTransaction();
120          try {
121              $entity = Entity::findOrFail($entityId);
122              $oldLogo = $entity->logo;
123  
124              // Update entity data if provided
125              if (!empty($data)) {
126                  $entity->fill($data);
127                  $entity->save();
128              }
129  
130              // Update contact info if provided
131              if (!empty($contactInfo)) {
132                  $entity->contactInfo()->update($contactInfo);
133              }
134  
135              // Handle logo update
136              if ($logo) {
137                  // Delete old logo if exists
138                  if ($oldLogo && Storage::disk('public')->exists($oldLogo)) {
139                      Storage::disk('public')->delete($oldLogo);
140                  }
141  
142                  // Store new logo using Laravel's file handling
143                  $entity->logo = $logo->store('logos', 'public');
144                  $entity->save();
145              }
146  
147              // Fire event after successful update
148              DB::commit();
149              return true;
150          } catch (\Exception $e) {
151              DB::rollBack();
152              logger()->error($e);
153              throw new Exception(__('entities.notifications.update.error.message'));
154          }
155      }
156  
157      /**
158       * Destroy a resource
159       *
160       * @return true
161       * @throws \Throwable
162       */
163      public static function remove(int $entityId): bool
164      {
165          try {
166              DB::beginTransaction();
167              Entity::destroy($entityId);
168              DB::commit();
169  
170              return true;
171          } catch (Exception $e) {
172              DB::rollBack();
173              throw new Exception(__('entities.notifications.remove.error.message'));
174          }
175      }
176  
177      /**
178       * Restore a resource
179       *
180       * @return true
181       * @throws \Throwable
182       */
183      public static function restore(int $entityId)
184      {
185          try {
186              DB::beginTransaction();
187              Entity::withTrashed()->find($entityId)->restore();
188              DB::commit();
189  
190              return true;
191          } catch (Exception $e) {
192              DB::rollBack();
193              throw new Exception(__('entities.notifications.remove.error.message'));
194          }
195      }
196  
197  
198      public static function getEntityCompanies()
199      {
200          return Entity::query()
201              ->select('id', 'name')
202              ->where('entity_type_id', EntityTypeEnum::company()->value)
203              ->orderBy('name')
204              ->get();
205      }
206  
207      public static function getEntityLaboratories()
208      {
209          return Entity::query()
210              ->select('id', 'name')
211              ->where('entity_type_id', EntityTypeEnum::laboratory()->value)
212              ->orderBy('name')
213              ->get();
214      }
215  }