<?php
declare(strict_types=1);
namespace App\Admin;
use App\Entity\BoletimMedicao;
use App\Entity\Empresa;
use App\Entity\FluxoCaixa;
use App\Entity\OrdemDeServico;
use App\Entity\PropostaComercial;
use App\Entity\ServicoPropostaComercial;
use App\Model\PropostaModel;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Form\Type\ModelType;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\Form\Type\CollectionType;
use Sonata\Form\Validator\ErrorElement;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
final class PropostaComercialAdmin extends BaseAdmin
{
// protected $datagridValues = [
// '_page' => 1,
// '_sort_order' => 'DESC',
// '_sort_by' => 'ano',
// '_per_page' => 1000
// ];
/**
* @param ErrorElement $errorElement
* @param PropostaComercial $object
*/
public function validate(ErrorElement $errorElement, $object)
{
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$os = $em->getRepository(OrdemDeServico::class)->findOneBy(['proposta'=>$object]);
// Verifica se existe uma OS
if($os instanceof OrdemDeServico && $object->getServicos()->count() > 0) {
//$errorElement->with('usuarioAcesso')->addViolation('Ops! Esta proposta já tem ordem de serviço emitida e não pode ser alterada.');
}
}
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
$query->addOrderBy($query->getRootAliases()[0].'.anoProposta', 'DESC');
$query->addOrderBy($query->getRootAliases()[0].'.numero', 'DESC');
// Subquery para identificar propostas que não são referenciadas como "propostaOriginal"
// $query->andWhere(
// $query->expr()->isNull($query->getRootAliases()[0] . '.propostaOriginal')
// );
// Subquery para obter o maior ID de cada histórico
// $subQuery = $query->getEntityManager()->createQueryBuilder()
// ->select('MAX(sub.id)')
// ->from('App\Entity\PropostaComercial', 'sub')
// ->where('sub.propostaOriginal = ' . $query->getRootAliases()[0] . '.id');
// Filtrar propostas onde haveNewVersion é false ou null
$query->andWhere(
$query->expr()->orX(
$query->expr()->eq($query->getRootAliases()[0] . '.haveNewVersion', ':haveNewVersion'),
$query->expr()->isNull($query->getRootAliases()[0] . '.haveNewVersion')
)
)->setParameter('haveNewVersion', false);
return $query;
}
public function prePersist($object)
{
/** @var PropostaComercial $object */
parent::prePersist($object); // TODO: Change the autogenerated stub
$object->setCadastradoPor($this->getUserLogado());
foreach ($object->getServicos() as $servico) {
$servico->setProposta($object);
}
$object->setCadastradoPor($this->getUserLogado());
$object->setNumRevisao(1);
$object->setNumero($this->getProximoNumeroProposta());
$object->setAnoProposta($this->getAnoProposta());
// if($object->getNotas() != ''){
// $notas = str_replace('<br />', PHP_EOL, $object->getNotas());
// $notas = str_replace('<br />', "\n", $object->getNotas());
// $object->setNotas($notas);
// }
}
public function preUpdate($object)
{
/** @var PropostaComercial $object */
parent::preUpdate($object); // TODO: Change the autogenerated stub
foreach ($object->getServicos() as $servico) {
$servico->setProposta($object);
}
//$numRevisao = $object->getNumRevisao() + 1;
//$object->setNumRevisao($numRevisao);
// if($object->getNotas() != ''){
// $notas = str_replace('<br />', PHP_EOL, $object->getNotas());
// $notas = str_replace('<br />', "\n", $object->getNotas());
// $object->setNotas($notas);
// }
}
protected function configureRoutes(RouteCollection $collection)
{
$collection->add('propostaPdf');
$collection->add('propostaPdfEmail');
$collection->add('novaVersaoProposta');
$collection->add('cloneProposta');
$collection->add('alteraStatusProposta');
$collection->add('updatenumeroProposta');
$collection->add('enviaEmailCliente');
$collection->add('relatorioEnderecos');
$collection->add('relatorioEquipamentoSemEmpresa');
$collection->add('relatorioPatrimonioSemEmpresa');
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
$datagridMapper
->add('numero')
->add('anoProposta')
->add('destinatarioNome','doctrine_orm_callback',[
'label'=>'Nome Destinatário',
'callback' => array($this, 'filterNomeDestinatario')
])
->add('cliente','doctrine_orm_callback',[
'label'=>'Razão Social',
'callback' => array($this, 'filterCliente')
])
->add('servico','doctrine_orm_callback',[
'label'=>'Serviço',
'callback' => array($this, 'filterServico')
])
->add('servicos','doctrine_orm_callback',[
'label'=>'Serviços(interno)',
'callback' => array($this, 'filterServicos')
])
->add('status')
;
}
public function filterNomeDestinatario($queryBuilder, $alias, $field, $value)
{
if (!$value['value']) {
return;
}
$value = mb_strtolower($value['value']);
$queryBuilder
//->andWhere("UNACCENT(LOWER($alias.destinatarioNome)) LIKE UNACCENT(:destinatarioNome)" )
->andWhere("LOWER($alias.destinatarioNome) LIKE :destinatarioNome" )
->setParameter('destinatarioNome', "%$value%");
return true;
}
public function filterServico($queryBuilder, $alias, $field, $value)
{
if (!$value['value']) {
return;
}
$value = mb_strtolower($value['value']);
$queryBuilder
//->andWhere("UNACCENT(LOWER($alias.titulo)) LIKE UNACCENT(:servico)" )
->andWhere("LOWER($alias.titulo) LIKE :servico" )
->setParameter('servico', "%$value%");
return true;
}
public function filterServicos($queryBuilder, $alias, $field, $value)
{
if (!$value['value']) {
return;
}
//$value = mb_strtolower($value['value']);
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$servicosProposta = $em->getRepository(ServicoPropostaComercial::class)->getServicosPropostasPeloTituloDoServico($value['value']);
$idsServicosPropostas = [];
foreach ($servicosProposta as $servicoProposta) {
//echo $servicoProposta->getServico()->getTitulo() . '<br/>';
$idsServicosPropostas[] = $servicoProposta->getId();
}
if(count($idsServicosPropostas)>0){
//$idsServicosPropostas = implode(',',$idsServicosPropostas);
$queryBuilder
->join("$alias.servicos","servs")
->where('servs IN (:listServ)')
->setParameter('listServ', $idsServicosPropostas);
}
return true;
}
// Filtro de condomínio por logradouro
public function filterCliente($queryBuilder, $alias, $field, $value)
{
if (!$value['value']) {
return;
}
$value = mb_strtolower($value['value']);
$queryBuilder
->join("$alias.cliente","cli")
//->andWhere("UNACCENT(LOWER(cli.razaoSocial)) LIKE UNACCENT(:nome)" )
->andWhere("LOWER(cli.razaoSocial) LIKE :nome" )
->setParameter('nome', "%$value%");
return true;
}
protected function configureListFields(ListMapper $listMapper): void
{
$listMapper
->add('status.cor',null, ['label'=>false,'template'=>'Propostas/status_sinalizador_list.html.twig'])
->add('numero',null,['label'=>'Nº. Proposta', 'template'=>'Propostas/num_list.html.twig'])
->add('titulo',null,['label'=>'Serviço'])
->add('destinatarioNome', null, ['label'=>'Nome Destinatário'])
->add('cliente.razaoSocial', null, ['label'=>'Razão Social'])
->add('os', null, ['label'=>'OS', 'template'=>'Propostas/status_list_os.html.twig'])
->add('status', null, ['label'=>'Status', 'template'=>'Propostas/status_list.html.twig'])
->add('_action', null, [
'actions' => [
//'show' => [],
'edit' => [],
'delete' => [],
'novaVersaoProposta' => [
'template' => 'Propostas/list__action_novaVersaoProposta.html.twig',
],
'cloneProposta' => [
'template' => 'Propostas/list__action_cloneProposta.html.twig',
],
'propostaPdf' => [
'template' => 'Propostas/list__action_pdfProposta.html.twig',
],
'propostaPdfEmail' => [
'template' => 'Propostas/list__action_pdfPropostaEmail.html.twig',
]
],
]);
}
protected function configureFormFields(FormMapper $formMapper): void
{
$formMapper
->add('numero', null, ['label'=>"Número", 'required'=>true])
->add('titulo', null, ['label'=>"Título", 'required'=>true])
->add('cliente', ModelType::class, [
'placeholder' => '-- Selecione --',
'label' => 'Cliente',
'required' => true,
'expanded' => false,
'multiple' => false,
'btn_add' => false
])
->add('tipo', ChoiceType::class, [
'choices' => [
'Selecione' => '',
'Comercial' => 'Comercial',
'Técnica' => 'Técnica',
]
])
->add('destinatarioNome', null, ['label'=>"Nome destinatário"])
->add('destinatarioEmail', null, ['label'=>"Email destinatário"])
->add('destinatarioTelefone', null, ['label'=>"Telefone destinatário"])
->add('descricaoEnderecoObra', null, ['label'=>"Endereço da Obra"])
->add('cobraART', null, ['label'=>"Cobrar ART"])
->add('valorRT', MoneyType::class, [
'label' => 'Valor específico para ART',
'currency' => 'BRL',
'grouping' => true,
'required' => false,
'help'=>'* Este valor será usado somente nessa proposta.',
'attr' => ['class' => 'maskMoney'],
])
->add('isCobraRelatorioTecnico', null, ['label'=>"Cobrar Relatório Técnico"])
->add('percentualRelatorioTecnico', MoneyType::class, [
'label' => 'Percentual Relatório Técnico',
'currency' => 'BRL',
'grouping' => true,
'required' => false,
'help'=>'* Este valor será usado somente nessa proposta.',
'attr' => ['class' => 'usePercentPromocaoValor'],
])
->add('isCobraImposto', null, ['label'=>"Cobrar Impostos"])
->add('percentualImpostos', MoneyType::class, [
'label' => 'Percentual Impostos',
'currency' => 'BRL',
'grouping' => true,
'required' => false,
'help'=>'* Este valor será usado somente nessa proposta.',
'attr' => ['class' => 'usePercentPromocaoValor'],
])
->add('notas', null, ['label'=>"Notas(4. CONDIÇÕES CONTRATUAIS)", 'required'=>false, 'attr'=>['class'=>'editorHtml']])
->add('condicoesPagamento',null,['label'=>'Condições de Pagamento(6. CONDIÇÕES DE PAGAMENTO)', 'attr'=>['style'=>"height:200px",'class'=>'editorHtml']])
//->add('destinatarioCargo', null, ['label'=>"Cargo destinatário"])
->add('servicos', CollectionType::class, [
'label' => 'Serviços Solicitados',
'by_reference' => false,
], [
'edit' => 'inline',
'inline' => 'table'
])
->add('status', ModelType::class, [
'placeholder' => '-- Selecione --',
'label' => 'Status da Proposta',
'required' => false,
'expanded' => false,
'multiple' => false,
])
;
}
protected function configureShowFields(ShowMapper $showMapper): void
{
$showMapper
->add('id')
->add('destinatarioNome')
->add('destinatarioEmail')
->add('destinatarioTelefone')
->add('destinatarioCargo')
->add('numero')
->add('tipo')
->add('createdAt')
;
}
public function getProximoNumeroProposta() {
// Vefifica se tem alguma proposta nesse ano
$data = new \DateTime('now');
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$proposta = $em->getRepository(PropostaComercial::class)->findBy(['anoProposta'=>$data->format('Y')], array('createdAt' => 'DESC'));
if(count($proposta)>0) {
// pega o maior numero
$maiorNumero = $proposta[0]->getNumero();
return $maiorNumero+1;
} else {
return 1;
}
}
public function getAnoProposta() {
// Vefifica se tem alguma proposta nesse ano
$data = new \DateTime('now');
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$proposta = $em->getRepository(PropostaComercial::class)->findBy(['anoProposta'=>$data->format('Y')], array('createdAt' => 'DESC'));
if(count($proposta)>0) {
// Pega o maior numero
return (int)$proposta[0]->getAnoProposta();
} else {
return (int)$data->format('Y');
}
}
function preRemove($object)
{
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
parent::preRemove($object);
if($object->getPropostaOriginal() instanceof PropostaComercial){
$object->getPropostaOriginal()->setHaveNewVersion(false);
$em->flush();
}
}
}