|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Services; |
| 4 | + |
| 5 | +use App\Repositories\Interfaces\OrderRepositoryInterface; |
| 6 | +use App\Traits\Filterable; |
| 7 | + |
| 8 | +class OrderService |
| 9 | +{ |
| 10 | + use Filterable; |
| 11 | + |
| 12 | + /** |
| 13 | + * Inject the order repository |
| 14 | + * |
| 15 | + * @param OrderRepositoryInterface $orderRepo |
| 16 | + */ |
| 17 | + public function __construct( |
| 18 | + protected OrderRepositoryInterface $orderRepo |
| 19 | + ) {} |
| 20 | + |
| 21 | + /** |
| 22 | + * Get paginated orders with filters |
| 23 | + * |
| 24 | + * @param int $perPage |
| 25 | + * @param array $filters |
| 26 | + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator |
| 27 | + */ |
| 28 | + public function getAllPaginated(int $perPage = 10, array $filters = []) |
| 29 | + { |
| 30 | + $query = $this->orderRepo->query()->with(['user', 'orderItems.item']); |
| 31 | + |
| 32 | + if (! empty($filters['search'])) { |
| 33 | + $query->where(function ($q) use ($filters) { |
| 34 | + $q->where('id', 'like', '%' . $filters['search'] . '%') |
| 35 | + ->orWhereHas('user', function ($userQuery) use ($filters) { |
| 36 | + $userQuery->where('name', 'like', '%' . $filters['search'] . '%'); |
| 37 | + }); |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + $this->applyExactFilter($query, 'status', $filters['status'] ?? null); |
| 42 | + $this->applyExactFilter($query, 'payment_method', $filters['payment_method'] ?? null); |
| 43 | + $this->applyExactFilter($query, 'delivery_method', $filters['delivery_method'] ?? null); |
| 44 | + |
| 45 | + return $query->orderBy('created_at', 'desc')->paginate($perPage); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Find an order by ID |
| 50 | + * |
| 51 | + * @param int $id |
| 52 | + * @return Order|null |
| 53 | + */ |
| 54 | + public function find(int $id) |
| 55 | + { |
| 56 | + return $this->orderRepo->query() |
| 57 | + ->with(['user', 'orderItems.item']) |
| 58 | + ->find($id); |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Update order status |
| 63 | + * |
| 64 | + * @param int $id |
| 65 | + * @param string $status |
| 66 | + * @return bool |
| 67 | + */ |
| 68 | + public function updateStatus(int $id, string $status): bool |
| 69 | + { |
| 70 | + $data = ['status' => $status]; |
| 71 | + |
| 72 | + return $this->orderRepo->update($id, $data); |
| 73 | + } |
| 74 | +} |
0 commit comments