src/Admin/ContratoClienteAdmin.php line 20

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Admin;
  4. use App\Enums\StatusContratoEnum;
  5. use Sonata\AdminBundle\Admin\AbstractAdmin;
  6. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  7. use Sonata\AdminBundle\Datagrid\ListMapper;
  8. use Sonata\AdminBundle\Form\FormMapper;
  9. use Sonata\AdminBundle\Form\Type\ModelType;
  10. use Sonata\AdminBundle\Show\ShowMapper;
  11. use Symfony\Component\Validator\Constraints as Assert;
  12. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  13. use Symfony\Component\Form\Extension\Core\Type\FileType;
  14. use Sonata\AdminBundle\Route\RouteCollection;
  15. use Sonata\Form\Validator\ErrorElement;
  16. final class ContratoClienteAdmin extends BaseAdmin
  17. {
  18. /**
  19.  * TODO 
  20.  * Saber se o contrato vincula com uma proposta ou com um cliente;
  21.  * Formatar Contrato;
  22.  */
  23.     protected $datagridValues = [
  24.         '_page'         => 1,
  25.         '_sort_order'   => 'DESC',
  26.         '_sort_by'      => 'createdAt',
  27.         '_per_page'     => 1000
  28.     ];
  29.     protected function configureRoutes(RouteCollection $collection)
  30.     {
  31.         $collection->add('contratoPdf');
  32.     }
  33.     /**
  34.      * @param ErrorElement $errorElement
  35.      * @param ContratoCliente $object
  36.      */
  37.     public function validate(ErrorElement $errorElement$object)
  38.     {
  39.         $container $this->getConfigurationPool()->getContainer();
  40.         $em $container->get('doctrine.orm.entity_manager');
  41.         // // Verifica se o contrato já foi assinado
  42.         // if($object->getStatus()==StatusContratoEnum::ASSINADO) {
  43.         //     $errorElement->with('status')->addViolation('Ops! Este contrato já foi assinado e não pode ser alterada.');
  44.         // }
  45.     }
  46.     protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
  47.     {
  48.         $datagridMapper
  49.             ->add('cliente','doctrine_orm_callback',[
  50.                 'label'=>'Cliente - Razão Social',
  51.                 'callback'   => array($this'filterCliente')
  52.             ])
  53.             ->add('status')
  54.             ;
  55.     }
  56.     public function filterCliente($queryBuilder$alias$field$value)
  57.     {
  58.         if (!$value['value']) {
  59.             return;
  60.         }
  61.         $value mb_strtolower($value['value']);
  62.         $queryBuilder
  63.             ->join("$alias.cliente","cli")
  64.             ->andWhere("LOWER(cli.razaoSocial) LIKE :nome" )
  65.             ->setParameter('nome'"%$value%");
  66.         return true;
  67.     }
  68.     protected function configureListFields(ListMapper $listMapper): void
  69.     {
  70.         $listMapper
  71.             ->add('status',null, ['label'=>'Status do Contrato'])
  72.             ->add('cliente.razaoSocial')
  73.             ->add('proposta'null, ['label'=>'Proposta Comercial'])
  74.             ->add('_action'null, [
  75.                 'actions' => [
  76.                     'show' => [],
  77.                     'edit' => [],
  78.                     'delete' => [],
  79.                     'contratoPdf' => [
  80.                         'template' => 'ContratoCliente/list__action_pdfContrato.html.twig',
  81.                     ]
  82.                 ],
  83.             ]);
  84.     }
  85.     protected function configureFormFields(FormMapper $formMapper): void
  86.     {
  87.         /** @var ContratoCliente $contrato */
  88.         $contrato $this->getSubject();
  89.         
  90.         $fileFieldOptionsContrato = [
  91.             'data_class' => null,
  92.             'required' => false,
  93.             'label' => 'Contrato Assinado',
  94.             'help' => '',
  95.         ];
  96.         if (!is_null($contrato) && $contrato->getContrato() != '') {
  97.             $fileFieldOptionsContrato['help'] = '<a href="/'.$contrato->getContrato().'" target="_blank" class="btn btn-warning"/><i class="fa fa-eye" aria-hidden="true"></i> Visualizar Contrato</a>';
  98.         }
  99.         
  100.         
  101.         $fileFieldOptionsContratoAnexo = [
  102.             'data_class' => null,
  103.             'required' => false,
  104.             'label' => 'Contrato Anexo',
  105.             'help' => '',
  106.         ];
  107.         if (!is_null($contrato) && $contrato->getContratoAnexo() != '') {
  108.             $fileFieldOptionsContratoAnexo['help'] = '<a href="/'.$contrato->getContratoAnexo().'" target="_blank" class="btn btn-primary"/><i class="fa fa-eye" aria-hidden="true"></i> Visualizar Anexo</a>';
  109.         }
  110.         $formMapper
  111.             ->add('cliente'ModelType::class, [
  112.                 'placeholder' => '-- Selecione --',
  113.                 'label' => 'Cliente',
  114.                 'required' => true,
  115.                 'expanded' => false,
  116.                 'multiple' => false,
  117.                 'btn_add'  => false
  118.             ])
  119.             ->add('proposta'ModelType::class, [
  120.                 'placeholder' => '-- Selecione --',
  121.                 'label' => 'Proposta Comercial',
  122.                 'disabled' => false,
  123.                 'required' => true,
  124.                 'expanded' => false,
  125.                 'multiple' => false,
  126.                 'btn_add' => false,
  127.             ])
  128.             ->add('status'ChoiceType::class, [
  129.                 'choices' => StatusContratoEnum::getAssociatedValues(),
  130.             ])
  131.             ->add('contratoFile'FileType::class, [
  132.                 'constraints' => [new Assert\File([
  133.                     'mimeTypes' => [
  134.                         'application/pdf',
  135.                         'application/x-pdf'
  136.                     ],
  137.                     'mimeTypesMessage' => 'O sistema só aceita arquivos no formato .pdf'
  138.                 ])],
  139.                 'label' => 'Contrato Assinado',
  140.                 'help' => $fileFieldOptionsContrato['help'],
  141.                 'required' => false,
  142.             ])
  143.             
  144.             ->add('contratoAnexoFile'FileType::class, [
  145.                 'constraints' => [new Assert\File([
  146.                     'mimeTypes' => [
  147.                         'application/pdf',
  148.                         'application/x-pdf'
  149.                     ],
  150.                     'mimeTypesMessage' => 'O sistema só aceita arquivos no formato .pdf'
  151.                 ])],
  152.                 'label' => 'Contrato Anexo',
  153.                 'help' => $fileFieldOptionsContratoAnexo['help'],
  154.                 'required' => false,
  155.             ])
  156.             ;
  157.     }
  158.     protected function configureShowFields(ShowMapper $showMapper): void
  159.     {
  160.         $showMapper
  161.             ->add('id')
  162.             ;
  163.     }
  164.     public function prePersist($object)
  165.     {
  166.         ini_set('upload_max_filesize''10M');
  167.         $object->setCadastradoPor($this->getUserLogado());
  168.         $object->setCreatedAt(new \DateTime('now'));
  169.         $object->setUpdatedAt(new \DateTime('now'));
  170.         parent::prePersist($object); // TODO: Change the autogenerated stub
  171.         if($object->getContratoFile()){
  172.             $this->manageFilesUploadContrato($object);
  173.         }
  174.         if($object->getContratoAnexoFile()){
  175.             $this->manageFilesUploadContratoAnexo($object);
  176.         }
  177.     }
  178.     public function preUpdate($object)
  179.     {
  180.         ini_set('upload_max_filesize''10M');
  181.         $object->setUpdatedAt(new \DateTime('now'));
  182.         parent::preUpdate($object); // TODO: Change the autogenerated stub
  183.         if($object->getContratoFile()){
  184.             $this->manageFilesUploadContrato($object);
  185.         }
  186.         
  187.         if($object->getContratoAnexoFile()){
  188.             $this->manageFilesUploadContratoAnexo($object);
  189.         }
  190.     }
  191.     public function postRemove($object)
  192.     {
  193.         parent::postRemove($object); // TODO: Change the autogenerated stub
  194.         if($object->getContratoFile()){
  195.             if (file_exists($object->getContratoFile())) {
  196.                 @unlink($object->getContrato());
  197.             }
  198.         }
  199.         
  200.         if($object->getContratoAnexoFile()){
  201.             if (file_exists($object->getContratoAnexoFile())) {
  202.                 @unlink($object->getContratoAnexo());
  203.             }
  204.         }
  205.     }
  206.     /**
  207.      * @param ContratoCliente $obj
  208.      * @return ContratoCliente
  209.      */
  210.     private function manageFilesUploadContrato($obj)
  211.     {
  212.         $file $obj->getContratoFile();
  213.         $nameFile $filename md5(date('Y-m-d H:i:s:u')).".".$file->getClientOriginalExtension();
  214.         $uploadPath "uploads/contratos-clientes";
  215.         $file->move($uploadPath$nameFile);
  216.         $obj->setContrato($uploadPath "/" $filename);
  217.         $obj->setContratoOriginal($uploadPath "/" $filename);
  218.     }
  219.     
  220.     /**
  221.      * @param ContratoCliente $obj
  222.      * @return ContratoCliente
  223.      */
  224.     private function manageFilesUploadContratoAnexo($obj)
  225.     {
  226.         $file $obj->getContratoAnexoFile();
  227.         $nameFile $filename md5(date('Y-m-d H:i:s:u')).".".$file->getClientOriginalExtension();
  228.         $uploadPath "uploads/contratos-clientes-anexo";
  229.         $file->move($uploadPath$nameFile);
  230.         $obj->setContratoAnexo($uploadPath "/" $filename);
  231.         $obj->setContratoAnexoOriginal($uploadPath "/" $filename);
  232.     }
  233. }