src/Admin/PropostaComercialAdmin.php line 27

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Admin;
  4. use App\Entity\BoletimMedicao;
  5. use App\Entity\Empresa;
  6. use App\Entity\FluxoCaixa;
  7. use App\Entity\OrdemDeServico;
  8. use App\Entity\PropostaComercial;
  9. use App\Entity\ServicoPropostaComercial;
  10. use App\Model\PropostaModel;
  11. use Sonata\AdminBundle\Admin\AbstractAdmin;
  12. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  13. use Sonata\AdminBundle\Datagrid\ListMapper;
  14. use Sonata\AdminBundle\Form\FormMapper;
  15. use Sonata\AdminBundle\Form\Type\ModelType;
  16. use Sonata\AdminBundle\Show\ShowMapper;
  17. use Sonata\Form\Type\CollectionType;
  18. use Sonata\Form\Validator\ErrorElement;
  19. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  20. use Sonata\AdminBundle\Route\RouteCollection;
  21. use Symfony\Component\Form\Extension\Core\Type\MoneyType;
  22. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  23. final class PropostaComercialAdmin extends BaseAdmin
  24. {
  25.     //    protected $datagridValues = [
  26.     //        '_page'         => 1,
  27.     //        '_sort_order'   => 'DESC',
  28.     //        '_sort_by'      => 'ano',
  29.     //        '_per_page'     => 1000
  30.     //    ];
  31.     /**
  32.      * @param ErrorElement $errorElement
  33.      * @param PropostaComercial $object
  34.      */
  35.     public function validate(ErrorElement $errorElement$object)
  36.     {
  37.         $container $this->getConfigurationPool()->getContainer();
  38.         $em $container->get('doctrine.orm.entity_manager');
  39.         $os $em->getRepository(OrdemDeServico::class)->findOneBy(['proposta'=>$object]);
  40.         // Verifica se existe uma OS
  41.         if($os instanceof OrdemDeServico && $object->getServicos()->count() > 0) {
  42.             //$errorElement->with('usuarioAcesso')->addViolation('Ops! Esta proposta já tem ordem de serviço emitida e não pode ser alterada.');
  43.         }
  44.     }
  45.     public function createQuery($context 'list')
  46.     {
  47.         $query parent::createQuery($context);
  48.         $query->addOrderBy($query->getRootAliases()[0].'.anoProposta''DESC');
  49.         $query->addOrderBy($query->getRootAliases()[0].'.numero''DESC');
  50.         
  51.         // Subquery para identificar propostas que não são referenciadas como "propostaOriginal"
  52.         // $query->andWhere(
  53.         //     $query->expr()->isNull($query->getRootAliases()[0] . '.propostaOriginal')
  54.         // );
  55.         
  56.         // Subquery para obter o maior ID de cada histórico
  57.         // $subQuery = $query->getEntityManager()->createQueryBuilder()
  58.         //     ->select('MAX(sub.id)')
  59.         //     ->from('App\Entity\PropostaComercial', 'sub')
  60.         //     ->where('sub.propostaOriginal = ' . $query->getRootAliases()[0] . '.id');
  61.     
  62.         // Filtrar propostas onde haveNewVersion é false ou null
  63.         $query->andWhere(
  64.             $query->expr()->orX(
  65.                 $query->expr()->eq($query->getRootAliases()[0] . '.haveNewVersion'':haveNewVersion'),
  66.                 $query->expr()->isNull($query->getRootAliases()[0] . '.haveNewVersion')
  67.             )
  68.         )->setParameter('haveNewVersion'false);
  69.         return $query;
  70.     }
  71.     public function prePersist($object)
  72.     {
  73.         /** @var PropostaComercial $object */
  74.         parent::prePersist($object); // TODO: Change the autogenerated stub
  75.         $object->setCadastradoPor($this->getUserLogado());
  76.         foreach ($object->getServicos() as $servico) {
  77.             $servico->setProposta($object);
  78.         }
  79.         $object->setCadastradoPor($this->getUserLogado());
  80.         $object->setNumRevisao(1);
  81.         $object->setNumero($this->getProximoNumeroProposta());
  82.         $object->setAnoProposta($this->getAnoProposta());
  83.         // if($object->getNotas() != ''){
  84.         //     $notas = str_replace('<br />', PHP_EOL, $object->getNotas());
  85.         //     $notas = str_replace('<br />', "\n", $object->getNotas());
  86.         //     $object->setNotas($notas);
  87.         // }
  88.     }
  89.     public function preUpdate($object)
  90.     {
  91.         /** @var PropostaComercial $object */
  92.         parent::preUpdate($object); // TODO: Change the autogenerated stub
  93.         foreach ($object->getServicos() as $servico) {
  94.             $servico->setProposta($object);
  95.         }
  96.         //$numRevisao = $object->getNumRevisao() + 1;
  97.         //$object->setNumRevisao($numRevisao);
  98.         // if($object->getNotas() != ''){
  99.         //     $notas = str_replace('<br />', PHP_EOL, $object->getNotas());
  100.         //     $notas = str_replace('<br />', "\n", $object->getNotas());
  101.         //     $object->setNotas($notas);
  102.         // }
  103.     }
  104.     protected function configureRoutes(RouteCollection $collection)
  105.     {
  106.         $collection->add('propostaPdf');
  107.         $collection->add('propostaPdfEmail');
  108.         $collection->add('novaVersaoProposta');
  109.         $collection->add('cloneProposta');
  110.         $collection->add('alteraStatusProposta');
  111.         $collection->add('updatenumeroProposta');
  112.         $collection->add('enviaEmailCliente');
  113.         $collection->add('relatorioEnderecos');
  114.         
  115.         $collection->add('relatorioEquipamentoSemEmpresa');
  116.         $collection->add('relatorioPatrimonioSemEmpresa');
  117.     
  118.     }
  119.     protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
  120.     {
  121.         $datagridMapper
  122.             ->add('numero')
  123.             ->add('anoProposta')
  124.             ->add('destinatarioNome','doctrine_orm_callback',[
  125.                 'label'=>'Nome Destinatário',
  126.                 'callback'   => array($this'filterNomeDestinatario')
  127.             ])
  128.             ->add('cliente','doctrine_orm_callback',[
  129.                 'label'=>'Razão Social',
  130.                 'callback'   => array($this'filterCliente')
  131.             ])
  132.             ->add('servico','doctrine_orm_callback',[
  133.                 'label'=>'Serviço',
  134.                 'callback'   => array($this'filterServico')
  135.             ])
  136.             ->add('servicos','doctrine_orm_callback',[
  137.                 'label'=>'Serviços(interno)',
  138.                 'callback'   => array($this'filterServicos')
  139.             ])
  140.             ->add('status')
  141.         ;
  142.     }
  143.     
  144.     public function filterNomeDestinatario($queryBuilder$alias$field$value)
  145.     {
  146.         if (!$value['value']) {
  147.             return;
  148.         }
  149.         $value mb_strtolower($value['value']);
  150.         $queryBuilder
  151.             //->andWhere("UNACCENT(LOWER($alias.destinatarioNome)) LIKE UNACCENT(:destinatarioNome)" )
  152.             ->andWhere("LOWER($alias.destinatarioNome) LIKE :destinatarioNome" )
  153.             ->setParameter('destinatarioNome'"%$value%");
  154.         return true;
  155.     }
  156.     public function filterServico($queryBuilder$alias$field$value)
  157.     {
  158.         if (!$value['value']) {
  159.             return;
  160.         }
  161.         $value mb_strtolower($value['value']);
  162.         $queryBuilder
  163.             //->andWhere("UNACCENT(LOWER($alias.titulo)) LIKE UNACCENT(:servico)" )
  164.             ->andWhere("LOWER($alias.titulo) LIKE :servico" )
  165.             ->setParameter('servico'"%$value%");
  166.         return true;
  167.     }
  168.     
  169.     public function filterServicos($queryBuilder$alias$field$value)
  170.     {
  171.         if (!$value['value']) {
  172.             return;
  173.         }
  174.         //$value = mb_strtolower($value['value']);
  175.         
  176.         $container $this->getConfigurationPool()->getContainer();
  177.         $em $container->get('doctrine.orm.entity_manager');
  178.         $servicosProposta $em->getRepository(ServicoPropostaComercial::class)->getServicosPropostasPeloTituloDoServico($value['value']);
  179.         
  180.         $idsServicosPropostas = [];
  181.         
  182.         foreach ($servicosProposta as $servicoProposta) {
  183.             //echo $servicoProposta->getServico()->getTitulo() . '<br/>';
  184.             $idsServicosPropostas[] = $servicoProposta->getId();
  185.         }
  186.         
  187.         if(count($idsServicosPropostas)>0){
  188.             //$idsServicosPropostas = implode(',',$idsServicosPropostas);
  189.             $queryBuilder
  190.                 ->join("$alias.servicos","servs")
  191.                 ->where('servs IN (:listServ)')
  192.                 ->setParameter('listServ'$idsServicosPropostas);
  193.         }
  194.         
  195.         return true;
  196.     }
  197.     // Filtro de condomínio por logradouro
  198.     public function filterCliente($queryBuilder$alias$field$value)
  199.     {
  200.         if (!$value['value']) {
  201.             return;
  202.         }
  203.         $value mb_strtolower($value['value']);
  204.         $queryBuilder
  205.             ->join("$alias.cliente","cli")
  206.             //->andWhere("UNACCENT(LOWER(cli.razaoSocial)) LIKE UNACCENT(:nome)" )
  207.             ->andWhere("LOWER(cli.razaoSocial) LIKE :nome" )
  208.             ->setParameter('nome'"%$value%");
  209.         return true;
  210.     }
  211.     protected function configureListFields(ListMapper $listMapper): void
  212.     {
  213.         $listMapper
  214.             ->add('status.cor',null, ['label'=>false,'template'=>'Propostas/status_sinalizador_list.html.twig'])
  215.             ->add('numero',null,['label'=>'Nº. Proposta''template'=>'Propostas/num_list.html.twig'])
  216.             ->add('titulo',null,['label'=>'Serviço'])
  217.             ->add('destinatarioNome'null, ['label'=>'Nome Destinatário'])
  218.             ->add('cliente.razaoSocial'null, ['label'=>'Razão Social'])
  219.             ->add('os'null, ['label'=>'OS''template'=>'Propostas/status_list_os.html.twig'])
  220.             ->add('status'null, ['label'=>'Status''template'=>'Propostas/status_list.html.twig'])
  221.             ->add('_action'null, [
  222.                 'actions' => [
  223.                     //'show' => [],
  224.                     'edit' => [],
  225.                     'delete' => [],
  226.                     'novaVersaoProposta' => [
  227.                         'template' => 'Propostas/list__action_novaVersaoProposta.html.twig',
  228.                     ],
  229.                     'cloneProposta' => [
  230.                         'template' => 'Propostas/list__action_cloneProposta.html.twig',
  231.                     ],
  232.                     'propostaPdf' => [
  233.                         'template' => 'Propostas/list__action_pdfProposta.html.twig',
  234.                     ],
  235.                     'propostaPdfEmail' => [
  236.                         'template' => 'Propostas/list__action_pdfPropostaEmail.html.twig',
  237.                     ]
  238.                 ],
  239.             ]);
  240.     }
  241.     protected function configureFormFields(FormMapper $formMapper): void
  242.     {
  243.         $formMapper
  244.             ->add('numero'null, ['label'=>"Número"'required'=>true])
  245.             ->add('titulo'null, ['label'=>"Título"'required'=>true])
  246.             ->add('cliente'ModelType::class, [
  247.                 'placeholder' => '-- Selecione --',
  248.                 'label' => 'Cliente',
  249.                 'required' => true,
  250.                 'expanded' => false,
  251.                 'multiple' => false,
  252.                 'btn_add'  => false
  253.             ])
  254.             ->add('tipo'ChoiceType::class, [
  255.                 'choices' => [
  256.                     'Selecione' => '',
  257.                     'Comercial' => 'Comercial',
  258.                     'Técnica' => 'Técnica',
  259.                 ]
  260.             ])
  261.             ->add('destinatarioNome'null, ['label'=>"Nome destinatário"])
  262.             ->add('destinatarioEmail'null, ['label'=>"Email destinatário"])
  263.             ->add('destinatarioTelefone'null, ['label'=>"Telefone destinatário"])
  264.             ->add('descricaoEnderecoObra'null, ['label'=>"Endereço da Obra"])
  265.             ->add('cobraART'null, ['label'=>"Cobrar ART"])
  266.             ->add('valorRT'MoneyType::class, [
  267.                 'label' => 'Valor específico para ART',
  268.                 'currency' => 'BRL',
  269.                 'grouping' => true,
  270.                 'required' => false,
  271.                 'help'=>'* Este valor será usado somente nessa proposta.',
  272.                 'attr' => ['class' => 'maskMoney'],
  273.             ])
  274.             ->add('isCobraRelatorioTecnico'null, ['label'=>"Cobrar Relatório Técnico"])
  275.             ->add('percentualRelatorioTecnico'MoneyType::class, [
  276.                 'label' => 'Percentual Relatório Técnico',
  277.                 'currency' => 'BRL',
  278.                 'grouping' => true,
  279.                 'required' => false,
  280.                 'help'=>'* Este valor será usado somente nessa proposta.',
  281.                 'attr' => ['class' => 'usePercentPromocaoValor'],
  282.             ])
  283.             ->add('isCobraImposto'null, ['label'=>"Cobrar Impostos"])
  284.             ->add('percentualImpostos'MoneyType::class, [
  285.                 'label' => 'Percentual Impostos',
  286.                 'currency' => 'BRL',
  287.                 'grouping' => true,
  288.                 'required' => false,
  289.                 'help'=>'* Este valor será usado somente nessa proposta.',
  290.                 'attr' => ['class' => 'usePercentPromocaoValor'],
  291.             ])
  292.             ->add('notas'null, ['label'=>"Notas(4. CONDIÇÕES CONTRATUAIS)"'required'=>false'attr'=>['class'=>'editorHtml']])
  293.             ->add('condicoesPagamento',null,['label'=>'Condições de Pagamento(6. CONDIÇÕES DE PAGAMENTO)''attr'=>['style'=>"height:200px",'class'=>'editorHtml']])
  294.             //->add('destinatarioCargo', null, ['label'=>"Cargo destinatário"])
  295.             ->add('servicos'CollectionType::class, [
  296.                 'label' => 'Serviços Solicitados',
  297.                 'by_reference' => false,
  298.             ], [
  299.                 'edit' => 'inline',
  300.                 'inline' => 'table'
  301.             ])
  302.             ->add('status'ModelType::class, [
  303.                 'placeholder' => '-- Selecione --',
  304.                 'label' => 'Status da Proposta',
  305.                 'required' => false,
  306.                 'expanded' => false,
  307.                 'multiple' => false,
  308.             ])
  309.         ;
  310.     }
  311.     protected function configureShowFields(ShowMapper $showMapper): void
  312.     {
  313.         $showMapper
  314.             ->add('id')
  315.             ->add('destinatarioNome')
  316.             ->add('destinatarioEmail')
  317.             ->add('destinatarioTelefone')
  318.             ->add('destinatarioCargo')
  319.             ->add('numero')
  320.             ->add('tipo')
  321.             ->add('createdAt')
  322.         ;
  323.     }
  324.     public function getProximoNumeroProposta() {
  325.         // Vefifica se tem alguma proposta nesse ano
  326.         $data = new \DateTime('now');
  327.         $container $this->getConfigurationPool()->getContainer();
  328.         $em $container->get('doctrine.orm.entity_manager');
  329.         $proposta $em->getRepository(PropostaComercial::class)->findBy(['anoProposta'=>$data->format('Y')], array('createdAt' => 'DESC'));
  330.         if(count($proposta)>0) {
  331.             // pega o maior numero
  332.             $maiorNumero $proposta[0]->getNumero();
  333.             return $maiorNumero+1;
  334.         } else {
  335.             return 1;
  336.         }
  337.     }
  338.     public function getAnoProposta() {
  339.         // Vefifica se tem alguma proposta nesse ano
  340.         $data = new \DateTime('now');
  341.         $container $this->getConfigurationPool()->getContainer();
  342.         $em $container->get('doctrine.orm.entity_manager');
  343.         $proposta $em->getRepository(PropostaComercial::class)->findBy(['anoProposta'=>$data->format('Y')], array('createdAt' => 'DESC'));
  344.         if(count($proposta)>0) {
  345.             // Pega o maior numero
  346.             return (int)$proposta[0]->getAnoProposta();
  347.         } else {
  348.             return (int)$data->format('Y');
  349.         }
  350.     }
  351.     
  352.     function preRemove($object)
  353.     {
  354.         $container $this->getConfigurationPool()->getContainer();
  355.         $em $container->get('doctrine.orm.entity_manager');
  356.         
  357.         parent::preRemove($object);
  358.         if($object->getPropostaOriginal() instanceof PropostaComercial){
  359.             $object->getPropostaOriginal()->setHaveNewVersion(false);
  360.             $em->flush();
  361.         }
  362.     }
  363. }