src/Controller/Admin/ValoracionAdminController.php line 36

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller\Admin;
  4. use App\Entity\UnidadNegocio;
  5. use App\Entity\Usuario;
  6. use App\Entity\Valoracion;
  7. use App\Entity\ValoracionesRelojes;
  8. use App\Enum\TipoOperacionEnum;
  9. use App\Exception\EnTramitacionOperacionException;
  10. use App\Exception\EnTramitacionValoracionException;
  11. use App\UseCase\Valoracion\EnTramitacionUseCase;
  12. use Doctrine\Persistence\ManagerRegistry;
  13. use Sonata\AdminBundle\Bridge\Exporter\AdminExporter;
  14. use Sonata\AdminBundle\Controller\CRUDController;
  15. use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  19. use Symfony\Component\Routing\Generator\UrlGenerator;
  20. use function is_string;
  21. final class ValoracionAdminController extends CRUDController
  22. {
  23.     protected $om;
  24.     public function __construct(ManagerRegistry $mr,
  25.         private AdminExporter $exporter,
  26.         private EnTramitacionUseCase $useCaseEnTramitacionValoracion)
  27.     {
  28.         $this->om $mr->getManager();
  29.     }
  30.     public function listAction(Request $request): Response
  31.     {
  32.         $this->assertObjectExists($request);
  33.         $this->admin->checkAccess('list');
  34.         $preResponse $this->preList($request);
  35.         if (null !== $preResponse) {
  36.             return $preResponse;
  37.         }
  38.         $listMode $request->get('_list_mode');
  39.         if (is_string($listMode)) {
  40.             $this->admin->setListMode($listMode);
  41.         }
  42.         $datagrid $this->admin->getDatagrid();
  43.         $datagrid->buildPager();
  44.         $pager $datagrid->getPager();
  45.         $pager->setPage($request->query->getInt('page'1));
  46.         $formView $datagrid->getForm()->createView();
  47.         // Ejecutamos la query y obtenemos resultados iniciales
  48.         $results iterator_to_array($pager->getCurrentPageResults());
  49.         $valoracionIds array_map(fn($vR) => $vR->getValoracion()->getId(), $results);
  50.         $search $datagrid->getValues()['busqueda']['value'] ?? null;
  51.         if ($search && count($valoracionIds) > 0) {
  52.             $qb $this->om->getRepository(ValoracionesRelojes::class)->qbValoracionesSinStockByIdValoracion($valoracionIds);
  53.             $pager->setQuery(new ProxyQuery($qb));
  54.         }
  55.         // set the theme for the current Admin Form
  56.         $this->setFormTheme($formView$this->admin->getFilterTheme());
  57.         $template $this->admin->getTemplateRegistry()->getTemplate('list');
  58. //        if ($this->container->has('sonata.admin.admin_exporter')) {
  59. //            $exporter = $this->container->get('sonata.admin.admin_exporter');
  60. //            \assert($exporter instanceof AdminExporter);
  61.             $exportFormats $this->exporter->getAvailableFormats($this->admin);
  62. //        }
  63.         return $this->render($template, [
  64.             'action' => 'list',
  65.             'form' => $formView,
  66.             'datagrid' => $datagrid,
  67.             'csrf_token' => $this->getCsrfToken('sonata.batch'),
  68.             'export_formats' => $exportFormats ?? $this->admin->getExportFormats(),
  69.         ]);
  70.     }
  71. //    protected function preList(Request $request): ?Response
  72. //    {
  73. //        $response = parent::preList($request);
  74. //
  75. //        $datagrid = $this->admin->getDatagrid();
  76. //        $pager = $datagrid->getPager();
  77. //        $query = $pager->getQuery();
  78. //
  79. //        // Obtener valor del filtro de búsqueda
  80. //        $filters = $datagrid->getValues();
  81. //        $search = $filters['busqueda']['value'] ?? null;
  82. //
  83. //        if (!$search) return $response;
  84. //
  85. //        // Ejecutar query original para sacar IDs de Valoraciones
  86. //        $originalResults = $pager->getCurrentPageResults();
  87. //        $valoracionIds = array_map(fn($vR) => $vR->getValoracion()->getId(), $originalResults);
  88. //
  89. //        if (empty($valoracionIds)) return $response;
  90. //
  91. //        // Crear nueva query: todos los ValoracionesRelojes de esas Valoraciones
  92. //        $qb = $this->em->createQueryBuilder();
  93. //        $qb->select('vr')
  94. //            ->from(ValoracionesRelojes::class, 'vr')
  95. //            ->innerJoin('vr.valoracion', 'v')
  96. //            ->where($qb->expr()->in('v.id', ':valoracionIds'))
  97. //            ->setParameter('valoracionIds', $valoracionIds)
  98. //            ->orderBy('v.fecha', 'DESC');
  99. //
  100. //        // Reemplazar query del Pager
  101. //        $pager->setQuery($qb->getQuery());
  102. //
  103. //        return $response;
  104. //    }
  105.     public function editAction(Request $request): Response
  106.     {
  107.         $responseEdit parent::editAction($request);
  108.         try {
  109.             switch ($request->query->get('action'))
  110.             {
  111.                 case 'in-process':
  112.                     return $this->inProcessAction($request);
  113.                 case 'sales-management':
  114.                     return $this->salesManagementAction($request);
  115.                 default:
  116.                     return $responseEdit;
  117.             }
  118.         }
  119.         catch (EmptyOperacionException $e)
  120.         {
  121.             $this->addFlash('error'$this->trans($e->getMessage(), [], 'exception'));
  122.         }
  123.         return $this->redirect($_SERVER['HTTP_REFERER']);
  124.     }
  125.     public function statsAction()
  126.     {
  127.     }
  128.     public function historyAction(Request $request): Response
  129.     {
  130.         return parent::historyAction($request); // TODO: Change the autogenerated stub
  131.     }
  132.     public function cloneAction(Request $request)
  133.     {
  134.         try {
  135.             $user $this->getUser()?->getUsuario();
  136.             $id $request->get($this->admin->getIdParameter());
  137.             $object $this->admin->getObject($id);
  138.             if (!$object) {
  139.                 throw new NotFoundHttpException('VALORACION_NOT_EXISTS');
  140.             }
  141.             $clonedObject = clone $object;
  142.             $object->setDuplicados($object->getDuplicados() + 1);
  143.             $clonedObject->setClone($object);
  144.             $clonedObject->setUsuario($this->om->getReference(Usuario::class, $user->getId()));
  145.             $unidad $clonedObject->getUnidadNegocio();
  146.             if ($unidad) {
  147.                 $clonedObject->setUnidadNegocio(
  148.                     $this->om->getReference(UnidadNegocio::class, $unidad->getId())
  149.                 );
  150.             }
  151. //            $clonedObject->setUnidadNegocio($user?->getUnidadNegocio());
  152.             $this->om->persist($object);
  153.             $this->om->flush($object);
  154.             $this->admin->create($clonedObject);
  155.             $this->addFlash('sonata_flash_success'$this->trans('clone.valoracion.ok', [], 'flash'));
  156.             return $this->redirect($this->generateUrl('admin_app_valoracion_edit', ['id' => $clonedObject->getId()], UrlGenerator::ABSOLUTE_URL));
  157.         }
  158.         catch (NotFoundHttpException $e)
  159.         {
  160.             $this->addFlash('sonata_flash_error'$e->getMessage());
  161.         }
  162.         return $this->redirect($_SERVER['HTTP_REFERER']);
  163.     }
  164.     public function swapAction()
  165.     {}
  166.     public function inProcessAction(Request $request)
  167.     {
  168.         try
  169.         {
  170.             $object $this->assertObjectExists($requesttrue);
  171.             $tipo TipoOperacionEnum::OPERACION_COMPRA;
  172.             if (!$object) throw new NotFoundHttpException('VALORACION_NOT_EXISTS');
  173.             $relojesVenta $object->getValoracionesRelojesStocks()->count();
  174.             $relojesCompra $object->getValoracionesRelojesSinStocks()->count();
  175.             if($relojesCompra && $relojesVenta)
  176.                 $tipo TipoOperacionEnum::OPERACION_PERMUTA;
  177.             elseif($relojesVenta)
  178.             {
  179.                 $tipo TipoOperacionEnum::OPERACION_VENTA;
  180.             }
  181.             $this->useCaseEnTramitacionValoracion->enTramitacion($object$tipo);
  182.             $object $this->om->getRepository(Valoracion::class)->find($object);
  183.             if(!$object) throw new EnTramitacionValoracionException('exception.valoracion.action_in_process.create_operacion.fail');
  184.             return $this->redirect($this->generateUrl('admin_app_operacion_edit', ['id' => $object->getOperacion()->getId()], UrlGenerator::ABSOLUTE_URL));
  185.         }
  186.         catch (NotFoundHttpException $e)
  187.         {
  188.             $this->addFlash('sonata_flash_error'$e->getMessage());
  189.         }
  190.         catch (EnTramitacionValoracionException $e)
  191.         {
  192.             $this->addFlash('sonata_flash_error'$this->trans($e->getMessage(), [], 'flash'));
  193.         }
  194.         catch (EnTramitacionOperacionException $e)
  195.         {
  196.             $this->addFlash('sonata_flash_error'$this->trans($e->getMessage(), [], 'flash'));
  197.         }
  198.         return $this->redirect($_SERVER['HTTP_REFERER']);
  199.     }
  200.     public function salesManagementAction(Request $request)
  201.     {
  202.         try
  203.         {
  204.             $object $this->assertObjectExists($requesttrue);
  205.             if (!$object) throw new NotFoundHttpException('VALORACION_NOT_EXISTS');
  206.             if($object->getValoracionesRelojesStocks()->count()) throw new EnTramitacionValoracionException('exception.case_use.valoracion.en_tramitacion.operation_not_allowed');
  207.             $this->useCaseEnTramitacionValoracion->enTramitacion($objectTipoOperacionEnum::OPERACION_GESTION);
  208.             $object $this->om->getRepository(Valoracion::class)->find($object);
  209.             if(!$object) throw new EnTramitacionValoracionException('exception.valoracion.action_sales_management.create_operacion.fail');
  210.             return $this->redirect($this->generateUrl('admin_app_operacion_edit', ['id' => $object->getOperacion()->getId()], UrlGenerator::ABSOLUTE_URL));
  211.         }
  212.         catch (NotFoundHttpException $e)
  213.         {
  214.             $this->addFlash('sonata_flash_error'$e->getMessage());
  215.         }
  216.         catch (EnTramitacionValoracionException $e)
  217.         {
  218.             $this->addFlash('sonata_flash_error'$this->trans($e->getMessage(), [], 'flash'));
  219.         }
  220.         return $this->redirect($_SERVER['HTTP_REFERER']);
  221.     }
  222.     public function switchOperacionAction()
  223.     {
  224.     }
  225. }