<?php
declare(strict_types=1);
namespace App\Controller\Admin;
use App\Entity\UnidadNegocio;
use App\Entity\Usuario;
use App\Entity\Valoracion;
use App\Entity\ValoracionesRelojes;
use App\Enum\TipoOperacionEnum;
use App\Exception\EnTramitacionOperacionException;
use App\Exception\EnTramitacionValoracionException;
use App\UseCase\Valoracion\EnTramitacionUseCase;
use Doctrine\Persistence\ManagerRegistry;
use Sonata\AdminBundle\Bridge\Exporter\AdminExporter;
use Sonata\AdminBundle\Controller\CRUDController;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Generator\UrlGenerator;
use function is_string;
final class ValoracionAdminController extends CRUDController
{
protected $om;
public function __construct(ManagerRegistry $mr,
private AdminExporter $exporter,
private EnTramitacionUseCase $useCaseEnTramitacionValoracion)
{
$this->om = $mr->getManager();
}
public function listAction(Request $request): Response
{
$this->assertObjectExists($request);
$this->admin->checkAccess('list');
$preResponse = $this->preList($request);
if (null !== $preResponse) {
return $preResponse;
}
$listMode = $request->get('_list_mode');
if (is_string($listMode)) {
$this->admin->setListMode($listMode);
}
$datagrid = $this->admin->getDatagrid();
$datagrid->buildPager();
$pager = $datagrid->getPager();
$pager->setPage($request->query->getInt('page', 1));
$formView = $datagrid->getForm()->createView();
// Ejecutamos la query y obtenemos resultados iniciales
$results = iterator_to_array($pager->getCurrentPageResults());
$valoracionIds = array_map(fn($vR) => $vR->getValoracion()->getId(), $results);
$search = $datagrid->getValues()['busqueda']['value'] ?? null;
if ($search && count($valoracionIds) > 0) {
$qb = $this->om->getRepository(ValoracionesRelojes::class)->qbValoracionesSinStockByIdValoracion($valoracionIds);
$pager->setQuery(new ProxyQuery($qb));
}
// set the theme for the current Admin Form
$this->setFormTheme($formView, $this->admin->getFilterTheme());
$template = $this->admin->getTemplateRegistry()->getTemplate('list');
// if ($this->container->has('sonata.admin.admin_exporter')) {
// $exporter = $this->container->get('sonata.admin.admin_exporter');
// \assert($exporter instanceof AdminExporter);
$exportFormats = $this->exporter->getAvailableFormats($this->admin);
// }
return $this->render($template, [
'action' => 'list',
'form' => $formView,
'datagrid' => $datagrid,
'csrf_token' => $this->getCsrfToken('sonata.batch'),
'export_formats' => $exportFormats ?? $this->admin->getExportFormats(),
]);
}
// protected function preList(Request $request): ?Response
// {
// $response = parent::preList($request);
//
// $datagrid = $this->admin->getDatagrid();
// $pager = $datagrid->getPager();
// $query = $pager->getQuery();
//
// // Obtener valor del filtro de búsqueda
// $filters = $datagrid->getValues();
// $search = $filters['busqueda']['value'] ?? null;
//
// if (!$search) return $response;
//
// // Ejecutar query original para sacar IDs de Valoraciones
// $originalResults = $pager->getCurrentPageResults();
// $valoracionIds = array_map(fn($vR) => $vR->getValoracion()->getId(), $originalResults);
//
// if (empty($valoracionIds)) return $response;
//
// // Crear nueva query: todos los ValoracionesRelojes de esas Valoraciones
// $qb = $this->em->createQueryBuilder();
// $qb->select('vr')
// ->from(ValoracionesRelojes::class, 'vr')
// ->innerJoin('vr.valoracion', 'v')
// ->where($qb->expr()->in('v.id', ':valoracionIds'))
// ->setParameter('valoracionIds', $valoracionIds)
// ->orderBy('v.fecha', 'DESC');
//
// // Reemplazar query del Pager
// $pager->setQuery($qb->getQuery());
//
// return $response;
// }
public function editAction(Request $request): Response
{
$responseEdit = parent::editAction($request);
try {
switch ($request->query->get('action'))
{
case 'in-process':
return $this->inProcessAction($request);
case 'sales-management':
return $this->salesManagementAction($request);
default:
return $responseEdit;
}
}
catch (EmptyOperacionException $e)
{
$this->addFlash('error', $this->trans($e->getMessage(), [], 'exception'));
}
return $this->redirect($_SERVER['HTTP_REFERER']);
}
public function statsAction()
{
}
public function historyAction(Request $request): Response
{
return parent::historyAction($request); // TODO: Change the autogenerated stub
}
public function cloneAction(Request $request)
{
try {
$user = $this->getUser()?->getUsuario();
$id = $request->get($this->admin->getIdParameter());
$object = $this->admin->getObject($id);
if (!$object) {
throw new NotFoundHttpException('VALORACION_NOT_EXISTS');
}
$clonedObject = clone $object;
$object->setDuplicados($object->getDuplicados() + 1);
$clonedObject->setClone($object);
$clonedObject->setUsuario($this->om->getReference(Usuario::class, $user->getId()));
$unidad = $clonedObject->getUnidadNegocio();
if ($unidad) {
$clonedObject->setUnidadNegocio(
$this->om->getReference(UnidadNegocio::class, $unidad->getId())
);
}
// $clonedObject->setUnidadNegocio($user?->getUnidadNegocio());
$this->om->persist($object);
$this->om->flush($object);
$this->admin->create($clonedObject);
$this->addFlash('sonata_flash_success', $this->trans('clone.valoracion.ok', [], 'flash'));
return $this->redirect($this->generateUrl('admin_app_valoracion_edit', ['id' => $clonedObject->getId()], UrlGenerator::ABSOLUTE_URL));
}
catch (NotFoundHttpException $e)
{
$this->addFlash('sonata_flash_error', $e->getMessage());
}
return $this->redirect($_SERVER['HTTP_REFERER']);
}
public function swapAction()
{}
public function inProcessAction(Request $request)
{
try
{
$object = $this->assertObjectExists($request, true);
$tipo = TipoOperacionEnum::OPERACION_COMPRA;
if (!$object) throw new NotFoundHttpException('VALORACION_NOT_EXISTS');
$relojesVenta = $object->getValoracionesRelojesStocks()->count();
$relojesCompra = $object->getValoracionesRelojesSinStocks()->count();
if($relojesCompra && $relojesVenta)
$tipo = TipoOperacionEnum::OPERACION_PERMUTA;
elseif($relojesVenta)
{
$tipo = TipoOperacionEnum::OPERACION_VENTA;
}
$this->useCaseEnTramitacionValoracion->enTramitacion($object, $tipo);
$object = $this->om->getRepository(Valoracion::class)->find($object);
if(!$object) throw new EnTramitacionValoracionException('exception.valoracion.action_in_process.create_operacion.fail');
return $this->redirect($this->generateUrl('admin_app_operacion_edit', ['id' => $object->getOperacion()->getId()], UrlGenerator::ABSOLUTE_URL));
}
catch (NotFoundHttpException $e)
{
$this->addFlash('sonata_flash_error', $e->getMessage());
}
catch (EnTramitacionValoracionException $e)
{
$this->addFlash('sonata_flash_error', $this->trans($e->getMessage(), [], 'flash'));
}
catch (EnTramitacionOperacionException $e)
{
$this->addFlash('sonata_flash_error', $this->trans($e->getMessage(), [], 'flash'));
}
return $this->redirect($_SERVER['HTTP_REFERER']);
}
public function salesManagementAction(Request $request)
{
try
{
$object = $this->assertObjectExists($request, true);
if (!$object) throw new NotFoundHttpException('VALORACION_NOT_EXISTS');
if($object->getValoracionesRelojesStocks()->count()) throw new EnTramitacionValoracionException('exception.case_use.valoracion.en_tramitacion.operation_not_allowed');
$this->useCaseEnTramitacionValoracion->enTramitacion($object, TipoOperacionEnum::OPERACION_GESTION);
$object = $this->om->getRepository(Valoracion::class)->find($object);
if(!$object) throw new EnTramitacionValoracionException('exception.valoracion.action_sales_management.create_operacion.fail');
return $this->redirect($this->generateUrl('admin_app_operacion_edit', ['id' => $object->getOperacion()->getId()], UrlGenerator::ABSOLUTE_URL));
}
catch (NotFoundHttpException $e)
{
$this->addFlash('sonata_flash_error', $e->getMessage());
}
catch (EnTramitacionValoracionException $e)
{
$this->addFlash('sonata_flash_error', $this->trans($e->getMessage(), [], 'flash'));
}
return $this->redirect($_SERVER['HTTP_REFERER']);
}
public function switchOperacionAction()
{
}
}