FranchiseeContractService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Services;
  3. use App\Models\FranchiseeContract;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class FranchiseeContractService
  6. {
  7. public function getAll(): Collection
  8. {
  9. return FranchiseeContract::orderBy('created_at', 'desc')
  10. ->get();
  11. }
  12. public function getActive(): Collection
  13. {
  14. $today = now()->toDateString();
  15. return FranchiseeContract::with('unit')
  16. ->whereNotNull('start_date')
  17. ->whereNotNull('end_date')
  18. ->where('start_date', '<=', $today)
  19. ->where('end_date', '>=', $today)
  20. ->orderBy('start_date')
  21. ->get();
  22. }
  23. public function findById(int $id): ?FranchiseeContract
  24. {
  25. return FranchiseeContract::find($id);
  26. }
  27. public function getByUnitId(int $unitId): Collection
  28. {
  29. return FranchiseeContract::where('unit_id', $unitId)
  30. ->orderBy('created_at', 'desc')
  31. ->get();
  32. }
  33. public function create(array $data): FranchiseeContract
  34. {
  35. $data['protocol'] = (FranchiseeContract::where('unit_id', $data['unit_id'])->max('protocol') ?? 0) + 1;
  36. $data['signature_date'] = $data['start_date'];
  37. if (isset($data['start_date'], $data['end_date'])) {
  38. $data['validity_months'] = (int) \Carbon\Carbon::parse($data['start_date'])
  39. ->diffInMonths(\Carbon\Carbon::parse($data['end_date']));
  40. }
  41. return FranchiseeContract::create($data);
  42. }
  43. public function update(int $id, array $data): ?FranchiseeContract
  44. {
  45. $model = $this->findById($id);
  46. if (!$model) {
  47. return null;
  48. }
  49. $model->update($data);
  50. return $model->fresh();
  51. }
  52. public function delete(int $id): bool
  53. {
  54. $model = $this->findById($id);
  55. if (!$model) {
  56. return false;
  57. }
  58. return $model->delete();
  59. }
  60. // Add custom business logic methods here
  61. }