<?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\Supplier;
use App\Entity\User;
use App\MDS\AvexpressBundle\Entity\AveDocInvoiceItems;
use App\MDS\AvexpressBundle\Entity\AveDocProforma;
use App\MDS\AvexpressBundle\Entity\AveDocProformaItems;
use App\MDS\AvexpressBundle\Entity\AveFiles;
use App\MDS\AvexpressBundle\Entity\AveProduct;
use App\MDS\AvexpressBundle\Entity\AveProductFileLocationNames;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use App\MDS\AvexpressBundle\Entity\AveProductFile;
use App\MDS\AvexpressBundle\Entity\AveTemplate;
use App\MDS\AvexpressBundle\Entity\AveTemplateItems;
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 App\MDS\GreenPatioBundle\Entity\ReservationInvoice;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Contracts\Translation\TranslatorInterface;
class ProductsFilesController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/**
* @Route("/productfileadd/", name="ave_add_productfile")
* Agregar un producto a un expediente
*/
public function addProductFileAction( Request $request)
{
$em = $this->getDoctrine()->getManager();
$clients = $em->getRepository(Client::class)->findAll();
$newRequest = $request->request->get('productfile');
$editFile = $em->getRepository(AveFiles::class)->findOneById($newRequest['fileId']);
$mdvProductSelected = $em->getRepository(AveProduct::class)->findOneById($newRequest['productId']);
$logTelegram = false;
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$newProductFile = new AveProductFile();
$newProductFile->setProductName($mdvProductSelected->getName());
$newProductFile->setProductId($mdvProductSelected->getId());
$newProductFile->setType($mdvProductSelected->getType());
if (!empty($newRequest['servicePrice'])){
$newProductFile->setServicePrice($newRequest['servicePrice']);
} else {
// Si el precio viene vacio tomamos el valor por defecto del producto
$newProductFile->setServicePrice($mdvProductSelected->getPrice());
}
$newProductFile->setDescription($mdvProductSelected->getDescription());
$newProductFile->setFileId($newRequest['fileId']);
if (!empty($newRequest['dateStart'])) { $newProductFile->setDateStart(new \DateTime($newRequest['dateStart'].' '.$newRequest['hourStart'])); }
if (!empty($newRequest['dateEnd'])) { $newProductFile->setDateEnd(new \DateTime($newRequest['dateStart'].' '.$newRequest['hourEnd'])); }
$dataDates = $this->obtenerFechas($newRequest['fileId'], $newProductFile->getDateStart(), $newProductFile->getDateEnd());
$newProductFile->setDateStart($dataDates['dateStart']);
$newProductFile->setDateEnd($dataDates['dateEnd']);
$newProductFile->setDateInAt($dataDates['dateStart']);
$newProductFile->setDateOutAt($dataDates['dateEnd']);
$newProductFile->setCreatedId($user_id);
$newProductFile->setUpdatedId($user_id);
$newProductFile->setCreatedAt(new \DateTime("now"));
$newProductFile->setUpdatedAt(new \DateTime("now"));
$newProductFile->setOpIva(true);
$newProductFile->setIva('21');
if (!empty($newRequest['supplierExt'])){
$supplier = $em->getRepository(Supplier::class)->findOneById($newRequest['supplierExt']);
$newProductFile->setSupplierExt($supplier->getName());
$newProductFile->setSupplierExtId($newRequest['supplierExt']);
} else {
$newProductFile->setSupplierExt(null);
$newProductFile->setSupplierExtId(null);
}
if (empty($newProductFile->getType())){ $newProductFile->setType('Otros'); }
$dataRankAv = $this->obtenerRankAv($newRequest['fileId']);
$newProductFile->setRankAv($dataRankAv);
$newProductFile->setDays((($newProductFile->getDateEnd()->diff($newProductFile->getDateStart()))->days + 1));
$em->persist($newProductFile);
$em->flush();
$products = $em->getRepository(AveProduct::class)->findAll();
$data = $this->calculosFile($newRequest['fileId'], null, 0, 'File');
$sumatoriaTotalNet = 0;
$sumatoriaTotalVat = 0;
$sumatoriaTotal = 0;
$resultados = array(
'totalNeto' => $sumatoriaTotalNet,
'vat' => $sumatoriaTotalVat,
'total' => $sumatoriaTotal,
);
$productInFile = $em->getRepository(AveProductFile::class)->findByFileId($newRequest['fileId']);
$numeroItems = sizeof($productInFile);
$file = $editFile;
// 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(),
)
);
if (!empty($control)){
// Existe un destino con Avexpress como proveedor, hay se agregara el servicio
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
$logTelegram = true;
$service = new ProposalSupplierServices();
$service->setServiceIdFather(0);
$service->setControlId($control->getId());
$service->setProposalId($file->getIdProposal());
$service->setDestinationId($control->getDestinoId());
$service->setSupplierId(80);
$service->setIdeaId(null);
$service->setServiceId($newProductFile->getProductId());
$service->setServiceCatName('Av');
$service->setServiceCatId(3);
$service->setName($newProductFile->getProductName());
// $service->setPrice($mdvProductSelected->getPrice() * 1.21);
$priceInOut = $mdvProductSelected->getSubTotalPrice() / $mdvProductSelected->getPax(); // Se devuelve el calculo dividiendo entre personas
$priceInOut = $priceInOut / $mdvProductSelected->getUnits(); // Se devuelve el calculo dividiendo entre cantidades
$priceInOut = $priceInOut / round($mdvProductSelected->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->setPrice($mdvProductSelected->getPrice());
$service->setCurrency(null);
$service->setUnits(1);
$service->setCommission(0);
$service->setOver(0);
$service->setIva(21);
$service->setPax(0);
$service->setHour(null);
$service->setDateInAt(new \DateTime("now"));
$service->setDateOutAt(new \DateTime("now"));
$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(1);
$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();
// Guardamos el ID del servicio (Eventos) asociado al producto (AvExpress)
$newProductFile->setOriginId($service->getId());
$em->persist($newProductFile);
$em->flush();
}
}
}
//INICIO: Notificamos al agente por Telegram
if ($logTelegram){
//Buscamos todos los agentes del proposal
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
//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 (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ 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 (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ 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 (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ 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 (Nuevo Servicio) __ ID: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
}
}
//FIN: Notificamos al agente por Telegram
return $this->render('MDS/AvexpressBundle/Avexpress/edit-files.html.twig',
array(
'id' => $newRequest['fileId'],
'clients' => $clients,
'clientId' => $editFile->getClient(),
'file' => $editFile,
'products' => $products,
'numeroItems' => $numeroItems,
'arrayProductFile' => $data['datasupplier']['product'],
'services' => null,
'facturas' => null,
'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'],
));
}
/**
* @Route("/productfiledelete/{id}", name="ave_delete_productfile")
* Eliminar un producto de un expediente
*/
public function deleteProductFileAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$mdvProductSelected = $em->getRepository(AveProductFile::class)->findOneById($id);
$id = $mdvProductSelected->getFileId();
$logTelegram = false;
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
//INICIO: Si hay un ID origin se debe eliminar en Eventos
if (!empty($mdvProductSelected->getOriginId())){
$logTelegram = true;
$delete = $em->getRepository(ProposalSupplierServices::class)->findOneById($mdvProductSelected->getOriginId());
if (!empty($delete)) {
$destinationId = $delete->getDestinationId();
$proposalId = $delete->getProposalId();
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($delete->getProposalId());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
if (!empty($delete)) {
$delete_sub = $em->getRepository(ProposalSupplierServices::class)->findByServiceIdFather($delete->getId());
foreach ($delete_sub as $deletesub) {
$em->remove($deletesub);
}
$em->remove($delete);
$em->flush();
}
}
} else {
// El servicio origen no se encontro
$logTelegram = false;
}
}
//INICIO: Notificamos al agente por Telegram
if ($logTelegram){
//Buscamos todos los agentes del proposal
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
//Buscamos el Destino
$proposalDestino = $em->getRepository(Destination::class)->findOneById($destinationId);
//Buscamos el agente de Develup
$userData = $em->getRepository(User::class)->findOneById($user_id);
if (!empty($proposalAgents)){
if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
$this->sendTelegram($proposalAgents->getAgOne(),'1. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
$this->sendTelegram($proposalAgents->getAgTwo(),'2. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
$this->sendTelegram($proposalAgents->getAgThree(),'3. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
$this->sendTelegram($proposalAgents->getAgFour(),'4. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
}
}
//FIN: Notificamos al agente por Telegram
//FIN: Si hay un ID origin se debe eliminar en Eventos
//INICIO: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiƩn
$productInProforma = $em->getRepository(AveDocProformaItems::class)->findByControlId($mdvProductSelected->getId());
if (!empty($productInProforma)){
foreach ($productInProforma as $item){
$item->setFileId((-1) * $item->getFileId()); // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
$em->persist($item);
// $em->remove($item);
$em->flush();
}
}
//FIN: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiƩn
$mdvProductSelected->setFileId((-1) * $mdvProductSelected->getFileId()); // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
$em->persist($mdvProductSelected);
// $em->remove($mdvProductSelected);
$em->flush();
return $this->redirectToRoute('ave_edit_file', array('id' => $id));
}
/**
* @Route("/productfileproformadelete/{id}", name="ave_delete_productfileproforma")
* Eliminar un producto de una proforma
*/
public function deleteProductFileInProformaAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$mdvProductSelected = $em->getRepository(AveDocProformaItems::class)->findOneByControlId($id);
$id = $mdvProductSelected->getFileId();
$em->remove($mdvProductSelected);
$em->flush();
return $this->redirectToRoute('ave_edit_file', array('id' => $id));
}
/**
* @Route("/updateproductfilegrid/", name="ave_updategrid_productfile")
* Actualizar grid de productos de un expediente
*/
public function updategridProductFileAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$newRequest = $request->request->get('product');
$fileId = $request->request->get('fileId');
$logTelegram = false;
$srvInconsistentes = ''; // Mensaje de alerta por inconsistencia en los servicios
$txtOfChanges = '';
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
foreach ($newRequest as $key => $item) {
$txtWarning = '';
if (!empty($item['name'])){
if (is_numeric($item['price'])){
$logTelegram = true;
$productInFile = $em->getRepository(AveProductFile::class)->findOneById($key);
$productInFile->setProductName($item['name']);
$productInFile->setServicePrice($item['price']);
$productInFile->setUnits($item['units']);
$productInFile->setDays($item['days']);
$productInFile->setSubTotalPrice($item['price'] * $item['units'] *$item['days']);
// *** Primero se debe calcular la comision y luego el over ***
// Calculo de comision
if ($productInFile->getOpCommission()){
//Over positivo
if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
$suma = $productInFile->getCommission()/100;
$suma = $productInFile->getSubTotalPrice() * $suma;
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $suma);
}
} else {
//Over negativo
if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
$suma = $productInFile->getCommission()/100;
$suma = $productInFile->getSubTotalPrice() * $suma;
if ($productInFile->getSubTotalPrice() > $suma){ // La comision a restar no puede ser mayor que el precio total
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() - $suma);
}
}
}
// Calculo con OVER
if ($productInFile->getOpOver()){
//Over positivo
if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $productInFile->getOver());
}
} else {
//Over negativo
if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + ((-1) * $productInFile->getOver()));
}
}
// IVA
// $productInFile->setDescription($item['description']);
$productInFile->setUpdatedId($user_id);
$productInFile->setUpdatedAt(new \DateTime("now"));
//Si las fechas de inicio y fin no coinciden con el campo dias se debe enviar alerta
$txtWarning = ($productInFile->getDateOutAt()->diff($productInFile->getDateInAt()))->days + 1 <> $productInFile->getDays() ? '<br>'.$productInFile->getProductName() : '';
if (!empty($txtWarning)){
if (empty($srvInconsistentes)){ $srvInconsistentes = 'Hay inconsistencias en: '.'<br>'.$txtWarning; } else { $srvInconsistentes = $srvInconsistentes.'<br>'.$txtWarning; }
}
$em->persist($productInFile);
$em->flush();
//INICIO: Duplicamos en Eventos
$proposalId = 0;
if (!empty($productInFile->getOriginId())) {
$serviceEvent = $em->getRepository(ProposalSupplierServices::class)->findOneById($productInFile->getOriginId());
$oldServiceEvent = array(
'activityId' => $serviceEvent->getActivityId(),
'assistantId' => $serviceEvent->getAssistantId(),
'breakdown' => $serviceEvent->getBreakdown(),
'commission' => $serviceEvent->getCommission(),
'controlId' => $serviceEvent->getControlId(),
'currency' => $serviceEvent->getCurrency(),
'dateBlockLimit' => $serviceEvent->getDateBlockLimit(),
'dateInAt' => $serviceEvent->getDateInAt(),
'dateOutAt' => $serviceEvent->getDateOutAt(),
'destinationId' => $serviceEvent->getDestinationId(),
'directPayment' => $serviceEvent->getDirectPayment(),
'hour' => $serviceEvent->getHour(),
'ideaId' => $serviceEvent->getIdeaId(),
'isFather' => $serviceEvent->getIsFather(),
'iva' => $serviceEvent->getIva(),
'name' => $serviceEvent->getName(),
'opCommission' => $serviceEvent->getOpCommission(),
'opIva' => $serviceEvent->getOpIva(),
'opOver' => $serviceEvent->getOpOver(),
'originalIva' => $serviceEvent->getOriginalIva(),
'originalPrice' => $serviceEvent->getOriginalPrice(),
'originalopIva' => $serviceEvent->getOriginalopIva(),
'over' => $serviceEvent->getOver(),
'pax' => $serviceEvent->getPax(),
'preCommission' => $serviceEvent->getPreCommission(),
'preIva' => $serviceEvent->getPreIva(),
'price' => $serviceEvent->getPrice(),
'proposalId' => $serviceEvent->getProposalId(),
'rank' => $serviceEvent->getRank(),
'serviceCatId' => $serviceEvent->getServiceCatId(),
'serviceCatName' => $serviceEvent->getServiceCatName(),
'serviceId' => $serviceEvent->getServiceId(),
'serviceIdFather' => $serviceEvent->getServiceIdFather(),
'status' => $serviceEvent->getStatus(),
'statusRec' => $serviceEvent->getStatusRec(),
'statusinternal' => $serviceEvent->getStatusinternal(),
'supplierId' => $serviceEvent->getSupplierId(),
'units' => $serviceEvent->getUnits(),
);
if (!empty($serviceEvent)) {
$proposalId = $serviceEvent->getProposalId();
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($serviceEvent->getProposalId());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
// $serviceEvent->setUnits(1); // Las unidades no se pueden replicar o se genera un sobre calculo del lado de Evenetos
$serviceEvent->setName($productInFile->getProductName());
$priceInOut = $productInFile->getSubTotalPrice();
if (!($productInFile->getPax() == 0)) {
$priceInOut = $priceInOut / $productInFile->getPax(); // Se devuelve el calculo dividiendo entre personas
}
if (!($productInFile->getUnits() == 0)) {
$priceInOut = $priceInOut / $productInFile->getUnits(); // Se devuelve el calculo dividiendo entre cantidades
}
if (!($productInFile->getDays() == 0)) {
$priceInOut = $priceInOut / round($productInFile->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);
$serviceEvent->setPrice($priceInOut);
// Se verifican los precios en ambas partes (AV Express e InOut)
if (!($serviceEvent->getPrice() == $productInFile->getServicePrice())) {
// Si ambos precios unitarios son distintos se ha modificado el numero de dĆas en Av Express
$newPriceInOut = $this->precioPorVariacionDeDias($serviceEvent, $productInFile);
$serviceEvent->setPrice($newPriceInOut);
} else {
// si son iguales tambien se deben verificar el numero de dias
if (!(($serviceEvent->getDateOutAt()->diff($serviceEvent->getDateInAt())->days + 1) == $productInFile->getDays())) {
$newPriceInOut = $this->precioPorVariacionDeDias($serviceEvent, $productInFile);
$serviceEvent->setPrice($newPriceInOut);
}
}
$serviceEvent->setCurrency($productInFile->getCurrency());
$serviceEvent->setUnits($productInFile->getUnits());
// $serviceEvent->setIva(21);
if (empty($productInFile->getPax())) {
$serviceEvent->setPax(1);
} else {
$serviceEvent->setPax($productInFile->getPax());
}
$serviceEvent->setDateInAt($productInFile->getDateInAt());
$serviceEvent->setDateOutAt($productInFile->getDateOutAt());
//Verificamos cambios e informamos al agente del proposal
$boolChanges = false;
if (!($serviceEvent->getRank() == $oldServiceEvent['rank'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Orden</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['rank'].', su nuevo valor es: '.$serviceEvent->getRank().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getName() == $oldServiceEvent['name'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Nombre</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['name'].', su nuevo valor es: '.$serviceEvent->getName().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getPrice() == $oldServiceEvent['price'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Precio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['price'].', su nuevo valor es: '.$serviceEvent->getPrice().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getCurrency() == $oldServiceEvent['currency'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Moneda</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['currency'].', su nuevo valor es: '.$serviceEvent->getCurrency().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getUnits() == $oldServiceEvent['units'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Cantidad</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['units'].', su nuevo valor es: '.$serviceEvent->getUnits().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getPax() == $oldServiceEvent['pax'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Personas</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['pax'].', su nuevo valor es: '.$serviceEvent->getPax().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOpOver() == $oldServiceEvent['opOver'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpOver().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOver() == $oldServiceEvent['over'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['over'].', su nuevo valor es: '.$serviceEvent->getOver().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOpCommission() == $oldServiceEvent['opCommission'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpCommission().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getCommission() == $oldServiceEvent['commission'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>ComisiĆ³n" ha sido modificado. Su valor era: '.$oldServiceEvent['commission'].', su nuevo valor es: '.$serviceEvent->getCommission().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOpIva() == $oldServiceEvent['opIva'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpIva().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getIva() == $oldServiceEvent['iva'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['iva'].', su nuevo valor es: '.$serviceEvent->getIva().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateInAt()->format('H:i') == $oldServiceEvent['dateInAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('H:i').'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateInAt()->format('Ymd') == $oldServiceEvent['dateInAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('d/m/Y').'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateOutAt()->format('H:i') == $oldServiceEvent['dateOutAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('H:i').'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateOutAt()->format('Ymd') == $oldServiceEvent['dateOutAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('d/m/Y').'<br>'; $boolChanges = true; }
$em->persist($serviceEvent);
$em->flush();
}
}
}
//FIN: Duplicamos en Eventos
}
}
}
// Notificamos al agente de InOut si se hicieron actualizaciones en los servicios desde AvExpress
if (!empty($txtOfChanges)) { $this->messageOfChangesToAgent($txtOfChanges, $proposalId); }
$file = $em->getRepository(AveFiles::class)->findOneById($fileId);
$event = 'Servicios guardados correctamente.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeav', $successMessage);
if (!empty($srvInconsistentes) and !empty($file->getIdProposal())){ $this->addFlash('mensajeaverror', $srvInconsistentes); }
// Si el proposalId esta vacio no se notifica a nadie por Telegram
if (empty($file->getIdProposal())){$logTelegram = false;}
//INICIO: Notificamos al agente por Telegram
if ($logTelegram){
//Buscamos todos los agentes del proposal
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
//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 (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
$this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
$this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
$this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
}
}
//FIN: Notificamos al agente por Telegram
return $this->redirectToRoute('ave_edit_file', array('id' => $fileId));
}
/**
* @Route("/updateproductfilegridtwo/", name="ave_update_productfile_grid_two")
* Editar todos los producto de un expediente con todos sus campos
*/
public function updateProductFileGridTwoAction(Request $request){
$em = $this->getDoctrine()->getManager();
$newRequest = $request->request->get('services');
$fileId = $request->request->get('fileId');
$logTelegram = false;
$srvInconsistentes = ''; // Mensaje de alerta por inconsistencia en los servicios
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$txtOfChanges = ''; $boolNotifyOfChanges = false; $proposalId = 0;
foreach ($newRequest as $item) {
$productInFile = $em->getRepository(AveProductFile::class)->findOneById($item['productFileId']);
$logTelegram = true;
$txtWarning = '';
$productInFile->setProductName($item['name']);
$productInFile->setServicePrice($item['price']);
// $productInFile->setDescription($item['description']);
$productInFile->setCurrency($item['currency']);
$productInFile->setUnits($item['units']);
$productInFile->setType($item['prdType']);
$productInFile->setLocation($item['location']);
$productInFile->setRankAv(intval($item['rankAv']));
if (array_key_exists('dateInAt',$item)){
$productInFile->setDateStart(new \DateTime($item['dateInAt']));
$productInFile->setDateInAt(new \DateTime($item['dateInAt']));
} else {
// No se requiere accion
}
if (array_key_exists('dateOutAt',$item)){
$productInFile->setDateEnd(new \DateTime($item['dateOutAt']));
$productInFile->setDateOutAt(new \DateTime($item['dateOutAt']));
} else {
// No se requiere accion
}
if (empty($item['days'])){
// $productInFile->setDays($days = (((new \DateTime($item['dateOutAt']))->diff(new \DateTime($item['dateInAt'])))->days + 1));
$productInFile->setDays($days = (($productInFile->getDateOutAt()->diff($productInFile->getDateInAt()))->days + 1));
} else {
$productInFile->setDays($item['days']);
}
$productInFile->setPax($item['pax']);
$productInFile->setOpCommission($item['opCommission']);
$productInFile->setCommission($item['commission']);
$productInFile->setOpOver($item['opOver']);
$productInFile->setOver($item['over']);
$productInFile->setOpIva($item['opIva']);
$productInFile->setIva($item['iva']);
if (!empty($item['supplierExt'])){
$supplier = $em->getRepository(Supplier::class)->findOneById($item['supplierExt']);
$productInFile->setSupplierExt($supplier->getName());
$productInFile->setSupplierExtId($item['supplierExt']);
} else {
$productInFile->setSupplierExt(null);
$productInFile->setSupplierExtId(null);
}
$productInFile->setHourStart(substr($item['start'],0,2));
$productInFile->setMinStart(substr($item['start'],3,2));
$productInFile->setHourEnd(substr($item['end'],0,2));
$productInFile->setMinEnd(substr($item['end'],3,2));
$productInFile->setUpdatedId($user_id);
$productInFile->setUpdatedAt(new \DateTime("now"));
$productInFile->setSubTotalPrice($productInFile->getServicePrice());
//INICIO: Validaciones para el sub total
if (is_numeric($productInFile->getUnits())){
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() * $productInFile->getUnits());
}
if (is_numeric($productInFile->getPax())){
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() * $productInFile->getPax());
}
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() * $productInFile->getDays());
// *** Primero se debe calcular la comision y luego el over ***
// Calculo de comision
if ($productInFile->getOpCommission()){
//Over positivo
if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
$suma = $productInFile->getCommission()/100;
$suma = $productInFile->getSubTotalPrice() * $suma;
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $suma);
}
} else {
//Over negativo
if (!($productInFile->getCommission() == 0) and is_numeric($productInFile->getCommission())){
$suma = $productInFile->getCommission()/100;
$suma = $productInFile->getSubTotalPrice() * $suma;
if ($productInFile->getSubTotalPrice() > $suma){ // La comision a restar no puede ser mayor que el precio total
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() - $suma);
}
}
}
// Calculo con OVER
if ($productInFile->getOpOver()){
//Over positivo
if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + $productInFile->getOver());
}
} else {
//Over negativo
if (!($productInFile->getOver() == 0) and is_numeric($productInFile->getOver())){
$productInFile->setSubTotalPrice($productInFile->getSubTotalPrice() + ((-1) * $productInFile->getOver()));
}
}
// IVA
//FIN: Validaciones para el sub total
//Si las fechas de inicio y fin no coinciden con el campo dias se debe enviar alerta
$txtWarning = ($productInFile->getDateOutAt()->diff($productInFile->getDateInAt()))->days + 1 <> $productInFile->getDays() ? '<br>'.$productInFile->getProductName() : '';
if (!empty($txtWarning)){
if (empty($srvInconsistentes)){ $srvInconsistentes = 'Hay inconsistencias en: '.'<br>'.$txtWarning; } else { $srvInconsistentes = $srvInconsistentes.'<br>'.$txtWarning; }
}
$em->persist($productInFile);
$em->flush();
$em->clear();
//INICIO: Duplicamos en Eventos (SINCRONIZACION)
if (!empty($productInFile->getOriginId())){
$serviceEvent = $em->getRepository(ProposalSupplierServices::class)->findOneById($productInFile->getOriginId());
$proposalId = $serviceEvent->getProposalId();
$oldServiceEvent = array(
'activityId' => $serviceEvent->getActivityId(),
'assistantId' => $serviceEvent->getAssistantId(),
'breakdown' => $serviceEvent->getBreakdown(),
'commission' => $serviceEvent->getCommission(),
'controlId' => $serviceEvent->getControlId(),
'currency' => $serviceEvent->getCurrency(),
'dateBlockLimit' => $serviceEvent->getDateBlockLimit(),
'dateInAt' => $serviceEvent->getDateInAt(),
'dateOutAt' => $serviceEvent->getDateOutAt(),
'destinationId' => $serviceEvent->getDestinationId(),
'directPayment' => $serviceEvent->getDirectPayment(),
'hour' => $serviceEvent->getHour(),
'ideaId' => $serviceEvent->getIdeaId(),
'isFather' => $serviceEvent->getIsFather(),
'iva' => $serviceEvent->getIva(),
'name' => $serviceEvent->getName(),
'opCommission' => $serviceEvent->getOpCommission(),
'opIva' => $serviceEvent->getOpIva(),
'opOver' => $serviceEvent->getOpOver(),
'originalIva' => $serviceEvent->getOriginalIva(),
'originalPrice' => $serviceEvent->getOriginalPrice(),
'originalopIva' => $serviceEvent->getOriginalopIva(),
'over' => $serviceEvent->getOver(),
'pax' => $serviceEvent->getPax(),
'preCommission' => $serviceEvent->getPreCommission(),
'preIva' => $serviceEvent->getPreIva(),
'price' => $serviceEvent->getPrice(),
'proposalId' => $serviceEvent->getProposalId(),
'rank' => $serviceEvent->getRank(),
'serviceCatId' => $serviceEvent->getServiceCatId(),
'serviceCatName' => $serviceEvent->getServiceCatName(),
'serviceId' => $serviceEvent->getServiceId(),
'serviceIdFather' => $serviceEvent->getServiceIdFather(),
'status' => $serviceEvent->getStatus(),
'statusRec' => $serviceEvent->getStatusRec(),
'statusinternal' => $serviceEvent->getStatusinternal(),
'supplierId' => $serviceEvent->getSupplierId(),
'units' => $serviceEvent->getUnits(),
);
if (!empty($serviceEvent)) {
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($serviceEvent->getProposalId());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
$serviceEvent->setName($productInFile->getProductName());
// Se verifican los precios en ambas partes (AV Express e InOut)
if (!($serviceEvent->getPrice() == $productInFile->getServicePrice())) {
// Si ambos precios unitarios son distintos se ha modificado el numero de dĆas en Av Express
$newPriceInOut = $this->precioPorVariacionDeDias($serviceEvent, $productInFile);
$serviceEvent->setPrice($newPriceInOut);
} else {
// si son iguales tambien se deben verificar el numero de dias
if (!(($serviceEvent->getDateOutAt()->diff($serviceEvent->getDateInAt())->days + 1) == $productInFile->getDays())) {
$newPriceInOut = $this->precioPorVariacionDeDias($serviceEvent, $item);
$serviceEvent->setPrice($newPriceInOut);
}
}
$serviceEvent->setCurrency($productInFile->getCurrency());
$serviceEvent->setUnits($productInFile->getUnits());
if (empty($productInFile->getPax())) {
$serviceEvent->setPax(1);
} else {
$serviceEvent->setPax($productInFile->getPax());
}
$serviceEvent->setDateInAt($productInFile->getDateInAt());
$serviceEvent->setDateOutAt($productInFile->getDateOutAt());
// Se verifican los precios en ambas partes (AV Express e InOut)
if (!($serviceEvent->getPrice() == $productInFile->getServicePrice())) {
// Si ambos precios unitarios son distintos se ha modificado el numero de dĆas en Av Express
$newPriceInOut = $this->precioPorVariacionDeDias($serviceEvent, $productInFile);
$serviceEvent->setPrice($newPriceInOut);
} else {
// si son iguales tambien se deben verificar el numero de dias
if (!(($serviceEvent->getDateOutAt()->diff($serviceEvent->getDateInAt())->days + 1) == $productInFile->getDays())) {
$newPriceInOut = $this->precioPorVariacionDeDias($serviceEvent, $productInFile);
$serviceEvent->setPrice($newPriceInOut);
}
}
//Verificamos cambios e informamos al agente del proposal
$boolChanges = false;
if (!($serviceEvent->getRank() == $oldServiceEvent['rank'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Orden</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['rank'].', su nuevo valor es: '.$serviceEvent->getRank().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getName() == $oldServiceEvent['name'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Nombre</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['name'].', su nuevo valor es: '.$serviceEvent->getName().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getPrice() == $oldServiceEvent['price'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Precio</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['price'].', su nuevo valor es: '.$serviceEvent->getPrice().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getCurrency() == $oldServiceEvent['currency'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Moneda</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['currency'].', su nuevo valor es: '.$serviceEvent->getCurrency().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getUnits() == $oldServiceEvent['units'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Cantidad</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['units'].', su nuevo valor es: '.$serviceEvent->getUnits().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getPax() == $oldServiceEvent['pax'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Personas</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['pax'].', su nuevo valor es: '.$serviceEvent->getPax().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOpOver() == $oldServiceEvent['opOver'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpOver().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOver() == $oldServiceEvent['over'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Over</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['over'].', su nuevo valor es: '.$serviceEvent->getOver().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOpCommission() == $oldServiceEvent['opCommission'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpCommission().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getCommission() == $oldServiceEvent['commission'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>ComisiĆ³n" ha sido modificado. Su valor era: '.$oldServiceEvent['commission'].', su nuevo valor es: '.$serviceEvent->getCommission().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getOpIva() == $oldServiceEvent['opIva'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getOpIva().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getIva() == $oldServiceEvent['iva'])){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->getName().'<br>'; } $txtOfChanges = $txtOfChanges . '<br><br>El campo "<strong>Iva</strong>" ha sido modificado. Su valor era: '.$oldServiceEvent['iva'].', su nuevo valor es: '.$serviceEvent->getIva().'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateInAt()->format('H:i') == $oldServiceEvent['dateInAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('H:i').'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateInAt()->format('Ymd') == $oldServiceEvent['dateInAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateInAt()->format('d/m/Y').'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateOutAt()->format('H:i') == $oldServiceEvent['dateOutAt']->format('H:i'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('H:i').'<br>'; $boolChanges = true; }
if (!($serviceEvent->getDateOutAt()->format('Ymd') == $oldServiceEvent['dateOutAt']->format('Ymd'))){ if (!$boolChanges){ $txtOfChanges = $txtOfChanges.'<br><br>En el servicio: '.$serviceEvent->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: '.$serviceEvent->getDateOutAt()->format('d/m/Y').'<br>'; $boolChanges = true; }
$em->persist($serviceEvent);
$em->flush();
$em->clear();
}
}
}
//FIN: Duplicamos en Eventos
}
// Notificamos al agente de InOut si se hicieron actualizaciones en los servicios desde AvExpress
if (!empty($txtOfChanges)) { $this->messageOfChangesToAgent($txtOfChanges, $proposalId); }
$file = $em->getRepository(AveFiles::class)->findOneById($fileId);
$event = 'Servicios guardados correctamente.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeav', $successMessage);
if (!empty($srvInconsistentes) and !empty($file->getIdProposal())){ $this->addFlash('mensajeaverror', $srvInconsistentes); }
// Si el proposalId esta vacio no se notifica a nadie por Telegram
if (empty($file->getIdProposal())){$logTelegram = false;}
//INICIO: Notificamos al agente por Telegram
if ($logTelegram){
//Buscamos todos los agentes del proposal
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
//Buscamos el Destino
// $proposalDestino = $em->getRepository(Destination::class)->findOneById($control->getDestinoId());
//Buscamos el agente de Develup
$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 (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
$this->sendTelegram($proposalAgents->getAgTwo(),'2. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
$this->sendTelegram($proposalAgents->getAgThree(),'3. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
$this->sendTelegram($proposalAgents->getAgFour(),'4. PROPOSAL ACTUALIZADO DESDE AVEXPRESS (GRID2) __ ID: '.$file->getIdProposal().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
}
}
//FIN: Notificamos al agente por Telegram
return $this->redirectToRoute('ave_edit_file', array('id' => $fileId));
}
/**
* @Route("/productfilelistmultiple/{id}", name="ave_list_multiple_productfile")
* Listar multiples productos para agregar en el expediente id
*/
public function listMultipleProductFileAction( $id, Request $request){
$em = $this->getDoctrine()->getManager();
// $avs = $em->getRepository(AveProduct::class)->findAll();
// Listamos por orden alfabetico y se deja de primero a "Otro servicio"
$parameters = array();
$dql = 'SELECT i
FROM AvexpressBundle:AveProduct i
ORDER BY i.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$avs = $query->getResult();
$newAvs = array();
foreach ($avs as $key => $item) {
if ($item->getName() == 'Otro servicio'){
$item->setName('0 - Otro servicio');
$newAvs = array($item);
unset($avs[$key]);
foreach ($avs as $keyTwo => $elem){
$ind = $keyTwo + 1;
$elem->setName($ind.' - '.$elem->getName());
array_push($newAvs,$elem);
}
}
}
$avs = $newAvs;
/* av Description*/
$data_av = array();
foreach($avs as $av){
$data_av[] = array(
'id' => $av->getId(),
'name' => $av->getName(),
'modules' => null,
'type' => $av->getType(),
'currency' => 'Euro',
'price' => $av->getPrice(),
'commission' => 0,
'iva' => 21,
'controlId' => 0,
'description' => null
);
}
// Buscamos las plantilas precargadas
$parameters = array();
$dql = 'SELECT i
FROM AvexpressBundle:AveTemplate i
ORDER BY i.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$aveTemplates = $query->getResult();
// Buscamos las proformas
$proformas = $em->getRepository(AveDocProforma::class)->findByFileId($id);
return $this->render('MDS/AvexpressBundle/Avexpress/add-services.html.twig',
array(
'id' => $id,
'avs' => $data_av,
'newAvs' => $newAvs,
'aveTemplates' => $aveTemplates,
'proformas' => $proformas,
'technology' => null,
));
}
/**
* @Route("/productfilemultipleadd/", name="ave_add_multiple_productfile")
* Agregar multiples productos a un expediente
*/
public function addMultipleProductFileAction( Request $request){
$logTelegram = false;
$fileId = $request->request->get('fileId');
$products = $request->request->get('av');
$template = $request->request->get('avexpress');
$template = $template['template'];
$srvDestination = $request->request->get('srvDestination');
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$em = $this->getDoctrine()->getManager();
$file = $em->getRepository(AveFiles::class)->findOneById($fileId);
$template = $em->getRepository(AveTemplate::class)->findOneById($template);
if(!empty($products)) {
foreach ($products as $item) {
$mdvProductSelected = $em->getRepository(AveProduct::class)->findOneById($item);
$newProductFile = new AveProductFile();
$newProductFile->setProductName($mdvProductSelected->getName());
$newProductFile->setProductId($mdvProductSelected->getId());
$newProductFile->setServicePrice($mdvProductSelected->getPrice());
$newProductFile->setDescription($mdvProductSelected->getDescription());
$newProductFile->setType($mdvProductSelected->getType());
$newProductFile->setFileId($fileId);
$newProductFile->setUnits('1');
$newProductFile->setOpIva(true);
$newProductFile->setIva('21');
$newProductFile->setSupplierExt($mdvProductSelected->getSupplierExt());
$newProductFile->setSupplierExtId($mdvProductSelected->getSupplierExtId());
$dataDates = $this->obtenerFechas($newProductFile->getFileId(), $newProductFile->getDateStart(), $newProductFile->getDateEnd());
$newProductFile->setDateStart($dataDates['dateStart']);
$newProductFile->setDateEnd($dataDates['dateEnd']);
$newProductFile->setDateInAt($dataDates['dateStart']);
$newProductFile->setDateOutAt($dataDates['dateEnd']);
$dataRankAv = $this->obtenerRankAv($fileId);
$newProductFile->setRankAv($dataRankAv);
$newProductFile->setCreatedId($user_id);
$newProductFile->setUpdatedId($user_id);
$newProductFile->setCreatedAt(new \DateTime("now"));
$newProductFile->setUpdatedAt(new \DateTime("now"));
if (empty($newProductFile->getType())){ $newProductFile->setType('Otros'); }
$newProductFile->setDays((($newProductFile->getDateEnd()->diff($newProductFile->getDateStart()))->days + 1));
$newProductFile->setSubTotalPrice($newProductFile->getServicePrice() * $newProductFile->getDays());
$em->persist($newProductFile);
$em->flush();
if (!($srvDestination == 0)){
//Se debe agregar el producto a una proforma
$this->addProductFileToProforma($fileId, $newProductFile->getId(), $srvDestination);
}
// 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 Av Express 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(),
)
);
if (!empty($control)) {
// Existe un destino con Av Express como proveedor, hay se agregara el servicio
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
$logTelegram = true;
$service = new ProposalSupplierServices();
$service->setServiceIdFather(0);
$service->setControlId($control->getId());
$service->setProposalId($file->getIdProposal());
$service->setDestinationId($control->getDestinoId());
$service->setSupplierId(80);
$service->setIdeaId(null);
$service->setServiceId($newProductFile->getProductId());
$service->setServiceCatName('Av');
$service->setServiceCatId(3);
$service->setName($newProductFile->getProductName());
$service->setPrice($newProductFile->getSubTotalPrice() / $newProductFile->getDays());
// $priceInOut = $newProductFile->getSubTotalPrice() / $newProductFile->getPax(); // Se devuelve el calculo dividiendo entre personas
// $priceInOut = $priceInOut / $newProductFile->getUnits(); // Se devuelve el calculo dividiendo entre cantidades
// $priceInOut = $priceInOut / round($newProductFile->getDays()); // Se devuelve el calculo dividiendo entre dias, se redondea por si es 1.5
// $service->setPrice($priceInOut);
$service->setCurrency($newProductFile->getCurrency());
$service->setUnits($newProductFile->getUnits());
$service->setCommission(0);
$service->setOver(0);
$service->setIva(21);
$service->setPax(1);
$service->setHour(null);
$service->setDateInAt($newProductFile->getDateInAt());
$service->setDateOutAt($newProductFile->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(1);
$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();
// Guardamos el ID del servicio (Eventos) asociado al producto (AvExpress)
$newProductFile->setOriginId($service->getId());
$em->persist($newProductFile);
$em->flush();
}
}
}
}
}
// Buscamos los elementos de la plantilla seleccionada
$templateItems = array();
if(!empty($template)){
$templateItems = $em->getRepository(AveTemplateItems::class)->findByTemplateId($template);
}
foreach ($templateItems as $item){
$newProductFile = new AveProductFile();
$newProductFile->setProductName($item->getProductName());
$newProductFile->setProductId($item->getProductId());
$newProductFile->setServicePrice($item->getServicePrice());
$newProductFile->setFileId($fileId);
$newProductFile->setPax($item->getPax());
$newProductFile->setType($item->getType());
$newProductFile->setHourStart($item->getHourStart());
$newProductFile->setMinStart($item->getMinStart());
$newProductFile->setHourEnd($item->getHourEnd());
$newProductFile->setMinEnd($item->getMinEnd());
$newProductFile->setDescription($item->getDescription());
$newProductFile->setSupplierExtId($item->getSupplierExtId());
$newProductFile->setSupplierExt($item->getSupplierExt());
$newProductFile->setServiceIdProposal($item->getServiceIdProposal());
$newProductFile->setServiceIdFather($item->getServiceIdFather());
$newProductFile->setControlId($item->getControlId());
$newProductFile->setProposalId($item->getProposalId());
$newProductFile->setDestinationId($item->getDestinationId());
$newProductFile->setIdeaId($item->getIdeaId());
$newProductFile->setActivityId($item->getActivityId());
$newProductFile->setSupplierId($item->getSupplierId());
$newProductFile->setAssistantId($item->getAssistantId());
$newProductFile->setServiceId($item->getServiceId());
$newProductFile->setServiceCatId($item->getServiceCatId());
$newProductFile->setServiceCatName($item->getServiceCatName());
$newProductFile->setName($item->getName());
$newProductFile->setPrice($item->getPrice());
$newProductFile->setCurrency($item->getCurrency());
$newProductFile->setUnits($item->getUnits());
$newProductFile->setOpCommission($item->getOpCommission());
$newProductFile->setCommission($item->getCommission());
$newProductFile->setOpOver($item->getOpOver());
$newProductFile->setOver($item->getOver());
$newProductFile->setOpIva($item->getOpIva());
$newProductFile->setIva($item->getIva());
$newProductFile->setHour($item->getHour());
$dataDates = $this->obtenerFechas($newProductFile->getFileId(), $newProductFile->getDateStart(), $newProductFile->getDateEnd());
$newProductFile->setDateStart($dataDates['dateStart']);
$newProductFile->setDateEnd($dataDates['dateEnd']);
$newProductFile->setDateInAt($dataDates['dateStart']);
$newProductFile->setDateOutAt($dataDates['dateEnd']);
$newProductFile->setContcolor($item->getContcolor());
$newProductFile->setRank($item->getRank());
$dataRankAv = $this->obtenerRankAv($fileId);
$newProductFile->setRankAv($dataRankAv);
$newProductFile->setRenovate($item->getRenovate());
$newProductFile->setPay($item->getPay());
$newProductFile->setDays($item->getDays());
$newProductFile->setSubTotalPrice($item->getSubTotalPrice());
$newProductFile->setCreatedId($user_id);
$newProductFile->setUpdatedId($user_id);
$newProductFile->setCreatedAt(new \DateTime("now"));
$newProductFile->setUpdatedAt(new \DateTime("now"));
if (empty($newProductFile->getType())){ $newProductFile->setType('Otros'); }
$em->persist($newProductFile);
$em->flush();
if (!($srvDestination == 0)){
//Se debe agregar el producto a una proforma
$this->addProductFileToProforma($fileId, $newProductFile->getId(), $srvDestination);
}
// 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 Av Express 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(),
)
);
if (!empty($control)){
// Existe un destino con Av Express como proveedor, hay se agregara el servicio
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($file->getIdProposal());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
$logTelegram = true;
$service = new ProposalSupplierServices();
$service->setServiceIdFather(0);
$service->setControlId($control->getId());
$service->setProposalId($file->getIdProposal());
$service->setDestinationId($control->getDestinoId());
$service->setSupplierId(80);
$service->setIdeaId(null);
$service->setServiceId($newProductFile->getProductId());
$service->setServiceCatName('Av');
$service->setServiceCatId(3);
$service->setName($newProductFile->getProductName());
$service->setPrice($newProductFile->getSubTotalPrice());
$service->setCurrency(null);
$service->setUnits(1);
$service->setCommission(0);
$service->setOver(0);
$service->setIva(21);
$service->setPax(0);
$service->setHour(null);
$service->setDateInAt(new \DateTime("now"));
$service->setDateOutAt(new \DateTime("now"));
$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(1);
$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();
// Guardamos el ID del servicio (Eventos) asociado al producto (AvExpress)
$newProductFile->setOriginId($service->getId());
$em->persist($newProductFile);
$em->flush();
}
}
}
}
//INICIO: Notificamos al agente por Telegram
if ($logTelegram){
//Buscamos todos los agentes del proposal
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($file->getIdProposal());
//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: '.$file->getIdProposal().' __ 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: '.$file->getIdProposal().' __ 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: '.$file->getIdProposal().' __ 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: '.$file->getIdProposal().' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
}
}
//FIN: Notificamos al agente por Telegram
return $this->redirectToRoute('ave_edit_file',
array(
'id' => $fileId
)
);
}
/**
* @Route("/productfileedit/{id}", name="ave_productfile_edit")
* Editar un producto de un expediente
*/
public function editProductFileAction($id, Request $request){
$em = $this->getDoctrine()->getManager();
$productFile = $em->getRepository(AveProductFile::class)->findOneById($id);
$fileId = $productFile->getFileId();
// 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($fileId);
$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'; }
$productInFile = array();
foreach ($arrayLocation as $item){
// VIDEO
$parameters = array(
'fileId' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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' => $fileId,
'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();
}
$productInFile = array_merge($productInFile,$productsInFileVid, $productsInFileSound, $productsInFileLights, $productsInFileOther, $productsInFileNull);
}
$parameters = array();
$dql = 'SELECT p.id, p.name
FROM App\Entity\Supplier p
WHERE p.isSupplierAvExpress = TRUE
ORDER BY p.name ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$suppliers = $query->getResult();
// Quitamos el elemento seleccionado para evitar duplicaciones
foreach ($productInFile as $key => $item) {
if ($productFile->getId() == $item->getId()){
unset($productInFile[$key]);
}
}
$id = $productFile->getFileId();
$numeroItems = sizeof($productInFile) + 1;
$productsLocation = $em->getRepository(AveProductFileLocationNames::class)->findAll();
return $this->render('MDS/AvexpressBundle/Avexpress/edit-productfiles.html.twig',
array(
'id' => $id,
'numeroItems' => $numeroItems,
'arrayProductFile' => $productInFile,
'services' => $productInFile,
'product' => array($productFile),
'suppliers' => $suppliers,
'productsLocation' => $productsLocation,
));
}
/**
* @Route("/cleanproductfile/{id}", name="ave_clean_productfile")
* Eliminar los productos (y servicios en InOut) de un expediente que no estƩn relacionados con una factura o una proforma
*/
public function cleanProductFileAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$allMdvProductSelected = $em->getRepository(AveProductFile::class)->findByFileId($id);
// Si el ProductFile esta asociado a una factura o a una proforma se mantiene, de lo contrario se elimina y su evento asociado
foreach ($allMdvProductSelected as $key => $item){
$isInInvoice = $em->getRepository(AveDocInvoiceItems::class)->findOneByPrdControlId($item->getId());
$isInProforma = $em->getRepository(AveDocProformaItems::class)->findOneByControlId($item->getId());
if (!empty($isInInvoice) or !empty($isInProforma)){
//Lo sacamos de la lista de elementos a eliminar
unset($allMdvProductSelected[$key]);
}
}
foreach ($allMdvProductSelected as $mdvProductSelected){
$logTelegram = false;
//INICIO: Si hay un ID origin se debe eliminar en Eventos
if (!empty($mdvProductSelected->getOriginId())){
$logTelegram = true;
$delete = $em->getRepository(ProposalSupplierServices::class)->findOneById($mdvProductSelected->getOriginId());
if (!empty($delete)) {
$destinationId = $delete->getDestinationId();
$nameServEvents = $delete->getName();
$proposalId = $delete->getProposalId();
$prpInv = $em->getRepository(ProposalInvoice::class)->findOneByProposalId($delete->getProposalId());
if (empty($prpInv)) { //Si hay factura en InOut no se debe modificar
if (!empty($delete)) {
$delete_sub = $em->getRepository(ProposalSupplierServices::class)->findByServiceIdFather($delete->getId());
foreach ($delete_sub as $deletesub) {
$em->remove($deletesub);
}
$em->remove($delete);
$em->flush();
}
}
} else {
// El servicio origen no se encontro
$logTelegram = false;
}
}
//INICIO: Notificamos al agente por Telegram
if ($logTelegram){
//Buscamos todos los agentes del proposal
$proposalAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposalId);
//Buscamos el Destino
$proposalDestino = $em->getRepository(Destination::class)->findOneById($destinationId);
//Buscamos el agente de Develup
$userData = $em->getRepository(User::class)->findOneById($user_id);
if (!empty($proposalAgents)){
if ((!empty($proposalAgents->getAgOne())) and (!($proposalAgents->getAgOne() == 0))){
$this->sendTelegram($proposalAgents->getAgOne(),'1. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgTwo())) and (!($proposalAgents->getAgTwo() == 0))){
$this->sendTelegram($proposalAgents->getAgTwo(),'2. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgThree())) and (!($proposalAgents->getAgThree() == 0))){
$this->sendTelegram($proposalAgents->getAgThree(),'3. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
if ((!empty($proposalAgents->getAgFour())) and (!($proposalAgents->getAgFour() == 0))){
$this->sendTelegram($proposalAgents->getAgFour(),'4. SERVICIO ELIMINADO DESDE AVEXPRESS __ ID: '.$proposalId.' __ DESTINO: '.$proposalDestino->getTitle().' __ PROVEEDOR: AvExpress __ CONTACTO: '.$userData->getName().' '.$userData->getLastName());
}
}
}
//FIN: Notificamos al agente por Telegram
//FIN: Si hay un ID origin se debe eliminar en Eventos
//INICIO: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiƩn
$productInProforma = $em->getRepository(AveDocProformaItems::class)->findOneByControlId($mdvProductSelected->getId());
if (!empty($productInProforma)){
$productInProforma->setFileId((-1) * $productInProforma->getFileId()); // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
$em->persist($productInProforma);
// $em->remove($productInProforma);
$em->flush();
}
//FIN: Si el producto se encuentra dentro de una proforma (Ave_Doc_Proforma_Items) se elimina tambiƩn
$mdvProductSelected->setFileId((-1) * $mdvProductSelected->getFileId()); // No lo vamos a eliminar, apuntarĆ” al fileId en negativo
$em->persist($mdvProductSelected);
// $em->remove($mdvProductSelected);
$em->flush();
}
return $this->redirectToRoute('ave_edit_file', array('id' => $id));
}
/**
* @Route("/overallproductfile/", name="ave_over_all_productfile")
* Aplicar un Over a todos los productos de un expediente
*/
public function overAllProductFileAction(Request $request){
$fileId = $request->request->get('fileId');
$opOverAll = $request->request->get('opOverAll');
$overAll = $request->request->get('overAll');
$em = $this->getDoctrine()->getManager();
$productInFile = $em->getRepository(AveProductFile::class)->findByFileId($fileId);
foreach ($productInFile as $item){
$itemId = $item->getId();
$item->setOpOver($opOverAll);
$item->setOver($overAll);
$em->persist($item);
$em->flush();
}
return $this->redirectToRoute('ave_productfile_edit', array('id' => $itemId));
}
/**
* @Route("/commissionallproductfile/", name="ave_commission_all_productfile")
* Aplicar una Comision a todos los productos de un expediente
*/
public function commissionAllProductFileAction(Request $request){
$fileId = $request->request->get('fileId');
$opCommissionAll = $request->request->get('opCommissionAll');
$commissionAll = $request->request->get('commissionAll');
$em = $this->getDoctrine()->getManager();
$productInFile = $em->getRepository(AveProductFile::class)->findByFileId($fileId);
foreach ($productInFile as $item){
$itemId = $item->getId();
$item->setOpCommission($opCommissionAll);
$item->setCommission($commissionAll);
$em->persist($item);
$em->flush();
}
return $this->redirectToRoute('ave_productfile_edit', array('id' => $itemId));
}
/**
* @Route("/ivazeroallproductfile/", name="ave_iva_zero_all_productfile")
* Aplicar un IVA de cero a todos los productos de un expediente
*/
public function ivaZeroAllProductFileAction(Request $request){
$fileId = $request->request->get('fileId');
// $opCommissionAll = $request->request->get('opCommissionAll');
// $commissionAll = $request->request->get('commissionAll');
$em = $this->getDoctrine()->getManager();
$productInFile = $em->getRepository(AveProductFile::class)->findByFileId($fileId);
foreach ($productInFile as $item){
$itemId = $item->getId();
$item->setOpIva(1);
$item->setIva(0);
$em->persist($item);
$em->flush();
}
return $this->redirectToRoute('ave_productfile_edit', array('id' => $itemId));
}
/**
* @Route("/productfilelocationadd/", name="ave_add_productfilelocation")
* Agregar una Ubicacion. Salas en donde estara el producto
*/
public function addProductFileLocationAction( Request $request)
{
$em = $this->getDoctrine()->getManager();
$newRequest = $request->request->get('product');
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$newProductFile = new AveProductFileLocationNames();
$newProductFile->setName($newRequest['name']);
$newProductFile->setDescription($newRequest['description']);
$newProductFile->setCreatedId($user_id);
$newProductFile->setUpdatedId($user_id);
$newProductFile->setCreatedAt(new \DateTime("now"));
$newProductFile->setUpdatedAt(new \DateTime("now"));
$em->persist($newProductFile);
$em->flush();
return $this->redirectToRoute('ave_list_productfilelocation');
}
/**
* @Route("/productfilelocationlist/", name="ave_list_productfilelocation")
* Listar Ubicaciones para los productos
*/
public function listProductFileLocationAction(Request $request){
$em = $this->getDoctrine()->getManager();
$productsLocation = $em->getRepository(AveProductFileLocationNames::class)->findAll();
return $this->render('MDS/AvexpressBundle/Avexpress/list-productsfile-locationnames.html.twig',
array(
'productsLocation' => $productsLocation,
));
}
/**
* @Route("/productfilelocationedit/{id}", name="ave_edit_productfilelocation")
* Editar una Ubicacion
*/
public function editProductFileLocationAction( $id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$editProductLocation = $em->getRepository(AveProductFileLocationNames::class)->findOneById($id);
return $this->render('MDS/AvexpressBundle/Avexpress/edit-productsfiles-location.html.twig',
array(
'id' => $editProductLocation->getId(),
'productLocation' => $editProductLocation,
));
}
/**
* @Route("/productfilelocationupdate/", name="ave_update_productfilelocation")
* Update de una Ubicacion
*/
public function updateProductFileLocationAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$newRequest = $request->request->get('product');
$id = $newRequest['id'];
$newProduct = $em->getRepository(AveProductFileLocationNames::class)->findOneById($id);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
if (!empty($newRequest['name'])){$newProduct->setName($newRequest['name']);}
$newProduct->setDescription($newRequest['description']);
$newProduct->setUpdatedId($user_id);
$newProduct->setUpdatedAt(new \DateTime("now"));
$em->persist($newProduct);
$em->flush();
return $this->redirectToRoute('ave_list_productfilelocation');
}
/**
* @Route("/productfilelocationdelete/{id}", name="ave_delete_productfilelocation")
* Eliminar una Ubicacion
*/
public function deleteProductAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$delProduct = $em->getRepository(AveProductFileLocationNames::class)->findOneById($id);
if (!empty($delProduct)){
$em->remove($delProduct);
$em->flush();
}
return $this->redirectToRoute('ave_list_productfilelocation');
}
// 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());
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('3');
$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){
if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
$subtotal = 0;
$neto = 0;
$subtotalProduct = 0;
} else {
$subtotalProduct = $item->getServicePrice() * 1.21;
$subneto = $item->getServicePrice();
$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);
$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(),
'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){
$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(ReservationInvoice::class)->findOneById($numberInvoiceOrProforma);
$newInvoice->setBalance($totales_all);
$em->persist($newInvoice);
$em->flush();
}
$data = array(
'id' => $id,
'type' => $type,
'number' => $number,
'prefix' => 'GPF-'.(new DateTime('now'))->format('dmy').'-',
'date' => new DateTime('now'),
'file' => $file,
// 'token' => $reservation->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;
}
private function obtenerRankAv($id)
{
// $id Id del Expediente (File)
$em = $this->getDoctrine()->getManager();
$items = $em->getRepository(AveProductFile::class)->findByFileId($id);
if (empty($items)){ $num = 1; } else { $num = sizeof($items) + 1; }
$data = $num;
return $data;
}
private function obtenerFechas($id, $dateStart, $dateEnd)
{
// $id Id del Expediente (File)
// $dateStart Fecha de inicio (Producto)
// $dateEnd Fecha de fin (Producto)
$em = $this->getDoctrine()->getManager();
$file = $em->getRepository(AveFiles::class)->findOneById($id);
if (empty($dateStart)){ $newDateStart = $file->getDateStart(); } else { $newDateStart = $dateStart; }
if (empty($dateEnd)){ $newDateEnd = $file->getDateEnd(); } else { $newDateEnd = $dateEnd; }
$data = array(
'dateStart' => $newDateStart,
'dateEnd' => $newDateEnd,
);
return $data;
}
private function sendTelegram( $id, $text )
{
$em = $this->getDoctrine()->getManager();
$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 addProductFileToProforma( $fileId, $newProductId, $proformaId )
{
$em = $this->getDoctrine()->getManager();
$file = $em->getRepository(AveFiles::class)->findOneById($fileId);
$productFile = $em->getRepository(AveProductFile::class)->findOneById($newProductId);
$proforma = $em->getRepository(AveDocProforma::class)->findOneById($proformaId);
if (!empty($file) and !empty($productFile) and !empty($proforma) ){
$newProformaItem = new AveDocProformaItems();
$newProformaItem->setControlId($newProductId);
$newProformaItem->setType('PRODUCT');
$newProformaItem->setFileId($fileId);
$newProformaItem->setProformaId($proformaId);
$em->persist($newProformaItem);
$em->flush();
return true;
} else {
return false;
}
}
private function precioPorVariacionDeDias ($supplierService, $productFile){
$em = $this->getDoctrine()->getManager();
// 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;
if (array_key_exists('productFileId',$productFile)){
// En el GridTwo viene es un arreglo no la entidad
$productInFile = $em->getRepository(AveProductFile::class)->findOneById($productFile['productFileId']);
$newPrice = $productInFile->getSubTotalPrice() / ( $days );
} else {
$newPrice = $productFile->getSubTotalPrice() / ( $days );
}
$newPrice = $newPrice / $supplierService->getUnits();
$newPrice = round($newPrice,2,PHP_ROUND_HALF_UP);
return $newPrice;
}
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;
}
};