<?php
/**
* Created by Mediterranean Develup Solutions
* User: jorge.defreitas@develup.solutions
* Date: 04/12/2017
* Time: 9:49
*/
namespace App\MDS\EventsBundle\Controller;
use App\Constants\VacationsConstants;
use App\Entity\Activities;
use App\Entity\Cities;
use App\Entity\Client;
use App\Entity\Configuration;
use App\Entity\Country;
use App\Entity\Destination;
use App\Entity\Ideas;
use App\Entity\ProposalsInvoiceSummary;
use App\Entity\Provinces;
use App\Entity\Regions;
use App\Entity\SettingsCompany;
use App\Entity\SettingsRol;
use App\Entity\Supplier;
use App\Entity\User;
use App\MDS\EventsBundle\Entity\Proposal;
use App\MDS\EventsBundle\Entity\ProposalDiscount;
use App\MDS\EventsBundle\Entity\ProposalFee;
use App\MDS\EventsBundle\Entity\ProposalFeeInvoice;
use App\MDS\EventsBundle\Entity\ProposalInvoice;
use App\MDS\EventsBundle\Entity\ProposalInvoiceDepositControl;
use App\MDS\EventsBundle\Entity\ProposalInvoiceDepositItems;
use App\MDS\EventsBundle\Entity\ProposalPaymentsClient;
use App\MDS\EventsBundle\Entity\ProposalProforma;
use App\MDS\EventsBundle\Entity\ProposalsSupplierServicesAssistantName;
use App\MDS\EventsBundle\Entity\ProposalSupplierServicesCostsClient;
use App\MDS\EventsBundle\Entity\ProposalTracing;
use App\MDS\EventsBundle\Form\ProposalPaymentsClientType;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class ProposalInvoiceController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/*
* ATENCION LAS RAIZ DE @Route POR DEFECTO DEL BUNDLE: EventsBundle ES /events/, NO PONERLO EN LA @Route("")
*
* */
/**
* @Route("/proposal/invoice/{id}", name="proposal_invoice_detector")
*/
public function detectorInvoiceAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$invoiceconsulta= array();
$typeconsulta ='';
$invoice = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
if (!empty($invoice)){
$invoiceconsulta = $invoice;
$typeconsulta = $invoice->getType();
}
// $novatinvoice= $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
// if (!empty($novatinvoice)){
// $invoiceconsulta = $novatinvoice;
// $typeconsulta = 'No Vat Invoice';
// }
// $invoiceconsulta = $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
if (!empty($invoiceconsulta)){
$type = $typeconsulta;
// $number = $invoiceconsulta->getId();
$number = $invoiceconsulta->getNumber();
$date = $invoiceconsulta->getDateAt();
$prefix = $invoiceconsulta->getPrefix();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$data = $this->baseInvoiceProposal($id, $type, $number, $prefix, $date, $request);
$token = $data['token'];
$em->clear();
$invoice_query = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
$invoice_query->setTotalnet($data['totales_neto']);
$invoice_query->setVat(serialize($data['bases_imponibles']));
$invoice_query->setTotal($data['totales']);
$em->persist($invoice_query);
$em->flush();
}else{
return $this->redirectToRoute('proposal_generate_proforma',
array(
'id' => $id
)
);
}
$fees = $em->getRepository(ProposalFeeInvoice::class)->findByProposalId($id);
if (!empty($fees)){ if (!($fees[0]->getToInvoice())){ $fees = null; } } // Si no se debe mostrar en factura se pone a null
$summary = $em->getRepository(ProposalsInvoiceSummary::class)->findOneByProposalId($id);
$summaryInvoice = !empty($summary);
$summaryInvoiceText = !empty($summary) ? $summary->getDescription() : null;
return $this->render('MDS/EventsBundle/services/services-invoice-proposal.html.twig',
array(
'id' => $id,
'type' => $data['type'],
'number' => $data['number'],
'prefix' => $data['prefix'],
'date' => $data['date'],
'token' => $token,
'proposal' => $data['proposal'],
'company' => $data['company'],
'clients' => $data['clients'],
'datasupplier' => $data['datasupplier'],
'totales_neto_antes' => $data['totales_neto_antes'],
'totales_neto' => $data['totales_neto'], // totales neto
'bases_imponibles' => $data['bases_imponibles'],
'totales_antes' => $data['totales_antes'],
'totales' => $data['totales'], // totales generales
'balance' => $data['balance'],
'totales_generales' => $data['totales_generales'],
'currency' => $data['currency'],
'detail_iva' => 'no',
'discounts' => $data['discounts'],
'fees' => $fees,
'summaryInvoice' => $summaryInvoice,
'summaryInvoiceText' => $summaryInvoiceText,
'paymentInvoice' => $data['paymentInvoice'],
'invoiceDesposit' => $data['invoiceDesposit'],
'mcp' => $data['proposal']->getMcp()
)
);
}
/**
* @Route("/proposal/invoice/print/{id}", name="proposal_invoice_detector_print")
*/
public function detectorInvoicePrintAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$invoiceconsulta= array();
$typeconsulta ='';
$invoice= $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
if (!empty($invoice)){
$invoiceconsulta = $invoice;
$typeconsulta = $invoice->getType();
}
// $novatinvoice= $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
// if (!empty($novatinvoice)){
// $invoiceconsulta = $novatinvoice;
// $typeconsulta = 'No Vat Invoice';
// }
// $invoiceconsulta = $em->getRepository(ProposalNoVatInvoice::class)->findOneByProposalId($id);
if (!empty($invoiceconsulta)){
$type = $typeconsulta;
// $number = $invoiceconsulta->getId();
$number = $invoiceconsulta->getNumber();
$date = $invoiceconsulta->getDateAt();
$prefix = $invoiceconsulta->getPrefix();
$data = $this->baseInvoiceProposal($id, $type, $number, $prefix, $date, $request);
$token = $data['token'];
}else{
return $this->redirectToRoute('proposal_generate_proforma',
array(
'id' => $id
)
);
}
$fees = $em->getRepository(ProposalFeeInvoice::class)->findByProposalId($id);
if (!empty($fees)){
$fees[0]->setAmount($fees[0]->getFeeNet());
if (!($fees[0]->getToInvoice())){ $fees = null; } } // Si no se debe mostrar en factura se pone a null
$summary = $em->getRepository(ProposalsInvoiceSummary::class)->findOneByProposalId($id);
$summaryInvoice = !empty($summary);
$summaryInvoiceText = !empty($summary) ? $summary->getDescription() : null;
return $this->render('MDS/EventsBundle/services/services-invoice-print-proposal.html.twig',
array(
'id' => $id,
'type' => $data['type'],
'number' => $data['number'],
'prefix' => $data['prefix'],
'date' => $data['date'],
'token' => $token,
'proposal' => $data['proposal'],
'company' => $data['company'],
'clients' => $data['clients'],
'datasupplier' => $data['datasupplier'],
'totales_neto_antes' => $data['totales_neto_antes'],
'totales_neto' => $data['totales_neto'],
'bases_imponibles' => $data['bases_imponibles'],
'totales_antes' => $data['totales_antes'],
'totales' => $data['totales'],
'balance' => $data['balance'],
'totales_generales' => $data['totales_generales'],
'currency' => $data['currency'],
'detail_iva' => 'no',
'discounts' => $data['discounts'],
'fees' => $fees,
'paymentInvoice' => $data['paymentInvoice'],
'invoiceDesposit' => $data['invoiceDesposit'],
'summaryInvoice' => $summaryInvoice,
'summaryInvoiceText' => $summaryInvoiceText,
)
);
}
/**
* @Route("/proposal/generate/proforma/{id}", name="proposal_generate_proforma")
*/
public function generateProformaAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proforma = $em->getRepository(ProposalProforma::class)->findOneByProposalId($id);
$prefix = "MP".date('ymd')."-";
if (is_null($proforma)){
$proforma_new = new ProposalProforma();
$proforma_new->setProposalId($id);
$proforma_new->setPrefix($prefix);
$proforma_new->setDateAt(new \DateTime("now"));
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$proforma_new->setCreatedId($user_id);
$proforma_new->setUpdatedId($user_id);
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
if($proposal->getStatus() != 'Invoiced'){
$em->persist($proforma_new);
$em->flush();
}
}
return $this->redirectToRoute('proposal_invoice_proforma', array( 'id' => $id ) );
}
/**
* @Route("/proposal/invoice/proforma/{id}", name="proposal_invoice_proforma")
*/
public function detailsProformaAction($id, Request $request)
{
$data = array();
$em = $this->getDoctrine()->getManager();
$paymentsClient = new ProposalPaymentsClient();
$paymentsClient->setProposalId($id);
$form = $this->createProposalPaymentsClientForm($paymentsClient);
$payments = $em->getRepository(ProposalPaymentsClient::class)->findByProposalId($id);
$proforma = $em->getRepository(ProposalProforma::class)->findOneByProposalId($id);
if (!empty($proforma)){
$type = 'Proforma';
$number = $proforma->getId();
$date = $proforma->getDateAt();
$prefix = $proforma->getPrefix();
$data = $this->baseInvoiceProposal($id, $type, $number, $prefix, $date, $request);
$token = $data['token'];
}else{
return $this->redirectToRoute('proposal_generate_proforma',
array(
'id' => $id
)
);
}
$fees = $em->getRepository(ProposalFee::class)->findByProposalId($id);
if (!empty($fees)){ if (!($fees[0]->getToInvoice())){ $fees = null; } } // Si no se debe mostrar en factura se pone a null
return $this->render('MDS/EventsBundle/services/services-proforma-proposal.html.twig',
array(
'id' => $id,
'type' => $data['type'],
'number' => $data['number'],
'prefix' => $data['prefix'],
'date' => $data['date'],
'token' => $token,
'proposal' => $data['proposal'],
'company' => $data['company'],
'clients' => $data['clients'],
'datasupplier' => $data['datasupplier'],
'totales_neto_antes' => $data['totales_neto_antes'],
'totales_neto' => $data['totales_neto'],
'bases_imponibles' => $data['bases_imponibles'],
'totales_antes' => $data['totales_antes'],
'totales' => $data['totales'],
'balance' => $data['balance'],
'totales_generales' => $data['totales_generales'],
'currency' => $data['currency'],
'detail_iva' => 'yes',
'discounts' => $data['discounts'],
'fees' => $fees,
'paymentInvoice' => $data['paymentInvoice'],
'payments' => $payments,
'invoiceDesposit' => $data['invoiceDesposit'],
'form' => $form->createView(),
'mcp' => $data['proposal']->getMcp(),
)
);
}
private function createProposalPaymentsClientForm(ProposalPaymentsClient $entity)
{
$form = $this->createForm(ProposalPaymentsClientType::class, $entity, array(
'action' => $this->generateUrl('proposal_payments_client_add'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/proposal/payments", name="proposal_payments_client_add")
*/
public function createAction(Request $request)
{
$paymentsClient = new ProposalPaymentsClient();
$form = $this->createProposalPaymentsClientForm($paymentsClient);
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$paymentsClient->setCreatedId($user_id);
$paymentsClient->setUpdatedId($user_id);
/* Gestión de eventos en Log */
$user_lastname = $user_logueado->getLastname();
$user_name = $user_logueado->getName();
$user_email = $user_logueado->getEmail();
$user_rol = $user_logueado->getRoles();
$event_url = $request->getPathInfo();
$event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
$proposal = $em->getRepository(Proposal::class)->findOneById($paymentsClient->getProposalId());
if($proposal->getStatus() != 'Invoiced'){
$em->persist($paymentsClient);
$em->flush();
$event = 'the payment was registered';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajepaymentsclient', $successMessage);
}else{
$errorMessage = $this->translator->trans('Error, the proposal is invoiced and cannot be modified');
$this->addFlash('mensajepaymentsclienterror', $errorMessage);
}
return $this->redirectToRoute('proposal_invoice_proforma',
array(
'id' => $paymentsClient->getProposalId()
)
);
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajepaymentsclienterror', $errorMessage);
}
return $this->redirectToRoute('proposal_invoice_proforma',
array(
'id' => $paymentsClient->getProposalId()
)
);
}
/**
* @Route("/proposal/pdfpdf", name="proposal_invoice_proforma_pdf_prueba")
*/
public function pdfAction()
{
$snappy = $this->get('knp_snappy.pdf');
$filename = 'myFirstSnappyPDF';
$url = 'http://mante.develup.solutions';
return new Response(
$snappy->getOutput($url),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
)
);
}
/**
* @Route("/proposal/invoice/proforma/pdf/{id}", name="proposal_invoice_proforma_pdf")
*/
public function detailsProformaPdfActionAction($id, Request $request)
{
$snappy = $this->get('knp_snappy.pdf');
$filename = 'myFirstSnappyPDF';
// use absolute path !
$pageUrl = $this->generateUrl('proposal_invoice_proforma_print_externo', array('id'=>$id), UrlGeneratorInterface::ABSOLUTE_URL);
return new Response(
$snappy->getOutput($pageUrl),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
)
);
}
/**
* @Route("/proposal/invoice/pdf/{id}", name="proposal_invoice_proforma_pdf")
*/
public function detailsInvoicePdfActionAction($id, Request $request)
{
$snappy = $this->get('knp_snappy.pdf');
$filename = 'myFirstSnappyPDF';
// use absolute path !
$pageUrl = $this->generateUrl('proposal_invoice_detector_print_externo', array('id'=>$id), UrlGeneratorInterface::ABSOLUTE_URL);
return new Response(
$snappy->getOutput($pageUrl),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
)
);
}
/**
* @Route("/proposal/invoice/proforma/print/{id}", name="proposal_invoice_proforma_print")
*/
public function detailsProformaPrintAction($id, Request $request)
{
// $token = "";
$em = $this->getDoctrine()->getManager();
$proforma = $em->getRepository(ProposalProforma::class)->findOneByProposalId($id);
if (!empty($proforma)){
$type = 'Proforma';
$number = $proforma->getId();
$date = $proforma->getDateAt();
$prefix = $proforma->getPrefix();
$data = $this->baseInvoiceProposal($id, $type, $number, $prefix, $date, $request);
$token = $data['token'];
}else{
return $this->redirectToRoute('proposal_generate_proforma',
array(
'id' => $id
)
);
}
$fees = $em->getRepository(ProposalFee::class)->findByProposalId($id);
if (!empty($fees)){ if (!($fees[0]->getToInvoice())){ $fees = null; } } // Si no se debe mostrar en factura se pone a null
$summary = $em->getRepository(ProposalsInvoiceSummary::class)->findOneByProposalId($id);
$summaryInvoice = !empty($summary);
$summaryInvoiceText = !empty($summary) ? $summary->getDescription() : null;
return $this->render('MDS/EventsBundle/services/services-invoice-print-proposal.html.twig',
array(
'id' => $id,
'type' => $data['type'],
'number' => $data['number'],
'prefix' => $data['prefix'],
'date' => $data['date'],
'token' => $token,
'proposal' => $data['proposal'],
'company' => $data['company'],
'clients' => $data['clients'],
'datasupplier' => $data['datasupplier'],
'totales_neto_antes' => $data['totales_neto_antes'],
'totales_neto' => $data['totales_neto'],
'bases_imponibles' => $data['bases_imponibles'],
'totales_antes' => $data['totales_antes'],
'totales' => $data['totales'],
'balance' => $data['balance'],
'totales_generales' => $data['totales_generales'],
'currency' => $data['currency'],
'detail_iva' => 'yes',
'discounts' => $data['discounts'],
'fees' => $fees,
'paymentInvoice' => $data['paymentInvoice'],
'summaryInvoice' => $summaryInvoice,
'invoiceDesposit' => $data['invoiceDesposit'],
'summaryInvoiceText' => $summaryInvoiceText,
)
);
}
/**
* @Route("/proposal/generate/invoice/{id}", name="proposal_generate_invoice")
*/
public function generateInvoiceAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$invoiceGenerate = $request->request->get('invoiceGenerate');
$invoice= $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
// d($invoiceGenerate);
// exit();
if (is_null($invoice)){
$proposal= $em->getRepository(Proposal::class)->findOneById($id);
$status = $proposal->getStatus(); // Para controlar que se guarde si no está facturado
$proposal->setStatus('Invoiced');
$invoice_new = new ProposalInvoice();
$invoice_new->setNumber($invoiceGenerate['number']);
$invoice_new->setDateAt(new \DateTime($invoiceGenerate['dateInvoice']));
$invoice_new->setType($invoiceGenerate['type']);
$invoice_new->setProposalId($invoiceGenerate['id']);
$invoice_new->setPrefix('');
// $invoice_new->setDateAt(new \DateTime("now"));
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$invoice_new->setCreatedId($user_id);
$invoice_new->setUpdatedId($user_id);
if($status != 'Invoiced'){
$em->persist($invoice_new);
$em->persist($proposal);
$em->flush();
}
//Envio correo a administracion en el caso que no tenga numero de factura y este como no enviado
if( empty($invoiceGenerate['number'])){
$time = new \DateTime("now");
$agent = $em->getRepository(User::class)->findOneBy(
array(
"id" => $proposal->getAgentId(),
"status" => VacationsConstants::PAYROLL_STAFF_STATUS
)
)
;
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$passGmail = $agent->getPassGmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$setting_rol = $em->getRepository(SettingsRol::class)->findBy(
array(
'weight' => array('2','3'),
'madmin' => '1',
)
);
$mailAdmin = array();
foreach($setting_rol as $settingRol){
$administration = $em->getRepository(User::class)->findByUserrol($settingRol->getId());
foreach($administration as $admin){
$mailAdmin[] = $admin->getEmail();
}
}
$body ='P#'.$proposal->getId().', '.$proposal->getTitle().'<br><br>
<a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/invoice/number/'.$proposal->getId().'">Asignar Número de Factura</a><br>
<a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/edit/'.$proposal->getId().'">Ir al Proposal</a> -
<a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/summary/prices/'.$proposal->getId().'">Ver Resumen</a>
<br><br>
Alerta de solicitud automatizada de número de factura en fecha: '.$time->format('d/m/Y H:i:s').'<br><br>';
$data = array(
'body' => $body,
'firm' => $firmGmail,
);
$mailTodos = array_merge($mailAgent, $mailAdmin);
// EJECUTAR ENVIO DE ALERTA DE VISTO POR CLIENTE
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl') //ssl / tls
->setPort(465) // 465 / 587
->setUsername($agentMail)
->setPassword($passGmail);
// ->setUsername('desarrollo@develup.solutions')
// ->setPassword('Develup2017');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#'.$proposal->getId().', Solicitud de número de factura automatizada')
->setSender($agentMail)
->setFrom($mailAgentSent)
->setReplyTo($mailAgentSent)
->setTo($mailTodos)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
)
;
$mailer->send($message);
}
// Guardo en historico de seguimiento
$textHistory = $this->translator->trans('Billed Proposal');
$history = $this->TracingHistoryOperations($proposal->getId(), $textHistory);
// Verificamos si se debe crear un Fee asociado a la factura
$fee = $em->getRepository(ProposalFee::class)->findOneByProposalId($id);
if (!empty($fee)){
$feeInvoice = new ProposalFeeInvoice();
$feeInvoice->setProposalId($id);
$feeInvoice->setName($fee->getName());
$feeInvoice->setType($fee->getType());
$feeInvoice->setAmount($fee->getAmount());
$feeInvoice->setOpIva($fee->getOpIva());
$feeInvoice->setIva($fee->getIva());
$feeInvoice->setToInvoice($fee->getToInvoice());
$feeInvoice->setInvoiceId($invoice_new->getId());
$feeInvoice->setFeeNet(0);
$feeInvoice->setFeeTotal(0);
$feeInvoice->setCreatedId($user_id);
$feeInvoice->setCreatedAt(new \DateTime("now"));
if($status != 'Invoiced'){
$em->persist($feeInvoice);
$em->flush();
}
}
}
return $this->redirectToRoute('proposal_invoice_detector',
array(
'id' => $invoiceGenerate['id']
)
);
}
/**
* @Route("/proposal/invoice/proforma/payments/delete/{id}", name="proposal_invoice_proforma_payments_delete")
*/
public function deletePaymentsProformaAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$delete= $em->getRepository(ProposalPaymentsClient::class)->findOneById($id);
$proposalId = $delete->getProposalId();
$em->remove($delete);
$em->flush();
return $this->redirectToRoute('proposal_invoice_proforma',
array(
'id' =>$proposalId
)
);
}
private function baseInvoiceProposal($id, $type, $number, $prefix, $date, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal= $em->getRepository(Proposal::class)->findOneById($id);
$services_supplier = $em->getRepository(ProposalSupplierServicesCostsClient::class)->findBy(
array(
'proposalId' => $id,
'serviceIdFather' => '0'
),
array(
'id' => 'ASC'
)
);
$data_iva = array();
$supplier_control = array();
foreach($services_supplier as $servicessupplier){
//// $supplier_control[$servicessupplier->getSupplierId()] = $servicessupplier->getSupplierId();
// $supplier_control[$servicessupplier->getSupplierId()] = array(
// 'id' => $servicessupplier->getSupplierId(),
// 'destinoId' => $servicessupplier->getDestinationId(),
// );
if(!is_null($servicessupplier->getActivityId())){
$supplier_control[$servicessupplier->getActivityId()] = array(
'master' => 'activity',
'id' => $servicessupplier->getActivityId(),
'destinoId' => $servicessupplier->getDestinationId(),
);
}
if(!is_null($servicessupplier->getIdeaId())){
$supplier_control[$servicessupplier->getIdeaId()] = array(
'master' => 'idea',
'id' => $servicessupplier->getIdeaId(),
'destinoId' => $servicessupplier->getDestinationId(),
);
}
if((!is_null($servicessupplier->getSupplierId())) and ($servicessupplier->getIdeaId() == null) and ($servicessupplier->getActivityId() == null)){
$supplier_control[$servicessupplier->getSupplierId()] = array(
'master' => 'supplier',
'id' => $servicessupplier->getSupplierId(),
'destinoId' => $servicessupplier->getDestinationId(),
);
}
}
$data_serviceCat = array();
$data_supplier = array();
$totales_neto_all = 0;
$totales_all = 0;
$currency ="";
$data_service_supplier = array();
foreach($supplier_control as $suppliercontrol){
// $destination = $em->getRepository(Destination::class)->findOneById($suppliercontrol['destinoId']);
$destination = $em->getRepository(Destination::class)->findOneById($suppliercontrol['destinoId']);
$colorlabel= "bg-success-300";
$sqlactivities = "";
if($suppliercontrol['master'] == 'activity'){
$master = "activity";
$sqlactivities = $em->getRepository(Activities::class)->findOneById($suppliercontrol['id']);
// ORDEN DESCENDENTE Y POR SERVICES
$parameters = array(
'proposalId' => $id,
'serviceIdFather' => '0',
'activityId' => $suppliercontrol['id']
);
$dql = 'SELECT p
FROM EventsBundle:ProposalSupplierServicesCostsClient p
WHERE p.proposalId = :proposalId AND p.activityId = :activityId AND p.serviceIdFather = :serviceIdFather
ORDER BY p.serviceCatId, p.rank ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$data_service_supplier = $query->getResult();
}
$sqlideas = "";
if($suppliercontrol['master'] == 'idea'){
$master = "idea";
$sqlideas = $em->getRepository(Ideas::class)->findOneById($suppliercontrol['id']);
// ORDEN DESCENDENTE Y POR SERVICES
$parameters = array(
'proposalId' => $id,
'serviceIdFather' => '0',
'ideaId' => $suppliercontrol['id']
);
$dql = 'SELECT p
FROM EventsBundle:ProposalSupplierServicesCostsClient p
WHERE p.proposalId = :proposalId AND p.ideaId = :ideaId AND p.serviceIdFather = :serviceIdFather
ORDER BY p.serviceCatId, p.rank ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$data_service_supplier = $query->getResult();
}
$sqlsuppliers ="";
if($suppliercontrol['master'] == 'supplier'){
$master = "supplier";
$sqlsuppliers = $em->getRepository(Supplier::class)->findOneById($suppliercontrol['id']);
if(!is_null($sqlsuppliers)){
switch ($sqlsuppliers->getStar()) {
case 1:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i>');
break;
case 2:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
break;
case 3:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
break;
case 4:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
break;
case 5:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i> SUP');
break;
case 6:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i>');
break;
case 7:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i> GL');
break;
case 8:
$sqlsuppliers->setStar('<i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i><i class="icon-star-full2"></i> GL');
break;
}
}
// ORDEN DESCENDENTE Y POR SERVICES
$parameters = array(
'proposalId' => $id,
'serviceIdFather' => '0',
'supplierId' => $suppliercontrol['id']
);
$dql = 'SELECT p
FROM EventsBundle:ProposalSupplierServicesCostsClient p
WHERE p.proposalId = :proposalId AND p.supplierId = :supplierId AND p.ideaId is null AND p.activityId is null AND p.serviceIdFather = :serviceIdFather
ORDER BY p.serviceCatId, p.rank ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$data_service_supplier = $query->getResult();
// Agrupamos asistencias de In-Out por ID de Agente
$new_data_service_supplier = array();
$arregloAcumulador = array();
$acumulador = array();
if ($sqlsuppliers->getCompany() == 'IN OUT TRAVEL & EVENTS') {
// El proveedor es In Out
foreach ($data_service_supplier as $dtsp){
$zNameSrvOrNameUsr = $em->getRepository(ProposalsSupplierServicesAssistantName::class)->findOneByPrpSupSrvId($dtsp->getServiceIdProposal());
if ($dtsp->getServiceCatId() != 15){
$new_data_service_supplier[] = $dtsp;
} else {
// Tenemos una asistencia de In Out
// vamos acumulando precios, over, etc
if ((! array_key_exists($dtsp->getAssistantId().'-'.$dtsp->getPrice(),$arregloAcumulador) ) and (!is_null($dtsp->getAssistantId()))){
// Antes se comprobaba sololo con el id ahora el id del agente y el precio de la asistencia
// $zAg= $em->getRepository(User::class)->findOneById($dtsp->getAssistantId());
// $dtsp->setName('Staff In Out Events: '. $zAg->getName(). ' ' . $zAg->getLastName());
// $dtsp->setUnits(1);
// $arregloAcumulador[$dtsp->getAssistantId()] = $dtsp;
$zAg= $em->getRepository(User::class)->findOneById($dtsp->getAssistantId());
// if($zAg->getId() == 20){
// AQUI TENDRIAMOS LA CONDICION PARA QUE APAREZCA O NO EL NOMBRE EDL AGENTE (FUTURO DESARROLLO)
// }else {
if (empty($zNameSrvOrNameUsr) && !is_null($zAg)) {
$dtsp->setName('Staff In Out Events: ' . $zAg->getName() . ' ' . $zAg->getLastName());
}
// }
$dtsp->setUnits(1);
$arregloAcumulador[$dtsp->getAssistantId().'-'.$dtsp->getPrice()] = $dtsp;
} else {
if ((!is_null($dtsp->getAssistantId()))){
// Antes se comprobaba sololo con el id ahora el id del agente y el precio de la asistencia
// $tempAcum = $arregloAcumulador[$dtsp->getAssistantId()];
$tempAcum = $arregloAcumulador[$dtsp->getAssistantId().'-'.$dtsp->getPrice()];
$tempAcum->setUnits($tempAcum->getUnits() + 1);
//Si el dia de inicio es menor actualizas (para establecer rangos de varios dias)
if ($dtsp->getDateInAt() < $tempAcum->getDateInAt()) {
$tempAcum->setDateInAt($dtsp->getDateInAt());
}
//Si el dia de fin es mayor actualizas (para establecer rangos de varios dias)
if ($dtsp->getDateOutAt() > $tempAcum->getDateOutAt()) {
$tempAcum->setDateOutAt($dtsp->getDateOutAt());
}
// Antes se comprobaba sololo con el id ahora el id del agente y el precio de la asistencia
// $arregloAcumulador[$dtsp->getAssistantId()] = $tempAcum;
$arregloAcumulador[$dtsp->getAssistantId().'-'.$dtsp->getPrice()] = $tempAcum;
} else {
// Tenemos una asistencia de un agente EXTERNO - este agente no se encuentra en el listado de agentes de In Out
if ( array_key_exists($dtsp->getName(),$arregloAcumulador) ){
$tempAcum = $arregloAcumulador[$dtsp->getName()];
$tempAcum->setUnits($tempAcum->getUnits() + 1);
if (empty($zNameSrvOrNameUsr)) {
$tempAcum->setName('Staff In Out Events: ' . $dtsp->getName());
}
//Si el dia de inicio es menor actualizas (para establecer rangos de varios dias)
// if ($dtsp->getDateInAt() < $tempAcum->getDateInAt()) {
// $tempAcum->setDateInAt($dtsp->getDateInAt());
// }
// //Si el dia de fin es mayor actualizas (para establecer rangos de varios dias)
// if ($dtsp->getDateOutAt() > $tempAcum->getDateOutAt()) {
// $tempAcum->setDateOutAt($dtsp->getDateOutAt());
// }
$arregloAcumulador[$dtsp->getName()] = $tempAcum;
} else {
$arregloAcumulador[$dtsp->getName()] = $dtsp;
if (empty($zNameSrvOrNameUsr)) {
$arregloAcumulador[$dtsp->getName()]->setName('Staff In Out Events: ' . $dtsp->getName());
}
}
}
}
}
}
//
foreach ($arregloAcumulador as $aAc){
$new_data_service_supplier[] = $aAc;
}
$data_service_supplier = $new_data_service_supplier;
}
// FIN - Agrupamos asistencias de In-Out por ID de Agente
}
$imagenSmall = null;
$service_supplier_data = array();
$totales_neto ='0';
$totales_iva ='0';
$totales_con_iva ='0';
$totales_paying ='0';
$totales_pago ='0';
$totales_benefit_moneda ='0';
$totales_benefit_porsentaje ='0';
foreach($data_service_supplier as $data_service){
// d($data_service->getId());
//Currency
$currency = $data_service->getCurrency();
if (isset($currency)){$currency="Euro";}
if ($currency == "Euro"){$currency="€";}
if ($currency == "Dolar"){$currency=" $";}
if ($currency == "MXN"){$currency=" MXN";}
$data_service->setCurrency($currency);
$idcat = $data_service->getServiceCatId();
$price = ($data_service->getPrice() == "")? 0 : $data_service->getPrice();
$units = ($data_service->getUnits() == "")? 0 : $data_service->getUnits();
$pax = ($data_service->getPax() == "")? 0 : $data_service->getPax();
$opcommission = $data_service->getOpCommission();
$commission = $data_service->getCommission();
$opover = $data_service->getOpOver();
$over = $data_service->getOver();
$opiva = $data_service->getOpIva();
// $iva = $data_service->getIva();
$iva = empty($data_service->getIva())? 0 : $data_service->getIva();
$dateInAt = $data_service->getDateInAt();
$dateOutAt = $data_service->getDateOutAt();
if (!is_null($dateInAt) and !is_null($dateOutAt)){
$days = $dateInAt->diff($dateOutAt);
$day = $days->days;
}else{
$day = "0";
}
if(!is_null($data_service->getActivityId())){
$name_supplier = $em->getRepository(Activities::class)->findOneById($data_service->getActivityId());
if (empty($name_supplier)){
$namesupplier = '';
}else{
$namesupplier = $name_supplier->getName();
}
}
if(!is_null($data_service->getIdeaId())){
$name_supplier = $em->getRepository(Ideas::class)->findOneById($data_service->getIdeaId());
if (empty($name_supplier)){
$namesupplier = '';
}else{
$namesupplier = $name_supplier->getName();
}
}
if((!is_null($data_service->getSupplierId())) and ($data_service->getIdeaId() == null) and ($data_service->getActivityId() == null) ){
$name_supplier = $em->getRepository(Supplier::class)->findOneById($data_service->getSupplierId());
if (empty($name_supplier)){
$namesupplier = '';
}else{
$namesupplier = $name_supplier->getName();
}
}
// $name_supplier = $em->getRepository(Supplier::class)->findOneById($data_service->getSupplierId());
// $namesupplier = $name_supplier->getName();
if($type == 'No Vat Invoice'){
$iva="0";
$data_service->setIva($iva);
}
$calculos = $this->CalculoTotalesservices($price, $units, $pax, $day, $opcommission, $commission, $opover, $over, $opiva, $iva, $idcat);
$data_service->setPrice($calculos['precio']); //ojo aqui
$service_supplier_data[] = array(
'calculos' => $calculos,
'services_data' => $data_service,
'namesupplier' => $namesupplier
);
$totales_neto += $calculos['total_neto'];
$totales_iva += $calculos['sub_total_iva'];
$totales_con_iva += $calculos['total'];
$totales_paying += $calculos['total_paying'];
$totales_pago += $calculos['total_pago'];
$totales_benefit_moneda += $calculos['benefit_moneda'];
/* base imponible por servicios */
if (empty($base_imponible_service[$idcat])){
$base_imponible_service[$idcat]= 0;
}
$base_imponible_service[$idcat] += $calculos['total_neto'];
$data_serviceCat[$idcat] = array(
'idcat' => $idcat,
'total_neto' => $base_imponible_service[$idcat],
);
/* base impobnible detalles por diferentes Ivas */
if (empty($base_imponible_iva[$iva])){
$base_imponible_iva[$iva]= 0;
}
$base_imponible_iva[$iva] += $calculos['total_neto'];
if (empty($totales_ivas_all[$iva])){
$totales_ivas_all[$iva]= 0;
}
$totales_ivas_all[$iva] += $calculos['sub_total_iva'];
$totales_neto_all += $calculos['total_neto'];
$totales_all += $calculos['total'];
$data_iva[$iva] = array(
'iva' => $iva,
'ivas' => $totales_ivas_all[$iva],
'total_iva' => $base_imponible_iva[$iva]
);
if ($totales_benefit_moneda == '0'){
$totales_benefit_porsentaje = '0';
}else{
if ($totales_neto != 0) {
$totales_benefit_porsentaje = $totales_benefit_moneda / $totales_neto * 100; // arreglado or esteban
} else {
$totales_benefit_porsentaje = 0;
}
}
}
$calculos_totatales = array(
'totales_neto' => $totales_neto,
'totales_iva' => $totales_iva,
'totales_con_iva' => $totales_con_iva,
'totales_paying' => $totales_paying,
'totales_benefit_moneda' => $totales_benefit_moneda,
'totales_benefit_porsentaje' => $totales_benefit_porsentaje
);
$data_supplier[$destination->getTitle()][] = array(
'master' => $master,
'colorlabel' => $colorlabel,
'control' => "1",
'supplier' => $sqlsuppliers,
'idea' => $sqlideas,
'activity' => $sqlactivities,
'image' => $imagenSmall,
'services' => $service_supplier_data,
'totales_services' => $calculos_totatales
);
}
$totales_neto_antes = $totales_neto_all;
$totales_antes = $totales_all;
/*Group Everything*/
if($type == 'Group Everything'){
$data_supplier = array();
$service_supplier_data = array();
$messageitems = $this->translator->trans('Grouped Services');
$data_service = array(
"price" => $totales_neto_antes,
"name" => $messageitems,
"units" => 1,
"iva" => $iva,
"dateInAt" => "2018-4-4",
"dateOutAt" => "2018-4-4",
);
$calculos = array(
"precio" => $totales_neto_antes,
"total_days" => 1,
"sub_total" => $totales_neto_antes,
"sub_total_iva" => 0,
"total_neto" => $totales_neto_antes,
"total_iva" => 0,
"total_paying" => 0,
"total_pago" => 0,
"total_comision" => "0",
"total" => $totales_antes,
"benefit_moneda" => 0,
);
$service_supplier_data[] = array(
'calculos' => $calculos,
'services_data' => $data_service,
'namesupplier' => ""
);
$calculos_totatales = array(
'totales_neto' => $totales_neto_antes,
'totales_iva' => "",
'totales_con_iva' => $totales_antes,
'totales_paying' => "",
'totales_benefit_moneda' => "",
'totales_benefit_porsentaje' => ""
);
$data_supplier[$messageitems][] = array(
'master' => '',
'colorlabel' => '',
'control' => "1",
'supplier' => '',
'idea' => '',
'activity' => '',
'image' => '',
'services' => $service_supplier_data,
'totales_services' => $calculos_totatales
);
}
$data_serviceOut = array(
'idcat' => null,
'total_neto' => $totales_neto_all,
);
// d($data_serviceCat,$data_serviceOut);
array_push ( $data_serviceCat, $data_serviceOut );
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('1');
$parameters = array(
'id' => $proposal->getclientId(),
);
$dql = 'SELECT cl, c.country, re.region, p.name, r.city
FROM App:Client cl
INNER JOIN App:Country c WITH c.id = cl.country
INNER JOIN App:Regions re WITH re.id = cl.region
INNER JOIN App:Provinces p WITH p.id = cl.province
INNER JOIN App:Cities r WITH r.id = cl.population
WHERE cl.id = :id';
$query = $em->createQuery($dql)->setParameters($parameters);
$client = $query->getResult();
// d($data_iva);
$data_invoice = array();
$inv_neto_total = 0;
$inv_total = 0;
$invoice_deposit_control = $em->getRepository(ProposalInvoiceDepositControl::class)->findByProposalId($proposal->getId());
if (!empty($invoice_deposit_control)){
foreach($invoice_deposit_control as $invoicedepositcontrol) {
$data_items_inv = array();
$invoice_deposit_items = $em->getRepository(ProposalInvoiceDepositItems::class)->findByControlId($invoicedepositcontrol->getId());
foreach($invoice_deposit_items as $invoicedeposititems) {
$invamount = $invoicedeposititems->getAmount();
$invamount_iva = $invoicedeposititems->getIva();
$invamount_el_iva = $invamount * ($invamount_iva / 100);
$invamount_con_iva = $invamount * (($invamount_iva / 100) + 1 );
$inv_neto_total += $invamount;
$inv_total += $invamount_con_iva;
if (is_null($invoicedepositcontrol->getNumber())){
$numInvoice = $invoicedepositcontrol->getId();
}else{
$numInvoice = $invoicedepositcontrol->getNumber();
}
$data_items_inv[] = array(
'numInvoice' => $numInvoice,
'name' => $invoicedeposititems->getName(),
'amount' => $invoicedeposititems->getAmount(),
'iva' => $invoicedeposititems->getIva(),
'ivaamount' => $invamount_el_iva,
'total' => $invamount_con_iva,
);
foreach($data_iva as $items_iva) {
if ($items_iva['iva'] == $invoicedeposititems->getIva()){
$new_iva = $items_iva['iva'];
$new_ivas = $items_iva['ivas'] - $invamount_el_iva;
$new_total_iva = $items_iva['total_iva'] - $invoicedeposititems->getAmount();
$new_data_iva = array(
'iva' => $new_iva,
'ivas' => $new_ivas,
'total_iva' => $new_total_iva
);
$data_iva = array_replace($data_iva, array( $new_iva => $new_data_iva ));
}
}
}
$data_invoice[] = array(
'itemsInvoice' => $data_items_inv,
);
}
// d($inv_neto_total, $inv_total);
$totales_neto_all = $totales_neto_all - $inv_neto_total;
$totales_all = $totales_all - $inv_total;
// d($totales_neto_all, $totales_all);
}
// d($data_invoice, $data_iva);
// d($data_iva);
$consulta_discount = $em->getRepository(ProposalDiscount::class)->findByProposalId($id);
$cuantosdiscount = count($consulta_discount);
//
//
// if (!empty($consulta_discount)){
// $descuento =array();
// $name ="";
// $amount = "";
// $type_des = "";
// $iva_discount="";
// $totales_generales="";
// $totales_neto_des = $totales_neto_all;
// $calculo_net_negativo="";
// $total_con_iva_desc="";
//
// foreach($consulta_discount as $consultadiscount) {
//
// $iva = $consultadiscount->getIva() / 100;
// if ($consultadiscount->getType()=="0"){
// $por = $consultadiscount->getAmount() / 100;
// $totales_neto_des = $totales_neto_des / ($por + 1) ;
//
// $name = $consultadiscount->getName();
// $type_des = $consultadiscount->getType();
// $amount = $consultadiscount->getAmount();
// }
//
//
// if ($consultadiscount->getType()=="1"){
// $totales_neto_des = $totales_neto_des - $consultadiscount->getAmount();
// $name = $consultadiscount->getName();
// $type_des = $consultadiscount->getType();
// $amount = $consultadiscount->getAmount();
// }
//
// // resultados en negativo
// $calculo_net_negativo = $totales_neto_des - $totales_neto_all;
//
// $total_desc = "0";
// // resultados para calculos
// $calculo_net = $totales_neto_all - $totales_neto_des;
// if($consultadiscount->getOpIva() =='0'){
// $iva_discount = $calculo_net - ($calculo_net / ($iva + 1));
// $calculo_net_negativo = $calculo_net_negativo + $iva_discount;
// $totales_neto_des = $totales_neto_des + $iva_discount;
// $total_desc = $iva_discount;
// }
// if($consultadiscount->getOpIva() =='1'){
// $iva_discount = $calculo_net * $iva;
// $total_desc = $iva_discount;
// }
//
// if($type == 'No Vat Invoice'){
// $iva_discount = "0";
// }
// // resultados en negativo
//// $calculo_net_negativo = $totales_neto_des - $totales_neto_all;
//
// $total_con_iva_desc = $calculo_net_negativo - $iva_discount;
//
//
// $operacion = $totales_all - $totales_neto_all;
// $totales_generales = $totales_neto_des + $operacion - $total_desc;
//
//
//
// $descuento[] = array(
// 'name' => $name,
// 'type' => $type_des,
// 'amount' => $amount,
// 'iva' => $consultadiscount->getIva(),
// 'totales_neto_des' => $calculo_net_negativo,
// 'total' => $total_con_iva_desc,
// );
//
// $totales_neto_all = $totales_neto_des;
// $totales_all = $totales_generales;
//
// }
// }
$totales_generales="";
$descuento =array();
if (!empty($consulta_discount)){
// d($data_serviceCat);
$quitar_en_todos = 0;
$datos_total_neto_suma = 0;
foreach($data_serviceCat as $dataserviceat) {
$name ="";
$amount = "";
$type_des = "";
$iva_discount="";
$datos_idcat = $dataserviceat['idcat'];
$datos_total_neto = $dataserviceat['total_neto'];
$totales_neto_des = $datos_total_neto;
$datosiva_neto_des = $datos_total_neto;
$calculo_net_negativo="";
$total_con_iva_desc="";
$contarveces = 1;
foreach($consulta_discount as $consultadiscount) {
if($dataserviceat['idcat'] == null){
if($contarveces > 1 ){
$totales_neto_des = $datos_total_neto_suma;
$datosiva_neto_des = $datos_total_neto_suma;
$datos_total_neto = $datos_total_neto_suma;
}else{
if($cuantosdiscount > 1){
$totales_neto_des = $dataserviceat['total_neto'] - $quitar_en_todos;
$datosiva_neto_des = $dataserviceat['total_neto'] - $quitar_en_todos;
$datos_total_neto = $dataserviceat['total_neto'] - $quitar_en_todos;
}
}
$contarveces += 1;
}
if ($dataserviceat['idcat'] == $consultadiscount->getServiceId()){
$iva = $consultadiscount->getIva() / 100;
if ($consultadiscount->getType()=="0"){
$por = $consultadiscount->getAmount() / 100;
// $datosiva_neto_des = $datosiva_neto_des / ($por + 1) ;
$datosiva_neto_des = $datosiva_neto_des - ($datosiva_neto_des * $por) ;
$name = $consultadiscount->getName();
$type_des = $consultadiscount->getType();
$amount = $consultadiscount->getAmount();
}
if ($consultadiscount->getType()=="1"){
$datosiva_neto_des = $datosiva_neto_des - $consultadiscount->getAmount();
$name = $consultadiscount->getName();
$type_des = $consultadiscount->getType();
$amount = $consultadiscount->getAmount();
}
// d($dataserviceat['idcat'], $datos_total_neto);
// resultados en negativo
$calculo_net_negativo = $datosiva_neto_des - $datos_total_neto;
// d($calculo_net_negativo);
$total_desc = "0";
// resultados para calculos
$calculo_net = $datos_total_neto - $datosiva_neto_des;
if($consultadiscount->getOpIva() =='0'){
$iva_discount = $calculo_net - ($calculo_net / ($iva + 1));
$calculo_net_negativo = $calculo_net_negativo + $iva_discount;
$totales_neto_des = $totales_neto_des + $iva_discount;
$total_desc = $iva_discount;
}
if($consultadiscount->getOpIva() =='1'){
$iva_discount = $calculo_net * $iva;
$total_desc = $iva_discount;
}
if($type == 'No Vat Invoice'){
$iva_discount = "0";
}
// if($dataserviceat['idcat'] == null){
$datos_total_neto_suma = $datos_total_neto- abs($calculo_net_negativo);
// }
$quitar_en_todos = $quitar_en_todos + abs($calculo_net_negativo);
// d($datosiva_neto_des, $calculo_net_negativo);
// $datosiva_neto_des = $datosiva_neto_des + $calculo_net_negativo;
// d($quitar_en_todos);
$total_con_iva_desc = $calculo_net_negativo - $iva_discount;
$totales_neto_all = $totales_neto_all - abs($calculo_net_negativo);
$totales_all = $totales_all - abs($total_con_iva_desc);
$descuento[] = array(
'name' => $name,
'type' => $type_des,
'amount' => $amount,
'iva' => $consultadiscount->getIva(),
'iva_amount' => $iva_discount,
'totales_neto_des' => $calculo_net_negativo,
'total' => $total_con_iva_desc,
);
// Nueva actualizacion 17-07-2019 Recalcular Ivas
foreach($data_iva as $items_iva) {
if ($items_iva['iva'] == $consultadiscount->getIva()){
$new_iva = $items_iva['iva'];
$new_ivas = $items_iva['ivas'] - $iva_discount;
$new_total_iva = $items_iva['total_iva'] - $iva_discount;
$new_data_iva = array(
'iva' => $new_iva,
'ivas' => $new_ivas,
'total_iva' => $new_total_iva
);
$data_iva = array_replace($data_iva, array( $new_iva => $new_data_iva ));
}
}
}
}
}
}
// d($descuento);
// d($data_iva);
$payments = $em->getRepository(ProposalPaymentsClient::class)->findByProposalId($id);
$amount_pay = 0;
foreach($payments as $payment) {
$amount_pay = $amount_pay + $payment->getAmount();
}
$totales_all = round($totales_all,2);
$totales_total = $totales_all;
if (!empty($payments)){
$totales_all = $totales_all - $amount_pay;
}
//Si hay uno o varios depositos previos el IVA debe ser calculado en funcion de totales_neto = totales_neto_antes - amount
// $adelanto = 0;
// if(sizeof($data_invoice)!=0){
// foreach ($data_invoice as $pago_previo){
// foreach ($pago_previo as $adel){
// foreach ($adel as $ade){
// $adelanto = $adelanto + $ade['amount'];
// }
// }
// }
// }
//
// if ($adelanto != 0){
// $new_data_iva = null;
// $new_iva = number_format($totales_neto_antes, 2, '.','') - number_format($adelanto, 2, '.','');
// $new_iva = $new_iva * $data_iva['21']['iva'];
// $new_iva =$new_iva/100;
// $new_iva = number_format($new_iva, 2, '.','');
// foreach ($data_iva as $dativ){
// $dativ['ivas'] = $new_iva;
// $new_data_iva['21'] = $dativ;
// }
//
// $data_iva = $new_data_iva;
//
// }
$data = array(
'id' => $id,
'type' => $type,
'number' => $number,
'prefix' => $prefix,
'date' => $date,
'token' => $proposal->getAccessKey(),
'proposal' => $proposal,
'company' => $company,
'clients' => $client,
'datasupplier' => $data_supplier,
'totales_neto_antes' => $totales_neto_antes,
'totales_neto' => $totales_neto_all,
'totales_generales' => $totales_generales,
'bases_imponibles' => $data_iva,
'totales_antes' => $totales_antes,
'totales' => $totales_total,
'balance' => $totales_all,
'currency' => $currency,
'paymentInvoice' => $amount_pay,
'discounts' => $descuento,
'invoiceDesposit' => $data_invoice,
);
// ************************************************ FEE ************************************************************
$fees = $em->getRepository(ProposalFee::class)->findByProposalId($id);
$feesInvoice = $em->getRepository(ProposalFeeInvoice::class)->findByProposalId($id);
if (!empty($feesInvoice)) {
// Fee en factura
// Solo se haran los calculos si el Fee va a la factura, en caso contrario es un fee oculto y ya estará cargado en los servicios
if ($feesInvoice[0]->getToinvoice() == true) {
foreach ($feesInvoice as $feeInv) {
if ($feeInv->getType() == 0) {
// Tenemos un porcentaje en el Fee de la factura, debe calcularse
$feeNet = ($data['totales_neto_antes'] * $feeInv->getAmount()) / 100;
} else {
$feeNet = $feeInv->getAmount();
}
$feeTotal = $feeNet * 1.21; //El fee siempre será al 21%, Esteban Rincón
if ($feeInv->getToInvoice() == true) {
$data['totales_neto'] += $feeNet;
$data['totales'] += $feeTotal;
$data['balance'] += $feeTotal;
if (array_key_exists('21', $data['bases_imponibles'])) {
$data['bases_imponibles']['21']['ivas'] += $feeNet * 0.21;
$data['bases_imponibles']['21']['total_iva'] += $feeNet;
} else {
$data['bases_imponibles']['21']['iva'] = '21';
$data['bases_imponibles']['21']['ivas'] = $feeNet * 0.21;
$data['bases_imponibles']['21']['total_iva'] = $feeNet;
}
}
if ($feeInv->getFeeNet() == 0 or empty($feeInv->getFeeNet())) {
// La asignación solo se hace la primera vez
$feeInv->setFeeNet($feeNet);
$feeInv->setFeeTotal($feeTotal);
$em->persist($feeInv);
$em->flush();
}
}
}
} else {
// Fee en proforma
if (!empty($fees)) {
// Solo se haran los calculos si el Fee va a la factura, en caso contrario es un fee oculto y ya estará cargado en los servicios
if ($fees[0]->getToinvoice() == true) {
foreach ($fees as $fee) {
if ($fee->getType() == 0) {
// Tenemos un porcentaje, debe calcularse
$amount = ($data['totales_neto_antes'] * $fee->getAmount()) / 100;
$fee->setAmount($amount);
}
$fee->setFeeTotal($fee->getAmount() * 1.21); //El fee siempre será al 21%, Esteban Rincón
if ($fee->getToInvoice() == true) {
$data['totales_neto'] += $fee->getAmount();
$data['totales'] += $fee->getFeeTotal();
$data['balance'] += $fee->getFeeTotal();
if (array_key_exists('21', $data['bases_imponibles'])) {
$data['bases_imponibles']['21']['ivas'] += $fee->getAmount() * 0.21;
$data['bases_imponibles']['21']['total_iva'] += $fee->getAmount();
} else {
$data['bases_imponibles']['21']['iva'] = '21';
$data['bases_imponibles']['21']['ivas'] = $fee->getAmount() * 0.21;
$data['bases_imponibles']['21']['total_iva'] = $fee->getAmount();
}
}
}
}
}
}
// ************************************************ FEE ************************************************************
return $data;
}
public function CalculoTotalesservices($price, $units, $pax, $days, $opcommission, $commission, $opover, $over, $opiva, $iva, $idcat)
{
$price = trim($price);
$over = trim($over);
$price = str_replace(",", ".", $price);
$over = str_replace(",", ".", $over);
if (empty($iva)){$iva=0;}
$iva = $iva / 100;
if($opiva =='0'){
$price = $price / ($iva + 1);
}
if(!empty($commission)){
if($opcommission=='0'){
$commission = (100 - $commission) / 100;
$precio_units = $price;
$price = $price * $commission;
}
if($opcommission=='1'){
$commission = ($commission / 100) + 1;
$precio_units = $price * $commission;
}
}else{
$precio_units = $price;
}
//Units
if(empty($units) or $units =="0"){
$units = "1";
}
// Calculo Especial por categoria
//Alojamientos
if($idcat =="1"){
$informativo_days = "si";
$pax = "1";
}
//Transporte
elseif($idcat =="13"){
$informativo_days = "no";
$pax = "1";
// if($days > "1"){
// $days = "2";
// }else{
// $days = "1";
// }
}
//Lounge
elseif($idcat =="10"){
$informativo_days = "no";
$pax = "1";
}
//Guia
elseif($idcat =="8"){
$informativo_days = "no";
$pax = "1";
}
//Asistencia
elseif($idcat =="15"){
$informativo_days = "no";
$days = '0';
}else{
$informativo_days = "no";
}
//Pax
if(empty($pax) or $pax =="0"){
$pax = "1";
}
//Over
if(empty($over)){
$over = "0";
}
if($informativo_days =="no"){
//Days
if(empty($days) or $days =="0"){
$days = "1";
}else{
$days = $days + 1 ;
}
}
$total_items = $price * $units * $pax * $days;
// $total_pdirect = $price * $units * $pax * $days;
$total_over = $over * $units * $pax * $days;
// if($opover=='0'){
// $total_neto = $total_items / $commission - $total_over ;
// $precio_units = $precio_units - $over;
// }
// if($opover=='1'){
// $total_neto = $total_items / $commission + $total_over;
// $precio_units = $precio_units + $over;
// }
if(!empty($commission)){
if($opcommission=='0'){
$total_neto = $total_items / $commission;
}
if($opcommission=='1'){
$total_neto = $total_items * $commission;
}
}else{
$total_neto = $total_items;
}
if($opover=='0'){
$total_neto = $total_neto - $total_over ;
$precio_units = $precio_units - $over;
}
if($opover=='1'){
$total_neto = $total_neto + $total_over;
$precio_units = $precio_units + $over;
}
$total_paying = $total_items * ($iva + 1);
$total_comision ="0";
$total_pago = $total_items;
$total_iva = $total_items * $iva;
$sub_total_iva = $total_neto * $iva;
$total = $total_neto + $sub_total_iva;
$benefit_moneda = $total_neto - $total_items;
$data_calculos = array(
'precio' => $precio_units,
'total_days' => $days,
'sub_total' => $total_items,
'sub_total_iva' => $sub_total_iva,
'total_neto' => $total_neto,
'total_iva' => $total_iva,
'total_paying' => $total_paying,
'total_pago' => $total_pago,
'total_comision' => $total_comision,
'total' => $total,
'benefit_moneda' => $benefit_moneda
);
return $data_calculos;
}
/**
* @Route("/proposal/invoice/number/{id}", name="proposal_invoice_number")
*/
public function InvoiceEmptyNumberAction($id, Request $request) {
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$invoice = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
$client = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$country = $em->getRepository(Country::class)->findOneById($client->getCountry());
$client->setCountry($country->getCountry());
$regions = $em->getRepository(Regions::class)->findOneById($client->getRegion());
$client->setRegion($regions->getRegion());
$province = $em->getRepository(Provinces::class)->findOneById($client->getProvince());
$client->setProvince($province->getName());
$cities = $em->getRepository(Cities::class)->findOneById($client->getPopulation());
$client->setPopulation($cities->getCity());
return $this->render('MDS/EventsBundle/invoice/add-number-invoice.html.twig', array(
'id' => $id,
'invoice' => $invoice,
'mcp' => $proposal->getMcp(),
'token' => $proposal->getAccessKey(),
'proposal' => $proposal,
'client' => $client,
));
}
/**
* @Route("/proposal/invoice/number/updated/{id}", name="proposal_invoice_number_update")
*/
public function InvoiceEmptyNumberupdateAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$invoice = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
$numberinvoice = $request->request->get('invoice')['number'];
$dateAt = new \DateTime($request->request->get('invoice')['dateAt']);
if(!empty($numberinvoice))
{
$invoice->setNumber($numberinvoice);
$invoice->setDateAt($dateAt);
// Envio correo al agente para informar que fue colocado el numero de factura
$time = new \DateTime("now");
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$passGmail = $agent->getPassGmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$body = 'P#'.$proposal->getId().', '.$proposal->getTitle().'<br>
<a href="http://'.$request->server->get('HTTP_HOST').'/events/events/proposal/edit/'.$proposal->getId().'">Ir al Proposal</a> -
<a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/invoice/'.$proposal->getId().'">Ver Factura</a><br>
<br>Alerta de Fatura activada: '.$time->format('d/m/Y H:i:s').'<br><br>';
$data = array(
'body' => $body,
'firm' => $firmGmail,
);
$mailTodos = array_merge($mailAgent);
// EJECUTAR ENVIO DE ALERTA DE VISTO POR CLIENTE
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl') //ssl / tls
->setPort(465) // 465 / 587
->setUsername($agentMail)
->setPassword($passGmail);
// ->setUsername('desarrollo@develup.solutions')
// ->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#'.$proposal->getId().', Alerta de Fatura activada.')
->setSender($agentMail)
->setFrom($mailAgentSent)
->setReplyTo($mailAgentSent)
->setTo($mailTodos)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
)
;
$mailer->send($message);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$proposal->setUpdatedId($user_id);
$em->persist($invoice);
$em->persist($proposal);
$em->flush();
$event = 'The Invoice has been Updated. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeproposaldestinationerror', $errorMessage);
}
return $this->redirectToRoute('proposal_invoice_number',
array(
'id' => $id
)
);
}
/**
* @Route("/proposal/invoice/number/liberate/{id}", name="proposal_invoice_number_liberate")
*/
public function InvoiceEmptyNumberliberateAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$proposal->setStatus('Confirmed');
$em->persist($proposal);
$invoice = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($id);
$em->remove($invoice);
$em->flush();
$event = 'The Invoice has been Liberate. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
$feesInvoice = $em->getRepository(ProposalFeeInvoice::class)->findOneByProposalId($id);
if (!empty($feesInvoice)){
$em->remove($feesInvoice);
$em->flush();
}
return $this->redirectToRoute('proposal_invoice_number',
array(
'id' => $id
)
);
}
// Funcion para insertar historico de seguimiento
// $textHistory = $this->translator->trans('');
// $history = $this->TracingHistoryOperations($proposal->getId(), $text);
private function TracingHistoryOperations($id, $text)
{
$em = $this->getDoctrine()->getManager();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$history = new ProposalTracing();
$history->setDateAt(new \DateTime('now'));
$history->setText($text);
$history->setAgentId($user_id);
$history->setProposalId($id);
$history->setViewed('no');
$history->setCreatedId($user_id);
$history->setUpdatedId($user_id);
$em->persist($history);
$em->flush();
$success = 'success';
return $success;
}
}