<?php declare(strict_types=1);
namespace App\Delivery\Controller;
use App\Customer\Service\DeliveryAddressService;
use App\Delivery\Service\HolidayService;
use App\Delivery\Service\ShipmentService;
use App\Delivery\Service\VehicleService;
use App\Framework\Controller\APIController;
use App\Framework\Serializer\APISerializerGroup;
use DateTime;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
#[Route(path: '/api/shipment_routes')]
class ShipmentRoutesController extends APIController
{
/**
*
* @throws ExceptionInterface
* @return mixed[]
*/
#[Route(path: '', methods: ['GET'])]
#[APISerializerGroup('vehicle_route:default', 'vehicle:default', 'order_shipping:default', 'streetaddress:default')]
#[Security("is_granted('ROLE_ADMIN') or is_granted('ROLE_CHOFER') or is_granted('ROLE_HUERTA') or is_granted('ROLE_CALLCENTER')")]
public function getDeliveryRoutes(ShipmentService $shipmentService, VehicleService $vehicleService): array
{
$dateString = $this->getRequestFilter('date', true, null);
$date = new DateTime($dateString);
$result = $shipmentService->getRoutesByDate($date);
// Only return owned routes for drivers
if ($this->isGranted('ROLE_CHOFER')) {
// Reset our routes
$vehicle = $vehicleService->getVehicleByOwner($this->getUser());
$routes = [];
if ($vehicle !== null) {
foreach ($result['routes'] as $route) {
if ($route->getVehicle() === $vehicle) {
$routes[] = $route;
}
}
}
$result['routes'] = $routes;
}
return $result;
}
/**
* @throws ExceptionInterface
*
* @return array<string, bool>
*/
#[Route(path: '/availability', methods: ['GET'])]
public function getAvailabilityForDate(
DeliveryAddressService $deliveryAddressService,
ShipmentService $shipmentService,
VehicleService $vehicleService,
HolidayService $holidayService
): array {
$addressId = (int) $this->getRequestFilter('address', true, null);
$dateString = $this->getRequestFilter('date', true, null);
$startString = $this->getRequestFilter('start', true, null);
$endString = $this->getRequestFilter('end', true, null);
$featureIds = $this->getRequestFilter('features', false, []);
$date = new DateTime($dateString);
// check if the date is a holiday
$isHoliday = $holidayService->isHoliday($date);
if ($isHoliday) {
return [
'available' => false,
];
}
$address = $deliveryAddressService->getAddressById($addressId);
$start = new DateTime('1970-01-01' . $startString);
$end = new DateTime('1970-01-01' . $endString);
$features = array_map(fn ($id) => $vehicleService->getVehicleFeatureById($id), $featureIds);
$result = $shipmentService->isTimeframeAvailable($address, $date, $start, $end, $features);
return [
'available' => $result,
];
}
}