src/Controller/Admin/ShippingCrudController.php line 207

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\DTO\Expedient\ApplyDiscountDTO;
  4. use App\Entity\Airline;
  5. use App\Entity\Airplane;
  6. use App\Entity\BusinessClient;
  7. use App\Entity\Shipping;
  8. use App\Services\CubaCustomsService;
  9. use App\Services\DocumentationService;
  10. use App\Services\NomenclatorService;
  11. use App\Services\PackageReceptionService;
  12. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  13. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  14. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  15. use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
  16. use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  17. use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
  18. use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
  19. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  20. use EasyCorp\Bundle\EasyAdminBundle\Filter\ChoiceFilter;
  21. use EasyCorp\Bundle\EasyAdminBundle\Filter\DateTimeFilter;
  22. use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
  23. use EasyCorp\Bundle\EasyAdminBundle\Filter\TextFilter;
  24. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  25. use Symfony\Component\HttpFoundation\JsonResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Contracts\Translation\TranslatorInterface;
  30. class ShippingCrudController extends DefaultCrudOptions
  31. {
  32.     /**
  33.      * @var PackageReceptionService
  34.      */
  35.     protected PackageReceptionService $packageService;
  36.     /**
  37.      * @param PackageReceptionService $packageService
  38.      */
  39.     public function __construct(PackageReceptionService $packageService)
  40.     {
  41.         $this->packageService $packageService;
  42.     }
  43.     public static function getEntityFqcn(): string
  44.     {
  45.         return Shipping::class;
  46.     }
  47.     public function configureCrud(Crud $crud): Crud
  48.     {
  49.         return parent::configureCrud($crud)
  50.             ->setPageTitle(Crud::PAGE_INDEX'app.shipping.index.title')
  51.             ->setDefaultSort(['id' => 'DESC']);
  52.     }
  53.     public function configureFilters(Filters $filters): Filters
  54.     {
  55.         return $filters->add(TextFilter::new('label''Etiqueta'))
  56.             ->add(EntityFilter::new('personSending''Persona que Envía'))
  57.             ->add(EntityFilter::new('personReceiving''Persona que Recibe'))
  58.             ->add(DateTimeFilter::new('createAt''Fecha de Creación'))
  59.             ->add(ChoiceFilter::new('deliveryType''Tipo de Servicio')
  60.                 ->setChoices(['ENVÍO' => 'shipping''ENA' => 'ena']))
  61.             ->add(EntityFilter::new('createdBy''Creado Por'));
  62.     }
  63.     public function configureFields(string $pageName): iterable
  64.     {
  65.         return [
  66.             TextField::new('label'),
  67.             TextField::new('personSending''Emisor')
  68.                 ->setTemplatePath('cruds/shipping/emitter-field.html.twig'),
  69.             TextField::new('personReceiving''Receptor')
  70.                 ->setTemplatePath('cruds/shipping/receiver-field.html.twig'),
  71.             DateTimeField::new('createAT''F. Creación'),
  72.             TextField::new('deliveryType''Tipo de Servicio')->setCssClass('text-uppercase')
  73.                 ->setTemplatePath('cruds/shipping/delivery-type-field.html.twig'),
  74.             AssociationField::new('box''Cant. Bultos'),
  75.             NumberField::new('price''Precio')
  76.         ];
  77.     }
  78.     public function configureActions(Actions $actions): Actions
  79.     {
  80.         return $actions
  81.             ->add(Crud::PAGE_INDEXAction::DETAIL)
  82.             ->update(Crud::PAGE_INDEXAction::DETAIL, function (Action $action) {
  83.                 return $action->linkToRoute('app_package_reception_details', function (Shipping $shipping) {
  84.                     return [
  85.                         'id' => $shipping->getId(),
  86.                     ];
  87.                 })
  88.                     ->setLabel('Expediente');
  89.             })
  90.             ->update(Crud::PAGE_INDEXAction::NEW, function (Action $action) {
  91.                 return $action->setCssClass('btn btn-primary')
  92.                     ->setLabel('app.shipping.action.new')
  93.                     ->linkToRoute('app_package_reception');
  94.             })
  95.             ->update(Crud::PAGE_INDEXAction::EDIT, function (Action $action) {
  96.                 return $action->linkToRoute('app_package_reception', function (Shipping $shipping) {
  97.                     return [
  98.                         'id' => $shipping->getId(),
  99.                     ];
  100.                 });
  101.             });
  102.     }
  103.     /**
  104.      * @Route("/package/reception", name="app_package_reception")
  105.      */
  106.     public function renderPackageReception(Request            $requestAdminUrlGenerator $urlGenerator,
  107.                                            NomenclatorService $nomenclatorService,
  108.                                            CubaCustomsService $cubaCustomsService): Response
  109.     {
  110.         $id $request->get('id');
  111.         $businessClients $nomenclatorService->getBusinessClients();
  112.         $cubaCustomsItems $cubaCustomsService->getCubaCustomsItems();
  113.         $categories = [];
  114.         foreach ($cubaCustomsItems as $cubaCustomsItem) {
  115.             $index array_search($cubaCustomsItem['categoryId'], array_column($categories'id'));
  116.             if (!is_bool($index)) {
  117.                 $categories[$index]['items'][] = [
  118.                     'id' => $cubaCustomsItem['itemId'],
  119.                     'name' => $cubaCustomsItem['itemName'],
  120.                     'maxQuantity' => $cubaCustomsItem['maxQuantity'],
  121.                     'customPoint' => $cubaCustomsItem['customPoint'],
  122.                     'maxQuantityMetricUnit' => $cubaCustomsItem['maxQuantityMetricUnit'],
  123.                     'metricUnit' => $cubaCustomsItem['metricUnit']
  124.                 ];
  125.             } else {
  126.                 $categories[] = [
  127.                     'id' => $cubaCustomsItem['categoryId'],
  128.                     'name' => $cubaCustomsItem['categoryName'],
  129.                     'items' => [[
  130.                         'id' => $cubaCustomsItem['itemId'],
  131.                         'name' => $cubaCustomsItem['itemName'],
  132.                         'maxQuantity' => $cubaCustomsItem['maxQuantity'],
  133.                         'customPoint' => $cubaCustomsItem['customPoint'],
  134.                         'maxQuantityMetricUnit' => $cubaCustomsItem['maxQuantityMetricUnit'],
  135.                         'metricUnit' => $cubaCustomsItem['metricUnit']
  136.                     ]]
  137.                 ];
  138.             }
  139.         }
  140.         return $this->render('cruds/packageReception/package_reception.html.twig', [
  141.             'id' => $id ?? "",
  142.             'crudShippingPath' => $urlGenerator->setController(ShippingCrudController::class)
  143.                 ->setAction('index')->generateUrl(),
  144.             'businessClients' => array_map(function (BusinessClient $businessClient) {
  145.                 return ['id' => $businessClient->getId(), 'name' => $businessClient->getName()];
  146.             }, $businessClients),
  147.             'cubaCustomsCategories' => $categories
  148.         ]);
  149.     }
  150.     /**
  151.      * @Route("/package/reception/details", name="app_package_reception_details")
  152.      */
  153.     public function renderDetails(Request              $requestAdminUrlGenerator $urlGenerator,
  154.                                   DocumentationService $documentationService,
  155.                                   NomenclatorService   $nomenclatorService): Response
  156.     {
  157.         $id $request->get('id');
  158.         $airlines $nomenclatorService->getAirlines();
  159.         $airplanes $nomenclatorService->getAirplanes();
  160.         return $this->render('cruds/packageReception/details.html.twig', [
  161.             'id' => $id ?? "",
  162.             'crudShippingPath' => $urlGenerator->setController(ShippingCrudController::class)
  163.                 ->setAction('index')->generateUrl(),
  164.             'houseNumbers' => $documentationService->getAvailableHouseNumbers(),
  165.             'masterNumbers' => $documentationService->getAvailableMasterNumbers(),
  166.             'airlines' => array_map(function (Airline $airline) {
  167.                 return ['id' => $airline->getId(), 'name' => $airline->getName()];
  168.             }, $airlines),
  169.             'airplanes' => array_map(function (Airplane $airplane) {
  170.                 return ['id' => $airplane->getId(), 'name' => $airplane->getModel()];
  171.             }, $airplanes)
  172.         ]);
  173.     }
  174.     /**
  175.      * @Route("/package/search", name="app_package_search", methods={"POST"})
  176.      */
  177.     public function searchShippingById(Request $request): Response
  178.     {
  179.         return new JsonResponse($this->packageService->searchShippingById($request->toArray()));
  180.     }
  181.     /**
  182.      * @Route("/package/get-general-config", name="app_package_general_config")
  183.      */
  184.     public function getGeneralConfig(): Response
  185.     {
  186.         return new JsonResponse($this->packageService->getGeneralConfig());
  187.     }
  188.     /**
  189.      * @Route("/get-packing-list", name="app_packing_list")
  190.      */
  191.     public function getPackingList(): Response
  192.     {
  193.         return new JsonResponse($this->packageService->getPackingList());
  194.     }
  195.     /**
  196.      * @Route("package/get-item-list", name="app_package_item_list")
  197.      */
  198.     public function getItemList(Request $request): Response
  199.     {
  200.         return new JsonResponse($this->packageService->getItemListByShippingMode($request->get('search')));
  201.     }
  202.     /**
  203.      * @Route(path="/package/get-item-desc", name="app_package_item_desc")
  204.      * @param Request $request
  205.      * @return Response
  206.      */
  207.     public function getItemsByDescription(Request $request): Response
  208.     {
  209.         $response $this->packageService->getItemListByTerm($request->query->get('search'));
  210.         return $this->json(['status' => true'data' => $response]);
  211.     }
  212.     /**
  213.      * @Route(path="/package/emitter/data", methods={"GET"}, name="app_package_emitter_data")
  214.      * @param Request $request
  215.      * @return Response
  216.      */
  217.     public function getEmitterByDocument(Request $request): Response
  218.     {
  219.         $response $this->packageService->getEmitterByDocument($request->query->get('document'));
  220.         if (!empty($response)) {
  221.             $response $response[0];
  222.             $response['dateBirth'] = $response['dateBirth']->format('Y-m-d');
  223.         }
  224.         return $this->json(['status' => true'data' => $response]);
  225.     }
  226.     /**
  227.      * @Route(path="/package/receiver/data", name="app_package_receiver_data", methods={"GET"})
  228.      * @param Request $request
  229.      * @return Response
  230.      */
  231.     public function getReceiverData(Request $request): Response
  232.     {
  233.         $response $this->packageService->getReceiverByDocument($request->query->get('document'));
  234.         if (!empty($response)) {
  235.             $response $response[0];
  236.         }
  237.         return $this->json(['status' => true'data' => $response]);
  238.     }
  239.     /**
  240.      * @Route("package/add", name="app_add_package", methods={"POST"})
  241.      */
  242.     public function addPackage(AdminUrlGenerator $adminUrlGeneratorRequest $requestNomenclatorService $nomenclatorService): Response
  243.     {
  244.         $this->packageService->addPackage($request->toArray(), $this->getUser(), $nomenclatorService);
  245.         return new JsonResponse($adminUrlGenerator->setController(ShippingCrudController::class)
  246.             ->setAction('index')->generateUrl());
  247.     }
  248.     /**
  249.      * @Route(path="/business-clients/prices", name="app_business_client_prices")
  250.      * @param Request $request
  251.      * @param NomenclatorService $nomenclatorService
  252.      * @return Response
  253.      */
  254.     public function getPricesForBusinessClients(Request $requestNomenclatorService $nomenclatorService): Response
  255.     {
  256.         $content json_decode($request->getContent(), true);
  257.         $prices $nomenclatorService->getPriceRangesForBusinessClients($content['id']);
  258.         return $this->json(['status' => true'data' => $prices]);
  259.     }
  260.     /**
  261.      * @Route(path="/logs", name="app_shipping_logs", methods={"POST"})
  262.      * @param Request $request
  263.      * @param PackageReceptionService $packageReceptionService
  264.      * @param TranslatorInterface $translator
  265.      * @return Response
  266.      */
  267.     public function getLogs(Request $requestPackageReceptionService $packageReceptionServiceTranslatorInterface $translator): Response
  268.     {
  269.         $content json_decode($request->getContent(), true);
  270.         $logs $packageReceptionService->getLogs($content['id']);
  271.         $result array_map(function ($log) use ($translator) {
  272.             $log['createdAt'] = $log['createdAt']->format('Y-m-d H:i');
  273.             $log['key'] = $log['operation'];
  274.             $log['operation'] = $translator->trans('app.packaging.operation.' $log['operation']);
  275.             return $log;
  276.         }, $logs);
  277.         return $this->json(['status' => true'data' => $result]);
  278.     }
  279.     /**
  280.      * @Route(path="/discount/apply", name="app_apply_discount", methods={"POST"})
  281.      * @param Request $request
  282.      * @param PackageReceptionService $packageReceptionService
  283.      * @return Response
  284.      */
  285.     public function applyDiscount(Request $requestPackageReceptionService $packageReceptionService): Response
  286.     {
  287.         $content json_decode($request->getContent(), true);
  288.         $dto = new ApplyDiscountDTO();
  289.         $dto->setId($content['id']);
  290.         $dto->setAmount($content['amount']);
  291.         $dto->setComments($content['comments']);
  292.         $result $packageReceptionService->applyDiscount($dto$this->getUser());
  293.         if ($result) {
  294.             $this->addFlash('success''Descuento Aplicado Correctamente');
  295.         }
  296.         return $this->json(['status' => $result]);
  297.     }
  298.     /**
  299.      * @Route(path="/discount/cancel", name="app_discount_cancel", methods={"POST"})
  300.      * @param Request $request
  301.      * @param PackageReceptionService $packageReceptionService
  302.      * @return Response
  303.      */
  304.     public function cancelDiscount(Request $requestPackageReceptionService $packageReceptionService): Response
  305.     {
  306.         $content json_decode($request->getContent(), true);
  307.         $result $packageReceptionService->cancelDiscount($content['logId'], $content['id'], $this->getUser());
  308.         if ($result) {
  309.             $this->addFlash('success''Descuento Cancelado correctamente');
  310.         }
  311.         return $this->json(['status' => $result]);
  312.     }
  313. }