<?php
declare(strict_types=1);
namespace App\Admin;
use App\Entity\CentroCusto;
use App\Entity\ContaPagar;
use App\Entity\ContaReceber;
use App\Entity\Empresa;
use App\Entity\FluxoCaixa;
use App\Enums\ContasBancariasEnum;
use App\Enums\StatusContaFinanceiro;
use App\Model\ImageCacheDescriber;
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\DatePickerType;
use Sonata\Form\Type\DateRangePickerType;
use Sonata\Form\Type\DateTimePickerType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints as Assert;
final class ContaReceberAdmin extends BaseAdmin
{
protected $datagridValues = [
'_page' => 1,
'_sort_order' => 'DESC',
'_sort_by' => 'vencimento',
//'_per_page' => 2000
];
public function prePersist($object)
{
ini_set('upload_max_filesize', '10M');
//parent::prePersist($object); // TODO: Change the autogenerated stub
/** @var ContaReceber $object */
$object->setCreatedAt(new \DateTime('now'));
$object->setUpdatedAt(new \DateTime('now'));
if($object->getNotaFiscalFile()){
$this->manageFilesUploadPdfNotaFiscal($object);
}
if($object->getComprovantePagamentoFile()){
$this->manageFilesUploadPdfComprovante($object);
}
$object->setCadastradoPor($this->getUserLogado());
return $object;
}
public function preUpdate($object)
{
ini_set('upload_max_filesize', '10M');
$object->setUpdatedAt(new \DateTime('now'));
if($object->getNotaFiscalFile()){
$this->manageFilesUploadPdfNotaFiscal($object);
}
if($object->getComprovantePagamentoFile()){
$this->manageFilesUploadPdfComprovante($object);
}
return $object;
}
public function postRemove($object)
{
parent::postRemove($object); // TODO: Change the autogenerated stub
if($object->getNotaFiscalFile()){
if (file_exists($object->getNotaFiscalFile())) {
@unlink($object->getNotaFiscal());
}
}
if($object->getComprovantePagamentoFile()){
if (file_exists($object->getComprovantePagamentoFile())) {
@unlink($object->getComprovantePagamento());
}
}
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$centrosCustoChoices = [];
$centrosCusto = $em->getRepository(CentroCusto::class)->custosReceitas();
foreach ($centrosCusto as $cc) {
$centrosCustoChoices[$cc->getTitulo()] = $cc->getTitulo();
}
$datagridMapper
->add('classificacao',null, array('label'=>'Classificação', 'field_options' => ['expanded' => false, 'multiple' => true]))
// ->add('classificacao','doctrine_orm_callback', array('label'=>'Classificação', 'callback' => array($this, 'filterContaReceberTitulo')), ChoiceType::class,
// array('choices' => $centrosCustoChoices))
->add('status','doctrine_orm_callback', array(
'label' => 'Situação',
'callback' => function($queryBuilder, $alias, $field, $value) {
if (!$value['value']) {
return;
}
if($value['value']==StatusContaFinanceiro::ABERTO) {
$hoje = new \DateTime('now');
$hoje = $hoje->format('Y-m-d') . ' 00:00:00';
$queryBuilder->andWhere($alias.'.pagoEm is null');
$queryBuilder->andWhere($alias.'.vencimento > :hoje');
$queryBuilder->setParameter('hoje', $hoje);
} else if($value['value']==StatusContaFinanceiro::PAGO) {
$queryBuilder->andWhere($alias.'.pagoEm is not null');
} else if($value['value']==StatusContaFinanceiro::ATRASADO) {
$queryBuilder->andWhere($alias.'.pagoEm is null');
$queryBuilder->andWhere($alias.'.vencimento < :hoje');
$queryBuilder->setParameter('hoje',new \DateTime('now'));
}
return true;
}
), ChoiceType::class, array(
'choices' => StatusContaFinanceiro::getAssociatedValues()
))
->add('vencimento', 'doctrine_orm_datetime_range', ['field_type'=> DateRangePickerType::class])
->add('valorBruto')
->add('pagoEm', 'doctrine_orm_datetime_range', ['field_type'=> DateRangePickerType::class])
->add('valorLiquido')
->add('dataEmissaoNota')
->add('numeroNota')
->add('cliente','doctrine_orm_callback',[
'label'=>'Cliente',
'callback' => array($this, 'filterBMCliente'),
//'field_type' => 'text',
])
;
}
public function getFullTextFilter($query, $alias, $field, $value)
{
if (!$value['value']) {
return false;
}
$query->andWhere($alias.'.pagoEm is null');
return true;
}
public function filterContaReceberTitulo($queryBuilder, $alias, $field, $value)
{
if (!$value['value']) {
return;
}
$value = mb_strtolower($value['value']);
$queryBuilder
->join("$alias.classificacao","cla")
//->andWhere("UNACCENT(LOWER(cla.titulo)) LIKE UNACCENT(:titulo)" )
->andWhere("LOWER(cla.titulo) LIKE :titulo" )
->setParameter('titulo', "%$value%");
return true;
}
public function filterBMCliente($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
{
$this->setTemplate('list', 'ContaReceber/list.html.twig');
$listMapper
->add('status',null, ['label'=>false,'template'=>'ContaPagar/status_list.html.twig'])
->add('cliente',null, ['label'=>'Cliente','template'=>'ContaPagar/nome_cliente.html.twig'])
->add('boletimMedicao.os.proposta.numeroFormatado',null, ['label'=>'OS'])
->add('vencimento')
->add('valorBruto', null, ['label'=>'Valor Bruto','template'=>'Generic/currency_valorBruto_list.html.twig'])
->add('valorLiquido', null, ['label'=>'Valor Líquido','template'=>'Generic/currency_valorLiquido.html.twig'])
->add('pagoEm')
->add('classificacao',null, array('label'=>'Classificação'))
->add('_action', null, [
'actions' => [
'show' => [],
'edit' => [],
'delete' => [],
],
]);
}
protected function configureFormFields(FormMapper $formMapper): void
{
/** @var ContaReceber $contaReceber */
$contaReceber = $this->getSubject();
//$imgReq = !is_null($empresa) && is_null($empresa->getId());
$imgReq = false;
$fileFieldOptionsNotaFiscal = [
'data_class' => null,
'required' => false,
'label' => 'Nota Fiscal',
'help' => '',
];
if (!is_null($contaReceber) && $contaReceber->getNotaFiscal() != '') {
$fileFieldOptionsNotaFiscal['help'] = '<a href="/'.$contaReceber->getNotaFiscal().'" target="_blank" class="btn btn-warning"/><i class="fa fa-eye" aria-hidden="true"></i> Visualizar</a>';
}
$fileFieldOptionsComprovantePagamento = [
'data_class' => null,
'required' => false,
'label' => 'Comprovante de Pagamento',
'help' => '',
];
if (!is_null($contaReceber) && $contaReceber->getComprovantePagamento() != '') {
$fileFieldOptionsComprovantePagamento['help'] = '<a href="/'.$contaReceber->getComprovantePagamento().'" target="_blank" class="btn btn-warning"/><i class="fa fa-eye" aria-hidden="true"></i> Visualizar</a>';
}
$queryBuilderClassificacao = $this->getModelManager()
->getEntityManager(CentroCusto::class)
->createQueryBuilder('cc')
->select('cc')
->where('cc.classificacao = :classificacao OR cc.classificacao = :classificacao2')
->from('App:CentroCusto', 'cc')
->setParameter('classificacao','RECEBIMENTOS')
->setParameter('classificacao2','CREDITOS')
->orderBy('cc.titulo', 'ASC')
;
$formMapper
->add('boletimMedicao', ModelType::class, [
'placeholder' => '-- Selecione --',
'label' => 'Boletim de Medição',
'property' => 'informacoesCompleta',
'required' => false,
'expanded' => false,
'multiple' => false,
'btn_add' => false,
])
->add('cliente', ModelType::class, [
'placeholder' => '-- Selecione --',
'label' => 'Cliente',
'required' => false,
'expanded' => false,
'multiple' => false,
// 'disabled' => true,
'btn_add' => false,
])
->add('classificacao', ModelType::class, [
'placeholder' => '-- Selecione --',
'label' => 'Classificação de Receita',
'required' => true,
'expanded' => false,
'multiple' => false,
'btn_add' => false,
'query' => $queryBuilderClassificacao
])
->add('descricao')
->add('valorBruto', MoneyType::class, [
'label' => 'Valor Bruto',
'currency' => 'BRL',
'grouping' => true,
'required' => true,
'attr' => ['class' => 'maskMoney'],
])
->add('vencimento', DatePickerType::class,['label'=>'Data de vencimento'])
->add('pagoEm', DatePickerType::class,['label'=>'Data do pagamento', 'required'=>false])
->add('valorLiquido', MoneyType::class, [
'label' => 'Valor Líquido',
'currency' => 'BRL',
'grouping' => true,
'required' => false,
'attr' => ['class' => 'maskMoney'],
])
->add('dataEmissaoNota', DatePickerType::class,['label'=>'Data de emissão nota fiscal', 'required'=>false])
->add('numeroNota', null, ['label'=>'Nº nota fiscal'])
->add('notaFiscalFile', FileType::class, [
'constraints' => [new Assert\File([
'mimeTypes' => [
'application/pdf',
'application/x-pdf'
],
'mimeTypesMessage' => 'O sistema só aceita arquivos no formato .pdf'
])],
'label' => 'Nota Fiscal',
'help' => $fileFieldOptionsNotaFiscal['help'],
'required' => false,
])
->add('comprovantePagamentoFile', FileType::class, [
'constraints' => [new Assert\File([
'mimeTypes' => [
'application/pdf',
'application/x-pdf'
],
'mimeTypesMessage' => 'O sistema só aceita arquivos no formato .pdf'
])],
'label' => 'Comprovante de pagamento',
'help' => $fileFieldOptionsNotaFiscal['help'],
'required' => false,
])
->add('contaBancaria', ChoiceType::class, [
'label' => 'Conta Bancária da movimentação',
'placeholder' => '-- Selecione --',
'choices' => ContasBancariasEnum::getAssociatedValues(),
'required' => true
])
;
}
protected function configureShowFields(ShowMapper $showMapper): void
{
$showMapper
->add('id')
->add('vencimento')
->add('classificacao',null, ['label'=>'Classificação'])
->add('valorBruto', null, ['label'=>'Valor bruto', 'template'=>'Generic/currency_show_valor_bruto.html.twig'])
->add('pagoEm', null, ['label'=>'Data do pagamento'])
->add('valorLiquido', null, ['label'=>'Valor líquido', 'template'=>'Generic/currency_show_valor_liquido.html.twig'])
->add('dataEmissaoNota', null, ['label'=>'Data de emissão nota fiscal'])
->add('numeroNota', null, ['label'=>'Nº nota fiscal'])
->add('createdAt', null, ['label'=>'Data de cadastro'])
->add('updatedAt', null, ['label'=>'Data da última atualização'])
;
}
/**
* @param ContaReceber $obj
* @return ContaReceber
*/
private function manageFilesUploadPdfNotaFiscal($obj)
{
$file = $obj->getNotaFiscalFile();
$nameFile = $filename = md5(date('Y-m-d H:i:s:u')).".".$file->getClientOriginalExtension();
$uploadPath = "uploads/notas-fiscais-contas-receber";
$file->move($uploadPath, $nameFile);
$obj->setNotaFiscalOriginal($uploadPath . "/" . $filename);
$obj->setNotaFiscal($uploadPath . "/" . $filename);
}
/**
* @param ContaReceber $obj
* @return ContaReceber
*/
private function manageFilesUploadPdfComprovante($obj)
{
$file = $obj->getComprovantePagamentoFile();
$nameFile = $filename = md5(date('Y-m-d H:i:s:u')).".".$file->getClientOriginalExtension();
$uploadPath = "uploads/comprovantes-contas-receber";
$file->move($uploadPath, $nameFile);
$obj->setComprovantePagamento($uploadPath . "/" . $filename);
$obj->setComprovantePagamentoOriginal($uploadPath . "/" . $filename);
}
public function postPersist($object)
{
parent::postPersist($object); // TODO: Change the autogenerated stub
$this->geraFluxoCaixa($object);
}
public function postUpdate($object)
{
/** @var ContaPagar $object */
parent::postUpdate($object); // TODO: Change the autogenerated stub
$this->geraFluxoCaixa($object);
}
private function geraFluxoCaixa($object) {
// Criar um fluxo de caixa
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
if($object->getPagoEm()) {
$fluxoCaixaConta = $em->getRepository(FluxoCaixa::class)->findOneBy(['contaReceber'=>$object]);
if(!$fluxoCaixaConta instanceof FluxoCaixa){
$fluxoCaixa = (new FluxoCaixa())
->setContaReceber($object)
->setTipo('CONTA RECEBER')
->setCadastradoPor($this->getUserLogado())
->setDataExtrato($object->getPagoEm());
$em->persist($fluxoCaixa);
$em->flush();
}
}
}
}