CartService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Cart;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Support\Facades\DB;
  7. class CartService
  8. {
  9. public function getAll(): Collection
  10. {
  11. return Cart::query()
  12. ->with(['items.schedule'])
  13. ->orderBy('created_at', 'desc')
  14. ->get();
  15. }
  16. public function findById(int $id): ?Cart
  17. {
  18. return Cart::query()
  19. ->with(['items.schedule'])
  20. ->find($id);
  21. }
  22. public function create(array $data): Cart
  23. {
  24. return Cart::create($data);
  25. }
  26. public function createWithSchedules(array $data): Cart
  27. {
  28. return DB::transaction(function () use ($data) {
  29. $items = $this->scheduleItems($data);
  30. $schedules = app(ScheduleService::class)->createSingleOrMultiple(
  31. baseData: $this->baseScheduleData($data),
  32. schedules: $items,
  33. );
  34. $cart = Cart::create([
  35. 'client_id' => $data['client_id'],
  36. ]);
  37. foreach ($schedules as $schedule) {
  38. $cart->items()->create([
  39. 'schedule_id' => $schedule->id,
  40. ]);
  41. }
  42. return $cart->fresh(['items.schedule.client.user', 'items.schedule.provider.user', 'items.schedule.address']);
  43. });
  44. }
  45. public function update(int $id, array $data): ?Cart
  46. {
  47. $model = $this->findById($id);
  48. if (! $model) {
  49. return null;
  50. }
  51. $model->update($data);
  52. return $model->fresh();
  53. }
  54. public function delete(int $id): bool
  55. {
  56. $model = $this->findById($id);
  57. if (! $model) {
  58. return false;
  59. }
  60. return $model->delete();
  61. }
  62. //
  63. private function baseScheduleData(array $data): array
  64. {
  65. return Arr::except($data, [
  66. 'schedules',
  67. 'dates',
  68. 'date',
  69. 'period_type',
  70. 'start_time',
  71. 'end_time',
  72. 'total_amount',
  73. 'offers_meal',
  74. ]);
  75. }
  76. private function scheduleItems(array $data): array
  77. {
  78. if (! empty($data['schedules'])) {
  79. return $data['schedules'];
  80. }
  81. if (! empty($data['dates'])) {
  82. return array_map(
  83. fn (string $date) => array_merge(
  84. Arr::only($data, ['period_type', 'start_time', 'end_time', 'total_amount', 'offers_meal']),
  85. ['date' => $date],
  86. ),
  87. $data['dates'],
  88. );
  89. }
  90. return [
  91. Arr::only($data, ['date', 'period_type', 'start_time', 'end_time', 'total_amount', 'offers_meal']),
  92. ];
  93. }
  94. }