<?php
namespace App\Controller\Admin;
use App\DTO\Expedient\ApplyDiscountDTO;
use App\Entity\Airline;
use App\Entity\Airplane;
use App\Entity\BusinessClient;
use App\Entity\Shipping;
use App\Services\CubaCustomsService;
use App\Services\DocumentationService;
use App\Services\NomenclatorService;
use App\Services\PackageReceptionService;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Filter\ChoiceFilter;
use EasyCorp\Bundle\EasyAdminBundle\Filter\DateTimeFilter;
use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
use EasyCorp\Bundle\EasyAdminBundle\Filter\TextFilter;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
class ShippingCrudController extends DefaultCrudOptions
{
/**
* @var PackageReceptionService
*/
protected PackageReceptionService $packageService;
/**
* @param PackageReceptionService $packageService
*/
public function __construct(PackageReceptionService $packageService)
{
$this->packageService = $packageService;
}
public static function getEntityFqcn(): string
{
return Shipping::class;
}
public function configureCrud(Crud $crud): Crud
{
return parent::configureCrud($crud)
->setPageTitle(Crud::PAGE_INDEX, 'app.shipping.index.title')
->setDefaultSort(['id' => 'DESC']);
}
public function configureFilters(Filters $filters): Filters
{
return $filters->add(TextFilter::new('label', 'Etiqueta'))
->add(EntityFilter::new('personSending', 'Persona que Envía'))
->add(EntityFilter::new('personReceiving', 'Persona que Recibe'))
->add(DateTimeFilter::new('createAt', 'Fecha de Creación'))
->add(ChoiceFilter::new('deliveryType', 'Tipo de Servicio')
->setChoices(['ENVÍO' => 'shipping', 'ENA' => 'ena']))
->add(EntityFilter::new('createdBy', 'Creado Por'));
}
public function configureFields(string $pageName): iterable
{
return [
TextField::new('label'),
TextField::new('personSending', 'Emisor')
->setTemplatePath('cruds/shipping/emitter-field.html.twig'),
TextField::new('personReceiving', 'Receptor')
->setTemplatePath('cruds/shipping/receiver-field.html.twig'),
DateTimeField::new('createAT', 'F. Creación'),
TextField::new('deliveryType', 'Tipo de Servicio')->setCssClass('text-uppercase')
->setTemplatePath('cruds/shipping/delivery-type-field.html.twig'),
AssociationField::new('box', 'Cant. Bultos'),
NumberField::new('price', 'Precio')
];
}
public function configureActions(Actions $actions): Actions
{
return $actions
->add(Crud::PAGE_INDEX, Action::DETAIL)
->update(Crud::PAGE_INDEX, Action::DETAIL, function (Action $action) {
return $action->linkToRoute('app_package_reception_details', function (Shipping $shipping) {
return [
'id' => $shipping->getId(),
];
})
->setLabel('Expediente');
})
->update(Crud::PAGE_INDEX, Action::NEW, function (Action $action) {
return $action->setCssClass('btn btn-primary')
->setLabel('app.shipping.action.new')
->linkToRoute('app_package_reception');
})
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action) {
return $action->linkToRoute('app_package_reception', function (Shipping $shipping) {
return [
'id' => $shipping->getId(),
];
});
});
}
/**
* @Route("/package/reception", name="app_package_reception")
*/
public function renderPackageReception(Request $request, AdminUrlGenerator $urlGenerator,
NomenclatorService $nomenclatorService,
CubaCustomsService $cubaCustomsService): Response
{
$id = $request->get('id');
$businessClients = $nomenclatorService->getBusinessClients();
$cubaCustomsItems = $cubaCustomsService->getCubaCustomsItems();
$categories = [];
foreach ($cubaCustomsItems as $cubaCustomsItem) {
$index = array_search($cubaCustomsItem['categoryId'], array_column($categories, 'id'));
if (!is_bool($index)) {
$categories[$index]['items'][] = [
'id' => $cubaCustomsItem['itemId'],
'name' => $cubaCustomsItem['itemName'],
'maxQuantity' => $cubaCustomsItem['maxQuantity'],
'customPoint' => $cubaCustomsItem['customPoint'],
'maxQuantityMetricUnit' => $cubaCustomsItem['maxQuantityMetricUnit'],
'metricUnit' => $cubaCustomsItem['metricUnit']
];
} else {
$categories[] = [
'id' => $cubaCustomsItem['categoryId'],
'name' => $cubaCustomsItem['categoryName'],
'items' => [[
'id' => $cubaCustomsItem['itemId'],
'name' => $cubaCustomsItem['itemName'],
'maxQuantity' => $cubaCustomsItem['maxQuantity'],
'customPoint' => $cubaCustomsItem['customPoint'],
'maxQuantityMetricUnit' => $cubaCustomsItem['maxQuantityMetricUnit'],
'metricUnit' => $cubaCustomsItem['metricUnit']
]]
];
}
}
return $this->render('cruds/packageReception/package_reception.html.twig', [
'id' => $id ?? "",
'crudShippingPath' => $urlGenerator->setController(ShippingCrudController::class)
->setAction('index')->generateUrl(),
'businessClients' => array_map(function (BusinessClient $businessClient) {
return ['id' => $businessClient->getId(), 'name' => $businessClient->getName()];
}, $businessClients),
'cubaCustomsCategories' => $categories
]);
}
/**
* @Route("/package/reception/details", name="app_package_reception_details")
*/
public function renderDetails(Request $request, AdminUrlGenerator $urlGenerator,
DocumentationService $documentationService,
NomenclatorService $nomenclatorService): Response
{
$id = $request->get('id');
$airlines = $nomenclatorService->getAirlines();
$airplanes = $nomenclatorService->getAirplanes();
return $this->render('cruds/packageReception/details.html.twig', [
'id' => $id ?? "",
'crudShippingPath' => $urlGenerator->setController(ShippingCrudController::class)
->setAction('index')->generateUrl(),
'houseNumbers' => $documentationService->getAvailableHouseNumbers(),
'masterNumbers' => $documentationService->getAvailableMasterNumbers(),
'airlines' => array_map(function (Airline $airline) {
return ['id' => $airline->getId(), 'name' => $airline->getName()];
}, $airlines),
'airplanes' => array_map(function (Airplane $airplane) {
return ['id' => $airplane->getId(), 'name' => $airplane->getModel()];
}, $airplanes)
]);
}
/**
* @Route("/package/search", name="app_package_search", methods={"POST"})
*/
public function searchShippingById(Request $request): Response
{
return new JsonResponse($this->packageService->searchShippingById($request->toArray()));
}
/**
* @Route("/package/get-general-config", name="app_package_general_config")
*/
public function getGeneralConfig(): Response
{
return new JsonResponse($this->packageService->getGeneralConfig());
}
/**
* @Route("/get-packing-list", name="app_packing_list")
*/
public function getPackingList(): Response
{
return new JsonResponse($this->packageService->getPackingList());
}
/**
* @Route("package/get-item-list", name="app_package_item_list")
*/
public function getItemList(Request $request): Response
{
return new JsonResponse($this->packageService->getItemListByShippingMode($request->get('search')));
}
/**
* @Route(path="/package/get-item-desc", name="app_package_item_desc")
* @param Request $request
* @return Response
*/
public function getItemsByDescription(Request $request): Response
{
$response = $this->packageService->getItemListByTerm($request->query->get('search'));
return $this->json(['status' => true, 'data' => $response]);
}
/**
* @Route(path="/package/emitter/data", methods={"GET"}, name="app_package_emitter_data")
* @param Request $request
* @return Response
*/
public function getEmitterByDocument(Request $request): Response
{
$response = $this->packageService->getEmitterByDocument($request->query->get('document'));
if (!empty($response)) {
$response = $response[0];
$response['dateBirth'] = $response['dateBirth']->format('Y-m-d');
}
return $this->json(['status' => true, 'data' => $response]);
}
/**
* @Route(path="/package/receiver/data", name="app_package_receiver_data", methods={"GET"})
* @param Request $request
* @return Response
*/
public function getReceiverData(Request $request): Response
{
$response = $this->packageService->getReceiverByDocument($request->query->get('document'));
if (!empty($response)) {
$response = $response[0];
}
return $this->json(['status' => true, 'data' => $response]);
}
/**
* @Route("package/add", name="app_add_package", methods={"POST"})
*/
public function addPackage(AdminUrlGenerator $adminUrlGenerator, Request $request, NomenclatorService $nomenclatorService): Response
{
$this->packageService->addPackage($request->toArray(), $this->getUser(), $nomenclatorService);
return new JsonResponse($adminUrlGenerator->setController(ShippingCrudController::class)
->setAction('index')->generateUrl());
}
/**
* @Route(path="/business-clients/prices", name="app_business_client_prices")
* @param Request $request
* @param NomenclatorService $nomenclatorService
* @return Response
*/
public function getPricesForBusinessClients(Request $request, NomenclatorService $nomenclatorService): Response
{
$content = json_decode($request->getContent(), true);
$prices = $nomenclatorService->getPriceRangesForBusinessClients($content['id']);
return $this->json(['status' => true, 'data' => $prices]);
}
/**
* @Route(path="/logs", name="app_shipping_logs", methods={"POST"})
* @param Request $request
* @param PackageReceptionService $packageReceptionService
* @param TranslatorInterface $translator
* @return Response
*/
public function getLogs(Request $request, PackageReceptionService $packageReceptionService, TranslatorInterface $translator): Response
{
$content = json_decode($request->getContent(), true);
$logs = $packageReceptionService->getLogs($content['id']);
$result = array_map(function ($log) use ($translator) {
$log['createdAt'] = $log['createdAt']->format('Y-m-d H:i');
$log['key'] = $log['operation'];
$log['operation'] = $translator->trans('app.packaging.operation.' . $log['operation']);
return $log;
}, $logs);
return $this->json(['status' => true, 'data' => $result]);
}
/**
* @Route(path="/discount/apply", name="app_apply_discount", methods={"POST"})
* @param Request $request
* @param PackageReceptionService $packageReceptionService
* @return Response
*/
public function applyDiscount(Request $request, PackageReceptionService $packageReceptionService): Response
{
$content = json_decode($request->getContent(), true);
$dto = new ApplyDiscountDTO();
$dto->setId($content['id']);
$dto->setAmount($content['amount']);
$dto->setComments($content['comments']);
$result = $packageReceptionService->applyDiscount($dto, $this->getUser());
if ($result) {
$this->addFlash('success', 'Descuento Aplicado Correctamente');
}
return $this->json(['status' => $result]);
}
/**
* @Route(path="/discount/cancel", name="app_discount_cancel", methods={"POST"})
* @param Request $request
* @param PackageReceptionService $packageReceptionService
* @return Response
*/
public function cancelDiscount(Request $request, PackageReceptionService $packageReceptionService): Response
{
$content = json_decode($request->getContent(), true);
$result = $packageReceptionService->cancelDiscount($content['logId'], $content['id'], $this->getUser());
if ($result) {
$this->addFlash('success', 'Descuento Cancelado correctamente');
}
return $this->json(['status' => $result]);
}
}