<?php
namespace App\MDS\AvexpressBundle\Controller;
use App\Entity\Cities;
use App\Entity\Client;
use App\Entity\Configuration;
use App\Entity\Country;
use App\Entity\Destination;
use App\Entity\Regions;
use App\Entity\SettingsCompany;
use App\Entity\User;
use App\Entity\HtFile;
use App\MDS\AvexpressBundle\Entity\AveBenefitsSupplier;
use App\MDS\AvexpressBundle\Entity\AveBriefings;
use App\MDS\AvexpressBundle\Entity\AveBudgetPending;
use App\MDS\GreenPatioBundle\Entity\Reservation;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use DateTime;
use App\MDS\AvexpressBundle\Entity\AveFiles;
use App\MDS\AvexpressBundle\Entity\AveBudgetToProforma;
use App\MDS\AvexpressBundle\Entity\AveDocInvoice;
use App\MDS\AvexpressBundle\Entity\AveDocInvoiceItems;
use App\MDS\AvexpressBundle\Entity\AveDocInvoiceRec;
use App\MDS\AvexpressBundle\Entity\AveDocInvoiceRecItems;
use App\MDS\AvexpressBundle\Entity\AveDocProforma;
use App\MDS\AvexpressBundle\Entity\AveDocProformaItems;
use App\MDS\AvexpressBundle\Entity\AvePaymentsClient;
use App\MDS\AvexpressBundle\Entity\AveProduct;
use App\MDS\AvexpressBundle\Entity\AveProductFile;
use App\MDS\AvexpressBundle\Entity\AveServices;
use App\MDS\DevelupBundle\Entity\MdvTelegramUser;
use App\MDS\EventsBundle\Entity\Proposal;
use App\MDS\EventsBundle\Entity\ProposalAgents;
use App\MDS\EventsBundle\Entity\ProposalInvoice;
use App\MDS\EventsBundle\Entity\ProposalSupplierControl;
use App\MDS\EventsBundle\Entity\ProposalSupplierServices;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Contracts\Translation\TranslatorInterface;
class FilesController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/**
* @Route("/fileadd/", name="ave_add_file")
* Agregar un expediente
*/
public function addFileAction( Request $request)
{
$em = $this->getDoctrine()->getManager();
$clients = $em->getRepository(Client::class)->findAll();
$destinations = $em->getRepository(Destination::class)->findAll();
$aveFiles = $em->getRepository(AveFiles::class)->findAll();
$id =0;
if (empty($aveFiles)){
$id ++;
} else {
$lastElem = end($aveFiles);
$id = $lastElem->getId() + 1;
}
return $this->render('MDS/AvexpressBundle/Avexpress/add-files.html.twig',
array(
'id' => $id,
'clients' => $clients,
'destinations' => $destinations,
'clientId' => 0,
));
}
/**
* @Route("/filelist/", name="ave_list_file")
* Listar expedientes
*/
public function listFileAction( Request $request)
{
$em = $this->getDoctrine()->getManager();
$idgroup = null;
$parameters = array( 'status' => 'Deleted' );
$dql = 'SELECT i
FROM AvexpressBundle:AveFiles i
WHERE i.status != :status
ORDER BY i.dateStart DESC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$ref = array();
$reservas = $query->getResult();
foreach ($reservas as $res) {
$client = $em->getRepository(Client::class)->findOneById($res->getClient());
if (!empty($client)) { $res->setClient($client->getName()); } else { $res->setClient(null); }
if (!empty($res->getDateStart()) and !empty($res->getDateEnd())) {
$ref[$res->getId()] = '#' . ($res->getDateStart())->format('ymd') . ($res->getDateEnd())->format('ymd');
} else {
$ref[$res->getId()] = '#' . '000000' . '000000';
}
}
$reservasZero = array();
foreach ($reservas as $res) {
$reservasZero[] = array(
'dateStart' => $res->getDateStart(),
'dateEnd' => $res->getDateEnd(),
'id' => $res->getId(),
'title' => $res->getTitle(),
'client' => $res->getClient(),
'createdId' => $res->getCreatedId(),
'ref' => $ref[$res->getId()],
'reservation' => $res->getReservation(),
);
}
$reservas = $reservasZero;
return $this->render('MDS/AvexpressBundle/Avexpress/list-files.html.twig',
array(
'groups' => null,
'listofdeletedfiles' => false,
'reservations' => $reservas
)
);
}
/**
* @Route("/filesave/", name="ave_save_file")
* Guardar un expediente nuevo
*/
public function saveFileAction( Request $request)
{
$em = $this->getDoctrine()->getManager();
$newRequest = $request->request->get('avexpress');
if (empty($newRequest['title'])){ return $this->redirectToRoute('ave_add_file'); }
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$newFile = new AveFiles();
$newFile->setTitle($newRequest['title']);
$newFile->setClient($newRequest['client']);
if (!empty($newRequest['idProposal'])){
$newFile->setIdProposal($newRequest['idProposal']);
} else {
$newFile->setIdProposal(null);
}
$newFile->setStatus($newRequest['status']);
$newFile->setAdvancePayment($newRequest['advancePayment']);
$newFile->setDescription($newRequest['description']);
if (empty($newRequest['dateStart'])){
$newFile->setDateStart(new \DateTime("now"));
} else {
$newFile->setDateStart(new \DateTime($newRequest['dateStart']));}
if (empty($newRequest['dateEnd'])){
$newFile->setDateEnd(new \DateTime("now"));
} else {
$newFile->setDateEnd(new \DateTime($newRequest['dateEnd']));}
if (!empty($newRequest['destination'])){
$newFile->setDestinoId($newRequest['destination']);
}
$newFile->setCreatedId($user_id);
$newFile->setUpdatedId($user_id);
$newFile->setCreatedAt(new \DateTime("now"));
$newFile->setUpdatedAt(new \DateTime("now"));
$em->persist($newFile);
$em->flush();
$clients = $em->getRepository(Client::class)->findAll();
$products = $em->getRepository(AveProduct::class)->findAll();
$data = $this->calculosFile($newFile->getId(), null, 0, 'File');
$sumatoriaTotalNet = 0;
$sumatoriaTotalVat = 0;
$sumatoriaTotal = 0;
$resultados = array(
'totalNeto' => $sumatoriaTotalNet,
'vat' => $sumatoriaTotalVat,
'total' => $sumatoriaTotal,
);
$productInFile = $em->getRepository(AveProductFile::class)->findByFileId($newFile->getId());
$numeroItems = sizeof($productInFile);
return $this->redirectToRoute('ave_edit_file', array( 'id' => $newFile->getId() ));
}
/**
* @Route("/fileupdate/{id}", name="ave_update_file")
* Actualizar un expediente
*/
public function updateFileAction($id, Request $request)
{
$logTelegram = false;
$numberToPrefix = 0;
$em = $this->getDoctrine()->getManager();
$newFile = $em->getRepository(AveFiles::class)->findOneById($id);
$newRequest = $request->request->get('avexpress');
$srvInconsistentes = ''; // Mensaje de alerta por inconsistencia en los servicios
// INICIO: Si existe un documento creado no se puede cambiar el cliente
$oldDoc = $em->getRepository(AveDocInvoice::class)->findOneByFileId($id);
$noexistefactura = empty($oldDoc);
// FIN: Si existe un documento creado no se puede cambiar el cliente
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
if (!empty($newRequest['title'])){$newFile->setTitle($newRequest['title']);}
if ($noexistefactura)
{
$newFile->setClient($newRequest['client']);
$msjErrorClt = '';
}
else
{ /* Hay una factura, no se debe cambiar el cliente */
// Verificamos si intenta cambiar el cliente para informar que no es posible hacerlo
if (!($newFile->getClient() == $newRequest['client'])){
$msjErrorClt = 'El cliente no puede ser modificado, ya existe una factura previa';
} else {
$msjErrorClt = '';
}
}
if (!empty($newRequest['idProposal'])){$newFile->setIdProposal($newRequest['idProposal']);} else {$newFile->setIdProposal(null);}
$newFile->setStatus($newRequest['status']);
$newFile->setDescription($newRequest['description']);
$newFile->setUpdatedId($user_id);
$newFile->setUpdatedAt(new \DateTime("now"));
if (!empty($newRequest['destination'])){$newFile->setDestinoId($newRequest['destination']);}
if (!empty($newRequest['dateStart'])){$newFile->setDateStart(new DateTime($newRequest['dateStart']));}
if (!empty($newRequest['dateEnd'])){$newFile->setDateEnd(new DateTime($newRequest['dateEnd']));}
if (!empty($newRequest['xtraFieldOne'])){$newFile->setXtraFieldOne($newRequest['xtraFieldOne']);}
try{
$em->persist($newFile);
$em->flush();
$event = 'El expediente ha sido actualizado. ';
if (!empty($msjErrorClt)){ $event = $event.$msjErrorClt; }
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeav', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeaverror', $errorMessage);
}
$productInFile = $em->getRepository(AveProductFile::class)->findByFileId($newFile->getId());
$txtWarning = '';
if(!empty($newFile->getIdProposal())){
// El expediente se ha relacionado con un proposal, se debe actualizar en eventos
$file = $newFile;
// Si hay proposal se debe actualizar en el expediente de Eventos
if (!empty($file->getIdProposal()) and is_numeric($file->getIdProposal())){
// Buscamos el destino donde se encuentre Avexpress y ahi agregamos el servicio, si no se encuentra no se agregara el servicio
$control = $em->getRepository(ProposalSupplierControl::class)->findOneBy(
array(
'supplierId' => 80, // El supplier 80 es Avexpress
'proposalId' => $file->getIdProposal(),
)
);
// INICIO: Buscamos la info del lado de eventos (SINCRONIZACION)
$txtOfChanges = ''; //Mensaje para el agente de cambios en los servicios hechos desde AvExpress
$proposal = $em->getRepository(Proposal::class)->findOneById($file->getIdProposal());
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$agentFullName = $agent->getName().' '.$agent->getLastName();
$proposalTitle = $proposal->getId().' - '.$proposal->getTitle();
// FIN: Buscamos la info del lado de eventos
foreach ($productInFile as $item){
//Si las fechas de inicio y fin no coinciden con el campo dias se debe enviar alerta
$txtWarning = ($item->getDateOutAt()->diff($item->getDateInAt()))->days + 1 <> $item->getDays() ? '<br>'.$item->getProductName() : '';
if (!empty($txtWarning)){
if (empty($srvInconsistentes)){ $srvInconsistentes = 'Hay inconsistencias en: '.'<br>'.$txtWarning; } else { $srvInconsistentes = $srvInconsistentes.'<br>'.$txtWarning; }
}
if (!empty($control)){
// Existe un destino con AvExpress como proveedor, ahĆ se agregara el servicio
$yaexistiaunservicio = false; $proposalServicex = null;
// Se verifica que no el productfile Av no tenga imagen en Eventos
if (!empty($item->getOriginId())){
// Se verifica que aun exista en Eventos el servicio
$proposalServicex = $em->getRepository(ProposalSupplierServices::class)->findOneById($item->getOriginId());
if (!empty($proposalServicex)){ $yaexistiaunservicio = true; } else { $yaexistiaunservicio = false; }
} else {
// no estaba relacionado con nada en eventos, se crea uno nuevo
$yaexistiaunservicio = false;
}
if ($yaexistiaunservicio){
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
$service = $proposalServicex;
$oldServiceEvent = array(
'activityId' => $service->getActivityId(),
'assistantId' => $service->getAssistantId(),
'breakdown' => $service->getBreakdown(),
'commission' => $service->getCommission(),
'controlId' => $service->getControlId(),
'currency' => $service->getCurrency(),
'dateBlockLimit' => $service->getDateBlockLimit(),
'dateInAt' => $service->getDateInAt(),
'dateOutAt' => $service->getDateOutAt(),
'destinationId' => $service->getDestinationId(),
'directPayment' => $service->getDirectPayment(),
'hour' => $service->getHour(),
'ideaId' => $service->getIdeaId(),
'isFather' => $service->getIsFather(),
'iva' => $service->getIva(),
'name' => $service->getName(),
'opCommission' => $service->getOpCommission(),
'opIva' => $service->getOpIva(),
'opOver' => $service->getOpOver(),
'originalIva' => $service->getOriginalIva(),
'originalPrice' => $service->getOriginalPrice(),
'originalopIva' => $service->getOriginalopIva(),
'over' => $service->getOver(),
'pax' => $service->getPax(),
'preCommission' => $service->getPreCommission(),
'preIva' => $service->getPreIva(),
'price' => $service->getPrice(),
'proposalId' => $service->getProposalId(),
'rank' => $service->getRank(),
'serviceCatId' => $service->getServiceCatId(),
'serviceCatName' => $service->getServiceCatName(),
'serviceId' => $service->getServiceId(),
'serviceIdFather' => $service->getServiceIdFather(),
'status' => $service->getStatus(),
'statusRec' => $service->getStatusRec(),
'statusinternal' => $service->getStatusinternal(),
'supplierId' => $service->getSupplierId(),
'units' => $service->getUnits(),
);
$service->setName($item->getProductName());
// Se verifican los precios en ambas partes (AV Express e InOut)
if (!($service->getPrice() == $item->getServicePrice())) {
// Si ambos precios unitarios son distintos se ha modificado el numero de dĆas en Av Express
$newPriceInOut = $this->precioPorVariacionDeDias($service, $item);
$service->setPrice($newPriceInOut);
} else {
// si son iguales tambien se deben verificar el numero de dias
if (!(($service->getDateOutAt()->diff($service->getDateInAt())->days + 1) == $item->getDays())) {
$newPriceInOut = $this->precioPorVariacionDeDias($service, $item);
$service->setPrice($newPriceInOut);
}
}
$service->setCurrency($item->getCurrency());
$service->setUnits($item->getUnits());
// $service->setCommission(0); // InOut puede haber metido una Comision y no se le debe modificar
// $service->setOver(0); // InOut puede haber metido un Over y no se le debe modificar
$service->setIva(21);
if (empty($item->getPax())) {
$service->setPax(1);
} else {
$service->setPax($item->getPax());
}
$service->setHour(null);
$service->setDateInAt($item->getDateInAt());
$service->setDateOutAt($item->getDateOutAt());
$service->setDirectPayment(0);
// $service->setStatus('Pending'); // InOut puede haber Confirmado y no se le debe modificar
$service->setStatusinternal('Additional');
$service->setPreCommission(null);
$service->setPreIva(null);
$service->setDateBlockLimit(null);
// $service->setOpCommission(1); // InOut puede haber metido una Op Comision y no se le debe modificar
// $service->setOpOver(1); // InOut puede haber metido una Op Over y no se le debe modificar
// $service->setOpIva(1); // InOut puede haber metido una Op Iva y no se le debe modificar
$service->setBreakdown(0);
$service->setIsFather(0);
$service->setRank($this->rankAvParaInOutService($item->getId()));
$service->setOriginalopIva(1);
$service->setStatusRec('normal');
$service->setCreatedId($user_id);
$service->setUpdatedId($user_id);
$em->persist($service);
$em->flush();
// Se debe notificar por Telegram al agente de eventos
$logTelegram = true;
//Verificamos cambios e informamos al agente del proposal
$boolChanges = false;
if (!($service->getRank() == $oldServiceEvent['rank'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Orden</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['rank'].', su nuevo valor es: '.$service->getRank().'<br>'; $boolChanges = true; }
if (!($service->getName() == $oldServiceEvent['name'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Nombre</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['name'].', su nuevo valor es: '.$service->getName().'<br>'; $boolChanges = true; }
if (!($service->getPrice() == $oldServiceEvent['price'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Precio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['price'].', su nuevo valor es: '.$service->getPrice().'<br>'; $boolChanges = true; }
if (!($service->getCurrency() == $oldServiceEvent['currency'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Moneda</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['currency'].', su nuevo valor es: '.$service->getCurrency().'<br>'; $boolChanges = true; }
if (!($service->getUnits() == $oldServiceEvent['units'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Cantidad</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['units'].', su nuevo valor es: '.$service->getUnits().'<br>'; $boolChanges = true; }
if (!($service->getPax() == $oldServiceEvent['pax'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Personas</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['pax'].', su nuevo valor es: '.$service->getPax().'<br>'; $boolChanges = true; }
if (!($service->getOpOver() == $oldServiceEvent['opOver'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>OpciĆ³n (-/+) del Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['opOver'].', su nuevo valor es: '.$service->getOpOver().'<br>'; $boolChanges = true; }
if (!($service->getOver() == $oldServiceEvent['over'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['over'].', su nuevo valor es: '.$service->getOver().'<br>'; $boolChanges = true; }
if (!($service->getOpCommission() == $oldServiceEvent['opCommission'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>OpciĆ³n (-/+) de la ComisiĆ³n</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['opCommission'].', su nuevo valor es: '.$service->getOpCommission().'<br>'; $boolChanges = true; }
if (!($service->getCommission() == $oldServiceEvent['commission'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>ComisiĆ³n" ha sido modificado. Su valor era: '.$oldServiceEvent['commission'].', su nuevo valor es: '.$service->getCommission().'<br>'; $boolChanges = true; }
if (!($service->getOpIva() == $oldServiceEvent['opIva'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>OpciĆ³n (-/+) del Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['opIva'].', su nuevo valor es: '.$service->getOpIva().'<br>'; $boolChanges = true; }
if (!($service->getIva() == $oldServiceEvent['iva'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['iva'].', su nuevo valor es: '.$service->getIva().'<br>'; $boolChanges = true; }
if (!($service->getDateInAt()->format('H:i') == $oldServiceEvent['dateInAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Hora inicio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateInAt']->format('H:i').', su nuevo valor es: '.$service->getDateInAt()->format('H:i').'<br>'; $boolChanges = true; }
if (!($service->getDateInAt()->format('Ymd') == $oldServiceEvent['dateInAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Fecha inicio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateInAt']->format('d/m/Y').', su nuevo valor es: '.$service->getDateInAt()->format('d/m/Y').'<br>'; $boolChanges = true; }
if (!($service->getDateOutAt()->format('H:i') == $oldServiceEvent['dateOutAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Hora fin</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateOutAt']->format('H:i').', su nuevo valor es: '.$service->getDateOutAt()->format('H:i').'<br>'; $boolChanges = true; }
if (!($service->getDateOutAt()->format('Ymd') == $oldServiceEvent['dateOutAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$service->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Fecha fin</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['dateOutAt']->format('d/m/Y').', su nuevo valor es: '.$service->getDateOutAt()->format('d/m/Y').'<br>'; $boolChanges = true; }
} else {
$srvAlreadyInvoiced = 'Error al sincronizar. <br><br> InOut ya ha facturado.';
$this->addFlash('mensajeaverror', $srvAlreadyInvoiced);
}
} else{
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
$service = new ProposalSupplierServices();
$service->setServiceIdFather(0);
$service->setControlId($control->getId());
$service->setProposalId($file->getIdProposal());
$service->setDestinationId($control->getDestinoId());
$service->setSupplierId(80); // 80 es AvExpress
$service->setIdeaId(null);
$service->setServiceId($item->getProductId());
$service->setServiceCatName('Av');
$service->setServiceCatId(3);
$service->setName($item->getProductName());
$priceInOut = $item->getSubTotalPrice();
if (!($item->getPax() == 0)) {
$priceInOut = $priceInOut / $item->getPax(); // Se devuelve el calculo dividiendo entre personas
}
if (!($item->getUnits() == 0)) {
$priceInOut = $priceInOut / $item->getUnits(); // Se devuelve el calculo dividiendo entre cantidades
}
if (!($item->getDays() == 0)) {
$priceInOut = $priceInOut / round($item->getDays()); // Se devuelve el calculo dividiendo entre dias, se redondea por si es 1.5
}
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$priceInOut = round($priceInOut, 2, PHP_ROUND_HALF_UP);
$service->setPrice($priceInOut);
$service->setCurrency($item->getCurrency());
$service->setUnits($item->getUnits());
$service->setCommission(0);
$service->setOver(0);
$service->setIva(21);
if (empty($item->getPax())) { $service->setPax(1); } else { $service->setPax($item->getPax()); }
$service->setHour(null);
$service->setDateInAt($item->getDateInAt());
$service->setDateOutAt($item->getDateOutAt());
$service->setDirectPayment(0);
$service->setStatus('Pending');
$service->setStatusinternal('Additional');
$service->setPreCommission(null);
$service->setPreIva(null);
$service->setDateBlockLimit(null);
$service->setOpCommission(1);
$service->setOpOver(1);
$service->setOpIva(1);
$service->setBreakdown(0);
$service->setIsFather(0);
$service->setRank($this->rankAvParaInOutService($item->getId()));
$service->setOriginalopIva(1);
$service->setOriginalIva(null);
$service->setOriginalPrice(null);
$service->setStatusRec('normal');
$service->setAssistantId(null);
$service->setCreatedId($user_id);
$service->setUpdatedId($user_id);
$service->setCreatedAt(new \DateTime("now"));
$service->setUpdatedAt(new \DateTime("now"));
$em->persist($service);
$em->flush();
// Se relaciona el nuevo Servicio InOut con el Servicio AV
$item->setOriginId($service->getId());
$em->persist($item);
$em->flush();
// Se debe notificar por Telegram al agente de eventos
$logTelegram = true;
} else {
$srvAlreadyInvoiced = 'Error al sincronizar. <br><br> InOut ya ha facturado.';
$this->addFlash('mensajeaverror', $srvAlreadyInvoiced);
}
}
}
// Notificamos al agente de InOut si se hicieron actualizaciones en los servicios desde AvExpress
if (!empty($txtOfChanges)) { $this->messageOfChangesToAgent($txtOfChanges, $proposal->getId()); }
//INICIO: Creamos una orden de hacer proforma
//INICIO: Calculamos el ID de la proforma
$numberToPrefix = $em->getRepository(AveDocProforma::class)->findAll();
if (empty($numberToPrefix)){
$numberToPrefix = 0;
} else {
$numberToPrefix = end($numberToPrefix)->getId();
}
$numberToPrefix++;
//FIN: Calculamos el ID de la proforma
$order = new AveBudgetToProforma();
$order->setStatus('Pending');
$order->setFileId($file->getId());
$order->setProductFileId($item->getId());
$order->setUserConfirmedId($proposal->getAgentId());
$order->setUserConfirmedFullName($agentFullName);
$order->setProposalTitle($proposalTitle);
$order->setProformaId($numberToPrefix);
$em->persist($order);
$em->flush();
//FIN: Creamos una orden de hacer proforma
}
$event = 'Expediente guardado correctamente.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeav', $successMessage);
if (!empty($srvInconsistentes) and !empty($newFile->getIdProposal())){ $this->addFlash('mensajeaverror', $srvInconsistentes); }
//INICIO: Notificamos al agente por Telegram
if ($logTelegram){
//Buscamos todos los agentes del proposal
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
//Buscamos el Destino
$proposalDestino = $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
//Buscamos el agente de Avexpress
$userData = $em->getRepository(User::class)->findOneById($user_id);
if (!empty($proposalAgents) and !($user_id == 22)){
if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
$this->sendTelegram($proposalAgents->getAgOne(),'1. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
$this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
$this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
$this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS __ ID: '.$proposal->getId().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
}
}
//FIN: Notificamos al agente por Telegram
//INICIO: Creamos el presupuesto (proforma)
$budToPro = $em->getRepository(AveBudgetToProforma::class)->findByProformaId($numberToPrefix);
//INICIO: Se agrupan por expediente (fileId)
$proformas = array();
foreach ($budToPro as $item){
$proformas[$item->getFileId()][] = $item;
}
//FIN: Se agrupan por expediente (fileId)
if (!empty($budToPro)){
foreach ($proformas as $key => $elemento){
//INICIO: Creamos las proformas
$newProforma = new AveDocProforma();
$newProforma->setPrefix('AVE-' . (new DateTime('now'))->format('dmy') . '-' . $numberToPrefix . '-' . $key);
$newProforma->setDateAt(new DateTime('now'));
$newProforma->setFileId($key);
$newProforma->setCreatedId($user_id);
$newProforma->setUpdatedId($user_id);
$newProforma->setCreatedAt(new DateTime('now'));
$newProforma->setUpdatedAt(new DateTime('now'));
// $em->persist($newProforma);
$em->flush();
//FIN: Creamos las proformas
foreach ($elemento as $item) {
//$key es el id del expediente
// $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
//INICIO: Creamos los elemento que iran dentro de las proformas
$itemProforma = new AveDocProformaItems();
$itemProforma->setType('PRODUCT');
$itemProforma->setFileId($key);
$itemProforma->setProformaId($newProforma->getId());
$itemProforma->setControlId($item->getProductFileId());
// $em->persist($itemProforma);
$em->flush();
//INICIO: Confirmamos el BudToProforma
// $item->setStatus('Tosend'); // El elemento se ha pasado a la proforma, solo falta enviar
$item->setProformaId($newProforma->getId());
// $em->persist($item);
$em->flush();
//FIN: Confirmamos el BudToProforma
//FIN: Creamos los elemento que iran dentro de las proformas
}
}
}
//FIN: Creamos el presupuesto (proforma)
// INICIO: Se envia al agente el presupuesto
$budToPro = $em->getRepository(AveBudgetToProforma::class)->findByStatus('Tosend');
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$arrayIdPro = array(); // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
//INICIO: Se agrupan por expediente (fileId)
$proformas = array();
foreach ($budToPro as $item){
$proformas[$item->getFileId()][] = $item;
}
//FIN: Se agrupan por expediente (fileId)
if (!empty($budToPro)){
foreach ($proformas as $key => $elemento){
//INICIO: Creamos las proformas
foreach ($elemento as $item) {
//$key es el id del expediente
if (!empty($item->getProformaId())) {
$arrayIdPro[$item->getProformaId()] = $item->getUserConfirmedId(); // $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
}
//INICIO: Confirmamos el BudToProforma
$item->setStatus('Confirmed'); // El elemento se ha pasado a confirmado porque se enviara por correo
$em->persist($item);
$em->flush();
//FIN: Confirmamos el BudToProforma
//FIN: Creamos los elemento que iran dentro de las proformas
}
}
}
//INICIO: Notificamos de todos los presupuestos (proformas) que se han creado
foreach ($arrayIdPro as $key => $item){
//Buscamos la info del proposal
$xprof = $em->getRepository(AveDocProforma::class)->findOneById($key);
if (!empty($xprof)){
$xfile = $em->getRepository(AveFiles::class)->findOneById($xprof->getFileId());
$xprop = $em->getRepository(Proposal::class)->findOneById($xfile->getIdProposal());
$xcli = $em->getRepository(Client::class)->findOneById($xprop->getClientId());
$xbody = 'Proposal #'.$xprop->getId().' - '.$xprop->getName().
'<br><a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/edit/' . $xprop->getId() . '">Ver el Proposal</a>'.
'<br>Cliente: '.$xcli->getName().
'<br><br>' .'Presupuesto AvExpress #' . $key . ', ' . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/pdf/avexpressproforma/' . $key . '">Ver el PDF del presupuesto</a><br><br>NotificaciĆ³n de nuevo presupuesto: Este presupuesto ha sido creado de forma automĆ”tica.' .
'<br>Si el enlace al presupuesto no funciona correctamente, se debe a que desde AV lo han modificado o descartado.'.
'<br><br>';
} else {
$xbody = 'Presupuesto AvExpress #' . $key . ', ' . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/pdf/avexpressproforma/' . $key . '">Ver el PDF del presupuesto</a><br><br>NotificaciĆ³n de nuevo presupuesto: Este presupuesto ha sido creado de forma automĆ”tica.' . '<br><br>';
}
//Buscamos los agentes a notificar
// $arrayIdPro['X'] = 'Y'; al agente 'Y' se le informa del presupuesto 'X'
$agent = $em->getRepository(User::class)->findOneById($item);
$agentMail = $agent->getEmail();
$mailAgent = $agentMail;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $xbody,
'firm' => $firmGmail,
);
// EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername('desarrollo@develup.solutions')
->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('Presupuesto #' . $key . ', NotificaciĆ³n de nuevo presupuesto')
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($mailAgent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
//FIN: Notificamos de todos los presupuestos (proformas) que se han creado
// FIN: Se envia al agente el presupuesto
}
}
if(!empty($msjErrorClt)){
$errorMessage = $this->translator->trans('Error, el cliente no puede ser modificado, ya existe una factura previa');
$this->addFlash('mensajeaverror', $errorMessage);
return $this->redirectToRoute('ave_edit_file', array('id' => $newFile->getId()));
}
return $this->redirectToRoute('ave_edit_file', array('id' => $newFile->getId()));
}
/**
* @Route("/fileedit/{id}", name="ave_edit_file")
* Editar un expediente
*/
public function editFileAction( $id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$editFile = $em->getRepository(AveFiles::class)->findOneById($id);
$clients = $em->getRepository(Client::class)->findAll();
$clientSelected = $em->getRepository(Client::class)->findOneById($editFile->getClient());
$products = $em->getRepository(AveProduct::class)->findAll();
$destinations = $em->getRepository(Destination::class)->findAll();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$data = $this->calculosFile($id, null, 0, 'File');
$sumatoriaTotalNet = 0;
$sumatoriaTotalVat = 0;
$sumatoriaTotal = 0;
$resultados = array(
'totalNeto' => $sumatoriaTotalNet,
'vat' => $sumatoriaTotalVat,
'total' => $sumatoriaTotal,
);
$productInFile = $em->getRepository(AveProductFile::class)->findByFileId($id);
$numeroItems = sizeof($productInFile);
$facturas = $em->getRepository(AveDocInvoice::class)->findByFileId($id);
$facturasRec = $em->getRepository(AveDocInvoiceRec::class)->findByFileId($id);
foreach ($facturasRec as $item){ array_push($facturas,$item); }
$proformas = array();
$allProformas = $em->getRepository(AveDocProforma::class)->findByFileId($id);
foreach ($allProformas as $item) {
$dataTwo = $this->baseInvoiceDoneFileTwo($id, $item->getId(), 'P');
$bases = 0;
if (is_numeric($dataTwo['totales']) and is_numeric($dataTwo['totales_neto'])) {
$bases = $dataTwo['totales'] - $dataTwo['totales_neto'];
}
$itemsInProforma = array();
if (array_key_exists('product', $dataTwo['datasupplier'])) {
foreach ($dataTwo['datasupplier']['product'] as $elem) {
$itemsInProforma[] = $em->getRepository(AveProductFile::class)->findOneById($elem['id']);
}
$proformas[] = array(
'id' => $dataTwo['number'],
'itemsInProforma' => $itemsInProforma,
'date' => $dataTwo['date'],
'neto' => $dataTwo['totales_neto'],
'bases_imponibles' => $bases,
'total' => $dataTwo['totales'],
);
}
}
// Calculamos el beneficio
$dataThree = $this->baseBenefits($id);
// Buscamos los serviicos pendientes
$pendingBuds = $em->getRepository(AveBudgetPending::class)->findByProposalId($editFile->getIdProposal());
$pBuds = array();
// Creamos la agrupacion por proposal
foreach ($pendingBuds as $item){
if (!(array_key_exists($item->getProposalId(),$pBuds))){
if (!empty($item->getOriginId())){ // Los vacios solo contienen briefings
$pBuds[$item->getProposalId()] = null;
}
}
}
// Metemos los items en el arreglo clasificado por proposal
foreach ($pendingBuds as $item){
if (!empty($item->getOriginId())) { // Los vacios solo contienen briefings
$pBuds[$item->getProposalId()][] = $item;
}
}
ksort($pBuds);
$keysPbuds = array_keys($pBuds);
$gpFile = $em->getRepository(Reservation::class)->findOneById($editFile->getReservation());
$htFile = !(empty($gpFile)) ? (in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $em->getRepository(HtFile::class)->findOneByReservation($gpFile) : null ) : null;
$gpFile = in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $gpFile : null ;
return $this->render('MDS/AvexpressBundle/Avexpress/edit-files.html.twig',
array(
'id' => $id,
'clients' => $clients,
'clientId' => $editFile->getClient(),
'clientSelected' => $clientSelected,
'file' => $editFile,
'numeroItems' => $numeroItems,
'arrayProductFile' => $data['datasupplier']['product'],
'products' => $products,
'services' => null,
'facturas' => $facturas,
'proformas' => $proformas,
'paymentNotIvoiced' => null,
'paymentsAll' => null,
'resultados' => $resultados,
'totales_global_con_iva' => $data['totales'], //$data['totales_global_con_iva'],
'totales_global_iva' => $data['bases_imponibles']['ivaMontoVeintiUno'], //$data['totales_global_iva'],
'totales_global_neto' => $data['totales_neto'], //$data['totales_global_neto'],
'totales_global_servicios_con_iva' => 0, //$data['totales_global_servicios_con_iva'],
'totales_global_servicios_neto' => 0, //$data['totales_global_servicios_neto'],
'totales_global_servicios_iva' => 0, //$data['totales_global_servicios_iva'],
'sumatoria_totales_global_con_iva' => 0, //$data['sumatoria_totales_global_con_iva'],
'sumatoria_totales_global_neto' => 0, //$data['sumatoria_totales_global_neto'],
'sumatoria_totales_global_iva' => 0, //$data['sumatoria_totales_global_iva'],
'benefitEuro' => $dataThree['benefitEuro'],
'benefitPerc' => $dataThree['benefitPerc'],
'pendingBudgets' => $pBuds,
'keysPendingBudgets' => $keysPbuds,
'destinations' => $destinations,
'htFile' => $htFile,
'gpFile' => $gpFile,
));
}
/**
* @Route("/filedelete/{id}", name="ave_delete_file")
* Actualizar un expediente
*/
public function deleteFileAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$newFile = $em->getRepository(AveFiles::class)->findOneById($id);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$newFile->setStatus('Deleted');
$newFile->setUpdatedId($user_id);
$newFile->setUpdatedAt(new \DateTime("now"));
$em->persist($newFile);
$em->flush();
return $this->redirectToRoute('ave_edit_file', array( 'id' => $id ));
}
/**
* @Route("/filefrombudget/{id}", name="ave_add_file_from_budget")
* Agregar un expediente desde un presupuesto
*/
public function addFileFromBudgetAction( $id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$budget = $em->getRepository(AveBudgetPending::class)->findOneById($id);
$proposal = $em->getRepository(Proposal::class)->findOneById($budget->getProposalId());
$newFile = $em->getRepository(AveFiles::class)->findOneByIdProposal($proposal->getId());
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
if (empty($newFile)){
// No hay un File asociado a ese proposal, se debe crear uno nuevo
$newFile = new AveFiles();
$newFile->setTitle($proposal->getId().' - ' .$budget->getProposalTitle());
$newFile->setClient(262); // In Out es el cliente
$newFile->setIdProposal($proposal->getId());
$newFile->setStatus('Pending');
$newFile->setAdvancePayment(null);
if (!empty($budget->getBriefing())){
$newFile->setDescription('<p> ********* MENSAJE DEL AGENTE ********* </p>' . $budget->getBriefing());
}
$newFile->setDateStart(new \DateTime("now"));
$newFile->setDateEnd(new \DateTime("now"));
$newFile->setCreatedId($user_id);
$newFile->setUpdatedId($user_id);
$newFile->setCreatedAt(new \DateTime("now"));
$newFile->setUpdatedAt(new \DateTime("now"));
} else {
// Ya existe un File asociado a ese proposal
$newFile->setClient(262); // In Out es el cliente
$newFile->setStatus('Pending');
if (!empty($budget->getBriefing())) {
$newFile->setDescription($newFile->getDescription() . '<p> ********* MENSAJE DEL AGENTE ********* </p>' . $budget->getBriefing());
}
$newFile->setUpdatedId($user_id);
$newFile->setUpdatedAt(new \DateTime("now"));
}
$em->persist($newFile);
$em->flush();
$em->remove($budget);
$em->flush();
//Actualizamos los Briefings que esten en FileId null con el recien generado fileId en base al proposalId
$allBriefings = $em->getRepository(AveBriefings::class)->findByProposalId($proposal->getId());
foreach ($allBriefings as $item){
if (empty($item->getFileId())) {
$item->setFileId($newFile->getId());
$em->persist($item);
$em->flush();
}
}
return $this->redirectToRoute('ave_edit_file', array( 'id' => $newFile->getId() ));
}
/**
* @Route("/filelistbriefings/{id}", name="ave_list_file_briefings")
* Listar briefings del expediente
*/
public function listFileBriefingsAction($id, Request $request){
$em = $this->getDoctrine()->getManager();
$briefings = $em->getRepository(AveBriefings::class)->findByFileId($id);
return $this->render('MDS/AvexpressBundle/Avexpress/list-briefings.html.twig',
array(
'id' => $id,
'briefings' => $briefings,
)
);
}
/**
* @Route("/briefingadd/{id}", name="ave_add_file_briefings")
* Agregar briefing al expediente
*/
public function addFileBriefingsAction($id, Request $request){
$brif = $request->request->get('newbriefing');
$em = $this->getDoctrine()->getManager();
$file = $em->getRepository(AveFiles::class)->findOneById($id);
$proposalId = $file->getIdProposal();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$userConfirmedFullName = $user_logueado->getName().' '.$user_logueado->getLastName();
$briefing = new AveBriefings();
$briefing->setProposalId($proposalId);
$briefing->setBriefing($brif);
$briefing->setBudgetPendingId(null);
$briefing->setFileId($id);
$briefing->setUserConfirmedFullName($userConfirmedFullName);
$briefing->setUserConfirmedId($user_id);
$briefing->setCreatedAt(new \DateTime("now"));
$em->persist($briefing);
$em->flush();
$briefings = $em->getRepository(AveBriefings::class)->findByFileId($id);
return $this->render('MDS/AvexpressBundle/Avexpress/list-briefings.html.twig',
array(
'id' => $id,
'briefings' => $briefings,
)
);
}
/**
* @Route("/filedeletedlist/", name="ave_list_file_deleted")
* Listar expedientes cancelados
*/
public function listFileDeletedAction( Request $request)
{
$em = $this->getDoctrine()->getManager();
$idgroup = null; $ref = array();
$reservas = $em->getRepository(AveFiles::class)->findByStatus('Deleted');
foreach ($reservas as $res) {
$client = $em->getRepository(Client::class)->findOneById($res->getClient());
if (!empty($client)) { $res->setClient($client->getName()); } else { $res->setClient(null); }
if (!empty($res->getDateStart()) and !empty($res->getDateEnd())) {
$ref[$res->getId()] = '#' . ($res->getDateStart())->format('ymd') . ($res->getDateEnd())->format('ymd');
} else {
$ref[$res->getId()] = '#' . '000000' . '000000';
}
}
$reservasZero = array();
foreach ($reservas as $res) {
$reservasZero[] = array(
'dateStart' => $res->getDateStart(),
'dateEnd' => $res->getDateEnd(),
'id' => $res->getId(),
'title' => $res->getTitle(),
'client' => $res->getClient(),
'createdId' => $res->getCreatedId(),
'ref' => $ref[$res->getId()],
'reservation' => $res->getReservation(),
);
}
$reservas = $reservasZero;
return $this->render('MDS/AvexpressBundle/Avexpress/list-files.html.twig',
array(
'groups' => null,
'listofdeletedfiles' => true,
'reservations' => $reservas
)
);
}
/**
* @Route("/updatefilecomments/{id}", name="ave_update_file_comments")
* Actualizar Comentarios y booleanos del expediente
*/
public function updateFileCommentsAction($id, Request $request){
$em = $this->getDoctrine()->getManager();
$file = $em->getRepository(AveFiles::class)->findOneById($id);
$newComments = $request->request->get('comments');
$chkCommentsToPro = $request->request->get('chkCommentsToPro');
$chkCommentsToInv = $request->request->get('chkCommentsToInv');
if ($chkCommentsToInv == 'on'){ $chkCommentsToInv = true; } else { $chkCommentsToInv = false; }
if ($chkCommentsToPro == 'on'){ $chkCommentsToPro = true; } else { $chkCommentsToPro = false; }
$file->setComments($newComments);
$file->setCommentsInInv($chkCommentsToInv);
$file->setCommentsInPro($chkCommentsToPro);
$em->persist($file);
$em->flush();
return $this->redirectToRoute('ave_edit_file', array( 'id' => $id ));
}
private function baseInvoiceDoneFileTwo($fileId, $invoiceId, $typeBase)
{
$em = $this->getDoctrine()->getManager();
$file = $em->getRepository(AveFiles::class)->findOneById($fileId);
$dateDocument = null; //Fecha final del documento
$subneto = 0;
if (($typeBase == 'I') or ($typeBase == 'P')) {
if ($typeBase == 'I') {
$items = $em->getRepository(AveDocInvoiceItems::class)->findBy(array('fileId' => $fileId, 'invoiceId' => $invoiceId));
} else {
// Es proforma
// $items = $em->getRepository(AveDocProformaItems::class)->findBy(array('fileId' => $fileId, 'proformaId' => $invoiceId));
// $items = $em->getRepository(AveDocProformaItems::class)->findBy(array('fileId' => $fileId, 'proformaId' => $invoiceId));
$parameters = array(
'fileId' => $fileId,
'proformaId' => $invoiceId,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE i.fileId = :fileId AND c.proformaId =:proformaId
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$items = $query->getResult();
$arrayLocation = array();
$arrayLocationWithNull = false;
foreach ($items as $item){
if (!empty($item->getLocation())){
$arrayLocation[$item->getLocation()] = $item->getLocation();
} else {
$arrayLocationWithNull = true;
}
}
if ($arrayLocationWithNull){ $arrayLocation['null'] = 'null'; }
$productsInFile = array();
foreach ($arrayLocation as $item){
// VIDEO
$parameters = array(
'fileId' => $fileId,
'type' => 'VĆdeo',
'location' => $item,
'proformaId' => $invoiceId,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileVid = $query->getResult();
// SONIDO
$parameters = array(
'fileId' => $fileId,
'type' => 'Sonido',
'location' => $item,
'proformaId' => $invoiceId,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileSound = $query->getResult();
// ILUMINACION
$parameters = array(
'fileId' => $fileId,
'type' => 'IluminaciĆ³n',
'location' => $item,
'proformaId' => $invoiceId,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location AND c.proformaId =:proformaId
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileLights = $query->getResult();
// OTROS
$parameters = array(
'fileId' => $fileId,
'typeV' => 'VĆdeo',
'typeS' => 'Sonido',
'typeI' => 'IluminaciĆ³n',
'location' => $item,
'proformaId' => $invoiceId,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location = :location AND c.proformaId =:proformaId)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileOther = $query->getResult();
// CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
$parameters = array(
'fileId' => $fileId,
'location' => $item,
'proformaId' => $invoiceId,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location = :location AND c.proformaId =:proformaId)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileNull = $query->getResult();
// Para el location en NULL el SQL tiene que ser diferente por eso el siguiente condicional
if ($item == 'null'){
// VIDEO
$parameters = array(
'fileId' => $fileId,
'type' => 'VĆdeo',
'proformaId' => $invoiceId,
// 'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileVid = $query->getResult();
// SONIDO
$parameters = array(
'fileId' => $fileId,
'type' => 'Sonido',
'proformaId' => $invoiceId,
// 'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileSound = $query->getResult();
// ILUMINACION
$parameters = array(
'fileId' => $fileId,
'type' => 'IluminaciĆ³n',
'proformaId' => $invoiceId,
// 'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE i.fileId = :fileId AND i.type = :type AND i.location IS NULL AND c.proformaId =:proformaId
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileLights = $query->getResult();
// OTROS
$parameters = array(
'fileId' => $fileId,
'typeV' => 'VĆdeo',
'typeS' => 'Sonido',
'typeI' => 'IluminaciĆ³n',
'proformaId' => $invoiceId,
// 'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location IS NULL AND c.proformaId =:proformaId)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileOther = $query->getResult();
// CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
$parameters = array(
'fileId' => $fileId,
'proformaId' => $invoiceId,
// 'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
INNER JOIN AvexpressBundle:AveDocProformaItems c WITH c.controlId = i.id
WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location IS NULL AND c.proformaId =:proformaId)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileNull = $query->getResult();
}
$productsInFile = array_merge($productsInFile, $productsInFileVid, $productsInFileSound, $productsInFileLights, $productsInFileOther, $productsInFileNull);
}
$items = $productsInFile; // En Items estaban todos pero sin ordenamiento, ahora estan organizados por location y tipo
}
} else {
// No es factura ni proforma, es una rectificativa
$items = $em->getRepository(AveDocInvoiceRecItems::class)->findBy(array('fileId' => $fileId, 'invoiceRecId' => $invoiceId));
}
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('4');
$client = $em->getRepository(Client::class)->findById($file->getClient());
if (empty($client)){
$client[0] = new Client();
$client[0]->setName('');
$client[0]->setTitle('');
$client[0]->setIdDocument('');
$client[0]->setPopulation('');
$client[0]->setRegion('');
$client[0]->setCountry('');
} else {
if (is_numeric($client[0]->getPopulation())){
$city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
$client[0]->setPopulation($city->getCity());
}
if (is_numeric($client[0]->getRegion())){
$region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
$client[0]->setRegion($region->getRegion());
}
if (is_numeric($client[0]->getCountry())){
$country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
$client[0]->setCountry($country->getCountry());
}
}
// Acumuladores de los calculos
$totales_neto_all = 0;
$data_iva = array(
'iva' => 21,
'ivaMontoVeintiUno' => 0,
'ivaMontoDiez' => 0,
'ivaMontoCero' => 0,
);
//INICIO: Determinamos el numero de factura o proforma
if ($typeBase == 'I'){
// Es una Factura
$number = $em->getRepository(AveDocInvoice::class)->findOneById($invoiceId);
$dateDocument = $number->getDateAt();
$number = $number->getNumber();
$type = 'Invoice';
} else {
if ($typeBase == 'R'){
// Es una factura rectificativa
$number = $em->getRepository(AveDocInvoiceRec::class)->findOneById($invoiceId);
$dateDocument = $number->getDateAt();
$type = 'Invoice Rec';
} else {
// Es una Proforma
$number = $invoiceId;
$type = 'Proforma';
}
}
//FIN: Determinamos el numero de factura o proforma
// Buscamos los productos, pagos y servicios
$arrayItems = array();
$fileProducts = array();
$payments = array();
$services = array();
if (!empty($items)) {
if (($typeBase == 'I') or ($typeBase == 'R')) {
foreach ($items as $item) {
switch ($item->getItemType()) {
case 'PRODUCT': // Producto
$fileProducts[] = $item;
break;
case 'PAYMENT': // Pago
$payments[] = $item;
break;
case 'SERVICE': // Servicio
$services[] = $item;
break;
default:
break;
}
}
} else {
// Es una proforma
foreach ($items as $item) {
switch ($item->getType()) {
case 'PRODUCT': // Producto
$productPro = $em->getRepository(AveProductFile::class)->findOneById($item->getControlId());
if (!empty($productPro)) {
$fileProducts[] = $productPro;
}
break;
case 'PAYMENT': // Pago
$paymentPro = $em->getRepository(AvePaymentsClient::class)->findOneById($item->getControlId());
if (!empty($paymentPro)) {
$payments[] = $paymentPro;
}
break;
case 'SERVICE': // Servicio
$servicePro = $em->getRepository(AveServices::class)->findOneById($item->getControlId());
if (!empty($servicePro)) {
$services[] = $servicePro;
}
break;
default:
// Producto (Video, Iluminacion, Sonido, Otros)
if (!empty($item)) {
$fileProducts[] = $item;
}
break;
}
}
}
}
$data_supplier = array();
$i = 0;
$iva = '21'; // Esteban Rincon: "Por Ley de localizaciĆ³n del impuesto, siempre serĆ” un 21%"
$pax = '1';
$qty = '1';
$product = array(
'neto' => 0,
'sumSubT' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
$service = array(
'neto' => 0,
'sumSubT' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
foreach ($fileProducts as $item){
if (!is_null($item->getUnits()) or !empty($item->getUnits())){
$qty = $item->getUnits();
}
if (($typeBase == 'I') or ($typeBase == 'R')) {
if (is_null($item->getPrdServicePrice()) or empty($item->getPrdServicePrice())){
$subtotal = 0;
$neto = 0;
$subtotalProduct = 0;
} else {
// $subtotalProduct = $item->getPrdServicePrice() * 1.21;
$subtotalProduct = $item->getPrdSubTotalPrice() * 1.21;
// $subneto = $item->getPrdServicePrice();
$subneto = $item->getPrdSubTotalPrice();
$subtotal = $subtotalProduct;
$neto = $subneto;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
$neto = round($neto,2,PHP_ROUND_HALF_UP);
$arrayItems[] = array(
'type' => 'Product',
'name' => $item->getPrdName(),
'amount' => $neto,
'iva' => '21',
'total' => $subtotal,
);
}
} else {
// Es proforma
if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
$subtotal = 0;
$neto = 0;
$subtotalProduct = 0;
} else {
// $subtotalProduct = $item->getServicePrice() * 1.21;
$subtotalProduct = $item->getSubTotalPrice() * 1.21;
// $subneto = $item->getServicePrice();
$subneto = $item->getSubTotalPrice();
$subtotal = $subtotalProduct;
$neto = $subneto;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
$neto = round($neto,2,PHP_ROUND_HALF_UP);
$arrayItems[] = array(
'type' => 'Product',
'name' => $item->getProductName(),
'amount' => $neto,
'iva' => '21',
'total' => $subtotal,
);
}
}
// Acumula netos totales e IVA
$totales_neto_all = $totales_neto_all + $neto;
$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21);
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
// Acumula netos totales e IVA
$product['neto'] = $product['neto'] + $neto;
$product['sumSubT'] = $product['sumSubT'] + $subtotal;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$product['neto'] = round($product['neto'],2,PHP_ROUND_HALF_UP);
$product['sumSubT'] = round($product['sumSubT'],2,PHP_ROUND_HALF_UP);
if (($typeBase == 'I') or ($typeBase == 'R')) {
$data_supplier['product'][$i] = array(
'id' => $item->getId(),
'productName' => $item->getPrdName(),
'productId' => $item->getPrdProductId(),
'dateStart' => $item->getPrdDateStart(),
'dateEnd' => $item->getPrdDateEnd(),
'servicePrice' => $item->getPrdServicePrice(),
'serviceSubTotalPrice' => $subneto, //antes de IVA
'subtotalProduct' => $subtotalProduct,
'iva' => $iva,
'pax' => $pax,
'qty' => $qty,
'type' => $item->getPrdType(),
'subtotal' => $subtotal,
);
} else {
// Es proforma
$data_supplier['product'][$i] = array(
'id' => $item->getId(),
'productName' => $item->getProductName(),
'productId' => $item->getProductId(),
'dateStart' => $item->getDateStart(),
'dateEnd' => $item->getDateEnd(),
'servicePrice' => $item->getServicePrice(),
'subtotalProduct' => $subtotalProduct,
'iva' => $iva,
'pax' => $pax,
'qty' => $qty,
'type' => $item->getType(),
'subtotal' => $subtotal,
);
}
$i++;
}
$data_supplier['productSubTotal'] = array(
'neto' => $product['neto'],
'sumSubT' => $product['sumSubT'],
);
$payment = array(
'sumSubT' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
$i = 0;
foreach ($payments as $item){
if (($typeBase == 'I') or ($typeBase == 'R')) {
$payment['sumSubT'] = $payment['sumSubT'] + $item->getPayAmountTotal();
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$payment['sumSubT'] = round($payment['sumSubT'], 2, PHP_ROUND_HALF_UP);
$data_supplier['payment'][$i] = array(
'id' => $item->getId(),
'amount' => $item->getPayAmount(),
'amountTotal' => $item->getPayAmountTotal(),
'vat' => $item->getPayVat(),
'datePayAt' => $item->getPayDatePayAt(),
'wayToPay' => $item->getPayWayToPay(),
);
$arrayItems[] = array(
'type' => 'Payment',
'name' => $item->getPayWayToPay(),
'amount' => $item->getPayAmount(),
'total' => $item->getPayAmountTotal(),
'iva' => $item->getPayVat(),
);
} else {
// Es una proforma
$payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal();
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$payment['sumSubT'] = round($payment['sumSubT'], 2, PHP_ROUND_HALF_UP);
$data_supplier['payment'][$i] = array(
'id' => $item->getId(),
'amount' => $item->getAmount(),
'amountTotal' => $item->getAmountTotal(),
'vat' => $item->getVat(),
'datePayAt' => $item->getDatePayAt(),
'wayToPay' => $item->getWayToPay(),
);
$arrayItems[] = array(
'type' => 'Payment',
'name' => $item->getWayToPay(),
'amount' => $item->getAmount(),
'total' => $item->getAmountTotal(),
'iva' => $item->getVat(),
);
}
$i++;
}
if (!empty($payments)) {
$data_supplier['paymentSubTotal'] = array(
'sumSubT' => $payment['sumSubT'],
);
}
foreach ($services as $item){
if (($typeBase == 'I') or ($typeBase == 'R')) {
if (is_null($item->getSrvPrice()) or empty($item->getSrvPrice())) {
$subtotal = 0;
$neto = 0;
$subtotalService = 0;
} else {
$subtotalService = $item->getSrvPrice();
$subneto = $item->getSrvPrice();
// Commission
if ($item->getSrvOpCommission() == '1') {
$subtotalService = $subtotalService * (1 + ($item->getSrvCommission() / 100));
$subneto = $subneto * (1 + ($item->getSrvCommission() / 100));
} else {
$subtotalService = $subtotalService * (1 - ($item->getSrvCommission() / 100));
$subneto = $subneto * (1 - ($item->getSrvCommission() / 100));
}
// Over
if ($item->getSrvOpOver() == '1') {
$subtotalService = $subtotalService + $item->getSrvOver();
$subneto = $subneto + $item->getSrvOver();
} else {
$subtotalService = $subtotalService - $item->getSrvOver();
$subneto = $subneto - $item->getSrvOver();
}
// IVA
if ($item->getSrvOpIva() == '1') {
$subtotalService = $subtotalService * (1 + ($item->getSrvIva() / 100));
} else {
$subtotalService = $item->getSrvPrice();
$subneto = ($subneto * 100) / (100 + $item->getSrvIva());
}
switch ($item->getSrvServiceCatId()) {
case 1: // Alojamiento
// el numero de noches $numNoches; precio unitario $subneto
$numNoches = (($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days;
// La personas no afectan este calculo
$subtotal = $subtotalService * $numNoches * $item->getSrvUnits();
$subnetoUnit = $subneto;
$subneto = $subneto * $numNoches * $item->getSrvUnits();
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Hotel',
'date' => ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y'),
'qty' => $item->getSrvUnits(),
'iva' => $item->getSrvIva(),
'pax' => '-',
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 2: //Actividades
// El nĆŗmero de personas es considerado en el calculo
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$subtotal = $subtotalService * $days * $item->getSrvUnits();
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $item->getSrvUnits();
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Actividad',
'date' => $dateServ,
'qty' => $item->getSrvUnits(),
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 3: // AV
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'AV',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 4: //Creative
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Creativo',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 5: //Cruise
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Crucero',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 6: //Entertaiment
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Entretenimiento',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 7: // Gifts
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$days = 1;
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Regalos',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 8: //Guide
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Regalos',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 9: //Itineraries
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Itinerarios',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 10: //Lounge -- No Aplica
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
//
// $data_supplier['service'][$i] = array (
// 'id' => $item->getId(),
// 'serviceCatId' => $item->getServiceCatId(),
// 'serviceName' => $item->getName(),
// 'serviceType' => 'Itinerarios',
// 'date' => $dateServ,
// 'qty' => $unitsServ,
// 'iva' => $item->getIva(),
// 'pax' => $item->getPax(),
// 'precioUnit' => $subnetoUnit,
// 'subneto' => $subneto,
// 'subtotal' => $subtotal,
// );
break;
case 11: //Menu
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'MenĆŗ',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 12: //Others
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Otros',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 13: //Transport
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Transporte',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 14: //Technology
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$days = 1;
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'TecnologĆa',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 15: //Assisstant
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'Asistente',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 16: //DDR
$pax = $item->getSrvPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getSrvDateOutAt())->diff($item->getSrvDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y') . ' - ' . ($item->getSrvDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getSrvDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getSrvUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getSrvServiceCatId(),
'serviceName' => $item->getSrvName(),
'serviceType' => 'DDR',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getSrvIva(),
'pax' => $item->getSrvPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
default:
break;
}
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal, 2, PHP_ROUND_HALF_UP);
$neto = round($subneto, 2, PHP_ROUND_HALF_UP);
$arrayItems[] = array(
'type' => 'Service',
'name' => $item->getSrvName(),
'amount' => $neto,
'iva' => $item->getSrvIva(),
'total' => $subtotal,
);
}
switch ($item->getSrvIva()) {
// Acumula IVA
case 21:
$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getSrvIva() / 100));
break;
case 10:
$data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getSrvIva() / 100));
break;
case 0:
break;
default:
break;
}
} else {
// Es una proforma
if (is_null($item->getPrice()) or empty($item->getPrice())) {
$subtotal = 0;
$neto = 0;
$subtotalService = 0;
} else {
$subtotalService = $item->getPrice();
$subneto = $item->getPrice();
// Commission
if ($item->getOpCommission() == '1') {
$subtotalService = $subtotalService * (1 + ($item->getCommission() / 100));
$subneto = $subneto * (1 + ($item->getCommission() / 100));
} else {
$subtotalService = $subtotalService * (1 - ($item->getCommission() / 100));
$subneto = $subneto * (1 - ($item->getCommission() / 100));
}
// Over
if ($item->getOpOver() == '1') {
$subtotalService = $subtotalService + $item->getOver();
$subneto = $subneto + $item->getOver();
} else {
$subtotalService = $subtotalService - $item->getOver();
$subneto = $subneto - $item->getOver();
}
// IVA
if ($item->getOpIva() == '1') {
$subtotalService = $subtotalService * (1 + ($item->getIva() / 100));
} else {
$subtotalService = $item->getPrice();
$subneto = ($subneto * 100) / (100 + $item->getIva());
}
switch ($item->getServiceCatId()) {
case 1: // Alojamiento
// el numero de noches $numNoches; precio unitario $subneto
$numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
// La personas no afectan este calculo
$subtotal = $subtotalService * $numNoches * $item->getUnits();
$subnetoUnit = $subneto;
$subneto = $subneto * $numNoches * $item->getUnits();
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Hotel',
'date' => ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y'),
'qty' => $item->getUnits(),
'iva' => $item->getIva(),
'pax' => '-',
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 2: //Actividades
// El nĆŗmero de personas es considerado en el calculo
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$subtotal = $subtotalService * $days * $item->getUnits();
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $item->getUnits();
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Actividad',
'date' => $dateServ,
'qty' => $item->getUnits(),
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 3: // AV
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'AV',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 4: //Creative
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Creativo',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 5: //Cruise
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Crucero',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 6: //Entertaiment
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Entretenimiento',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 7: // Gifts
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$days = 1;
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Regalos',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 8: //Guide
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Regalos',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 9: //Itineraries
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Itinerarios',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 10: //Lounge -- No Aplica
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
//
// $data_supplier['service'][$i] = array (
// 'id' => $item->getId(),
// 'serviceCatId' => $item->getServiceCatId(),
// 'serviceName' => $item->getName(),
// 'serviceType' => 'Itinerarios',
// 'date' => $dateServ,
// 'qty' => $unitsServ,
// 'iva' => $item->getIva(),
// 'pax' => $item->getPax(),
// 'precioUnit' => $subnetoUnit,
// 'subneto' => $subneto,
// 'subtotal' => $subtotal,
// );
break;
case 11: //Menu
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'MenĆŗ',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 12: //Others
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Otros',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 13: //Transport
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Transporte',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 14: //Technology
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$days = 1;
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'TecnologĆa',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 15: //Assisstant
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Asistente',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 16: //DDR
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1) {
$dateServ = ($item->getDateInAt())->format('d/m/Y') . ' - ' . ($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array(
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'DDR',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
default:
break;
}
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal, 2, PHP_ROUND_HALF_UP);
$neto = round($subneto, 2, PHP_ROUND_HALF_UP);
$arrayItems[] = array(
'type' => 'Service',
'name' => $item->getName(),
'amount' => $neto,
'iva' => $item->getIva(),
'total' => $subtotal,
);
}
switch ($item->getIva()) {
// Acumula IVA
case 21:
$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva() / 100));
break;
case 10:
$data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getIva() / 100));
break;
case 0:
break;
default:
break;
}
}
$totales_neto_all = $totales_neto_all + $neto;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
// Acumula netos totales e IVA
$service['neto'] = $service['neto'] + $neto;
$service['sumSubT'] = $service['sumSubT'] + $subtotal;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
$service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
$i++;
}
$data_supplier['serviceSubTotal'] = array(
'neto' => $service['neto'],
'sumSubT' => $service['sumSubT'],
);
$currency = 'ā¬';
$totales_total = $totales_neto_all + $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
if (!empty($payments)) {
$amount_pay = $data_supplier['paymentSubTotal']['sumSubT'];
} else {
$amount_pay = 0;
}
$totales_all = $totales_total - $amount_pay;
if (empty($dateDocument)){
$dateDocument = new DateTime('now');
}
$data = array(
'id' => $fileId,
'type' => $type,
// 'type' => '',
'number' => $number,
// 'prefix' => $prefix,
'prefix' => 'AVE-'.(new DateTime('now'))->format('dmy').'-'.$invoiceId,
'date' => $dateDocument,
'file' => $file,
'token' => $file->getAccessKey(),
'company' => $company,
'clients' => $client,
'arrayItems' => $arrayItems,
'datasupplier' => $data_supplier,
'currency' => $currency,
'totales_neto' => $totales_neto_all,
'bases_imponibles' => $data_iva,
'totales' => $totales_total,
'balance' => $totales_all,
'paymentInvoice' => $amount_pay,
);
return $data;
}
// Replicar cambios entre FileController y ProductsFilesController
private function calculosFile($id, $arrayBools, $number, $type)
{
// $id Id del Expediente (File)
// $arrayBool arreglo de logicos
// $number *********************
// $type tipo de calculos a realizar (edicion de expediente, factura, factura de deposito, proforma)
$em = $this->getDoctrine()->getManager();
$file = $em->getRepository(AveFiles::class)->findOneById($id);
// $items = $em->getRepository(AveProductFile::class)->findByFileId($file->getId());
// Primero se agrupan por sala (Ubicacion), luego por tipo y finalmente por RankAv
// Salvador Guerrero indico, el orden de los productos en la factura o proforma serĆ” (Video - Sonido - Iluminacion - Otros)
$allProductFile = $em->getRepository(AveProductFile::class)->findByFileId($id);
$arrayLocation = array();
$arrayLocationWithNull = false;
foreach ($allProductFile as $item){
if (!empty($item->getLocation())){
$arrayLocation[$item->getLocation()] = $item->getLocation();
} else {
$arrayLocationWithNull = true;
}
}
if ($arrayLocationWithNull){ $arrayLocation['null'] = 'null'; }
$productsInFile = array();
$items = array();
foreach ($arrayLocation as $item){
// VIDEO
$parameters = array(
'fileId' => $id,
'type' => 'VĆdeo',
'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileVid = $query->getResult();
// SONIDO
$parameters = array(
'fileId' => $id,
'type' => 'Sonido',
'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileSound = $query->getResult();
// ILUMINACION
$parameters = array(
'fileId' => $id,
'type' => 'IluminaciĆ³n',
'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE i.fileId = :fileId AND i.type = :type AND i.location = :location
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileLights = $query->getResult();
// OTROS
$parameters = array(
'fileId' => $id,
'typeV' => 'VĆdeo',
'typeS' => 'Sonido',
'typeI' => 'IluminaciĆ³n',
'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND i.location = :location)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileOther = $query->getResult();
// CASO NULL (Los casos EMPTY estan considerados en las consultas previas)
$parameters = array(
'fileId' => $id,
'location' => $item,
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE (i.fileId = :fileId AND i.type IS NULL AND i.location = :location)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileNull = $query->getResult();
// Para el location en NULL el SQL tiene que ser diferente por eso el siguiente condicional
if ($item == 'null'){
// VIDEO
$parameters = array(
'fileId' => $id,
'type' => 'VĆdeo',
'location' => '',
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileVid = $query->getResult();
// SONIDO
$parameters = array(
'fileId' => $id,
'type' => 'Sonido',
'location' => '',
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileSound = $query->getResult();
// ILUMINACION
$parameters = array(
'fileId' => $id,
'type' => 'IluminaciĆ³n',
'location' => '',
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE i.fileId = :fileId AND i.type = :type AND (i.location IS NULL OR i.location = :location)
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileLights = $query->getResult();
// OTROS
$parameters = array(
'fileId' => $id,
'typeV' => 'VĆdeo',
'typeS' => 'Sonido',
'typeI' => 'IluminaciĆ³n',
'location' => '',
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE (i.fileId = :fileId AND i.type != :typeV AND i.type != :typeS AND i.type != :typeI AND (i.location IS NULL OR i.location = :location))
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileOther = $query->getResult();
// CASO NULL DEL TIPO (Los casos EMPTY estan considerados en las consultas previas)
$parameters = array(
'fileId' => $id,
'location' => '',
);
$dql = 'SELECT i
FROM AvexpressBundle:AveProductFile i
WHERE (i.fileId = :fileId AND i.type IS NULL AND (i.location IS NULL OR i.location = :location))
ORDER BY i.rankAv ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$productsInFileNull = $query->getResult();
}
$items = array_merge($items,$productsInFileVid, $productsInFileSound, $productsInFileLights, $productsInFileOther, $productsInFileNull);
}
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('4');
$client = $em->getRepository(Client::class)->findById($file->getClient());
if (!empty($client)){
$city = ($em->getRepository(Cities::class)->findOneById($client[0]->getPopulation()));
$client[0]->setPopulation($city);
$region = ($em->getRepository(Regions::class)->findOneById($client[0]->getRegion()));
$client[0]->setRegion($region);
$country = ($em->getRepository(Country::class)->findOneById($client[0]->getCountry()));
$client[0]->setCountry($country);
} else {
$client[0] = new Client();
$client[0]->setName('');
$client[0]->setTitle('');
$client[0]->setIdDocument('');
$client[0]->setPopulation('');
$client[0]->setRegion('');
$client[0]->setCountry('');
}
// Acumuladores de los calculos
$totales_neto_all = 0;
$data_iva = array(
'iva' => 21,
'ivaMontoVeintiUno' => 0,
'ivaMontoDiez' => 0,
'ivaMontoCero' => 0,
);
//INICIO: Determinamos el numero de factura o proforma
if (substr($number,0,1) == 'I'){
// Es una Factura
$numberInvoiceOrProforma = substr($number,1);
$number = $numberInvoiceOrProforma;
$type = 'Invoice';
} else {
// Es una Proforma
$numberInvoiceOrProforma = substr($number,1);
$number = $numberInvoiceOrProforma;
$type = 'Proforma';
}
//FIN: Determinamos el numero de factura o proforma
// Buscamos las salas reservadas, pagos y servicios para el evento
$arrayItems = array();
$fileProducts = array();
if (!empty($arrayBools['lounge'])) {
foreach ($arrayBools['lounge'] as $key => $item) {
if ($item == 'true') {
// $fileProducts[] = $em->getRepository('DevelupBundle:ReservationLoungeSimple')->findOneById($key);
}
}
}
$payments = array();
if (!empty($arrayBools['payment'])) {
foreach ($arrayBools['payment'] as $key => $item) {
if ($item == 'true') {
// $payments[] = $em->getRepository('DevelupBundle:ReservationPaymentsClient')->findOneById($key);
}
}
}
$services = array();
if (!empty($arrayBools['service'])) {
foreach ($arrayBools['service'] as $key => $item) {
if ($item == 'true') {
// $services[] = $em->getRepository('DevelupBundle:ReservationService')->findOneById($key);
}
}
}
$data_supplier = array();
$i = 0;
$iva = '21'; // Esteban Rincon: "Por Ley de localizaciĆ³n del impuesto, siempre serĆ” un 21%"
$pax = '-';
$qty = '1';
$product = array(
'neto' => 0,
'sumSubT' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
$service = array(
'neto' => 0,
'sumSubT' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
if (empty($items)){
$data_supplier['product'][0] = null;
}
foreach ($items as $item){
$days = '1';
if (!empty($item->getUnits())){
$qty = $item->getUnits();
}
if (!empty($item->getDays())){
$days = $item->getDays();
}
if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
$subtotal = 0;
$neto = 0;
$subtotalProduct = 0;
} else {
// $subtotalProduct = $item->getServicePrice() * 1.21;
$subtotalProduct = $item->getSubTotalPrice() * 1.21;
// $subneto = $item->getServicePrice();
$subneto = $item->getSubTotalPrice();
$subtotal = $subtotalProduct;
$neto = $subneto;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
$neto = round($neto,2,PHP_ROUND_HALF_UP);
$arrayItems[] = array(
'type' => 'Product',
'name' => $item->getProductName(),
'amount' => $neto,
'iva' => '21',
'total' => $subtotal,
);
}
// Acumula netos totales e IVA
$totales_neto_all = $totales_neto_all + $neto;
switch ($item->getIva()){
case 21: $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21); break;
case 10: $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * 0.1); break;
case 0: $data_iva['ivaMontoCero'] = $data_iva['ivaMontoCero'] + ($neto * 0); break;
default: break;
}
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
// Acumula netos totales e IVA
$product['neto'] = $product['neto'] + $neto;
$product['sumSubT'] = $product['sumSubT'] + $subtotal;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$product['neto'] = round($product['neto'],2,PHP_ROUND_HALF_UP);
$product['sumSubT'] = round($product['sumSubT'],2,PHP_ROUND_HALF_UP);
$data_supplier['product'][$i] = array (
'id' => $item->getId(),
'productName' => $item->getProductName(),
'description' => $item->getDescription(),
'productId' => $item->getProductId(),
'dateStart' => $item->getDateStart(),
'dateEnd' => $item->getDateEnd(),
'servicePrice' => $item->getServicePrice(),
'subTotalPrice' => $item->getSubTotalPrice(),
'subtotalProduct' => $subtotalProduct,
'iva' => $iva,
'pax' => $pax,
'qty' => $qty,
'days' => $days,
'type' => $item->getType(),
'subtotal' => $subtotal,
);
$i++;
}
$data_supplier['productSubTotal'] = array(
'neto' => $product['neto'],
'sumSubT' => $product['sumSubT'],
);
$payment = array(
'sumSubT' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
$i = 0;
foreach ($payments as $item){
$payment['sumSubT'] = $payment['sumSubT'] + $item->getAmountTotal();
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$payment['sumSubT'] = round($payment['sumSubT'],2,PHP_ROUND_HALF_UP);
$data_supplier['payment'][$i] = array (
'id' => $item->getId(),
'amount' => $item->getAmount(),
'amountTotal' => $item->getAmountTotal(),
'vat' => $item->getVat(),
'datePayAt' => $item->getDatePayAt(),
'wayToPay' => $item->getWayToPay(),
);
$arrayItems[] = array(
'type' => 'Payment',
'name' => $item->getWayToPay(),
'amount' => $item->getAmount(),
'total' => $item->getAmountTotal(),
'iva' => $item->getVat(),
);
$i++;
}
if (!empty($payments)) {
$data_supplier['paymentSubTotal'] = array(
'sumSubT' => $payment['sumSubT'],
);
}
foreach ($services as $item){
if (is_null($item->getPrice()) or empty($item->getPrice())){
$subtotal = 0;
$neto = 0;
$subtotalService = 0;
} else {
$subtotalService = $item->getPrice();
$subneto = $item->getPrice();
// Commission
if ($item->getOpCommission()=='1'){
$subtotalService = $subtotalService * (1 + ($item->getCommission()/100));
$subneto = $subneto * (1 + ($item->getCommission()/100));
} else {
$subtotalService = $subtotalService * (1 - ($item->getCommission()/100));
$subneto = $subneto * (1 - ($item->getCommission()/100));
}
// Over
if ($item->getOpOver()=='1'){
$subtotalService = $subtotalService + $item->getOver();
$subneto = $subneto + $item->getOver();
} else {
$subtotalService = $subtotalService - $item->getOver();
$subneto = $subneto - $item->getOver();
}
// IVA
if ($item->getOpIva()=='1'){
$subtotalService = $subtotalService * (1 + ($item->getIva()/100));
} else {
$subtotalService = $item->getPrice();
$subneto = ($subneto * 100) / (100 + $item->getIva());
}
switch ($item->getServiceCatId()){
case 1: // Alojamiento
// el numero de noches $numNoches; precio unitario $subneto
$numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
// La personas no afectan este calculo
$subtotal = $subtotalService * $numNoches * $item->getUnits();
$subnetoUnit = $subneto;
$subneto = $subneto * $numNoches * $item->getUnits();
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Hotel',
'date' => ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y'),
'qty' => $item->getUnits(),
'iva' => $item->getIva(),
'pax' => '-',
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 2: //Actividades
// El nĆŗmero de personas es considerado en el calculo
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$subtotal = $subtotalService * $days * $item->getUnits();
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $item->getUnits();
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Actividad',
'date' => $dateServ,
'qty' => $item->getUnits(),
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 3: // AV
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'AV',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 4: //Creative
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Creativo',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 5: //Cruise
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Crucero',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 6: //Entertaiment
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Entretenimiento',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 7: // Gifts
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$days = 1;
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Regalos',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 8: //Guide
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Regalos',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 9: //Itineraries
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Itinerarios',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 10: //Lounge -- No Aplica
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
//
// $data_supplier['service'][$i] = array (
// 'id' => $item->getId(),
// 'serviceCatId' => $item->getServiceCatId(),
// 'serviceName' => $item->getName(),
// 'serviceType' => 'Itinerarios',
// 'date' => $dateServ,
// 'qty' => $unitsServ,
// 'iva' => $item->getIva(),
// 'pax' => $item->getPax(),
// 'precioUnit' => $subnetoUnit,
// 'subneto' => $subneto,
// 'subtotal' => $subtotal,
// );
break;
case 11: //Menu
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'MenĆŗ',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 12: //Others
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Otros',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 13: //Transport
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Transporte',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 14: //Technology
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$days = 1;
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'TecnologĆa',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 15: //Assisstant
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'Asistente',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
case 16: //DDR
$pax = $item->getPax();
if (empty($pax) or $pax == "0") {
$pax = 1;
}
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
if ($days > 1){
$dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
} else {
$dateServ = ($item->getDateInAt())->format('d/m/Y');
}
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") {
$unitsServ = 1;
}
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subnetoUnit = $subneto;
$subneto = $subneto * $days * $unitsServ * $pax;
$data_supplier['service'][$i] = array (
'id' => $item->getId(),
'serviceCatId' => $item->getServiceCatId(),
'serviceName' => $item->getName(),
'serviceType' => 'DDR',
'date' => $dateServ,
'qty' => $unitsServ,
'iva' => $item->getIva(),
'pax' => $item->getPax(),
'precioUnit' => $subnetoUnit,
'subneto' => $subneto,
'subtotal' => $subtotal,
);
break;
default:
break;
}
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
$neto = round($subneto,2,PHP_ROUND_HALF_UP);
$arrayItems[] = array(
'type' => 'Service',
'name' => $item->getName(),
'amount' => $neto,
'iva' => $item->getIva(),
'total' => $subtotal,
);
}
switch ($item->getIva()){
// Acumula IVA
case 21:
$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva()/100));
break;
case 10:
$data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getIva()/100));
break;
case 0:
break;
default:
break;
}
$totales_neto_all = $totales_neto_all + $neto;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
// Acumula netos totales e IVA
$service['neto'] = $service['neto'] + $neto;
$service['sumSubT'] = $service['sumSubT'] + $subtotal;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
$service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
$i++;
}
$data_supplier['serviceSubTotal'] = array(
'neto' => $service['neto'],
'sumSubT' => $service['sumSubT'],
);
$currency = 'ā¬';
$totales_total = $totales_neto_all + $data_iva['ivaMontoVeintiUno'] + $data_iva['ivaMontoDiez'];
if (!empty($payments)) {
$amount_pay = $data_supplier['paymentSubTotal']['sumSubT'];
} else {
$amount_pay = 0;
}
$totales_all = $totales_total - $amount_pay;
if ($type == 'Invoice'){
$em->clear(); // sin este clear se producia error al guardar
$newInvoice = $em->getRepository(AveDocInvoice::class)->findOneById($numberInvoiceOrProforma);
$newInvoice->setBalance($totales_all);
$em->persist($newInvoice);
$em->flush();
}
$data = array(
'id' => $id,
'type' => $type,
'number' => $number,
'prefix' => 'AVE-'.(new DateTime('now'))->format('dmy').'-',
'date' => new DateTime('now'),
'file' => $file,
'company' => $company,
'clients' => $client,
'arrayItems' => $arrayItems,
'datasupplier' => $data_supplier,
'currency' => $currency,
'totales_neto' => $totales_neto_all,
'bases_imponibles' => $data_iva,
'totales' => $totales_total,
'balance' => $totales_all,
'paymentInvoice' => $amount_pay,
);
return $data;
}
private function sendTelegram($id, $text )
{
$em = $this->getDoctrine()->getManager();
// No es necesario tener una tabla de TelegramUser para el modulo de AvExpress
$telegUser = $em->getRepository(MdvTelegramUser::class)->findOneByUserId($id);
if (empty($telegUser)){return true;}
$parameters = array(
'chat_id' => $telegUser->getChatId(),
'text' => $text,
);
$bot_token = $telegUser->getBotToken();
$url = "https://api.telegram.org/bot$bot_token/sendMessage";
if (!$curl = curl_init()){
exit();
}
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$parameters);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($curl);
curl_close($curl);
return true;
}
private function baseBenefits($fileId){
$em = $this->getDoctrine()->getManager();
// $file = $em->getRepository(AveFiles::class)->findOneById($fileId);
$productsInFile = $em->getRepository(AveProductFile::class)->findByFileId($fileId);
$benefitEuro = 0;
$benefitPerc = 0;
$totalSale = 0;
foreach ($productsInFile as $item){
if(empty($item->getSupplierExt()) or ($item->getSupplierExt() == 'AV EXPRESS S.L.')){
// El proveedor es AV, el beneficio es 100%
$benefitEuro = $benefitEuro + $item->getSubTotalPrice();
} else {
// El proveedor es externo, el beneficio lo determinan el over y la comision
// $subTotalPriceExt = $item->getServicePrice() * $item->getUnits() * $item->getDays(); // Precio sin Over ni Comision
// $benefitEuro = $benefitEuro + ($item->getSubTotalPrice() - $subTotalPriceExt);
$prdPrice = $item->getServicePrice(); if (empty($prdPrice)){ $prdPrice = 0; }
$prdUnits = $item->getUnits(); if (empty($prdUnits)){ $prdUnits = 1; }
$prdDays = $item->getDays(); if (empty($prdDays)){ $prdDays = 1; }
$prdPax = $item->getPax(); if (empty($prdPax)){ $prdPax = 1; }
$subTotalPriceExt = $prdPrice * $prdUnits * $prdDays * $prdPax; // Precio sin Over ni Comision
$benefitEuro = $benefitEuro + ($item->getSubTotalPrice() - $subTotalPriceExt);
}
$totalSale = $totalSale + $item->getSubTotalPrice();
}
// Verificamos beneficios simplificados de proveedores
$simplyBen = $em->getRepository(AveBenefitsSupplier::class)->findByFileId($fileId);
foreach ($simplyBen as $item){ $benefitEuro = $benefitEuro - $item->getBenefitSupplier(); }
if (!($totalSale == 0)){
$benefitPerc = ($benefitEuro * 100)/$totalSale;
}
$data = array(
'id' => $fileId,
'benefitEuro' => $benefitEuro,
'benefitPerc' => $benefitPerc,
);
return $data;
}
private function precioPorVariacionDeDias ($supplierService, $productFile){
// El precio unitario debe ser dividido en funcion de los dias que tiene InOut y no en funcion de los dias de Av Express
$days = ($supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days)===0 ? 1 : $supplierService->getDateOutAt()->diff($supplierService->getDateInAt())->days +1;
$newPrice = $productFile->getSubTotalPrice() / ( $days );
$newPrice = $newPrice / $supplierService->getUnits();
$newPrice = round($newPrice,2,PHP_ROUND_HALF_UP);
return $newPrice;
}
private function rankAvParaInOutService($idProduct){
// con el ID del product buscamos en "ave_doc_invoice_items" con prdControl($idProduct) para determinar la factura, y buscamos elementos dentro de esa factura
// luego si es vacio repetimos para proformas en "ave_doc_proforma_items"
// Devuelve el numero de RankAv considerando la posible asociacion por sala y ordenando segun el criterio (video, sonido, iluminacion, otros)
$em = $this->getDoctrine()->getManager();
$rankAv = 1; $proformaItemsInSameProforma = array(); $boolFound = false;
$invoiceItem = $em->getRepository(AveDocInvoiceItems::class)->findOneByPrdControlId($idProduct);
$invoiceItemsInSameInvoice = (!empty($invoiceItem)) ? $em->getRepository(AveDocInvoiceItems::class)->findByInvoiceId($invoiceItem->getInvoiceId()) : array();
if (empty($invoiceItemsInSameInvoice)){
// No se encontraba facturado, buscamos en proforma el item y los elementos que esten en esa proforma
$proformaItem = $em->getRepository(AveDocProformaItems::class)->findOneByControlId($idProduct);
$proformaItemsInSameProforma = (!empty($proformaItem)) ? $em->getRepository(AveDocProformaItems::class)->findByProformaId($proformaItem->getProformaId()) : array();
}
$arrayItems = empty($invoiceItemsInSameInvoice) ? $proformaItemsInSameProforma : $invoiceItemsInSameInvoice;
foreach ($arrayItems as $item){
$idToCheck = empty($invoiceItemsInSameInvoice) ? $item->getControlId() : $item->getPrdControlId();
if (!($idToCheck == $idProduct)){ if(!($boolFound)){ $rankAv++;} } else { $boolFound = true; }
}
// 001, 002, ... 010, 011, ..., 100, 101
$rankAv = ($rankAv < 100) ? (($rankAv < 10) ? '00'. $rankAv : '0'. $rankAv) : $rankAv;
return $rankAv;
}
private function messageOfChangesToAgent($message, $proposalId){
// $message mensaje a enviar a los agentes del proposal
if ($proposalId == 0){ return true; }
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($proposalId);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$agent = $em->getRepository(User::class)->findOneById($user_id);
$message = 'El proposal <strong>#'.$proposalId.' '.$proposal->getName().'</strong>'.' ha sido modificacdo por el agente: '.$agent->getName().' '.$agent->getLastName().'<br><br><br>'.$message;
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
$mailArrayTo = array();
if (!empty($agent)){ $mailArrayTo[$agent->getEmail()] = $agent->getEmail(); }
if (!empty($proposalAgents)){
if (!empty($proposalAgents->getAgOne())){
$agent = $em->getRepository(User::class)->findOneById($proposalAgents->getAgOne());
$mailArrayTo[$agent->getEmail()] = $agent->getEmail();
}
if (!empty($proposalAgents->getAgTwo())){
$agent = $em->getRepository(User::class)->findOneById($proposalAgents->getAgTwo());
$mailArrayTo[$agent->getEmail()] = $agent->getEmail();
}
if (!empty($proposalAgents->getAgThree())){
$agent = $em->getRepository(User::class)->findOneById($proposalAgents->getAgThree());
$mailArrayTo[$agent->getEmail()] = $agent->getEmail();
}
if (!empty($proposalAgents->getAgFour())){
$agent = $em->getRepository(User::class)->findOneById($proposalAgents->getAgFour());
$mailArrayTo[$agent->getEmail()] = $agent->getEmail();
}
}
if (!empty($mailArrayTo)){
$mailArrayTo[$agent->getEmail()] = $agent->getEmail();
$replyTo = array();
foreach ($mailArrayTo as $item){ $replyTo[$item] = $item; }
$agentMail = $agent->getEmail();
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $message,
'firm' => $firmGmail,
);
// EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername('desarrollo@develup.solutions')
->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('ActualizaciĆ³n de servicios AvExpress del proposal: '. $proposalId)
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($replyTo)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
return true;
}
};