src/Admin/ContaReceberAdmin.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Admin;
  4. use App\Entity\CentroCusto;
  5. use App\Entity\ContaPagar;
  6. use App\Entity\ContaReceber;
  7. use App\Entity\Empresa;
  8. use App\Entity\FluxoCaixa;
  9. use App\Enums\ContasBancariasEnum;
  10. use App\Enums\StatusContaFinanceiro;
  11. use App\Model\ImageCacheDescriber;
  12. use Sonata\AdminBundle\Admin\AbstractAdmin;
  13. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  14. use Sonata\AdminBundle\Datagrid\ListMapper;
  15. use Sonata\AdminBundle\Form\FormMapper;
  16. use Sonata\AdminBundle\Form\Type\ModelType;
  17. use Sonata\AdminBundle\Show\ShowMapper;
  18. use Sonata\Form\Type\DatePickerType;
  19. use Sonata\Form\Type\DateRangePickerType;
  20. use Sonata\Form\Type\DateTimePickerType;
  21. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  22. use Symfony\Component\Form\Extension\Core\Type\FileType;
  23. use Symfony\Component\Form\Extension\Core\Type\MoneyType;
  24. use Symfony\Component\Security\Core\Security;
  25. use Symfony\Component\Validator\Constraints as Assert;
  26. final class ContaReceberAdmin extends BaseAdmin
  27. {
  28.     protected $datagridValues = [
  29.         '_page'         => 1,
  30.         '_sort_order'   => 'DESC',
  31.         '_sort_by'      => 'vencimento',
  32.         //'_per_page'     => 2000
  33.     ];
  34.     public function prePersist($object)
  35.     {
  36.         ini_set('upload_max_filesize''10M');
  37.         //parent::prePersist($object); // TODO: Change the autogenerated stub
  38.         /** @var ContaReceber $object */
  39.         $object->setCreatedAt(new \DateTime('now'));
  40.         $object->setUpdatedAt(new \DateTime('now'));
  41.         if($object->getNotaFiscalFile()){
  42.             $this->manageFilesUploadPdfNotaFiscal($object);
  43.         }
  44.         if($object->getComprovantePagamentoFile()){
  45.             $this->manageFilesUploadPdfComprovante($object);
  46.         }
  47.         $object->setCadastradoPor($this->getUserLogado());
  48.         return $object;
  49.     }
  50.     public function preUpdate($object)
  51.     {
  52.         ini_set('upload_max_filesize''10M');
  53.         $object->setUpdatedAt(new \DateTime('now'));
  54.         if($object->getNotaFiscalFile()){
  55.             $this->manageFilesUploadPdfNotaFiscal($object);
  56.         }
  57.         if($object->getComprovantePagamentoFile()){
  58.             $this->manageFilesUploadPdfComprovante($object);
  59.         }
  60.         return $object;
  61.     }
  62.     public function postRemove($object)
  63.     {
  64.         parent::postRemove($object); // TODO: Change the autogenerated stub
  65.         if($object->getNotaFiscalFile()){
  66.             if (file_exists($object->getNotaFiscalFile())) {
  67.                 @unlink($object->getNotaFiscal());
  68.             }
  69.         }
  70.         if($object->getComprovantePagamentoFile()){
  71.             if (file_exists($object->getComprovantePagamentoFile())) {
  72.                 @unlink($object->getComprovantePagamento());
  73.             }
  74.         }
  75.     }
  76.     protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
  77.     {
  78.         $container $this->getConfigurationPool()->getContainer();
  79.         $em $container->get('doctrine.orm.entity_manager');
  80.         $centrosCustoChoices = [];
  81.         $centrosCusto $em->getRepository(CentroCusto::class)->custosReceitas();
  82.         
  83.         foreach ($centrosCusto as $cc) {
  84.             $centrosCustoChoices[$cc->getTitulo()] = $cc->getTitulo();
  85.         }
  86.         
  87.         $datagridMapper
  88.         
  89.             ->add('classificacao',null,  array('label'=>'Classificação''field_options' => ['expanded' => false'multiple' => true]))
  90.         
  91.             // ->add('classificacao','doctrine_orm_callback', array('label'=>'Classificação', 'callback'  => array($this, 'filterContaReceberTitulo')), ChoiceType::class,
  92.             //     array('choices' => $centrosCustoChoices))
  93.             
  94.             ->add('status','doctrine_orm_callback',  array(
  95.                 'label' => 'Situação',
  96.                 'callback' => function($queryBuilder$alias$field$value) {
  97.                     if (!$value['value']) {
  98.                         return;
  99.                     }
  100.                     if($value['value']==StatusContaFinanceiro::ABERTO) {
  101.                         
  102.                         $hoje = new \DateTime('now');
  103.                         $hoje $hoje->format('Y-m-d') . ' 00:00:00';
  104.                         
  105.                         $queryBuilder->andWhere($alias.'.pagoEm is null');
  106.                         $queryBuilder->andWhere($alias.'.vencimento > :hoje');
  107.                         $queryBuilder->setParameter('hoje'$hoje);
  108.                     } else if($value['value']==StatusContaFinanceiro::PAGO) {
  109.                         $queryBuilder->andWhere($alias.'.pagoEm is not null');
  110.                     } else if($value['value']==StatusContaFinanceiro::ATRASADO) {
  111.                         $queryBuilder->andWhere($alias.'.pagoEm is null');
  112.                         $queryBuilder->andWhere($alias.'.vencimento < :hoje');
  113.                         $queryBuilder->setParameter('hoje',new \DateTime('now'));
  114.                     }
  115.                     return true;
  116.                 }
  117.             ), ChoiceType::class, array(
  118.                 'choices' => StatusContaFinanceiro::getAssociatedValues()
  119.             ))
  120.             ->add('vencimento''doctrine_orm_datetime_range', ['field_type'=> DateRangePickerType::class])
  121.             ->add('valorBruto')
  122.             ->add('pagoEm''doctrine_orm_datetime_range', ['field_type'=> DateRangePickerType::class])
  123.             ->add('valorLiquido')
  124.             ->add('dataEmissaoNota')
  125.             ->add('numeroNota')
  126.             ->add('cliente','doctrine_orm_callback',[
  127.                 'label'=>'Cliente',
  128.                 'callback'   => array($this'filterBMCliente'),
  129.                 //'field_type' => 'text',
  130.             ])
  131.             ;
  132.     }
  133.     
  134.     public function getFullTextFilter($query$alias$field$value)
  135.     {
  136.         if (!$value['value']) {
  137.             return false;
  138.         }
  139.         
  140.         $query->andWhere($alias.'.pagoEm is null');
  141.         return true;
  142.     }
  143.     
  144.     public function filterContaReceberTitulo($queryBuilder$alias$field$value)
  145.     {
  146.         if (!$value['value']) {
  147.             return;
  148.         }
  149.         $value mb_strtolower($value['value']);
  150.         $queryBuilder
  151.             ->join("$alias.classificacao","cla")
  152.             //->andWhere("UNACCENT(LOWER(cla.titulo)) LIKE UNACCENT(:titulo)" )
  153.             ->andWhere("LOWER(cla.titulo) LIKE :titulo" )
  154.             ->setParameter('titulo'"%$value%");
  155.         return true;
  156.     }
  157.     public function filterBMCliente($queryBuilder$alias$field$value)
  158.     {
  159.         if (!$value['value']) {
  160.             return;
  161.         }
  162.         $value mb_strtolower($value['value']);
  163.         $queryBuilder
  164.             ->join("$alias.cliente","cli")
  165.             //->andWhere("UNACCENT(LOWER(cli.razaoSocial)) LIKE UNACCENT(:nome)" )
  166.             ->andWhere("LOWER(cli.razaoSocial) LIKE :nome" )
  167.             ->setParameter('nome'"%$value%");
  168.         return true;
  169.     }
  170.     protected function configureListFields(ListMapper $listMapper): void
  171.     {
  172.         $this->setTemplate('list''ContaReceber/list.html.twig');
  173.         $listMapper
  174.             ->add('status',null, ['label'=>false,'template'=>'ContaPagar/status_list.html.twig'])
  175.             ->add('cliente',null, ['label'=>'Cliente','template'=>'ContaPagar/nome_cliente.html.twig'])
  176.             ->add('boletimMedicao.os.proposta.numeroFormatado',null, ['label'=>'OS'])
  177.             ->add('vencimento')
  178.             ->add('valorBruto'null, ['label'=>'Valor Bruto','template'=>'Generic/currency_valorBruto_list.html.twig'])
  179.             ->add('valorLiquido'null, ['label'=>'Valor Líquido','template'=>'Generic/currency_valorLiquido.html.twig'])
  180.             ->add('pagoEm')
  181.             ->add('classificacao',null,  array('label'=>'Classificação'))
  182.             ->add('_action'null, [
  183.                 'actions' => [
  184.                     'show' => [],
  185.                     'edit' => [],
  186.                     'delete' => [],
  187.                 ],
  188.             ]);
  189.     }
  190.     protected function configureFormFields(FormMapper $formMapper): void
  191.     {
  192.         /** @var ContaReceber $contaReceber */
  193.         $contaReceber $this->getSubject();
  194.         //$imgReq = !is_null($empresa) && is_null($empresa->getId());
  195.         $imgReq false;
  196.         $fileFieldOptionsNotaFiscal = [
  197.             'data_class' => null,
  198.             'required' => false,
  199.             'label' => 'Nota Fiscal',
  200.             'help' => '',
  201.         ];
  202.         if (!is_null($contaReceber) && $contaReceber->getNotaFiscal() != '') {
  203.             $fileFieldOptionsNotaFiscal['help'] = '<a href="/'.$contaReceber->getNotaFiscal().'" target="_blank" class="btn btn-warning"/><i class="fa fa-eye" aria-hidden="true"></i> Visualizar</a>';
  204.         }
  205.         $fileFieldOptionsComprovantePagamento = [
  206.             'data_class' => null,
  207.             'required' => false,
  208.             'label' => 'Comprovante de Pagamento',
  209.             'help' => '',
  210.         ];
  211.         if (!is_null($contaReceber) && $contaReceber->getComprovantePagamento() != '') {
  212.             $fileFieldOptionsComprovantePagamento['help'] = '<a href="/'.$contaReceber->getComprovantePagamento().'" target="_blank" class="btn btn-warning"/><i class="fa fa-eye" aria-hidden="true"></i> Visualizar</a>';
  213.         }
  214.         $queryBuilderClassificacao $this->getModelManager()
  215.             ->getEntityManager(CentroCusto::class)
  216.             ->createQueryBuilder('cc')
  217.             ->select('cc')
  218.             ->where('cc.classificacao = :classificacao OR cc.classificacao = :classificacao2')
  219.             ->from('App:CentroCusto''cc')
  220.             ->setParameter('classificacao','RECEBIMENTOS')
  221.             ->setParameter('classificacao2','CREDITOS')
  222.             ->orderBy('cc.titulo''ASC')
  223.         ;
  224.         $formMapper
  225.             ->add('boletimMedicao'ModelType::class, [
  226.                 'placeholder' => '-- Selecione --',
  227.                 'label' => 'Boletim de Medição',
  228.                 'property' => 'informacoesCompleta',
  229.                 'required' => false,
  230.                 'expanded' => false,
  231.                 'multiple' => false,
  232.                 'btn_add' => false,
  233.             ])
  234.             ->add('cliente'ModelType::class, [
  235.                 'placeholder' => '-- Selecione --',
  236.                 'label' => 'Cliente',
  237.                 'required' => false,
  238.                 'expanded' => false,
  239.                 'multiple' => false,
  240. //                'disabled' => true,
  241.                 'btn_add' => false,
  242.             ])
  243.             ->add('classificacao'ModelType::class, [
  244.                 'placeholder' => '-- Selecione --',
  245.                 'label' => 'Classificação de Receita',
  246.                 'required' => true,
  247.                 'expanded' => false,
  248.                 'multiple' => false,
  249.                 'btn_add' => false,
  250.                 'query' => $queryBuilderClassificacao
  251.             ])
  252.             ->add('descricao')
  253.             ->add('valorBruto'MoneyType::class, [
  254.                 'label' => 'Valor Bruto',
  255.                 'currency' => 'BRL',
  256.                 'grouping' => true,
  257.                 'required' => true,
  258.                 'attr' => ['class' => 'maskMoney'],
  259.             ])
  260.             ->add('vencimento'DatePickerType::class,['label'=>'Data de vencimento'])
  261.             ->add('pagoEm'DatePickerType::class,['label'=>'Data do pagamento''required'=>false])
  262.             ->add('valorLiquido'MoneyType::class, [
  263.                 'label' => 'Valor Líquido',
  264.                 'currency' => 'BRL',
  265.                 'grouping' => true,
  266.                 'required' => false,
  267.                 'attr' => ['class' => 'maskMoney'],
  268.             ])
  269.             ->add('dataEmissaoNota'DatePickerType::class,['label'=>'Data de emissão nota fiscal''required'=>false])
  270.             ->add('numeroNota'null, ['label'=>'Nº nota fiscal'])
  271.             ->add('notaFiscalFile'FileType::class, [
  272.                 'constraints' => [new Assert\File([
  273.                     'mimeTypes' => [
  274.                         'application/pdf',
  275.                         'application/x-pdf'
  276.                     ],
  277.                     'mimeTypesMessage' => 'O sistema só aceita arquivos no formato .pdf'
  278.                 ])],
  279.                 'label' => 'Nota Fiscal',
  280.                 'help' => $fileFieldOptionsNotaFiscal['help'],
  281.                 'required' => false,
  282.             ])
  283.             ->add('comprovantePagamentoFile'FileType::class, [
  284.                 'constraints' => [new Assert\File([
  285.                     'mimeTypes' => [
  286.                         'application/pdf',
  287.                         'application/x-pdf'
  288.                     ],
  289.                     'mimeTypesMessage' => 'O sistema só aceita arquivos no formato .pdf'
  290.                 ])],
  291.                 'label' => 'Comprovante de pagamento',
  292.                 'help' => $fileFieldOptionsNotaFiscal['help'],
  293.                 'required' => false,
  294.             ])
  295.             
  296.             ->add('contaBancaria'ChoiceType::class, [
  297.                 'label' => 'Conta Bancária da movimentação',
  298.                 'placeholder' => '-- Selecione --',
  299.                 'choices' => ContasBancariasEnum::getAssociatedValues(),
  300.                 'required' => true
  301.             ])
  302.             ;
  303.     }
  304.     protected function configureShowFields(ShowMapper $showMapper): void
  305.     {
  306.         $showMapper
  307.             ->add('id')
  308.             ->add('vencimento')
  309.             ->add('classificacao',null, ['label'=>'Classificação'])
  310.             ->add('valorBruto'null, ['label'=>'Valor bruto''template'=>'Generic/currency_show_valor_bruto.html.twig'])
  311.             ->add('pagoEm'null, ['label'=>'Data do pagamento'])
  312.             ->add('valorLiquido'null, ['label'=>'Valor líquido''template'=>'Generic/currency_show_valor_liquido.html.twig'])
  313.             ->add('dataEmissaoNota'null, ['label'=>'Data de emissão nota fiscal'])
  314.             ->add('numeroNota'null, ['label'=>'Nº nota fiscal'])
  315.             ->add('createdAt'null, ['label'=>'Data de cadastro'])
  316.             ->add('updatedAt'null, ['label'=>'Data da última atualização'])
  317.             ;
  318.     }
  319.     /**
  320.      * @param ContaReceber $obj
  321.      * @return ContaReceber
  322.      */
  323.     private function manageFilesUploadPdfNotaFiscal($obj)
  324.     {
  325.         $file $obj->getNotaFiscalFile();
  326.         $nameFile $filename md5(date('Y-m-d H:i:s:u')).".".$file->getClientOriginalExtension();
  327.         $uploadPath "uploads/notas-fiscais-contas-receber";
  328.         $file->move($uploadPath$nameFile);
  329.         $obj->setNotaFiscalOriginal($uploadPath "/" $filename);
  330.         $obj->setNotaFiscal($uploadPath "/" $filename);
  331.     }
  332.     /**
  333.      * @param ContaReceber $obj
  334.      * @return ContaReceber
  335.      */
  336.     private function manageFilesUploadPdfComprovante($obj)
  337.     {
  338.         $file $obj->getComprovantePagamentoFile();
  339.         $nameFile $filename md5(date('Y-m-d H:i:s:u')).".".$file->getClientOriginalExtension();
  340.         $uploadPath "uploads/comprovantes-contas-receber";
  341.         $file->move($uploadPath$nameFile);
  342.         $obj->setComprovantePagamento($uploadPath "/" $filename);
  343.         $obj->setComprovantePagamentoOriginal($uploadPath "/" $filename);
  344.     }
  345.     public function postPersist($object)
  346.     {
  347.         parent::postPersist($object); // TODO: Change the autogenerated stub
  348.         $this->geraFluxoCaixa($object);
  349.     }
  350.     public function postUpdate($object)
  351.     {
  352.         /** @var ContaPagar $object */
  353.         parent::postUpdate($object); // TODO: Change the autogenerated stub
  354.         $this->geraFluxoCaixa($object);
  355.     }
  356.     private function geraFluxoCaixa($object) {
  357.         // Criar um fluxo de caixa
  358.         $container $this->getConfigurationPool()->getContainer();
  359.         $em $container->get('doctrine.orm.entity_manager');
  360.         if($object->getPagoEm()) {
  361.             $fluxoCaixaConta $em->getRepository(FluxoCaixa::class)->findOneBy(['contaReceber'=>$object]);
  362.             if(!$fluxoCaixaConta instanceof FluxoCaixa){
  363.                 $fluxoCaixa = (new FluxoCaixa())
  364.                     ->setContaReceber($object)
  365.                     ->setTipo('CONTA RECEBER')
  366.                     ->setCadastradoPor($this->getUserLogado())
  367.                     
  368.                     ->setDataExtrato($object->getPagoEm());
  369.                 $em->persist($fluxoCaixa);
  370.                 $em->flush();
  371.             }
  372.         }
  373.     }
  374. }